text stringlengths 10 2.61M |
|---|
class Admin::JobFeesController < Admin::BaseController
authorize_resource :class => "JobFee"
# GET /admin/titles
def index
@job_fees = JobFee.all
end
# GET /admin/titles/1
def show
@job_fee = JobFee.find(params[:id])
end
# GET /admin/titles/new
def new
@job_fee = JobFee.new
end
# GET /admin/titles/1/edit
def edit
@job_fee = JobFee.find(params[:id])
end
# POST /titles
def create
@job_fee = JobFee.new(params[:job_fee])
if @job_fee.save
redirect_to(admin_job_fees_path, :notice => 'Job Fee was successfully created.')
else
render :action => "new"
end
end
# PUT /titles/1
def update
@job_fee = JobFee.find(params[:id])
if @job_fee.update_attributes(params[:job_fee])
redirect_to(admin_job_fees_path, :notice => 'Job Fee was successfully updated.')
else
render :action => "edit"
end
end
# DELETE /titles/1
def destroy
@job_fee = JobFee.find(params[:id])
@job_fee.destroy
redirect_to(admin_job_fees_path, :notice => 'Job Fee was successfully deleted.')
end
end
|
require_relative 'account'
class Statement
attr_accessor :summary
def initialize
@summary = []
end
def show
puts 'Date ||Deb/Cr||Amt||Bal||'
@summary.each do |line|
line.each do |x|
print x.to_s + "||"
end
print "\n"
end
end
end
|
class RemoveSeveralColumnsFromTalent < ActiveRecord::Migration[6.1]
def change
remove_column :talents, :intern
remove_column :talents, :grad_year
remove_column :talents, :institution
remove_column :talents, :level
remove_column :talents, :course
remove_column :talents, :entry_year
add_column :talents, :leadership, :string
end
end
|
require 'httparty'
require 'soda/client'
module RecordsHelper
attr_reader :hits
# SFGov Data - Currently set for 2017
def self.get_records
client = SODA::Client.new({:domain => "data.sfgov.org", :app_token => "YSf0ezIV7JKqotNR8TEexPqaL", :ignore_ssl => 'true'})
client.get("cuks-n6tp", {"$where" => "category = 'PROSTITUTION' AND date > '2015-12-31T00:00:00.000' or category = 'DRUG/NARCOTIC' AND date > '2015-12-31T00:00:00.000'"})
end
# https://data.sfgov.org/resource/cuks-n6tp.json
# "$limit" => 5,
# Crimespotting API, stopped updating 2015
# def self.get_records
# HTTParty.get ("http://sanfrancisco.crimespotting.org/crime-data?format=json&count=1000&type=Pr,Na&dstart=2013-01-01")
# end
@@hits = [/HALLUCINOGENIC/, /METH-AMPHETAMINE/, /MARIJUANA/, /PROSTITUTION/, /OPIATES/, /COCAINE/, /HEROIN/] #/PRESCRIPTION/
@@prostitution = [/PIMPING/, /PANDERING/, /INDECENT/, /LEWD/, /HOUSE/, /LOITERING/] #/SOLICITS/
def self.screen_records_for_input(record, array)
@@hits.each do |hit|
if record.descript =~ hit || record.category =~ /PROSTITUTION/
array << record
end
end
return array
end
def self.description(record, array)
# tag sales
if record.category =~ /PROSTITUTION/
record.sale = true
else
record.descript =~ /SALE/ ? record.sale = true : record.sale = false
end
# separate between cocaine and crack
if record.descript =~ /COCAINE/
if record.descript =~ /ROCK/
record.description = 'CRACK'
else
record.description = 'COCAINE'
end
#find the marijuana growers
elsif record.descript =~ /MARIJUANA/
if record.descript =~ /CULTIVATING/
record.description = 'GROWER'
else
record.description = 'MARIJUANA'
end
# break out prostitution charges
elsif record.category =~ /PROSTITUTION/
@@prostitution.each do |prostitution|
if record.descript =~ prostitution
record.description = prostitution.match(prostitution.to_s)[0]
end
end
# label all other charges.
else
@@hits.each do |hit|
if record.descript =~ hit
# record[:description] = 'test'
record.description = hit.match(hit.to_s)[0]
# record[:description].gsub(/''/, 'MARIJUANA')
end
end
end
array << record
return array
end
def self.create_params(record)
new_record = ActionController::Parameters.new(popo_id: record.incidntnum,
category: record.category,
description: record.description,
full_description: record.descript,
day_of_week: record.dayofweek,
district: record.pddistrict,
sale: record.sale,
lat: record.y,
long: record.x,
datetime: record.date
)
return new_record
end
end
|
# frozen_string_literal: true
# rubocop:todo all
# TODO convert, move or delete these tests as part of RUBY-2706.
=begin
require 'lite_spec_helper'
describe Mongo::Collection::View::Builder::FindCommand do
let(:client) do
new_local_client_nmio(['127.0.0.1:27017'])
end
let(:base_collection) { client['find-command-spec'] }
describe '#specification' do
let(:view) do
Mongo::Collection::View.new(base_collection, filter, options)
end
let(:builder) do
described_class.new(view, nil)
end
let(:specification) do
builder.specification
end
let(:selector) do
specification[:selector]
end
context 'when the options are standard' do
let(:filter) do
{ 'name' => 'test' }
end
let(:options) do
{
sort: { _id: 1 },
projection: { name: 1 },
hint: { name: 1 },
skip: 10,
limit: 20,
batch_size: 5,
single_batch: false,
comment: "testing",
max_scan: 200,
max_time_ms: 40,
max_value: { name: 'joe' },
min_value: { name: 'albert' },
return_key: true,
show_disk_loc: true,
snapshot: true,
tailable: true,
oplog_replay: true,
no_cursor_timeout: true,
await_data: true,
allow_partial_results: true,
collation: { locale: 'en_US' }
}
end
context 'when the operation has a session' do
let(:session) do
double('session')
end
let(:builder) do
described_class.new(view, session)
end
it 'adds the session to the specification' do
expect(builder.specification[:session]).to be(session)
end
end
it 'maps the collection name' do
expect(selector['find']).to eq(base_collection.name)
end
it 'maps the filter' do
expect(selector['filter']).to eq(filter)
end
it 'maps sort' do
expect(selector['sort']).to eq('_id' => 1)
end
it 'maps projection' do
expect(selector['projection']).to eq('name' => 1)
end
it 'maps hint' do
expect(selector['hint']).to eq('name' => 1)
end
it 'maps skip' do
expect(selector['skip']).to eq(10)
end
it 'maps limit' do
expect(selector['limit']).to eq(20)
end
it 'maps batch size' do
expect(selector['batchSize']).to eq(5)
end
it 'maps single batch' do
expect(selector['singleBatch']).to be false
end
it 'maps comment' do
expect(selector['comment']).to eq('testing')
end
it 'maps max scan' do
expect(selector['maxScan']).to eq(200)
end
it 'maps max time ms' do
expect(selector['maxTimeMS']).to eq(40)
end
it 'maps max' do
expect(selector['max']).to eq('name' => 'joe')
end
it 'maps min' do
expect(selector['min']).to eq('name' => 'albert')
end
it 'maps return key' do
expect(selector['returnKey']).to be true
end
it 'maps show record id' do
expect(selector['showRecordId']).to be true
end
it 'maps snapshot' do
expect(selector['snapshot']).to be true
end
it 'maps tailable' do
expect(selector['tailable']).to be true
end
it 'maps oplog_replay' do
expect(selector['oplogReplay']).to be true
end
it 'warns when using oplog_replay' do
client.should receive(:log_warn).with('oplogReplay is deprecated and ignored by MongoDB 4.4 and later')
selector
end
it 'maps no cursor timeout' do
expect(selector['noCursorTimeout']).to be true
end
it 'maps await data' do
expect(selector['awaitData']).to be true
end
it 'maps allow partial results' do
expect(selector['allowPartialResults']).to be true
end
it 'maps collation' do
expect(selector['collation']).to eq('locale' => 'en_US')
end
end
context 'when there is a limit' do
let(:filter) do
{ 'name' => 'test' }
end
context 'when limit is 0' do
context 'when batch_size is also 0' do
let(:options) do
{ limit: 0, batch_size: 0 }
end
it 'does not set the singleBatch' do
expect(selector['singleBatch']).to be nil
end
it 'does not set the limit' do
expect(selector['limit']).to be nil
end
it 'does not set the batch size' do
expect(selector['batchSize']).to be nil
end
end
context 'when batch_size is not set' do
let(:options) do
{ limit: 0 }
end
it 'does not set the singleBatch' do
expect(selector['singleBatch']).to be nil
end
it 'does not set the limit' do
expect(selector['limit']).to be nil
end
it 'does not set the batch size' do
expect(selector['batchSize']).to be nil
end
end
end
context 'when the limit is negative' do
context 'when there is a batch_size' do
context 'when the batch_size is positive' do
let(:options) do
{ limit: -1, batch_size: 3 }
end
it 'sets single batch to true' do
expect(selector['singleBatch']).to be true
end
it 'converts the limit to a positive value' do
expect(selector['limit']).to be(options[:limit].abs)
end
it 'sets the batch size' do
expect(selector['batchSize']).to be(options[:batch_size])
end
end
context 'when the batch_size is negative' do
let(:options) do
{ limit: -1, batch_size: -3 }
end
it 'sets single batch to true' do
expect(selector['singleBatch']).to be true
end
it 'converts the limit to a positive value' do
expect(selector['limit']).to be(options[:limit].abs)
end
it 'sets the batch size to the limit' do
expect(selector['batchSize']).to be(options[:limit].abs)
end
end
end
context 'when there is not a batch_size' do
let(:options) do
{ limit: -5 }
end
it 'sets single batch to true' do
expect(selector['singleBatch']).to be true
end
it 'converts the limit to a positive value' do
expect(selector['limit']).to be(options[:limit].abs)
end
it 'does not set the batch size' do
expect(selector['batchSize']).to be_nil
end
end
end
context 'when the limit is positive' do
context 'when there is a batch_size' do
context 'when the batch_size is positive' do
let(:options) do
{ limit: 5, batch_size: 3 }
end
it 'does not set singleBatch' do
expect(selector['singleBatch']).to be nil
end
it 'sets the limit' do
expect(selector['limit']).to be(options[:limit])
end
it 'sets the batch size' do
expect(selector['batchSize']).to be(options[:batch_size])
end
end
context 'when the batch_size is negative' do
let(:options) do
{ limit: 5, batch_size: -3 }
end
it 'sets the singleBatch' do
expect(selector['singleBatch']).to be true
end
it 'sets the limit' do
expect(selector['limit']).to be(options[:limit])
end
it 'sets the batch size to a positive value' do
expect(selector['batchSize']).to be(options[:batch_size].abs)
end
end
end
context 'when there is not a batch_size' do
let(:options) do
{ limit: 5 }
end
it 'does not set the singleBatch' do
expect(selector['singleBatch']).to be nil
end
it 'sets the limit' do
expect(selector['limit']).to be(options[:limit])
end
it 'does not set the batch size' do
expect(selector['batchSize']).to be nil
end
end
end
end
context 'when there is a batch_size' do
let(:filter) do
{ 'name' => 'test' }
end
context 'when there is no limit' do
context 'when the batch_size is positive' do
let(:options) do
{ batch_size: 3 }
end
it 'does not set the singleBatch' do
expect(selector['singleBatch']).to be nil
end
it 'does not set the limit' do
expect(selector['limit']).to be nil
end
it 'sets the batch size' do
expect(selector['batchSize']).to be(options[:batch_size])
end
end
context 'when the batch_size is negative' do
let(:options) do
{ batch_size: -3 }
end
it 'sets the singleBatch' do
expect(selector['singleBatch']).to be true
end
it 'does not set the limit' do
expect(selector['limit']).to be nil
end
it 'sets the batch size to a positive value' do
expect(selector['batchSize']).to be(options[:batch_size].abs)
end
end
context 'when batch_size is 0' do
let(:options) do
{ batch_size: 0 }
end
it 'does not set the singleBatch' do
expect(selector['singleBatch']).to be nil
end
it 'does not set the limit' do
expect(selector['limit']).to be nil
end
it 'does not set the batch size' do
expect(selector['batchSize']).to be nil
end
end
end
end
context 'when limit and batch_size are negative' do
let(:filter) do
{ 'name' => 'test' }
end
let(:options) do
{ limit: -1, batch_size: -3 }
end
it 'sets single batch to true' do
expect(selector['singleBatch']).to be true
end
it 'converts the limit to a positive value' do
expect(selector['limit']).to be(options[:limit].abs)
end
end
context 'when cursor_type is specified' do
let(:filter) do
{ 'name' => 'test' }
end
context 'when cursor_type is :tailable' do
let(:options) do
{
cursor_type: :tailable,
}
end
it 'maps to tailable' do
expect(selector['tailable']).to be true
end
it 'does not map to awaitData' do
expect(selector['awaitData']).to be_nil
end
end
context 'when cursor_type is :tailable_await' do
let(:options) do
{
cursor_type: :tailable_await,
}
end
it 'maps to tailable' do
expect(selector['tailable']).to be true
end
it 'maps to awaitData' do
expect(selector['awaitData']).to be true
end
end
end
context 'when the collection has a read concern defined' do
let(:collection) do
base_collection.with(read_concern: { level: 'invalid' })
end
let(:view) do
Mongo::Collection::View.new(collection, {})
end
it 'applies the read concern of the collection' do
expect(selector['readConcern']).to eq(BSON::Document.new(level: 'invalid'))
end
context 'when explain is called for the find' do
let(:collection) do
base_collection.with(read_concern: { level: 'invalid' })
end
let(:view) do
Mongo::Collection::View.new(collection, {})
end
it 'applies the read concern of the collection' do
expect( builder.explain_specification[:selector][:explain][:readConcern]).to eq(BSON::Document.new(level: 'invalid'))
end
end
end
context 'when the collection does not have a read concern defined' do
let(:filter) do
{}
end
let(:options) do
{}
end
it 'does not apply a read concern' do
expect(selector['readConcern']).to be_nil
end
end
end
end
=end
|
require 'station'
describe Station do
# let(:station) { double(:station, name: 'name', zone: 'zone') }
let(:name) { double(:name) }
let(:zone) { double(:zone) }
subject(:station) { described_class.new(name,zone) }
it { is_expected.to respond_to(:name) }
it { is_expected.to respond_to(:zone) }
describe '#initialize' do
it 'initializes with a name' do
expect(subject.name).to eq name
end
it 'initializes with a zone' do
expect(subject.zone).to eq zone
end
end
end |
module Dota
module API
class Match
class Draft < Entity
def order
raw["order"] + 1
end
def pick?
raw["is_pick"]
end
def team
raw["team"] == 0 ? :radiant : :dire
end
def hero
Hero.new(raw["hero_id"])
end
end
end
end
end
|
require_relative '../../test_helper'
require 'rake'
class LapisErrorCodeTest < ActiveSupport::TestCase
# Basic smoke test
def setup
Rake.application.rake_require("tasks/error_codes")
Rake::Task.define_task(:environment)
end
test "lapis:error_codes doesn't error when run, and outputs list to stdout" do
out, err = capture_io do
Rake::Task['lapis:error_codes'].execute
end
assert_match /UNAUTHORIZED: 1/, out
assert err.blank?
end
end
|
#!/usr/bin/env ruby
# Populate a file with a precise number of bytes
# MIT LICENCE
# Copyright 2013 NOCTURNAL CODE
#
# USAGE:
# pop <size>[B,KB,MB,GB,TB] <filename>
# Examples:
# pop 1MB oneMegFile.txt
# pop 1 oneByteFile.txt
# pop 5.5GB fiveAndAHalfGigFile.txt
def denomination_multiplier(unit)
# exponential = %w{B KB MB GB TB PB EB ZB YB}.index(unit.upcase) # probably don't need a YottaByte
exponential = %w{B KB MB GB TB}.index(unit.upcase)
exponential.nil? ? 1 : 1024 ** exponential # default to bytes if unrecogised unit
end
def usage
puts "USAGE: pop <size>[,B,KB,MB,GB,PB] <filename> [-t]"
puts ""
puts " -h: display this help text"
puts " -t: dummy test, don't write file"
puts ""
end
if ARGV[0] == "-h"
usage
exit 0
end
unless ARGV.length >= 1
usage
exit 1
end
size = ARGV[0]
filename = ARGV[1]
match = /(?<size>\d+\.?\d*)(?<denomination>\w*)/.match(size)
bytes = match[:size].to_f
bytes = (bytes * denomination_multiplier(match[:denomination])).to_i
File.open(filename,"w+") do |f|
f.write "a" * bytes
end unless ARGV[2] == "-t"
puts "Populated #{filename} with #{bytes} byte#{"s" unless bytes==1}"
|
class AuthorizationsController < ApplicationController
before_filter :require_user
# GET /authorizations
# GET /authorizations.json
def index
@authorizations = current_user.authorizations
respond_to do |format|
format.html # index.html.erb
format.json { render json: @authorizations }
end
end
# GET /authorizations/new
# GET /authorizations/new.json
def new
@services = Authorization.services.delete_if{|a|
current_user.authorizations.any?{|b|
b.auth_type.downcase==a.downcase
}}
respond_to do |format|
if !@services.empty?
format.html # show.html.erb
else
format.html{redirect_to authorizations_url, alert: "You can't create any more services"}
end
end
end
def callback
@services = Authorization.services.delete_if{|a|
current_user.authorizations.any?{|b|
b.auth_type.downcase==a.downcase
}}
case params[:provider]
when "google"
@authorization = GoogleAuth.new
when "foursquare"
@authorization = FoursquareAuth.new
when "instagram"
@authorization = InstagramAuth.new
when "twitter"
@authorization = TwitterAuth.new
@authorization.request_token({:request_token=>session[:request_token],
:request_secret => session[:request_secret]
})
when "facebook"
@authorization = FacebookAuth.new
end
@authorization.user=current_user
@authorization.params=params
respond_to do |format|
if @authorization.save!
format.html { redirect_to authorizations_url, notice: 'Authorization was successfully created.' }
else
format.html { render action: "new" }
end
end
end
# POST /authorizations
# POST /authorizations.json
def create
case params[:provider].downcase
when "google"
auth=GoogleAuth.new
when "instagram"
auth=InstagramAuth.new
when "foursquare"
auth = FoursquareAuth.new
when "twitter"
auth=TwitterAuth.new
request_token=auth.request_token
session[:request_token]=request_token.token
session[:request_secret]=request_token.secret
when "facebook"
auth=FacebookAuth.new
end
respond_to do |format|
format.html { redirect_to auth.access_url}
format.json { render json: @authorization }
end
end
# DELETE /authorizations/1
# DELETE /authorizations/1.json
def destroy
@authorization = Authorization.find(params[:id])
@authorization.destroy
respond_to do |format|
format.html { redirect_to authorizations_url }
format.json { head :no_content }
end
end
end
|
class User < ActiveRecord::Base
anonymizable public: true, raise_on_delete: true do
only_if :can_anonymize?
attributes :first_name,
:last_name,
:profile,
email: Proc.new { |u| "anonymized.user.#{u.id}@foobar.com" },
password: :random_password
associations do
anonymize :posts, :comments
delete :avatar, :likes
destroy :images
end
after :email_user, :email_admin
end
belongs_to :role
has_many :posts
has_many :comments
has_one :avatar, foreign_key: :profile_id
has_many :images
has_many :likes
def can_anonymize?
!role.admin?
end
def random_password
SecureRandom.hex.sub(/([a-z])/) { |s| s.upcase }
end
def email_user(original_attributes)
end
def email_admin(original_attributes)
end
end
|
module CourierFacility
module CommandPreprocessor
VALID_COMMANDS_WITH_ARGS = {
create_parcel_slot_lot: {
regex: /^create_parcel_slot_lot (?<required_rack_size>\d+)$/,
capture: [:required_rack_size]
},
park: {
regex: /^park (?<code>\d+) (?<weight>\d+)$/,
capture: [:code, :weight]
},
status: {
regex: /^status$/,
capture: []
},
delivery: {
regex: /^leave (?<slot_number>\d+) for delivery$/,
capture: [:slot_number]
},
parcel_code_for_parcels_with_weight: {
regex: /^parcel_code_for_parcels_with_weight (?<weight>\d+)$/,
capture: [:weight]
},
slot_numbers_for_parcels_with_weight: {
regex: /^slot_numbers_for_parcels_with_weight (?<weight>\d+)$/,
capture: [:weight]
},
slot_number_for_registration_number: {
regex: /^slot_number_for_registration_number (?<code>\d+$)/,
capture: [:code]
}
}.freeze
# ASSUMPTION: All the arguments are integer.
# To add other data type, we'll have to add data_type key along with each capture key in VALID_COMMANDS_WITH_ARGS
def preprocess_text_command(text)
# sanitize text command
input_command = format_text(text)
match_command, args = nil, {}
VALID_COMMANDS_WITH_ARGS.each do |command, hash|
match_data = hash[:regex].match(input_command)
unless match_data.nil?
match_command = command
hash[:capture].each {|key| args[key] = match_data[key].to_i}
break
end
end
{
command: match_command,
args: args
}
end
private
def format_text(text)
text.to_s.strip.gsub(/\s+/, ' ').downcase
end
end
end
|
require 'json'
require 'csv'
module CommonLib
module Json2csvHelper
include LogFactory
def json2csv input_data
@input_data = input_data
process_json
format_data
export_to_csv
end
def json2excel input_data
@input_data = input_data
process_json
format_data
[@headers, @constructed_array_of_rows]
end
# Processing json data
def process_json
@row_data = {}
@building_array_of_hashes = []
if @input_data.is_a? Array
@input_data.each {|row| process_row row}
elsif @input_data.is_a? Hash
process_row(@input_data)
end
end
# Inserting item
def insert_item key, value
@row_data[key] = value
end
# Inserting new line for every row
def insert_new_line depth
@building_array_of_hashes << @row_data
@row_data = {}
end
# Processing each row and inserting item
def process_row row
@depth = 0
row.each do |key, value|
check_type key, value, key, ''
end
end
# checking the type as Array or Hash or final key, value pair
def check_type key, value, row_key, new_ar_key_prepend
if value.is_a? Array
array_depth = @depth
value.each_with_index do |ele, index|
@depth = array_depth
new_ar_key = new_ar_key_prepend
insert_new_line @depth if index > 0
check_type key, ele, row_key, new_ar_key
end
elsif value.is_a? Hash
value.each do |key, value|
new_ar_key = "#{new_ar_key_prepend}__#{key}"
check_type key, value, row_key, new_ar_key
end
else
@depth = @depth + 1
insert_item row_key + new_ar_key_prepend, value
end
end
# Arranging data into rows
def format_data
@building_array_of_hashes << @row_data
@headers = []
@building_array_of_hashes.each do |data|
@headers = @headers | data.keys
end
@constructed_array_of_rows = []
@building_array_of_hashes.each do |data|
row = []
@headers.each do |key|
row << data[key] ? data[key] : ""
end
@constructed_array_of_rows << row
end
end
# Exporting data into csv
def export_to_csv
CSV.open('public/report_content.csv', 'w', write_headers: true, headers: @headers) do |csv|
@constructed_array_of_rows.each do |row|
csv << row
end
end
end
end
end |
# frozen_string_literal: true
# Always allow requests from localhost
# (blocklist & throttles are skipped)
Rack::Attack.safelist('allow from localhost') do |req|
# Requests are allowed if the return value is truthy
'127.0.0.1' == req.ip || '::1' == req.ip
end
# Allow an IP address to make 10 requests every 10 seconds
Rack::Attack.throttle('req/ip', limit: 5, period: 5) do |req|
req.ip
end
|
# Fact Types Controller: JSON response through Active Model Serializers
class Api::V1::FactTypesController < MasterApiController
respond_to :json
def index
render json: FactType.all
end
def show
render json: factType
end
def create
render json: FactType.create(factType_params)
end
def update
render json: factType.update(factType_params)
end
def destroy
render json: factType.destroy
end
private
def factType
FactType.find(params[:id])
end
def factType_params
params.require(:data).require(:attributes).permit(:fact_type).permit(:name, :posts_count, :eligibility_counter)
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
require 'open-uri'
require 'pry'
BASE_URL = "http://api.seatgeek.com/2/events"
QUERY = "?geoip=true&per_page=100&range=25mi&page=1&taxonomies.name=concert"
hash = JSON.load(open(BASE_URL+QUERY))
def create_event(event_hash)
Event.create(seat_geek_id: event_hash["id"],
listing_count: event_hash["stats"]["listing_count"],
average_price: event_hash["stats"]["average_price"],
lowest_price: event_hash["stats"]["lowest_price"],
highest_price: event_hash["stats"]["highest_price"],
title: event_hash["title"],
datetime_local: event_hash["datetime_local"])
end
def create_artist(artist_hash)
Artist.create(event_count: artist_hash["stats"]["event_count"],
name: artist_hash["name"],
seat_geek_id: artist_hash["id"])
end
def create_venue(venue_hash)
Venue.create(city: venue_hash["city"],
name: venue_hash["name"],
extended_address: venue_hash["extended_address"],
display_location: venue_hash["display_location"],
state: venue_hash["state"],
postal_code: venue_hash["postal_code"],
longitude: venue_hash["location"]["lon"],
latitude: venue_hash["location"]["lat"],
address: venue_hash["address"],
seat_geek_id: venue_hash["id"])
end
def create_genre(name)
Genre.create(name: name)
end
hash["events"].each do |event_hash|
new_event = create_event(event_hash)
new_venue = create_venue(event_hash["venue"])
new_event.venue = new_venue
new_venue.save
new_event.save
event_hash["performers"].each do |artist|
new_artist = create_artist(artist)
new_event.artists << new_artist
# associate events and artists
if artist["genres"]
artist["genres"].each do |genre|
new_artist.genres << create_genre(genre["name"])
#associate genres and artists
end
end
end
end
|
Koala.configure do |config|
config.access_token = Rails.application.secrets.koala_access_token
end
|
module Humble
class Configuration
attr_reader :connection_string
def initialize(connection_string, table_builder = MappingConfigurationBuilder.new)
@mapping_configurations = []
@connection_string = connection_string
@table_builder = table_builder
end
def add(mapping)
@mapping_configurations.push(MappingConfiguration.new(@table_builder.build(mapping), self))
end
def build_session_factory
SessionFactory.new(self)
end
def mapping_for(item)
@mapping_configurations.find do |mapping|
mapping.matches?(item)
end
end
end
end
|
class AddColumnEquipmentToStockInputDetails < ActiveRecord::Migration
def change
add_reference :stock_input_details, :article, index: true
add_column :stock_input_details, :equipment_id, :integer
end
end
|
# cf) https://github.com/sstephenson/ruby-build/wiki#suggested-build-environment
case node[:platform]
when "debian", "ubuntu"
package "autoconf"
package "bison"
package "build-essential"
package "libssl-dev"
package "libyaml-dev"
package "libreadline6-dev"
package "zlib1g-dev"
package "libncurses5-dev"
package "libffi-dev"
package "libgdbm3"
package "libgdbm-dev"
package "libffi-dev"
when "redhat", "fedora"
# redhat is including CentOS
package "gcc"
package "openssl-devel"
package "libyaml-devel"
package "libffi-devel"
package "readline-devel"
package "zlib-devel"
package "gdbm-devel"
package "ncurses-devel"
package "libffi-devel"
else
# for backward compatibility (<= v0.2.1)
package "libffi-devel"
package "openssl-devel"
package "readline-devel"
end
package "git"
scheme = "git"
scheme = node[:rbenv][:scheme] if node[:rbenv][:scheme]
require "itamae/plugin/recipe/rbenv"
git rbenv_root do
repository "#{scheme}://github.com/sstephenson/rbenv.git"
end
git "#{rbenv_root}/plugins/ruby-build" do
repository "#{scheme}://github.com/sstephenson/ruby-build.git"
if node[:'ruby-build'] && node[:'ruby-build'][:revision]
revision node[:'ruby-build'][:revision]
end
end
git "#{rbenv_root}/plugins/rbenv-gem-rehash" do
repository "#{scheme}://github.com/sstephenson/rbenv-gem-rehash.git"
if node[:'rbenv-gem-rehash'] && node[:'rbenv-gem-rehash'][:revision]
revision node[:'rbenv-gem-rehash'][:revision]
end
end
git "#{rbenv_root}/plugins/rbenv-default-gems" do
repository "#{scheme}://github.com/sstephenson/rbenv-default-gems.git"
if node[:'rbenv-default-gems'] && node[:'rbenv-default-gems'][:revision]
revision node[:'rbenv-default-gems'][:revision]
end
end
if node[:'rbenv-default-gems'] && node[:'rbenv-default-gems'][:'default-gems']
file "#{rbenv_root}/default-gems" do
content node[:'rbenv-default-gems'][:'default-gems'].join("\n") + "\n"
mode "664"
end
end
node[:rbenv][:versions].each do |version|
execute "rbenv install #{version}" do
command "#{rbenv_init} rbenv install #{version}"
not_if "#{rbenv_init} rbenv versions | grep #{version}"
end
end
node[:rbenv][:global].tap do |version|
execute "rbenv global #{version}" do
command "#{rbenv_init} rbenv global #{version}"
not_if "#{rbenv_init} rbenv version | grep #{version}"
end
end
|
# This class is used to parse products that need to have their prices removed.
# i.e. they are no longer appearing the social commerce feed. We don't delete
# the product since reviews might be attached.
#
# Usage: Mysears::SocComRemoveParser.new('/some/path/to/remove.txt').parse
module Mysears
class SocComRemoveParser
def initialize(file, source, pid_length)
@file = file
@source = source
@pid_length = pid_length
end
def parse
@total = @successes = @errors = @skipped = 0
logger.info "SocComRemoveParser: parsing file #{@file}"
File.open(@file) do |io|
io.each_line do |line|
process_line(line)
end
end
logger.info "SocComRemoveParser: finished #{@file}"
logger.info "SocComRemoveParser: total seen: #{@total}"
logger.info "SocComRemoveParser: successes: #{@successes}"
logger.info "SocComRemoveParser: skipped: #{@skipped}"
logger.info "SocComRemoveParser: errors: #{@errors}"
end
private
def process_line(line)
begin
@total += 1
partner_key = SocComParser.parse_key_from_link(line, @source, @pid_length)
pp = PartnerProduct.find_by_source_id_and_partner_key(@source.id, partner_key)
if pp && !pp.prices.empty?
Price.destroy(pp.prices)
@successes += 1
else
@skipped += 1
end
rescue Exception => ex
logger.info "SocComRemoveParser: #{ex}:\n#{line}\n#{ex.backtrace.join("\n")}"
@errors += 1
end
end
def logger
RAILS_DEFAULT_LOGGER
end
end # of class SocComRemoveParser
end # of module Mysears
|
class AdminController < ApplicationController
layout 'admin'
before_filter :require_admin
def require_admin
unless user_signed_in?
redirect_to new_user_session_path
end
end
end |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_cart
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
Cart.new
end
end
|
class Event < ApplicationRecord
belongs_to :nightclub
belongs_to :user
has_many :images
has_many :tweets
has_many :organizers
has_many :artist_identifyings
has_many :artists, through: :artist_identifyings
has_one :publishing, dependent: :destroy
delegate :name, prefix: true, to: :nightclub
validates :name, :tag, :start_at, :end_at, presence: true
def total_count
Event.published.count
end
scope :published, -> do
joins(:publishing)
end
scope :unpublished, -> do
left_joins(:publishing)
.where(publishing: { id: nil })
end
scope :archived, -> do
where(arel_attribute(:end_at).lt Time.zone.now)
end
scope :scheduled, -> do
where(arel_attribute(:start_at).gt Time.zone.now)
end
scope :featured, -> do
where(arel_attribute(:end_at).gt Time.zone.now).where(arel_attribute(:start_at).lt Time.zone.now)
end
end
|
# coding: utf-8
require 'fibonacci_rng'
require 'composite_rng'
#* generator.rb -- The internal pseudo-random number generator.
class Mystiko
#A specialized variant of the composite pseudo RNG.
class Generator < CompositeRng
#Create the default pseudo random data generator.
#<br> Endemic Code Smells
#* :reek:FeatureEnvy
def initialize(key)
parent = FibonacciRng.new(key)
child = Random.new(parent.hash_value)
super(parent, child, 31, 31)
end
end
end
|
#!/usr/bin/env ruby
def execute
if ARGV.empty?
wrong_args_message
else
parse_args
end
end
def wrong_args_message
end
execute
|
require "integration_helper"
describe "deletion" do
include_context "orm"
context "when deleting a record" do
before :each do
connection[:movies].insert(:name => 'mo money')
movie = session.find_all(Movie).first
session.delete(movie)
end
it "should remove it from the database" do
connection[:movies].all.count.should == 0
end
end
end
|
require 'spec_helper'
describe EventsController do
def mock_event(stubs={})
(@mock_event ||= mock_model(Event).as_null_object).tap do |event|
event.stub(stubs) unless stubs.empty?
end
end
describe "GET show" do
it "assigns the requested event as @event" do
Event.stub(:find).with("37") { mock_event }
get :show, :id => "37"
assigns(:event).should be(mock_event)
end
end
end
|
require 'spec_helper'
describe Boxzooka::Item do
let(:item) { described_class.new(ucc: ucc) }
let(:ucc) { 12345678 }
describe 'serialization' do
subject { Boxzooka::Xml.serialize(item) }
it 'should capitalize UCC' do
expect(subject).to include("<UCC>#{ucc}</UCC>")
end
end
end
|
class ClientesController < ApplicationController
before_action :authenticate_user!
before_action :set_cliente, only: [:show, :edit, :update, :destroy]
# GET /clientes
def index
filter = ["0=0"]
if params.has_key?("nome")
if !params[:nome].blank?
nome = params[:nome]
filter << [" nome like '%#{nome}%'"]
end
if !params[:cpf_cnpj].blank?
doc = params[:cpf_cnpj]
filter << [ "nr_cpf_cnpj like '%#{doc}%'"]
end
end
@clientes = Cliente.where(filter.join(" And ")).paginate(:page => params[:page], :per_page =>8 )
end
# GET /clientes/1
def show
@contratos = Cliente.find(params[:id]).contratos
end
# GET /clientes/new
def new
@cliente = Cliente.new
end
# GET /clientes/1/edit
def edit
@cliente.updated_by = current_user.username
end
# POST /clientes
def create
@cliente = Cliente.new(cliente_params)
@cliente.created_by = current_user.username
@cliente.updated_by = current_user.username
if @cliente.save
redirect_to @cliente, notice: 'Cliente foi criado com sucesso.'
else
render :new
end
end
# PATCH/PUT /clientes/1
def update
@cliente.updated_by = current_user.username
if @cliente.update(cliente_params)
redirect_to @cliente, notice: 'Cliente foi alterado com sucesso.'
else
render :edit
end
end
# DELETE /clientes/1
def destroy
@cliente.destroy
redirect_to clientes_url, notice: 'Cliente foi eliminado com sucesso.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cliente
@cliente = Cliente.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def cliente_params
params.require(:cliente).permit(:nome, :dt_nascimento, :nr_documento, :tp_documento, :nr_cpf_cnpj, :rua, :numero, :bairro, :cidade, :uf, :cep, :obs, :created_by, :updated_by)
end
def set_lists
@UFs = ["AC","AL","AM","AP","BA","CE","DF","ES","GO","MA","MG","MS","MT","PA","PB","PE",
"PI","PR","RJ","RN","RO","RR","RS","SC","SE","SP","TO"]
end
end
|
class UsersController < ApplicationController
before_filter :save_login_state, :only => [:new, :create]
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "Cuenta creada!"
redirect_to root_path
else
render 'new'
end
end
def profile
unless session[:user_id]
#si no hay session de user lo envio a login y guardo la url (profile) para enviarlo al ingresar
store_location
redirect_to login_path
else
@user = User.find(session[:user_id])
end
end
def update
@user = User.find(session[:user_id])
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to profile_path, notice: 'account was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "profile" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
def destroy
@user = User.find(params[:id])
respond_to do |format|
if @user.destroy
format.html { redirect_to users_path, notice: 'account was successfully updated.' }
format.json { head :ok }
else
format.html { redirect_to 'users' }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
end
|
class CardsController < ApplicationController
before_action :find_card, only: [:edit, :update, :destroy]
def index
@deck = current_user.decks.find(params[:deck_id])
render 'decks/show'
end
def new
@card = current_user.cards.new(deck_id: params[:deck_id])
end
def create
@card = current_user.cards.new(card_params)
if @card.save
redirect_to deck_path(params[:deck_id])
else
render 'new'
end
end
def edit
end
def update
if @card.update(card_params)
redirect_to deck_path(params[:deck_id])
else
render 'edit'
end
end
def destroy
@card.destroy
redirect_to deck_path(params[:deck_id])
end
private
def find_card
@card = current_user.cards.find(params[:id])
end
def card_params
params.require(:card).
permit(:deck_id, :original_text, :translated_text, :review_date, :figure)
end
end
|
class UsersController < ApplicationController
before_action :set_user, only: [:edit, :update]
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
# save the user's id into the session (so the user is now considered logged in for the session)
session[:user_id] = @user.id
flash[:success] = "Welcome, #{@user.username}!"
redirect_to users_path(@user)
else
render 'new'
end
end
def edit
set_user
# if the user isn't logged in or the logged in user is not the user in /users/id/edit, then don't allow the edit.
if (logged_in? && current_user.id != @user.id) || !logged_in?
flash[:danger] = "You cannot edit this user"
redirect_to root_path
end
end
def update
set_user
@user.update(user_params)
if @user.update(user_params)
flash[:success] = "Beeb successfully updated"
redirect_to user_path(@user)
else
render 'edit'
end
end
def show
set_user
if !logged_in?
flash[:danger] = "Log in first before you can view users!"
redirect_to root_path
end
end
private
# saves the user object indicated in the params (from route's URL path) in @user, so the controller actions can be performed on the correct user object
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:username, :email, :password)
end
end |
class AddForeignKeys < ActiveRecord::Migration[5.2]
def change
add_foreign_key :order_items, :orders, on_delete: :cascade
add_foreign_key :order_items, :weddings, on_delete: :cascade
end
end
|
# frozen_string_literal: true
module Dynflow
class DeadLetterSilencer < Concurrent::Actor::DefaultDeadLetterHandler
def initialize(matchers)
@matchers = Type! matchers, Array
end
def should_drop?(dead_letter)
@matchers.any? { |matcher| matcher.match? dead_letter }
end
def on_message(dead_letter)
super unless should_drop?(dead_letter)
end
private
class Matcher
Any = Algebrick.atom
def initialize(from, message = Any, to = Any)
@from = from
@message = message
@to = to
end
def match?(dead_letter)
return unless dead_letter.sender.respond_to?(:actor_class)
evaluate(dead_letter.sender.actor_class, @from) &&
evaluate(dead_letter.message, @message) &&
evaluate(dead_letter.address.actor_class, @to)
end
private
def evaluate(thing, condition)
case condition
when Any
true
when Proc
condition.call(thing)
else
condition == thing
end
end
end
end
end
|
class NotSpecialCharactersValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
special_characters_regex = /\A([0-9a-zA-Z\-\s])+\z/
unless value =~ special_characters_regex
record.errors[attribute] << (options[:message] || "invalid format")
end
end
end
|
module AmazonRateConcern
extend ActiveSupport::Concern
include ApplicationConcern
include AmazonRateAdjustConcern
attr_reader :name, :address1, :address2, :city, :state, :country_code, :zip, :sku_and_quantity
Address = Struct.new(:name, :line_1, :line_2, :line_3, :city, :state_or_province_code, :country_code, :postal_code)
Item = Struct.new(:seller_sku, :seller_fulfillment_order_item_id, :quantity)
def get_always_present_shipping_info(my_params) #everything but name and address, sometimes name and address isn't present when they preview rates in the cart
@city = my_params[:destination][:city]
@state = my_params[:destination][:state_iso2]
@country_code = my_params[:destination][:country_iso2]
@zip = my_params[:destination][:zip]
end
def get_name_and_address(my_params)
if do_we_need_a_fake_address?(my_params)
@name = "Joe Schmoe"
@address1 = "123 Main Street"
else
@name = my_params[:destination][:name]
@address1 = my_params[:destination][:street_1]
@address2 = my_params[:destination][:street_2]
end
end
def do_we_need_a_fake_address?(my_params)
my_params[:destination][:name].empty?
end
def setup_address_struct
Address.new(name, address1, address2, "", city, state, country_code, zip)
end
def setup_items_struct
items = []
sku_and_quantity.map do |product|
seller_sku = product[:sku]
seller_fulfillment_order_item_id = "bytestand_#{(0...8).map { (65 + rand(26)).chr }.join.downcase}"
quantity = product[:quantity]
items << Item.new(seller_sku, seller_fulfillment_order_item_id, quantity)
end
end
def get_skus_and_quantity(my_params)
@sku_and_quantity = []
my_params[:items].each do |product|
@sku_and_quantity << {sku: product["sku"], quantity: product["quantity"]}
end
end
def parse_rates_from_amazon(amazon_fee_response)
amazon_rates = []
amazon_fee_response["FulfillmentPreviews"]["member"].each do |speed|
if speed["IsFulfillable"] == "true"
arrival_date = speed["FulfillmentPreviewShipments"]["member"]["EarliestArrivalDate"]
amazon_rates << {speed: speed["ShippingSpeedCategory"],
amount: speed["EstimatedFees"]["member"]["Amount"]["Value"],
currency: speed["EstimatedFees"]["member"]["Amount"]["CurrencyCode"],
transit_duration: determine_transit_duration(arrival_date)}
end
end
return amazon_rates
end
def determine_transit_duration(arrival_date)
today = DateTime.now
delivery = DateTime.parse(arrival_date)
(delivery - today).round
end
end |
class VerbsController < ApplicationController
# GET /verbs
# GET /verbs.json
before_filter :authenticate_user!, :except => [:select_part, :forward_test, :forward_test_step]
def index
@verbs = Verb.where(:language => @language).order(:verb).all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @verbs }
end
end
# GET /verbs/1
# GET /verbs/1.json
def show
@verb = Verb.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @verb }
end
end
# GET /verbs/new
# GET /verbs/new.json
def new
@verb = Verb.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @verb }
end
end
# GET /verbs/1/edit
def edit
@verb = Verb.find(params[:id])
end
# POST /verbs
# POST /verbs.json
def create
@verb = Verb.new(params[:verb])
@verb.language = @language
respond_to do |format|
if @verb.save
format.html { redirect_to controller: :verbs, action: :new, notice: 'Verb was successfully created.' }
format.json { render json: @verb, status: :created, location: @verb }
else
format.html { render action: "new" }
format.json { render json: @verb.errors, status: :unprocessable_entity }
end
end
end
# PUT /verbs/1
# PUT /verbs/1.json
def update
@verb = Verb.find(params[:id])
respond_to do |format|
if @verb.update_attributes(params[:verb])
format.html { redirect_to controller: :verbs, action: :index, notice: 'Verb was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @verb.errors, status: :unprocessable_entity }
end
end
end
# DELETE /verbs/1
# DELETE /verbs/1.json
def destroy
@verb = Verb.find(params[:id])
@verb.destroy
respond_to do |format|
format.html { redirect_to verbs_url }
format.json { head :no_content }
end
end
def forward_test
@verbs = Verb.where(:language => @language).where(:part => params[:part_id]).all
if @verbs.empty?
redirect_to :controller => :main, :action => :index
end
end
def forward_test_step
@verb = Verb.find(params[:id])
@translations = [[@verb.translation, @verb.clarification]]
@verbs = [@verb.verb]
for i in 1..3
tr2 = @translations.collect{ |t| "'" + t[0] + "'" }.join(",")
vr = @verbs.collect{ |v| "'" + v + "'" }.join(",")
off1 = rand(Verb.where(:language => @language).where(:part => @verb.part).where("translation not in (#{tr2})").where("verb not in (#{vr})").count)
verbr = Verb.where(:language => @language).where(:part => @verb.part).where("translation not in (#{tr2})").where("verb not in (#{vr})").first(:offset => off1)
if !verbr.nil?
@translations.push [ verbr.translation, verbr.clarification ]
@verbs.push verbr.verb
end
end
@prepositions = Verb.where(:language => @language).all.collect{|vrx| vrx.preposition}.uniq
@prepositions.delete(@verb.preposition)
@prepositions.shuffle!
@prepositions = @prepositions.slice(0,2)
@prepositions.push(@verb.preposition)
respond_to do |format|
format.json { render json: {verb: @verb, translations: @translations.shuffle, prepositions: @prepositions.sort} }
end
end
end
|
require 'travis/github_sync/services/sync_user/result'
describe Travis::GithubSync::Services::SyncUser::Result do
subject { described_class.new }
it 'keeps an array of hashes' do
subject.add_org('id' => 1)
subject.add_org('id' => 2)
expect(subject.orgs).to eql([{ 'id' => 1 }, { 'id' => 2 }])
end
it 'filters out irrelevant attributes' do
subject.add_org('id' => 1, 'site_admin' => false)
expect(subject.orgs).to eql([{ 'id' => 1 }])
end
it 'ignores duplicate hashes' do
subject.add_org('id' => 1)
subject.add_org('id' => 1)
expect(subject.orgs).to eql([{ 'id' => 1 }])
end
end
|
require 'spec_helper'
describe FacebookDialog::Dialog do
class DummyDialog < FacebookDialog::Dialog; end
it "includes the api key as an app id argument" do
FacebookDialog.api_key = "something"
FacebookDialog::Feed.new.url.should include("app_id=#{Rack::Utils.escape(FacebookDialog.api_key)}")
end
it "raises an error when a resource name is not defined when getting base uri" do
lambda { DummyDialog.base_uri }.should raise_error(
FacebookDialog::ResourceNameNotDefined
)
end
it "validates the display" do
mock_validator = mock(:validate => nil)
FacebookDialog::Validators::Display.expects(:new).returns(mock_validator)
DummyDialog.new.to_h
end
end
|
class UserExercise < ApplicationRecord
belongs_to :exercise
belongs_to :user
end
|
require 'spec_helper'
describe Nmax::StreamNumbersParser do
let(:data) { '2243-0 s;la0493 120392nweqk30402klj\nqw 32002 wkljqlk203 902p0-42-32' }
let(:result) { [0, 0, 32, 42, 203, 493, 902, 2243, 30_402, 32_002, 120_392] }
let(:stream) { StringIO.new(data) }
let(:parser) { described_class.new(stream) }
it 'parse numbers from stream' do
numbers = []
parser.parse { |number| numbers << number }
expect(numbers).to match_array result
end
end
|
# frozen_string_literal: true
require 'singleton'
require_relative './services/validation.rb'
require_relative './services/icmp_flood_report.rb'
require_relative './services/sql_injection_report.rb'
require_relative './services/query_helper'
module Departments
##
# A module that has direct access to models, i.e. {FriendlyResource}.
module Archive
##
# Methods that are consumed by the other modules, i.e.
# {Workers::Analysis::CodeInjection::Sql::CyberReportProducer}.
class Api
include Singleton
# @param [Integer] page
# @param [Integer] page_size
# @return [Array<FriendlyResource>]
def friendly_resources(page, page_size)
Services::Validation.instance.page?(page)
Services::Validation.instance.page_size?(page_size)
Rails.logger.info("#{self.class.name} - #{__method__} - #{page}, #{page_size}.") if Rails.env.development?
records_to_skip = Services::QueryHelper.instance.records_to_skip(page, page_size)
FriendlyResource.order('created_at desc').limit(page_size).offset(records_to_skip).to_a
end
# Total amount of {FriendlyResource} records in the database.
# @return [Integer]
def friendly_resources_count
Rails.logger.info("#{self.class.name} - #{__method__}.") if Rails.env.development?
FriendlyResource.count
end
# @param [CyberReport] cyber_report For example, {Dos::IcmpFloodReport}.
# @return [FriendlyResource]
def friendly_resource_by_cyber_report(cyber_report)
Services::Validation.instance.cyber_report?(cyber_report)
Rails.logger.info("#{self.class.name} - #{__method__} - #{cyber_report.inspect}.") if Rails.env.development?
cyber_report.friendly_resource
end
# @param [Integer] id {FriendlyResource} id in the database.
# @return [FriendlyResource]
def friendly_resource_by_id(id)
Services::Validation.instance.id?(id)
Rails.logger.info("#{self.class.name} - #{__method__} - #{id}.") if Rails.env.development?
FriendlyResource.find(id)
end
# @param [Integer] ip_address {FriendlyResource} ip address.
# @return [FriendlyResource]
def friendly_resource_by_ip(ip_address)
Services::Validation.instance.friendly_resource_ip_address?(ip_address)
Services::Validation.instance.integer?(ip_address)
Rails.logger.info("#{self.class.name} - #{__method__} - #{ip_address}.") if Rails.env.development?
FriendlyResource.find_by(ip_address: ip_address)
end
# Initiates a new {FriendlyResource} object. It is not persisted in the database yet.
# @param [String] name {FriendlyResource} name.
# @param [Object] ip_address {FriendlyResource} ip address. It can be a [String] or an [Integer].
# @return [FriendlyResource]
def new_friendly_resource(name, ip_address)
Services::Validation.instance.friendly_resource_name?(name)
Services::Validation.instance.friendly_resource_ip_address?(ip_address)
Rails.logger.info("#{self.class.name} - #{__method__} - #{name}, #{ip_address}.") if Rails.env.development?
if ip_address.class == String
if ip_address.match?(/^[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*$/)
ip_address = IPAddr.new(ip_address).to_i
elsif ip_address.match?(/^[0-9]*$/)
ip_address = ip_address.to_i
end
end
FriendlyResource.new(name: name, ip_address: ip_address)
end
# Initiates a new {FriendlyResource} object. It is not persisted in the database yet.
# @param [Hash] friendly_resource Contains fields and values for {FriendlyResource}.
# @return [FriendlyResource]
def new_friendly_resource_from_hash(friendly_resource)
Services::Validation.instance.hash?(friendly_resource)
Rails.logger.info("#{self.class.name} - #{__method__} - #{friendly_resource}.") if Rails.env.development?
new_friendly_resource(friendly_resource['name'], friendly_resource['ip_address'])
end
# Initiates a new {FriendlyResource} object. It is not persisted in the database yet.
# @return [FriendlyResource]
def new_empty_friendly_resource
Rails.logger.info("#{self.class.name} - #{__method__}.") if Rails.env.development?
FriendlyResource.new
end
# Will persist the {FriendlyResource} object in the database.
# @param [FriendlyResource] friendly_resource {FriendlyResource}.
# @return [Void]
def persist_friendly_resource(friendly_resource)
Services::Validation.instance.friendly_resource?(friendly_resource)
if Rails.env.development?
debug_message = "#{self.class.name} - #{__method__} - #{friendly_resource.inspect}."
Rails.logger.info(debug_message)
end
friendly_resource.save
end
# Total amount of {CyberReport} records in the database by a report type.
# @param [Integer] ip {FriendlyResource} ip address.
# @param [Symbol] type For example, {Shared::AnalysisType::ICMP_DOS_CYBER_REPORT}.
# @return [Integer]
def cyber_reports_count(ip, type)
Services::Validation.instance.friendly_resource_ip_address?(ip)
Services::Validation.instance.cyper_report_type?(type)
Rails.logger.info("#{self.class.name} - #{__method__} - #{ip}, #{type}.") if Rails.env.development?
result = 0
friendly_resource = friendly_resource_by_ip(ip)
if friendly_resource
case type
when Shared::AnalysisType::ICMP_DOS_CYBER_REPORT
result = Services::IcmpFloodReport.instance.count_records(friendly_resource.id)
when Shared::AnalysisType::SQL_INJECTION_CYBER_REPORT
result = Services::SqlInjectionReport.instance.count_records(friendly_resource.id)
end
end
result
end
# Retrieves in DESC order, according to the creation date.
# @param [Integer] ip {FriendlyResource} ip address.
# @param [Symbol] type For example, {Shared::AnalysisType::ICMP_DOS_CYBER_REPORT}.
# @param [Integer] page Starts at 1.
# @param [Integer] page_size
# @return [Array<CyberReport>]
def cyber_reports_by_friendly_resource_ip_and_type(ip, type, page, page_size)
Services::Validation.instance.friendly_resource_ip_address?(ip)
Services::Validation.instance.cyper_report_type?(type)
Services::Validation.instance.page?(page)
Services::Validation.instance.page_size?(page_size)
if Rails.env.development?
debug_message = "#{self.class.name} - #{__method__} - #{ip}, #{type}, #{page}, #{page_size}."
Rails.logger.info(debug_message)
end
result = []
ip = IPAddr.new(ip).to_i if ip.class == String
friendly_resource = friendly_resource_by_ip(ip)
if friendly_resource
case type
when Shared::AnalysisType::ICMP_DOS_CYBER_REPORT
result = Services::IcmpFloodReport.instance.latest_reports_by_friendly_resource_id(
friendly_resource.id,
page,
page_size
)
when Shared::AnalysisType::SQL_INJECTION_CYBER_REPORT
result = Services::SqlInjectionReport.instance.latest_reports_by_friendly_resource_id(
friendly_resource.id,
page,
page_size
)
end
end
result
end
# @param [Integer] id {CyberReport} id in the database.
# @param [Symbol] type For example, {Shared::AnalysisType::ICMP_DOS_CYBER_REPORT}.
# @return [CyberReport]
def cyber_report_by_id_and_type(id, type)
Services::Validation.instance.integer?(id)
Services::Validation.instance.cyper_report_type?(type)
Rails.logger.info("#{self.class.name} - #{__method__} - #{id}, #{type}.") if Rails.env.development?
cyber_report = nil
case type
when Shared::AnalysisType::ICMP_DOS_CYBER_REPORT
cyber_report = Services::IcmpFloodReport.instance.report_by_id(id)
when Shared::AnalysisType::SQL_INJECTION_CYBER_REPORT
cyber_report = Services::SqlInjectionReport.instance.report_by_id(id)
end
cyber_report
end
# @param [Integer] ip {FriendlyResource} ip address.
# @param [Symbol] type For example, {Shared::AnalysisType::ICMP_DOS_CYBER_REPORT}.
# @param [Hash] opts Additional custom attributes:
# * 'seasonal_index' [Integer] a mandatory attribute for {Dos::IcmpFloodReport}.
# @return {CyberReport}
def cyber_report_by_friendly_resource_ip_and_type_and_custom_attr(ip, type, opts)
Services::Validation.instance.friendly_resource_ip_address?(ip)
Services::Validation.instance.cyper_report_type?(type)
Services::Validation.instance.custom_attributes?(opts)
Rails.logger.info("#{self.class.name} - #{__method__} - #{ip}, #{type}, #{opts}.") if Rails.env.development?
ip = IPAddr.new(ip).to_i if ip.class == String
friendly_resource = friendly_resource_by_ip(ip)
if friendly_resource
result = nil
case type
when Shared::AnalysisType::ICMP_DOS_CYBER_REPORT
Services::Validation.instance.seasonal_index_in_opts?(opts)
result = Services::IcmpFloodReport.instance.latest_report_by_friendly_resource_id_and_seasonal_index(
friendly_resource.id,
opts['seasonal_index']
)
end
return result
end
error_message = "#{self.class.name} - #{__method__} - no friendly resource for ip : #{ip}."
throw Exception.new(error_message)
end
# Initializes a {CyberReport} instance, i.e. {Dos::IcmpFloodReport}.
# @param [Integer] ip {FriendlyResource} ip address.
# @param [AnalysisType] type For example, {Shared::AnalysisType::ICMP_DOS_CYBER_REPORT}.
# @param [Hash] opts Additional custom attributes:
# * 'seasonal_index' [Integer] a mandatory attribute for {Dos::IcmpFloodReport}.
# @return {CyberReport}
def new_cyber_report_object_for_friendly_resource(ip, type, opts = {})
Services::Validation.instance.friendly_resource_ip_address?(ip)
Services::Validation.instance.cyper_report_type?(type)
Services::Validation.instance.custom_attributes?(opts)
Rails.logger.info("#{self.class.name} - #{__method__} - #{ip}, #{type}, #{opts}.") if Rails.env.development?
ip = IPAddr.new(ip).to_i if ip.class == String
friendly_resource = friendly_resource_by_ip(ip)
if friendly_resource
result = nil
case type
when Shared::AnalysisType::ICMP_DOS_CYBER_REPORT
Services::Validation.instance.seasonal_index_in_opts?(opts)
result = Services::IcmpFloodReport.instance.new_report_object(
opts['seasonal_index']
)
friendly_resource.icmp_flood_report << result if result
return result
when Shared::AnalysisType::SQL_INJECTION_CYBER_REPORT
result = Services::SqlInjectionReport.instance.new_report_object
friendly_resource.sql_injection_report << result if result
return result
end
end
error_message = "#{self.class.name} - #{__method__} - no friendly resource for ip : #{ip}."
throw Exception.new(error_message)
end
# @param [CyberReport] cyber_report One of the {CyberReport} instances,
# i.e. {Dos::IcmpFloodReport}
def persist_cyber_report(cyber_report)
Services::Validation.instance.cyber_report?(cyber_report)
Rails.logger.info("#{self.class.name} - #{__method__} - #{cyber_report.inspect}.") if Rails.env.development?
cyber_report.save
end
# @return [Array<Symbol>]
def cyber_report_types
Rails.logger.info("#{self.class.name} - #{__method__}.") if Rails.env.development?
Shared::AnalysisType.formats
end
end
end
end
|
# frozen_string_literal: true
describe Facts::Macosx::SystemProfiler::ProcessorSpeed do
describe '#call_the_resolver' do
subject(:fact) { Facts::Macosx::SystemProfiler::ProcessorSpeed.new }
let(:value) { '2.8 GHz' }
let(:expected_resolved_fact) { double(Facter::ResolvedFact, name: 'system_profiler.processor_speed', value: value) }
before do
expect(Facter::Resolvers::SystemProfiler).to receive(:resolve).with(:processor_speed).and_return(value)
expect(Facter::ResolvedFact).to receive(:new)
.with('system_profiler.processor_speed', value)
.and_return(expected_resolved_fact)
end
it 'returns system_profiler.processor_speed fact' do
expect(fact.call_the_resolver).to eq(expected_resolved_fact)
end
end
end
|
require 'station'
describe Station do
let(:station) {described_class.new("waterloo", "4")}
context 'On initialisation' do
it 'creates a struct with name attribute' do
expect(station.name).to eq "waterloo"
end
it 'creates a struct with `zone attribute' do
expect(station.zone).to eq "4"
end
end
end |
class Mailer < ActionMailer::Base
helper :customers, :application
default :from => "AutoConfirm-#{Option.venue_shortname}@audience1st.com"
before_filter :setup_defaults
def confirm_account_change(customer, whathappened, newpass=nil)
@whathappened = whathappened
@newpass = newpass
@customer = customer
mail(:to => customer.email, :subject => "#{@subject} #{customer.full_name}'s account")
end
def confirm_order(purchaser,order)
@order = order
mail(:to => purchaser.email, :subject => "#{@subject} order confirmation")
end
def confirm_reservation(customer,showdate,num=1)
@customer = customer
@showdate = showdate
@num = num
@notes = @showdate.patron_notes
mail(:to => customer.email, :subject => "#{@subject} reservation confirmation")
end
def cancel_reservation(old_customer, old_showdate, num = 1, confnum)
@showdate,@customer = old_showdate, old_customer
@num,@confnum = num,confnum
mail(:to => @customer.email, :subject => "#{@subject} CANCELLED reservation")
end
def donation_ack(customer,amount,nonprofit=true)
@customer,@amount,@nonprofit = customer, amount, nonprofit
@donation_chair = Option.donation_ack_from
mail(:to => @customer.email, :subject => "#{@subject} Thank you for your donation!")
end
def upcoming_birthdays(send_to, num, from_date, to_date, customers)
@num,@customers = num,customers
@subject << "Birthdays between #{from_date.strftime('%x')} and #{to_date.strftime('%x')}"
mail(:to => send_to, :subject => @subject)
end
protected
def setup_defaults
@venue = Option.venue
@subject = "#{@venue} - "
@contact = if Option.help_email.blank?
then "call #{Option.boxoffice_telephone}"
else "email #{Option.help_email} or call #{Option.boxoffice_telephone}"
end
end
end
|
class CreateSessions < ActiveRecord::Migration
def self.up
create_table :sessions do |t|
t.belongs_to :site # Required
t.belongs_to :campaign # Only for campaigns
t.string :visitor, :limit => 20
t.integer :visit, :default => 0
t.string :session, :limit => 20
t.integer :event_count
t.string :browser, :limit => 20
t.string :browser_version, :limit => 10
t.string :language, :limit => 10
t.string :screen_size, :limit => 10
t.integer :color_depth, :limit => 2
t.string :charset, :limit => 10
t.string :os_name, :limit => 20
t.string :os_version, :limit => 10
t.string :flash_version, :limit => 10
t.string :campaign_name, :limit => 50
t.string :campaign_source
t.string :campaign_medium
t.string :campaign_content
t.string :ip_address, :limit => 20
t.string :locality
t.string :region
t.string :country
t.float :latitude
t.float :longitude
t.integer :duration, :default => 0
t.datetime :started_at
t.datetime :ended_at
end
end
def self.down
drop_table :sessions
end
end
|
class CreateUserAccounts < ActiveRecord::Migration[6.1]
def change
create_table :user_accounts do |t|
t.decimal :balance, default: 0
t.decimal :single_send_limit
t.decimal :monthtly_send_limit
t.text :description
#t.references :currency, null: false, foreign_key: true
t.timestamps
end
end
end
|
class Admin::PreferencesController < ApplicationController
def index
@prefs = Preference.all
end
end
|
class Organization < ActiveRecord::Base
validates :name, presence: true
validates :description, presence: true
validates :visibility, inclusion: { in: %w(publicly_visible members_only) }
extend FriendlyId
friendly_id :name, :use => :history
def should_generate_new_friendly_id?
name_changed? || super
end
has_many :memberships, :dependent => :destroy
has_many :pending_memberships, :dependent => :destroy
has_many :users, through: :memberships
accepts_nested_attributes_for :pending_memberships, :allow_destroy => true
enum visibility: [ :publicly_visible, :members_only]
acts_as_tree
end
|
class ChildrenController < ApplicationController
# GET /children
# GET /children.json
before_action :set_meal, only: [:show, :edit, :update, :destroy]
def index
@meals = Meal.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @meals }
end
end
# GET /meals/1
# GET /meals/1.json
def show
@user = Person.find(user_id => User.id)
respond_to do |format|
format.html # show.html.erb
format.json { render json: @meal }
end
end
# GET /meals/new
# GET /meals/new.json
def new
@meal = Meal.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @meal }
end
end
# GET /meals/1/edit
def edit
end
# POST /meals
# POST /meals.json
def create
@meal = Meal.new(meal_params)
respond_to do |format|
if @meal.save
format.html { redirect_to @meal, notice: 'Child was successfully created.' }
format.json { render json: @meal, status: :created, location: @meal }
else
format.html { render action: "new" }
format.json { render json: @meal.errors, status: :unprocessable_entity }
end
end
end
# PUT /meals/1
# PUT /meals/1.json
def update
respond_to do |format|
if @meal.update_attributes(meal_params)
format.html { redirect_to @meal, notice: 'Child was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @meal.errors, status: :unprocessable_entity }
end
end
end
# DELETE /meals/1
# DELETE /meals/1.json
def destroy
@child.destroy
respond_to do |format|
format.html { redirect_to meals_url }
format.json { head :no_content }
end
end
private
def set_meal
@meal = Meal.find(params[[:id])
end
def meal_params
params.require(:meal).permit(:food_type, :meal_date, :meal_type, :user_id)
end
end
|
class CreateFavorite < ActiveRecord::Migration
def up
create_table :favorites do |t|
t.belongs_to :user
t.belongs_to :tweet
t.timestamps
end
end
def down
drop_table :favortes
end
end
|
#####################################################################
# tc_memory.rb
#
# Test case for the Windows::Memory module.
#####################################################################
base = File.basename(Dir.pwd)
if base == 'test' || base =~ /windows-pr/
Dir.chdir '..' if base == 'test'
$LOAD_PATH.unshift Dir.pwd + '/lib'
Dir.chdir 'test' rescue nil
end
require 'windows/memory'
require 'test/unit'
class Foo
include Windows::Memory
end
class TC_Windows_Path < Test::Unit::TestCase
def setup
@foo = Foo.new
@path = "C:\\"
end
def test_numeric_constants
assert_not_nil(Foo::GHND)
assert_not_nil(Foo::GMEM_FIXED)
assert_not_nil(Foo::GMEM_MOVABLE)
assert_not_nil(Foo::GMEM_ZEROINIT)
assert_not_nil(Foo::GPTR)
end
def test_method_constants
assert_not_nil(Foo::GlobalAlloc)
assert_not_nil(Foo::GlobalFlags)
assert_not_nil(Foo::GlobalFree)
assert_not_nil(Foo::GlobalHandle)
assert_not_nil(Foo::GlobalLock)
assert_not_nil(Foo::GlobalMemoryStatus)
assert_not_nil(Foo::GlobalMemoryStatusEx)
assert_not_nil(Foo::GlobalReAlloc)
assert_not_nil(Foo::GlobalSize)
assert_not_nil(Foo::GlobalUnlock)
end
def teardown
@foo = nil
@path = nil
end
end
|
class Loan < ApplicationRecord
belongs_to :user
has_many :payments, dependent: :destroy
# monetize :requested_amount
# validates :user_id, presence: true
# validates :requested_amount, presence: true,
# numericality: { less_than_or_equal_to: 15000, greater_than: 0}
# validates :when_declining_a_loan, on: :update
# validates :category, presence: true
# validates :purpose, presence: true
# validates :description, presence: true,
# length: { minimum: 20,
# too_short: "You need to exceed %{count} characters in your description"}
after_commit :update_status
# def live?
# status == "Loan Oustanding"
# end
# def any_delay_payment?
# payments.any?{|payment| payment.delayed_payment?}
# end
# def any_missed_payment?
# payments.any?{|payment| payment.missed_payment}
# end
# #PAYMENT METHOD
# #Retrieve the most recent payment which has passed it's due date
# def most_recent_payment
# payments.where("due_date < ?", DateTime.now).last
# end
# def amount_owed
# amount = 0
# payments.each do |payment|
# amount += payment.amount_paid unless payment.paid
# end
# amount
# end
# def amount_overdue
# amount_overdue = 0
# payments.each do |payment|
# if payment.due_date < DateTime.now && payment.paid
# amount_overdue += payment.amount
# end
# end
# amount_overdue
# end
# #Calculate the remaining capital on the loan
# def remaining_capital
# payments_total = 0
# payments.each do |payment|
# payments_total +=payment.amount if payment.paid ==true
# end
# payments.to_a.reduce(0){|sum, payment| sum +=payment.amount} - payments_total
# end
# #Calculate the total repaid capital
# def total_capital_repaid
# sum = Money.new(0)
# payments.each do |payment|
# sum += payment.amount if payment.paid == true
# end
# sum
# end
# def total_capital
# payments.reduce(0){|sum, p| sum +=payment.amount}
# end
# #LOAN FILTERS
# #Finds loans which have no missed/delayed payments
# def self.good_loans
# result = order(start_date: :desc).where(status: "Loan Outstanding").reject{|loan| Loan.missed_payment_loans.include?(loan)}
# result.reject {|loan| Loan.delayed_payment_loans.include?(loan)}
# end
# ##TODO: Make the method modula so that User can choose the allowed day of default
# #Finds loans which have missed payment (due_date + 7 days)
# def self.missed_payment_loans
# order(start_date: :desc).where(status: "Loan Oustanding").joins(:payments).where('payments.due_date <?', (DateTime.now.end_of_day - 7.day)).where(payments: {paid: false})
# end
# #Finds loans which have delayed payments (less than 7 days since due date)
# def self.delayed_payment_loans
# result = order(start_date: :desc).where(status: "Loan Oustanding").joins(:payments).where(payments: {due_date: DateTime.now.end_of_day - 7.day ..DateTime.now.end_of_day}).where(payments: {paid: false})
# result.select {|loan| loan unless missed_payment_loans.include?(loan)}
# end
# #Find loan that payments which are shown to the user before confirming/accepting the loan
# def create_payments_proposed
# payment_amount = ((proposed_amount.amount * (1 + interest_rate.fdiv(100)))/duration_months) *100
# counter = 1
# duration_months.times do
# payment = payments.build(amount)
# end
# end
def self.update_status
if self.loan_amount == self.total_loanpaided
self.Loan.status("Loan Repaid")
else
self.Loan.status("Loan Outstanding")
end
end
private
#Takes a argument that defines if monthly, yearly or daily and return the loan amount to be paid
def self.loaned_amount_to_be_pay(monthly = "monthly")
if monthly == "yearly"
(Loan.agreed_amount * (1+Loan.interest_rate)).round(2)
elsif monthly == "daily"
(Loan.agreed_amount * (1+Loan.interest_rate/(12*30))).round(2)
else
(Loan.agreed_amount * (1+Loan.interest_rate/12)).round(2)
end
end
#Take a loan and return the total amount paid on the loan
def self.total_loanpaided
totalpaided = 0
Loan.payments.each do |payment|
totalpaided += payment.amount_paid
end
totalpaided.round(2)
end
def self.loan_amount
#TODO:
#If the total payment of the loan is eq to agreed_amount + interest
#Make sure that on the view you would display
#Loan amount (Loan.agreed_amount and Loan.interest_rate) and
#Total amount that needs to be paid at the end of the LOAN
loan_amount = loaned_amount_to_be_pay("dailly") * (Loan.start_date - Loan.final_date)
loan_amount.round(2)
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'associations' do
it { should have_many(:answers).dependent(:destroy) }
it { should have_many(:questions).dependent(:destroy) }
it { should have_many(:rewards).dependent(:destroy) }
it { should have_many(:comments).dependent(:destroy) }
it { should have_many(:authorizations).dependent(:destroy) }
it { should have_many(:subscriptions).dependent(:destroy) }
end
describe 'validations' do
it { should validate_presence_of :email }
it { should validate_presence_of :password }
it { should validate_length_of(:password).is_at_least(6) }
it { should have_db_index(:email).unique(:true) }
end
describe '#author_of?(item)' do
let(:author) { create(:user) }
let(:not_author) { create(:user) }
let(:question) { create(:question, user: author) }
let(:item_without_author) { Class.new }
context 'author' do
subject { author }
it { is_expected.to be_an_author_of(question) }
it { is_expected.to_not be_an_author_of(item_without_author) }
end
context 'not_author' do
subject { not_author }
it { is_expected.to_not be_an_author_of(question) }
it { is_expected.to_not be_an_author_of(item_without_author) }
end
end
describe '#subscribed_on?(question)' do
let(:question) { create(:question) }
let(:subscriber) { create(:user) }
let(:not_subscriber) { create(:user) }
let!(:subscription) { create(:subscription, user: subscriber, question: question) }
context 'subscriber' do
subject { subscriber }
it { is_expected.to be_an_subscribed_on(question) }
end
context 'not subscriber' do
subject { not_subscriber }
it { is_expected.to_not be_an_subscribed_on(question) }
end
end
describe '.find_for_oauth(auth, email)' do
let!(:user) { create(:user) }
let(:auth) { OmniAuth::AuthHash.new(provider: 'facebook', uid: '123') }
let(:service) { double('FindForOauthService') }
it 'calls FindForOauthService' do
expect(FindForOauthService).to receive(:new).with(auth, user.email)
.and_return(service)
expect(service).to receive(:call)
User.find_for_oauth(auth, user.email)
end
end
describe '.find_or_create!(email)' do
context 'User with current email exist' do
let!(:user) { create(:user, email: 'existing@email.com') }
subject { User.find_or_create!('existing@email.com') }
it { is_expected.to eq user }
end
context 'User with current email does not exist' do
it 'creates new user' do
expect{ User.find_or_create!('new_user@email.com') }
.to change(User, :count).by(1)
end
it 'creates user with current email' do
expect(User.create_user_with_rand_password!('new_user@email.com'))
.to eq User.find_by(email: 'new_user@email.com')
end
end
end
describe '.create_user_with_rand_password!(email)' do
it 'creates new user' do
expect{ User.find_or_create!('new_user@email.com') }
.to change(User, :count).by(1)
end
it 'creates user with current email' do
expect(User.create_user_with_rand_password!('new_user@email.com'))
.to eq User.find_by(email: 'new_user@email.com')
end
end
end
|
module GapIntelligence
class DeltaPromotion < Record
attributes :merchant_id, :category_id, :category_version_id,
:brand_id, :product_id, :product_version_id
attributes :category_name, :country_code, :category_version_name
attributes :merchant_name, :merchant_channel
attributes :brand_name, :part_number, :product_version_name
attributes :product_status, :specifications
attributes :start_date, :end_date, class: Date
attributes :promotion_type, :promotion_event
attributes :shelf_price, :value, :promo_percentage
attributes :bundle_type, :on_ad, :notes
end
end
|
require 'spec_helper'
feature "User lists an auction" do
# In order to sell my items
# As a logged in user
# I want to list an auction
# - user enters item condition, size(s), season(s), type (e.g. pants), brand, number/gender of items, item title, item description, starting bid price, and buy now price
# - user can upload one item photo
before do
Fabricate(:child_configuration, siblings_type: "triplets", genders: "mmm")
Fabricate(:child_configuration, siblings_type: "triplets", genders: "mmf")
Fabricate(:child_configuration, siblings_type: "siblings", genders: "mf")
Fabricate(:clothing_condition, name: "new")
Fabricate(:clothing_condition, name: "gently used")
Fabricate(:season, name: "Spring")
Fabricate(:season, name: "Summer")
Fabricate(:clothing_size, name: "3T")
Fabricate(:clothing_size, name: "5")
Fabricate(:clothing_type, name: "jackets")
Fabricate(:clothing_type, name: "full outfits")
Fabricate(:brand, name: "Janie & Jack")
end
scenario "A signed out user is redirect upon logging in" do
visit root_path
click_link "Sell"
page.should have_content "You need to sign in or sign up before continuing."
login_as :user
current_path.should == new_auction_path
end
scenario "happy path auction creation" do
user = login_as :user, first_name: "Sue", last_name: "Smith"
click_link "Sell"
fill_in "Title", with: "3 boys sailor suits"
fill_in "Starting Price", with: "48.00"
check "triplets - mmm"
select "new", from: "Condition"
select "Spring"
check "3T"
select "Janie & Jack", from: "Brand"
select "full outfits", from: "Clothing Type"
fill_in "Description", with: "Three Brand New Janie & Jack boys sailor suits in size 3T"
attach_file "Item Photo", "spec/support/files/ally.jpg"
# click_button "Preview my auction"
click_button "START AUCTION"
within(".auction") do
page.should have_content("3 boys sailor suits")
find("img.item_photo")["src"].should include("ally.jpg")
page.should have_content "new"
page.should have_content "Spring"
page.should have_content "3T"
page.should have_content "Janie & Jack"
page.should have_content "Three Brand New Janie & Jack boys sailor suits in size 3T"
page.should have_content "Sue S."
click_link "Sue S."
end
current_path.should == user_path(user)
page.should have_content("Sue's Current Listings")
page.should have_content("3 boys sailor suits")
click_link "3 boys sailor suits"
current_path.should == auction_path(Auction.last)
end
scenario "missing auction values" do
user = login_as :user, first_name: "Sue", last_name: "Smith"
click_link "Sell"
# click_button "Preview my auction"
click_button "START AUCTION"
page.should have_error("can't be blank", on: "Title")
page.should have_error("must be greater than 0", on: "Starting Price")
page.should have_error("can't be blank", on: "Condition")
page.should have_error("can't be blank", on: "Brand")
page.should have_error("can't be blank", on: "Clothing Type")
page.should have_error("can't be blank", on: "Description")
page.should have_error("can't be blank", on: "Season")
page.should have_error("can't be blank", on: "Item Photo")
page.should have_collection_error("must select at least 1", on: "auction_child_configurations")
page.should have_collection_error("must select at least 1", on: "auction_clothing_sizes")
end
scenario "creating a auction with multiple sizes, set types and seasons" do
user = login_as :user, first_name: "Sue", last_name: "Smith"
click_link "Sell"
fill_in "Title", with: "sibling sailor suits"
fill_in "Starting Price", with: "48"
check "siblings - mf"
check "triplets - mmm"
select "gently used", from: "Condition"
select "Summer"
check "3T"
check "5"
select "Janie & Jack", from: "Brand"
select "full outfits", from: "Clothing Type"
fill_in "Description", with: "Brand New Janie & Jack sailor suits in size 3T and 5. They fit my kids when they were 3 years old and 6 years old perfectly."
attach_file "Item Photo", "spec/support/files/ally.jpg"
# click_button "Preview my auction"
click_button "START AUCTION"
auction = Auction.last
page.should have_content("Your auction has been created.")
current_path.should == auction_path(auction)
within(".auction") do
find("img.item_photo")["src"].should include("ally.jpg")
page.should have_content "gently used"
page.should have_content "Summer"
page.should have_content "3T"
page.should have_content "5"
page.should have_css(".mmm")
page.should have_css(".mf")
end
end
end
|
require 'kfsdb'
class Org
attr_reader :chart, :org, :name, :type_name, :number_of_accounts
def initialize(chart, org, name, type_name)
@chart = chart
@org = org
@name = name
@type_name = type_name
@number_of_accounts = 0
end
def populate_children!(con)
#puts "populating children for #{@chart} #{@org}"
@children = []
org_type_code = ""
con.query("select ca_org_t.fin_coa_cd, ca_org_t.org_cd, ca_org_t.org_nm, ca_org_type_t.org_typ_nm from ca_org_t join ca_org_type_t on ca_org_t.org_typ_cd = ca_org_type_t.org_typ_cd where ca_org_t.rpts_to_fin_coa_cd = ? and ca_org_t.rpts_to_org_cd = ?", @chart, @org) do |row|
#puts "retrieved "+row["fin_coa_cd"]+" "+row["org_cd"]+" by #{@chart} #{@org}"
if row["fin_coa_cd"] != @chart || row["org_cd"] != @org
#puts "so i'll add it"
@children << Org.new(row["fin_coa_cd"], row["org_cd"], row["org_nm"], row["org_typ_nm"])
end
end
con.query("select count(*) as c from ca_account_t where fin_coa_cd = ? and org_cd = ?",@chart,@org) do |row|
@number_of_accounts = row["c"]
end
#puts "children size: #{@children.size}"
@children.each { |kid_org| kid_org.populate_children!(con) }
end
def to_s
"<ul><li>#{@chart}-#{@org} #{@name} TYPE: #{@type_name} (number of accounts: #{@number_of_accounts})#{@children.collect{|kid_org| kid_org.to_s}.join("")}</li></ul>"
end
end
def build_dept(con)
org = Org.new("IU", "UNIV", "UNIVERSITY LEVEL", "UNIVERSITY")
org.populate_children!(con)
return org.to_s
end
s = ""
db_connect("kfstst_at_kfsstg") do |con|
s << "<html><head><title>KFS Demo Data Org Structure</title><link rel=\"stylesheet\" href=\"http://static.jstree.com/3.1.1/assets/bootstrap/css/bootstrap.min.css\" /><link rel=\"stylesheet\" href=\"http://static.jstree.com/3.1.1/assets/dist/themes/default/style.min.css\" />"
s << "<head><body>"
s << "<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-1.10.2.js\"></script>\n<script src=\"http://code.jquery.com/jquery.address-1.6.js\"></script>\n<script src=\"http://static.jstree.com/3.1.1/assets/vakata.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/jstree/3.1.0/jstree.min.js\"></script>\n<script type=\"text/javascript\">\n\t\t$(document).ready(function() {\n\t\t\t$('#org-struct').jstree({\"core\" : {\"themes\" : { \"variant\" : \"large\" }}});\n\t\t});\n</script>"
s << "<div id=\"org-struct\">"
s << build_dept(con)
s << "</div></body></html>"
end
puts s |
require 'spec_helper'
describe Navigation::ProgramNavigator do
describe "initialization" do
it "uses the PhaseStrategy for Phase objects" do
n = Navigation::ProgramNavigator.new(FactoryGirl.build(:phase),
User.new)
n.strategy.should be_instance_of(Navigation::PhaseStrategy)
end
it "uses the SectionStrategy for Section objects" do
n = Navigation::ProgramNavigator.new(FactoryGirl.build(:section),
User.new)
n.strategy.should be_instance_of(Navigation::SectionStrategy)
end
it "uses the SectionStepStrategy for SectionStep objects" do
n = Navigation::ProgramNavigator.new(FactoryGirl.build(:section_step),
User.new)
n.strategy.should be_instance_of(Navigation::SectionStepStrategy)
end
it "raises an exception for unspported context objects" do
expect{Navigation::ProgramNavigator.new(double(:foo), User.new)}
.to raise_error(Navigation::UnsupportedContextObject)
end
end
describe "navigation" do
let(:nav) {Navigation::ProgramNavigator.new(FactoryGirl.build(:phase),
User.new)}
it "delegates #next to strategy" do
n = double(:next)
nav.strategy.should_receive(:next).and_return n
nav.next.should == n
end
it "delegates #previous to strategy" do
p = double(:previous)
nav.strategy.should_receive(:previous).and_return p
nav.previous.should == p
end
end
end
|
module ListMore
class SignIn < UseCase
attr_reader :params
def run params
@params = params
unless verify_fields
return failure "Please check all fields"
end
user = ListMore.users_repo.find_by_username(params['username'])
unless user
return failure "User not found"
end
if user.has_password? params['password']
created_session = ListMore::CreateSession.run user
else
return failure "Incorrect Password"
end
success :token => created_session.token, :user => user
end
def verify_fields
return false if !(params['username'] && params['password'])
true
end
end
end |
class Notifier < ActionMailer::Base
default from: "notice@barter.li"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.notifier.welocme_mail.subject
#
def welcome_mail(joiner)
@asscociation_type = joiner.association_type
mail to: joiner.email, subject: "Barter.li Registration"
end
end
|
module Openra
class IRCBot < Cinch::Bot
module Plugins
class Na
include Cinch::Plugin
match 'n/a'
def execute(m)
m.reply <<-QUOTE.strip.gsub(/\s+/, ' ')
Thus, ergo, concordantly, I must declare that I have won this
argument with my rebbutal of no substance
QUOTE
end
end
end
end
end
|
# frozen_string_literal: true
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('dummy/config/environment.rb', __dir__)
require 'rspec/rails'
require 'factory_bot_rails'
require 'pry-byebug'
require 'stripe_mock'
require 'ffaker'
require 'database_cleaner'
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
RSpec::Matchers.define_negated_matcher :not_change, :change
RSpec.configure do |config|
config.include_context 'with stripe mock', :stripe
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation, except: %w[spatial_ref_sys])
end
config.around do |example|
DatabaseCleaner.cleaning do
example.run
end
end
config.infer_spec_type_from_file_location!
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.shared_context_metadata_behavior = :apply_to_host_groups
config.filter_run_when_matching :focus
config.example_status_persistence_file_path = 'spec/examples.txt'
config.default_formatter = 'doc' if config.files_to_run.one?
config.disable_monkey_patching!
config.profile_examples = 10
config.order = :random
Kernel.srand config.seed
end
|
class Team < ActiveRecord::Base
attr_accessible :name
#has_many :users
#belongs_to :project
validates_presence_of :name
end
|
class OpenIdState < ApplicationRecord
validates :nonce, presence: true, uniqueness: true
end
|
#!/usr/bin/env ruby
require_relative "../lib/kindle_pras"
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: kindle_pras.rb [options]"
opts.on('-l', '--list', "List all available books") do |v|
options[:list_books] = v
end
opts.on('-eBOOK_TITLE_PART_REGEXP', '--extract-book=BOOK_TITLE_PART_REGEXP', "Extract all highlights as notes for a given book. Eg: ./bin/kindle_pras -e 'getting things done' --name='GTD'") do |v|
options[:extract_book] = v
end
opts.on('--name=NAME', "Short name of the book for filename and URL use. Use it along with the '-e' flag.") do |v|
options[:name] = v
end
opts.on('--preview', "Preview the notes for the given book") do |v|
options[:preview] = v
end
opts.on('-p', "Print the template for the 'extract-book' command with all options.") do |v|
puts %Q|./bin/kindle_pras --extract-book="getting things done" --name='GTD' --preview|
puts %Q|./bin/kindle_pras -e "getting things done" -n 'GTD' --preview|
exit
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end.parse!
KindlePras::Processor.new(options).do_the_work!
|
require "spec_helper"
describe "Song" do
let!(:song) {Song.new("Survivor")}
describe "#new" do
it "is initialized with an argument of a name" do
expect{Song.new("Say my Name")}.to_not raise_error
end
end
describe "#name" do
it "has a name" do
expect(song.name).to eq("Survivor")
end
end
describe "#artist" do
it "belongs to an artist" do
drake = Artist.new("Drake")
song.artist = drake
expect(song.artist).to eq(drake)
end
end
describe "#artist_name" do
it "knows the name of its artist" do
drake = Artist.new("Drake")
song.artist = drake
expect(song.artist_name).to eq("Drake")
end
it "returns nil if the song does not have an artist" do
song = Song.new("Cool for the Summer")
expect(song.artist_name).to eq nil
end
end
end |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :activity do
name "MyString"
subject { FactoryGirl.build(:player, score: 10) }
user nil
end
end
|
class Project < ApplicationRecord
has_many :user_projects
has_many :feed_items
has_many :change_orders
has_many :users, through: :user_projects
validates :name, presence: true, length: { maximum: 20 }
validates :order_num, presence: true, numericality: { only_integer: true}, length: { is: 6 }
validates :original_contract, presence: true, numericality: true, length: { maximum: 10 }
#shows current contract amount
def current_contract
value = original_contract
change_orders.each do |co|
co.approved_co_value = 0 if co.approved_co_value == nil
value += co.approved_co_value
end
value
end
def co_amount
current_contract - original_contract
end
def co_percent
co_amount / original_contract * 100
end
end
|
class TasksController < ApplicationController
def index
@tasks = Task.find_incomplete :limit => 20
end
end
|
# Problem: Write a method that takes a string and returns a string that has
# all number words converted to string digits.
# Example: 'Call me at four five five six six six.' == 'Call me at 4 5 5 6 6 6.'
# Input: String
# Output: String
# Steps
# 1: Define a method that takes a string as an argument
# 2: Initialize a constant above the method that has all single digit number as
# values and words as keys
# 3: Scrath the above. Lets brute force 10x gsubs
NUMBERS = %w(zero one two three four five six seven eight nine)
def word_to_digit(str)
NUMBERS.each_with_index do |num, idx|
str.gsub!(/\b#{num}\b/, idx.to_s)
end
number_spacer(str)
end
#Steps:
# =>intialize a new variable - newstr
# =>itterate over the string with .chars
# => if char is a space then check if idx +1 and idx - 1 are both numbers
# => do not append space to string.. or do nothing
# => else just append current char
def number_spacer(str)
new_str = ''
str.chars.each_with_index do |char, idx|
if !(char == ' ' && str[idx - 1] =~ /[0-9]/ && str[idx + 1] =~ /[0-9]/)
new_str << char
end
end
phone_format(new_str)
end
# Steps:
# => Itterate over str.split
# => Itterate over the string
# => check if char is a number and index-1 -2 -3 -4 are also numbers
# and index +1 +2 +3 +4 + 5 are all numbers then
def phone_format(str)
str.split.each do |word|
phone = ""
if word =~ /\b[0-9]{10}\b/
phone = "(" + word[0..2] + ")" + " " + word[3..5] + "-" + word[6..9]
str.gsub!(/\b[0-9]{10}\b/, phone)
end
end
str
end
p word_to_digit("Please call two me at nine zero five five five five one two "\
"three four. Thanks.")
# == 'Please call me at 5 5 5 1 2 3 4. Thanks.'
|
class AddFinishedProcessingAtToImportTasks < ActiveRecord::Migration[5.1]
def change
add_column :import_tasks, :finished_processing_at, :datetime
end
end
|
require 'immutable/list'
# Monkey-patches to Ruby's built-in `IO` class.
# @see http://www.ruby-doc.org/core/IO.html
class IO
# Return a lazy list of "records" read from this IO stream.
# "Records" are delimited by `$/`, the global input record separator string.
# By default, it is `"\n"`, a newline.
#
# @return [List]
def to_list(sep = $/) # global input record separator
Immutable::LazyList.new do
line = gets(sep)
if line
Immutable::Cons.new(line, to_list)
else
EmptyList
end
end
end
end
|
require 'rails_helper'
describe Article do
it 'is has a valid factory' do
expect(build(:article)).to be_valid
end
it 'is invalid without title' do
article = build(:article, title: nil)
expect(article).to be_invalid
end
it 'is invalid without author' do
article = build(:article, author: nil)
expect(article).to be_invalid
end
it 'is invalid with a duplicate title' do
create(:article)
expect(build(:article)).to be_invalid
end
it 'is able to return a string of Title: by Author' do
article = build(:article)
expect(article.title_and_author).to eq 'Of Mice And Men: by John Steinbeck'
end
end
|
class CartsController < ApplicationController
#authorize_resource
before_action :authenticate_user!
def index
end
def add
product = Product.find(params[:product_id])
quantity = params[:quantity].to_i rescue 0
@cart.product_specifics.new(product: product, quantity: quantity)
if @cart.save
redirect_to products_path, notice: "Product added to cart"
else
redirect_to products_path, alert: "Could not add product: #{@cart.errors.full_messages.join(",")}"
end
end
def clear
if @cart.product_specifics.map{|x| x.destroy}
redirect_to carts_path, notice: 'Items were removed from cart.'
else
redirect_to carts_path, notice: 'Error in removing items.'
end
end
def destroy
if @cart.product_specifics.find(params[:id]).destroy
redirect_to carts_path, notice: 'Item was removed from cart.'
else
redirect_to carts_path, notice: 'Error in removing item.'
end
end
end |
# == Schema Information
#
# Table name: public.users
#
# id :integer not null, primary key
# name :string
# flat_no :string
# tower_no :string
# alt_no :string
# blood_group :string
# occupation :string
# family_memebers :integer default("0")
# adult :integer default("0")
# kids :integer default("0")
# bio :text
# candidate :boolean default("false")
# mob_num :string default("")
# email :string default("")
# avatar :string
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default("0"), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :inet
# last_sign_in_ip :inet
# tenant_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# invitation_token :string
# invitation_created_at :datetime
# invitation_sent_at :datetime
# invitation_accepted_at :datetime
# invitation_limit :integer
# invited_by_id :integer
# invited_by_type :string
# invitations_count :integer default("0")
# car_nums :text default("{}"), is an Array
# payment_type :integer
# trial :boolean default("true")
# paid_on :datetime
#
require 'test_helper'
class UserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
class CreateLeagues < ActiveRecord::Migration
def change
create_table :leagues do |t|
t.string :name, limit: 60, null: false
t.string :country, limit: 60, null: false
t.integer :status, index: true, null: false
t.string :codename
t.timestamps null: false
end
end
end
|
FactoryBot.define do
factory :project_report do
project_id { "" }
report_at { "2018-12-02 17:43:01" }
status_cd { "MyText" }
end
end
|
class CacheColumnGenerator < Rails::Generator::NamedBase
attr_accessor :cached_columns, :migration_name
def initialize(args, options = {})
super
@class_name = args[0]
@cached_columns = []
args[1..-1].each do |arg|
col_name, col_type = arg.split(':')
col_type ||= 'string'
@cached_columns.push({:name => col_name, :type => col_type})
end
end
def manifest
file_name = generate_file_name
@migration_name = file_name.camelize
record do |m|
m.migration_template "cache_column_migration.rb.erb",
File.join('db', 'migrate'),
:migration_file_name => file_name
end
end
private
def generate_file_name
names = @cached_columns.map{|a| a[:name].underscore }
names = names[0..-2] + ["and", names[-1]] if names.length > 1
"add_cache_column#{(names.length > 1) ? 's' : ''}_#{names.join("_")}_to_#{@class_name.underscore}"
end
end
|
require 'rails_helper'
RSpec.describe PagesController, type: :controller do
describe "GET the dashboard" do
it "should GET if logged in" do
pages_user = FactoryGirl.create(:user)
sign_in(pages_user)
assert_response :success
end
it "should redirect if not logged in" do
logged_out_user = FactoryGirl.create(:user)
sign_out(logged_out_user)
get :dashboard
expect(response).to be_redirect
end
end
end
|
class ApplyMailer < ActionMailer::Base
default :from => "noreply@deroseforleaders.org"
default :to => "afalkear@gmail.com"
def new_apply_form(message)
@message = message
mail(:subject => "[DeRose Method For Leaders] New Apply Message from company #{@message.company}")
end
end
|
require 'skit/amqp'
describe Skit::AMQP do
describe '#instance' do
subject { Skit::AMQP.instance }
it 'returns a runner instance' do
expect(subject).to be_instance_of(Skit::AMQP::Runner)
end
end
describe '#run' do
let(:instance_double) { double('Runner Instance') }
subject { Skit::AMQP.run { puts '' } }
before do
expect(Skit::AMQP).to receive(:instance).and_return(instance_double)
expect(instance_double).to receive(:run).and_yield
end
it 'delegates to runner instance' do
subject
end
end
end
|
When(/^customer is logged in with a (.*) accounts$/) do |nickname_accounts|
@nickname_account = nickname_accounts.downcase.gsub(" ", "")
on(LoginPage) do |page|
login_data = page.data_for(:acs_nickname_accounts)
@nick_name_account_data = page.data_for(:acs_nickname_accounts)
password = login_data['password']
username = page.data_for(:acs_nickname_accounts)[@nickname_account + "_username"]
ssoid = page.data_for(:acs_nickname_accounts)[@nickname_account + "_ssoid"]
page.login(username, password, ssoid)
end
#on(AccountSummaryPage).wait_for_page_to_load
end
Then(/^customer should be seeing nick name$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
on(AccountSummaryPage).nick_name(account).should == name.to_s
end
Then(/^customer should be seeing nick name on statements and documents page$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
on(AccountSummaryPage).select_statements_link_for(account)
on(StatementsPage).wait_for_page_to_load
on(StatementsPage).page_heading.should include on(StatementsPage).heading
on(StatementsPage).cardsdropdown.lstrip.rstrip.should == name.to_s
on(StatementsPage).logo
end
Then(/^customer should be seeing nick name with account closed on statements and documents page$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
visit(StatementsPage)
on(StatementsPage).cardsdropdown_element.select('Test 100# chars with Cash, Mi ...3308 (Account Closed)')
end
Then(/^customer should be seeing nick name with account restricted on statements and documents page$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
visit(StatementsPage)
on(StatementsPage).cardsdropdown_element.select('WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW ...0793 (Account Restricted)')
end
Then(/^customer should be seeing nick name on make a payment page$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
on(AccountSummaryPage).pay_bill_revoked(account)
a = on(PaymentsDetailsPage).pay_to_account_options.to_s
a.should include name.to_s
end
Then(/^customer should be seeing nick name with account closed on payment page$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
visit(PaymentsDetailsPage)
on(PaymentsDetailsPage).pay_to_account_element.select('Test 100# chars with Cash, Mi ...3308 (Account Closed)')
end
Then(/^customer should be seeing nick name with account restricted on make a payment page$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
visit(PaymentsDetailsPage)
on(PaymentsDetailsPage).pay_to_account_element.select('WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW ...0793 (Account Restricted)')
end
Then(/^customer should be seeing nick name on payment activity page$/) do
puts account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
puts name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
visit(PaymentActivityPage)
sleep 10
puts a = on(PaymentActivityPage).pay_to_accounts_options.to_s
a.should include name.to_s
end
Then(/^customer should be seeing nick name with account closed on payment activity page$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
visit(PaymentActivityPage)
on(PaymentActivityPage).pay_to_accounts_element.select('Test 100# chars with Cash, Mi ...3308 ')
end
Then(/^customer should be seeing nick name with account restricted on payment activity page$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
visit(PaymentActivityPage)
on(PaymentActivityPage).pay_to_accounts_element.select('WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW ...0793')
end
Then(/^customer should be seeing nick name on Transactions and Details page$/) do
account = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_account_number"]
name = on(AccountSummaryPage).data_for(:acs_nickname_accounts)[@nickname_account + "_name"]
on(AccountSummaryPage).select_transaction_link_for(account)
on(TransactionsDetailsPage).wait_for_page_to_load
on(TransactionsDetailsPage).heading.should include on(TransactionsDetailsPage).heading
on(TransactionsDetailsPage).multi_card_names.lstrip.rstrip.should == name.to_s
end
|
#!/usr/bin/ruby -w
require 'facter'
require 'resolv'
require 'ipaddr'
ENV['PATH'] = '/bin:/sbin:/usr/bin:/usr/sbin'
VIRTIFS_CONFIG = '/etc/virtifs'
# Silently exit if the config file doesn't exist, that's an indication
# that this machine doesn't need any virtual interfaces configured.
exit if !File.exist?(VIRTIFS_CONFIG)
# Tell facter to load everything, otherwise it tries to dynamically
# load the individual fact libraries using a very broken mechanism
Facter.loadfacts
# Prepare the configuration of our virtual interfaces
virtcounters = {}
virtifs = {}
IO.foreach(VIRTIFS_CONFIG) do |line|
line.chomp!
next if line =~ /^\s*#/ # Skip comments
next if line =~ /^\s*$/ # And blank lines
hostname, cachedip = line.split
# Try to look up the IP for that hostname
res = Resolv::DNS::new()
ip = nil
begin
addr = res.getaddress(hostname)
ip = addr.to_s
rescue Resolv::ResolvError
ip = cachedip
end
ipaddr = IPAddr.new(ip)
# Find the physical interface to which this virtual interface should
# belong
Facter['interfaces'].value.split(',').each do |nic|
if nic !~ /:/ && nic !~ /__tmp/
ifip = Facter["ipaddress_#{nic}"].value
next if ifip.nil?
mask = Facter["netmask_#{nic}"].value
subnetaddr = IPAddr.new("#{ifip}/#{mask}")
if subnetaddr.include?(ipaddr)
# Calculate the virtual interface name
virtif = nic + ':'
if virtcounters.has_key?(nic)
virtcounters[nic] += 1
else
virtcounters[nic] = 0
end
virtif << virtcounters[nic].to_s
# Store the interface data
virtifs[virtif] = { 'ip' => ip, 'mask' => mask }
break
end
end
end
end
# Clean up any existing virtual interfaces
Facter['interfaces'].value.split(',').each do |nic|
if nic =~ /:/
puts "ifconfig #{nic} down"
system "ifconfig #{nic} down"
end
end
# Activate our virtual interface configuration
virtifs.each do |virtif, virtifdata|
ip = virtifdata['ip']
mask = virtifdata['mask']
puts "ifconfig #{virtif} #{ip} netmask #{mask}"
system "ifconfig #{virtif} #{ip} netmask #{mask}"
end
|
module ClassSpecs
class A; end
class B
@@cvar = :cvar
@ivar = :ivar
end
class C
def self.make_class_variable
@@cvar = :cvar
end
def self.make_class_instance_variable
@civ = :civ
end
end
class D
def make_class_variable
@@cvar = :cvar
end
end
class E
def self.cmeth() :cmeth end
def meth() :meth end
class << self
def smeth() :smeth end
end
CONSTANT = :constant!
end
class F; end
class F
def meth() :meth end
end
class F
def another() :another end
end
class G
def override() :nothing end
def override() :override end
end
class Container
class A; end
class B; end
end
O = Object.new
class << O
def smeth
:smeth
end
end
class H
def self.inherited(sub)
track_inherited << sub
end
def self.track_inherited
@inherited_modules ||= []
end
end
class K < H; end
class I
class J < self
end
end
class K
def example_instance_method
end
def self.example_class_method
end
end
class L; end
class M < L; end
#TODO: Can this be replaced with thie IO helper?
class StubWriter
def write(s)
s && s.size || 0
end
end
class StubWriterWithClose < StubWriter
def close(*args)
end
end
class StubReader
def initialize(s)
@s = s
end
def read(size=2048)
s, @s = @s, nil
s
end
end
class StubReaderWithClose < StubReader
def close(*args)
end
end
class Undef_to_s
if self.methods.include?(:to_s) then
undef to_s
end
end
end
class Class
def example_instance_method_of_class; end
def self.example_class_method_of_class; end
end
class << Class
def example_instance_method_of_metaclass; end
def self.example_class_method_of_metaclass; end
end
class Object
def example_instance_method_of_object; end
def self.example_class_method_of_object; end
end
|
RSpec::Matchers.define :alias_attribute do |alias_name, original_name|
match do |actual|
actual.class.attribute_alias(alias_name) == original_name.to_s
end
failure_message do |actual|
"expected #{actual.class.name} to alias attribute :#{alias_name} by :#{original_name}"
end
end
|
$: << 'cf_spec'
require 'cf_spec_helper'
describe 'CF PHP Buildpack' do
let(:browser) { Machete::Browser.new(@app) }
before(:context) do
@app = Machete.deploy_app(
'app_with_local_dependencies',
{env: {'COMPOSER_GITHUB_OAUTH_TOKEN' => ENV['COMPOSER_GITHUB_OAUTH_TOKEN']}}
)
end
after(:context) do
Machete::CF::DeleteApp.new.execute(@app)
end
context 'the application has vendored dependencies' do
specify do
expect(@app).to be_running
browser.visit_path('/')
expect(browser).to have_body 'App with dependencies running'
end
context 'in offline mode', :cached do
specify do
expect(@app).not_to have_internet_traffic
end
end
end
end
|
LETTER_TO_INDEX = { 'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7,
'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13, 'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18,
'T' => 19, 'U' => 20, 'V' => 21, 'W' => 22, 'X' => 23, 'Y' => 24, 'Z' => 25, '¿'=> 26, '?'=>27, '*'=>28, '_'=>29 }.freeze
# busca en un hash por clave o por valor
def finder(hash, str)
hash[str] || hash.key(str)
end
def vigenere_cipher(string, keys, action)
# encrypted_word ->se almacenará el resultado del cifrado o descifrado
encrypted_word = ''
string.each_char.with_index do |char, i|
key1 = keys[i % keys.length]
key = finder(LETTER_TO_INDEX, key1)
index_char_msg = finder(LETTER_TO_INDEX, char)
if action == false # cifrar
# ex= (x+n)mod(26) -> cifrado
# el tamaño del alfabeto es 26 (no incluye la ñ)
# para poder usar cualquier tamaño del alfabeto cambiamos el 26 por el tamaño del alfabeto que se usa
ex = (index_char_msg + key) % LETTER_TO_INDEX.length
encrypted_word << finder(LETTER_TO_INDEX, ex)
else
# dx= (x-n)mod(26) -> descifrado
dx = (index_char_msg - key) % LETTER_TO_INDEX.length
encrypted_word << finder(LETTER_TO_INDEX, dx)
end
end
encrypted_word.upcase
end
# alfabeto con ñ y espacio
# LETTER_TO_INDEX = {"a"=>0,"b"=> 1,"c"=> 2,"d"=> 3,"e"=> 4,"f"=> 5,"g"=> 6,"h"=> 7,
# "i"=> 8,"j"=> 9, "k"=>10, "l"=>11, "m"=>12, "n"=>13, "o"=>14, "ñ"=>15,"p"=>16, "q"=>17, "r"=>18, "s"=>19, "t"=>20, "u"=>21,
# "v"=>22, "w"=>23, "x"=>24, "y"=>25, "z"=>26, " "=>27}
# msg= "este mensaje se autodestruira ññññ"
# msg= "este mensaje se autodestruira"
# msg= "morrgdxvek"
# msg2= msg.delete(' ')
# clave= "lunes"
puts 'Elija [1].Cifrar o [2].Descifrar'
choice = gets.chomp
if choice == '1'
accion = false
puts 'Introduzca el mensaje'
msg = gets.chomp
msg_org = msg.delete(' ') # quitamos los espacios del mensaje
puts
puts 'Introduzca la clave'
clave = gets.chomp
puts
p "El mensaje cifrado es: #{vigenere_cipher(msg_org, clave, accion)}"
#p vigenere_cipher(msg_org, clave, accion)
elsif choice == '2'
accion = true
puts 'Introduzca el mensaje cifrado'
msg = gets.chomp
msg_org = msg.delete(' ')
puts
puts 'Introduzca la clave'
clave = gets.chomp
puts
p "El mensaje original es: #{vigenere_cipher(msg_org, clave, accion)}"
elsif
p 'Opción no soportada.'
end
|
require 'spec_helper'
require 'rails_helper'
RSpec.describe 'Routing', type: :routing do
it "routes for root url" do
expect(get("/")).to route_to("messages#index")
end
it "Messages index" do
expect(get: "/messages").to route_to(controller: 'messages', action: 'index')
end
it 'To create messages' do
expect(post: '/messages').to route_to(controller: 'messages', action: 'create')
end
it 'redirect any path to root path' do
expect(get: '/any_path').to route_to(controller: 'messages', action: 'index', unmatched: "any_path")
end
end |
# frozen_string_literal: true
namespace :test do
desc "Reproduces an error when an application gets into a deadlock during autoloading"
task :finish_him, %i[autoload_mode] => :environment do |_, args|
require "open3"
ENV["AUTOLOAD_MODE"] = args[:autoload_mode] || "zeitwerk"
Thread.report_on_exception = false
make_request = proc { |action| Thread.new { HTTP.get("http://localhost:3000/#{action}") } }
Open3.popen2("rails s", chdir: Rails.root) do |_stdin, stdout, wait_thr|
Signal.trap("INT") do
print "Exiting...\n"
Thread.list
.then { |threads| threads.select { |thr| thr.status == "run" } }
.then { |threads| threads - [Thread.current] }
.each(&:join)
Process.kill("KILL", wait_thr.pid)
exit
end
stdout.each_line { |line| break if line.match?(/use ctrl\-c/i) }
loop do
threads = %w[first second].map(&make_request)
FileUtils.touch(Rails.root.join("app", "services", "first_module.rb"))
sleep 0.5
threads.map(&:kill)
print "Requested...\n"
if (debug_body = HTTP.get("http://localhost:3000/rails/locks").body).present?
print debug_body
break
end
end
Process.kill("KILL", wait_thr.pid)
end
end
desc "Access to three constants from different threads, which causes script execution to freeze"
task access_in_threads: :environment do
200.times do
p "Trying..."
Rails.application.reloader.reload!
# Sleep forever
Thread.new { FirstModule }
Thread.new { SecondModule }
Thread.new { ThirdModule }
SecondModule # When we access this constant, script stuck or crash with segmentation fault
end
end
end
|
class ReviewsController < ApplicationController
include ProjectScoped
def create
review = Review.new review_params
if review.save
flash[:success] = 'Succesfully saved your review for this source!'
redirect_to project_source_url(@project, review.source)
else
flash[:danger] = 'Failed to save your review for this source...'
redirect_to (review.source.present? ? project_source_url(@project, review.source) : project_sources_url(@project))
end
end
def update
review = Review.find params[:id]
if review.update(review_params)
flash[:success] = 'Succesfully updated your review for this source!'
redirect_to project_source_url(@project, review.source)
else
flash[:danger] = 'Failed to update your review for this source...'
redirect_to (review.source.present? ? project_source_url(@project, review.source) : project_sources_url(@project))
end
end
def destroy
review = Review.find params[:id]
if review.destroy
flash[:success] = 'Succesfully deleted your review for this source!'
redirect_to project_source_url(@project, review.source)
else
flash[:danger] = 'Failed to delete your review for this source...'
redirect_to (review.source.present? ? project_source_url(@project, review.source) : project_sources_url(@project))
end
end
protected
def review_params
prms = params.require(:review).permit(
:source_id,
:comment,
:rating
)
prms[:user_id] = current_user.id
prms
end
end
|
class Admin::VendorsController < Admin::BaseController
resource_controller
index.response do |wants|
wants.html { render :action => :index }
wants.json { render :json => @collection.to_json}
end
new_action.response do |wants|
wants.html {render :action => :new, :layout => false}
end
create.response do |wants|
# go to edit form after creating as new product
wants.html {redirect_to :controller=>'admin/vendors', :action=>'index' }
end
update.response do |wants|
# override the default redirect behavior of r_c
# need to reload Product in case name / permalink has changed
wants.html {redirect_to :controller=>'admin/vendors', :action=>'index' }
end
# override the destory method to set deleted_at value
# instead of actually deleting the product.
def destroy
@vendor = Vendor.find(params[:id])
@vendor.deleted_at = Time.now()
if @vendor.save
flash[:notice] = "Vendor has been deleted"
else
flash[:notice] = "Vendor could not be deleted"
end
respond_to do |format|
format.html { redirect_to collection_url }
format.js { render_js_for_destroy }
end
end
#
# def clone
# load_object
# @new = @product.duplicate
#
# if @new.save
# flash[:notice] = "Product has been cloned"
# else
# flash[:notice] = "Product could not be cloned"
# end
#
# redirect_to edit_admin_product_url(@new)
# end
#
private
def collection
@search = Vendor.searchlogic(params[:search])
@search.order ||= "descend_by_created_at"
@search.deleted_at_null = true
# QUERY - get per_page from form ever??? maybe push into model
# @search.per_page ||= Spree::Config[:orders_per_page]
# turn on show-complete filter by default
# unless params[:search] && params[:search][:completed_at_not_null]
# @search.completed_at_not_null = true
# end
@collection = @search.paginate(:per_page => Spree::Config[:orders_per_page],
:page => params[:page])
end
end
|
RSpec.describe Yaks::Resource::Form::Fieldset do
subject(:fieldset) { described_class.new(fields: []) }
describe '#type' do
its(:type) { should equal :fieldset }
end
end
|
class InvoiceItem < ApplicationRecord
validates :quantity, :unit_price, presence: true
belongs_to :item
belongs_to :invoice
def self.random
id = InvoiceItem.pluck(:id).sample
InvoiceItem.find(id)
end
end
|
Pod::Spec.new do |s|
s.name = 'LGHelper'
s.version = '1.1.2'
s.platform = :ios, '6.0'
s.license = 'MIT'
s.homepage = 'https://github.com/Friend-LGA/LGHelper'
s.author = { 'Grigory Lutkov' => 'Friend.LGA@gmail.com' }
s.source = { :git => 'https://github.com/Friend-LGA/LGHelper.git', :tag => s.version }
s.summary = 'iOS helper contains a lot of useful macrosses, methods and hints for every day'
s.library = 'z'
s.requires_arc = true
s.source_files = 'LGHelper/*.{h,m}'
s.source_files = 'LGHelper/**/*.{h,m}'
end
|
class Product < ActiveRecord::Base
attr_accessible :name, :description, :is_visible, :price, :sku, :collection_id, :lat, :lon, :zoom, :token, :in_stock_at
belongs_to :collection
has_one :picture, as: :assetable, dependent: :destroy, conditions: {is_main: true}
has_many :pictures, as: :assetable, dependent: :destroy, conditions: {is_main: false}
fileuploads :picture, :pictures
translates :name, :description
attr_accessible *all_translated_attribute_names
scope :visible, where(is_visible: true)
scope :un_visible, where(is_visible: false)
include AbAdmin::Concerns::AdminAddition
scope :admin, includes(:translations, :picture)
alias_attribute :title, :name
validates :sku, presence: true
#include AbAdmin::Concerns::HasTracking
def publish!
update_column(:is_visible, true)
end
def un_publish!
update_column(:is_visible, false)
end
end
|
class HeadlinerSection < ActiveRecord::Base
belongs_to :headliner_box
belongs_to :section
end
|
class FamiliesController < ApplicationController
skip_before_action :authenticate_user!, only: [:new, :create]
skip_after_action :verify_authorized
def index
@families = Family.all
end
def show
@family = Family.find(params[:id])
authorize @family
end
def new
@family = Family.new
end
def create
@family = Family.new(family_params)
if @family.save
redirect_to new_user_registration_path
end
end
private
def family_params
params.require(:family).permit(:name)
end
end
|
# контроллер блогов контентной части сайта
# возвращает:
# - список постов
# - пост
# - json-массив с постами для текущей категории в backbone
#
class Content::BlogsController < Content::BaseController
before_action :get_locale
before_action :set_category
before_action :navigation, only: [:list, :item]
protect_from_forgery except: [:fetch]
def list
@items = Post.all
end
def item
@items = @category.posts
end
def fetch
if fetch_params == 'all'
@posts = Post.all
else
category = Category.find_by_slug fetch_params
@posts = category.posts if category.present?
end
respond_to do |format|
if @posts
format.json { render action: 'fetch' }
else
format.json { head :no_content }
end
end
end
def get_item
@category
end
def page_title_prefix
# hardcode?
if @category
'Блоги:'
end
end
private
def set_category
@category = Category.find_by slug: params[:slug]
end
def fetch_params
params.require(:collection)
end
def navigation
items = []
items << { href: blogs_path, title: 'Все записи', category: 'all' }
PostCategory.all.each do |i|
items << { href: blogs_item_path(i.slug), title: i.title, category: i.slug }
end
@navigation = {
fixed: true,
helper: T("Тэги"),
title: T("Выберите категорию блога"),
items: items
}
end
end
|
class ChangeColumnName < ActiveRecord::Migration[6.1]
def change
rename_column :sightings, :longtitude, :longitude
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.