text stringlengths 10 2.61M |
|---|
class GigabitEthernetCondition
def initialize(params)
@params = params
end
def gigabit_ethernets
relation = GigabitEthernet.all
relation = relation.where(device_id: device_id) if device_id?
relation = relation.where(name: name) if name?
relation
end
private
def name?
name.present?
end
def name
@params['name']
end
def device_id?
device_id.present?
end
def device_id
@params['device_id']
end
end
|
FactoryBot.define do
factory :comment do
advice_id { FactoryBot.create(:advice).id}
actor_id { FactoryBot.create(:user).id}
description { Faker::FunnyName.name_with_initial }
end
end
|
class User < ApplicationRecord
rolify
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
before_save :set_auth_token
private
def set_auth_token
return if auth_token.present?
self.auth_token = generate_auth_token
end
def generate_auth_token
loop do
token = Devise.friendly_token
break token unless self.class.exists?(auth_token: token)
end
end
end
|
class CharactersGame < ApplicationRecord
has_many :characters
has_many :games
end
|
require 'rubygems'
require 'digest/md5'
require 'bankjob'
module Bankjob
##
# A Transaction object represents a transaction in a bank account (a withdrawal, deposit,
# transfer, etc) and is generally the result of running a Bankjob scraper.
#
# A Scraper will create Transactions while scraping web pages in an online banking site.
# These Transactions will be collected in a Statement object which will then be written
# to a file.
#
class Transaction
# OFX transaction type for Generic credit
CREDIT = "CREDIT"
# OFX transaction type for Generic debit
DEBIT = "DEBIT"
# OFX transaction type for Interest earned or paid. (Depends on signage of amount)
INT = "INT"
# OFX transaction type for Dividend
DIV = "DIV"
# OFX transaction type for FI fee
FEE = "FEE"
# OFX transaction type for Service charge
SRVCHG = "SRVCHG"
# OFX transaction type for Deposit
DEP = "DEP"
# OFX transaction type for ATM debit or credit. (Depends on signage of amount)
ATM = "ATM"
# OFX transaction type for Point of sale debit or credit. (Depends on signage of amount)
POS = "POS"
# OFX transaction type for Transfer
XFER = "XFER"
# OFX transaction type for Check
CHECK = "CHECK"
# OFX transaction type for Electronic payment
PAYMENT = "PAYMENT"
# OFX transaction type for Cash withdrawal
CASH = "CASH"
# OFX transaction type for Direct deposit
DIRECTDEP = "DIRECTDEP"
# OFX transaction type for Merchant initiated debit
DIRECTDEBIT = "DIRECTDEBIT"
# OFX transaction type for Repeating payment/standing order
REPEATPMT = "REPEATPMT"
# OFX transaction type for Other
OTHER = "OTHER"
# OFX type of the transaction (credit, debit, atm withdrawal, etc)
# Translates to the OFX element TRNTYPE and according to the OFX 2.0.3 schema this can be one of
# * CREDIT
# * DEBIT
# * INT
# * DIV
# * FEE
# * SRVCHG
# * DEP
# * ATM
# * POS
# * XFER
# * CHECK
# * PAYMENT
# * CASH
# * DIRECTDEP
# * DIRECTDEBIT
# * REPEATPMT
# * OTHER
attr_accessor :type
# date of the transaction
# Translates to OFX element DTPOSTED
attr_accessor :date
# the date the value affects the account (e.g. funds become available)
# Translates to OFX element DTUSER
attr_accessor :value_date
# description of the transaction
# This description is typically set by taking the raw description and
# applying rules. If it is not set explicitly it returns the same
# value as +raw_description+
# Translates to OFX element MEMO
attr_accessor :description
# the original format of the description as scraped from the bank site
# This allows the raw information to be preserved when modifying the
# +description+ with transaction rules (see Scraper#transaction_rule)
# This does _not_ appear in the OFX output, only +description+ does.
attr_accessor :raw_description
# amount of the credit or debit (negative for debits)
# Translates to OFX element TRNAMT
attr_accessor :amount
# account balance after the transaction
# Not used in OFX but important for working out statement balances
attr_accessor :new_balance
# account balance after the transaction as a numeric Ruby Float
# Not used in OFX but important for working out statement balances
# in calculations (see #real_amount)
attr_reader :real_new_balance
# the generated unique id for this transaction in an OFX record
# Translates to OFX element FITID this is generated if not set
attr_accessor :ofx_id
# the payee of an expenditure (ie a debit or transfer)
# This is of type Payee and translates to complex OFX element PAYEE
attr_accessor :payee
# the cheque number of a cheque transaction
# This is of type Payee and translates to OFX element CHECKNUM
attr_accessor :check_number
##
# the numeric real-number amount of the transaction.
#
# The transaction amount is typically a string and may hold commas for
# 1000s or for decimal separators, making it unusable for mathematical
# operations.
#
# This attribute returns the amount converted to a Ruby Float, which can
# be used in operations like:
# <tt>
# if (transaction.real_amount < 0)
# puts "It's a debit!"
# end
#
# The +real_amount+ attribute is calculated using the +decimal+ separator
# passed into the constructor (defaults to ".")
# See Scraper#decimal
#
# This attribute is not used in OFX.
#
attr_reader :real_amount
##
# Creates a new Transaction with the specified attributes.
#
def initialize(decimal = ".")
@ofx_id = nil
@date = nil
@value_date = nil
@raw_description = nil
@description = nil
@amount = 0
@new_balance = 0
@decimal = decimal
# Always create a Payee even if it doesn't get used - this ensures an empty
# <PAYEE> element in the OFX output which is more correct and, for one thing,
# stops Wesabe from adding UNKNOWN PAYEE to every transaction (even deposits)
@payee = Payee.new()
@check_number = nil
@type = OTHER
end
def date=(raw_date_time)
@date = Bankjob.create_date_time(raw_date_time)
end
def value_date=(raw_date_time)
@value_date = Bankjob.create_date_time(raw_date_time)
end
##
# Creates a unique ID for the transaction for use in OFX documents, unless
# one has already been set.
# All OFX transactions need a unique identifier.
#
# Note that this is generated by creating an MD5 digest of the transaction
# date, raw description, type, amount and new_balance. Which means that two
# identical transactions will always produce the same +ofx_id+.
# (This is important so that repeated scrapes of the same transaction value
# produce identical ofx_id values)
#
def ofx_id()
if @ofx_id.nil?
text = "#{@date}:#{@raw_description}:#{@type}:#{@amount}:#{@new_balance}"
@ofx_id= Digest::MD5.hexdigest(text)
end
return @ofx_id
end
##
# Returns the description, defaulting to the +raw_description+ if no
# specific description has been set by the user.
#
def description()
@description.nil? ? raw_description : @description
end
##
# Returns the Transaction amount attribute as a ruby Float after
# replacing the decimal separator with a . and stripping any other
# separators.
#
def real_amount()
Bankjob.string_to_float(amount, @decimal)
end
##
# Returns the new balance after the transaction as a ruby Float after
# replacing the decimal separator with a . and stripping any other
# separators.
#
def real_new_balance()
Bankjob.string_to_float(new_balance, @decimal)
end
##
# Produces a string representation of the transaction
#
def to_s
"#{self.class} - ofx_id: #{@ofx_id}, date:#{@date}, raw description: #{@raw_description}, type: #{@type} amount: #{@amount}, new balance: #{@new_balance}"
end
##
# Overrides == to allow comparison of Transaction objects so that they can
# be merged in Statements. See Statement#merge
#
def ==(other) #:nodoc:
if other.kind_of?(Transaction)
# sometimes the same date, when written and read back will not appear equal so convert to
# a canonical string first
return (Bankjob.date_time_to_ofx(@date) == Bankjob.date_time_to_ofx(other.date) and
# ignore value date - it may be updated between statements
# (consider using ofx_id here later)
@raw_description == other.raw_description and
@amount == other.amount and
@type == other.type and
@new_balance == other.new_balance)
end
end
#
# Overrides eql? so that array union will work when merging statements
#
def eql?(other) #:nodoc:
return self == other
end
##
# Overrides hash so that array union will work when merging statements
#
def hash() #:nodoc:
prime = 31;
result = 1;
result = prime * result + @amount.to_i
result = prime * result + @new_balance.to_i
result = prime * result + (@date.nil? ? 0 : Bankjob.date_time_to_ofx(@date).hash);
result = prime * result + (@raw_description.nil? ? 0 : @raw_description.hash);
result = prime * result + (@type.nil? ? 0 : @type.hash);
# don't use value date
return result;
end
end # class Transaction
end # module
|
require 'todobot/responders/base_responder'
require 'todobot/message_sender'
module TodoBot
class UndefinedResponder < BaseResponder
def respond
TodoBot::MessageSender.new(bot: bot, chat: chat, text: I18n.t('undefined_command_type')).send
end
end
end
|
# == Schema Information
#
# Table name: houses
#
# id :integer not null, primary key
# address :string not null
# created_at :datetime
# updated_at :datetime
#
class House < ActiveRecord::Base
has_many :residents,
primary_key: :id,
foreign_key: :house_id,
class_name: "Person"
has_many :prized_possessions,
through: :residents,
source: :prized_possessions
validates :address, :presence => true
validates :address, :uniqueness => true
# validate :address_does_not_begin_with_9
private
def address_does_not_begin_with_9
if address[0] = "9"
errors[:address] << "can't begin with 9"
end
end
end
|
set :application, "splogna"
set :scm, :git
set :repository, "git://github.com/superchris/splogna.git"
# If you aren't deploying to /u/apps/#{application} on the target
# servers (which is the default), you can specify the actual location
# via the :deploy_to variable:
set :deploy_to, "/home/christo0/apps/#{application}"
set :scm_command, "/usr/local/bin/git"
set :local_scm_command, "/usr/local/git/bin/git"
set :scm_username, "superchris"
set :user, "christo0"
set :use_sudo, false
# If you aren't using Subversion to manage your source code, specify
# your SCM below:
# set :scm, :subversion
server "www.christophernelsonconsulting.com", :app, :web, :db, :primary => true
after "deploy:update_code", "shared:symlink"
namespace :shared do
desc "Make symlink for database yaml"
task :symlink do
run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml"
end
end
namespace :deploy do
task :start, :roles => :app do
run "touch #{deploy_to}/current/tmp/restart.txt"
end
task :restart, :roles => :app do
run "touch #{deploy_to}/current/tmp/restart.txt"
end
end
|
class EventsController < ApplicationController
skip_before_action :authenticate_member!, :only => [:generate, :calendar, :index, :month]
helper :members
def show
@title = "Viewing Event"
@event = Event.find(params[:id])
authorize! :read, @event
end
def finance
@title = "Viewing Event Finances"
@event = Event.find(params[:id])
authorize! :read, Timecard
end
def new
@title = "Create New Event"
@event = Event.new
authorize! :create, @event
end
def duplicate
@old_event = Event.find(params[:id])
@event = @old_event.amoeba_dup
@event.status = Event::Event_Status_Initial_Request
@title = "Duplicate Event #" + @event.id.to_s
authorize! :create, @event
end
def edit
@title = "Edit Event"
@event = Event.find(params[:id])
@event.eventdates.each do |ed|
ed.event_roles.build if ed.event_roles.empty?
end
authorize! :update, @event
end
def create
@title = "Create New Event"
if cannot? :create, Organization
params[:event].delete(:org_type)
params[:event].delete(:org_new)
end
p = params.require(:event).permit(:title, :org_type, :organization_id, :org_new, :status, :billable, :rental,
:textable, :publish, :contact_name, :contactemail, :contact_phone, :price_quote, :notes, :created_email,
:eventdates_attributes =>
[:startdate, :description, :enddate, :calldate, :strikedate, :calltype, :striketype, :email_description, :notes,
{:location_ids => []}, {:equipment_ids => []}, {:event_roles_attributes => [:role, :member_id, :appliable]}],
:event_roles_attributes => [:role, :member_id, :appliable],
:attachments_attributes => [:attachment, :name],
:blackout_attributes => [:startdate, :enddate, :with_new_event, :_destroy])
@event = Event.new(p)
authorize! :create, @event
if @event.save
flash[:notice] = "Event created successfully!"
redirect_to @event
else
render :new
end
end
def update
@title = "Edit Event"
@event = Event.find(params[:id])
authorize! :update, @event
p = params.require(:event).permit(:title, :org_type, :organization_id, :org_new, :status, :billable, :rental,
:textable, :publish, :contact_name, :contactemail, :contact_phone, :price_quote, :notes,
:eventdates_attributes =>
[:id, :_destroy, :startdate, :description, :enddate, :calldate, :strikedate, :calltype, :striketype,
:email_description, :notes, {:location_ids => []}, {:equipment_ids => []},
{:event_roles_attributes => [:id, :role, :member_id, :appliable, :_destroy]}],
:attachments_attributes => [:attachment, :name, :id, :_destroy],
:event_roles_attributes => [:id, :role, :member_id, :appliable, :_destroy],
:invoices_attributes => [:status, :id],
:blackout_attributes => [:startdate, :enddate, :id, :_destroy])
if cannot? :create, Organization
p.delete(:org_type)
p.delete(:org_new)
end
if cannot? :manage, :finance
p.delete(:invoice_attributes)
end
if cannot? :tic, @event
p.delete(:title)
p.delete(:org_type)
p.delete(:organization_id)
p.delete(:org_new)
p.delete(:status)
p.delete(:billable)
p.delete(:textable)
p.delete(:rental)
p.delete(:publish)
p.delete(:contact_name)
p.delete(:contactemail)
p.delete(:contact_phone)
p.delete(:price_quote)
p.delete(:blackout_attributes)
# If you are not TiC for the event, with regards to run positions, you
# can only delete yourself from a run position, assign a member who isn't
# you to be one of your assistants, or modify a run position which is one
# of your assistants
assistants = @event.run_positions_for(current_member).flat_map(&:assistants)
p[:event_roles_attributes].select! do |bleh,er|
if er[:id]
rer = EventRole.find(er[:id])
if rer.member_id == current_member.id
er[:_destroy] == '1'
else
assistants.include? er[:role] and assistants.include? rer.role
end
else
er[:member_id] != current_member.id and assistants.include? er[:role]
end
end
# If you are not TiC for the event, with regards to eventdates, you
# can only edit and delete eventdates that you are the TiC of. You cannot
# create a new eventdate. If you are not the TiC of an eventdate but are
# a run position, you may only delete yourself from a run position, assign
# a member who isn't you to be one of your assistants, or modify a run
# position which is one of your assistants
if p[:eventdates_attributes]
p[:eventdates_attributes].each do |key,ed|
if ed[:id]
red = Eventdate.find(ed[:id])
if !red.tic.include? current_member
p[:eventdates_attributes][key].delete(:_destroy)
p[:eventdates_attributes][key].delete(:startdate)
p[:eventdates_attributes][key].delete(:description)
p[:eventdates_attributes][key].delete(:enddate)
p[:eventdates_attributes][key].delete(:calldate)
p[:eventdates_attributes][key].delete(:strikedate)
p[:eventdates_attributes][key].delete(:calltype)
p[:eventdates_attributes][key].delete(:striketype)
p[:eventdates_attributes][key].delete(:location_ids)
p[:eventdates_attributes][key].delete(:equipment_ids)
p[:eventdates_attributes][key].delete(:email_description)
assistants = red.run_positions_for(current_member).flat_map(&:assistants)
p[:eventdates_attributes][key][:event_roles_attributes].select! do |_,er|
if er[:id]
rer = EventRole.find(er[:id])
if rer.member_id == current_member.id
er[:_destroy] == '1'
else
assistants.include? er[:role] and assistants.include? rer.role
end
else
er[:member_id] != current_member.id and assistants.include? er[:role]
end
end
end
else
p[:eventdates_attributes].delete(key)
end
end
end
end
if @event.update(p)
flash[:notice] = "Event updated successfully!"
redirect_to @event
else
render :edit
end
end
def destroy
@event = Event.find(params["id"])
authorize! :destroy, @event
flash[:notice] = "Deleted event " + @event.title + "."
@event.destroy
redirect_to events_url
end
def delete_conf
@title = "Delete Event Confirmation"
@event = Event.find(params["id"])
authorize! :destroy, @event
end
def index
@title = "Event List"
authorize! :index, Event
if(can? :read, Event)
@eventdates = Eventdate.where("enddate >= ? AND NOT events.status IN (?)", Time.now.utc, Event::Event_Status_Group_Completed)
else
@eventdates = Eventdate.where("enddate >= ? AND NOT events.status IN (?) AND events.publish = true", Time.now.utc, Event::Event_Status_Group_Completed).order("startdate ASC")
end
@eventdates = @eventdates.order("startdate ASC").includes({event: [:organization]}, {event_roles: [:member]}, :locations, :equipment).references(:event)
@eventweeks = Eventdate.weekify(@eventdates)
if not member_signed_in?
render(:action => "index", :layout => "public")
end
end
def month
@title = "Event List for " + Date::MONTHNAMES[params[:month].to_i] + " " + params[:year]
authorize! :index, Event
if((Time.now.year > params[:year].to_i or (Time.now.year == params[:year].to_i and Time.now.month > params[:month].to_i)) and not can? :read, Event)
redirect_to new_member_session_path and return
end
@startdate = Time.zone.parse(params["year"] + "-" + params["month"] + "-1").to_datetime.beginning_of_month
enddate = @startdate.end_of_month
if(can? :read, Event)
@eventdates = Eventdate.where("enddate >= ? AND startdate <= ?", @startdate.utc, enddate.utc).order("startdate ASC")
else
@eventdates = Eventdate.where("enddate >= ? AND startdate <= ? AND events.publish = true", @startdate.utc, enddate.utc).order("startdate ASC").includes(:event).references(:event)
end
@eventruns = Eventdate.runify(@eventdates)
if not member_signed_in?
render(:action => "month", :layout => "public")
end
end
def incomplete
@title = "Incomplete Event List"
authorize! :read, Event
@eventdates = Eventdate.where("NOT events.status IN (?)", Event::Event_Status_Group_Completed).order("startdate ASC").includes(:event).references(:event)
@eventruns = Eventdate.runify(@eventdates)
end
def past
@title = "Past Event List"
authorize! :read, Event
@eventdates = Eventdate.where("startdate <= ?", Time.now.utc).order("startdate DESC").paginate(:per_page => 50, :page => params[:page])
@eventruns = Eventdate.runify(@eventdates)
end
def search
@title = "Event List - Search for " + params[:q]
authorize! :read, Event
@eventdates = Eventdate.search params[:q].gsub(/[^A-Za-z0-9 ]/,""), :page => params[:page], :per_page => 50, :order => "startdate DESC"
@eventruns = Eventdate.runify(@eventdates)
end
def calendar
@title = "Calendar"
if params[:selected]
@selected = Time.zone.parse(params[:selected])
else
@selected = Time.zone.now
end
@selected_month = []
12.times do |i|
@selected_month[i] = @selected + (i-3).months
end
if not member_signed_in?
render(:action => "calendar", :layout => "public")
end
end
# Some documentation for generate (accessed with url /calendar/generate.(ics|calendar)
# URL Parameters: [startdate (parsed date string), enddate, | matchdate] [showall (true|false),] [period (like f05 s01 u09 or fa05 sp02 su09 or soon)]
# All parameters are optional. Default behavior is to give today's events.
def generate
# Determine date period
if params[:startdate] and params[:enddate]
begin
@startdate = Date.parse(params['startdate'])
rescue
render text: "Start date is not valid." and return
end
begin
@enddate = Date.parse(params['enddate'])
rescue
render text: "End date is not valid." and return
end
elsif params[:period] == "soon"
# "Soon" is from 1 week ago through 3 months from now.
# This is good for syncing a calendar.
@startdate = 1.week.ago
@enddate = 3.months.from_now
elsif params[:period]
# a string such as 'f2005' or 'S01' or 'u09' [summer]
if not (params[:period].length == 3 or params[:period].length == 5)
render text: "Badly formatted period." and return
end
year = params[:period][1..-1]
if year.length == 2
year = "20" + year
end
period = params[:period][0].downcase
if period == "f"
@startdate = Date.new(year.to_i, 8, 10)
@enddate = Date.new(year.to_i, 12, 31)
elsif period == "s"
@startdate = Date.new(year.to_i, 1, 1)
@enddate = Date.new(year.to_i, 5, 31)
elsif period == "u"
@startdate = Date.new(year.to_i, 6, 1)
@enddate = Date.new(year.to_i, 8, 9)
else
render text: "Invalid period." and return
end
else
# Assume the period is the current one if parsing the params has failed.
reference = Date.today
if params[:matchdate]
begin
reference = Date.parse(params[:matchdate])
rescue
render text: "Match date is not valid." and return
end
end
year = reference.year
case reference
when Date.new(year, 8, 10)..Date.new(year, 12, 31)
@startdate = Date.new(year, 8, 10)
@enddate = Date.new(year, 12, 31)
when Date.new(year, 1, 1)..Date.new(year, 5, 31)
@startdate = Date.new(year, 1, 1)
@enddate = Date.new(year, 5, 31)
else
@startdate = Date.new(year, 6, 1)
@enddate = Date.new(year, 8, 9)
end
end
@eventdates = Eventdate.where("(? < startdate) AND (? > enddate)", @startdate, @enddate).order(startdate: :asc).includes(:event, :locations)
# showall=true param includes unpublished events
if not params[:showall]
@eventdates = @eventdates.where("events.publish = TRUE").references(:events)
end
respond_to do |format|
format.schedule
format.ics
end
end
end
|
class Book < ApplicationRecord
belongs_to :user
#attachment :image # ここを追加(_idは含めません)
validates :title, presence: true, length: {minimum: 2}
validates :body, presence: true, length: {maximum: 200}
end
|
require 'rails_helper'
RSpec.describe 'Microposts', type: :system, js: true do
describe '#new,#show,#destroy' do
context 'ログインしたとき' do
before do
@user = create(:user)
visit '/sign_in'
fill_in 'メールアドレス', with: @user.email
fill_in 'パスワード', with: @user.password
click_button 'ログイン'
expect(page).to have_content "コレクション"
end
it '新規投稿ページの要素が正しく表示される' do
visit '/microposts/new'
expect(page).to have_selector 'h1',text: '新しいコレクション'
expect(page).to have_field 'js_presentImg',visible: false
expect(page).to have_field placeholder:'例)東京都渋谷区'
expect(page).to have_field placeholder:'この写真にタイトルをつけましょう!(20字以内)'
expect(page).to have_field placeholder:'この写真についてもっと教えてください!(140字以内)'
expect(page).to have_button '投稿する!'
end
it '新規投稿、投稿削除が可能' do
visit '/microposts/new'
attach_file 'js_presentImg',"#{Rails.root}/spec/fixtures/test.jpg", visible: false
find('.address-form').set('北海道札幌市')
find('.title-form').set('sample_title')
find('.form-area').set('sample_content')
click_button '投稿する!'
# ユーザーページにリダイレクトされるか
expect(current_path).to eq user_path(@user)
# 投稿が保存されているか
@micropost = Micropost.first
expect(@micropost.title).to eq('sample_title')
expect(@micropost.content).to eq('sample_content')
expect(@micropost.address).to eq('北海道札幌市')
#geocodingが正確に行われているか
expect(@micropost.latitude.present?).to be_present
expect(@micropost.longitude.present?).to be_present
# 投稿詳細ページに遷移
visit "/microposts/#{@micropost.id}"
expect(page).to have_selector 'h2',text: @micropost.title
# 投稿の削除
find('.fa-trash-alt').click
expect(page.driver.browser.switch_to.alert.text).to eq "コレクションから「#{@micropost.title}」を削除します"
page.driver.browser.switch_to.alert.accept
expect(current_path).to eq user_path(@user)
# 投稿が削除されているか
expect(Micropost.where(id: @user.id).count).to eq 0
end
end
end
end |
class MonthlyDistrictReport::Hypertension::BlockData
include MonthlyDistrictReport::Utils
attr_reader :repo, :district, :report_month, :last_6_months
def initialize(district, period_month)
@district = district
@report_month = period_month
@last_6_months = Range.new(@report_month.advance(months: -5), @report_month)
@repo = Reports::Repository.new(district.block_regions, periods: @last_6_months)
end
def content_rows
district
.block_regions
.order(:name)
.map do |block|
row_data(block)
end
end
def header_rows
[[ # row 1
"Blocks",
"Total hypertension registrations",
"Total assigned hypertension patients",
"Total hypertension patients under care",
"Total hypertension patients lost to followup",
"Treatment outcome", *Array.new(3, nil),
"Total registered hypertension patients", *Array.new(5, nil),
"Hypertension patients under care", *Array.new(5, nil),
"New registered hypertension patients", *Array.new(5, nil),
"Hypertension patient follow-ups", *Array.new(5, nil),
"BP controlled rate", *Array.new(5, nil)
],
[ # row 2
nil, # "Blocks"
nil, # "Total registrations"
nil, # "Total assigned patients"
nil, # "Total patients under care"
nil, # "Total patients lost to followup"
"% BP controlled",
"% BP uncontrolled",
"% Missed Visits",
"% Visits, no BP taken",
*last_6_months.map { |period| format_period(period) }, # "Total registered patients"
*last_6_months.map { |period| format_period(period) }, # "Patients under care"
*last_6_months.map { |period| format_period(period) }, # "New registered patients"
*last_6_months.map { |period| format_period(period) }, # "Patient follow-ups"
*last_6_months.map { |period| format_period(period) } # "BP controlled rate"
]]
end
private
def row_data(block)
{
"Blocks" => block.name,
"Total hypertension registrations" => repo.cumulative_registrations[block.slug][report_month],
"Total assigned hypertension patients" => repo.cumulative_assigned_patients[block.slug][report_month],
"Total hypertension patients under care" => repo.adjusted_patients[block.slug][report_month],
"Total hypertension patients lost to followup" => repo.ltfu[block.slug][report_month],
"% BP controlled" => percentage_string(repo.controlled_rates[block.slug][report_month]),
"% BP uncontrolled" => percentage_string(repo.uncontrolled_rates[block.slug][report_month]),
"% Missed Visits" => percentage_string(repo.missed_visits_rate[block.slug][report_month]),
"% Visits, no BP taken" => percentage_string(repo.visited_without_bp_taken_rates[block.slug][report_month]),
**last_6_months_data(repo.cumulative_registrations, block, :cumulative_registrations),
**last_6_months_data(repo.under_care, block, :under_care),
**last_6_months_data(repo.monthly_registrations, block, :monthly_registrations),
**last_6_months_data(repo.hypertension_follow_ups, block, :hypertension_follow_ups),
**last_6_months_data(repo.controlled_rates, block, :controlled_rates, true)
}
end
def last_6_months_data(data, block, indicator, show_as_rate = false)
last_6_months.each_with_object({}) do |month, hsh|
value = data.dig(block.slug, month)
hsh["#{indicator} - #{month}"] = indicator_string(value, show_as_rate)
end
end
end
|
# ----------------------------------------------------------------------------------
# MIT License
#
# Copyright(c) Microsoft Corporation. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# ----------------------------------------------------------------------------------
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ---------------------------------------------------------------------------------------------------------
# Documentation References:
# Associated Article - https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-ruby
# What is a Storage Account - https://docs.microsoft.com/en-us/azure/storage/common/storage-create-storage-account
# Getting Started with Blobs-https://docs.microsoft.com/en-us/azure/storage/blobs/storage-ruby-how-to-use-blob-storage
# Blob Service Concepts - https://docs.microsoft.com/en-us/rest/api/storageservices/Blob-Service-Concepts
# Blob Service REST API - https://docs.microsoft.com/en-us/rest/api/storageservices/Blob-Service-REST-API
# ----------------------------------------------------------------------------------------------------------
require 'openssl'
require 'securerandom'
require 'rbconfig'
# Require the azure storage blob rubygem
require 'azure/storage/blob'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
$stdout.sync = true
# Method that creates a test file in the 'Documents' folder or in the home directory on Linux.
# This sample application creates a test file, uploads the test file to the Blob storage,
# lists the blobs in the container, and downloads the file with a new name.
def run_sample
account_name = 'accountname'
account_key = 'accountkey'
is_windows = (RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/)
# Create a BlobService object
blob_client = Azure::Storage::Blob::BlobService
begin
# Create a BlobService object
blob_client = Azure::Storage::Blob::BlobService.create(
storage_account_name: account_name,
storage_access_key: account_key
)
# Create a container called 'quickstartblobs'.
container_name = 'quickstartblobs' + SecureRandom.uuid
puts "Creating a container: " + container_name
container = blob_client.create_container(container_name)
# Set the permission so the blobs are public.
blob_client.set_container_acl(container_name, "container")
# Create a file in Documents to test the upload and download.
if(is_windows)
local_path = File.expand_path("~/Documents")
else
local_path = File.expand_path("~/")
end
local_file_name = "QuickStart_" + SecureRandom.uuid + ".txt"
full_path_to_file = File.join(local_path, local_file_name)
# Write text to the file.
file = File.open(full_path_to_file, 'w')
file.write("Hello, World!")
file.close()
puts "\nCreated a temp file: " + full_path_to_file
puts "\nUploading to Blob storage as blob: " + local_file_name
# Upload the created file using local_file_name for the blob name
blob_client.create_block_blob(container.name, local_file_name, full_path_to_file)
# List the blobs in the container
puts "\nList blobs in the container following continuation token"
nextMarker = nil
loop do
blobs = blob_client.list_blobs(container_name, { marker: nextMarker })
blobs.each do |blob|
puts "\tBlob name #{blob.name}"
end
nextMarker = blobs.continuation_token
break unless nextMarker && !nextMarker.empty?
end
# Download the blob(s).
# Add '_DOWNLOADED' as prefix to '.txt' so you can see both files in Documents.
full_path_to_file2 = File.join(local_path, local_file_name.gsub('.txt', '_DOWNLOADED.txt'))
puts "\nDownloading blob to " + full_path_to_file2
blob, content = blob_client.get_blob(container_name,local_file_name)
File.open(full_path_to_file2,"wb") {|f| f.write(content)}
puts "Sample finished running. Hit <any key>, to delete resources created by the sample and exit the application"
readline()
rescue Exception => e
puts e.message
ensure
# Clean up resources. This includes the container and the temp files
blob_client.delete_container(container_name)
File.delete(full_path_to_file)
File.delete(full_path_to_file2)
end
end
# Main method.
run_sample
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# nom :string
# email :string
# created_at :datetime not null
# updated_at :datetime not null
# birthdate :date
# readMoreBooks :boolean
# readBooks :integer
# cvPath :string
# watchedMoviesCinema :integer
# watchedMoviesTV :integer
# watchedMoviesComputer :integer
# watchedMoviesTablet :integer
#
class User < ActiveRecord::Base
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :nom, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :birthdate, :presence => true
validates :watchedMoviesCinema, :presence => true
validates :watchedMoviesTV, :presence => true
validates :watchedMoviesComputer, :presence => true
validates :watchedMoviesTablet, :presence => true
validates :readBooks, :presence => true
validates :readMoreBooks, inclusion: [true, false]
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :adjust_format_for_iphone
# before_filter :set_year
# before_filter :reload_settings
##
# Stuff to store and return to last recorded page
##
def remember_current_page(url=nil)
flash[:notice] = nil
flash[:error] = nil
cookies[:last_page] = url || request.original_fullpath
end
def stored_page
return cookies[:last_page] || home_path
end
def load_stored_page
redirect_to stored_page
end
def reload_settings
Settings.reload unless Rails.env.test?
end
# For ajax requests
# skip_before_filter :verify_authenticity_token, :only => [:name_of_your_action]
unless Rails.application.config.consider_all_requests_local
rescue_from Exception, with: :render_500
rescue_from ActionController::RoutingError, with: :render_404
rescue_from ActionController::UnknownController, with: :render_404
rescue_from ::AbstractController::ActionNotFound, with: :render_404
rescue_from Mongoid::Errors::DocumentNotFound, with: :render_404
end
#
## Note: Unclear why I need any of these
##
## Devise methods
##
# helper_method :current_user
#
def current_user
return @current_user ||= warden.authenticate(:scope => :user)
end
helper_method :current_user_name
def current_user_name
return user_signed_in? ? current_user.full_name : "Guest"
end
helper_method :user_signed_in?
#
def user_signed_in?
return !!current_user
end
#
def user_session
return current_user && warden.session(:user)
end
helper_method :editable?
def editable?
user_signed_in?
end
# if user is logged in, return current_user, else return guest_user
def current_or_guest_user
if current_user
if session[:guest_user_id]
logging_in
guest_user.destroy
session[:guest_user_id] = nil
end
return current_user
else
return guest_user
end
end
# # find guest_user object associated with the current session,
# # creating one as needed
# def guest_user
# return User.find(session[:guest_user_id].nil? ? session[:guest_user_id] = create_guest_user.id : session[:guest_user_id])
# end
# called (once) when the user logs in, insert any code your application needs
# to hand off from guest_user to current_user.
# def logging_in
# # For example:
# # guest_comments = guest_user.comments.all
# # guest_comments.each do |comment|
# # comment.user_id = current_user.id
# # comment.save
# # end
# end
#
# def create_guest_user
# u = User.new
# u.save(:validate => false)
# return u
# end
# def devise_mapping
# @devise_mapping ||= Devise.mappings[:user]
# end
protected
# Per https://github.com/galetahub/ckeditor/issues/222
def ckeditor_filebrowser_scope(options = {})
super({assetable_id: current_user.id, assetable_type: 'Teacher' }.merge(options))
end
def check_for_cancel
load_stored_page if params[:cancel]
end
private
def set_year
params[:year] ||= Settings.academic_year
end
def render_404(exception)
@not_found_path = exception.message
##
## handle old paths
##
if m = exception.message.match(/^\/course_index\.php\?course_num=(\d+)$/)
redirect_to controller: :courses, action: :show, id: "#{m[0]}.to_i"
return
end
respond_to do |format|
format.html { render template: 'errors/error_404', layout: nil, status: 404 }
format.all { render nothing: true, status: 404 }
end
end
def render_500(exception)
@error = exception
respond_to do |format|
format.html { render template: 'errors/error_500', layout: nil, status: 500 }
format.all { render nothing: true, status: 500}
end
end
def adjust_format_for_iphone
# request.format = :ios if request.env["HTTP_USER_AGENT"] =~ %r{Mobile/.+Safari}
end
def after_sign_in_path_for(resource)
stored_page
end
end
|
class ConnectionContextsController < ApplicationController
before_filter :authenticate_user!
def show
@application = Application.find(params[:application_id])
authenticate_ownership(@application)
@context = @application.connection_contexts.find(params[:id])
end
def edit
@application = Application.find(params[:application_id])
authenticate_ownership(@application)
@context = @application.connection_contexts.find(params[:id])
end
def update
end
def new
@application = Application.find(params[:application_id])
authenticate_ownership(@application)
@context = @application.connection_contexts.build
end
def create
@application = Application.find(params[:application_id])
authenticate_ownership(@application)
@context = @application.connection_contexts.build params[:connection_context]
@context.connection_context_protocols << ConnectionContextProtocol.find_by_name('text-protocol') if params[:text_protocol]
if @context.save
redirect_to application_connection_context_path(@application, @context)
else
render 'new'
end
end
def redirect_back_from_signup
redirect_back root_path
end
end |
require 'rspec'
require_relative 'find_and_replace'
describe FindAndReplacePath do
subject(:replacer) { described_class.new(find_pattern, replace_pattern) }
before do
@here = Dir.pwd
@there = '/tmp/find_and_replace_test_dir'
@file = "#{@there}/file.rb"
Dir.mkdir @there
Dir.chdir @there
end
after do
`rm -r #{@there}`
Dir.chdir @here
end
describe '#call' do
context 'when replacing foo' do
let(:find_pattern) { 'foo' }
context 'with bar' do
let(:replace_pattern) { 'bar' }
it 'foobar.rb becomes barbar.rb' do
file = "#{@there}/foobar.rb"
expected_file = "#{@there}/barbar.rb"
File.open(file, 'w+') do |f|
f.write 'hello world'
end
replacer.call
expect(File.exist?(file)).to eq false
expect(File.exist?(expected_file)).to eq true
end
end
end
end
end
describe FindAndReplaceText do
before do
@here = Dir.pwd
@there = '/tmp/find_and_replace_test_dir'
@file = "#{@there}/file.rb"
Dir.mkdir @there
Dir.chdir @there
File.open(@file, 'w+') do |f|
f.write 'hello world'
end
end
after do
`rm -r #{@there}`
Dir.chdir @here
end
describe "#call" do
context "search string is 'hello'" do
let(:find_str) { 'hello' }
context "replace string is 'goodbye'"do
let(:replace_str) { 'goodbye' }
context "setting the file pattern" do
let(:file_pattern) { "*.foo" }
before do
File.open("#{@there}/file_2.foo", 'w+') do |f|
f.write 'hello world'
end
end
it 'changes only the specified files' do
described_class.new(find_str, replace_str, file_pattern).call
expect(File.read("#{@there}/file_2.foo")).to eq 'goodbye world'
expect(File.read("#{@there}/file.rb")).to eq 'hello world'
end
end
context "multiple files" do
before do
File.open("#{@there}/file_2.rb", 'w+') do |f|
f.write 'hello world'
end
end
it "changes all files to read 'goodbye world'" do
described_class.new(find_str, replace_str).call
Dir.glob("#{@there}/*") do |file|
expect(File.read(file)).to eq 'goodbye world'
end
end
end
context "multiple directories" do
before do
Dir.mkdir "#{@there}/dir"
File.open("#{@there}/dir/file_2.rb", 'w+') do |f|
f.write 'hello world'
end
end
it "changes all files to read 'goodbye world'" do
described_class.new(find_str, replace_str).call
Dir.glob("#{@there}/**/*.rb") do |file|
expect(File.read(file)).to eq 'goodbye world'
end
end
end
end
end
end
end
|
#encoding: utf-8
class WesellItem < ActiveRecord::Base
belongs_to :store
belongs_to :category
has_many :order_items, dependent: :restrict_with_exception
has_many :orders, through: :order_items
has_many :options_groups, dependent: :destroy
has_many :wesell_item_options
has_many :comments, dependent: :destroy, as: :commentable
mount_uploader :image, ImageUploader
mount_uploader :banner, BannerUploader
STATUS = {
"不限量供应" => 0,
"限量供应" => 1,
"等待发售" => 2,
# "下架" => 10
}
RULE = {
"普通" => "rule",
"限制" => "showroom"
}
def human_status
yxj = { 'normal' => '已下架', 'event' => '已过期'}
dks = { 'normal' => '待开售', 'event' => '即将开放报名' }
ysq = { 'normal' => '已售罄', 'event' => '名额已报满' }
ys_ = { 'normal' => '已售', 'event' => '已报' }
return yxj[self.store.stype] if status >= 10
return dks[self.store.stype] if status == 2
return quantity <=0 ? " #{ysq[self.store.stype]}" : "" if status == 1
return total_sold > 0 ? "#{ys_[self.store.stype]}#{total_sold}#{unit_name}" : ""
end
validates_presence_of :name, :quantity, :price, :unit_name, :status, :sequence
# validates_uniqueness_of :name, scope: [:store_id, :status]
# validates_numericality_of :price, greater_than: 0
validates_numericality_of :original_price, :quantity, greater_than_or_equal_to: 0
validates_length_of :description, maximum: 140
delegate :monetary_unit, :monetary_tag, to: :store
default_scope { order('wesell_items.sequence ASC') }
scope :online, -> { where('deleted = false AND status < 10') }
scope :offline, -> { where('deleted = false AND status = 10') }
scope :undeleted, -> { where(deleted: false) }
after_save :update_counter_cache
after_destroy :update_process
after_update :update_order_items, :if => :price_changed?
searchable do
text :name, stored: true
text :description, stored: true
integer :total_sold
integer :store_id
end
def update_order_items
self.order_items.each do |i|
new_price = self.price
i.unit_price = new_price
i.save
end
end
def show_buyers?
return self.store.show_buyers
#return false if self.store.id != 3408 && self.store.id != 1 #this is a quick way
#return true
end
def show_visitors?
return false if self.store.id != 3408 && self.store.id != 1 #this is a quick way
return true
end
def buyers
bs = []
self.orders.unopen.pluck(:customer_id).uniq.each { |cid| bs << Customer.find_by(id: cid) }
return bs
end
def visitors
bs = []
self.orders.open.pluck(:customer_id).uniq.each { |cid| bs << Customer.find_by(id: cid) }
return bs
end
def human_price mystore=nil
mystore ||= store
"#{mystore.monetary_tag}#{price}/#{unit_name}"
end
def human_original_price mystore=nil
mystore ||= store
"#{mystore.monetary_tag}#{original_price}/#{unit_name}"
end
def the_order_by buyer
buyer.orders.each do |order|
return order if order.wesell_items.include? self
end
end
def category_name
category.name if category
end
def add_to_order order
OrderItem.find_or_initialize_by({
order_id: order.id,
wesell_item_id: self.id,
category_id: self.category_id,
name: self.name,
unit_price: self.price,
unit_name: self.unit_name
})
end
def data_hash
{ product_id: self.id,
dishid: self.id,
dunitname: self.unit_name,
dsubcount: self.total_sold,
dname: self.name,
dtaste: "",
ddescribe: self.description,
dprice: self.price,
dishot: "2",
dspecialprice: self.original_price,
disspecial: "1",
shopinfo: ""}
end
#下架
def offline
update_attribute :status, 10
end
def offline?
status >= 10
end
def online?
!offline?
end
def online
update_attribute :status, 0
end
def delete!
update_attributes deleted: true
end
def sold_out?
if status == 0
return false
elsif quantity <= 0
return true
end
end
def human_stock
status == 0 ? '不限量供应' : "库存#{quantity}#{unit_name}"
end
def copy! options = {}
item_copy = self.dup
item_copy.oldid = nil
item_copy.name = options[:name] if options.present?
if item_copy.save
self.options_groups.each do |option_group|
option_group_copy = option_group.dup
option_group_copy.wesell_item_id = item_copy.id
option_group_copy.oldid = nil
if option_group_copy.save(validate: false)
option_group.wesell_item_options.each do |option|
option_copy = option.dup
option_copy.wesell_item_id = option_group_copy.wesell_item_id
option_copy.options_group_id = option_group_copy.id
option_copy.save(validate: false)
end
end
end
end
item_copy
end
def update_counter_cache
if self.changes[:store_id].present? || self.changes[:deleted]
self.update_process
# Store.find(self.changes[:store_id].compact).each do |store|
# store.wesell_items_count = WesellItem.where("deleted = false AND store_id = ?", store.id).count
# store.save
# end
end
if self.changes[:category_id].present?
Category.find(self.changes[:category_id].compact).each do |category|
category.products_count = WesellItem.where("deleted = false AND category_id = ?", category.id).count
category.save(validate: false)
end
end
end
def update_process
# logger.info "======== true ========="
# logger.info "======== #{self.changes} ========="
store = self.store
store.wesell_items_count = WesellItem.where("deleted = false AND store_id = ?", store.id).count
store.save(validate: false)
end
end
|
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
require 'set'
require 'dataMetaDom/util'
require 'dataMetaDom/recAttr'
require 'dataMetaDom/dataType'
require 'dataMetaDom/field'
require 'dataMetaDom/docs'
require 'dataMetaDom/enum'
require 'dataMetaDom/record'
require 'dataMetaDom/ref'
require 'dataMetaDom/sourceFile'
require 'date'
require 'dataMetaXtra'
require 'dataMetaDom/sources'
require 'dataMetaDom/model'
=begin rdoc
DataMeta DOM infrastructure root.
For command line details either check the new method's source or the README.rdoc file, the usage section.
=end
module DataMetaDom
# Current version
VERSION = '1.0.7'
=begin rdoc
Quick and dirty turning a Windows path into a path of the platform on which this script is running.
Assumes that backslash is never used as a part of a directory name, pretty safe assumption.
=end
def uniPath(source)
source.gsub(/\\/, File::SEPARATOR)
end
=begin rdoc
Returns an array of the namespace and the base, first element nil if no namespace
both elements nil if not a proper namespace.
@param [String] source source text to split
@return [Array] array of +String+, the namespace and the base
=end
def splitNameSpace(source)
#noinspection RubyNestedTernaryOperatorsInspection
source =~ /(\w[\w\.]*)\.(#{TYPE_START}\w*)/ ? [($1.empty? ? nil : $1), $2] :
(source =~ /(#{TYPE_START}\w*)/ ? [nil, source] : [nil, nil])
end
# adjust the namespace if required
def nsAdjustment(namespace, options, src)
src && options[:autoVerNs] ? "#{namespace}.v#{src.ver.full.toVarName}" : namespace
end
=begin rdoc
Combines the namespace with the base name: if the namespace is empty or +nil+, returns the base name as a symbol,
otherwise returns namespace.base
@param [String] namespace the namespace part
@param [String] base the base name of the entity
@return [String] base and namespace properly combined into full name specification
=end
def combineNsBase(namespace, base)
namespace && !namespace.empty? ? "#{namespace}.#{base}".to_sym : base.to_sym
end
=begin rdoc
Given the namespace and the base, returns true if the namespace is a valid one.
@param [String] namespace the namespace part
@param [String] base the base name of the entity
@return [Boolean] true if the given namespace passes simple smell check with the given base
=end
def validNs?(namespace, base)
namespace && !namespace.empty? && namespace.to_sym != base
end
=begin rdoc
if name is a standard type, return it.
if name is a fully qualified namespaced name, return it
otherwise, combine the namespace provided with the base to return the full name
=end
def fullTypeName(namespace, name)
#noinspection RubyUnusedLocalVariable
ns, _ = splitNameSpace(name.to_s) # if it is already a full namespaced name or a standard type, return original
validNs?(ns, name) || STANDARD_TYPES.member?(name) ? name.to_sym : "#{combineNsBase(namespace, name)}".to_sym
end
# Returns qualified name for the given namespace: strips the namespace if the namespace is the same, or keep it
def qualName(namespace, name)
ns, b = splitNameSpace(name.to_s)
!STANDARD_TYPES.member?(name.to_sym) && (!validNs?(ns, b) || ns == namespace) ? b : name
end
=begin rdoc
Simplest diminfo to be reused wherever no other aspect of a datatype is needed
@!attribute [r] len
@return [Fixnum] the Length part of the dimension info
@!attribute [r] scale
@return [Fixnum] the Scale part of the dimension info
=end
class DimInfo
attr_reader :len, :scale
# Creates an instance with the given parameters
def initialize(len, scale); @len = len; @scale = scale end
# Textual representation of this instance, length.scale
def to_s; "#{@len}.#{@scale}" end
# Convenience constant - NIL dimension to use in the types that are not dimensioned.
NIL=DimInfo.new(nil, nil)
end
=begin rdoc
# Parses parenthesized dimension info such as (18, 2) or just (18)
Returns DimInfo::NIL if the dimSpec is +nil+ or the DimInfo instance as specified
=end
def getParenDimInfo(dimSpec)
return DimInfo::NIL unless dimSpec
result = dimSpec =~ /^\s*\(\s*(\d+)\s*(?:,\s*(\d+))?\s*\)\s*$/
raise "Invalid dimension specification: '#{dimSpec}'" unless result
DimInfo.new($1.to_i, $2.to_i)
end
=begin rdoc
Adds options to help and version from the first argument
And shortcuts to showing the help screen if the ARGV is empty.
The options for help are either <tt>--help</tt> or </tt>-h</tt>.
The option for show version and exit is either <tt>--version</tt> or <tt>-v</tt>.
=end
def helpAndVerFirstArg
raise Trollop::HelpNeeded if ARGV.empty? || ARGV[0] == '--help' || ARGV[0] == '-h' # show help screen
raise Trollop::VersionNeeded if ARGV[0] == '--version' || ARGV[0].downcase == '-v' # show version screen
end
module_function :combineNsBase, :splitNameSpace, :uniPath, :validNs?, :getParenDimInfo,
:helpAndVerFirstArg, :fullTypeName, :nsAdjustment
end
|
class Question < ActiveRecord::Base
attr_accessible :text, :adjectives
belongs_to :user
validates_presence_of :adjectives, :text
end
|
require './hash_keys'
describe Hash do
describe '#keys_of' do
it "should return the keys that match the values" do
expect({:a=> 1, :b=> 2, :c=> 3}).keys_of(1)).to eq([:a])
end
it "should return the keys that match the values" do
expect({:a=> 1, :b=> 2, :c=> 3, :d=> 1}).keys_of(1)).to eq([:a, :d])
end
it "should return the keys that match the values" do
expect({:a=> 1, :b=> 2, :c=> 3, :d=> 1}).keys_of(1, 2)).to eq([:a, :b, :d])
end
end
end
|
class Thought
attr_reader :comment
def initialize
@comment = THOUGHTS.reduce('') { |carry, part| carry << part.sample + ' ' }.strip
end
THOUGHTS = [
[
'Es bonito',
'Me gusta',
'Lo mejor del mundo',
'Menos mal que puedo',
'Amo'
],
[
'encerrarme a ver Netflix',
'convivir con mi perrito',
'hablar con gente que no me tire mala vibra',
'leer un buen libro',
'ignorar a todos'
],
[
'y sentirme feliz',
'y que me valga verga el mundo',
'y confiar más en mi',
'y empoderarme de mi ser',
'y consentirme un poquito más'
],
[
'para alejarme de',
'para evitar',
'para no contaminarme de',
'para cuidarme de',
'para no caer en'
],
[
'emociones tóxicas',
'personas tóxicas',
'situaciones tóxicas',
'comentarios tóxicos',
'conversaciones tóxicas',
]
]
end
|
class Workplace < ActiveRecord::Base
attr_accessible :name
has_many :users
has_one :location
end
|
class UserResult
ERROR_TYPES = {
:duplicate => 'This email is already taken'
}.freeze
attr_reader :success, :error_reader
def initialize(success:, error_type: nil)
@success = success
@error_type = error_type
end
def success?
return @success
end
def duplicate?
return true if @error_type == :duplicate
end
def error_message
ERROR_TYPES[@error_type]
end
def self.duplicate_result
UserResult.new(success: false, error_type: :duplicate)
end
def self.successful_result
UserResult.new(success: true)
end
end
|
module Vizier
class ExecutableUnit
def initialize(path, tasks)
@path = path
@tasks = tasks
@current_task = 0
@view = { "results" => [], "tasks" => {}, "subject" => {} }
@tasks.each do |task|
@view["tasks"][task.name] = {}
end
end
attr_reader :view, :path
def undoable?
@undoable ||= @tasks.all?{|task| task.respond_to?(:undo)}
end
def started?
@current_task > 0
end
def finished?
@current_task >= @tasks.length
end
#XXX include task instances
def inspect
return "#<EU:#{path.join("/")}>:#{"%#x" % self.object_id}"
rescue
super
end
def go(collector)
@tasks.each.with_index(@current_task) do |task, idx|
@current_task = idx
task.execute(@view["tasks"][task.name])
@view["subject"].merge! task.subject_view
end
@current_task = @tasks.length
end
def undo(collector)
@tasks.reverse_each.with_index(length - @current_task) do |task, idx|
@current_task = length - idx
task.reverse(@view["tasks"][task.name])
@view["subject"].merge! task.subject_view
end
@current_task = 0
end
def join_undo(stack)
stack.add(self) if undoable?
end
end
end
|
module EmployeesHelper
#Developer : André & Frank
# return total salary of the given collection employees
def get_total_salaries(employees)
total = 0
employees.each do |e|
unless e.salary.nil?
total += e.salary
end
end
total.round(2)
end
# returns the average salary of the given collection employees
def get_mean_salary(employees)
if employees.count != 0
(get_total_salaries(employees) / employees.count).round(2)
else
0
end
end
end
|
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.integer :stock_id
t.string :productname
t.string :producttype
t.integer :productprice
t.integer :amount
t.integer :shippingfee
t.string :shippingway
t.string :shippingcode
t.string :ordernum
t.date :paydate
t.string :paytime
t.string :payaccount
t.string :paytype
t.string :status
t.integer :buyer_id
t.string :buyertel
t.string :buyername
t.integer :saler_id
t.string :salertel
t.timestamps
end
end
end
|
# frozen_string_literal: true
module Exceptions
# Base Json Api Exception
class NotAuthorized < Base
def errors
{
code: 401,
status: :unauthorized,
title: 'Not Authorized',
detail: @exception,
id: 401
}
end
end
end
|
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val = 0, left = nil, right = nil)
# @val = val
# @left = left
# @right = right
# end
# end
# @param {Integer[]} preorder
# @param {Integer[]} inorder
# @return {TreeNode}
def build_tree(preorder, inorder)
return nil if inorder.empty?
root_node = TreeNode.new(preorder.first)
root_index = inorder.index(preorder.first)
root_node.left = build_tree(preorder[1..root_index], inorder[0...root_index])
root_node.right = build_tree(preorder[root_index+1..-1], inorder[root_index+1..-1])
return root_node
end
|
class Student
attr_reader :first_name
@@all = []
def initialize(first_name)
@first_name = first_name
@@all << self
end
def self.all
@@all
end
def add_boating_test(test_name, status, instructor)
BoatingTest.new(self, test_name, "pending", instructor)
end
def self.find_student(first_name)
self.all.find{|student|
if student.first_name == first_name
return student
end
}
end
def grade_percentage
tests = BoatingTest.all.find_all{|boatingTest| boatingTest.student == self}
totalTests = tests.length.to_f
total = tests.find_all{|t| t.test_status == "passed"}
floatTotal = total.length.to_f
floatTotal / totalTests
end
end
|
class AddCompanyNameToEnquiries < ActiveRecord::Migration[5.2]
def change
add_column :enquiries, :company_name, :string
add_column :enquiries, :company_reg, :string
add_column :enquiries, :industry, :string
add_column :enquiries, :size, :string
add_column :enquiries, :location, :string
end
end
|
class Deck
attr_accessor :cards
def initialize
@cards = []
set_deck
end
def set_deck
Card::SUITS.each do |suit|
Card::RANKS.each do |rank, nominal|
card = Card.new(suit, rank, nominal)
@cards << card
end
end
end
def mix_deck
@cards.shuffle!
end
def give_a_card
@cards.pop
end
end
|
class JobApplicationsController < ApplicationController
before_filter :is_employer_exist_in_session, :only => [:call_for_interview]
def update
@job_application = JobApplication.includes(:job_seeker).find(params[:id])
@employer = Employer.find(session[:id])
@job_seeker = @job_application.job_seeker
@job = @job_application.job
respond_to do |format|
if (@job_application.update_attributes(params[:job_application]))
Notifier.delay.send_email_for_interview(@job_application)
format.html { redirect_to view_applicants_job_path(@job_application.job_id),
:notice => "An email has been sent to the job seeker" }
else
format.html { render "call_for_interview" }
end
end
end
def call_for_interview
@job_application = JobApplication.includes(:job_seeker, [:job => :employer]).find_by_id(params[:id])
end
def perform_action
@job_application = JobApplication.find_by_id(params[:id])
begin
if @job_application.send(params[:event])
flash[:notice] = "Action #{params[:event].humanize} has been successfully performed"
else
flash[:error] = "This Action (#{params[:event].humanize}) Cannot be Applied on current state"
end
redirect_to request.referrer
rescue => e
flash[:error] = "This Action (#{params[:event].humanize}) is invalid"
redirect_to request.referrer
end
end
def view_applicants
@job_applications = JobApplication.scoped_by_job_id(params[:id]).where(:state => params[:state])
render "job_applications/view_#{params[:state]}"
end
private
def is_employer_exist_in_session
@employer = Employer.find_by_id(session[:id]) if session[:user_type] == "employer"
unless @employer
flash[:error] = "Employer not found"
redirect_to root_url
end
end
end
|
require_relative 'produser_module.rb'
class Train
include Produser
attr_reader :type, :id, :station_index, :current_staion, :route_stations
@@trains = {}
def initialize(id, type)
@id = id
@type = type
@speed = 0
@waggons = []
@waggons_count = 0
@route_stations = []
@current_staion = nil
@@trains[id] = self
end
def self.find(id)
@@trains[id]
end
def speed_up
@speed += 10
@speed = 110 if @speed > 110
end
def print_sp
puts "Current speed of #{@id} is #{@speed} kmh"
end
def speed_down
@speed -= 10
@speed = 0 if @speed < 0
end
def print_wag
puts "Number of waggons of #{id} train is #{@waggons_count}"
end
def set_route(route)
if route.class != Route
puts "Wrong route"
else @route_stations = route.stations
@current_staion = @route_stations[0]
@station_index = 0
end
end
def move_next_station
if @station_index + 1 <= @route_stations.size
@station_index += 1
@current_staion = @route_stations[@station_index]
else
puts "You are on the final station of the route"
end
end
def move_previous_station
if @station_index - 1 >= 0
@station_index -= 1
@current_staion = @route_stations[@station_index]
else
puts "You are on the first station of the route"
end
end
def print_current_station
print @current_staion.name
end
def print_next_station
puts @route_stations[@station_index+1].name
end
def print_previous_station
puts @route_stations[@station_index-1].name
end
end
class PassengerTrain < Train
def initialize(id)
@id = id
@type = "passenger"
@waggons = []
@waggons_count = 0
@speed = 0
end
def add_wag(waggon,waggon_id)
if @speed == 0
if waggon.class == PassengerWaggon
@waggons << waggon
waggon.passenger_wagon_id = waggon_id
@waggons_count += 1
else puts "Wrong type of waggon"
end
else puts "Stop the train to remove waggons"
end
end
def remove_wag(waggon)
if @speed == 0
if @waggons.include?(waggon)
@waggons.delete(waggon)
@waggons_count -= 1
waggon.passenger_wagon_id = nil
else puts "This waggon is not attached to this train"
end
else puts "Stop the train to remove waggons"
end
end
end
class CargoTrain < Train
def initialize(id)
@id = id
@type = "cargo"
@waggons = []
@waggons_count = 0
@speed = 0
end
def add_wag(waggon,waggon_id)
if @speed == 0
if waggon.class == CargoWaggon
@waggons << waggon
waggon.cargo_wagon_id = waggon_id
@waggons_count += 1
else puts "Wrong type of waggon"
end
else puts "Stop the train to remove waggons"
end
end
def remove_wag(waggon)
if @speed == 0
if @waggons.include?(waggon)
@waggons.delete(waggon)
@waggons_count -= 1
waggon.cargo_wagon_id = nil
else puts "This waggon is not attached to this train"
end
else puts "Stop the train to remove waggons"
end
end
end
|
require 'capybara/rspec'
require 'text_order/rspec'
RSpec.describe 'RSpec matchers', type: :feature do
STRING = 'first middle last'
describe 'after' do
it 'detects value after expected text' do
expect(STRING).to include_text('last').after('first')
end
end
describe 'before' do
it 'detects value before expected text' do
expect(STRING).to include_text('first').before('last')
end
end
describe 'between' do
it 'detects value both before and after expected text' do
expect(STRING).to include_text('middle').before('last').after('first')
expect(STRING).to include_text('middle').after('first').before('last')
end
end
describe 'capybara page content' do
App = ->(*) { [200, {}, ['<div>first</div><div>middle</div><div>last</div>']] }
Capybara.app = App
it 'is useful in combination with capybara to determine page content ordering' do
visit '/'
expect(page.text).to include_text('middle').before('last').after('first')
end
it 'provides some useful shortcut matchers' do
visit '/'
expect('first').to appear_before('middle')
expect('last').to appear_after('middle')
end
end
end
|
require 'test_helper'
class CommercegateTest < Test::Unit::TestCase
def setup
@gateway = CommercegateGateway.new(
:login => 'usrID',
:password => 'usrPass'
)
@credit_card = ActiveMerchant::Billing::CreditCard.new(
:first_name => 'John',
:last_name => 'Doe',
:number => '5333339469130529',
:month => '01',
:year => Time.now.year + 1,
:verification_value => '123')
@amount = 1000
@options = {
:ip => '192.168.7.175', # conditional, required for authorize and purchase
:email => 'john_doe01@yahoo.com', # required
:merchant => '', # conditional, required only when you have multiple merchant accounts
:currency => 'EUR', # required
:address => address,
# conditional, required for authorize and purchase
:site_id => '123', # required
:offer_id => '321' # required
}
end
def test_successful_authorize
@gateway.expects(:ssl_post).returns(successful_authorize_response)
assert response = @gateway.authorize(@amount, @credit_card, @options)
assert_instance_of Response, response
assert_success response
assert_equal '100130291387', response.authorization
assert_equal 'U', response.avs_result["code"]
assert_equal 'S', response.cvv_result["code"]
end
def test_successful_capture
trans_id = '100130291387'
@gateway.expects(:ssl_post).returns(successful_capture_response)
assert response = @gateway.capture(@amount, trans_id, @options)
assert_instance_of Response, response
assert_success response
assert_equal '100130291402', response.authorization
assert_equal '10.00', response.params['amount']
assert_equal 'EUR', response.params['currencyCode']
end
def test_successful_purchase
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_instance_of Response, response
assert_success response
assert_equal '100130291412', response.authorization
assert_equal 'U', response.avs_result["code"]
assert_equal 'S', response.cvv_result["code"]
assert_equal 'rdkhkRXjPVCXf5jU2Zz5NCcXBihGuaNz', response.params['token']
end
def test_successful_refund
trans_id = '100130291387'
@gateway.expects(:ssl_post).returns(successful_refund_response)
assert response = @gateway.refund(@amount, trans_id, @options)
assert_instance_of Response, response
assert_success response
assert_equal '100130291425', response.authorization
assert_equal '10.00', response.params['amount']
assert_equal 'EUR', response.params['currencyCode']
end
def test_successful_void
trans_id = '100130291412'
@gateway.expects(:ssl_post).returns(successful_void_response)
assert response = @gateway.void(trans_id, @options)
assert_instance_of Response, response
assert_success response
assert_equal '100130425094', response.authorization
assert_equal '10.00', response.params['amount']
assert_equal 'EUR', response.params['currencyCode']
end
def test_unsuccessful_authorize
@gateway.expects(:ssl_post).returns(failed_authorize_response_invalid_country)
assert response = @gateway.authorize(@amount, @credit_card, @options)
assert_instance_of Response, response
assert_failure response
assert_equal '-103', response.params['returnCode']
end
def test_unsuccessful_capture_empty_trans_id
@gateway.expects(:ssl_post).returns(failed_request_response)
assert response = @gateway.capture(@amount, '', @options)
assert_instance_of Response, response
assert_failure response
assert_equal '-125', response.params['returnCode']
end
def test_unsuccessful_capture_trans_id_not_found
@gateway.expects(:ssl_post).returns(failed_capture_response_invalid_trans_id)
assert response = @gateway.capture(@amount, '', @options)
assert_instance_of Response, response
assert_failure response
assert_equal '-121', response.params['returnCode']
end
private
def failed_request_response
"returnCode=-125&returnText=Invalid+operation"
end
def successful_purchase_response
"action=SALE&returnCode=0&returnText=Success&authCode=040404&avsCode=U&cvvCode=S&amount=10.00¤cyCode=EUR&transID=100130291412&token=rdkhkRXjPVCXf5jU2Zz5NCcXBihGuaNz"
end
def successful_authorize_response
"action=AUTH&returnCode=0&returnText=Success&authCode=726293&avsCode=U&cvvCode=S&amount=10.00¤cyCode=EUR&transID=100130291387&token=Hf4lDYcKdJsdX92WJ2CpNlEUdh05utsI"
end
def failed_authorize_response_invalid_country
"action=AUTH&returnCode=-103&returnText=Invalid+country"
end
def successful_capture_response
"action=CAPTURE&returnCode=0&returnText=Success&amount=10.00¤cyCode=EUR&transID=100130291402"
end
def failed_capture_response_invalid_trans_id
"action=CAPTURE&returnCode=-121&returnText=Previous+transaction+not+found"
end
def successful_refund_response
"action=REFUND&returnCode=0&returnText=Success&amount=10.00¤cyCode=EUR&transID=100130291425"
end
def successful_void_response
"action=VOID_AUTH&returnCode=0&returnText=Success&amount=10.00¤cyCode=EUR&transID=100130425094"
end
end
|
module Translatable
extend ActiveSupport::Concern
DEFAULT_LOCALE = 'de'.freeze
TRANSLATABLE_LOCALES = ['ar', 'en', 'es', 'fa', 'fr', 'ku', 'pa', 'ps', 'ru', 'sq', 'sr', 'ti', 'tr', 'ur'].freeze
AREAS = Area.order(:id).pluck(:title).freeze rescue ['dresden', 'leipzig', 'bautzen'].freeze
# test flag, phraseapp generally inactive in testing, can be activated on a per instance basis
attr_accessor :force_translation_after_save
included do
after_save :update_or_create_translations,
if: -> { (Settings.phraseapp.active || force_translation_after_save) }
after_save :create_fapi_cache_job, on: :update
after_destroy :destroy_translations,
if: -> { (Settings.phraseapp.active || force_translation_after_save) }
def build_translation_key(attribute)
"#{self.class.translation_key_type}.#{id}.#{attribute}"
end
def self.build_translation_key(id, attribute)
"#{translation_key_type}.#{id}.#{attribute}"
end
def translation_key_type
self.class.translation_key_type
end
end
module ClassMethods
def translatable_attributes
raise NotImplementedError "translatable_attributes must be defined for class #{self.class}"
end
def translation_key_type
name.to_s.split('::').last.downcase.underscore
end
end
def client
@@client ||= PhraseAppClient.new
end
def create_fapi_cache_job
unless id_changed? # update
if translatable_attribute_changed?
# create translation cache job
FapiCacheJob.new.update_entry_translation(self, DEFAULT_LOCALE)
end
end
end
def update_or_create_translations
unless respond_to?(:root_orga?) && root_orga? # all entries except root orga
if translatable_attribute_changed?
json = create_json_for_translation_file
if json
translation_file_name = "#{translation_key_type}-#{id.to_s}-translation-#{DEFAULT_LOCALE}-"
file = client.write_translation_upload_json(translation_file_name, json)
if respond_to?(:area)
client.upload_translation_file_for_locale(file, DEFAULT_LOCALE, tags: area)
else
client.upload_translation_file_for_locale(file, DEFAULT_LOCALE)
end
else
Rails.logger.debug(
'skip phraseapp save hook because no nonempty translatable attributes present')
end
else
Rails.logger.debug(
'skip phraseapp save hook because no translatable attribute was changed')
end
end
end
def set_had_changes
# jsonapi calls two times save where the second call won't have changes anymore
# hence we only allow setting changes to true :-)
@had_changes = true if changed?
end
def create_json_for_translation_file(only_changes: true)
attribute_translations = {}
attributes_to_handle = self.class.translatable_attributes
if only_changes
attributes_to_handle.select! { |attribute| attribute.to_s.in?(changes.keys.map(&:to_s)) }
end
attributes_to_handle.each do |attribute|
next if send(attribute).blank?
attribute_translations[attribute.to_s] = send(attribute).presence
end
if !attribute_translations.empty?
return {
translation_key_type => {
id.to_s => attribute_translations
}
}
end
return nil
end
private
def translatable_attribute_changed?
changed? &&
self.class.translatable_attributes.
any? { |attribute| attribute.to_s.in?(changes.keys.map(&:to_s)) }
end
def destroy_translations
client.delete_translation(self)
end
end
|
json.array! @users_and_groups do |profile|
json.id profile.id
json.name profile.name
json.image_url profile.avatar_url(50)
json.link_url polymorphic_path(profile)
json.model_name profile.class.name
end
|
# encoding: utf-8
class FoodCalory < ActiveRecord::Base
def self.parse_amount( amount )
if pair = amount.match(/([1-9]+)\/([1-9]+)/)
origin, child, mother = pair.to_a
return (child.to_f / mother.to_f)
end
amount.to_f
end
def self.change_fraction( amount )
{
"½" => "1/2",
"⅓" => "1/3", "⅔" => "2/3",
"¼" => "1/4", "¾" => "3/4",
"⅕" => "1/5", "⅖" => "2/5", "⅗" => "3/5", "⅘" => "4/5",
"⅙" => "1/6", "⅚" => "5/6",
"⅛" => "1/8", "⅜" => "3/8", "⅝" => "5/8", "⅞" => "7/8",
}.each { |k,v| amount.gsub!(k,v) }
amount
end
def self.number_amount_parse( amount )
units = [
"個","m cà-phê","tô","nửa củ","ống","thia","chiếc","cọng","trai","cai","thìa cà phê","tai","lát","thìa","củ","muỗng canh",
"muỗng cà phê", "muỗng","quả","bát","gói","hộp","lá","chén","nhúm nhỏ","nhúm","lọn nhỏ","lóng","lon","ít","trái","nhánh",
"miếng","tép","cái","cây","viên","bánh","cốc","thỏi","bó","con","bịch","lít","cup","gr","g","ml","kg"
].join("|")
regexp = /\s*([0-9]+|[0-9]\.[0-9]|[1-9]+\/[1-9]+)\s*(#{units})\s*/
m = amount.match(regexp)
return unless m
origin, amount2, unit = m.to_a
amount3 = self.parse_amount( amount2 )
[origin,amount3,unit]
end
def self.name_parse_unit( amount )
units = [
"thìa cà phê","Một chút", "Một ít", "Vừa ăn", "Vừa đủ", "một chút", "một miếng","một ít",
"nửa củ", "nữa chén", "phan nguoi an", "tí xíu", "tùy khẩu vị", "tùy thích", "vua du",
"vài nhánh", "vừa ăn", "vừa đủ"
]
regexp = /\s*(#{units})\s*/
m = amount.match(regexp)
return unless m
origin, unit = m.to_a
[origin, 1, unit]
end
def self.parse_unit( amount )
amount = self.change_fraction( amount )
amount = amount.tr('0-9','0-9').tr('/','/')
amount = amount.gsub(/([0-9]+),([0-9]+)/,"\\1.\\2")
values = self.number_amount_parse( amount )
return values if values
values = self.name_parse_unit( amount )
return values if values
nil
end
end
|
require 'rails_helper'
def delete_post(post)
find(delete_post_selector).click
end
def edit_post_text(post, new_post_text)
find(edit_post_selector).click
fill_in "Body", with: new_post_text
click_on "Update Post"
end
def edit_post_picture(post, new_file_path)
find(edit_post_selector).click
attach_file "Picture", new_file_path
click_on "Update Post"
end
def create_post_with_text_and_picture(post_text, file_path)
fill_in "Body", with: post_text
attach_file "Picture", file_path
click_on "Create Post"
end
def create_post_with_picture_only(file_path)
attach_file "Picture", file_path
click_on "Create Post"
end
def have_post_author_name(post)
have_css("[data-test=post-#{post.id}]", text: post.user.name)
end
def posts_on_page
all(:xpath, '//div[@data-test]'){ |element| element['data-test'].include?('post') }
end
def post_doesnt_appear_editable(post)
within("[data-test=post-#{post.id}]") do
expect(page).not_to have_link("edit")
end
end
def post_doesnt_appear_deletable(post)
within("[data-test=post-#{post.id}]") do
expect(page).not_to have_link("delete")
end
end
def edit_post_selector
'[data-test="edit-post"]'
end
def delete_post_selector
'[data-test="delete-post"]'
end |
module Pacer::Core::Graph
# Basic methods for routes that contain only edges.
module EdgesRoute
import com.tinkerpop.pipes.transform.OutVertexPipe
import com.tinkerpop.pipes.transform.InVertexPipe
import com.tinkerpop.pipes.transform.BothVerticesPipe
# Extends the route with out vertices from this route's matching edges.
#
# @param [Array<Hash, extension>, Hash, extension] filter see {Pacer::Route#property_filter}
# @yield [VertexWrapper] filter proc, see {Pacer::Route#property_filter}
# @return [VerticesRoute]
def out_v(*filters, &block)
Pacer::Route.property_filter(outV,
filters, block)
end
def outV
chain_route(:element_type => :vertex,
:pipe_class => OutVertexPipe,
:route_name => 'outV')
end
# Extends the route with in vertices from this route's matching edges.
#
# @param [Array<Hash, extension>, Hash, extension] filter see {Pacer::Route#property_filter}
# @yield [VertexWrapper] filter proc, see {Pacer::Route#property_filter}
# @return [VerticesRoute]
def in_v(*filters, &block)
Pacer::Route.property_filter(inV,
filters, block)
end
def inV
chain_route(:element_type => :vertex,
:pipe_class => InVertexPipe,
:route_name => 'inV')
end
# Extends the route with both in and oud vertices from this route's matching edges.
#
# @param [Array<Hash, extension>, Hash, extension] filter see {Pacer::Route#property_filter}
# @yield [VertexWrapper] filter proc, see {Pacer::Route#property_filter}
# @return [VerticesRoute]
def both_v(*filters, &block)
Pacer::Route.property_filter(chain_route(:element_type => :vertex,
:pipe_class => BothVerticesPipe,
:route_name => 'bothV'),
filters, block)
end
# Extend route with the additional edge label, property and block filters.
#
# @param [Array<Hash, extension>, Hash, extension] filter see {Pacer::Route#property_filter}
# @yield [EdgeWrapper] filter proc, see {Pacer::Route#property_filter}
# @return [EdgesRoute]
def e(*filters, &block)
filter(*filters, &block)
end
# Return an route to all edge labels for edges emitted from this
# route.
#
# @return [Core::Route]
def labels
chain_route(:pipe_class => com.tinkerpop.pipes.transform.LabelPipe,
:route_name => 'labels',
:element_type => :object)
end
# Returns a hash of in vertices with an array of associated out vertices.
#
# See #subgraph for a more useful method.
#
# @return [Hash]
def to_h
inject(Hash.new { |h,k| h[k]=[] }) do |h, edge|
h[edge.out_vertex] << edge.in_vertex
h
end
end
# The element type of this route for this graph implementation.
#
# @return [element_type(:edge)] The actual type varies based on
# which graph is in use.
def element_type
:edge
end
protected
def id_pipe_class
com.tinkerpop.pipes.transform.IdEdgePipe
end
end
end
|
require 'spec_helper'
class ClassB; extend Questionnaire::FieldsHelper; end
describe Questionnaire::FieldsHelper do
let(:questionnaire_section) { { "section_name" => { "some_field" => nil, "some_other_field" => nil } } }
let(:questionnaire_with_two_sections) { questionnaire_section.merge("second_section" => {"second_field" => nil }) }
let(:questionnaire_fields_to_array) { [:some_field, :some_other_field, :second_field] }
describe "questionnaire fields" do
it "should return section_name with set of section fields" do
Questionnaire::Parser.stub(:load_fields).and_return(questionnaire_section)
ClassB.questionnaire_fields(questionnaire_section) {|s,b|}.should == questionnaire_section
end
it "should return array with section fields regardless section" do
Questionnaire::Parser.stub(:load_fields).and_return(questionnaire_with_two_sections)
ClassB.questionnaire_field_names(questionnaire_with_two_sections).should == questionnaire_fields_to_array
end
end
end
|
class AddressesController < ApplicationController
def new
@address = Address.new
end
def create
@address = Address.new(save_params)
if @address.save
redirect_to new_card_path
else
render "new"
end
end
private
def save_params
params.require(:address).permit(:last_name, :first_name, :last_name_kana, :first_name_kana, :postal_cord,
:prefecture_id, :city, :street_num, :building, :phone_num).merge(user_id: current_user.id)
end
end |
class TransferParticipantToUser
def initialize(participant:, user:, adapter: TwilioAdapter.new)
@participant = participant
@user = user
@adapter = adapter
end
def call
result = adapter.update_call(update_call_args)
if result
Result.success
else
Result.failure("Failed to update the call")
end
end
private
attr_reader :participant, :user, :adapter
def update_call_args
{
sid: participant.sid,
url: transfer_url,
}
end
def transfer_url
RouteHelper.transfer_participant_url(
to: user.phone_number,
from: participant.phone_number
)
end
end
|
class ConvertPreptimeToIntegerOnRecipes < ActiveRecord::Migration
def up
add_column :recipes, :baking, :integer, default: 0
add_column :recipes, :cooling, :integer, default: 0
add_column :recipes, :rest, :integer, default: 0
add_column :recipes, :cooking, :integer, default: 0
end
def down
remove_column :recipes, :baking
remove_column :recipes, :cooling
remove_column :recipes, :rest
remove_column :recipes, :cooking
end
end
|
FactoryGirl.define do
# DD: 'product' comes from Spree core, simple_product no longer exists
factory :subscribable_product, :parent => :product do
subscribable true
end
end
|
require 'spec_helper'
# FIXME: This is the worst spec I'v ever written. Magical and hackish, pls improve it.
describe DataMapper::Mongo::Adapter,'#connection' do
let(:object) { described_class.new(:default,options) }
subject { object.send :connection }
shared_examples_for 'a mongo connection setup' do
it 'should create the correct instance with additional options' do
expected_class.should_receive(:new).with(*(expected_arguments+[:logger => DataMapper.logger]))
subject
end
it 'should pass any extra option to mogo' do
options[:read]=:secondary
expected_class.should_receive(:new).with(*(expected_arguments+[:logger => DataMapper.logger,:read => :secondary]))
subject
end
end
context 'when seeds are not in options' do
let(:options) { { :host => 'example.net', :port => 27017 } }
let(:expected_class) { Mongo::Connection }
let(:expected_arguments) { ['example.net',27017] }
it_should_behave_like 'a mongo connection setup'
end
context 'when seeds are in options' do
let(:options) { { :seeds => [['a.example.net',27017],['b.example.net']] } }
let(:expected_class) { Mongo::ReplSetConnection }
let(:expected_arguments) { [['a.example.net',27017],['b.example.net',27017]] }
it_should_behave_like 'a mongo connection setup'
end
end
|
class CreateCreditCardServices
def initialize(params)
@params = params
@params[:last4] = resolve_last4
end
def create
credit_card = initial_credit_card
encrypt_fields(credit_card)
credit_card.save ? credit_card : credit_card.errors.full_messages
end
private
def resolve_last4
@params[:number].last(4) if @params[:number].present?
end
def initial_credit_card
credit_card = CreditCard.find_by(last4: @params[:last4])
credit_card.nil? ? CreditCard.new(@params) : credit_card
end
def encrypt_fields(credit_card)
credit_card.expiration_date = CryptServices.encrypt(@params[:expiration_date]) if @params[:expiration_date]
credit_card.number = CryptServices.encrypt(@params[:number]) if @params[:number]
credit_card.cvc = CryptServices.encrypt(@params[:cvc]) if @params[:cvc]
end
end |
class Gender < ActiveRecord::Base
has_and_belongs_to_many :targets
has_many :members
has_many :participant_surveys
default_scope order('position asc')
end
|
module Stylin
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path("../../templates", __FILE__)
desc "Installs Stylin ready for use."
def install
copy_file "stylin.yml", "config/stylin.yml"
empty_directory "app/styleguides"
route "mount Stylin::Engine => '/styleguides' if Rails.env.development?"
end
end
end
|
require "rails_helper"
RSpec.feature "Transactions", :type => :feature do
scenario "User borrows $500 on day one" do
user = User.create(first_name: 'Bill', last_name: 'Miller', email: 'bill.miller@example.com', password: 'password')
visit root_path(as: user)
click_link 'Withdraw'
fill_in 'Amount', with: '500.00'
click_button 'Create Transaction'
Timecop.travel(Date.today + 31.days) do
# In reality this would be a scheduled job. For simplicity I will
# just call this method manually
user.reload.close_period
end
expect(user.balance).to eq(Money.new(-51438))
end
scenario "User borrows $500 on day one, pays back $200 on day 15, and draws another $100 on day 25" do
user = User.create(first_name: 'Bill', last_name: 'Miller', email: 'bill.miller@example.com', password: 'password')
visit root_path(as: user)
click_link 'Withdraw'
fill_in 'Amount', with: '500.00'
click_button 'Create Transaction'
Timecop.travel(Date.today + 16.days) do
visit root_path(as: user)
click_link 'Pay'
fill_in 'Amount', with: '200.00'
click_button 'Create Transaction'
end
Timecop.travel(Date.today + 26.days) do
visit root_path(as: user)
click_link 'Withdraw'
fill_in 'Amount', with: '100.00'
click_button 'Create Transaction'
end
Timecop.travel(Date.today + 31.days) do
# In reality this would be a scheduled job. For simplicity I will
# just call this method manually
user.reload.close_period
end
expect(user.balance).to eq(Money.new(-41199))
end
end
|
class RemoveShopsFromUsers < ActiveRecord::Migration[5.1]
def change
remove_reference :users, :shop, foreign_key: true
end
end
|
require 'test_helper'
class BadgeTest < ActiveSupport::TestCase
self.use_instantiated_fixtures = true
fixtures :badges
def setup
@c = Client.find(:first)
@bi = BadgeImage.find(:first)
end
def test_create
b = Badge.new(:client_id => @c.id, :name => 'first time', :description => 'welcome, new user!', :badge_image_id => @bi.id)
assert !b.active
assert b.save
end
def test_empty_fields
b = Badge.new(:client_id => @c.id, :name => '', :description => '', :badge_image_id => @bi.id)
assert !b.save
end
def test_missing_fields
b = Badge.new(:client_id => nil, :name => 'first time', :description => 'welcome, new user!', :badge_image_id => @bi.id)
assert !b.save
b = Badge.new(:client_id => @c.id, :name => nil, :description => 'welcome, new user!', :badge_image_id => @bi.id)
assert !b.save
b = Badge.new(:client_id => @c.id, :name => 'first time', :description => nil, :badge_image_id => @bi.id)
assert !b.save
b = Badge.new(:client_id => @c.id, :name => 'first time', :description => 'welcome, new user!', :badge_image_id => nil)
assert !b.save
end
def test_field_lengths
b = Badge.new(:client_id => @c.id, :name => '0123456789012345678901234567890', :description => 'test', :badge_image_id => @bi.id)
assert !b.save
b = Badge.new(:client_id => @c.id, :name => 'test', :badge_image_id => @bi.id)
b.description = '012345678901234567890123456789012345678901234567890'
assert !b.save
end
def test_active
b = Badge.new(:client_id => @c.id, :name => 'test', :description => 'test', :badge_image_id => @bi.id)
b.active = false
assert b.save
end
end
|
require 'rails_helper'
class FactoryBot::Factory::Find
def association(runner)
runner.run
end
def result(evaluation)
query = get_overrides(evaluation)
result = build_class(evaluation).where(query).first
result
end
private
def build_class(evaluation)
evaluation.instance_variable_get(:@attribute_assigner).instance_variable_get(:@build_class)
end
def get_overrides(evaluation = nil)
return @overrides unless @overrides.nil?
evaluation.instance_variable_get(:@attribute_assigner).instance_variable_get(:@evaluator).instance_variable_get(:@overrides).clone
end
end
FactoryBot.register_strategy(:find, FactoryBot::Factory::Find)
|
require 'mongo'
require_relative '../../../lib/recommendations/model/preference'
require_relative '../../../lib/recommendations/model/preferences'
require_relative '../../../lib/caching/cacheable'
module Recommendations
module DataModel
class MongoDataModel
include Cacheable
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 27017
def initialize(conf)
@collection = Mongo::Connection.new(conf[:host] || DEFAULT_HOST, conf[:port] || DEFAULT_PORT).db(conf[:db])[conf[:collection]]
end
def preferences_for_user(user)
results = @collection.find({"user_id" => user})
extract_results_into_preferences(results)
end
def preference_for_user_and_item(user, item)
results = @collection.find({"user_id" => user, "item_id" => item})
extract_results_into_preferences(results)[0]
end
def items_for_users(users)
set = Set.new
users.each do |user|
preferences = preferences_for_user(user)
set.merge(preferences.map { |pref| pref.item })
end
set.to_a
end
def users(how_many=1000000)
@collection.distinct("user_id").first(how_many)
end
def preferences
results = @collection.find
extract_results_into_preferences(results)
end
def set_preference(user,item,value)
@collection.insert({user_id: user, item_id: item, preference: value})
end
private
def extract_results_into_preferences(results)
preferences = Recommendations::Model::Preferences.new
results.each do |row|
preferences << Recommendations::Model::Preference.new(row['user_id'], row['item_id'], row['preference'])
end
preferences
end
cacheable :users, :preferences, :items_for_users, :preference_for_user_and_item, :preferences_for_user
end
end
end |
require 'rails_helper'
RSpec.describe Discount, type: :model do
describe "relationships" do
it { should have_many :discount_items}
it { should have_many(:items).through(:discount_items)}
end
describe "instance methods" do
it ".apply_discount" do
@merchant_1 = Merchant.create!(name: 'Megans Marmalades', address: '123 Main St', city: 'Denver', state: 'CO', zip: 80218)
@merchant_2 = Merchant.create!(name: 'Brians Bagels', address: '125 Main St', city: 'Denver', state: 'CO', zip: 80218)
@m_user = @merchant_1.users.create(name: 'Megan', address: '123 Main St', city: 'Denver', state: 'CO', zip: 80218, email: 'megan@example.com', password: 'securepassword')
@ogre = @merchant_1.items.create!(name: 'Ogre', description: "I'm an Ogre!", price: 20.25, image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTaLM_vbg2Rh-mZ-B4t-RSU9AmSfEEq_SN9xPP_qrA2I6Ftq_D9Qw', active: true, inventory: 5 )
@order_2 = @m_user.orders.create!(status: "pending")
@order_item_3 = @order_2.order_items.create!(item: @ogre, price: @ogre.price, quantity: 5, fulfilled: false)
@discount_item_1 = @ogre.discounts.create!(minimum_amount: 5, discount_amount: 10)
expect(@order_2.grand_total).to eq(91.13)
end
it "only the largest discount will be used" do
@merchant_1 = Merchant.create!(name: 'Megans Marmalades', address: '123 Main St', city: 'Denver', state: 'CO', zip: 80218)
@merchant_2 = Merchant.create!(name: 'Brians Bagels', address: '125 Main St', city: 'Denver', state: 'CO', zip: 80218)
@m_user = @merchant_1.users.create(name: 'Megan', address: '123 Main St', city: 'Denver', state: 'CO', zip: 80218, email: 'megan@example.com', password: 'securepassword')
@ogre = @merchant_1.items.create!(name: 'Ogre', description: "I'm an Ogre!", price: 20.25, image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTaLM_vbg2Rh-mZ-B4t-RSU9AmSfEEq_SN9xPP_qrA2I6Ftq_D9Qw', active: true, inventory: 5 )
@order_2 = @m_user.orders.create!(status: "pending")
@order_item_3 = @order_2.order_items.create!(item: @ogre, price: @ogre.price, quantity: 10, fulfilled: false)
@discount_item_1 = @ogre.discounts.create!(minimum_amount: 5, discount_amount: 10)
@discount_item_2 = @ogre.discounts.create!(minimum_amount: 10, discount_amount: 15)
expect(@order_2.grand_total).to eq(172.13)
end
end
end
|
require 'spec_helper'
describe MoviesHelper do
context "#days" do
describe "When we want to show 5 days in to the future for movies" do
describe "When no date has been chosen" do
before(:each) do
@days = days(5.days.from_now.localtime.to_s, 'bondijunction')
@days_as_document = @days.map{|day| HTML::Document.new(day).root}
end
it "returns the days" do
assert_select(@days_as_document[0], 'a', text: "Today")
assert_select(@days_as_document[1], 'a', text: "Tomorrow")
assert_select(@days_as_document[2], 'a', text: 2.days.from_now.localtime.strftime("%a %-d %b"))
assert_select(@days_as_document[3], 'a', text: 3.days.from_now.localtime.strftime("%a %-d %b"))
assert_select(@days_as_document[4], 'a', text: 4.days.from_now.localtime.strftime("%a %-d %b"))
end
it "should link to the movies index page" do
5.times do |i|
assert_select(@days_as_document[i], 'a', attributes: {href: centre_movies_path('bondijunction', date: i.days.from_now.localtime.strftime('%d-%m-%Y'))})
end
end
it "should mark today as chosen by default" do
assert_select(@days_as_document[0], 'a', attributes: {class: 'selected'}, text: "Today")
assert_select(@days_as_document[1], 'a', attributes: {class: ''}, text: "Tomorrow")
end
end
describe "When a date has been chosen" do
before(:each) do
@days = days(5.days.from_now.to_s, 'bondijunction', 1.days.from_now.localtime.strftime("%A %-d"))
@days_as_document = @days.map{|day| HTML::Document.new(day).root}
end
it "should mark the chosen day as selected" do
assert_select(@days_as_document[0], 'a', attributes: {class: ''}, text: "Today")
assert_select(@days_as_document[1], 'a', attributes: {class: 'selected'}, text: "Tomorrow")
end
end
end
end
end
|
require "capybara/poltergeist/errors"
require "capybara/poltergeist/command"
require 'json'
require 'time'
module Capybara::Poltergeist
class Browser
ERROR_MAPPINGS = {
'Poltergeist.JavascriptError' => JavascriptError,
'Poltergeist.FrameNotFound' => FrameNotFound,
'Poltergeist.InvalidSelector' => InvalidSelector,
'Poltergeist.StatusFailError' => StatusFailError,
'Poltergeist.NoSuchWindowError' => NoSuchWindowError,
'Poltergeist.UnsupportedFeature' => UnsupportedFeature,
'Poltergeist.KeyError' => KeyError,
}
attr_reader :server, :client, :logger
def initialize(server, client, logger = nil)
@server = server
@client = client
@logger = logger
end
def restart
server.restart
client.restart
self.debug = @debug if defined?(@debug)
self.js_errors = @js_errors if defined?(@js_errors)
self.extensions = @extensions if @extensions
end
def visit(url)
command 'visit', url
end
def current_url
command 'current_url'
end
def status_code
command 'status_code'
end
def body
command 'body'
end
def source
command 'source'
end
def title
command 'title'
end
def parents(page_id, id)
command 'parents', page_id, id
end
def find(method, selector)
result = command('find', method, selector)
result['ids'].map { |id| [result['page_id'], id] }
end
def find_within(page_id, id, method, selector)
command 'find_within', page_id, id, method, selector
end
def all_text(page_id, id)
command 'all_text', page_id, id
end
def visible_text(page_id, id)
command 'visible_text', page_id, id
end
def delete_text(page_id, id)
command 'delete_text', page_id, id
end
def property(page_id, id, name)
command 'property', page_id, id, name.to_s
end
def attributes(page_id, id)
command 'attributes', page_id, id
end
def attribute(page_id, id, name)
command 'attribute', page_id, id, name.to_s
end
def value(page_id, id)
command 'value', page_id, id
end
def set(page_id, id, value)
command 'set', page_id, id, value
end
def select_file(page_id, id, value)
command 'select_file', page_id, id, value
end
def tag_name(page_id, id)
command('tag_name', page_id, id).downcase
end
def visible?(page_id, id)
command 'visible', page_id, id
end
def disabled?(page_id, id)
command 'disabled', page_id, id
end
def click_coordinates(x, y)
command 'click_coordinates', x, y
end
def evaluate(script, *args)
command 'evaluate', script, *args
end
def execute(script, *args)
command 'execute', script, *args
end
def within_frame(handle, &block)
if handle.is_a?(Capybara::Node::Base)
command 'push_frame', [handle.native.page_id, handle.native.id]
else
command 'push_frame', handle
end
yield
ensure
command 'pop_frame'
end
def switch_to_frame(handle, &block)
case handle
when Capybara::Node::Base
command 'push_frame', [handle.native.page_id, handle.native.id]
when :parent
command 'pop_frame'
when :top
command 'pop_frame', true
end
end
def window_handle
command 'window_handle'
end
def window_handles
command 'window_handles'
end
def switch_to_window(handle)
command 'switch_to_window', handle
end
def open_new_window
command 'open_new_window'
end
def close_window(handle)
command 'close_window', handle
end
def find_window_handle(locator)
return locator if window_handles.include? locator
handle = command 'window_handle', locator
raise NoSuchWindowError unless handle
return handle
end
def within_window(locator, &block)
original = window_handle
handle = find_window_handle(locator)
switch_to_window(handle)
yield
ensure
switch_to_window(original)
end
def click(page_id, id)
command 'click', page_id, id
end
def right_click(page_id, id)
command 'right_click', page_id, id
end
def double_click(page_id, id)
command 'double_click', page_id, id
end
def hover(page_id, id)
command 'hover', page_id, id
end
def drag(page_id, id, other_id)
command 'drag', page_id, id, other_id
end
def drag_by(page_id, id, x, y)
command 'drag_by', page_id, id, x, y
end
def select(page_id, id, value)
command 'select', page_id, id, value
end
def trigger(page_id, id, event)
command 'trigger', page_id, id, event.to_s
end
def reset
command 'reset'
end
def scroll_to(left, top)
command 'scroll_to', left, top
end
def render(path, options = {})
check_render_options!(options)
options[:full] = !!options[:full]
command 'render', path.to_s, options
end
def render_base64(format, options = {})
check_render_options!(options)
options[:full] = !!options[:full]
command 'render_base64', format.to_s, options
end
def set_zoom_factor(zoom_factor)
command 'set_zoom_factor', zoom_factor
end
def set_paper_size(size)
command 'set_paper_size', size
end
def resize(width, height)
command 'resize', width, height
end
def send_keys(page_id, id, keys)
command 'send_keys', page_id, id, normalize_keys(keys)
end
def path(page_id, id)
command 'path', page_id, id
end
def network_traffic(type = nil)
command('network_traffic', type).map do |event|
NetworkTraffic::Request.new(
event['request'],
event['responseParts'].map { |response| NetworkTraffic::Response.new(response) },
event['error'] ? NetworkTraffic::Error.new(event['error']) : nil
)
end
end
def clear_network_traffic
command('clear_network_traffic')
end
def set_proxy(ip, port, type, user, password)
args = [ip, port, type]
args << user if user
args << password if password
command('set_proxy', *args)
end
def equals(page_id, id, other_id)
command('equals', page_id, id, other_id)
end
def get_headers
command 'get_headers'
end
def set_headers(headers)
command 'set_headers', headers
end
def add_headers(headers)
command 'add_headers', headers
end
def add_header(header, options={})
command 'add_header', header, options
end
def response_headers
command 'response_headers'
end
def cookies
Hash[command('cookies').map { |cookie| [cookie['name'], Cookie.new(cookie)] }]
end
def set_cookie(cookie)
if cookie[:expires]
cookie[:expires] = cookie[:expires].to_i * 1000
end
command 'set_cookie', cookie
end
def remove_cookie(name)
command 'remove_cookie', name
end
def clear_cookies
command 'clear_cookies'
end
def cookies_enabled=(flag)
command 'cookies_enabled', !!flag
end
def set_http_auth(user, password)
command 'set_http_auth', user, password
end
def js_errors=(val)
@js_errors = val
command 'set_js_errors', !!val
end
def extensions=(names)
@extensions = names
Array(names).each do |name|
command 'add_extension', name
end
end
def url_whitelist=(whitelist)
command 'set_url_whitelist', *whitelist
end
def url_blacklist=(blacklist)
command 'set_url_blacklist', *blacklist
end
def debug=(val)
@debug = val
command 'set_debug', !!val
end
def clear_memory_cache
command 'clear_memory_cache'
end
def command(name, *args)
cmd = Command.new(name, *args)
log cmd.message
response = server.send(cmd)
log response
json = JSON.load(response)
if json['error']
klass = ERROR_MAPPINGS[json['error']['name']] || BrowserError
raise klass.new(json['error'])
else
json['response']
end
rescue DeadClient
restart
raise
end
def go_back
command 'go_back'
end
def go_forward
command 'go_forward'
end
def refresh
command 'refresh'
end
def accept_confirm
command 'set_confirm_process', true
end
def dismiss_confirm
command 'set_confirm_process', false
end
#
# press "OK" with text (response) or default value
#
def accept_prompt(response)
command 'set_prompt_response', response || false
end
#
# press "Cancel"
#
def dismiss_prompt
command 'set_prompt_response', nil
end
def modal_message
command 'modal_message'
end
private
def log(message)
logger.puts message if logger
end
def check_render_options!(options)
if !!options[:full] && options.has_key?(:selector)
warn "Ignoring :selector in #render since :full => true was given at #{caller.first}"
options.delete(:selector)
end
end
KEY_ALIASES = {
command: :Meta,
equals: :Equal,
Control: :Ctrl,
control: :Ctrl,
multiply: 'numpad*',
add: 'numpad+',
divide: 'numpad/',
subtract: 'numpad-',
decimal: 'numpad.'
}
def normalize_keys(keys)
keys.map do |key_desc|
case key_desc
when Array
# [:Shift, "s"] => { modifier: "shift", keys: "S" }
# [:Shift, "string"] => { modifier: "shift", keys: "STRING" }
# [:Ctrl, :Left] => { modifier: "ctrl", key: 'Left' }
# [:Ctrl, :Shift, :Left] => { modifier: "ctrl,shift", key: 'Left' }
# [:Ctrl, :Left, :Left] => { modifier: "ctrl", key: [:Left, :Left] }
_keys = key_desc.chunk {|k| k.is_a?(Symbol) && %w(shift ctrl control alt meta command).include?(k.to_s.downcase) }
modifiers = if _keys.peek[0]
_keys.next[1].map do |k|
k = k.to_s.downcase
k = 'ctrl' if k == 'control'
k = 'meta' if k == 'command'
k
end.join(',')
else
''
end
letters = normalize_keys(_keys.next[1].map {|k| k.is_a?(String) ? k.upcase : k })
{ modifier: modifiers, keys: letters }
when Symbol
# Return a known sequence for PhantomJS
key = KEY_ALIASES.fetch(key_desc, key_desc)
if match = key.to_s.match(/numpad(.)/)
res = { keys: match[1], modifier: 'keypad' }
elsif key !~ /^[A-Z]/
key = key.to_s.split('_').map{ |e| e.capitalize }.join
end
res || { key: key }
when String
key_desc # Plain string, nothing to do
end
end
end
end
end
|
class RemoveEmailAndPasswordDigestInLeadsModel < ActiveRecord::Migration
def up
remove_column :leads, :email
remove_column :leads, :password_digest
end
def down
add_column :leads, :email, :string
add_column :leads, :password_digest, :string
end
end
|
# Encoding: utf-8
require 'spec_helper'
describe 'kibana' do
describe file('/opt/kibana') do
it { should be_directory }
end
end
|
require 'rails_helper'
describe Card do
describe '#create' do
it "項目がすべて存在すれば登録できること" do
user = create(:user)
card = build(:card)
expect(card).to be_valid
end
it "user_idがない場合は登録出来ないこと" do
card = build(:card, user_id: nil)
card.valid?
expect(card.errors[:user]).to include("を入力してください")
end
it "card_idがない場合は登録できないこと" do
card = build(:card, card_id: nil)
card.valid?
expect(card.errors[:card_id]).to include("を入力してください")
end
it "customer_idがない場合は登録できないこと" do
card = build(:card, customer_id: nil)
card.valid?
expect(card.errors[:customer_id]).to include("を入力してください")
end
end
end
|
class RecordRingGroupVoicemailGreetingMutation < Types::BaseMutation
description "Saves the provided audio as the voicemail greeting message for the ring group"
argument :ring_group_id, ID, required: true
argument :audio,
Types::ActiveStorageSignedIdType,
description: "The signed id of the audio file",
required: true
field :ring_group, Outputs::RingGroupType, null: true
field :errors, resolver: Resolvers::Error
policy RingGroupPolicy, :manage?
def resolve
ring_group = RingGroup.find(input.ring_group_id)
authorize ring_group
if ring_group.update(voicemail_greeting: input.audio)
{ring_group: ring_group, errors: []}
else
{ring_group: nil, errors: ring_group.errors}
end
end
end
|
#encoding: utf-8
module Orthography
REPLACES=[['Амортиз стойка', 'Амортизаторная стойка'],
['Амморт', 'Амортизатор'],
['АммортS ', 'Амортизатор '],
['Амортиз ', 'Амортизатор '],
['Башмак натажителя', 'Башмак натяжителя'],
['Болт-секр.', 'Болт секретка'],
['Гидрокрректор', 'Гидрокорректор'],
['Датчик полож дросс заслонки', 'Датчик положения дроссельной заслонки'],
['Датчик темп охл.жидкости', 'Датчик температуры охлаждающей жидкости'],
['Датчик темп.воздуха салона', 'Датчик температуры воздуха салона'],
['Датчик темпер. охл. жидкости', 'Датчик температуры охлаждающей жидкости'],
['Датчик температуры окр. воздуха', 'Датчик температуры окружающего воздуха'],
['Датчик фаз р/вала', 'Датчик фаз распредвала'],
['Диск сц', 'Диск сцепления'],
['Карб.', 'Карбюратор'],
['Карб ', 'Карбюратор '],
['Клапан обр топл', 'Клапан обратный топливный'],
['Кнопка п/тум фар', 'Кнопка противотуманных фар'],
['Кол/торм зад', 'Колодки тормозные задние'],
['Кол/торм пер', 'Колодки тормозные передние'],
['Кол/торм ', 'Колодки тормозные '],
['Компл. тяг рул. трапеции','Комплект тяг рулевой трапеции'],
['Комплект б/конт зажигания','Комплект бесконтактного зажигания'],
['Комплект для подкл.п/тум фар','Комплект для подключения противотуманных фар'],
['Крышка б/бака','Крышка бензобака'],
['Крышка распред зажигания','Крышка распределителя зажигания'],
['Моторедуктор Стеклоочистит.','Моторедуктор стеклоочистителя'],
['МотоРедуктор Стеклоподъемн','Моторедуктор стеклоподъемника'],
['МотоРедуктор','Моторедуктор'],
['Наконеч /рул','Рулевой наконечник'],
['Наконеч/рул','Рулевой наконечник'],
['Опора кард вала','Опора карданного вала'],
['ПВН силик.','Провода высокого напряжения силиконовые'],
['ПВН','Провода высокого напряжения'],
['Переключ-клавиша','Переключатель-клавиша'],
['Переключ ','Переключатель '],
['Подшипник выжим.','Подшипник выжимной'],
['Подшипник з/мост','Подшипник задний мост'],
['Подшипник к/вала','Подшипник коленвала'],
['Полукольцо к/вала','Полукольцо коленвала'],
['Проставка б/насоса','Проставка бензонасоса'],
['Пружина задн.','Пружина задняя'],
['Пружина пер','Пружина передняя'],
['Рем. комплект', 'Ремкомплект'],
['Рем. к-т','Ремкомплект'],
['Р/комп. ','Ремкомплект'],
['Р/К-т','Ремкомплект'],
['Р/К','Ремкомплект'],
['Р/к','Ремкомплект'],
['Рем ген.','Ремень генератора'],
['Рем ген','Ремень генератора'],
['Рем ГРМ','Ремень ГРМ'],
['С/блок','Сайлентблок'],
['Сальник удленнителя','Сальник удлиннителя'],
['Трапеция ст/очистителя','Трапеция стеклоочистителя'],
['Усилитель вак. торм','Вакуумный усилитель тормозов'],
['Фара прот/тум','Фара противотуманная'],
['Фонарь осв.номерного знака','Фонарь освещения номерного знака'],
['Шкив к/вала','Шкив коленвала'],
['Шланг тормозной задн','Шланг тормозной задний'],
['Шланг тормозной пер.','Шланг тормозной передний'],
['Эл.двигатель','Электродвигатель'],
['Цилиндр тормозной пер/левый','Цилиндр тормозной передний левый'],
['Цилиндр тормозной пер/правый','Цилиндр тормозной передний правый'],
['Цилиндр торм/гл','Цилиндр тормозной главный'],
['Цилиндр торм/ гл.','Цилиндр тормозной главный'],
['Цилиндр торм/главный', 'Цилиндр тормозной главный'],
['Цилиндр торм/задний','Цилиндр тормозной задний'],
['Цилиндр торм/перед лев.','Цилиндр тормозной передний левый'],
['Цилиндр торм/перед лев','Цилиндр тормозной передний левый '],
['Цилиндр торм/перед. лев','Цилиндр тормозной передний левый '],
['Цилиндр торм/перед прав.','Цилиндр тормозной передний правый'],
['Цилиндр торм/перед прав','Цилиндр тормозной передний правый '],
['Цилиндр торм/','Цилиндр тормозной '],
['Патр пер. стойки','Патрон передней стойки'],
['Радиатор отопит.','Радиатор отопителя']]
end |
#encoding: utf-8
class Member < ActiveRecord::Base
PAYMENT_PERIODS = [ :yearly, :monthly]
PAYMENT_METHODS = [ :direct_debit, :bank_transfer]
has_many :children, dependent: :destroy
has_one :bank_account, dependent: :destroy
has_many :membership_fees, dependent: :destroy
attr_accessible :beitrag, :email, :first_name, :last_name, :phone, :postcode, :street, :town,
:eintrittsdatum, :austrittsdatum, :payment_period, :payment_method
validates :beitrag, :first_name, :last_name, :postcode, :street, :town, :payment_period, presence: true
validates :beitrag, numericality: {greater_than: 0}
validates :postcode, numericality: {greater_than: 0}, numericality: {less_than: 100000}
validates :postcode, :length => { :is => 5 }
def full_name
last_name + "," + first_name
end
def self.payments
Array payment_methods = [nil] + PAYMENT_METHODS.map { |p| [I18n.t(p), p] }
end
def payment_for_current_year
MembershipFee.where(member_id: id, school_year_id: SchoolYear.current_school_year.id)
end
def self.to_csv(options = {:col_sep => ";", :force_quotes => true})
current_date = DateTime.now.strftime("%Y/%m/%d")
CSV.generate(options) do |csv|
csv << %w(localBankCode localAccountNumber localName \
remoteBankCode remoteAccountNumber remoteName \
valutaDate date value_value value_currency \
transactionKey transactionCode transactionText purpose purpose1)
all.each do |member|
if member.bank_account.nil?
bank_code = "Kein Konto"
account_number = "Kein Konto"
else
bank_code = member.bank_account.bank_code
account_number = member.bank_account.account_number
end
csv << ["20050550", "1259125449", "Grundschule, Schulverein d" \
, bank_code, account_number, member.full_name \
, current_date, current_date, member.beitrag.truncate, "EUR" \
, "MSC", "05", "Lastschrift", "Jahresbeitrag Schulverein 2012/2013", "Vielen Dank!"]
end
end
end
def self.to_dtaus
# Konto des Auftraggebers
konto_auftraggeber = DTAUS::Konto.new(
:kontonummer => 1259125449,
:blz => 20050550,
:kontoinhaber => 'Schulverein Doehrnstr',
:bankname =>'HASPA',
:is_auftraggeber => true
)
# LASTSCHRIFT
# Erstellen eines Datensatzes für eine Lastschrift
lastschrift = DTAUS::Datensatz.new(:lastschrift, konto_auftraggeber)
# Rails.logger = Logger.new("/Users/afuerstenau/Projects/mars/log/mylog.log")
all.each do |member|
unless member.bank_account.nil?
kontoinhaber = member.full_name
kontoinhaber = member.bank_account.account_holder if member.bank_account.account_holder != "s.o."
konto_kunde = DTAUS::Konto.new(
:kontonummer => member.bank_account.account_number,
:blz => member.bank_account.bank_code,
:kontoinhaber => kontoinhaber,
:bankname => member.bank_account.bank_name,
:kundennummer => member.id
)
# Lastschrift-Buchung für den Kunden
buchung = DTAUS::Buchung.new(
:kunden_konto => konto_kunde,
:betrag => member.beitrag,
:transaktionstyp => :lastschrift,
:verwendungszweck => "Jahresbeitrag Schulverein Döhrnstr. 2012 / 2013. Vielen Dank!"
)
lastschrift.add(buchung)
end
end
return lastschrift
end
def self.find_all_tardy_members
members_have_payed = joins(:membership_fees).merge( MembershipFee.current_school_year )
Member.where("id NOT IN (?)", members_have_payed)
end
end
|
# encoding: utf-8
# copyright: 2016, you
# license: All rights reserved
# date: 2016-09-16
# description: The Microsoft Internet Explorer 11 Security Technical Implementation Guide (STIG) is published as a tool to improve the security of Department of Defense (DoD) information systems. Comments or proposed revisions to this document should be sent via e-mail to the following address: disa.stig_spt@mail.mil
# impacts
title 'V-46907 - .NET Framework-reliant components not signed with Authenticode must be disallowed to run (Internet zone).'
control 'V-46907' do
impact 0.5
title '.NET Framework-reliant components not signed with Authenticode must be disallowed to run (Internet zone).'
desc 'Unsigned components are more likely to contain malicious code and it is more difficult to determine the author of the application - therefore they should be avoided if possible. This policy setting allows you to manage whether .NET Framework components that are not signed with Authenticode can be executed from Internet Explorer. These components include managed controls referenced from an object tag and managed executables referenced from a link. If you enable this policy setting, Internet Explorer will execute unsigned managed components. If you select "Prompt" in the drop-down box, Internet Explorer will prompt the user to determine whether to execute unsigned managed components. If you disable this policy setting, Internet Explorer will not execute unsigned managed components. If you do not configure this policy setting, Internet Explorer will not execute unsigned managed components.'
tag 'stig', 'V-46907'
tag severity: 'medium'
tag checkid: 'C-49957r2_chk'
tag fixid: 'F-50643r1_fix'
tag version: 'DTBI920-IE11'
tag ruleid: 'SV-59773r1_rule'
tag fixtext: 'Set the policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer -> Internet Control Panel -> Security Page -> Internet Zone Run .NET Framework-reliant components not signed with Authenticode to Enabled, and select Disable from the drop-down box. '
tag checktext: 'The policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer -> Internet Control Panel -> Security Page -> Internet Zone Run .NET Framework-reliant components not signed with Authenticode must be Enabled, and Disable selected from the drop-down box. Procedure: Use the Windows Registry Editor to navigate to the following key: HKLM\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3 Criteria: If the value "2004" is REG_DWORD = 3, this is not a finding.'
# START_DESCRIBE V-46907
describe registry_key({
hive: 'HKLM',
key: 'Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3',
}) do
its('2004') { should eq 3 }
end
# STOP_DESCRIBE V-46907
end
|
class AddUniqueIndexToTextFiles < ActiveRecord::Migration
def change
add_index :text_files, :URL, :unique => true
end
end
|
class House < Sequel::Model(DB)
class List < Trailblazer::Operation
extend Contract::DSL
step Contract::Build()
step Contract::Validate()
step :list_by_user_id
failure :log_failure
contract do
property :user_id, virtual: true
validation do
required(:user_id).filled
end
end
def list_by_user_id(options, params:, **)
options['models'] = House.where(user_id: params[:user_id]).all
options['models']
end
def log_success(options, params:, model:, **)
LOGGER.info "[#{self.class}] Found houses for user #{params.to_json}. Houses: #{House::Representer.new(options['model']).to_json}"
end
def log_failure(options, params:, **)
LOGGER.info "[#{self.class}] Failed to find houses with params #{params.to_json}"
end
end
end |
# frozen_string_literal: true
class Addition < ApplicationRecord
has_attached_file :data
validates_attachment_content_type :data, content_type: 'text/plain'
validates_attachment_presence :data
end
|
# A controller which performs task related logic.
class TasksController < ApplicationController
# Loads the task specified by the id given in the url before update and destroy action is performed.
before_action :load_task, only: %i[update destroy]
# Returns all the tasks created by the user as an array of custom hashes in JSON to the client
# for front-end's need. For the detailed content of the hash, refer the documentation of the Tasks component
# under the javascript folder.
def index
@tasks = Task.all
response = @tasks.map{|task| get_task_hash(task)}
render json: response
end
# Creates a new task in the database using the specified url params and returns the task object as custom hash
# to the client if the action is successful. Otherwise, returns the error messages to the client.
def create
@task = Task.new(task_param)
if @task.save
render json: get_task_hash(@task)
else
render json: @task.errors.full_messages
end
end
# Updates the specified task in the database and returns the updated task object as custom hash
# to the client if the action is successful. Otherwise, returns the error messages to the client.
def update
if @task.update(task_param)
render json: get_task_hash(@task)
else
render json: @task.errors.full_messages
end
end
# Deletes the specified task in the database.
def destroy
@task.destroy
end
private
# Loads the task specified in the url from the database into the task attribute of the tasks controller.
def load_task
@task = Task.find(params[:id])
end
# Returns a custom hash representing the given task object. The attributes of the hash is the same as that of
# a task object except the hash contains a "tags" attribute which is an array of tags assigned to the task.
def get_task_hash(task)
hash = task.attributes
hash["tags"] = task.categories.to_ary.map{|category|
attributes = category.attributes
attributes["label"] = attributes.delete "name"
attributes
}
hash
end
# Checks if task param is present in the url params, then whitelist the properties of the task param.
def task_param
params.require(:task).permit(:title, :description, category_ids: [])
end
end
|
require 'krypt'
class MyProvider
def new_service(clazz, *args)
if clazz == Krypt::Digest && args[0] == "identity"
IdentityDigest.new
else
nil
end
end
def name
"MyProvider"
end
def finalize
end
end
class IdentityDigest
def initialize
reset
end
def reset
@buf = ""
end
def update(data)
@buf << data
end
alias << update
def digest(data=nil)
return data if data
digest_finalize
end
def hexdigest(data=nil)
Krypt::Hex.encode(digest(data))
end
def digest_length
-1
end
def block_length
-1
end
def name
identity
end
private
def digest_finalize
@buf
end
end
data = "letest"
Krypt::Provider.register(MyProvider.new)
id = Krypt::Provider.new_service(Krypt::Digest, 'identity')
puts id.digest(data)
sha = Krypt::Provider.new_service(Krypt::Digest, 'sha1')
p sha.digest(data)
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
respond_to :html, :json
rescue_from Contentful::BadRequest, :with => :not_found
def not_found(exception)
respond_to do |format|
format.json { render json: { status: "error", message: exception.message }, status: :not_found }
format.html { render file: "#{Rails.root}/public/404.html", layout: false, status: :not_found }
end
end
end
|
require 'spec_helper'
RSpec.describe 'Game' do
let(:response) { JSON.parse(last_response.body) }
before do
header 'CONTENT_TYPE', 'application/json'
post '/game', { player1: 'foo', player2: 'bar' }.to_json
end
describe 'POST /game' do
context 'when I create a game' do
it { expect(last_response.status).to eq 201 }
it { expect(response['current_player']).to eq 'player1' }
it 'should return the marks' do
expect(response['player1']['mark']).to eq('X')
expect(response['player2']['mark']).to eq('O')
end
it 'should return player names' do
expect(response['player1']['name']).to eq('foo')
expect(response['player2']['name']).to eq('bar')
end
end
end
describe 'POST /game/pick' do
context 'when player 1 makes a possible choice' do
before do
post '/game/pick', { current_player: 'player1', x: 0, y: 0 }.to_json
end
it 'should return the game state' do
expect(last_response.status).to eq 200
expect(response['current_state'][0][0]).to eq('X')
expect(response['current_player']).to eq('player2')
end
end
context 'when player 2 makes a possible choice' do
before do
post '/game/pick', { current_player: 'player1', x: 0, y: 0 }.to_json
post '/game/pick', { current_player: 'player2', x: 0, y: 1 }.to_json
end
it 'should return the game state' do
expect(last_response.status).to eq 200
expect(response['current_state'][0][0]).to eq('X')
expect(response['current_state'][0][1]).to eq('O')
expect(response['current_player']).to eq('player1')
end
end
context 'when player 2 tries to play on coordinate already taken' do
before do
post '/game/pick', { current_player: 'player1', x: 0, y: 0 }.to_json
post '/game/pick', { current_player: 'player2', x: 0, y: 0 }.to_json
end
it { expect(last_response.status).to eq 422 }
end
context 'when player 2 tries to play on invalid coordinate' do
before do
post '/game/pick', { current_player: 'player1', x: 0, y: 0 }.to_json
post '/game/pick', { current_player: 'player2', x: 6, y: 7 }.to_json
end
it { expect(last_response.status).to eq 422 }
end
context 'when player 1 tries to play twice' do
before do
post '/game/pick', { current_player: 'player1', x: 0, y: 0 }.to_json
post '/game/pick', { current_player: 'player1', x: 0, y: 1 }.to_json
end
it { expect(last_response.status).to eq 422 }
end
context 'when player 1 wins in column 0' do
before do
post '/game/pick', { current_player: 'player1', x: 0, y: 0 }.to_json
post '/game/pick', { current_player: 'player2', x: 0, y: 1 }.to_json
post '/game/pick', { current_player: 'player1', x: 1, y: 0 }.to_json
post '/game/pick', { current_player: 'player2', x: 0, y: 2 }.to_json
post '/game/pick', { current_player: 'player1', x: 2, y: 0 }.to_json
end
it { expect(last_response.status).to eq 200 }
it { expect(response['winner']).to eq('foo') }
end
context 'when player 1 wins in row 0' do
before do
post '/game/pick', { current_player: 'player1', x: 0, y: 0 }.to_json
post '/game/pick', { current_player: 'player2', x: 1, y: 1 }.to_json
post '/game/pick', { current_player: 'player1', x: 0, y: 1 }.to_json
post '/game/pick', { current_player: 'player2', x: 2, y: 2 }.to_json
post '/game/pick', { current_player: 'player1', x: 0, y: 2 }.to_json
end
it { expect(last_response.status).to eq 200 }
it { expect(response['winner']).to eq('foo') }
end
context 'when player 2 wins in diagonal' do
before do
post '/game/pick', { current_player: 'player1', x: 0, y: 1 }.to_json
post '/game/pick', { current_player: 'player2', x: 0, y: 0 }.to_json
post '/game/pick', { current_player: 'player1', x: 0, y: 2 }.to_json
post '/game/pick', { current_player: 'player2', x: 1, y: 1 }.to_json
post '/game/pick', { current_player: 'player1', x: 1, y: 2 }.to_json
post '/game/pick', { current_player: 'player2', x: 2, y: 2 }.to_json
end
it { expect(last_response.status).to eq 200 }
it { expect(response['winner']).to eq('bar') }
it { expect(response['current_state']).to be_a(Array) }
end
end
end
|
require 'rails_helper'
describe "Api::V1::Posts", type: :request do
let(:title) { 'this is a title' }
let(:content) { 'article content' }
let(:description) { 'this is a cool description' }
let(:image) { nil }
let(:attrs) do
{
title: title,
content: content,
description: description,
image: image
}
end
describe "GET /index" do
it "returns http success" do
VCR.use_cassette('gnews_success_query2') do
get "/api/v1/posts/index"
expect(response).to have_http_status(:success)
end
end
end
describe "POST /create" do
let(:image) { fixture_file_upload(Rails.root.join('spec', 'fixtures', 'images', '1.jpg'), 'image/jpg') }
it "returns http success" do
expect {
post "/api/v1/posts/create", params: attrs
}.to change(ActiveStorage::Attachment, :count).by(1)
expect(response).to have_http_status(:success)
end
end
describe "PUT /update" do
let(:post) { Post.create(attrs) }
let(:image) { fixture_file_upload(Rails.root.join('spec', 'fixtures', 'images', '2.jpg'), 'image/jpg') }
it "returns http success" do
expect {
put"/api/v1/posts/update/#{post.slug}", params: attrs
}.to change(ActiveStorage::Attachment, :count).by(1)
expect(response).to have_http_status(:success)
end
end
describe "GET /show (local post)" do
let(:post) { Post.create(attrs) }
it "returns http success" do
VCR.use_cassette('gnews_success_query2') do
get "/api/v1/posts/show/#{post.slug}"
expect(response).to have_http_status(:success)
end
end
end
describe "GET /show (remote post)" do
let(:slug) { 'gymnast-nastia-liukin-watches-her-hair-grow-in-rainfall-shower' }
it "returns http success" do
VCR.use_cassette('gnews_success_query2') do
get "/api/v1/posts/show/#{slug}"
expect(response).to have_http_status(:success)
end
end
end
describe "DELETE /destroy" do
let(:post) { Post.create(attrs) }
it "returns http success" do
delete "/api/v1/posts/destroy/#{post.slug}"
expect(response).to have_http_status(:success)
end
end
end
|
class VirtualAssistantsController < ApplicationController
# GET /virtual_assistants
# GET /virtual_assistants.json
def index
@virtual_assistants = VirtualAssistant.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @virtual_assistants }
end
end
# GET /virtual_assistants/1
# GET /virtual_assistants/1.json
def show
@virtual_assistant = VirtualAssistant.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @virtual_assistant }
end
end
# GET /virtual_assistants/new
# GET /virtual_assistants/new.json
def new
@virtual_assistant = VirtualAssistant.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @virtual_assistant }
end
end
# GET /virtual_assistants/1/edit
def edit
@virtual_assistant = VirtualAssistant.find(params[:id])
end
# POST /virtual_assistants
# POST /virtual_assistants.json
def create
@virtual_assistant = VirtualAssistant.new(params[:virtual_assistant])
respond_to do |format|
if @virtual_assistant.save
format.html { redirect_to @virtual_assistant, notice: 'Virtual assistant was successfully created.' }
format.json { render json: @virtual_assistant, status: :created, location: @virtual_assistant }
else
format.html { render action: "new" }
format.json { render json: @virtual_assistant.errors, status: :unprocessable_entity }
end
end
end
# PUT /virtual_assistants/1
# PUT /virtual_assistants/1.json
def update
@virtual_assistant = VirtualAssistant.find(params[:id])
respond_to do |format|
if @virtual_assistant.update_attributes(params[:virtual_assistant])
format.html { redirect_to @virtual_assistant, notice: 'Virtual assistant was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @virtual_assistant.errors, status: :unprocessable_entity }
end
end
end
# DELETE /virtual_assistants/1
# DELETE /virtual_assistants/1.json
def destroy
@virtual_assistant = VirtualAssistant.find(params[:id])
@virtual_assistant.destroy
respond_to do |format|
format.html { redirect_to virtual_assistants_url }
format.json { head :no_content }
end
end
end
|
class Video
attr_accessor :title, :duration, :genre, :rating
@@all = []
def initialize(title, duration, genre, rating)
@title = title
@duration = duration
@genre = genre
@rating = rating
end
def save
self.class.all << self
end
def self.all
@@all
end
def self.create(title, duration, genre, rating)
video = self.new(title, duration, genre, rating)
video.save
video
end
end |
class AddSeasonToDivisions < ActiveRecord::Migration[5.2]
def change
add_reference :divisions, :season, foreign_key: true
end
end
|
# encoding: UTF-8
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'appium_lib'
require 'rspec'
APP_PATH = '../build/iPhoneSimulator-7.1-Development/AppiumDemo.app'
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = [:should, :expect]
end
end
def desired_caps
{
'platformName' => 'iOS',
'deviceName' => 'iPhone Retina (4-inch)', # 'iPhone Simulator 4-inch',
'platformVersion' => '7.1',
'app' => absolute_app_path
}
end
def absolute_app_path
f = File.join(File.dirname(__FILE__), APP_PATH)
puts f
f
end
def server_url
"http://127.0.0.1:4723/wd/hub"
end
describe "AppiumDemo" do
before(:all) do
Appium::Driver.new(appium_lib: { server_url: server_url }, caps: desired_caps).start_driver
Appium.promote_appium_methods RSpec::Core::ExampleGroup
end
after(:each) do
back
end
after(:all) do
driver_quit
end
it "should be able to pick a date" do
find_element(:accessibility_id, 'Date').click
wheel_els = find_elements(:class_name, 'UIAPickerWheel')
wheel_els[0].send_keys 'March'
wheel_els[1].send_keys '1'
wheel_els[2].send_keys '2013'
wheel_els[0].value.should eq 'March'
wheel_els[1].value.should eq '1'
wheel_els[2].value.should eq '2013'
end
end
|
require_relative 'word_guess'
describe WordGuess do
let(:secret) {WordGuess.new("hello")}
it "converts number of words to '-'" do
expect(secret.word_convert).to eq "-----"
end
it "replaces '-' with correct letter" do
secret.word_convert
expect(secret.guess("h")).to eq "h----"
end
end |
require 'active_support/concern'
module RelationshipBulk
extend ActiveSupport::Concern
module ClassMethods
def bulk_update(ids, updates, team)
if updates[:action] == 'accept'
source_id = updates[:source_id]
pm_source = ProjectMedia.find_by_id(source_id)
# SQL bulk-update
updated_at = Time.now
update_columns = {
relationship_type: Relationship.confirmed_type,
updated_at: updated_at,
}
if User.current
update_columns[:confirmed_at] = updated_at
update_columns[:confirmed_by] = User.current&.id
end
relationships = Relationship.where(id: ids, source_id: source_id)
relationships.update_all(update_columns)
delete_cached_field(pm_source.id, ids)
# Run callbacks in background
extra_options = {
team_id: team&.id,
user_id: User.current&.id,
source_id: source_id,
}
self.delay.run_update_callbacks(ids.to_json, extra_options.to_json)
{ source_project_media: pm_source }
end
end
def bulk_destroy(ids, updates, team)
source_id = updates[:source_id]
pm_source = ProjectMedia.find_by_id(source_id)
relationships = Relationship.where(id: ids, source_id: source_id)
relationship_target = {}
relationships.find_each{ |r| relationship_target[r.id] = r.target_id}
relationships.delete_all
target_ids = relationship_target.values
delete_cached_field(pm_source.id, target_ids)
# Run callbacks in background
extra_options = {
team_id: team&.id,
user_id: User.current&.id,
source_id: source_id,
}
self.delay.run_destroy_callbacks(relationship_target.to_json, extra_options.to_json)
{ source_project_media: pm_source }
end
def delete_cached_field(source_id, target_ids)
# Clear cached fields
# List fields with `model: Relationship`
cached_fields = [
'is_suggested', 'is_confirmed', 'linked_items_count', 'suggestions_count','report_status','related_count',
'demand', 'last_seen', 'sources_as_sentence', 'added_as_similar_by_name', 'confirmed_as_similar_by_name'
]
cached_fields.each do |name|
Rails.cache.delete("check_cached_field:ProjectMedia:#{source_id}:#{name}")
target_ids.each { |id| Rails.cache.delete("check_cached_field:ProjectMedia:#{id}:#{name}") }
end
end
def run_update_callbacks(ids_json, extra_options_json)
ids = JSON.parse(ids_json)
extra_options = JSON.parse(extra_options_json)
whodunnit = extra_options['user_id'].blank? ? nil : extra_options['user_id'].to_s
team_id = extra_options['team_id']
# Update ES
index_alias = CheckElasticSearchModel.get_index_alias
es_body = []
versions = []
callbacks = [:reset_counters, :update_counters, :set_cluster, :propagate_inversion]
target_ids = []
Relationship.where(id: ids, source_id: extra_options['source_id']).find_each do |r|
target_ids << r.target_id
# ES fields
doc_id = Base64.encode64("ProjectMedia/#{r.target_id}")
fields = { updated_at: r.updated_at.utc, parent_id: r.source_id, unmatched: 0 }
es_body << { update: { _index: index_alias, _id: doc_id, retry_on_conflict: 3, data: { doc: fields } } }
# Add versions
r.relationship_type = Relationship.confirmed_type.to_yaml
v_object = r.dup
v_object.id = r.id
v_object.relationship_type = Relationship.suggested_type.to_yaml
v_object.confirmed_by = nil
v_object.confirmed_at = nil
versions << {
item_type: 'Relationship',
item_id: r.id.to_s,
event: 'update',
whodunnit: whodunnit,
object: v_object.to_json,
object_changes: {
relationship_type: [Relationship.suggested_type.to_yaml, Relationship.confirmed_type.to_yaml],
confirmed_by: [nil, whodunnit],
confirmed_at: [nil, r.updated_at],
}.to_json,
created_at: r.updated_at,
meta: r.version_metadata,
event_type: 'update_relationship',
object_after: r.to_json,
associated_id: r.target_id,
associated_type: 'ProjectMedia',
team_id: team_id
}
callbacks.each do |callback|
r.send(callback)
end
end
# Update un-matched field
ProjectMedia.where(id: target_ids).update_all(unmatched: 0)
# Update ES docs
$repository.client.bulk body: es_body unless es_body.blank?
# Import versions
bulk_import_versions(versions, team_id) if versions.size > 0
end
def run_destroy_callbacks(relationship_target_json, extra_options_json)
relationship_target = JSON.parse(relationship_target_json)
extra_options = JSON.parse(extra_options_json)
target_ids = relationship_target.values
whodunnit = extra_options['user_id'].blank? ? nil : extra_options['user_id'].to_s
team_id = extra_options['team_id']
source_id = extra_options['source_id']
# update_counters (destroy callback)
source = ProjectMedia.find_by_id(source_id)
version_metadata = nil
unless source.nil?
source.skip_check_ability = true
source.targets_count = Relationship.where(source_id: source.id).where('relationship_type = ? OR relationship_type = ?', Relationship.confirmed_type.to_yaml, Relationship.suggested_type.to_yaml).count
source.save!
# Get version metadata
version_metadata = {
source: {
title: source.title,
type: source.report_type,
url: source.full_url,
by_check: false,
}
}.to_json
end
ProjectMedia.where(id: target_ids).find_each do |target|
target.skip_check_ability = true
target.unmatched = 1
target.sources_count = Relationship.where(target_id: target.id).where('relationship_type = ?', Relationship.confirmed_type.to_yaml).count
target.save!
end
# Update ES
options = {
index: CheckElasticSearchModel.get_index_alias,
conflicts: 'proceed',
body: {
script: {
source: "ctx._source.updated_at = params.updated_at;ctx._source.unmatched = params.unmatched",
params: { updated_at: Time.now.utc, unmatched: 1 }
},
query: { terms: { annotated_id: target_ids } }
}
}
$repository.client.update_by_query options
versions = []
relationship_target.each do |r_id, target_id|
# Add versions
v_object = Relationship.new(id: r_id, source_id: source_id, target_id: target_id)
v_object.relationship_type = Relationship.suggested_type.to_yaml
v_object.confirmed_by = nil
v_object.confirmed_at = nil
versions << {
item_type: 'Relationship',
item_id: r_id.to_s,
event: 'destroy',
whodunnit: whodunnit,
object: v_object.to_json,
object_after: {}.to_json,
object_changes: {
relationship_type: [Relationship.suggested_type.to_yaml, nil],
}.to_json,
meta: version_metadata,
event_type: 'destroy_relationship',
associated_id: target_id,
associated_type: 'ProjectMedia',
team_id: team_id
}
end
# Import versions
bulk_import_versions(versions, team_id) if versions.size > 0
end
end
end
|
require 'spec_helper'
describe 'cassandra::agent' do
let(:params) do
{
:opscenter_ip => '192.168.2.1',
:opscenter_version => '5.0.1',
}
end
it 'does contain class cassandra::agent' do
should contain_class('cassandra::agent').with({
:opscenter_ip => '192.168.2.1',
:opscenter_version => '5.0.1',
})
end
it 'does contain package datastax-agent' do
should contain_package('datastax-agent')
end
it 'file /var/lib/datastax-agent/conf/address.yaml' do
should contain_file('/var/lib/datastax-agent/conf/address.yaml').with({
:ensure => 'file',
:path => '/var/lib/datastax-agent/conf/address.yaml',
:owner => 'opscenter-agent',
:group => 'opscenter-agent',
:content => /stomp_interface: 192.168.2.1/,
})
end
it 'does contain service agent' do
should contain_service('datastax-agent').with({
:ensure => 'running',
:enable => 'true',
})
end
end
|
class Item < ApplicationRecord
validates :item_cat_id, :name, :code, presence: true
belongs_to :item_cat
has_many :store_items
has_many :retur_items
has_many :order_items
has_many :transaction_items
has_many :grocer_items
has_many :supplier_items
belongs_to :edited_by, class_name: "User", foreign_key: "edited_by", optional: true
end
|
# filename: test_remove.rb
require "minitest/autorun"
require_relative "../../tile_group.rb"
##
# tests the hand method
class TestHand < Minitest::Test
# instantiating a new tile group
# like an @Before in JUnit4
def setup
@newTileGroup = TileGroup.new
end
# unit tests for the TileGroup:: hand method
def test_convert_empty_group_to_string
assert_equal('',@newTileGroup.hand)
end
def test_convert_single_tile_group_to_string
assert true,@newTileGroup.tiles.empty?
@newTileGroup.append(:A)
assert_equal('A',@newTileGroup.hand)
end
def test_convert_multi_tile_group_to_string
assert true,@newTileGroup.tiles.empty?
[:A,:A,:Z].each{|num| @newTileGroup.append(num)}
assert_equal("AAZ",@newTileGroup.hand)
end
def test_convert_multi_tile_group_with_duplicates_to_string
assert true,@newTileGroup.tiles.empty?
10.times{|num| @newTileGroup.append(:A)}
assert_equal(Array.new(10,'A').join(),@newTileGroup.hand)
end
end
|
class PositionLayout < Draco::System
filter LayoutGrid
def tick(args)
return if entities.nil?
entities.each do |layout|
current = world.scene || world
parent = current.entities[layout.tree.parent_id].first
#GTK::Log.puts_once layout.id, parent.inspect
#next unless parent
#next unless parent.components[:position]
#next unless parent.components[:size]
children = world.filter([Tree]).select { |e| e.tree.parent_id == layout.id }
position(layout, parent, children)
end
end
def position(layout, parent, children)
attr = layout.layout_grid.space
if attr == :evenly
space_evenly(layout, parent, children)
elsif attr == :start
space_start(layout, parent, children)
elsif attr == :end
space_end(layout, parent, children)
end
end
def space_start(layout, parent, children)
y = parent_rect(parent).top
y -= layout.layout_grid.padding
children.each do |child|
y -= child.size.height
child.components << Position.new(
x: align(layout, parent, child),
y: y,
absolute: true
)
end
end
def space_end(layout, parent, children)
total_children_height = children.map { |c| c.size.height }.reduce { |p, c| p + c }
y = parent_rect(parent).bottom + total_children_height
y += layout.layout_grid.padding
children.each do |child|
y -= child.size.height
child.components << Position.new(
x: align(layout, parent, child),
y: y,
absolute: true
)
end
end
def space_evenly(layout, parent, children)
total_children_height = children.map { |c| c.size.height }.reduce { |p, c| p + c }
empty_space = parent_height(parent) - total_children_height
space_per_child = empty_space / children.size
y = parent_rect(parent).top
children.each do |child|
y -= space_per_child / 2
y -= child.size.height
child.components << Position.new(
x: align(layout, parent, child),
y: y,
absolute: true
)
y -= space_per_child / 2
end
end
def align(entity, parent, child)
attr = entity.layout_grid.align
padding = entity.layout_grid.padding
return parent_rect(parent).left + padding if attr == :left
return parent_rect(parent).right - padding - child.size.width if attr == :right
parent_position(parent).x + parent_width(parent).half - child.size.width.half
end
def parent_position(parent)
if parent
parent.position
else
Position.new(x: 0, y: 0)
end
end
def parent_width(parent)
if parent
parent.size.width
else
$gtk.args.grid.w
end
end
def parent_height(parent)
if parent
parent.size.height
else
$gtk.args.grid.h
end
end
def parent_rect(parent)
if parent
[
parent_position(parent).x,
parent_position(parent).y,
parent.size.width,
parent.size.height
]
else
$gtk.args.grid.rect
end
end
end
|
class IssueLink
attr_reader :issue, :view_context
def initialize(issue, view_context, options={})
@issue = issue
@view_context = view_context
end
def attributes
{
title: issue.title,
url: issue.link,
published_at: issue.published_at.strftime("%Y-%m-%d")
}
end
def render
view_context.render partial: "shared/issue_link", locals: attributes
end
end
|
# prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
return nil if name_hash.empty?
name = name_hash.first.first
smallest_val = name_hash.first.last
name_hash.each do |k, v|
if smallest_val > v
name = k
smallest_val = v
end
end
name
end |
require 'unit_spec_helper'
describe HandleRecurrences do
let(:service) { HandleRecurrences.new }
context "#recurrences" do
it 'fetches all recurrences' do
Recurrence.expects(:ready)
service.recurrences
end
end
context "#perform" do
before do
service.stubs(:recurrences).returns(recurrences)
end
let(:first) { stub }
let(:second) { stub }
let(:recurrences) do [ first, second ] end
it 'should handle each recurrence' do
service.expects(:handle_recurrence).with(first)
service.expects(:handle_recurrence).with(second)
service.perform
end
context "#send_mail_notification" do
let(:mail) { stub }
let(:recurrence) { stub(user: "alice", task: "cooking") }
it 'sends an email to every recurrence' do
RecurrenceMailer.expects(:notify).with("alice", "cooking").returns(mail)
mail.expects(:deliver)
service.send_mail_notification(recurrence)
end
end
context "#set_last_at" do
let(:recurrence) { stub(next_at: 'paperino') }
it 'set last_at to next_at' do
recurrence.expects(:update_attributes).with(last_at: recurrence.next_at)
service.set_last_at(recurrence)
end
end
context "#reset_next_at" do
let(:recurrence) { stub }
it 'resets next_at to nil' do
recurrence.expects(:update_attributes).with(next_at: nil)
service.reset_next_at(recurrence)
end
end
end
end
|
class AddPhysicalLocationRelationBetweenSitesAndCountries < ActiveRecord::Migration[5.2]
def change
create_table :physical_locations do |t|
t.belongs_to :site, index: true
t.belongs_to :country, index: true
t.timestamps
end
end
end
|
class StaticController < ApplicationController
def index
if current_user
@users_households = Household.where(id: Householdmembers.where(member: current_user.id).pluck("hhid")).order("id DESC")
end
end
end
|
class GameSerializer < ActiveModel::Serializer
embed :ids, include: true
attributes :id, :state, :player_cards, :dealer_cards, :player_score, :dealer_score, :winner, :bet
has_one :user
has_many :cards
has_one :game_session
def cards
object.game_session.decks.map { |deck| deck.played_cards }.flatten
end
end
|
assert_throws NoExperienceError { employee.hire }
|
# MTA Lab
#
# Activity:
#
# Students should create a program that models a simple subway system.
#
# The program takes the line and stop that a user is getting on at and the line and stop that user is getting off at and prints:
#
# the stations the user must pass through, in order
# where to change lines, if necessary
# the total number of stops for the trip.
# There are 3 subway lines:
#
# The N line has the following stops: Times Square, 34th, 28th, 23rd, Union Square, and 8th
# The L line has the following stops: 8th, 6th, Union Square, 3rd, and 1st
# The 6 line has the following stops: Grand Central, 33rd, 28th, 23rd, Union Square, and Astor Place.
# All 3 subway lines intersect at Union Square, but there are no other intersection points.
# For example, this means the 28th stop on the N line is different than the 28th street stop on the 6 line, so you'll have to differentiate this when you name your stops in the arrays.
# We should be able to say:
#
# plan_trip( :n, "Times Square", :l, "Grand Central" )
# # Or something along those lines
# Hints:
#
# Don't worry about user input initially: get it working with hardcoded values first, and wire up the user interface once that's working
# Scope works in a different way in Ruby, so variables that you define outside won't be accessible in a method. Maybe think about using a function to return data. Or perhaps research other types of variables
# A symbol can't just be a number!
# Consider diagraming the lines by sketching out the subway lines and their stops and intersection.
# Make subway lines keys in a hash, while the values are an array of all the stops on each line.
# The key to the lab is to find the intersection of the lines at Union Square.
# Make sure the stops that are the same for different lines have different names (i.e. 23rd on the N and on the 6 need to be differentiated)
# pseudo
# need to head down the line
# can loop through until the function is equal to what i need.
# loop with each
# until the end train line
# want to return the train line minus union square
# test with other train stations in the lines
#
# make sure to start with an if to see they are not starting at the same station
# can use select to get to the right station?
#
#
# when it hits the station i will need it to put the station that i want to designate
# remove all the other stations so i just have the line (key) and the station left (value)
#
# **think of the index numbers with the previous versions
# #
#
#
# #
# Notes from class
#
# Iteration
# arr.map do |a|
# a * 2
# end
# map will go through and change what we need
#
# Selection for the stop that we want to find
# might be able to loop through the singel array to get the result i want
# arr.select do |a|
# a > 3
# end
#
# Array comparison, can we compare the end result and what is happening
#
#
# Accessing Values
# person = {
# :name => "Elke",
# :location => "Berkeley",
# "Skill in Mr. Squiggle" => 5
# }
# #
# person[:name]
# person["Skill in Mr. Squiggle"]
# #
# Iteration
# serge = {
# name: "Serge",
# nationality: "French"
# }
#
# serge.each do |key, value|
# puts "Key: #{key} and Value: #{value}"
# end
#
# serge.keys.each do |key|
# puts key
# end
#
# serge.values.each do |value|
# puts value
# end
#
# PSEUDO
# need to start on the correct line
# need to travel from one end to the other
# i can do this through indexing the different numbers and matching the index of start (this is the hardcode) to the one i want to get to
# start small
#
# get it to go loop through the n_line
#
# first of all i need to access the n_line
#NOTES FROM Ruby
# direction_check = start_index <=> end_index
# returns either a 1 for one way and a -1 for the other direction
#
#MY ANSWER
#what needs to be added
# figure out the direction i want to go by the size of the index for the line
# use this to figure out what line i need to go on
require "pry"
h_line = {
:line_n => ["Times Square", "34th", "28th", "23rd", "Union Square", "8th"],
:line_l => [ "8th", "6th", "Union Square", "3rd", "1st"],
:line_6 => [ "Grand Central", "33rd", "28th", "23rd", "Union Square", "Astor_Place"]
}
binding.pry
#Two way
#get the start station
puts "What station are you starting at?"
start_station = gets.to_s
#convert the start station to the necessary index number
h_line [ :line_n ].index { |x| x == "Times Square" }
start_station = gets.to_i
h_line [ :line_n ]
# display the message where the person will be startin
puts "you will be starting at the 'x-line' at #{ start_station }"
#find the end station
puts "what is your end station?"
end_station = gets.to_s
#convert the end station to the relevant
h_line [ :line_6 ].index { |x| x == "Grand Central"}
end_station = gets.to_i
#create the middle_station where everyone has to change
puts "middle_station"
#get the index for this as well
h_line [ :line_n ].index { |x| x == "Union Square"}
middle_station = gets.to_i
#start at the first station & loop through until you hit union station
if start_station <=> end station
#1 it will go one way
#-1 it will go the other way
if start_station == "Times Square"
h_line [ :line_n ].index { |x| x == "Times Square" }
start_station = gets.to_i
h_line [ :line_n ]
puts "you will be starting at the 'x-line' at #{ start_station }"
#this is where the loop needs to end
until middle_station = "Union Square"
h_line [ :line_n ].values.each do |x|
puts "Disemback at #{ middle_station }"
h_line [ :line_6 ]
# loop through the line_n until you get to Union Square
#ch
h_line [ :line_6 ].index { |x| x == "Grand central"}
puts "change line"
# travel from Union Square to Grand Central
end
end
#
#
#
# #One way
# # stary by asking which station someone is starting at
#
# puts "What station are you starting at?"
# start_station = gets.to_s
#
# # now access the right line as we know where it is
#
# if start_station == "Times Square"
# var = h_line [ :line_n ]
# puts "you will be starting at the 'x-line' at #{ start_station }"
#
# #loop through until we hit Union Square
# until end_station == "Union Square"
# puts "you will be ending at #{ end_station }"
# end
#
#
#
# h_line [ :line_n ].index { |x| x == "Times Square" }
# start_station = gets.to_i
#
# h_line [ :line_n ].index { |x| x == "8th"}
# end_station = gets.to_i
#
# if start_station < end_station
# puts "you will end on #{ end_station }"
# end
# alright start by accessing the different arrays
# practice get the 3 lines and merge them together just as an exercise
#
# n_line = %w[ Times_Square 34th 28th 23rd Union_Square 8th ]
# l_line = %w[ 8th 6th Union_Square 3rd 1st]
# 6_line = %w[ Grand_Central 33rd 28th 23rd Union_Square Astor_Place]
#
#
# h = { [:n_line => %w[ Times_Square 34th 28th 23rd Union_Square 8th ]
# }
# pseudo
# need to head down the line
# can loop through until the function is equal to what i need.
# it will either be heading one direction from big to small
#
# make sure to start with an if to see they are not starting at the same station
# can use select to get to the right station?
#
#
# when it hits the station i will need it to put the station that i want to designate
# remove all the other stations so i just have the line (key) and the station left (value)
#
# **think of the index numbers with the previous versions
|
class Users::Lawyer < User
def devise_mapping_override
:lawyer
end
end
|
require 'rspec'
require 'spec_helper'
describe 'Estrella' do
it 'deberia almacenar vida cuando se instancia el objeto' do
estrella = Estrella.new 70, 0
expect(estrella.vida).to eq 70
end
it 'deberia almacenar masa cuando se instancia el objeto' do
estrella = Estrella.new 100, 45
expect(estrella.masa).to eq 45
end
it 'deberia tener 100 puntos de vida cuando se instancia el objeto' do
estrella = Estrella.new
expect(estrella.vida).to eq 100
end
it 'deberia tener 100 puntos de masa cuando se instancia el objeto' do
estrella = Estrella.new
expect(estrella.masa).to eq 100
end
it 'deberia contener un asteroide en un mapa cuando se instancia el objeto' do
estrella = Estrella.new 100, 45
expect(estrella.efectos.key?(Asteroide)).to eq true
end
it 'deberia contener una bomba en un mapa cuando se instancia el objeto' do
estrella = Estrella.new 100, 45
expect(estrella.efectos.key?(Bomba)).to eq true
end
it 'deberia contener una nave en un mapa cuando se instancia el objeto' do
estrella = Estrella.new 100, 45
expect(estrella.efectos.key?(Nave)).to eq true
end
it 'deberia contener un misil en un mapa cuando se instancia el objeto' do
estrella = Estrella.new 100, 45
expect(estrella.efectos.key?(Misil)).to eq true
end
it 'deberia contener una estrella en un mapa cuando se instancia el objeto' do
estrella = Estrella.new 100, 45
expect(estrella.efectos.key?(Estrella)).to eq true
end
it 'deberia no estar viva cuando su vida es nula' do
estrella = Estrella.new 0, 45
expect(estrella.esta_vivo).to eq false
end
it 'deberia no estar viva cuando su masa es nula' do
estrella = Estrella.new 10, 0
expect(estrella.esta_vivo).to eq false
end
it 'deberia almacenar como minimo vida en 0' do
estrella = Estrella.new -1, 0
expect(estrella.vida).to eq 0
end
it 'deberia almacenar como minimo masa en 0' do
estrella = Estrella.new 10, -20
expect(estrella.masa).to eq 0
end
it 'deberia perder el 100% de su vida cuando colisiona con una nave' do
estrella = Estrella.new 50, 45
nave = Nave.new 250, 15
estrella.colisiona_con nave
expect(estrella.vida).to eq 0
end
it 'deberia no perder vida cuando colisiona con un misil' do
estrella = Estrella.new 50, 45
misil = Misil.new 80, 160
estrella.colisiona_con misil
expect(estrella.vida).to eq 50
end
it 'deberia no perder masa cuando colisiona con un misil' do
estrella = Estrella.new 50, 45
misil = Misil.new 80, 160
estrella.colisiona_con misil
expect(estrella.masa).to eq 45
end
it 'deberia perder el 100% de su vida cuando colisiona con una bomba' do
estrella = Estrella.new 50, 45
bomba = Bomba.new 100, 10
estrella.colisiona_con bomba
expect(estrella.vida).to eq 0
end
it 'deberia perder el 100% de su vida cuando colisiona con un asteroide' do
estrella = Estrella.new 50, 45
asteroide = Asteroide.new 180, 20
estrella.colisiona_con asteroide
expect(estrella.vida).to eq 0
end
it 'deberia perder el 100% de su vida cuando colisiona con otra estrella' do
estrella_1 = Estrella.new 50, 45
estrella_2 = Estrella.new 100, 100
estrella_1.colisiona_con estrella_2
expect(estrella_1.vida).to eq 0
end
it 'deberia quitarle el 100% de la vida a la otra estrella cuando colisiona con otra estrella' do
estrella_1 = Estrella.new 50, 45
estrella_2 = Estrella.new 100, 100
estrella_1.colisiona_con estrella_2
expect(estrella_2.vida).to eq 0
end
it 'deberia poder agregar nuevos objetos espaciales y efectos asociados' do
estrella = Estrella.new
bomba = Bomba.new
estrella.agregar_colision bomba, "cualquier_efecto"
expect(estrella.efectos[Bomba]).to eq "cualquier_efecto"
end
it 'deberia poder quitar objetos espaciales y efectos asociados' do
estrella = Estrella.new
estrella.quitar_colision Estrella
expect(estrella.efectos[Estrella]).to eq nil
end
end
|
require "rake/testtask"
Rake::TestTask.new do |t|
t.description = "Run integration and unit tests"
t.libs << "test"
t.pattern = File.join("test", "**", "test_*.rb")
t.warning = false
end
namespace :test do
mock = ENV["FOG_MOCK"] || "true"
task :travis do
sh("bundle exec rake test:unit")
end
desc "Run all integration tests in parallel"
multitask :parallel => ["test:compute",
"test:monitoring",
"test:pubsub",
"test:sql",
"test:storage"]
Rake::TestTask.new do |t|
t.name = "unit"
t.description = "Run Unit tests"
t.libs << "test"
t.pattern = FileList["test/unit/**/test_*.rb"]
t.warning = false
t.verbose = true
end
# This autogenerates rake tasks based on test folder structures
# This is done to simplify running many test suites in parallel
COMPUTE_TEST_TASKS = []
Dir.glob("test/integration/compute/**").each do |task|
suite_collection = task.gsub(/test\/integration\/compute\//, "")
component_name = task.gsub(/test\/integration\//, "").split("/").first
Rake::TestTask.new(:"#{component_name}-#{suite_collection}") do |t|
t.libs << "test"
t.description = "Autotask - run #{component_name} integration tests - #{suite_collection}"
t.pattern = FileList["test/integration/#{component_name}/#{suite_collection}/test_*.rb"]
t.warning = false
t.verbose = true
end
COMPUTE_TEST_TASKS << "#{component_name}-#{suite_collection}"
end
desc "Run Compute API tests"
task :compute => COMPUTE_TEST_TASKS
desc "Run Compute API tests in parallel"
multitask :compute_parallel => COMPUTE_TEST_TASKS
Rake::TestTask.new do |t|
t.name = "monitoring"
t.description = "Run Monitoring API tests"
t.libs << "test"
t.pattern = FileList["test/integration/monitoring/test_*.rb"]
t.warning = false
t.verbose = true
end
Rake::TestTask.new do |t|
t.name = "pubsub"
t.description = "Run PubSub API tests"
t.libs << "test"
t.pattern = FileList["test/integration/pubsub/test_*.rb"]
t.warning = false
t.verbose = true
end
# This autogenerates rake tasks based on test folder structures
# This is done to simplify running many test suites in parallel
SQL_TEST_TASKS = []
Dir.glob("test/integration/sql/**").each do |task|
suite_collection = task.gsub(/test\/integration\/sql\//, "")
component_name = task.gsub(/test\/integration\//, "").split("/").first
Rake::TestTask.new(:"#{component_name}-#{suite_collection}") do |t|
t.libs << "test"
t.description = "Autotask - run #{component_name} integration tests - #{suite_collection}"
t.pattern = FileList["test/integration/#{component_name}/#{suite_collection}/test_*.rb"]
t.warning = false
t.verbose = true
end
SQL_TEST_TASKS << "#{component_name}-#{suite_collection}"
end
desc "Run SQL API tests"
task :sql => SQL_TEST_TASKS
desc "Run SQL API tests in parallel"
multitask :sql_parallel => SQL_TEST_TASKS
# TODO(temikus): Remove after v1 is renamed in pipeline
desc "Run SQL API tests - v1 compat alias"
task :"sql-sqlv2" => :sql
Rake::TestTask.new do |t|
t.name = "sql"
t.description = "Run SQL API tests"
t.libs << "test"
t.pattern = FileList["test/integration/sql/test_*.rb"]
t.warning = false
t.verbose = true
end
Rake::TestTask.new do |t|
t.name = "storage"
t.description = "Run Storage API tests"
t.libs << "test"
t.pattern = FileList["test/integration/storage/test_*.rb"]
t.warning = false
t.verbose = true
end
end
|
#!/usr/bin/env ruby
require 'base64'
require 'openssl'
class ConvertCookie
# Encode session cookies as Base64
class Base64
def encode(str)
[str].pack('m').gsub(/\n/, '')
end
def decode(str)
str.unpack('m').first
end
# Encode session cookies as Marshaled Base64 data
class Marshal < Base64
def encode(str)
super(::Marshal.dump(str))
end
def decode(str)
::Marshal.load(super(str)) rescue nil
end
end
end
attr_accessor :decoded_cookie, :encoded_cookie
def initialize(secret = nil)
@secret = secret
@secret ||= 'c95f554820d160cac5792840a37900b98b30cd61f7dc7260a7532a8ffe15f46ddfd1e9005d648119a4f77d7f4221cb19ee6ef7d0bd4e08a42436502c212e9848'
@encoded_cookie = nil
@decoded_cookie = nil
@coder = Base64::Marshal.new
end
def decrypt(encoded)
@encoded_cookie = encoded
decoded = @coder.decode(encoded)
puts decoded
end
def encrypt(decoded, secret = nil)
@secret ||= secret
data = @coder.encode(decoded)
data = "#{data}--#{generate_hmac(data, @secret)}"
puts data
end
private
def generate_hmac(data, secret)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data)
end
end
choice = nil
while not %w(e d).include? choice do
print 'Would you like to encode or decode? (e or d): '
choice = gets.chomp
end
converter = ConvertCookie.new
print 'please provide a string: '
case choice
when 'd'
converter.decrypt(gets.chomp)
when 'e'
key = eval(gets.chomp)
print 'Please provide a secret: '
converter.encrypt(key, gets.chomp)
end |
#!/usr/bin/ruby -w
#
# Test miscellaneous items that don't fit elsewhere
#
require File.expand_path('etchtest', File.dirname(__FILE__))
require 'webrick'
class EtchMiscTests < Test::Unit::TestCase
include EtchTests
def setup
# Generate a file to use as our etch target/destination
@targetfile = released_tempfile
#puts "Using #{@targetfile} as target file"
# Generate a directory for our test repository
@repodir = initialize_repository
@server = get_server(@repodir)
# Create a directory to use as a working directory for the client
@testroot = tempdir
#puts "Using #{@testroot} as client working directory"
end
def test_empty_repository
# Does etch behave properly if the repository is empty? I.e. no source or
# commands directories.
testname = 'empty repository'
assert_etch(@server, @testroot, :testname => testname)
end
def teardown
remove_repository(@repodir)
FileUtils.rm_rf(@testroot)
FileUtils.rm_rf(@targetfile)
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
protected
def restrict_access
if !current_user
puts 'here'
flash[:alert] = "You must be logged in."
redirect_to '/'
end
end
def current_user
@current_user || User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
|
Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
get '/', to: 'welcome#index'
devise_for :users, skip: [:sessions]
as :user do
get '/login', to: 'devise/sessions#new', as: :new_user_session
post '/login', to: 'devise/sessions#create', as: :user_session
get '/logout', to: 'devise/sessions#destroy', as: :destroy_user_session
end
get 'teams/:team_id', to: 'teams#show', as: :team
get 'teams/:team_id/permits', to: 'team_permit_submissions#index', as: :team_permit_submissions
get 'teams/:team_id/permits/:permit_id', to: 'team_permit_submissions#show', as: :team_permit_submission
#delete '/permits/:id', to: 'team_permit_submissions#destroy'
get '/permits', to: 'permit_submissions#index', as: :permit_submissions
post '/permits', to: 'permit_submissions#create'
get '/permits/new', to: 'permit_submissions#new'
get '/permits/:id', to: 'permit_submissions#show', as: :permit_submission
get '/permits/:id/edit', to: 'permit_submissions#edit', as: :permit_edit
patch '/permits/:id', to: 'permit_submissions#update'
delete '/permits/:id', to: 'permit_submissions#destroy', as: :permit_delete
resources :alerts, only: [:index]
end
|
class UncompleteSkill
include Interactor
def setup
context.fail!(message: "provide a valid user") unless context[:user].present?
context.fail!(message: "provide a valid skill") unless context[:skill].present?
if !failure? && !context[:user].has_completed?(context[:skill])
context.fail!(message: "can only uncomplete a previously completed skill")
end
end
def perform
return if failure? # why is this not working?
completion = Completion.find_by!(user: context[:user], skill: context[:skill])
if completion.destroy
context[:completion] = completion
else
fail! message: "unable to uncomplete skill: #{completion.errors}"
end
end
end
|
require 'geo_ruby/geojson'
require 'phone'
require 'sequel'
ENV['DATABASE_URL'] ||= "postgres://localhost/citygram_#{Citygram::App.environment}"
DB = Sequel.connect(ENV['DATABASE_URL'])
Sequel.default_timezone = :utc
# no mass-assignable columns by default
Sequel::Model.set_allowed_columns(*[])
# use first!, create!, save! to raise
Sequel::Model.raise_on_save_failure = false
# sequel's standard pagination
DB.extension :pagination
# common model plugins
Sequel::Model.plugin :attributes_helpers
Sequel::Model.plugin :json_serializer
Sequel::Model.plugin :save_helpers
Sequel::Model.plugin :serialization
Sequel::Model.plugin :timestamps, update_on_create: true
Sequel::Model.plugin :validation_helpers
# round trip a geojson geometry through a postgis geometry column
Sequel::Plugins::Serialization.register_format(:geojson,
# transform a geojson geometry into extended well-known text format
->(v){ GeoRuby::GeojsonParser.new.parse(v).as_ewkt },
# transform extended well-known binary into a geojson geometry
->(v){ GeoRuby::SimpleFeatures::Geometry.from_hex_ewkb(v).to_json }
)
# set default to US for now
Phoner::Phone.default_country_code = '1'
# normalize phone numbers to E.164
Sequel::Plugins::Serialization.register_format(:phone,
->(v){ Phoner::Phone.parse(v).to_s },
->(v){ v } # identity
)
module Citygram
module Models
end
end
require 'app/models/event'
require 'app/models/publisher'
require 'app/models/subscription'
# access model class constants without qualifying namespace
include Citygram::Models
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.