text stringlengths 10 2.61M |
|---|
require 'formula'
class Le < Formula
homepage 'http://freecode.com/projects/leeditor'
# url 'http://ftp.yar.ru/pub/source/le/le-1.14.9.tar.xz'
# upstream not responding, source from debian
url 'http://ftp.de.debian.org/debian/pool/main/l/le/le_1.14.9.orig.tar.gz'
sha1 'ce85cbefb30cf1f5a7e8349dbb24ffa0f65b1fd7'
conflicts_with 'logentries', :because => 'both install a le binary'
def install
ENV.j1
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
end
end
|
require 'rails_helper'
RSpec.describe Post, type: :model do
before do
user = FactoryBot.create(:user)
@post = FactoryBot.create(:post, user_id: user.id)
# sleep 3
end
describe 'Tweetの保存' do
context 'Tweetが投稿出来る場合' do
it '入力内容に不備がない場合、投稿できる' do
@post.text = "テストテキスト"
@post.valid?
expect(@post).to be_valid
end
it 'imageがなくてもtitle,textがあれば投稿出来る' do
@post.text = "テストテキスト"
@post.image = nil
@post.valid?
expect(@post).to be_valid
end
end
context 'Tweetが保存できない場合' do
it 'titleがないとTweetは投稿できない' do
@post.title = ""
@post.valid?
expect(@post.errors.full_messages).to include("タイトルを入力してください")
end
it 'textがないとTweetは投稿できない' do
@post.text = ""
@post.valid?
expect(@post.errors.full_messages).to include("テキストを入力してください")
end
it 'textは1000文字以内でないと投稿できない' do
@post.text= ("a" * 1001)
@post.valid?
expect(@post.errors.full_messages).to include("テキストは1000文字以内で入力してください")
end
it 'titleが21文字以上だとTweetは投稿できない' do
@post.title = "あいうえおかきくけこさしすせそたちつてとな"
@post.valid?
expect(@post.errors.full_messages).to include("タイトルは20文字以内で入力してください")
end
it "ユーザーが紐付いていなければTweetが投稿できない" do
@post.user = nil
@post.valid?
expect(@post.errors.full_messages).to include("Userを入力してください")
end
end
end
end
|
require 'thor'
require 'yaml'
require 'json'
require_relative 'thor'
require_relative 'logger'
require_relative 'configs'
require_relative 'parser/parser'
require_relative 'token/handler'
require_relative 'code_object/base'
require_relative 'dom/dom'
require_relative 'processor'
# `#setup_application` is called during the initialization process of DocJs within {DocJs#docjs}
#
# 
#
# It is responsible to configure the two application-wide Singleton Objects {Logger} and {Configs}
# and fill {Configs} with the given commandline arguments.
#
# If the user is using it's own custom templates (see {file:CUSTOMIZE.md}) those templates will be
# included before the processing can begin.
def setup_application(options = {})
# Initialize Logger
Logger.setup :logfile => (options[:logfile] && File.expand_path(options[:logfile], Dir.pwd)),
:level => (options[:loglevel] || :info).to_sym
Logger.info "Setting up Application"
# Process option-values and store them in our Configs-object
Configs.set :options => options, # Just store the options for now
# Set the paths
:wdir => Dir.pwd, # The current working directory
:output => File.absolute_path(options[:output]),
:templates => File.absolute_path(options[:templates]),
:files => (options[:files] && options[:files].map {|path| Dir.glob(path) }.flatten),
:docs => (options[:docs] && options[:docs].map {|path| Dir.glob(path) }.flatten)
Logger.debug "Given options: #{options}"
Logger.debug "App Root: #{Configs.root}"
Logger.debug "Working Dir: #{Configs.wdir}"
Logger.debug "Output Dir: #{Configs.output}"
Logger.debug "Template Dir: #{Configs.templates}"
end
def load_templates(template_path = nil)
if template_path.nil? and Configs.templates
template_path = Configs.templates
elsif template_path.nil?
template_path =( Configs.root + 'templates').to_path
else
template_path = File.absolute_path(template_path)
end
require template_path + '/application.rb'
end |
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
module BackgrounDRb
class TargetLogDev
def initialize(target_id, name)
@logfile = File.open(File.join(Restore::Config.log_dir, "target_#{target_id}.log"), File::CREAT|File::RDWR|File::APPEND, 0640)
@target_id = target_id
end
def write(str)
# this is a little ridiculous
@logfile.write(str)
#escaped = Juggernaut.html_escape(str).gsub("\n", '\\\\\n').gsub("'", "\\\\\\\\'")
escaped = Juggernaut.html_escape(str).gsub("\n", '<br/>').gsub("'", "\\\\\\\\'")
Juggernaut.send_data("append_log('#{escaped}');", ["target_#{@target_id}".to_sym])
end
def close
@logfile.close
end
end
end
|
class UpdateTableVotesSetJobIdAsString < ActiveRecord::Migration[6.1]
def change
change_column :votes, :job_id, :string
end
end
|
class AddApplicantToPositionRequests < ActiveRecord::Migration
def change
add_column :position_requests, :applicant, :hstore
execute "CREATE INDEX position_requests_applicant ON position_requests USING GIN(applicant)"
end
end
|
class AddDefaultAreaCodeToGemeinschaftSetup < ActiveRecord::Migration
def change
add_column :gemeinschaft_setups, :default_area_code, :string
end
end
|
class SearchesController < ApplicationController
def show
@resource = Resource.resolve_path(params[:query])
if @resource.present?
return redirect_to([root_url, @resource.full_path].join('/'))
end
rescue ActiveRecord::RecordNotFound
@notes = Note.where "path || '/' || name ilike ?", "%#{params[:query]}%"
@folders = folders_with_pending
end
private
def folder_params
params.require(:folder).permit(:name, :path)
end
def folders_with_pending
existing_folders = Folder.where("path || '/' || name ilike ?", "%#{params[:query]}%")
pending_folders = @notes.map(&:parent_folders).flatten.select do |folder|
folder.name == params[:query]
end
(existing_folders + pending_folders).uniq(&:full_path)
end
end
|
describe Treasury::Models::Field, type: :model do
context 'when check db structure' do
it { is_expected.to have_db_column(:title).of_type(:string).with_options(limit: 128, null: false) }
it { is_expected.to have_db_column(:group).of_type(:string).with_options(limit: 128, null: false) }
it { is_expected.to have_db_column(:field_class).of_type(:string).with_options(limit: 128, null: false) }
it { is_expected.to have_db_column(:active).of_type(:boolean).with_options(default: false, null: false) }
it { is_expected.to have_db_column(:need_terminate).of_type(:boolean).with_options(default: false, null: false) }
it { is_expected.to have_db_column(:state).of_type(:string).with_options(limit: 128, null: false) }
it { is_expected.to have_db_column(:pid).of_type(:integer) }
it { is_expected.to have_db_column(:progress).of_type(:string).with_options(limit: 128) }
it { is_expected.to have_db_column(:snapshot_id).of_type(:string).with_options(limit: 4000) }
it { is_expected.to have_db_column(:last_error).of_type(:string).with_options(limit: 4000) }
it { is_expected.to have_db_column(:worker_id).of_type(:integer) }
it { is_expected.to have_db_column(:oid).of_type(:integer).with_options(null: false) }
it { is_expected.to have_db_column(:params).of_type(:string).with_options(limit: 4000) }
it { is_expected.to have_db_column(:storage).of_type(:string).with_options(limit: 4000) }
end
context 'when check associations' do
it { is_expected.to have_many(:processors) }
it { is_expected.to belong_to(:worker) }
end
end
|
require 'rails_helper'
RSpec.describe Challenge, type: :model do
# Validation tests
it { should validate_presence_of(:name) }
it { should validate_presence_of(:html) }
it { should validate_presence_of(:css) }
end
|
class Company::ApplicationController < ApplicationController
before_action :authorize_company!
layout "company"
private
def authorize_company!
authenticate_company!
unless current_company
redirect_to root_path, alert: "YOU ARE NOT AUTHORIZED! You lack certain permissions to proceed further"
end
end
end
|
module Ranks
TWO = "2"
THREE = "3"
FOUR = "4"
FIVE = "5"
SIX = "6"
SEVEN = "7"
EIGHT = "8"
NINE = "9"
TEN = "10"
ELEVEN = "11"
TWELVE = "12"
THIRTEEN = "13"
JACK = "jack"
QUEEN = "queen"
KING = "king"
ACE = "ace"
JOKER = "joker"
ALL_RANKS = [
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
ELEVEN,
TWELVE,
THIRTEEN,
JACK,
QUEEN,
KING,
ACE,
JOKER
]
end
|
task :default => [:compile_js]
task :compile_js do
scripts = Dir["js/*.js"]
content = ""
scripts.each do |script|
content += "\n" + File.read(script)
end
File.write("assets/lib.js", content)
puts "Compiled JS assets"
end
|
class Fighter < ApplicationRecord
validates :name, presence: true
validates :health, presence: true, inclusion: { in: 50..100 }
validates :attack, presence: true, inclusion: { in: 0..50 }
def is_survivor
health > 0
end
end
|
require "rails_helper"
RSpec::Matchers.define :facilities do |facilities|
match { |actual| actual.map(&:id) == facilities.map(&:id) }
end
RSpec.describe MyFacilitiesController, type: :controller do
let(:facility_group) { create(:facility_group) }
let(:supervisor) { create(:admin, :manager, :with_access, resource: facility_group) }
render_views
before do
sign_in(supervisor.email_authentication)
end
describe "GET #index" do
it "returns a success response" do
create(:facility, facility_group: facility_group)
get :index, params: {}
expect(response).to be_successful
end
end
describe "GET #blood_pressure_control" do
it "returns a success response" do
create(:facility, facility_group: facility_group)
get :blood_pressure_control, params: {}
expect(response).to be_successful
end
end
describe "GET #registrations" do
let!(:facility_under_supervisor) { create(:facility, facility_group: facility_group) }
let!(:facility_not_under_supervisor) { create(:facility) }
let!(:patients) do
[facility_under_supervisor, facility_not_under_supervisor].map do |facility|
create(:patient, registration_facility: facility, recorded_at: 3.months.ago)
end
end
it "returns a success response" do
get :registrations, params: {}
expect(response).to be_successful
end
it "instantiates a MyFacilities::RegistrationsQuery object with the right arguments and calls the required methods" do
params = {period: :quarter}
query_object = MyFacilities::RegistrationsQuery.new
allow(MyFacilities::RegistrationsQuery).to receive(:new).with(hash_including(params.merge(last_n: 3)))
.and_return(query_object)
expect(MyFacilities::RegistrationsQuery).to receive(:new)
.with(hash_including(facilities: facilities(Facility.where(id: facility_under_supervisor))))
expect(query_object).to receive(:registrations).and_return(query_object.registrations)
expect(query_object).to receive(:total_registrations).and_return(query_object.total_registrations)
get :registrations, params: params
end
end
describe "GET #missed_visits" do
let!(:facility_under_supervisor) { create(:facility, facility_group: facility_group) }
let!(:facility_not_under_supervisor) { create(:facility) }
let!(:patients) do
[facility_under_supervisor, facility_not_under_supervisor].map do |facility|
create(:patient, registration_facility: facility, recorded_at: 3.months.ago)
end
end
it "returns a success response" do
get :missed_visits, params: {}
expect(response).to be_successful
end
it "instantiates a MyFacilities::MissedVisitsQuery object with the right arguments and calls the required methods" do
params = {period: :quarter}
query_object = MyFacilities::MissedVisitsQuery.new
allow(MyFacilities::MissedVisitsQuery).to receive(:new).with(hash_including(params.merge(last_n: 3)))
.and_return(query_object)
expect(MyFacilities::MissedVisitsQuery).to receive(:new)
.with(hash_including(facilities: facilities(Facility.where(id: facility_under_supervisor))))
expect(query_object).to receive(:periods).and_return(query_object.periods)
expect(query_object).to receive(:missed_visits_by_facility).and_return(query_object.missed_visits_by_facility).at_least(:once)
expect(query_object).to receive(:missed_visit_totals).and_return(query_object.missed_visit_totals).at_least(:once)
expect(query_object).to receive(:calls_made).and_return(query_object.calls_made)
get :missed_visits, params: params
end
end
end
|
require 'tmpdir'
module KPM
class Database
class << self
# Mysql Information functions
LAST_INSERTED_ID = 'SELECT LAST_INSERT_ID();'
ROWS_UPDATED = 'SELECT ROW_COUNT();'
# Destination database
DATABASE = ENV['DATABASE'] || 'killbill'
USERNAME = ENV['USERNAME'] || 'root'
PASSWORD = ENV['PASSWORD'] || 'root'
HOST = ENV['HOST'] || 'localhost'
PORT = ENV['PORT'] || '3306'
COLUMN_NAME_POS = 3
STATEMENT_TMP_FILE = Dir.mktmpdir('statement') + File::SEPARATOR + 'statement.sql'
MYSQL_COMMAND_LINE = "mysql #{DATABASE} --user=#{USERNAME} --password=#{PASSWORD} "
@@mysql_command_line = MYSQL_COMMAND_LINE
@@username = USERNAME
@@password = PASSWORD
@@database = DATABASE
@@host = HOST
@@port = PORT
def set_logger(logger)
@@logger = logger
end
def set_credentials(user = nil, password = nil)
@@username = user
@@password = password
end
def set_host(host)
@@host = host
end
def set_port(port)
@@port = port
end
def set_database_name(database_name = nil)
@@database = database_name
end
def set_mysql_command_line
@@mysql_command_line = "mysql #{@@database} --host=#{@@host} --port=#{@@port} --user=#{@@username} --password=#{@@password} "
end
def execute_insert_statement(table_name, query, qty_to_insert, table_data, record_id = nil)
unless record_id.nil?
query = "set #{record_id[:variable]}=#{record_id[:value]}; #{query}"
end
query = "SET autocommit=0; #{query} COMMIT;"
File.open(STATEMENT_TMP_FILE,'w') do |s|
s.puts query
end
response = `#{@@mysql_command_line} < "#{STATEMENT_TMP_FILE}" 2>&1`
if response.include? 'ERROR'
@@logger.error "\e[91;1mTransaction that fails to be executed\e[0m"
@@logger.error "\e[91m#{query}\e[0m"
raise Interrupt, "Importing table #{table_name}...... \e[91;1m#{response}\e[0m"
end
if response.include? 'LAST_INSERT_ID'
@@logger.info "\e[32mImporting table #{table_name}...... Row 1 of #{qty_to_insert} success\e[0m"
return response.split("\n")[1]
end
if response.include? 'ROW_COUNT'
response_msg = response.split("\n")
row_count_inserted = response_msg[response_msg.size - 1]
@@logger.info "\e[32mImporting table #{table_name}...... Row #{ row_count_inserted || 1} of #{qty_to_insert} success\e[0m"
return true
end
return true
end
def generate_insert_statement(tables)
statements = []
@@logger.info "\e[32mGenerating statements\e[0m"
tables.each_key do |table_name|
table = tables[table_name]
if !table[:rows].nil? && table[:rows].size > 0
columns_names = table[:col_names].join(",").gsub(/'/,'')
rows = []
table[:rows].each do |row|
rows << row.map do |value|
if value.is_a?(Symbol)
value.to_s
else
escaped_value = value.to_s.gsub(/['"]/, "'" => "\\'", '"' => '\\"')
.gsub('\N{LINE FEED}', "\n")
.gsub('\N{VERTICAL LINE}', "|")
"'#{escaped_value}'"
end
end.join(",")
end
value_data = rows.map{|row| "(#{row})" }.join(",")
statements << {:query => get_insert_statement(table_name,columns_names,value_data, rows.size),
:qty_to_insert => rows.size, :table_name => table_name, :table_data => table}
end
end
statements
end
private
def get_insert_statement(table_name, columns_names, values, rows_qty)
return "INSERT INTO #{table_name} ( #{columns_names} ) VALUES #{values}; #{rows_qty == 1 ? LAST_INSERTED_ID : ROWS_UPDATED}"
end
end
end
end |
class PhotoViolationsController < ApplicationController
layout "bare"
before_filter :get_photo
def new
@photo_url = @photo.get_mid_size_url
@name = "#{session_user.first_name} #{session_user.last_name}" if session_user
@email = session_user.email if session_user
end
def create
violation = Violation.new(params[:violation])
violation.violated = @photo
violation.status = :active
violation.save
end
private
def get_photo
@photo = LocalPhoto.find(params[:photo])
end
end |
module IOTA
module API
module Wrappers
def getTransactionsObjects(hashes, &callback)
# If not array of hashes, return error
if !@validator.isArrayOfHashes(hashes)
return sendData(false, "Invalid inputs provided", &callback)
end
ret_status = false
ret_data = nil
# get the trytes of the transaction hashes
getTrytes(hashes) do |status, trytes|
ret_status = status
if status
transactionObjects = []
trytes.each do |tryte|
if !tryte
transactionObjects << nil
else
transactionObjects << @utils.transactionObject(tryte)
end
end
ret_data = transactionObjects
else
ret_data = trytes
end
end
sendData(ret_status, ret_data, &callback)
end
def findTransactionObjects(input, &callback)
findTransactions(input) do |status, transactions|
if !status
return sendData(status, transactions, &callback)
else
return getTransactionsObjects(transactions, &callback)
end
end
end
def getLatestInclusion(hashes, &callback)
ret_status = false
ret_data = nil
getNodeInfo do |status, data|
if status
ret_status = true
ret_data = data['latestSolidSubtangleMilestone']
end
end
if ret_status
return getInclusionStates(hashes, [ret_data], &callback)
else
return sendData(ret_status, ret_data, &callback)
end
end
def storeAndBroadcast(trytes, &callback)
storeTransactions(trytes) do |status, data|
if !status
return sendData(status, data, &callback)
else
return broadcastTransactions(trytes, &callback)
end
end
end
def sendTrytes(trytes, depth, minWeightMagnitude, options = {}, &callback)
# Check if correct depth and minWeightMagnitude
if !@validator.isValue(depth) || !@validator.isValue(minWeightMagnitude)
return sendData(false, "Invalid inputs provided", &callback)
end
reference = options[:reference] || options['reference']
getTransactionsToApprove(depth, reference) do |status, approval_data|
if !status
return sendData(false, approval_data, &callback)
end
attachToTangle(approval_data['trunkTransaction'], approval_data['branchTransaction'], minWeightMagnitude, trytes) do |status1, attached_data|
if !status1
return sendData(false, attached_data, &callback)
end
# If the user is connected to the sandbox and local pow is not used, we have to monitor the POW queue to check if the POW job was completed
if @sandbox && @pow_provider.nil?
# Implement sandbox processing
jobUri = @sandbox + '/jobs/' + attached_data['id']
# Do the Sandbox send function
@broker.sandboxSend(jobUri) do |status2, sandbox_data|
if !status2
return sendData(false, sandbox_data, &callback)
end
storeAndBroadcast(sandbox_data) do |status3, data|
if status3
return sendData(false, data, &callback)
end
finalTxs = []
attachedTrytes.each do |trytes1|
finalTxs << @utils.transactionObject(trytes1)
end
return sendData(true, finalTxs, &callback)
end
end
else
# Broadcast and store tx
storeAndBroadcast(attached_data) do |status2, data|
if !status2
return sendData(false, data, &callback)
end
transactions = attached_data.map { |tryte| @utils.transactionObject(tryte) }
sendData(true, transactions, &callback)
end
end
end
end
end
def bundlesFromAddresses(addresses, inclusionStates, &callback)
# call wrapper function to get txs associated with addresses
findTransactionObjects(addresses: addresses) do |status, transactionObjects|
if !status
return sendData(false, transactionObjects, &callback)
end
# set of tail transactions
tailTransactions = []
nonTailBundleHashes = []
transactionObjects.each do |trx|
# Sort tail and nonTails
if trx.currentIndex == 0
tailTransactions << trx.hash
else
nonTailBundleHashes << trx.bundle
end
end
# Get tail transactions for each nonTail via the bundle hash
findTransactionObjects(bundles: nonTailBundleHashes.uniq) do |st1, trxObjects|
if !st1
return sendData(false, trxObjects, &callback)
end
trxObjects.each do |trx|
tailTransactions << trx.hash if trx.currentIndex == 0
end
finalBundles = []
tailTransactions = tailTransactions.uniq
tailTxStates = []
# If inclusionStates, get the confirmation status of the tail transactions, and thus the bundles
if inclusionStates && tailTransactions.length > 0
getLatestInclusion(tailTransactions) do |st2, states|
# If error, return it to original caller
if !status
return sendData(false, states, &callback)
end
tailTxStates = states
end
end
tailTransactions.each do |tailTx|
getBundle(tailTx) do |st2, bundleTransactions|
if st2
if inclusionStates
thisInclusion = tailTxStates[tailTransactions.index(tailTx)]
bundleTransactions.each do |bundleTx|
bundleTx.persistence = thisInclusion
end
end
finalBundles << IOTA::Models::Bundle.new(bundleTransactions)
end
end
end
# Sort bundles by attachmentTimestamp
finalBundles = finalBundles.sort{|a, b| a.attachmentTimestamp <=> b.attachmentTimestamp}
return sendData(true, finalBundles, &callback)
end
end
end
def getBundle(transaction, &callback)
# Check if correct hash
if !@validator.isHash(transaction)
return sendData(false, "Invalid transaction input provided", &callback)
end
# Initiate traverseBundle
traverseBundle(transaction, nil, []) do |status, bundle|
if !status
return sendData(false, bundle, &callback)
end
if !@utils.isBundle(bundle)
return sendData(false, "Invalid Bundle provided", &callback)
end
return sendData(true, bundle, &callback)
end
end
# Replays or promote transactions based on tail consistency
def replayBundle(tail, depth, minWeightMagnitude, forcedReplay = false, &callback)
# Check if correct tail hash
if !@validator.isHash(tail)
return sendData(false, "Invalid trytes provided", &callback)
end
# Check if correct depth and minWeightMagnitude
if !@validator.isValue(depth) || !@validator.isValue(minWeightMagnitude)
return sendData(false, "Invalid inputs provided", &callback)
end
isPromotable = false
if !forcedReplay
checkConsistency([tail]) do |status, isConsistent|
isPromotable = status && isConsistent
end
end
getBundle(tail) do |status, transactions|
if !status
return sendData(false, transactions, &callback)
end
if !isPromotable
bundleTrytes = []
transactions.each do |trx|
bundleTrytes << @utils.transactionTrytes(trx);
end
return sendTrytes(bundleTrytes.reverse, depth, minWeightMagnitude, &callback)
else
account = IOTA::Models::Account.new(nil, transactions.first.address, self, @validator, @utils)
transfers = [{
address: '9' * 81,
value: 0,
message: '',
tag: ''
}]
begin
account.sendTransfer(depth, minWeightMagnitude, transfers, { reference: tail })
return sendData(status, transactions, &callback)
rescue => e
return sendData(false, e.message, &callback)
end
end
end
end
def broadcastBundle(tail, &callback)
# Check if correct tail hash
if !@validator.isHash(tail)
return sendData(false, "Invalid trytes provided", &callback)
end
getBundle(tail) do |status, transactions|
if !status
return sendData(false, transactions, &callback)
end
bundleTrytes = []
transactions.each do |trx|
bundleTrytes << @utils.transactionTrytes(trx);
end
return broadcastTransactions(bundleTrytes.reverse, &callback)
end
end
def traverseBundle(trunkTx, bundleHash, bundle, &callback)
# Get trytes of transaction hash
getTrytes([trunkTx]) do |status, trytesList|
if !status
return sendData(false, trytesList, &callback)
end
trytes = trytesList[0]
if !trytes
return sendData(false, "Bundle transactions not visible", &callback)
end
# get the transaction object
txObject = @utils.transactionObject(trytes)
if !trytes
return sendData(false, "Invalid trytes, could not create object", &callback)
end
# If first transaction to search is not a tail, return error
if !bundleHash && txObject.currentIndex != 0
return sendData(false, "Invalid tail transaction supplied", &callback)
end
# If no bundle hash, define it
if !bundleHash
bundleHash = txObject.bundle
end
# If different bundle hash, return with bundle
if bundleHash != txObject.bundle
return sendData(true, bundle, &callback)
end
# If only one bundle element, return
if txObject.lastIndex == 0 && txObject.currentIndex == 0
return sendData(true, [txObject], &callback)
end
# Define new trunkTransaction for search
trunkTx = txObject.trunkTransaction
# Add transaction object to bundle
bundle << txObject
# Continue traversing with new trunkTx
return traverseBundle(trunkTx, bundleHash, bundle, &callback)
end
end
def isReattachable(inputAddresses, &callback)
# if string provided, make array
inputAddresses = [inputAddresses] if @validator.isString(inputAddresses)
# Categorized value transactions
# hash -> txarray map
addressTxsMap = {}
addresses = []
inputAddresses.each do |address|
if !@validator.isAddress(address)
return sendData(false, "Invalid inputs provided", &callback)
end
address = @utils.noChecksum(address)
addressTxsMap[address] = []
addresses << address
end
findTransactionObjects(addresses: addresses) do |status, transactions|
if !status
return sendData(false, transactions, &callback)
end
valueTransactions = []
transactions.each do |trx|
if trx.value < 0
txAddress = trx.address
txHash = trx.hash
addressTxsMap[txAddress] << txHash
valueTransactions << txHash
end
end
if valueTransactions.length > 0
# get the includion states of all the transactions
getLatestInclusion(valueTransactions) do |st1, inclusionStates|
if !st1
return sendData(false, inclusionStates, &callback)
end
# bool array
results = addresses.map do |address|
txs = addressTxsMap[address]
numTxs = txs.length
if numTxs == 0
true
else
shouldReattach = true
(0...numTxs).step(1) do |i|
tx = txs[i]
txIndex = valueTransactions.index(tx)
isConfirmed = inclusionStates[txIndex]
shouldReattach = isConfirmed ? false : true
break if isConfirmed
end
shouldReattach
end
end
# If only one entry, return first
results = results.first if results.length == 1
return sendData(true, results, &callback)
end
else
results = [];
numAddresses = addresses.length;
# prepare results array if multiple addresses
if numAddresses > 1
numAddresses.each do |i|
results << true
end
else
results = true
end
return sendData(true, results, &callback)
end
end
end
end
end
end
|
Pod::Spec.new do |spec|
spec.name = "sMock"
spec.version = "1.1.0"
spec.summary = "Swift mock-helping library written with gMock (C++) library approach in mind"
spec.description = <<-DESC
Swift mock-helping library written with gMock (C++) library approach in mind;
uses XCTestExpectations inside, that makes sMock not only mocking library, but also library that allows easy unit-test coverage of mocked objects expected behavior;
lightweight and zero-dependecy;
works out-of-the-box without need of generators, tools, etc;
required minimum of additional code to prepare mocks.
DESC
spec.homepage = "https://github.com/Alkenso/sMock"
spec.license = "MIT"
spec.author = { "Vladimir Alkenso" => "alkensox@gmail.com" }
spec.source = { :git => "https://github.com/spin-org/sMock.git", :tag => "#{spec.version}" }
spec.source_files = "Sources/sMock/**/*.swift"
spec.swift_versions = '5.0'
spec.platform = :ios, '11.0'
spec.framework = 'XCTest'
end
|
class CreateHealthCareIndicators < ActiveRecord::Migration
def self.up
create_table :health_care_indicators, :primary_key => :indicator_id do |t|
t.integer :indicator_id
t.string :indicator_type
t.integer :indicator_value
t.string :facility
t.date :indicator_date
t.timestamps
end
end
def self.down
drop_table :health_care_indicators
end
end |
class RestaurantsController < ApplicationController
before_filter :require_signed_in!, :except => [:index]
def new
@city = City.find(params[:city_id])
@restaurant = @city.restaurants.new
end
def create
@city = City.find(params[:city_id])
@restaurant = @city.restaurants.new(params[:restaurant])
if @restaurant.save
redirect_to restaurant_url(@restaurant)
else
render :json => @restaurant.errors.full_messages
end
end
def edit
@restaurant = Restaurant.find(params[:id])
end
def update
@restaurant = Restaurant.find(params[:id])
if @restaurant.update_attributes(params[:restaurant])
redirect_to restaurant_url(@restaurant)
else
render :json => @restaurant.errors.full_messages
end
end
def show
@restaurant = Restaurant.find(params[:id])
# Restaurant.includes(:reviews, :categories, :city, :state, :users_who_favorited).find(params[:id])
end
def index
#@city = City.find(params[:city_id])
@city = City.find(1)
@restaurants = @city.restaurants.select("restaurants.*, AVG(reviews.rating) AS avg_rating")
.joins("LEFT JOIN reviews ON reviews.restaurant_id = restaurants.id")
.group("restaurants.id")
.order("avg_rating DESC NULLS LAST")
.page(params[:page])
.per(5)
@reviews = Review.select("reviews.*")
.joins("JOIN restaurants ON reviews.restaurant_id = restaurants.id")
.joins("JOIN cities ON cities.id = restaurants.city_id")
.where("cities.id = ?", @city.id)
.group("reviews.id")
.order("reviews.created_at")
.last(5)
.reverse!
end
def destroy
@restaurant = Restaurant.find(params[:id])
@restaurant.destroy
redirect_to restaurants_url
end
def search
@results = PgSearch.multisearch(params[:query])
if @results.empty?
return []
elsif Category.all.include?(@results.first.searchable)
@category = @results.first.searchable
.restaurants.where("city_id = ?", params[:city_id])
.sort!{ |a, b| a.average_rating <=> b.average_rating }
.reverse!
@restaurants = Kaminari.paginate_array(@category)
.page(params[:page])
.per(10)
else
@restaurants = @results.map(&:searchable).sort!{ |a, b| a.average_rating <=> b.average_rating }.reverse!
@restaurants = Kaminari.paginate_array(@restaurants).page(params[:page]).per(10)
end
# @restaurants = Restaurant.includes(:categories).where("city_id = ? AND categories.id = ?", params[:city_id], params[:cat_id]).page(params[:page])
end
end
|
require('minitest/autorun')
require_relative('../guest')
class TestGuest < MiniTest::Test
def setup
@guest1 = Guest.new("Bob", 25.00)
end
def test_check_guest_has_name()
assert_equal("Bob", @guest1.name())
end
def test_check_guest_has_wallet()
assert_equal(25.00, @guest1.wallet())
end
def test_remove_money()
@guest1.remove_money(5.00)
assert_equal(20.00, @guest1.wallet())
end
end
|
class Contact < ActiveRecord::Base
validates_presence_of :header_1, :link_1, :header_2, :link_2, :number, :address_name, :address_street, :city, :state, :zip_code
end
# == Schema Information
#
# Table name: contacts
#
# id :integer not null, primary key
# header_1 :string(255)
# link_1 :string(255)
# header_2 :string(255)
# link_2 :string(255)
# number :string(255)
# address_name :string(255)
# address_street :string(255)
# city :string(255)
# state :string(255)
# zip_code :integer
#
|
require "spec_helper"
describe Enumerable do
describe "#threading" do
it "acts like #collect" do
[1,2,3].threading(5) { |x| x * 2 }.to_a.should == [2,4,6]
end
it "runs things in separate threads" do
[1,2,3].threading(5) { Thread.current.object_id }.to_a.uniq.size.should eq(3)
end
it "is lazy" do
[1,2,3].with_time_bomb.threading(2) { |x| x * 2 }.first.should == 2
end
def round(n, accuracy = 0.02)
(n / accuracy).round.to_f * accuracy
end
it "runs the specified number of threads in parallel" do
delays = [0.03, 0.03, 0.03]
start = Time.now
delays.threading(2) do |delay|
sleep(delay)
end.to_a
round(Time.now - start).should eq(0.06)
end
it "acts as a sliding window" do
delays = [0.1, 0.08, 0.06, 0.04, 0.02]
start = Time.now
elapsed_times = delays.threading(3) do |delay|
sleep(delay)
round(Time.now - start)
end
elapsed_times.to_a.should eq([0.1, 0.08, 0.06, 0.14, 0.12])
end
it "surfaces exceptions" do
lambda do
[1,2,3].threading(5) { raise "hell" }.to_a
end.should raise_error(RuntimeError, "hell")
end
end
end
|
class RMQViewData
attr_accessor :events, :built, :is_screen_root_view, :screen, :cached_rmq #, :cache_queries
def screen_root_view?
!@is_screen_root_view.nil?
end
def cleanup
clear_query_cache
if @cached_rmq
@cached_rmq.selectors = nil
@cached_rmq.parent_rmq = nil
@cached_rmq = nil
end
@events = nil
@screen = nil
@_tags = nil
@_styles = nil
@_validation_errors = nil
@validation_errors = nil
@is_screen_root_view = false
@built = false
nil
end
def query_cache
@_query_cache ||= {}
end
def clear_query_cache
@query_cache = {}
end
def activity
if @screen
@screen.getActivity
end
end
# @return [Hash] Array of tag names assigned to to this view
def tags
@_tags ||= {}
end
# @return [Array] Array of tag names assigned to to this view
def tag_names
tags.keys
end
# *Do not* use this, use {RMQ#tag} instead:
# @example
# rmq(my_view).tag(:foo)
def tag(*tag_or_tags)
tag_or_tags.flatten!
tag_or_tags = tag_or_tags.first if tag_or_tags.length == 1
if tag_or_tags.is_a?(Array)
tag_or_tags.each do |tag_name|
tags[tag_name] = 1
end
elsif tag_or_tags.is_a?(Hash)
tag_or_tags.each do |tag_name, tag_value|
tags[tag_name] = tag_value
end
elsif tag_or_tags.is_a?(Symbol)
tags[tag_or_tags] = 1
end
end
# *Do not* use this, use {RMQ#untag} instead:
# @example
# rmq(my_view).untag(:foo, :bar)
# Do nothing if no tag supplied or tag not present
def untag(*tag_or_tags)
tag_or_tags.flatten.each do |tag_name|
tags.delete tag_name
end
end
# Check if this view contains a specific tag
#
# @param tag_name name of tag to check
# @return [Boolean] true if this view has the tag provided
def has_tag?(tag_name = nil)
if tag_name
tags.include?(tag_name)
else
RMQ.is_blank?(@_tags)
end
end
def style_name
self.styles.first
end
# Sets first style name, this is only here for backwards compatibility and as
# a convenience method
def style_name=(value)
self.styles[0] = value
end
#view.rmq_data.styles
def styles
@_styles ||= []
end
#view.rmq_data.has_style?(:style_name_here)
def has_style?(name = nil)
if name
self.styles.include?(name)
else
RMQ.is_blank?(@_styles)
end
end
def validation_errors; @_validation_errors ||= {}; end
def validation_errors=(value); @_validation_errors = value; end
def validations; @_validations ||= []; end
def validations=(value); @_validations = value; end
end
|
Pod::Spec.new do |s|
s.name = 'BridgeTechSupport'
s.version = '0.1.3'
s.summary = 'Adds an amazing support menu bar to your app\'s menu. Really useful for all developers with any kind of app. 😉'
s.description = 'Use this pod to see an example of how you might add an NSMenu to a menu bar and some useful links that will invoke the review prompt or the developer bage for your app.'
s.homepage = 'https://github.com/megatron1000/BridgeTechSupport'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'megatron1000' => 'mark@bridgetech.io' }
s.source = { :git => 'https://github.com/megatron1000/BridgeTechSupport.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/markbridgesapps'
s.platform = :osx, '10.11'
s.swift_version = '4.2'
s.source_files = 'BridgeTechSupport/Classes/**/*'
s.resource_bundles = {}
end
|
# coding: UTF-8
Encoding.default_internal = 'UTF-8' if defined? Encoding
gem 'test-unit', '>= 2' # necessary when not using bundle exec
require 'test/unit'
require 'nokogiri'
require 'redcarpet'
require 'redcarpet/render_strip'
require 'redcarpet/render_man'
require 'redcarpet/compat'
class Redcarpet::TestCase < Test::Unit::TestCase
def html_equal(html_a, html_b)
assert_equal Nokogiri::HTML::DocumentFragment.parse(html_a).to_html,
Nokogiri::HTML::DocumentFragment.parse(html_b).to_html
end
def assert_renders(html, markdown)
html_equal html, parser.render(markdown)
end
private
def parser
@parser ||= Redcarpet::Markdown.new(Redcarpet::Render::HTML)
end
end
|
class DocumentaryControl::BookWorksController < ApplicationController
before_filter :authenticate_user!, :only => [:index, :new, :create, :edit, :update ]
protect_from_forgery with: :null_session, :only => [:destroy, :delete]
def index
@type_book = TypeOfBookWork.where("cost_center_id = ?", get_company_cost_center('cost_center').to_s)
render layout: false
end
def show
@book = BookWork.find(params[:id])
render layout: false
end
def new
@cost_center = get_company_cost_center('cost_center')
@type_book = TypeOfBookWork.where("cost_center_id = ?", get_company_cost_center('cost_center').to_s)
@book = BookWork.new
render layout: false
end
def create
flash[:error] = nil
book = BookWork.new(book_parameters)
book.cost_center_id = get_company_cost_center('cost_center')
if book.save
flash[:notice] = "Se ha creado correctamente."
redirect_to :action => :index
else
book.errors.messages.each do |attribute, error|
puts flash[:error].to_s + error.to_s + " "
end
@book = book
render :new, layout: false
end
end
def edit
@book = BookWork.find(params[:id])
@cost_center = get_company_cost_center('cost_center')
@type_book = TypeOfBookWork.where("cost_center_id = ?", get_company_cost_center('cost_center').to_s)
@action = 'edit'
render layout: false
end
def update
book = BookWork.find(params[:id])
if book.update_attributes(book_parameters)
flash[:notice] = "Se ha actualizado correctamente los datos."
redirect_to :action => :index, company_id: params[:company_id]
else
book.errors.messages.each do |attribute, error|
flash[:error] = attribute " " + flash[:error].to_s + error.to_s + " "
end
# Load new()
@book = book
render :edit, layout: false
end
end
def destroy
book = BookWork.destroy(params[:id])
flash[:notice] = "Se ha eliminado correctamente."
render :json => book
end
def book_works
word = params[:wordtosearch]
@book = BookWork.where('name LIKE "%'+word.to_s+'%" OR description LIKE "%'+word.to_s+'%" OR date LIKE "'+word.to_s+'" AND cost_center_id = ?', get_company_cost_center('cost_center').to_s)
render layout: false
end
private
def book_parameters
params.require(:book_work).permit(:name, :description, :document, :date, :type_of_book_work_id)
end
end |
class Community < ApplicationRecord
include Postable
has_many :users, dependent: :destroy
belongs_to :creator, class_name: 'User'
has_one_attached :avatar
validates :name, presence: true
acts_as_followable
end
|
class CreateOpeningPlans < ActiveRecord::Migration
def change
create_table :opening_plans do |t|
t.references :organization, index: true
t.text :vision
t.text :name
t.text :description
t.date :publish_date
t.timestamps
end
end
end
|
class Doctor < ApplicationRecord
has_many :appointments, dependent: :destroy
has_many :patients, through: :appointments
def full_name
"#{self.first_name} #{self.last_name}"
end
end
|
class CreateBaliseffvls < ActiveRecord::Migration[6.1]
def change
create_table :baliseffvls do |t|
t.string :idBalise
t.string :nom
t.float :latitude
t.float :longitude
t.integer :altitude
t.string :departement
t.text :remarques
t.integer :decalageHoraire
t.string :struId
t.string :station_type
t.boolean :en_maintenance
t.string :url
t.string :url_histo
t.datetime :date
t.integer :vitesseVentMoy
t.integer :vitesseVentMax
t.integer :vitesseVentMin
t.integer :directVentMoy
t.integer :directVentInst
t.integer :temperature
t.integer :hydrometrie
t.integer :pression
t.integer :luminosite
t.integer :lum
t.string :address
t.timestamps
end
add_index :baliseffvls, :latitude
add_index :baliseffvls, :longitude
end
end
|
require 'rails_helper'
RSpec.describe ApplicationCable::Connection, type: :channel do
let(:username) { 'test' }
it "identifies current_user from cookies" do
connect cookies: { current_username: username }
expect(connection.current_user).to eq(username)
end
it "rejects unauthorized connection" do
expect {
connect
}.to have_rejected_connection
end
end
|
class AddVisibilityCreatedAtIndexOnPosts < ActiveRecord::Migration
def change
add_index :posts, [:visibility, :created_at]
end
end
|
class AddProviderToUserOauth < ActiveRecord::Migration
def change
add_column :user_oauth_tokens, :provider, :string
end
end
|
require 'rubylib/tcp_server'
require 'dist_server/server/message'
require 'dist_server/util/log'
class BaseServer < GameTCPServer
def initialize(server_info)
@server_info = server_info
super(server_info.name.nil? ? self.class.name : server_info.name)
end
def get_server_info
@server_info
end
def get_sender
Fiber.current.instance_variable_get('@sender')
end
def on_message(sender, message)
if self.respond_to?(message.method)
Fiber.current.instance_variable_set('@sender', sender)
ret = self.send(message.method, *message.params)
if message.need_return?
ret_msg = Message.create_return_pack(message, ret)
sender.send_pack(ret_msg.to_fs_pack)
end
else
FSLogger.get_logger(self).warn("%s could not found msg %s", self.name, message.method)
end
end
def wrap_client(node, klass)
end
def on_handle_pack(node_id, pack)
super
message = Message.create_from_pack(pack)
if message.is_return_package?
callback_id = message.get_callback_id
params = message.get_return_params
@clients[node_id].handle_return(callback_id, params)
else
if !@clients[node_id].on_message(@clients[node_id], message)
self.on_message( @clients[node_id], message)
end
end
end
end |
require "uri"
require "pincers/support/cookie_jar"
module Pincers::Support
class HttpClient
class HttpRequestError < StandardError
extend Forwardable
def_delegators :@response, :code, :body
attr_reader :response
def initialize(_response)
@response = _response
super _response.message
end
end
class MaximumRedirectsError < StandardError
def initialize
super 'Redirection loop detected!'
end
end
attr_reader :proxy_addr, :proxy_port, :cookies
def initialize(_options={})
if _options[:proxy]
@proxy_addr, @proxy_port = _options[:proxy].split ':'
end
@cookies = if _options[:cookies]
_options[:cookies].copy
else
CookieJar.new
end
@default_headers = _options[:headers]
end
def get(_url, _query={}, _headers={})
# TODO: append query string?
perform_request Net::HTTP::Get, URI(_url), _headers
end
def post(_url, _data, _headers={})
perform_request Net::HTTP::Post, URI(_url), _headers do |req|
req.body = prepare_data(_data)
end
end
def put(_url, _data, _headers={})
perform_request Net::HTTP::Put, URI(_url), _headers do |req|
req.body = prepare_data(_data)
end
end
def delete(_url)
perform_request Net::HTTP::Delete, URI(_url), _headers
end
private
def perform_request(_req_type, _uri, _headers, _limit=10)
raise MaximumRedirectsError.new if _limit == 0
request = _req_type.new(_uri.request_uri.empty? ? '/' : _uri.request_uri)
build_headers(request, _headers)
set_cookies(request, _uri)
yield request if block_given?
response = build_client(_uri).request request
case response
when Net::HTTPSuccess then
update_cookies(_uri, response)
response
when Net::HTTPRedirection then
location = response['location']
perform_request(_req_type, URI.parse(location), _headers, _limit - 1)
else
handle_error_response response
end
end
def build_client(uri)
client = Net::HTTP.new uri.host, uri.port || 80, proxy_addr, proxy_port
client.use_ssl = true if uri.scheme == 'https'
client.verify_mode = OpenSSL::SSL::VERIFY_NONE
client
end
def handle_error_response(_response)
raise HttpRequestError.new _response
end
def prepare_data(_data)
if _data.is_a? Hash
_data.keys.map { |k| "#{k}=#{_data[k]}" }.join '&'
else _data end
end
def build_headers(_request, _headers)
copy_headers _request, @default_headers if @default_headers
copy_headers _request, _headers
end
def set_cookies(_request, _uri)
_request['Cookie'] = @cookies.for_origin_as_header _uri
end
def update_cookies(_uri, _response)
cookies = _response.get_fields('set-cookie')
cookies.each { |raw| @cookies.set_raw _uri, raw } if cookies
end
def copy_headers(_request, _headers)
_headers.keys.each { |k| _request[k] = _headers[k] }
end
end
end |
module Net
RSpec.describe ICAPRequest do
let(:uri) { URI('icap://localhost/echo') }
it "creates a request with a method and path" do
request = ICAPRequest.new 'METHOD', false, uri
expect(request.method).to eq 'METHOD'
end
it "creates a request with a uri" do
request = ICAPRequest.new 'METHOD', false, uri
expect(request.uri).to eq uri
end
it "expects a response without a body" do
request = ICAPRequest.new 'METHOD', false, uri
expect(request.response_body_permitted?).to be_falsey
end
it "expects a response with a body" do
request = ICAPRequest.new 'METHOD', true, uri
expect(request.response_body_permitted?).to be_truthy
end
it "creates a request with a header" do
request = ICAPRequest.new 'METHOD', false, uri, { 'encapsulated' => 'req-hdr=0' }
expect(request['encapsulated']).to eq 'req-hdr=0'
end
it "can set an ICAP header" do
request = ICAPRequest.new 'METHOD', false, uri
request['encapsulated'] = 'res-body=0'
expect(request['encapsulated']).to eq 'res-body=0'
end
it "defaults header User-Agent to Ruby" do
request = ICAPRequest.new 'METHOD', false, uri
expect(request['user-agent']).to eq 'Ruby'
end
it "sets header Host from uri" do
request = ICAPRequest.new 'METHOD', false, uri
expect(request['host']).to eq 'localhost'
end
it "header Host includes hostname and non-default port" do
request = ICAPRequest.new 'METHOD', false, URI('icap://anyhost:1234/service')
expect(request['host']).to eq 'anyhost:1234'
end
it "parses Preview from header" do
request = ICAPRequest.new 'METHOD', false, uri, { 'preview' => '100' }
expect(request.preview).to eq 100
end
it "raises error when Preview is invalid" do
request = ICAPRequest.new 'METHOD', false, uri, { 'preview' => 'invalid' }
expect { request.preview }.to raise_error(Net::ICAPHeaderSyntaxError)
end
it "writes a simple header to the socket" do
request = ICAPRequest.new 'OPTIONS', false, uri
io = StringIO.new
request.send(:write_header, io)
expect(io.string).to eq "OPTIONS #{uri.to_s} ICAP/1.0\r\nHost: localhost\r\nUser-Agent: Ruby\r\n\r\n"
end
end
RSpec.describe ICAP::Options do
it "sets the request method to OPTIONS" do
request = ICAP::Options.new 'path'
expect(request.method).to eq 'OPTIONS'
end
end
RSpec.describe ICAP::Respmod do
it "sets the request method to RESPMOD" do
request = ICAP::Respmod.new 'path'
expect(request.method).to eq 'RESPMOD'
end
end
RSpec.describe ICAP::Reqmod do
it "sets the request method to REQMOD" do
request = ICAP::Reqmod.new 'path'
expect(request.method).to eq 'REQMOD'
end
end
end
|
require "rails_helper"
RSpec.describe Item, type: :model do
before do
@item = FactoryBot.build(:item)
end
describe '出品登録' do
context '新規登録できるとき' do
it 'image、name、price、description、condition_id、shipping_charge_id、prefecture_id、shipping_date_id、category_id、userが存在すれば登録できる' do
expect(@item).to be_valid
end
end
context '新規登録できないとき' do
it 'imageが空では登録できない' do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include("Image can't be blank")
end
end
it 'nameが空では登録できない' do
@item.name = ""
@item.valid?
expect(@item.errors.full_messages).to include("Name can't be blank")
end
it 'priceが空では登録できない' do
@item.price = nil
@item.valid?
expect(@item.errors.full_messages).to include("Price can't be blank")
end
it 'descriptionが空では登録できない' do
@item.description = ""
@item.valid?
expect(@item.errors.full_messages).to include("Description can't be blank")
end
it 'condition_idが空では登録できない' do
@item.condition_id = nil
@item.valid?
#binding.pry
expect(@item.errors.full_messages).to include("Condition can't be blank")
end
it 'shipping_charge_idが空では登録できない' do
@item.shipping_charge_id = nil
@item.valid?
expect(@item.errors.full_messages).to include("Shipping charge can't be blank")
end
it 'prefecture_idが空では登録できない' do
@item.prefecture_id = nil
@item.valid?
expect(@item.errors.full_messages).to include("Prefecture can't be blank")
end
it 'shipping_date_idが空では登録できない' do
@item.shipping_date_id = nil
@item.valid?
expect(@item.errors.full_messages).to include("Shipping date can't be blank")
end
it 'category_idが空では登録できない' do
@item.category_id = nil
@item.valid?
expect(@item.errors.full_messages).to include("Category can't be blank")
end
it 'category_idが0では登録できない' do
@item.category_id = 0
@item.valid?
expect(@item.errors.full_messages).to include("Category Select")
end
it 'condition_idが0では登録できない' do
@item.condition_id = 0
@item.valid?
expect(@item.errors.full_messages).to include("Condition Select")
end
it 'shipping_charge_idが0では登録できない' do
@item.shipping_charge_id = 0
@item.valid?
expect(@item.errors.full_messages).to include("Shipping charge Select")
end
it 'shipping_date_idが0では登録できない' do
@item.shipping_date_id = 0
@item.valid?
expect(@item.errors.full_messages).to include("Shipping date Select")
end
it 'priceが299円以下だと登録できない' do
@item.price = 299
@item.valid?
expect(@item.errors.full_messages).to include("Price must be greater than or equal to 300")
end
it 'priceが9,999,999円以上だと登録できない' do
@item.price = 10000000
@item.valid?
# binding.pry
expect(@item.errors.full_messages).to include("Price must be less than or equal to 9999999")
end
it 'priceが半角数字以外だと登録できない' do
@item.price = '111'
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it 'priceが半角数字と英字だと登録できない' do
@item.price = '111aaa'
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it 'priceが文字だけだと登録できない' do
@item.price = 'aaaa'
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
end
end |
require 'rails_helper'
RSpec.feature 'Visiting the schedule page', type: :feature do
before do
login_coach
visit 'schedule'
end
scenario 'it loads the schedule page' do
expect(current_path).to eq('/schedule')
end
scenario 'it displays the calendar' do
expect(page).to have_css('div.calendar-container')
end
end
RSpec.feature 'Creating a new event', type: :feature do
before do
login_athlete
visit 'schedule'
end
scenario 'the new event button triggers the new event modal' do
click_on 'New Event'
expect(page.find('#new-event')).not_to have_css('hidden')
end
end
|
require "English"
require "lucie/debug"
require "sub-process/io-handler-thread"
#
# Spawns a sub-process and registers handlers for standard IOs and
# process exit events.
#
class SubProcess::Shell # :nodoc:
include Lucie::Debug
#
# Calls the block passed as an argument with a new
# SubProcess::Shell object.
#
# _Example:_
# SubProcess::Shell.open do | shell |
# # Add some hooks here
# shell.on_...
# shell.on_...
# ...
#
# # Finally spawn a subprocess
# shell.exec command
# end
#
def self.open debug_options = {}, &block
block.call self.new( debug_options )
end
def initialize debug_options # :nodoc:
@debug_options = debug_options
end
#
# Returns the status code of the subprocess. The status code
# encodes both the return code of the process and information
# about whether it exited using the exit() or died due to a
# signal. Functions to help interpret the status code are defined
# in Process::Status class.
#
def child_status
$CHILD_STATUS
end
#
# Registers a block that is called when the subprocess outputs a
# line to standard out.
#
def on_stdout &block
@on_stdout = block
end
#
# Registers a block that is called when the subprocess outputs a
# line to standard error.
#
def on_stderr &block
@on_stderr = block
end
#
# Registers a block that is called when the subprocess exits.
#
def on_exit &block
@on_exit = block
end
#
# Registers a block that is called when the subprocess exits
# successfully.
#
def on_success &block
@on_success = block
end
#
# Registers a block that is called when the subprocess exits
# abnormally.
#
def on_failure &block
@on_failure = block
end
#
# Spawns a subprocess with specified environment variables.
#
def exec command, env = { "LC_ALL" => "C" }
return if dry_run
on_failure { raise "command #{ command } failed" } unless @on_failure
SubProcess::Process.new.popen SubProcess::Command.new( command, env ) do | stdout, stderr |
handle_child_output stdout, stderr
end.wait
handle_exitstatus
self
end
############################################################################
private
############################################################################
def handle_child_output stdout, stderr
tout = SubProcess::IoHandlerThread.new( stdout, method( :do_stdout ) ).start
terr = SubProcess::IoHandlerThread.new( stderr, method( :do_stderr ) ).start
tout.join
terr.join
end
# run hooks ################################################################
def handle_exitstatus
do_exit
if child_status.exitstatus == 0
do_success
else
do_failure
end
end
def do_stdout line
if @on_stdout
@on_stdout.call line
end
end
def do_stderr line
if @on_stderr
@on_stderr.call line
end
end
def do_failure
if @on_failure
@on_failure.call
end
end
def do_success
if @on_success
@on_success.call
end
end
def do_exit
if @on_exit
@on_exit.call
end
end
end
### Local variables:
### mode: Ruby
### coding: utf-8-unix
### indent-tabs-mode: nil
### End:
|
require "rails_helper"
describe Experimentation::Runner, type: :model do
describe ".call" do
before { Flipper.enable(:experiment) }
it "does not add patients, or create notifications if the feature flag is off" do
Flipper.disable(:experiment)
patient1 = create(:patient, age: 80)
create(:blood_sugar, patient: patient1, device_created_at: 100.days.ago)
experiment = create(:experiment, :with_treatment_group, experiment_type: "stale_patients")
create(:reminder_template, treatment_group: experiment.treatment_groups.first, message: "come today", remind_on_in_days: 0)
described_class.call
expect(experiment.patients.count).to eq(0)
expect(experiment.notifications.count).to eq(0)
end
it "calls conduct_daily on current and stale experiments with today's date" do
expect(Experimentation::CurrentPatientExperiment).to receive(:conduct_daily).with(Date.current)
expect(Experimentation::StalePatientExperiment).to receive(:conduct_daily).with(Date.current)
described_class.call
end
it "sends exceptions to Sentry and re-raises" do
exception = RuntimeError.new("bad things")
expect(Sentry).to receive(:capture_exception).with(exception)
expect(Experimentation::CurrentPatientExperiment).to receive(:conduct_daily).and_raise(exception)
expect {
described_class.call
}.to raise_error(exception)
end
end
end
|
class Admin::TasksController < Admin::ApplicationController
before_filter :setup_default_filter, only: :index
def index
@search = Task.search(params[:q])
search_result = @search.result(distinct: true)
@tasks = show_all? ? search_result : search_result.page(params[:page])
end
def show
@task = Task.find(params[:id])
end
def retry
@task = Task.find(params[:task_id])
@task.retry
redirect_to [:admin, @task]
end
def resolve
@task = Task.find(params[:task_id])
@task.resolve
redirect_to [:admin, @task]
end
def perform_callbacks
@task = Task.find(params[:task_id])
if @task.perform_callbacks!
redirect_to [:admin, @task]
else
redirect_to [:admin, @task], alert: @task.errors.full_messages.join("\n")
end
end
private
def setup_default_filter
params[:q] ||= {
state_in: ['failed'],
procedure_in: Task::PROCEDURES,
resource_type_in: Task.human_resource_types.map(&:last)
}
end
end
|
#-*- encoding : utf-8 -*-
default_environment["PATH"] = "/usr/local/rbenv/shims:/usr/local/rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"
set :application, "rails101_forum"
set :domain, "ec2-54-248-164-60.ap-northeast-1.compute.amazonaws.com"
set :repository, "git@github.com:maximx/rails101_forum.git"
set :deploy_to, "/home/apps/rails101_forum"
set :branch, "master"
set :scm, :git
set :user, "apps"
set :group, "apps"
set :deploy_to, "/home/apps/#{application}"
set :runner, "apps"
set :deploy_via, :remote_cache
set :git_shallow_clone, 1
set :use_sudo, false
role :web, "#{domain}"
role :app, "#{domain}"
role :db, "#{domain}", :primary => true
set :deploy_env, "production"
set :rails_env, "production"
set :scm_verbose, true
namespace :my_task do
task :symlink, :roles => [:web] do
run "mkdir -p #{deploy_to}/shared/log"
run "mkdir -p #{deploy_to}/shared/pids"
symlink_hash = {
"#{shared_path}/config/database.yml.production" => "#{release_path}/config/database.yml"
}
symlink_hash.each do |source, target|
run "ln -sf #{source} #{target}"
end
end
end
after "deploy:finalize_update", "my_task:symlink"
after "deploy:restart", "unicorn:restart"
|
#require 'spec_helper'
/
describe User do
it 'create an user' do #Teste unitário
user = User.new :name => 'Francieli', :email => 'francielifrv@gmail.com', :age => '20', :gender => User::FEMALE
user.save.should be_true
end
it 'Fail to create a user when name is blank' do
user = User.new :email => 'francielifrv@gmail.com', :age => '20'
user.save.should be_false
end
it 'Fail to create a user when email is blank' do
user = User.new :name => 'Francieli', :age => '20'
user.save.should be_false
end
it 'create an user with gender male' do #Teste unitário
user = User.new :name => 'José', :email => 'jose@gmail.com', :age => '20', :gender => User::MALE
user.save.should be_true
end
it 'create an user with gender female' do #Teste unitário
user = User.new :name => 'Maria', :email => 'maria@gmail.com', :age => '20', :gender => User::FEMALE
user.save.should be_true
end
context "When age >= 18 " do
it 'Creates user with gender value' do
user = User.new :name => 'Marta', :email => 'marta@gmail.com', :age => '23', :gender => User::FEMALE
user.save.should be_true
end
it 'Creates user without gender value' do
user = User.new :name => 'Marta', :email => 'marta@gmail.com', :age => '23'
user.save.should be_false
end
end
context "When age < 18" do
it 'Creates user with gender value' do
user = User.new :name => 'Marta', :email => 'marta@gmail.com', :age => '12', :gender => User::FEMALE
user.save.should be_true
end
it 'Creates user without gender value' do
user = User.new :name => 'Marta', :email => 'marta@gmail.com', :age => '12'
user.save.should be_true
end
end
it 'does not create two users wiht same email' do #Teste unitário
user = User.create :name => 'Francieli', :email => 'francielifrv@gmail.com', :age => '20', :gender => User::FEMALE
user = User.new :name => 'Francieli2', :email => 'francielifrv@gmail.com', :age => '20', :gender => User::FEMALE
user.save.should be_false
end
end
/ |
class User < ApplicationRecord
enum access_level: [:contractor, :company]
has_many :proposals, dependent: :destroy
has_many :submissions, dependent: :destroy
has_many :comments, dependent: :destroy
validates :user_name, presence: true, length: { minimum: 4, maximum: 16 }
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
#Paperclip shit
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/default-avatar.jpg"
end
|
#
# Cookbook:: yourls
# Attributes:: default
#
# Copyright:: 2018, Jailson Silva <jailson.silva@outlook.com.br>
#
# 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.
# Necessary package
default['yourls']['packages'] = %w(git curl)
# Repository and Tag version this project
default['yourls']['repo'] = 'https://github.com/YOURLS/YOURLS.git'
default['yourls']['tag_version'] = '1.7.2'
# Mysql Settings
default['yourls']['mysql']['db_user'] = nil
default['yourls']['mysql']['db_pass'] = nil
default['yourls']['mysql']['db_name'] = 'yourls'
default['yourls']['mysql']['db_host'] = 'localhost'
default['yourls']['mysql']['db_prefix'] = 'yourls_'
# Apache Confs
default['yourls']['conf']['doc_root'] = '/opt/yourls'
default['yourls']['conf']['server_name'] = 'yourls.com'
# Site Options
default['yourls']['conf']['hours_offset'] = '0'
# See http://yourls.org/translations
default['yourls']['conf']['lang'] = nil
default['yourls']['conf']['unique_urls'] = 'true'
default['yourls']['conf']['private'] = 'true'
default['yourls']['conf']['cookiekey'] = nil
# Debug mode to output some internal information
default['yourls']['conf']['debug'] = 'false'
# URL Shortening settings
default['yourls']['conf']['url_convert'] = '36' # or 62
default['yourls']['conf']['reserved_keywords'] = %w(porn faggot sex nigger fuck cunt dick)
# User config settings
default['yourls']['conf']['config_path'] = File.join(node['yourls']['conf']['doc_root'], '/user')
|
Pod::Spec.new do |spec|
spec.name = 'MMObjectModel'
spec.version = '0.0.1'
spec.summary = "Handy superclass for mapping JSON or XML data to model classes"
spec.homepage = "https://github.com/MacMannes/MMObjectModel"
spec.author = { "André Mathlener" => "info@macmannes.nl" }
spec.source = { :git => "https://github.com/MacMannes/MMObjectModel.git" }
spec.ios.deployment_target = '5.0'
spec.source_files = 'MMObjectModel/*.{h,m}'
spec.license = 'MIT'
spec.requires_arc = true
end
|
FactoryGirl.define do
sequence :url do |n|
"/path/#{n}"
end
factory :event do
url
user
end
end |
#
# Re-opening the item class to add some methods.
#
class Nanoc3::Item
def path
path = self.identifier.split('/')
path.delete('')
path
end
def title
t = self[:title]
return t.match(/^(.*) expression$/)[1] if self.path[0] == 'exp'
t
end
end
class SidebarFilter < Nanoc3::Filter
identifier :sidebar
def run (content, params)
items = if @item.path[0] == 'exp'
@items.select { |i| i.path[0] == 'exp' }
elsif @item.path[0] == 'part'
@items.select { |i| i.path[0] == 'part' }
else
@items.reject { |i|
i[:title].nil? ||
(
[ nil ] + %w[
css js ja images rel exp part
lists users download source resources presentations
documentation
]
).include?(i.path[0])
}
end
items = items.sort_by { |i| i[:side_title] || i[:title] }
head_item = if @item.path[0] == 'exp'
@items.find { |i| i.path.join('/') == 'expressions' }
elsif @item.path[0] == 'part'
@items.find { |i| i.path.join('/') == 'participants' }
else
nil
end
content.gsub(
'SIDEBAR',
render('sidebar', :items => items, :head_item => head_item))
end
end
|
class Front::ServicesController < FrontController
def index
@title = "Образы аниматоров на детский праздник | агентство Сказка Шоу"
@description = "Наши аниматоры могут перевоплотиться в любимые образы героев мультфильмов, сказок и фильмов ваших детей. Образы для малышей, детей от 5 до 7 лет и старше. Вы можете оставить заявку на проведение праздника в Москве с аниматорами на нашем сайте и по телефону: +7 (903) 130-36-64 "
@keywords = %w(образ детский аниматор заявка)
end
def show
end
end
|
class Blogger < ApplicationRecord
has_many :posts
has_many :destinations, through: :posts
end
|
require 'spec_helper'
describe 'appdynamics_agent::machine' do
on_supported_os(facterversion: '2.4').each do |os, os_facts|
context "on #{os}" do
let(:facts) { os_facts }
let(:params) do
{
'machine_path' => 'FOOBAR',
'machine_agent_file_32' => 'FOOBAR',
'machine_agent_file_64' => 'FOOBAR',
'controller_host' => 'FOOBAR',
'controller_port' => 'FOOBAR',
'unique_host_id' => 'FOOBAR',
'account_access_key' => 'FOOBAR',
'account_name' => 'FOOBAR',
}
end
it { is_expected.to compile }
end
end
end
|
#!/usr/bin/ruby
#
# Vagrant File for HBO | gotweb
# Provisioner: Salt
# OS: Ubuntu 12.04 LTS 64Bit
#
Vagrant.configure("2") do |config|
# Base Box - Hosted on S3
config.vm.box = "ubuntu_precise64_blank"
config.vm.box_url = "http://poke.vagrant.boxes.s3.amazonaws.com/ubuntu_precise64_blank.box"
#
# Port Forwarding / Assign static IP
#
# Nginx Port
config.vm.network :forwarded_port, guest: 80, host: 8080
# Ipython notebook
config.vm.network :forwarded_port, guest: 8888, host: 8888
config.vm.network :private_network, ip: "10.10.10.10"
#
# Virutalbox Settings - Remove this line if symlinks are not required
#
config.vm.provider :virtualbox do |v|
v.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/v-root", "1"]
end
#
# Synced Folders
#
# The Project Mount - This Directory
config.vm.synced_folder ".", "/home/vagrant/pokeradioholding", :nfs => true
# Project Salt Sates
config.vm.synced_folder "./salt", "/srv/salt"
# Poke Salt States
local_poke_states = File.join(File.expand_path('~'), '.salt-poke')
if File.directory?(local_poke_states)
config.vm.synced_folder local_poke_states, "/home/vagrant/.salt-poke"
else
abort("Please install the Poke Salt States.")
end
# Local Developer States - Not in version control, this is for the developer to manage, e.g Git / Vim Configs
# Developers should symlink this locally to ~/.salt-dev
local_developer_states = File.join(File.expand_path('~'), '.salt-dev')
if File.directory?(local_developer_states)
config.vm.synced_folder local_developer_states, "/home/vagrant/.salt-dev"
else
$stdout.write "Vagrant: Warning: You do not have any local states\n"
end
#
# Provisioner: Salt
#
config.vm.provision :salt do |s|
s.minion_config = "salt/config/minion.conf" # Where the minion config lives
s.install_type = "git"
s.install_args = "2014.7"
s.run_highstate = true # Always run the Salt Proviosining System
end
end
|
require 'test_helper'
class UserStoriesTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
fictures :products
test "buying a product" do
LineItem.delete_all
Order.delete_all
mcfarlane_figure = products(:ruby)
get "/"
assert_response :success
asser_template "index"
xml_http_request :post, '/line_items', product_id: mcfarlane_figure.id
assert_response :success
cart = Cart.find(session[:cart_id])
assert_equal 1, cart.line_items.size
assert_equal mcfarlane_figure, cart.line_items[0].product
get "/orders/new"
assert_response :success
assert_template "new"
post_via_redirect "/orders", order: { name: "Dave T", address: "52nd Ave", email: "mail@example.com", pay_type: "Visa" }
assert_response :success
asser_template "index"
cart = Cart.find(session[:cart_id])
assert_equal 0, cart.line_items.size
orders = Order.all
assert_equal 1, orders.size
order = orders[0]
assert_equal "Dave Thomas", order.name
assert_equal "52nd Ave", order.address
assert_equal "mail@example.com", order.email
assert_equal "Visa", order.pay_pal
assert_equal 1, order.line_items.size
line_item = order.line_items[0]
assert_equal mcfarlane_figure, line_item.product
mail = ActionMailer::Base.deliveries.last
assert_equal ["mail@example.com"], mail.to
assert_equal 'Sam Ruby <depot@example.com>', mail[:from].value
assert_equal "Order Confirmation", mail.subject
end
end
|
module BreadcrumbHelper
def render_breadcrumbs(type)
breadcrumbs = send("#{type}_breadcrumb")
# Don't link last item in breadcrumb
breadcrumbs.last[1] = nil
if breadcrumbs
render GovukComponent::Breadcrumbs.new(
breadcrumbs: breadcrumbs,
classes: "govuk-!-display-none-print",
)
end
end
def organisations_breadcrumb
@has_multiple_providers ? [["Organisations", providers_path]] : []
end
def provider_breadcrumb
path = provider_path(code: @provider.provider_code)
organisations_breadcrumb << [@provider.provider_name, path]
end
def recruitment_cycle_breadcrumb
if @provider.rolled_over?
path = provider_recruitment_cycle_path(@provider.provider_code, @recruitment_cycle.year)
provider_breadcrumb << [@recruitment_cycle.title, path]
else
provider_breadcrumb
end
end
def courses_breadcrumb
path = provider_recruitment_cycle_courses_path(@provider.provider_code)
recruitment_cycle_breadcrumb << ["Courses", path]
end
def course_breadcrumb
path = provider_recruitment_cycle_course_path(
@provider.provider_code,
course.recruitment_cycle_year,
course.course_code,
)
courses_breadcrumb << [course.name_and_code, path]
end
def sites_breadcrumb
path = provider_recruitment_cycle_sites_path(@provider.provider_code, @recruitment_cycle.year)
recruitment_cycle_breadcrumb << ["Locations", path]
end
def organisation_details_breadcrumb
path = details_provider_recruitment_cycle_path(@provider.provider_code, @recruitment_cycle.year)
recruitment_cycle_breadcrumb << ["About your organisation", path]
end
def users_breadcrumb
path = details_provider_recruitment_cycle_path(@provider.provider_code, @recruitment_cycle.year)
recruitment_cycle_breadcrumb << ["Users", path]
end
def edit_site_breadcrumb
path = edit_provider_recruitment_cycle_site_path(@provider.provider_code, @site.recruitment_cycle_year, @site.id)
sites_breadcrumb << [@site_name_before_update, path]
end
def new_site_breadcrumb
path = new_provider_recruitment_cycle_site_path(@provider.provider_code)
sites_breadcrumb << ["Add a location", path]
end
def ucas_contacts_breadcrumb
path = provider_ucas_contacts_path(@provider.provider_code)
provider_breadcrumb << ["UCAS contacts", path]
end
def training_providers_breadcrumb
path = training_providers_provider_recruitment_cycle_path(@provider.provider_code, @provider.recruitment_cycle_year)
provider_breadcrumb << ["Courses as an accredited body", path]
end
def training_provider_courses_breadcrumb
path = training_provider_courses_provider_recruitment_cycle_path(@provider.provider_code, @provider.recruitment_cycle_year, @training_provider.provider_code)
training_providers_breadcrumb << ["#{@training_provider.provider_name}’s courses", path]
end
def allocations_breadcrumb
path = provider_recruitment_cycle_allocations_path(@provider.provider_code, @provider.recruitment_cycle_year)
provider_breadcrumb << ["Request PE courses for #{next_allocation_cycle_period_text}", path]
end
def allocations_closed_breadcrumb
path = provider_recruitment_cycle_allocations_path(@provider.provider_code, @provider.recruitment_cycle_year)
provider_breadcrumb << ["PE courses for #{next_allocation_cycle_period_text}", path]
end
end
|
class Public::CartItemsController < ApplicationController
before_action :authenticate_customer!
def index
@tax = 1.08
@cart_items = current_customer.cart_items
@item_total = 0
@cart_items.each do |cart_item|
@item_total += cart_item.item.price * cart_item.count
end
end
def create # カートに入れるアクション
@item = Item.find(params[:item_id])
@cart_item = CartItem.new(cart_item_params)
@cart_item.customer_id = current_customer.id
@cart_item.item_id = @item.id
@cart_items = current_customer.cart_items.all
@cart_items.each do |cart_item|
if cart_item.item_id == @cart_item.item_id
new_quantity = cart_item.count + @cart_item.count
cart_item.update_attribute(:count, new_quantity)
@cart_item.delete
end
end
@cart_item.save
redirect_to public_cart_items_path
end
def update
cart_item = CartItem.find(params[:id])
cart_item.update(count: params[:cart_item][:count].to_i)
redirect_to public_cart_items_path
end
def empty
@cart_items = CartItem.where(customer_id: current_customer)
@cart_items.destroy_all
redirect_to public_cart_items_path
end
def destroy
@cart_item = CartItem.find(params[:id])
@cart_item.destroy
redirect_to public_cart_items_path
end
private
def cart_item_params
params.require(:cart_item).permit(:item_id, :count, :customer_id)
end
end |
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/methods'
describe "Time#zone" do
platform_is_not :windows do
# zone names not available on Windows w/o supplying zone offsets
it "returns the time zone abbreviation used for time" do
with_timezone("AST") do
Time.now.zone.should == "AST"
end
with_timezone("Asia/Kuwait") do
Time.now.zone.should == "AST"
end
end
end
it "returns the time zone abbreviation used for time" do
with_timezone("AST", 3) do
Time.now.zone.should == "AST"
end
end
it "returns UTC for utc times" do
with_timezone("AST", 3) do
Time.utc(2000).zone.should == "UTC"
end
end
end
|
class Category < ActiveRecord::Base
has_many :posts
validates_presence_of :name
end
|
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def input_to_index(index)
index=index.to_i-1
return index
end
def turn(board)
puts "Please enter 1-9:"
index=gets.strip
index=input_to_index(index)
value=valid_move?(board,index)
until value==true
puts "Please enter 1-9:"
index=gets.strip
index=input_to_index(index)
value=valid_move?(board,index)
end
move(board,index)
display_board(board)
end
# code your #valid_move? method here
def valid_move?(board,index)
if index.between?(0,8)==false
puts "invalid"
elsif position_taken?(board,index) == false
return true
else
puts "invalid"
end
end
# re-define your #position_taken? method here, so that you can use it in the #valid_move? method above.
def position_taken?(array,index_number)
if array[index_number] == ' '||array[index_number]==''||array[index_number]==nil
return false
else
return true
end
end
def move(board,index,position='X')
board[index]=position
end
|
# Match a private_ip_address line
class MatchesPrivateIpAddressLine
def self.===(item)
item.include?('private_ip_address')
end
end |
unless Kernel.respond_to?(:require_relative)
module Kernel
def require_relative(path)
require File.join(File.dirname(caller[0]), path.to_str)
end
end
end
case RUBY_PLATFORM
when /mingw|mswin/
@slash = "\\"
else
@slash = "/"
end
VERSION="2.0.4"
require 'rubygems'
require 'readline'
# CHECK FOR GEMS HACK METHOD
def gem_available?(name)
Gem::Specification.find_by_name(name)
rescue Gem::LoadError
puts "[*] - esearchy requires #{name}."
if RUBY_PLATFORM =~ /mingw|mswin/
system "gem install #{name}"
else
system "sudo gem install #{name}"
end
end
puts "-<[ ESearchy 0.3 CodeName Miata ]>-"
puts "-<[ Setup and Configurations script ]>-"
puts ""
puts "[*] - Missing Gem installation"
if RUBY_PLATFORM =~ /mingw|mswin/
puts "[*] - If windows need to install win32console Gem."
gem_available? 'win32console'
end
require_relative 'lib/esearchy/helpers/display.rb'
# MONGO METHODS
def mongo_download(os,platform)
case os
when /linux|osx/
Display.msg "Downloading mongodb-#{os}-#{platform}-#{VERSION}.tgz"
system("curl http://fastdl.mongodb.org/#{os}/mongodb-#{os}-#{platform}-#{VERSION}.tgz > external/mongodb.tgz")
when /win32/
Display.msg "Downloading mongodb-#{os}-#{platform}-#{VERSION}.zip"
system("external/tools/wget.exe -O external\\mongodb.zip http://fastdl.mongodb.org/#{os}/mongodb-#{os}-#{platform}-#{VERSION}.zip")
end
end
def mongo_install(os)
case os
when /linux|darwin/
Display.msg "Decompressing mongodb"
system("tar xzf external/mongodb.tgz -C external")
system("mv external/mongodb-* external/mongodb")
Display.msg "Removing downloaded file"
system("rm external/mongodb.tgz")
when /mingw|mswin/
Display.msg "Decompressing mongodb"
system("external/tools/unzip.exe external\\mongodb*.zip -d external")
system("move external\\mongodb-* external\\mongodb")
Display.msg "Removing downloaded file"
system("del external\\mongodb.zip")
end
end
def mongo_install_service
# runas /user:Administrator "external\mongodb\bin\mongod --install --dbpath=C:\Users\matt\.esearchy\data\db --logpath=C:\Users\matt\.esearchy\logs\mongodb.logs--logappend --serviceName=MONGODB"
mongod = "external/mongodb/bin/mongod --install"
dblogs = ENV['HOME'] + "/.esearchy/logs/mongodb.logs"
dbpath = ENV['HOME'] + "/.esearchy/data/db"
cmd = (mongod + " --dbpath=\"" + dbpath + "\" --logpath=\"" + dblogs + "\" --logappend --serviceName MONGODB").gsub("/",@slash)
system("external\\tools\\Elevate.exe " + cmd )
sleep(1)
rescue
Display.error "Something went wrong installing MongoDB as a service."
end
def mongo_install?
unless File.exists?((File.expand_path File.dirname(__FILE__) + "external").gsub("/",@slash))
system("mkdir external")
unless File.exists?((File.expand_path File.dirname(__FILE__) + "external/mongodb").gsub("/",@slash))
case RUBY_PLATFORM
when /linux/
Display.msg "IMPORTANT: curl must be installed and on $PATH."
RUBY_PLATFORM =~ /x86_64/ ?
mongo_download("linux", "x86_64") :
mongo_download("linux", "i686")
mongo_install("linux")
when /darwin/
RUBY_PLATFORM =~ /x86_64/ ?
mongo_download("osx", "x86_64") :
mongo_download("osx", "i386")
mongo_install("darwin")
when /mingw|mswin/
Display.msg "IMPORTANT: curl must be installed and on $PATH."
RUBY_PLATFORM =~ /x86_64/ ?
mongo_download("win32", "x86_64") :
mongo_download("win32", "i386")
mongo_install("mswin")
end
end
end
end
# CHECK FOR BASIC CONFIG STRUCTURE METHOD
# TODO: Might need to implement a few changes here for Windows.
def configure_esearchy
#Check & create folders
unless File.exists?((ENV["HOME"] + "/.esearchy").gsub("/",@slash))
Display.msg "Running for the first time."
Display.msg "Generating environment"
system(("mkdir " + ENV["HOME"] + "/.esearchy").gsub("/",@slash))
end
unless File.exists?((ENV["HOME"] + "/.esearchy/config").gsub("/",@slash))
File.open((ENV['HOME'] + "/.esearchy/config").gsub("/",@slash), "w" ) do |line|
# A few defaults. Although this can all be overwritten at runtime.
line << " { \"maxhits\" : 1000,\n"
line << " \"yahookey\" : \"AwgiZ8rV34Ejo9hDAsmE925sNwU0iwXoFxBSEky8wu1viJqXjwyPP7No9DYdCaUW28y0.i8pyTh4\",\n"
line << "\"bingkey\" : \"220E2E31383CA320FF7E022ABBB8B9959F3C0CFE\",\n"
line << "\"dburl\" : \"localhost\",\n"
line << "\"dbport\" : 27017,\n"
line << " \"dbname\" : \"esearchy\"\n,"
case RUBY_PLATFORM
when /linux|darwin/
line << " \"editor\" : \"vim\"\n"
when /mingw|mswin/
line << " \"editor\" : \"notepad.exe\"\n"
end
line << "}"
end
end
unless File.exists?((ENV["HOME"] + "/.esearchy/data").gsub("/",@slash))
system(("mkdir " + ENV["HOME"] + "/.esearchy/data").gsub("/",@slash))
unless File.exists?((ENV["HOME"] + "/.esearchy/data/db").gsub("/",@slash))
system(("mkdir " + ENV["HOME"] + "/.esearchy/data/db").gsub("/",@slash))
end
end
unless File.exists?((ENV["HOME"] + "/.esearchy/plugins").gsub("/",@slash))
system(("mkdir " + ENV["HOME"] + "/.esearchy/plugins").gsub("/",@slash))
end
unless File.exists?((ENV["HOME"] + "/.esearchy/logs").gsub("/",@slash))
system(("mkdir " + ENV["HOME"] + "/.esearchy/logs").gsub("/",@slash))
end
end
#gem_available? "sinatra"
gem_available? "mongo"
gem_available? "bson_ext"
gem_available? "mongo_mapper"
#gem_available? "restclient"
gem_available? 'json'
gem_available? 'zip'
#gem_available? 'uri'
#gem_available? 'pdf_reader'
gem_available? 'nokogiri'
gem_available? 'readline-history-restore'
gem_available? 'spidr'
Display.msg "Installing mongodb"
mongo_install?
Display.msg "Setup esearchy initial configuration"
configure_esearchy
if RUBY_PLATFORM =~ /mingw|mswin/
Display.msg "Installing mongodb as service"
mongo_install_service
end
|
require 'spec_helper'
describe "/judges/index.html.erb" do
include JudgesHelper
before(:each) do
assigns[:judges] = [
stub_model(Judge),
stub_model(Judge)
]
end
it "renders a list of judges" do
render
end
end
|
# encoding: utf-8
class InstallationPurchase < ActiveRecord::Base
attr_accessor :installation_name, :total
attr_accessible :installation_id, :applicant_id, :qty, :unit, :unit_price, :total, :for_what,
:part_name, :spec, :need_date,
:as => :role_new
attr_accessible :applicant_id, :qty, :unit, :unit_price, :total, :for_what, :need_date,
:part_name, :spec, :total_paid, :purchased, :qty_purchased, :qty_in_stock,
:storage_location,
:as => :role_update
attr_accessible :approved_by_vp_eng, :approve_vp_eng_id, :approve_date_vp_eng, :approved_by_ceo,
:approve_by_ceo_id, :approve_date_ceo,
:as => :role_approve
#has_and_belongs_to_many :categories
belongs_to :input_by, :class_name => 'User'
belongs_to :applicant, :class_name => 'User'
belongs_to :installation
has_many :installation_purchase_logs
validates :part_name, :presence => true, :uniqueness => {:case_sensitive => false}
validates :spec, :presence => true
validates :for_what, :presence => true
validates_numericality_of :installation_id, :greater_than => 0
validates_numericality_of :applicant_id, :greater_than => 0
validates_numericality_of :unit_price, :greater_than => 0
validates :need_date, :presence => true
validates :qty, :presence => true, :numericality => {:only_integer => true}
validates :qty_purchased, :numericality => {:only_integer => true }, :if => "purchased"
validates :unit, :presence => true
#validates :total, :presence => true
validates_numericality_of :qty_in_stock, :greater_than => 0, :only_integer => true, :if => "purchased"
validates_numericality_of :total_paid, :greater_than => 0, :if => "purchased"
end
|
# class Formtastic::SemanticFormBuilder
#
# def method_required_with_enquiry_form?(attribute)
# required_method = "#{attribute}_required?"
# if @object && @object.respond_to?(required_method)
# @object.send(required_method) || method_required_without_enquiry_form?(attribute)
# else
# method_required_without_enquiry_form?(attribute)
# end
# end
# alias_method_chain(:method_required?, :enquiry_form)
#
# end |
# encoding: utf-8
class MyApp < Sinatra::Application
post '/doubleclick' do
request.body.rewind
input = JSON.parse request.body.read.gsub('=>', ':')
logger.debug "Handling 'doubleclick' request."
clickId = input['conversion'][0]['clickId']
if clickId == 'goodclid_uno'
status 200
body "Success."
elsif clickId == 'want500'
status 200
body "Success."
elsif clickId == 'want500'
status 500
body "Dis is awful. Dis is just awful."
else
status 400
body "Womp womp, you fail."
end
end
post '/custom' do
request.body.rewind
input = JSON.parse request.body.read.gsub('=>', ':')
logger.debug "Handling 'custom' request."
status 200
body "success"
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
it "has the username set correctly." do
user = User.new username:"Pekka"
expect(user.username).to eq("Pekka")
end
it "is not saved without a password." do
user = User.create username:"Pekka"
expect(user).not_to be_valid
expect(User.count).to eq(0)
end
it "is not saved with too sort pasword." do
user = User.create username:"Pekka", password:"a", password_confirmation:"a"
expect(user).not_to be_valid
expect(User.count).to eq(0)
end
it "is not saved with pasword contaning only letters" do
user = User.create username:"Pekka", password:"letters", password_confirmation:"letters"
expect(user).not_to be_valid
expect(User.count).to eq(0)
end
describe "with a proper password" do
let(:user){ FactoryGirl.create(:user) }
it "is saved" do
expect(user).to be_valid
expect(User.count).to eq(1)
end
it "and with two ratings, has the correct average rating" do
user.ratings << FactoryGirl.create(:rating)
user.ratings << FactoryGirl.create(:rating2)
expect(user.ratings.count).to eq(2)
expect(user.average_rating).to eq(15.0)
end
end
describe "favorite beer" do
let(:user){FactoryGirl.create(:user) }
it "has method for determining one" do
user.should respond_to :favorite_beer
end
it "without ratings does not have one" do
expect(user.favorite_beer).to eq(nil)
end
it "is the only rated if only one rating" do
beer = FactoryGirl.create(:beer)
rating = FactoryGirl.create(:rating, beer:beer, user:user)
expect(user.favorite_beer).to eq(beer)
end
it "is the one with highest rating if several rated" do
create_beer_with_rating(10, user)
best = create_beer_with_rating(25, user)
create_beer_with_rating(7, user)
expect(user.favorite_beer).to eq(best)
end
end
describe "favorite style" do
let(:user){FactoryGirl.create(:user) }
let(:style){FactoryGirl.create(:style) }
let!(:style2) { FactoryGirl.create :style, name:"Porter" }
let!(:style3) { FactoryGirl.create :style, name:"IPA" }
it "has method for determining one" do
expect(user).to respond_to(:favorite_style)
end
it "without ratings does not have one" do
expect(user.favorite_style).to eq(nil)
end
it "is the style of the only rated if one rating" do
create_beers_with_ratings_and_style(10, style, user)
expect(user.favorite_style).to eq("Lager")
end
it "is the style with highest average rating if several rated" do
create_beers_with_ratings_and_style(10, 20, 15, style, user)
create_beers_with_ratings_and_style(35, style2, user)
create_beers_with_ratings_and_style(25, 20, 15, style3, user)
expect(user.favorite_style).to eq("Porter")
end
end
describe "favorite brewery" do
let(:user){FactoryGirl.create(:user) }
it "has method for determining one" do
expect(user).to respond_to(:favorite_brewery)
end
it "without ratings does not have one" do
expect(user.favorite_brewery).to eq(nil)
end
it "is the brewery of only rated if one rating" do
brewery = FactoryGirl.create(:brewery, name:"Koff")
create_beers_with_ratings_and_brewery(10, brewery, user)
expect(user.favorite_brewery).to eq(brewery)
end
it "is the brewery with highest average rating if several rated" do
plevna = FactoryGirl.create(:brewery, name:"Plevna")
create_beers_with_ratings_and_brewery(10, 20, 15, FactoryGirl.create(:brewery), user)
create_beers_with_ratings_and_brewery(35, plevna , user)
create_beers_with_ratings_and_brewery(25, 20, 15, FactoryGirl.create(:brewery), user)
expect(user.favorite_brewery).to eq(plevna)
end
end
describe "when one beer exists" do
let(:beer){FactoryGirl.create(:beer)}
it "is valid" do
expect(beer).to be_valid
end
it "has the default style" do
expect(beer.style.name).to eq("Lager")
end
end
end
|
Then /^I should see the hits metric for cinstance belonging to "([^"]*)"$/ do |buyer_name|
buyer_account = Account.find_by_org_name!(buyer_name)
metric = buyer_account.bought_cinstance.metrics.hits
selector = XPath.generate { |x| x.descendant(:div)[x.attr(:'data-metric') == metric.name ] }
should have_xpath(selector)
end
Then /^I should see a sparkline for "([^\"]*)"$/ do |metric|
within(".DashboardSection--audience") do
assert_selector 'div.Dashboard-chart'
end
end
Then /^I should see a chart called "([^\"]*)"$/ do |chart|
within("##{chart}") do
assert has_css?("svg")
end
end
Then /^I should see a list of metrics:$/ do |table|
table.hashes.each_with_index do |row, index|
within(".StatsSelector-container") do
assert_text :all, row['Buyer']
end
end
end
Then(/^I should see that application stats$/) do
page.should have_content "Traffic statistics for #{@application.name}"
end
And(/^I select (.+?) from the datepicker$/) do |date|
page.evaluate_script <<-JS
(function(){
var date = #{date.to_s.to_json}
$('#current-date').data('date', date)
Stats.SearchOptions.since = date
$('#submit-stats-search').click()
}());
JS
end
Then(/^the stats should load$/) do
page.should_not have_selector('.loading', visible: true)
end
|
require_relative 'reservable'
require_relative 'hotel'
module ReservationSystem
class Reservation
include Reservable
attr_reader :check_in, :nights, :dates_reserved, :room
def initialize(check_in_date, nights, room)
@check_in = check_in_date
@nights = nights
@room = room
@dates_reserved = date_range(check_in_date, nights)
@room.add_nights_reserved(check_in_date, nights)
end # initialize
def cost
cost = nights * room.rate
return cost
end # cost
end # Reservation class
end # ReservationSystem module
|
class GetBadgesService
def initialize(test_passage)
@test = test_passage.test
@user = test_passage.user
@test_passage = test_passage
end
def call
Badge.select do |badge|
rule = "reward_#{badge.rule}?"
send(rule)
end
end
private
def reward_first_try?
@test_passage.test_passed? && TestPassage.where(test: @test).count == 1
end
def reward_by_level?
test = Test.find_by(level: @test.level)
@test_passage.test_passed? && test.level == @test.level && Test.where(level: @test.level).count == completed_levels(@user, @test.level)
end
def reward_category?
category = Category.find_by(title: @test.category.title)
@test_passage.test_passed? && (category == @test.category) && (Test.where(category: category).count == completed_categories(@user, category))
end
def completed_categories(user, category)
user.test_passages.by_category(category).where(completed: true).group(:test).count.keys.size
end
def completed_levels(user, level)
user.test_passages.by_level(level).where(completed: true).group(:test).count.keys.size
end
end
|
class RubyGem < ActiveRecord::Base
#ask about where the dependent destory goes so if a
#gem is removed, the reviews are destroyed
has_many :reviews,
inverse_of: :ruby_gem,
dependent: :nullify
validates_presence_of :name
validates_uniqueness_of :name, :case_sensitive => false, message: 'already exists'
#evaluates 'devise' and 'Devise' as the same
def reviewed_by?(user)
reviews.pluck(:user_id).include?(user.id)
end
def review_sort
reviews.sort_by{ |review| "review.total_score DESC" }.reject{|review|review.id.nil?}
end
end
|
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def index #get, shows everything for the user
# render plain: "I'm in the index action!"
render json: User.all
end
def show #get Route parameters (e.g. the :id from /users/:id) # user have to specify to see the specific data entry
render json: User.find_by(id: params[:id])
end
def create #post
# # user = User.find_by(id: params[:id])
# user = User.new(user_params)
# if user.save
# # user.update(user_params)
# redirect_to user_url(user)
# else
# render json: user.errors.full_message, status:422
# end
# user = User.new(params.require(:user).permit(:name, :email))
# # replace the `user_attributes_here` with the actual attribute keys
# user.save!
# render json: user
# .require(:user)
user = User.new(params.require(:user).permit(:name, :email))
if user.save
render json: user
else
render json: user.errors.full_messages, status: :unprocessable_entity
end
end
def update #put/patch
user = User.find(params[:id])
if user.update_attributes(user_params)
render json: user
else
render json: user.errors, status: :unprocessable_entity
end
end
def destroy
user = User.find(params[:id])
user.destroy
render json: user
end
private
def user_params
params.require(:user).permit(:name, :email)
end
end |
# frozen_string_literal: true
module API
module Auth
extend ActiveSupport::Concern
included do
helpers do
AUTHENTICITY_TOKEN_LENGTH = 32
def session
env['rack.session']
end
def verified_request?
!protect_against_forgery? || request.head? ||
valid_authenticity_token?(session, request.headers['X-Csrf-Token']) ||
valid_authenticity_token?(session, request.headers['X-CSRF-Token'])
end
def protect_against_forgery?
allow_forgery_protection = Rails.configuration.action_controller.allow_forgery_protection
allow_forgery_protection.nil? || allow_forgery_protection
end
def valid_authenticity_token?(session, encoded_masked_token)
if encoded_masked_token.nil? || encoded_masked_token.empty? || !encoded_masked_token.is_a?(String)
return false
end
begin
masked_token = Base64.strict_decode64(encoded_masked_token)
rescue ArgumentError # encoded_masked_token is invalid Base64
return false
end
# See if it's actually a masked token or not. In order to
# deploy this code, we should be able to handle any unmasked
# tokens that we've issued without error.
if masked_token.length == AUTHENTICITY_TOKEN_LENGTH
# This is actually an unmasked token. This is expected if
# you have just upgraded to masked tokens, but should stop
# happening shortly after installing this gem
compare_with_real_token masked_token, session
elsif masked_token.length == AUTHENTICITY_TOKEN_LENGTH * 2
# Split the token into the one-time pad and the encrypted
# value and decrypt it
one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
csrf_token = xor_byte_strings(one_time_pad, encrypted_csrf_token)
compare_with_real_token csrf_token, session
else
false # Token is malformed
end
end
def compare_with_real_token(token, session)
ActiveSupport::SecurityUtils.secure_compare(token, real_csrf_token(session))
end
def real_csrf_token(session)
session[:_csrf_token] ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH)
Base64.strict_decode64(session[:_csrf_token])
end
def xor_byte_strings(s1, s2)
s2_bytes = s2.bytes
s1.each_byte.with_index { |c1, i| s2_bytes[i] ^= c1 }
s2_bytes.pack('C*')
end
end
end
end
end
|
Given(/^the web applications runs on Heroku$/) do
Capybara.current_driver = :selenium
Capybara.app_host = 'https://secret-chamber-2192.herokuapp.com'
end
When(/^I open the application url$/) do
visit(root_path)
end
Then(/^I must see the front page with application title "(.*?)"$/) do |title|
page.has_title? title
end
When(/^I press button "(.*?)"$/) do |button|
click_link_or_button(button)
end
Then(/^I must see the page with title "(.*?)"$/) do |title|
page.has_title? title
end
Then(/^I must be able to enter the following values:$/) do |table|
data = table.raw
data.each do |row|
fill_in(row[0], :with => row[1])
end
end
Then(/^I must see the original input data:$/) do |table|
data = table.raw
data.each do |row|
page.has_content?("#{row[0]} : #{row[1]}")
end
end
Then(/^list of stock values for each year:$/) do |table|
calculation_table_data = page.all('table#calculation-result td').map(&:text)
expect(calculation_table_data).to eq(table.raw.flatten)
end
Then(/^the stock growth is shown as a visual graph$/) do
expect(page).to have_selector('#stock-productivity-chart')
end
Then(/^the stock data must be saved into the database for later review$/) do
expect(Stock.count).to eq(1)
expect(CalculationParameter.count).to eq(1)
expect(CalculationResult.count).to eq(10)
expect(CalculationParameter.where(price: 2.00, quantity: 200, percentage: 3.0, period: 10 )).to exist
end
When(/^I click "(.*?)"$/) do |button|
click_link_or_button(button)
end
Given(/^the system has already calculated stocks$/) do |table|
table.hashes.each do |row|
visit(new_stock_input_path)
row.each do |key, value|
fill_in(key, :with => value)
end
click_link_or_button('Calculate')
end
end
Then(/^I must see a table of saved stocks:$/) do |table|
html_table_thead = page.all('table#calculated-stock th').map(&:text)
html_table_tbody = page.all('table#calculated-stock td').map(&:text)
expect(html_table_thead.concat(html_table_tbody)).to eq(table.raw.flatten)
end
When(/^I click on the calculated line "(.*?)"$/) do |stock_name|
click_link_or_button(stock_name)
end
Then(/^I must see the already calculated data$/) do
page.has_title? 'Calculation result'
end
|
module VieraPlay
class TV
def initialize(control_url)
@soap_client = Soapy.new(
:endpoint => control_url,
:namespace => "urn:schemas-upnp-org:service:AVTransport:1",
:default_request_args => {"InstanceID" => "0"}
)
end
def stop
send_command("Stop")
end
def pause
send_command("Pause")
end
def play
send_command("Play", "Speed" => "1")
end
def play_uri(uri)
stop
set_media_uri(uri)
play
end
private
attr_reader :soap_client
def set_media_uri(uri)
send_command(
"SetAVTransportURI",
"CurrentURI" => uri,
"CurrentURIMetaData" => ""
)
end
def send_command(command, args={})
soap_client.send_command(command, args)
end
end
end
|
class TaxAdvanceFinalTag < PayrollTag
def initialize
super(PayTagGateway::REF_TAX_ADVANCE_FINAL, PayConceptGateway::REFCON_TAX_ADVANCE_FINAL)
end
def deduction_netto?
true
end
end |
require "singleton"
module Service
#
# keeps a list of configuration files.
#
class ConfigManager
include Singleton
def initialize
@list = {}
end
def add service, path
@list[ service ] = path
end
def [] service
@list[ service ]
end
end
end
### Local variables:
### mode: Ruby
### coding: utf-8-unix
### indent-tabs-mode: nil
### End:
|
class ChangeTopic < ActiveRecord::Migration
def change
change_column_default :topics, :good, 0
change_column_default :topics, :bad, 0
end
end
|
class BookingsController < ApplicationController
def new
@flight = Flight.find_by(id: params['flight'])
@booking = Booking.new
params['passengers'].to_i.times { @booking.passengers.build }
end
def create
flight = Flight.find_by(id: params['flight'])
@booking = Booking.new(booking_params)
if @booking.save
@booking.passengers.each do |passenger|
PassengerMailer.thank_you_email(passenger, @booking).deliver_now!
end
redirect_to (@booking)
else
redirect_to '/'
end
end
def show
@booking = Booking.find_by(id: params['id'])
end
private
def booking_params
params.require(:booking).permit(:flight_id, passengers_attributes: [:id, :name, :email])
end
end |
log "
*****************************************
* *
* Recipe:#{recipe_name} *
* *
*****************************************
"
fslist=node[:clone12_2][:machprep][:newfs]
opts = "-Ayes -prw -a agblksize=4096 -a isnapshot=no"
#options for the file system creation
# for each quints, create the file system
#
fslist.each_slice(5) do | quints |
fs_mount, fs_size, vol_group, fs_log, fs_logsiz = quints
execute "make_filesystem_#{fs_mount}" do
user 'root'
group node[:root_group]
command "/usr/sbin/crfs -v jfs2 -g#{vol_group} -a size=#{fs_size} -m#{fs_mount} "\
"-a logname=#{vol_group}_loglv #{opts}"
not_if "lsfs #{fs_mount} | fgrep #{fs_mount} > /dev/null 2>&1"
end
execute "mount_the_fs_#{fs_mount}" do
user 'root'
group node[:root_group]
command "/usr/sbin/mount #{fs_mount}"
not_if "/usr/bin/df #{fs_mount} | grep -q #{fs_mount} > /dev/null 2>&1"
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
subject do
FactoryGirl.build(:user)
end
let(:user) do
User.new(
username: 'CalligraphyPuffin',
email: 'puffin@gmail.com',
encrypted_password: 'inkisawesome'
)
end
it { should have_valid(:username).when('sadusername') }
it { should_not have_valid(:username).when(nil, '') }
it { should have_valid(:email).when('sad@gmail.com') }
it { should_not have_valid(:email).when(nil, '') }
it { should have_valid(:encrypted_password).when('123456') }
it { should_not have_valid(:encrypted_password).when(nil, '') }
end
|
Sputnik::Application.routes.draw do
resources :users do
member do
get :following, :followers, :created, :participates
end
end
resources :microposts do
member do
get :detail
end
end
resources :polls do
member do
get :detail
end
end
resources :sessions, only: [:new, :create, :destroy]
resources :participations, only: [:create, :destroy]
resources :posts, only: [:create, :destroy]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :update, :destroy]
resources :password_resets
resources :proposals, only: [:create, :update, :destroy]
resources :polls, only: [:create, :update, :destroy]
resources :characteristics, only: [:create, :update, :destroy]
resources :characteristics_apps, only: [:create, :destroy]
resources :notifications, only: [:index]
root to: 'static_pages#home'
match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete
match '/help', to: 'static_pages#help'
match '/friend', to: 'static_pages#friend'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'
match '/terms', to: 'static_pages#terms_conditions'
match '/privacy', to: 'static_pages#privacy'
match '/search', to: 'static_pages#search'
match '/crop', to: 'static_pages#crop'
match '/crop/finish', to: 'static_pages#crop_finish'
match '/micropost/refresh', to: 'microposts#refresh'
match '/micropost/invite', to: 'microposts#invite'
match '/micropost/invite/emails', to: 'microposts#invite_emails'
match '/micropost/email/invite', to: 'invites#invite_redirect'
match '/post/refresh', to: 'posts#refresh'
match '/crop/image', to: 'static_pages#crop_image_render'
#Notification update unread to read
match '/notifications/update_read', to: 'notifications#update_read'
#Notification AJAX Update
match '/notifications/refresh', to: 'notifications#ajax_update'
#Mobile routes
match '/mobile/signin', to: 'sessions#create_mobile'
match '/mobile/signout', to: 'sessions#destroy_mobile'
match '/mobile/signup', to: 'users#create_mobile'
match '/mobile/post_refresh', to: 'posts#mobile_refresh'
match '/mobile/user', to: 'users#show_mobile'
match '/mobile/relationship_update', to: 'relationships#mobile_update'
match '/mobile/unfriend', to: 'relationships#mobile_destroy'
match '/mobile/location_autocomplete', to: 'google#place_autocomplete'
#match '/microposts/detail/:id', to: 'microposts#detail'
#Google routes
match '/google/places/autocomplete', to: 'google#places_autocomplete'
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end
|
class PaperSubmissionMailer < ActionMailer::Base
default from: "congressofaesf@gmail.com", :content_type => "text/html"
def send_confimation_paper_submission(paper_submission)
@paper_submission = paper_submission
mail(:to => @paper_submission.email, :subject => "Confirmacao de submissao de resumo.")
end
def send_accept_paper_submission(paper_submission)
@paper_submission = paper_submission
mail(:to => @paper_submission.email, :subject => "Resumo aceito nos Anais do VIII Congresso da FAESF.")
end
end
|
class ToDoList
attr_reader :list
attr_accessor :listname
def initialize(list = Array.new, listname = "Untitled list")
@list = list
@listname = listname
end
def check_item(index)
@list[index][0] = !@list[index][0]
end
def delete_item(index)
@list.delete_at(index)
end
def add_item(finished, item)
@list << [finished, item]
end
def is_done(index)
@list[index][0]
end
def update_item(index, message)
@list[index][1] = message
end
def get_item_string(index)
@list[index][1]
end
def list_count
@list.count
end
end |
# Fibonacci
# https://en.wikipedia.org/wiki/Fibonacci_number
# Fibonacci.new.calculate(input) #=> output
# input(Fn) -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8
# output −21 13 −8 5 −3 2 −1 1 0 1 1 2 3 5 8 13 21
require "minitest/autorun"
require "./fibonacci"
class TestFibonacci < Minitest::Test
def test_zero_to_one
assert_equal 0, subject.calculate(0)
assert_equal 1, subject.calculate(1)
end
def test_two_to_four
assert_equal 1, subject.calculate(2)
assert_equal 2, subject.calculate(3)
assert_equal 3, subject.calculate(4)
end
def test_large
assert_equal 5, subject.calculate(5)
assert_equal 144, subject.calculate(12)
end
def test_negative_one_to_negative_four
assert_equal 1, subject.calculate(-1)
assert_equal -1, subject.calculate(-2)
assert_equal 2, subject.calculate(-3)
assert_equal -3, subject.calculate(-4)
end
def test_large_negative
assert_equal 5, subject.calculate(-5)
assert_equal -21, subject.calculate(-8)
end
private
def subject
@subject ||= Fibonacci.new
end
end
|
require 'spec_helper'
describe SiteController do
describe "GET 'index'" do
it "returns http success" do
create :strip
get 'index'
response.should be_success
end
context 'assigns' do
let!(:strip){ create :strip }
it '@latest' do
get 'index'
assigns(:latest).should == strip
end
it '@count' do
get 'index'
assigns(:count).should == 1
end
end
end
end
|
# frozen_string_literal: true
require "factory_bot"
require "factory_bot_rails/generator"
require "factory_bot_rails/reloader"
require "rails"
module FactoryBotRails
class Railtie < Rails::Railtie
config.factory_bot = ActiveSupport::OrderedOptions.new
config.factory_bot.definition_file_paths = FactoryBot.definition_file_paths
initializer "factory_bot.set_fixture_replacement" do
Generator.new(config).run
end
initializer "factory_bot.set_factory_paths" do
FactoryBot.definition_file_paths = definition_file_paths
end
config.after_initialize do |app|
FactoryBot.find_definitions
Reloader.new(app).run
end
private
def definition_file_paths
config.factory_bot.definition_file_paths.map do |path|
Rails.root.join(path)
end
end
end
end
|
require 'rails_helper'
RSpec.describe SecureHeadersWhitelister do
describe '.extract_domain' do
def extract_domain(url)
SecureHeadersWhitelister.extract_domain(url)
end
it 'extracts the domain and port from a url' do
aggregate_failures do
expect(extract_domain('http://localhost:1234/foo/bar')).to eq('localhost:1234')
expect(extract_domain('https://example.com')).to eq('example.com')
expect(extract_domain('https://example.com/test')).to eq('example.com')
expect(extract_domain('https://example.com:1234')).to eq('example.com:1234')
end
end
end
end
|
module Spree
module Admin
class SizingGuidesController < ResourceController
def new
@sizing_guide = SizingGuide.new
@sizing_guide.build_sizing_guide_image
end
private
def permitted_sizing_guides_attributes
[:name, :description, :permalink, sizing_guide_image: [:attachment] ]
end
def find_resource
if parent_data.present?
parent.send(controller_name).friendly.find(params[:id])
else
model_class.friendly.find(params[:id])
end
end
end
end
end |
json.users do
json.array! @users do |user|
json.id user.id
json.name user.name
json.sleep_trackers user.sleep_trackers do |tracker|
json.id tracker.id
json.sleep_time tracker.sleep_time
json.waking_time tracker.waking_time
json.duration tracker.duration
end
end
end
json.total @total
|
class Neighborhood < ActiveRecord::Base
belongs_to :city
has_many :listings
has_many :reservations, through: :listings
def neighborhood_openings(start_date, end_date)
parsed_start = Date.parse(start_date)
parsed_end = Date.parse(end_date)
open_places = []
listings.each do |listing|
blocked = listing.reservations.any? do |reservation|
parsed_start.between?(reservation.checkin, reservation.checkout) || parsed_end.between?(reservation.checkin, reservation.checkout)
end
unless blocked
open_places << listing
end
end
open_places
end
def self.highest_ratio_res_to_listings
most_popular = Neighborhood.create(name: "There is no most popular neighborhood")
highest_ratio = 0
self.all.each do |neighborhood|
numerator = neighborhood.reservations.count
denominator = neighborhood.listings.count
if numerator == 0 || denominator == 0
next
else
ratio = numerator / denominator
if ratio >= highest_ratio
most_popular = neighborhood
highest_ratio = ratio
end
end
end
most_popular
end
def self.most_res
most_popular = Neighborhood.create(name: "There is no most popular neighborhood")
most_res = 0
self.all.each do |neighborhood|
res = neighborhood.reservations.count
if res >= most_res
most_res = res
most_popular = neighborhood
end
end
most_popular
end
end
|
# frozen_string_literal: true
require 'http/request'
require_relative '../client'
require_relative '../streaming/connection'
require_relative '../streaming/deleted_status'
require_relative '../streaming/message_parser'
require_relative '../streaming/response'
module Mastodon
module Streaming
# Streaming client class, to handle all streaming purposes.
class Client < Mastodon::Client
attr_writer :connection
# Initializes a new Client object
#
# @param options [Hash] A customizable set of options.
# @option options [String] :tcp_socket_class A class that Connection will
# use to create a new TCP socket.
# @option options [String] :ssl_socket_class A class that Connection will
# use to create a new SSL socket.
# @return [Mastodon::Streaming::Client]
def initialize(options = {})
super
options[:using_ssl] ||= base_url =~ /^https/
@connection = Streaming::Connection.new(options)
end
# Streams messages for a single user
#
# @yield [Mastodon::Status, Mastodon::Notification,
# Mastodon::Streaming::DeletedStatus] A stream of Mastodon objects.
def user(options = {}, &block)
stream('user', options, &block)
end
# Streams posts from the local instance
#
# @yield [Mastodon::Status, Mastodon::Notification,
# Mastodon::Streaming::DeletedStatus] A stream of Mastodon objects.
def local(options = {}, &block)
stream('public/local', options, &block)
end
# Returns statuses that contain the specified hashtag
#
# @yield [Mastodon::Status, Mastodon::Notification,
# Mastodon::Streaming::DeletedStatus] A stream of Mastodon objects.
def hashtag(tag, options = {}, &block)
options['tag'] = tag
stream('hashtag', options, &block)
end
# Returns local statuses that contain the specified hashtag
#
# @yield [Mastodon::Status, Mastodon::Notification,
# Mastodon::Streaming::DeletedStatus] A stream of Mastodon objects.
def local_hashtag(tag, options = {}, &block)
options['tag'] = tag
stream('hashtag/local', options, &block)
end
# Returns statuses from the specified list
#
# @yield [Mastodon::Status, Mastodon::Notification,
# Mastodon::Streaming::DeletedStatus] A stream of Mastodon objects.
def list(id, options = {}, &block)
options['list'] = id
stream('list', options, &block)
end
# Returns direct messages for the authenticated user
#
# @yield [Mastodon::Status, Mastodon::Notification,
# Mastodon::Streaming::DeletedStatus] A stream of Mastodon objects.
def direct(options = {}, &block)
stream('direct', options, &block)
end
# Returns all public statuses
#
# @yield [Mastodon::Status, Mastodon::Notification,
# Mastodon::Streaming::DeletedStatus] A stream of Mastodon objects.
def firehose(options = {}, &block)
stream('public', options, &block)
end
#
# Calls an arbitrary streaming endpoint and returns the results
# @yield [Mastodon::Status, Mastodon::Notification,
# Mastodon::Streaming::DeletedStatus] A stream of Mastodon objects.
def stream(path, options = {}, &block)
request(:get, "/api/v1/streaming/#{path}", options, &block)
end
# Set a Proc to be run when connection established.
def before_request(&block)
if block_given?
@before_request = block
self
elsif instance_variable_defined?(:@before_request)
@before_request
else
proc {}
end
end
private
def request(method, path, params)
before_request.call
uri = Addressable::URI.parse(base_url + path)
headers = Mastodon::Headers.new(self).request_headers
request = HTTP::Request.new(verb: method,
uri: "#{uri}?#{to_url_params(params)}",
headers: headers)
response = Streaming::Response.new do |type, data|
# rubocop:disable AssignmentInCondition
if item = Streaming::MessageParser.parse(type, data)
yield(item)
end
# rubocop:enable AssignmentInCondition
end
@connection.stream(request, response)
end
def to_url_params(params)
uri = Addressable::URI.new
uri.query_values = params
uri.query
end
end
end
end
|
require 'formula'
class Man2html < Formula
homepage 'http://www.oac.uci.edu/indiv/ehood/man2html.html'
url 'http://www.oit.uci.edu/indiv/ehood/tar/man2html3.0.1.tar.gz'
sha1 '18b617783ce59491db984d23d2b0c8061bff385c'
def install
bin.mkpath
man1.mkpath
system "/usr/bin/perl", "install.me", "-batch",
"-binpath", bin,
"-manpath", man
end
end
|
module ScheduleMixins
module Macros
def create_schedule(options={})
options[:users_count] ||= 1
let(:schedule) { create(:schedule_with_layers_and_users, options) }
let(:schedule_layer) { schedule.schedule_layers.first }
(1..options[:users_count]).each_with_index do |id, index|
let("user_#{id}") { schedule_layer.users[index] }
end
end
end
module Helpers
def now
Time.zone.now
end
end
end |
class Location < ApplicationRecord
has_and_belongs_to_many :courses
VALID_LOCATION = /\A[\d]{2}+\.[\d]{2}+\.[\d]{2}\z/
validates :name, presence: true, length: { is: 8, wrong_length: " min/max 8 character!" }, format: { with: VALID_LOCATION, message: " must be in format 00.00.00" }
end
|
require 'highline/import'
namespace :db do
desc "Anonymize your database"
task :anonymize => :environment do
DbTools::Anonymizer.execute
end
namespace :user do
desc "Change the password for an existing user"
task :password => :environment do
Spree::Setup.change_password
end
end
end
namespace :ssl do
desc "Disallow SSL"
task :disallow => :environment do
set_allow_ssl(false)
end
desc "Allow SSL"
task :allow => :environment do
set_allow_ssl(true)
end
def set_allow_ssl(allow_ssl)
if allow_ssl
say "SSL allowed"
else
say "SSL disallowed"
end
Spree::Config.set(:allow_ssl_in_production => allow_ssl)
Spree::Config.set(:allow_ssl_in_development_and_test => allow_ssl)
if !allow_ssl && 'production' == RAILS_ENV.downcase
say "\nWARNING: SSL is disallowed in production, this is not recommended\n\n"
end
end
end
desc "Make the current database ready for use in a non-production environment, normally used after importing a copy of the production database into a test database."
task :deprod do
Rake::Task["db:anonymize"].invoke
Rake::Task["ssl:disallow"].invoke
say "Any existing admin passwords have been reset, so you'll probably want to
set a new password for an admin user. Enter an admin user e-mail when prompted."
Rake::Task["db:user:password"].invoke
say "Deprod complete"
end
|
class Admin::CampaignsController < Admin::AdminController
before_action :set_campaign, only: %i[show edit update destroy]
after_action :verify_authorized
# GET /campaigns
# GET /campaigns.json
def index
@campaigns = Campaign.all
authorize @campaigns
end
# GET /campaigns/1
# GET /campaigns/1.json
def show; end
# GET /campaigns/new
def new
@campaign = Campaign.new
authorize @campaign
end
# GET /campaigns/1/edit
def edit; end
# POST /campaigns
# POST /campaigns.json
def create
@campaign = Campaign.new(campaign_params)
authorize @campaign
respond_to do |format|
if @campaign.save
format.html { redirect_to admin_campaign_path(@campaign), notice: 'Campaign was successfully created.' }
format.json { render :show, status: :created, location: @campaign }
else
format.html { render :new }
format.json { render json: @campaign.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /campaigns/1
# PATCH/PUT /campaigns/1.json
def update
respond_to do |format|
if @campaign.update(campaign_params)
authorize @campaign
format.html { redirect_to admin_campaign_path(@campaign), notice: 'Campaign was successfully updated.' }
format.json { render :show, status: :ok, location: @campaign }
else
format.html { render :edit }
format.json { render json: @campaign.errors, status: :unprocessable_entity }
end
end
end
# DELETE /campaigns/1
# DELETE /campaigns/1.json
def destroy
@campaign.destroy
respond_to do |format|
format.html { redirect_to admin_campaigns_url, notice: 'Campaign was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_campaign
@campaign = Campaign.friendly.find(params[:id])
authorize @campaign
end
# Never trust parameters from the scary internet, only allow the white list through.
def campaign_params
params.require(:campaign).permit(:name, :description, :status)
end
end
|
def fizzBuzz(num_range)
(num_range).each do |num|
if ( num % 3 == 0 ) && ( num % 5 == 0 )
print 'FizzBuzz'
elsif num % 3 == 0
print 'Fizz'
elsif num % 5 == 0
print 'Buzz'
else
print num
end
end
end
fizzBuzz(1..100) |
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :carts
after_create :create_cart
def create_cart
self.carts.build(state: 'open').save
end
end
|
require 'nokogiri'
class XcriCap
attr_reader :message, :contributor, :description, :provider_description, :provider_url, :provider_identifier, :provider_title, :course_title, :course_desc, :course_subject, :course_identifier, :course_type, :course_url, :course_abstract, :course_application_procedure
def initialize(id)
client = Savon::Client.new(wsdl: "http://www.hefty.ws/services/GetCourses?wsdl")
response = client.call(:get_course_by_id, message: { "courseid" => id })
#client = Savon::Client.new(wsdl: "http://www.webservicex.net/uszip.asmx?WSDL")
#response = client.request :web, :get_info_by_zip, body: { "USZip" => id }
#response = client.call(:get_info_by_zip, message: { "USZip" => id })
if response.success?
#data = response.to_array(:get_info_by_zip_response, :get_info_by_zip_result, :new_data_set, :table).first
data = response.to_hash[:catalog]#[:get_info_by_zip_result][:new_data_set][:table]
#provider = response.to_hash[:catalog][:provider]
courses = response.to_array(:catalog, :provider, :course)
#doc = response.doc
if data
@contributor = data[:contributor]
@description = data[:description]
@provider_description = data[:provider][:description]
@provider_url = data[:provider][:url]
@provider_identifier = data[:provider][:identifier]
@provider_title = data[:provider][:title]
#courses.each do |r|
if courses.empty?
@message = "No results returned."
else
if courses.count > 1
@message = "First of " + courses.count.to_s + " results."
@course_title = courses[0].to_hash[:title]
@course_type = courses[0].to_hash[:type]
@course_identifier = courses[0].to_hash[:identifier]
@course_subject = courses[0].to_hash[:subject]
@course_desc = courses[0].to_hash[:description]
@course_url = courses[0].to_hash[:url]
@course_abstract = courses[0].to_hash[:abstract]
@course_application_procedure = courses[0].to_hash[:applicationProcedure]
else
@message = "1 result."
@course_title = data[:provider][:course][:title]
@course_type = data[:provider][:course][:type]
@course_identifier = data[:provider][:course][:identifier]
@course_subject = data[:provider][:course][:subject]
@course_desc = data[:provider][:course][:description]
@course_url = data[:provider][:course][:url]
@course_abstract = data[:provider][:course][:abstract]
@course_application_procedure = data[:provider][:course][:applicationProcedure]
end
end
end
# else
# @message = "No results returned"
end
#doc.css('course').first do |co|
# @coursedesc = co.to_hash[:description]
#end
# end
# end
# end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.