text stringlengths 10 2.61M |
|---|
###########################################
# tc_sound.rb
#
# Test suite for the win32-sound package.
############################################
base = File.basename(Dir.pwd)
if base == "test" || base =~ /win32-sound/
Dir.chdir("..") if base == "test"
$LOAD_PATH.unshift Dir.pwd + '/lib'
Dir.chdir("test") if base =~ /win32-sound/
end
puts "You may hear some funny noises - don't panic"
sleep 1
require "test/unit"
require "win32/sound"
include Win32
class TC_Sound < Test::Unit::TestCase
def setup
@wav = "c:\\windows\\media\\chimes.wav"
end
def test_version
assert_equal("0.4.0", Sound::VERSION)
end
def test_beep
assert_respond_to(Sound, :beep)
assert_nothing_raised{ Sound.beep(55,100) }
assert_raises(SoundError){ Sound.beep(0,100) }
assert_raises(ArgumentError){ Sound.beep }
assert_raises(ArgumentError){ Sound.beep(500) }
assert_raises(ArgumentError){ Sound.beep(500,500,5) }
end
def test_devices
assert_respond_to(Sound, :devices)
assert_nothing_raised{ Sound.devices }
assert_kind_of(Array,Sound.devices)
end
def test_stop
assert_respond_to(Sound, :stop)
assert_nothing_raised{ Sound.stop }
assert_nothing_raised{ Sound.stop(true) }
end
def test_get_volume
assert_respond_to(Sound, :wave_volume)
assert_respond_to(Sound, :get_wave_volume)
assert_nothing_raised{ Sound.get_wave_volume }
assert_kind_of(Array, Sound.get_wave_volume)
assert_equal(2, Sound.get_wave_volume.length)
end
def test_set_volume
assert_respond_to(Sound, :set_wave_volume)
assert_nothing_raised{ Sound.set_wave_volume(30000) } # About half
assert_nothing_raised{ Sound.set_wave_volume(30000, 30000) }
end
def test_play
assert_respond_to(Sound, :play)
assert_nothing_raised{ Sound.play(@wav) }
assert_nothing_raised{ Sound.play("SystemAsterisk", Sound::ALIAS) }
end
def test_expected_errors
assert_raises(SoundError){ Sound.beep(-1, 1) }
end
def test_constants
assert_not_nil(Sound::ALIAS)
assert_not_nil(Sound::APPLICATION)
assert_not_nil(Sound::ASYNC)
assert_not_nil(Sound::FILENAME)
assert_not_nil(Sound::LOOP)
assert_not_nil(Sound::MEMORY)
assert_not_nil(Sound::NODEFAULT)
assert_not_nil(Sound::NOSTOP)
assert_not_nil(Sound::NOWAIT)
assert_not_nil(Sound::PURGE)
assert_not_nil(Sound::SYNC)
end
def teardown
@wav = nil
end
end |
require 'spec_helper'
describe Entry do
it { should have_many(:tasks).through(:entry_tasks) }
it { should have_many(:entry_tasks) }
it { should belong_to(:user) }
[:date_of_service,:duration_of_service,:group_size].each do |m|
it { should validate_presence_of(m) }
end
end
|
require 'csv_row_model/concerns/attributes_base'
require 'csv_row_model/concerns/import/parsed_model'
require 'csv_row_model/internal/import/attribute'
module CsvRowModel
module Import
module Attributes
extend ActiveSupport::Concern
include AttributesBase
include ParsedModel
# Mapping of column type classes to a parsing lambda. These are applied after {Import.format_cell}.
# Can pass custom Proc with :parse option.
CLASS_TO_PARSE_LAMBDA = {
nil => ->(s) { s }, # no type given
Boolean => ->(s) { s =~ BooleanFormatValidator.false_boolean_regex ? false : true },
String => ->(s) { s },
Integer => ->(s) { s.to_i },
Float => ->(s) { s.to_f },
DateTime => ->(s) { s.present? ? DateTime.parse(s) : s },
Date => ->(s) { s.present? ? Date.parse(s) : s }
}.freeze
included do
ensure_attribute_method
end
def attribute_objects
@attribute_objects ||= begin
parsed_model.valid?
_attribute_objects(parsed_model.errors)
end
end
# return [Hash] a map changes from {.column}'s default option': `column_name -> [value_before_default, default_set]`
def default_changes
column_names_to_attribute_value(self.class.column_names, :default_change).delete_if {|k, v| v.blank? }
end
protected
# to prevent circular dependency with parsed_model
def _attribute_objects(parsed_model_errors={})
index = -1
array_to_block_hash(self.class.column_names) do |column_name|
Attribute.new(column_name, source_row[index += 1], parsed_model_errors[column_name], self)
end
end
class_methods do
protected
def merge_options(column_name, options={})
original_options = columns[column_name]
parsed_model_class.add_type_validation(column_name, columns[column_name]) unless original_options[:validate_type]
super
end
def define_attribute_method(column_name)
return if super { original_attribute(column_name) }.nil?
parsed_model_class.add_type_validation(column_name, columns[column_name])
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe Team, :type => :model do
let(:team) {create(:team)}
let(:team_with_4) {create(:team_with_4_users)}
it 'should have valid factories' do
expect(
create(:team)
).to be_valid
expect(
create(:team_with_4_users)
).to be_valid
end
describe 'class' do
it 'should be able to have users' do
expect(team_with_4.users.count).to eq(4)
end
it 'needs a name' do
team = {name: nil}
team = Team.new(team)
team.save
expect(team.errors).to have_key(:name)
end
end
end
|
#!/usr/bin/env ruby
#
# Prime permutations
# http://projecteuler.net/problem=49
#
# The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases
# by 3330, is unusual in two ways: (i) each of the three terms are prime, and,
# (ii) each of the 4-digit numbers are permutations of one another.
#
# There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes,
# exhibiting this property, but there is one other 4-digit increasing sequence.
#
# What 12-digit number do you form by concatenating the three terms in this
# sequence?
#
require "prime"
class Numeric
def primes_upto(max)
if block_given?
Prime.take_while {|x| x <= max }.each {|y| yield y if y >= self }
else
Prime.take_while {|x| x <= max }.select {|y| y >= self }
end
end
def perm_of?(num)
to_s.chars.permutation.map(&:join).map(&:to_i).include?(num)
end
end
p 1000.primes_upto(9999).combination(2).map {|x, y|
[x, y, 2*y-x] if 2*y-x<10_000 and (2*y-x).prime? and x.perm_of?(y) and y.perm_of?(2*y-x)
}.compact.last.join.to_i
# => 296962999629
|
class DataTypesController < ApplicationController
before_filter :authenticate_user!
before_action :set_data_type, only: [:show, :edit, :update, :destroy]
# GET /data_types
# GET /data_types.json
def index
data_types_scope = DataType.current
@data_types = data_types_scope.search_by_terms(parse_search_terms(params[:search])).set_order(params[:order], "name asc").page_per(params) #.page(params[:page] ? params[:page] : 1).per(params[:per_page] == "all" ? nil : params[:per_page])
end
# GET /data_types/1
# GET /data_types/1.json
def show
end
# GET /data_types/new
def new
@data_type = DataType.new
end
# GET /data_types/1/edit
def edit
end
# POST /data_types
# POST /data_types.json
def create
@data_type = DataType.logged_new(data_type_params, current_user)
respond_to do |format|
if @data_type.save
format.html { redirect_to @data_type, notice: 'DataType was successfully created.' }
format.json { render action: 'show', status: :created, location: @data_type }
else
format.html { render action: 'new' }
format.json { render json: @data_type.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /data_types/1
# PATCH/PUT /data_types/1.json
def update
respond_to do |format|
if @data_type.logged_update(data_type_params)
format.html { redirect_to @data_type, notice: 'DataType was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @data_type.errors, status: :unprocessable_entity }
end
end
end
# DELETE /data_types/1
# DELETE /data_types/1.json
def destroy
@data_type.destroy
respond_to do |format|
format.html { redirect_to data_types_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_data_type
@data_type = DataType.current.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def data_type_params
params.require(:data_type).permit(:name, :storage, :range, :length, :values, :multiple)
end
end
|
require 'rails_helper'
RSpec.describe Reservation, type: :model do
context "validations" do
it { should validate_presence_of(:start_date) }
it { should validate_presence_of(:end_date) }
end
context "can calculate total for nights in stay" do
it "calculates correctly" do
space = create(:space)
order = create(:order)
reservation = Reservation.create(start_date: "2016/07/15", end_date: "2016/07/17", space: space, order: order, total: 10.0)
expect(reservation.total_nights).to eq(2)
end
end
context "can calculate total price for a trip" do
it "calculates correctly" do
space = create(:space, price: 5)
order = create(:order)
reservation = Reservation.create(start_date: "2016/07/15", end_date: "2016/07/17", space: space, order: order, total: 10.0)
expect(reservation.total_price).to eq(10)
end
end
context "validations" do
it "will allow creation if no reservations exist" do
space = create(:space)
order = create(:order)
new_reservation = Reservation.new(space: space, order: order, total: 15, start_date: "2016/07/15", end_date: "2016/07/20")
expect(new_reservation).to be_valid
end
it "won't allow creation if start date is taken" do
reservation = create(:reservation)
new_reservation = Reservation.new(space: reservation.space, order: reservation.order, total: 15, start_date: reservation.start_date, end_date: "2016/07/20")
expect(new_reservation).to_not be_valid
end
it "won't allow creation if end date is taken" do
reservation = create(:reservation)
new_reservation = Reservation.new(space: reservation.space, order: reservation.order, total: 15, start_date: "2016/07/14", end_date: reservation.end_date)
expect(new_reservation).to_not be_valid
end
it "won't validate if end date is between existing start/end dates" do
reservation = create(:reservation)
new_reservation = Reservation.new(space: reservation.space, order: reservation.order, total: 15, start_date: "2016/07/14", end_date: "2016/07/16")
expect(new_reservation).to_not be_valid
end
it "won't validate if start date is between existing start/end dates" do
reservation = create(:reservation)
new_reservation = Reservation.new(space: reservation.space, order: reservation.order, total: 15, start_date: "2016/07/16", end_date: "2016/07/22")
expect(new_reservation).to_not be_valid
end
it "won't validate if both dates are between start/end dates" do
reservation = create(:reservation)
new_reservation = Reservation.new(space: reservation.space, order: reservation.order, total: 15, start_date: "2016/07/16", end_date: "2016/07/17")
expect(new_reservation).to_not be_valid
end
it "won't validate if both dates are contain exisiting start/end dates" do
reservation = create(:reservation)
new_reservation = Reservation.new(space: reservation.space, order: reservation.order, total: 15, start_date: "2016/07/14", end_date: "2016/07/19")
expect(new_reservation).to_not be_valid
end
it "validates if new end date is on exisiting start date" do
reservation = create(:reservation)
new_reservation = Reservation.new(space: reservation.space, order: reservation.order, total: 15, start_date: "2016/07/13", end_date: "2016/07/15")
expect(new_reservation).to be_valid
end
it "validates if new start date is on exisiting end date" do
reservation = create(:reservation)
new_reservation = Reservation.new(space: reservation.space, order: reservation.order, total: 15, start_date: "2016/07/18", end_date: "2016/07/22")
expect(new_reservation).to be_valid
end
end
end
|
class AddLanguagesToTeamReportSettings < ActiveRecord::Migration[4.2]
def change
RequestStore.store[:skip_rules] = true
Team.find_each do |team|
settings = team.settings || {}
settings = settings.with_indifferent_access
if settings.has_key?('disclaimer') || settings.has_key?('introduction') || settings.has_key?('use_introduction') || settings.has_key?('use_disclaimer')
puts "[#{Time.now}] Updating team #{team.name}..."
new_settings = settings.clone
disclaimer = new_settings.delete('disclaimer')
introduction = new_settings.delete('introduction')
use_disclaimer = new_settings.delete('use_disclaimer')
use_introduction = new_settings.delete('use_introduction')
language = team.get_language || 'en'
new_settings[:report] = {}
new_settings[:report][language] = {
disclaimer: disclaimer,
introduction: introduction,
use_disclaimer: use_disclaimer,
use_introduction: use_introduction
}
team.settings = new_settings
team.save!
end
end
RequestStore.store[:skip_rules] = false
end
end
|
namespace :ab do
desc "A notification email to remind a user about the annual fee"
task annual_fee_reminder_email: :environment do
CardAccount::SendAnnualFeeReminder.()
end
end
|
class SearchController < ApplicationController
def index
if params[:screen_name].blank?
flash[:search_form_message] = 'Please enter a Twitter handle'
redirect_to root_path and return if params[:screen_name].blank?
end
redirect_to user_path(:id => params[:screen_name])
end
end
|
# frozen_string_literal: true
require 'tempfile'
require 'nice_hash'
require 'yaml'
require 'tilt/erubi'
require 'erubi/capture_end'
require 'json'
require 'pathname'
require 'fileutils'
require 'etc'
module TemplateCLI
# Main application
class App # rubocop:disable Metrics/ClassLength
TASKS = {
generate: lambda { |options| # rubocop:disable Metrics/BlockLength
source_read = App::GETTERS[:contents_from_file]
.call({
error_if_empty: true,
error_message: 'source need a string as input',
file_or_path: options[:source]
})
options_sanitized = {
locals: App::GETTERS[:locals].call(options[:locals]),
source: source_read[:contents]
}
p options_sanitized
# if source is a valid file read then no need to write to TempFile
if source_read[:read_success]
return App::UTILS[:return_template].call({
path_file_output: options['file-output'],
template_output: App::GETTERS[:template]
.call({
locals: options_sanitized[:locals],
source: source_read[:file_or_path_sanitized]
})
})
end
# need to write as TempFile
file_tmp = App::GETTERS[:template_write_tmp].call(options_sanitized[:source])
begin
template_output = App::GETTERS[:template].call({ locals: options_sanitized[:locals], source: file_tmp.path })
App::UTILS[:return_template].call({
path_file_output: options['file-output'],
template_output: template_output
})
ensure
file_tmp.close
file_tmp.unlink
end
}
}.freeze
GETTERS = {
template: lambda { |options|
Tilt::ErubiTemplate.new(options[:source], engine_class: Erubi::CaptureEndEngine)
.render(self, options[:locals])
},
contents_from_file: lambda { |options|
if options[:error_if_empty]
App::VALIDATORS[:string].call({ error_message: options[:error_message] || 'Empty contents is not permitted.',
value: options[:file_or_path] })
end
file_or_path_sanitized = App::UTILS[:sanitize_arg].call(options[:file_or_path])
file_or_path_sanitized = file_or_path_sanitized.start_with?('~') ? file_or_path_sanitized.sub!('~', Etc.getpwuid.dir) : file_or_path_sanitized # rubocop:disable Layout/LineLength
begin
contents = File.read(file_or_path_sanitized)
return {
contents: contents,
file_or_path_sanitized: file_or_path_sanitized,
read_success: true
}
rescue StandardError
return {
contents: file_or_path_sanitized,
file_or_path_sanitized: file_or_path_sanitized,
read_success: false
}
end
},
locals: lambda { |locals_string_or_filepath|
return locals_string_or_filepath if locals_string_or_filepath.nil? || locals_string_or_filepath.empty?
file_read = App::GETTERS[:contents_from_file]
.call({ file_or_path: locals_string_or_filepath })
# handle json since ruby escapes the string and it causes issues
begin
json_payload = App::VALIDATORS[:valid_json]
.call(file_read[:contents])
raise StandardError 'Not valid json.' unless json_payload[:success]
return json_payload[:json]
rescue StandardError
# attempt to load as yaml
template_value = YAML.safe_load(file_read[:contents])
unless template_value
raise StandardError,
'Template load as yaml failed'
end
return template_value.to_json.json
end
},
template_write_tmp: lambda { |contents|
file = Tempfile.new(['template_tmp', '.txt'])
file.write(contents)
# have to flush it for contents to be available for other functions.
file.flush
file
},
sanitized_file_read_contents: lambda { |x|
x.gsub! '\"', '"'
}
}.freeze
VALIDATORS = {
string: lambda { |x|
raise StandardError, x.error_message if x.nil? || x.empty?
x
},
valid_json: lambda { |x|
begin
return {
json: JSON.parse(x),
success: true
}
rescue StandardError
{
json: nil,
success: false
}
end
}
}.freeze
UTILS = {
return_template: lambda { |options|
path_output_sanitized = options[:path_file_output] ? App::UTILS[:sanitize_arg].call(options[:path_file_output]) : nil
if options[:path_file_output]
FileUtils.mkdir_p(File.dirname(path_output_sanitized))
File.open(path_output_sanitized, 'w') do |file_out|
file_out.write(options[:template_output])
file_out.close
end
else
puts options[:template_output]
end
},
sanitize_arg: lambda { |x|
return x if x.nil? || x.empty?
returned = x
if returned.start_with?('"') && returned.end_with?('"')
returned = returned.delete_prefix('"').delete_suffix('"')
end
if returned.start_with?("'") && returned.end_with?("'")
returned = returned.delete_prefix("'").delete_suffix("'")
end
returned
}
}.freeze
end
end
|
class Cart < ActiveRecord::Base
ECO_TAX = 2
has_many :line_items, dependent: :destroy
def add_product(product_id, quantity)
current_item = line_items.find_by(product_id: product_id)
if current_item
quantity ||= 1
current_item.quantity += quantity.to_i
else
current_item = line_items.build(product_id: product_id)
end
current_item
end
end
|
require_relative 'db_connection'
require 'active_support/inflector'
require "byebug"
# NB: the attr_accessor we wrote in phase 0 is NOT used in the rest
# of this project. It was only a warm up.
class SQLObject
attr_reader :cols
def self.columns
res = []
var = self.table_name
if @cols.nil?
@cols = DBConnection.execute2(<<-SQL)
SELECT
*
FROM
#{var}
SQL
@cols = @cols[0].map! { |col| col.to_sym}
end
@cols
end
def self.finalize!
self.columns.each do |col|
define_method(col) { return self.attributes[col] }
define_method(col.to_s + "=") { |val| self.attributes[col] = val }
end
end
def self.table_name=(table_name)
instance_variable_set("@" + self.to_s.downcase + "s", table_name)
end
def self.table_name
return self.to_s.downcase + "s"
end
def self.all
var = self.table_name
rows = DBConnection.execute(<<-SQL)
SELECT
#{var}.*
FROM
#{var}
SQL
self.parse_all(rows)
end
def self.parse_all(results)
arr = []
results.each do |hash|
arr << self.new(hash)
end
arr
end
def self.find(id)
var = self.table_name
res = DBConnection.execute(<<-SQL, id)
SELECT
#{var}.*
FROM
#{var}
WHERE
#{var}.id = ?
SQL
return nil if res[0] == nil
self.new(res[0])
end
def initialize(params = {})
self.class.finalize!
params.each do |k, v|
# define_method(k.to_s + "=") { |v| @attributes[k] = v } unless !params[k].nil?
raise "unknown attribute '#{k}'" unless self.class.columns.include?(k.to_sym)
send(k.to_s + "=", v)
end
end
def attributes
@attributes ||= {}
@attributes
# ...
end
def attribute_values
values = self.class.columns.map{|name| self.attributes[name.to_sym] }
values
end
def insert
col_names = self.class.columns.join(",")
question_marks = (["?"] * col_names.split(",").length).join(",")
values = col_names.split(",").map{|name| self.attributes[name.to_sym] }
# debugger
DBConnection.execute(<<-SQL, values)
INSERT INTO
#{self.class.table_name} (#{col_names})
VALUES
(#{question_marks})
SQL
self.id = DBConnection.last_insert_row_id
end
def update
arr = []
col_names = self.class.columns
# question_marks = (["?"] * col_names.split(",").length).join(",")
values = col_names.map{|name| self.attributes[name] }
# debugger
col_names.each_with_index do |name, i|
arr << (name.to_s + " = " + "?")
end
string = arr.join(", ")
DBConnection.execute(<<-SQL, values)
UPDATE
#{self.class.table_name}
SET
#{string}
WHERE
id = #{self.id}
SQL
self.id = DBConnection.last_insert_row_id
end
def save
if self.class.find(self.id).nil?
self.insert
else
self.update
end
end
end
|
class PasswordsController < Devise::PasswordsController
authorize_resource :class => false
skip_before_filter :verify_authenticity_token, :only => [:create, :update]
def create
self.resource = User.find_by_email(resource_params['email'])
yield resource if block_given?
@token = resource.send_reset_password_instructions
if successfully_sent?(resource)
@resource = resource
@success = true
render "create.json"
else
@success = false
@error = resource.errors.full_messages.join(" ")
render "create.json", status: 500
end
end
def update
self.resource = resource_class.reset_password_by_token(resource_params)
yield resource if block_given?
if resource.errors.empty?
resource.unlock_access! if unlockable?(resource)
flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
set_flash_message(:notice, flash_message) if is_flashing_format?
@success = true
render "update.json"
else
@success = false
@error = resource.errors.full_messages.join(" ")
render "update.json", status: 500
end
end
end
|
class Billiard
def initialize(width, depth, ball_radius)
@width = width .to_f
@depth = depth .to_f
@ball_radius = ball_radius.to_f
end
def shoot(x0, y0, theta0, shot_length)
x0 = x0 .to_f
y0 = y0 .to_f
theta0 = theta0 .to_f
shot_length = shot_length.to_f
theta0_in_radian = theta0 * Math::PI / 180.0
cos0 = Math.cos(theta0_in_radian)
sin0 = Math.sin(theta0_in_radian)
x_travel = shot_length * cos0
y_travel = shot_length * sin0
x_travel_before_first_wall = cos0 > 0 ? @width - @ball_radius - x0 \
: cos0 < 0 ? -(x0 - @ball_radius) \
: nil
y_travel_before_first_wall = sin0 > 0 ? @depth - @ball_radius - y0 \
: sin0 < 0 ? -(y0 - @ball_radius) \
: nil
virtual_width = @width - @ball_radius * 2
virtual_depth = @depth - @ball_radius * 2
num_hit_vertical_wall = x_travel_before_first_wall.nil? || x_travel.abs <= x_travel_before_first_wall.abs ? 0 \
: ((x_travel.abs - x_travel_before_first_wall.abs) / virtual_width).to_i + 1
num_hit_horizontal_wall = y_travel_before_first_wall.nil? || y_travel.abs <= y_travel_before_first_wall.abs ? 0 \
: ((y_travel.abs - y_travel_before_first_wall.abs) / virtual_depth).to_i + 1
is_x_to_be_reversed = cos0 == 0 ? false : cos0 > 0 ? num_hit_vertical_wall .odd? : num_hit_vertical_wall .even?
is_y_to_be_reversed = sin0 == 0 ? false : sin0 > 0 ? num_hit_horizontal_wall.odd? : num_hit_horizontal_wall.even?
if num_hit_vertical_wall == 0
x_final = x0 + x_travel
else
virtual_x_final = (x_travel - x_travel_before_first_wall).abs % virtual_width
virtual_x_final = (virtual_width - virtual_x_final) if is_x_to_be_reversed
x_final = virtual_x_final + @ball_radius
end
if num_hit_horizontal_wall == 0
y_final = y0 + y_travel
else
virtual_y_final = (y_travel - y_travel_before_first_wall).abs % virtual_depth
virtual_y_final = (virtual_depth - virtual_y_final) if is_y_to_be_reversed
y_final = virtual_y_final + @ball_radius
end
[x_final, y_final]
end
end
if __FILE__ == $0
width, depth, x0, y0, ball_radius, theta0, shot_length = gets.split.map(&:to_i)
billiard = Billiard.new(width, depth, ball_radius)
puts billiard.shoot(x0, y0, theta0, shot_length).join(' ')
end
|
Gem::Specification.new do |s|
s.name = 'kashflow_soap'
s.version = '0.0.3'
s.date = '2015-10-07'
s.authors = ["Ed Clements","Stephan Yu","Nicola Ferri"]
s.summary = "A Savon wrapper for the KashFlow accounting software API"
s.email = "ed.clements@gmail.com"
s.files = ["lib/kashflow_soap.rb"]
s.license = 'MIT'
end
|
class ManageIQ::Providers::Vmware::CloudManager::OrchestrationTemplate < OrchestrationTemplate
def parameter_groups
# Define vApp's general purpose parameters.
groups = [OrchestrationTemplate::OrchestrationParameterGroup.new(
:label => "vApp Parameters",
:parameters => vapp_parameters,
)]
# Parse template's OVF file
ovf_doc = MiqXml.load(content)
# Collect VM-specific parameters from the OVF template if it is a valid one.
groups.concat(vm_param_groups(ovf_doc.root)) unless ovf_doc.root.nil?
groups
end
def vapp_parameters
[
OrchestrationTemplate::OrchestrationParameter.new(
:name => "deploy",
:label => "Deploy vApp",
:data_type => "boolean",
:default_value => true,
:constraints => [
OrchestrationTemplate::OrchestrationParameterBoolean.new
]
),
OrchestrationTemplate::OrchestrationParameter.new(
:name => "powerOn",
:label => "Power On vApp",
:data_type => "boolean",
:default_value => false,
:constraints => [
OrchestrationTemplate::OrchestrationParameterBoolean.new
]
)
]
end
def vm_param_groups(ovf)
groups = []
# Parse the XML template document for specific vCloud attributes.
ovf.each_element("//vcloud:GuestCustomizationSection") do |el|
vm_id = el.elements["vcloud:VirtualMachineId"].text
vm_name = el.elements["vcloud:ComputerName"].text
groups << OrchestrationTemplate::OrchestrationParameterGroup.new(
:label => vm_name,
:parameters => [
# Name of the provisioned instance.
OrchestrationTemplate::OrchestrationParameter.new(
:name => "instance_name-#{vm_id}",
:label => "Instance name",
:data_type => "string",
:default_value => vm_name
),
# List of available VDC networks.
OrchestrationTemplate::OrchestrationParameter.new(
:name => "vdc_network-#{vm_id}",
:label => "Network",
:data_type => "string",
:default_value => "(default)",
:constraints => [
OrchestrationTemplate::OrchestrationParameterAllowedDynamic.new(:fqname => "/Cloud/Orchestration/Operations/Methods/Available_Vdc_Networks")
]
)
]
)
end
groups
end
def self.eligible_manager_types
[ManageIQ::Providers::Vmware::CloudManager]
end
def validate_format
if content
ovf_doc = MiqXml.load(content)
!ovf_doc.root.nil? && nil
end
rescue REXML::ParseException => err
err.message
end
end
|
class BestHand
def self.process(hand, deck)
hand.sort!
results = []
(0..deck.length).each do |time|
hand.combination(hand.length - time).each do |combination|
new_hand = combination | deck[0...time]
results << HandAnalyzer.analyze(new_hand)
end
end
results.sort_by(&:value).reverse.first
end
end
|
class FbInvoicesController < ApplicationController
# GET /fb_invoices
# GET /fb_invoices.xml
def index
@fb_invoices = FbInvoice.find_by_id '(firma = 399)'
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @fb_invoices }
end
end
# GET /fb_invoices/1
# GET /fb_invoices/1.xml
def show
@fb_invoice = FbInvoice.find_by_id(params[:id])
@fb_invoice_hash = @fb_invoice.attributes.symbolize_keys
@fb_invoice_keys = @fb_invoice_hash.keys.sort{|n,m| n.to_s <=> m.to_s }
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @fb_invoice }
end
end
# GET /fb_invoices/new
# GET /fb_invoices/new.xml
def new
@fb_invoice = FbInvoice.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @fb_invoice }
end
end
# GET /fb_invoices/1/edit
def edit
@fb_invoice = FbInvoice.find(params[:id])
end
# POST /fb_invoices
# POST /fb_invoices.xml
def create
@fb_invoice = FbInvoice.new(params[:fb_invoice])
respond_to do |format|
if @fb_invoice.save
format.html { redirect_to(@fb_invoice, :notice => 'Fb invoice was successfully created.') }
format.xml { render :xml => @fb_invoice, :status => :created, :location => @fb_invoice }
else
format.html { render :action => "new" }
format.xml { render :xml => @fb_invoice.errors, :status => :unprocessable_entity }
end
end
end
# PUT /fb_invoices/1
# PUT /fb_invoices/1.xml
def update
@fb_invoice = FbInvoice.find(params[:id])
respond_to do |format|
if @fb_invoice.update_attributes(params[:fb_invoice])
format.html { redirect_to(@fb_invoice, :notice => 'Fb invoice was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @fb_invoice.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /fb_invoices/1
# DELETE /fb_invoices/1.xml
def destroy
@fb_invoice = FbInvoice.find(params[:id])
@fb_invoice.destroy
respond_to do |format|
format.html { redirect_to(fb_invoices_url) }
format.xml { head :ok }
end
end
end
|
FactoryBot.define do
factory :fe_navigation, class: DataModules::FeNavigation::FeNavigation do
area { 'dresden' }
factory :fe_navigation_with_items, class: DataModules::FeNavigation::FeNavigation do
transient do
entry_count { 2 }
end
after(:create) do |navigation, evaluator|
create_list(:fe_navigation_item, evaluator.entry_count, navigation: navigation)
end
end
factory :fe_navigation_with_items_and_sub_items do
transient do
items_count { 2 }
sub_items_count { 2 }
end
after(:create) do |navigation, evaluator|
create_list(
:fe_navigation_item_with_sub_items,
evaluator.items_count,
navigation: navigation,
sub_items_count: evaluator.sub_items_count
)
end
end
end
end
|
class Card
attr_accessor :rank, :suit
def initialize(rank, suit)
self.rank = rank
self.suit = suit
end
def output_card
puts "#{self.rank} of #{self.suit}"
end
def self.random_card
Card.new(rand(10), :spades)
end
end
card = Card.new
|
require_relative '../feature_spec_helper'
describe "admin", type: :feature do
it "is redirected to the admin dashboard upon loggin in" do
user = FactoryGirl.create :user, :admin
visit '/login'
fill_in "email address", with: user.email
fill_in "password", with: user.password
click_button "Login"
expect(current_path).to eq admin_dashboard_path
end
it 'has the correct links' do
user = FactoryGirl.create :user, :admin
visit '/login'
fill_in "email address", with: user.email
fill_in "password", with: user.password
click_button "Login"
expect(page).to have_link "Users", href: admin_users_path
expect(page).to have_link "Listings", href: admin_items_path
end
end
|
# Table class
class Table
# The width of the table
attr_reader:width
# The height of the table
attr_reader:height
# Initialize the table with width and height (in units).
# ====== Parameters
# - +width+:: the width of the table
# - +height+:: the height of the table
def initialize(width, height)
# raise error for invalid arguments
raise ArgumentError, 'Table width is invalid.' unless (width.is_a?(Numeric) && width > 0)
raise ArgumentError, 'Table height is invalid.' unless (height.is_a?(Numeric) && height > 0)
@width = width
@height = height
end
# Validate x and y position to make sure the robot does not fall off the table.
# ====== Parameters
# - +x+:: the x position of the robot
# - +y+:: the y position of the robot
# ====== Returns
# - true when x and y is valid
def validate(x, y)
return x >= 0 && x < @width && y >= 0 && y < @height
end
end |
describe Pantograph::Actions::GitBranchAction do
describe "with no CI set ENV values" do
it "gets the value from Git directly" do
# expect(Pantograph::Actions::GitBranchAction).to receive(:`)
# .with(Pantograph::Helper::Git.current_branch)
# .and_return('branch-name')
result = Pantograph::PantFile.new.parse("lane :test do
git_branch
end").runner.execute(:test)
expect(result).to eq('git rev-parse --abbrev-ref HEAD')
end
end
end
|
$LOAD_PATH << "#{File.dirname(__FILE__)}/idcbatch"
module Idcbatch
require "idcbatch/ad"
require "idcbatch/hrsys"
require "idcbatch/read_config"
IDCBATCHVERSION = "1.2"
def self.version
IDCBATCHVERSION
end
end
|
class Target < ActiveRecord::Base
belongs_to :discussion
belongs_to :targetable, polymorphic: true
validates :discussion, presence: true
validates :targetable, presence: true
after_destroy :remove_discussion, if: -> { discussion.targets.count == 0 }
private
def remove_discussion
discussion.destroy!
end
end
|
class AddGridsMattersRelationship < ActiveRecord::Migration
def up
create_table :grids_matters do |t|
t.references :grid, :matter
end
end
def down
drop_table :grids_matters
end
end
|
Wcf3::Application.routes.draw do
resources :test_planes do as_routes end
resources :teams do as_routes end
resources :major_element do as_routes end # as_routes = ActiveScaffold routes
resources :minor_element do as_routes end
resources :reference_author do as_routes end
# get "users/show"
# get "users/new"
# get "session/new"
# Test routes - 30 Apr 2012
match 'specimen/edit_of_test/:id', :to => 'specimen#edit_of_test#id'
match 'specimen/on_field_change/:id', :to => 'specimen#on_field_change#id'
match 'specimen/edit_of_test/on_field_change/:id', :to => 'specimen#on_field_change#id'
root :to => 'pages#home'
get "pages/home"
get "pages/contact"
get "pages/about"
# resources :spectrum
resources :sessions, :only => [:new, :create, :destroy]
resources :users, :controller => 'User'
match '/signup', :to => 'users#new'
match '/signin', :to => 'sessions#new'
match '/signout', :to => 'sessions#destroy'
# Transferred from existing WCF
match 'account/login', :to => 'account#login'
match 'account/index', :to => 'account#index'
match 'account/signup', :to => 'account#signup'
match 'account/save_show_splash', :to => 'account#save_show_splash'
match 'additional_file/list', :to => 'additional_file#list'
match 'additional_file/new', :to => 'additional_file#new'
match 'additional_file/create', :to => 'additional_file#create'
match 'additional_file/show', :to => 'additional_file#show'
match 'additional_file/edit/:id', :to => 'additional_file#edit#:id'
match 'additional_file/destroy/:id', :to => 'additional_file#destroy#:id'
match 'additional_file/update/:id', :to => 'additional_file#update#:id'
match 'analysis_method/show',
:to => 'analysis_method#show'
match 'analysis_method/edit',
:to => 'analysis_method#edit'
match 'analysis_method/update',
:to => 'analysis_method#update'
match 'analysis_method/on_field_change/:id',
:to => 'analysis_method#on_field_change#:id'
match 'analysis_method/new',
:to => 'analysis_method#new'
# resources :authors
match 'author/list', :to => 'author#list'
match 'author/show', :to => 'author#show'
match 'author/new', :to => 'author#new'
match 'author/edit/on_field_change/:id', :to => 'author#on_field_change#id'
match 'author/on_field_change', :to => 'author#on_field_change'
match 'author/edit/:id', :to => 'author#edit#id'
match 'author/del_author', :to => 'author#del_author'
match 'author/update/id', :to => 'author#update#id'
match 'author/create', :to => 'author#create'
match 'exp_variable/list', :to => 'exp_variable#list'
match 'instrument/list', :to => 'instrument#list'
match 'instrument/show', :to => 'instrument#show'
match 'instrument/new', :to => 'instrument#new'
match 'instrument/edit/on_field_change/:id', :to => 'instrument#on_field_change#id'
match 'instrument/edit/:id', :to => 'instrument#edit#id'
match 'instrument/destroy', :to => 'instrument#destroy'
match 'instrument/create', :to => 'instrument#create'
match 'instrument/list_existing', :to => 'instrument#list_existing'
match 'keyword/list', :to => 'keyword#list'
match 'keyword/show', :to => 'keyword#show'
match 'keyword/new', :to => 'keyword#new'
# match 'keyword/destroy/:id', :to => 'keyword#destroy/id'
match 'keyword/destroy', :to => 'keyword#destroy' # why does this work w/o id param, above???JL
match 'keyword/edit/:id', :to => 'keyword#edit#id'
match 'keyword/update/:id', :to => 'keyword#update#id'
match 'keyword/create', :to => 'keyword#create'
match 'page_test/show_tabs', :to => 'page_test#show_tabs'
match 'page_test/show_tab2', :to => 'page_test#show_tab2'
match 'paramset/list/id', :to => 'paramset#list#id'
match 'paramset/show/:id', :to => 'paramset#show#id'
match 'paramset/edit/:id', :to => 'paramset#edit#id'
match 'paramset/edit/on_field_change/:id',
:to => 'paramset#on_field_change#id'
match 'paramset/on_field_change',
:to => 'paramset#on_field_change'
match 'paramset/destroy/:id', :to => 'paramset#destroy#id'
match 'paramset/update/:id', :to => 'paramset#update#id'
match 'paramset/new', :to => 'paramset#new'
match 'major_element/id', :to => 'major_element#id'
# match 'reference_author/id', :to => 'reference_author#id'
# resources :specimen
match 'specimen/list', :to => 'specimen#list'
match 'specimen/show', :to => 'specimen#show'
match 'specimen/new', :to => 'specimen#new'
match 'specimen/edit/on_field_change/:id', :to => 'specimen#on_field_change#id'
match 'specimen/on_field_change', :to => 'specimen#on_field_change'
match 'specimen/edit/:id', :to => 'specimen#edit#id'
match 'specimen/destroy/id', :to => 'specimen#destroy#id'
match 'specimen/update/id', :to => 'specimen#update#id'
match 'specimen/create', :to => 'specimen#create'
match 'spectral_feature/edit_table_ax', :to => 'spectral_feature#edit_table_ax'
match 'spectral_feature/list_spect_feat', :to => 'spectral_feature#list_spect_feat'
match 'spectral_feature/list_calib_info', :to => 'spectral_feature#list_calib_info'
match 'spectral_feature/new_calib_info', :to => 'spectral_feature#new_calib_info'
match 'spectral_feature/show_calib_info/:id', :to => 'spectral_feature#show_calib_info#id'
match 'spectral_feature/edit_calib_info/:id', :to => 'spectral_feature#edit_calib_info#id'
# match 'spectral_feature/edit_calib_info/on_field_change/:id', :to => 'spectral_feature#edit_calib_info#on_field_change#id'
match 'spectral_feature/update_calib_info/:id', :to => 'spectral_feature#update_calib_info#id'
match 'spectral_feature/destroy_calib_info/:id', :to => 'spectral_feature#destroy_calib_info#id'
match 'spectral_feature/new_spect_feat', :to => 'spectral_feature#new_spect_feat'
match 'spectral_feature/show_spect_feat', :to => 'spectral_feature#show_spect_feat'
match 'spectral_feature/edit_spect_feat/:id',
:to => 'spectral_feature#edit_spect_feat#id'
match 'spectral_feature/edit_spect_feat/on_field_change/:id',
:to => 'spectral_feature#on_field_change#id'
match 'spectral_feature/edit_calib_info/on_field_change/:id',
:to => 'spectral_feature#on_field_change#id'
match 'spectral_feature/on_field_change',
:to => 'spectral_feature#on_field_change'
match 'spectral_feature/destroy_spect_feat/:id', :to => 'spectral_feature#destroy_spect_feat#id'
match 'spectral_feature/update_spect_feat/:id', :to => 'spectral_feature#update_spect_feat#id'
match 'spectral_feature/create_spect_feat', :to => 'spectral_feature#create_spect_feat'
match 'spectral_feature/create_calib_info', :to => 'spectral_feature#create_calib_info'
match 'spectral_feat_tbl_unit/edit/:id', :to => 'spectral_feat_tbl_unit#edit#id'
match 'spectral_feat_tbl_unit/destroy/:id', :to => 'spectral_feat_tbl_unit#destroy#id'
match 'spectral_feat_tbl_unit/update/:id', :to => 'spectral_feat_tbl_unit#update#id'
match 'spectral_feat_tbl_unit/new', :to => 'spectral_feat_tbl_unit#new'
match 'spectral_feat_tbl_unit/create', :to => 'spectral_feat_tbl_unit#create'
match 'spectral_feat_tbl_unit/on_field_change', :to => 'spectral_feat_tbl_unit#on_field_change'
match 'spectral_feat_tbl_unit/edit/on_field_change/:id', :to => 'spectral_feat_tbl_unit#on_field_change#:id'
match 'submission/show_my', :to => 'submission#show_my'
match 'submission/list_submiss_dump', :to => 'submission#list_submiss_dump'
match 'submission/show/id', :to => 'submission#show#id'
match 'submission/destroy/id', :to => 'submission#destroy#id'
match 'submission/edit/id', :to => 'submission#edit#id'
match 'submission/edit/on_field_change/:id', :to => 'submission#on_field_change#id'
match 'submission/list_users/id', :to => 'submission#list_users#id'
match 'submission/do_submiss_summ', :to => 'submission#do_submiss_summ'
match 'submission/request_submit_to_sss', :to => 'submission#request_submit_to_sss'
match 'submission/save_after_edit', :to => 'submission#save_after_edit'
match 'submission/list_all_users/:id', :to => 'submission#list_all_users#:id'
match 'submission/select_user/:id', :to => 'submission#select_user#:id'
match 'submission/dump_submiss', :to => 'submission#dump_submiss'
match 'submission/admin_edit', :to => 'submission#admin_edit'
match 'submission/update_admin_edit/:id', :to => 'submission#update_admin_edit#:id'
match 'submission/flag_for_deletion', :to => 'submission#flag_for_deletion'
match 'subm_cloning/clone_subm_driver', :to => 'subm_cloning#clone_subm_driver'
match 'submission_reference/list', :to => 'submission_reference#list'
match 'submission_reference/new', :to => 'submission_reference#new'
match 'submission_reference/create', :to => 'submission_reference#create'
match 'submission_reference/edit/:id', :to => 'submission_reference#edit#id'
match 'submission_reference/edit/on_field_change/:id', :to => 'submission_reference#on_field_change#id'
match 'submission_reference/destroy/:id', :to => 'submission_reference#destroy#id'
match 'submission_reference/update/:id', :to => 'submission_reference#update#id'
match 'submission_reference/show/:id', :to => 'submission_reference#show#id'
match 'submission_reference/save/:id', :to => 'submission_reference#save#id'
match 'submission_reference/on_field_change', :to => 'submission_reference#on_field_change'
match 'user/edit', :to => 'user#edit' # can be made Restful ???JL
match 'user/show/:id', :to => 'user#show#id'
match 'user/remove_user_from_submission/:id', :to => 'user#remove_user_from_submission#:id'
match 'user/update/:id', :to => 'user#update#id'
match 'spectrum/list',
:to => 'spectrum#list'
match 'spectrum/show/:id',
:to => 'spectrum#show#:id'
match 'spectrum/update/:id',
:to => 'spectrum#update#:id'
match 'spectrum/edit/:id',
:to => 'spectrum#edit#:id'
match 'spectrum/destroy/:id',
:to => 'spectrum#destroy#:id'
match 'spectrum/new',
:to => 'spectrum#new'
match 'spectrum/show_upload_tab',
:to => 'spectrum#show_upload_tab'
match 'spectrum/show_paramset_tab',
:to => 'spectrum#show_paramset_tab'
match 'spectrum/edit/on_field_change/:id',
:to => 'spectrum#on_field_change#:id'
match 'spectrum/save_data_file',
:to => 'spectrum#save_data_file'
match 'spectrum/select_paramset',
:to => 'spectrum#select_paramset'
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id(.:format)))'
end
|
#! /usr/local/bin/ruby
require 'open3'
require 'docker'
sizelists = Hash.new()
childlists = Hash.new() { |h,k| h[k]=[] }
parents = {}
dot_file = []
dot_file << 'digraph docker {'
Docker::Image.all(all: true).each do |image|
id = image.id[0..11]
tags = image.info['RepoTags'].reject { |t| t == '<none>:<none>' }.join('\n')
parent_id = image.info['ParentId'][0..11]
size = image.info["VirtualSize"]
sizelists[id.to_sym] = size
parents[id] = parent_id
if parent_id.empty?
dot_file << "base -> \"#{id}\" [style=invis]"
else
dot_file << "\"#{parent_id}\" -> \"#{id}\""
end
childlists[parent_id].push id
if !tags.empty?
dot_file << "\"#{id}\" [label=\"#{id}\\n#{tags}\\n%{#{id}}MiB\n(Virtual: #{size / 1024.0}MiB)\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];"
else
dot_file << "\"#{id}\" [label=\"#{id}\\n%{#{id}}MiB\"];"
end
end
dot_file << 'base [style=invisible]'
dot_file << '}'
parents.keys.each { |k| childlists[k] } #iterate to make sure we have empty children
until childlists.empty?
childlists.delete_if do |k, v|
if v.empty?
sizelists[k.to_sym] = ( sizelists[k.to_sym] - sizelists[parents[k].to_sym] ) / 1024.0 rescue 0
childlists.each do |rk,rv|
rv.delete(k)
end
end
v.empty?
end
end
dot_file = dot_file.join("\n") % sizelists
Open3.popen3('/usr/bin/dot -Tsvg') do |stdin, stdout, stderr|
stdin.puts(dot_file)
stdin.close
STDOUT.write stdout.read
STDERR.write stderr.read
end
|
# frozen_string_literal: true
require 'spec_helper'
module Uploadcare
module Client
RSpec.describe FileClient do
subject { FileClient.new }
describe 'info' do
it 'shows insider info about that file' do
VCR.use_cassette('rest_file_info') do
uuid = '2e17f5d1-d423-4de6-8ee5-6773cc4a7fa6'
file = subject.info(uuid)
expect(file.value![:uuid]).to eq(uuid)
end
end
it 'shows nothing on invalid file' do
VCR.use_cassette('rest_file_info_fail') do
uuid = 'nonexistent'
expect { subject.info(uuid) }.to raise_error(RequestError)
end
end
end
describe 'delete' do
it 'deletes a file' do
VCR.use_cassette('rest_file_delete') do
uuid = '158e7c82-8246-4017-9f17-0798e18c91b0'
response = subject.delete(uuid)
response_value = response.value!
expect(response_value[:datetime_removed]).not_to be_empty
expect(response_value[:uuid]).to eq(uuid)
end
end
end
describe 'store' do
it 'changes file`s status to stored' do
VCR.use_cassette('rest_file_store') do
uuid = 'e9a9f291-cc52-4388-bf65-9feec1c75ff9'
response = subject.store(uuid)
expect(response.value![:datetime_stored]).not_to be_empty
end
end
end
end
end
end
|
# frozen_string_literal: true
class DrinkLike < ApplicationRecord
belongs_to :user
belongs_to :drink
validates_uniqueness_of :drink_id, scope: :user_id
end
|
module BillHelper
def bill_period(place=:from)
date_string(bill[:statement][:period][place])
end
def currency(number)
number_to_currency(number, unit: '£')
end
def date_string(string)
Date.parse(string).strftime('%d %b')
end
def rental_charge_total
bill[:sky_store][:rentals].sum { |rental| rental[:cost] }
end
end
|
require 'spec_helper'
module Ttycaca
describe Terminal do
let (:terminal) { Terminal.new }
describe "#width" do
it "should return a positive integer" do
expect(terminal.width).to be > 0
end
end
describe "#height" do
it "should return a positive integer" do
expect(terminal.height).to be > 0
end
end
end
end
|
require 'test_helper'
class CommentsControllerTest < ActionController::TestCase
setup do
@comment = comments(:one)
end
def sign_in
request.headers['Authorization'] = ActionController::HttpAuthentication::Basic.
encode_credentials('dhh', 'secret')
end
test "should create comment" do
assert_difference('Comment.count') do
post :create, article_id: @comment.article.id, comment: { body: 'Great article' }
end
assert_redirected_to article_path(@comment.article)
end
test "should not destroy comment if not signed in" do
assert_no_difference('Comment.count', -1) do
delete :destroy, article_id: @comment.article.id, id: @comment
end
assert_response :unauthorized
end
test "should destroy comment if signed in" do
sign_in
assert_difference('Comment.count', -1) do
delete :destroy, article_id: @comment.article.id, id: @comment
end
assert_redirected_to article_path(@comment.article)
end
end
|
#!/usr/bin/env ruby
# ARTML Copyright (c)2004 Thomas Sawyer
require 'getoptlong'
require 'artml'
if $0 == __FILE__
opts = GetoptLong.new(
[ "-h", "--help", GetoptLong::NO_ARGUMENT ],
[ "-v", "--verbose", GetoptLong::NO_ARGUMENT ],
[ "-d", "--debug", GetoptLong::NO_ARGUMENT ],
[ "-p", "--preprint", GetoptLong::NO_ARGUMENT ],
[ "-b", "--blueprint", GetoptLong::NO_ARGUMENT ],
[ "-a", "--adapter", GetoptLong::REQUIRED_ARGUMENT ]
)
opt_help = false
opt_verbose = false
opt_output = 'xhtml'
opts.each do |opt, arg|
case opt
when '-h'
opt_help = true
when '-v'
opt_verbose = true
when '-d'
$DEBUG = true
when '-b'
opt_output = 'blueprint'
when '-p'
opt_output = 'preprint'
when '-a'
opt_adapter = arg.downcase
end
end
raise 'no art files' if ARGV.length == 0
art_files = ARGV
arts = art_files.collect { |f| File.new(f) }
$stdout << ARTML.load(opt_output, *arts) << "\n"
end
#cells = {}
#cells['Button'] = 'test_action'
#cells['text'] = "E" * 200
#cells['check'] = %Q{1}
#cells['multitext'] = %Q{Multiple Lines\nEnter Here}
#cells['general'] = %Q{I've been replaced!}
#cells['listbox'] = %Q{Option A3}
#cells['listbox_'] = [ 'Option A1', 'Option A2', 'Option A3' ]
#cells['select'] = %Q{OB2}
#cells['select_'] = [ ['OB1', 'Option B1'], ['OB2', 'Option B2'], ['OB3', 'Option B3'] ]
#cells['ra'] = ['A1', 'A2', 'A3']
#cells['rb'] = ['B1', 'B2', 'B3']
#cells['rc'] = ['C1', 'C2', 'C3']
|
class AddLearnFieldToDocumentations < ActiveRecord::Migration[5.1]
def change
add_reference :documentations, :learn_field, foreign_key: true
end
end
|
require 'spec_helper'
describe 'unattended_upgrades' do
let(:file_unattended) { '/etc/apt/apt.conf.d/50unattended-upgrades' }
let(:file_periodic) { '/etc/apt/apt.conf.d/10periodic' }
let(:file_options) { '/etc/apt/apt.conf.d/10options' }
context 'with defaults on Raspbian' do
let(:facts) do
{
os: {
name: 'Raspbian',
family: 'Debian',
release: {
full: '8.0'
}
},
osfamily: 'Debian',
lsbdistid: 'Raspbian',
lsbdistcodename: 'jessie',
lsbrelease: '8.0'
}
end
it do
is_expected.to create_file(file_unattended).with(
owner: 'root',
group: 'root',
mode: '0644'
)
end
end
context 'with defaults on Linux Mint 13 Maya' do
let(:facts) do
{
os: {
name: 'LinuxMint',
family: 'Debian',
release: {
full: '13'
}
},
osfamily: 'Debian',
lsbdistid: 'LinuxMint',
lsbdistcodename: 'maya',
lsbdistrelease: '13',
lsbmajdistrelease: '13'
}
end
it do
is_expected.to create_file(file_unattended).with(
'owner' => 'root',
'group' => 'root',
'mode' => '0644'
).with_content(
# This is the only section that's different for Ubuntu compared to Debian
%r{\Unattended-Upgrade::Allowed-Origins\ {\n
\t"Ubuntu\:precise-security";\n
};}x
)
end
end
context 'with defaults on Linux Mint 17.3 Rosa' do
let(:facts) do
{
os: {
name: 'LinuxMint',
family: 'Debian',
release: {
full: '17.3'
}
},
osfamily: 'Debian',
lsbdistid: 'LinuxMint',
lsbdistcodename: 'rosa',
lsbdistrelease: '17.3',
lsbmajdistrelease: '17'
}
end
it do
is_expected.to create_file(file_unattended).with(
'owner' => 'root',
'group' => 'root',
'mode' => '0644'
).with_content(
# This is the only section that's different for Ubuntu compared to Debian
%r{\Unattended-Upgrade::Allowed-Origins\ {\n
\t"Ubuntu\:trusty-security";\n
};}x
)
end
end
context 'with defaults on Linux Mint 18 Sarah' do
let(:facts) do
{
os: {
name: 'LinuxMint',
family: 'Debian',
release: {
full: '18'
}
},
osfamily: 'Debian',
lsbdistid: 'LinuxMint',
lsbdistcodename: 'sarah',
lsbdistrelease: '18',
lsbmajdistrelease: '18'
}
end
it do
is_expected.to create_file(file_unattended).with(
'owner' => 'root',
'group' => 'root',
'mode' => '0644'
).with_content(
# This is the only section that's different for Ubuntu compared to Debian
%r{\Unattended-Upgrade::Allowed-Origins\ {\n
\t"Ubuntu\:xenial-security";\n
};}x
)
end
end
end
|
class DeploymentsController < ApplicationController
def create
project = current_user.projects.find(params[:project_id])
@deployment = project.deployments.build
if @deployment.save
DeploymentJob.perform_later(@deployment.id)
render action: :show
else
flash[:error] = 'Ooops! Something went wrong!'
redirect_to projects_path
end
end
def show
@deployment = Deployment.find(params[:id])
end
end
|
require "httplog/extensions/replacers/base_replacer"
module Extensions
module Replacers
class HalfReplacer < BaseReplacer
def replace(value)
value = value.to_s
fch = filtered_characters(value)
filtered_value * fch + value.to_s.slice(fch...value.length)
end
private
def visible_characters(value)
value.length / 2
end
def filtered_characters(value)
value.length - visible_characters(value)
end
def default_filtered_value
"*"
end
end
end
end
|
# encoding: utf-8
module Antelope
module Generation
class Constructor
# Contains the methods to determine if an object is nullable.
module Nullable
# Initialize.
def initialize
@nullifying = Set.new
end
# Determine if a given token is nullable. This is how the
# method should behave:
#
# nullable?(ϵ) == true # if ϵ is the epsilon token
# nullable?(x) == false # if x is a terminal
# nullable?(αβ) == nullable?(α) && nullable?(β)
# nullable?(A) == nullable?(a_1) || nullable?(a_2) || ... nullable?(a_n)
# # if A is a nonterminal and a_1, a_2, ..., a_n are all
# # of the right-hand sides of its productions
#
# @param token [Grammar::Token, Array<Grammar::Token>] the token to
# check.
# @return [Boolean] if the token can reduce to ϵ.
def nullable?(token)
case token
when Grammar::Token::Nonterminal
nullifying(token) do
productions = grammar.productions[token.name]
!!productions.any? { |prod| nullable?(prod[:items]) }
end
when Array
token.dup.delete_if { |tok|
@nullifying.include?(tok) }.all? { |tok| nullable?(tok) }
when Grammar::Token::Epsilon
true
when Grammar::Token::Terminal
false
else
incorrect_argument! token, Grammar::Token, Array
end
end
private
# Helps keep track of the nonterminals we're checking for
# nullability. This helps prevent recursion.
#
# @param tok [Grammar::Token::Nonterminal]
# @yield once.
# @return [Boolean]
def nullifying(tok)
@nullifying << tok
out = yield
@nullifying.delete tok
out
end
end
end
end
end
|
class ArticlesController < ApplicationController
def create
@article = current_user.articles.new(article_params)
if @article.save
render json: { success: "successfully created" }, status: :ok
else
render json: { error: @article.errors.messages.map { |msg, desc| msg.to_s + " " + desc[0] }.join(',') }, status: :not_found
end
end
def show
@article = current_user.articles.find(params[:id])
render json: { article: @article }, status: :ok
end
private
def article_params
params.require(:articles).permit(:title, :description)
end
end
|
class SignupLink < ActiveRecord::Base
attr_accessible :key, :user_id
belongs_to :user
validates :key, :user_id, presence: true
before_validation :create_key, :unless => Proc.new { |model| model.persisted? }
def link
if Rails.env.development?
host = "http://127.0.0.1"
else
host = "http://plansource.io"
end
"#{host}/users/signup_link/#{self.key}"
end
private
def create_key
self.key = loop do
random_token = SecureRandom.urlsafe_base64(64, false)
break random_token unless SignupLink.exists?(key: random_token)
end
end
end
|
require 'test_helper'
class PaistsControllerTest < ActionDispatch::IntegrationTest
setup do
@paist = paists(:one)
end
test "should get index" do
get paists_url
assert_response :success
end
test "should get new" do
get new_paist_url
assert_response :success
end
test "should create paist" do
assert_difference('Paist.count') do
post paists_url, params: { paist: { continentet_id: @paist.continentet_id, nombre: @paist.nombre } }
end
assert_redirected_to paist_url(Paist.last)
end
test "should show paist" do
get paist_url(@paist)
assert_response :success
end
test "should get edit" do
get edit_paist_url(@paist)
assert_response :success
end
test "should update paist" do
patch paist_url(@paist), params: { paist: { continentet_id: @paist.continentet_id, nombre: @paist.nombre } }
assert_redirected_to paist_url(@paist)
end
test "should destroy paist" do
assert_difference('Paist.count', -1) do
delete paist_url(@paist)
end
assert_redirected_to paists_url
end
end
|
json.array!(@det_compras) do |det_compra|
json.extract! det_compra, :id, :producto_id, :compra_id, :precio, :catidad, :num_bol_fac
json.url det_compra_url(det_compra, format: :json)
end
|
class NoticeCommentsController < ApplicationController
before_action :find_notice
def index
@comments = @notice.comments
end
def show
@comment = @notice.comments.find( params[:id] )
end
def new
@comment = @notice.comments.build
end
def create
@comment = @notice.comments.build( comment_params )
@comment.user_id = current_user.id
if @comment.save
redirect_to notice_comments_url( @notice )
else
render :action => :new
end
end
def edit
@comment = @notice.comments.find( params[:id] )
end
def update
@comment = @notice.comments.find( params[:id] )
if @comment.update( comment_params )
redirect_to notice_comments_url( @notice )
else
render :action => :edit
end
end
def destroy
@comment = @notice.comments.find( params[:id] )
@comment.destroy
redirect_to notice_comments_url( @notice )
end
protected
def find_notice
@notice = Notice.find( params[:notice_id] )
end
def comment_params
params.require(:comment).permit(:content)
end
end
|
require 'test_helper'
class PousadasControllerTest < ActionController::TestCase
setup do
@pousada = pousadas(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:pousadas)
end
test "should get new" do
get :new
assert_response :success
end
test "should create pousada" do
assert_difference('Pousada.count') do
post :create, pousada: { avalicao: @pousada.avalicao, cidade_id: @pousada.cidade_id, estado_id: @pousada.estado_id, nome: @pousada.nome, numero: @pousada.numero, pais_id: @pousada.pais_id, rua: @pousada.rua }
end
assert_redirected_to pousada_path(assigns(:pousada))
end
test "should show pousada" do
get :show, id: @pousada
assert_response :success
end
test "should get edit" do
get :edit, id: @pousada
assert_response :success
end
test "should update pousada" do
patch :update, id: @pousada, pousada: { avalicao: @pousada.avalicao, cidade_id: @pousada.cidade_id, estado_id: @pousada.estado_id, nome: @pousada.nome, numero: @pousada.numero, pais_id: @pousada.pais_id, rua: @pousada.rua }
assert_redirected_to pousada_path(assigns(:pousada))
end
test "should destroy pousada" do
assert_difference('Pousada.count', -1) do
delete :destroy, id: @pousada
end
assert_redirected_to pousadas_path
end
end
|
class SearchController < ApplicationController
before_action :set_param
before_action :authenticate_user!
def index
if @query.blank?
groups = Group.all.reject { |g| g.home? }
@index = true
else
groups = Group.search(
@query,
page: @page,
order: { created_at: :desc },
per_page: 20,
fields: [
{ name: :word_middle },
:description
],
operator: 'or')
end
@groups_joined = []
@groups_not_joined = []
@groups_not_joined_count = 0
groups.each do |g|
if view_context.joined_group?(g)
@groups_joined << g
else
@groups_not_joined << g
@groups_not_joined_count += 1
end
end
@groups_count = groups.count
end
private
def set_param
@query = params[:query]
@page = params[:page]
end
end
|
require 'spec_helper'
describe GapIntelligence::Header do
include_examples 'Record'
describe 'attributes' do
subject(:header) { described_class.new build(:header) }
it 'has name' do
expect(header).to respond_to(:name)
end
it 'has unit' do
expect(header).to respond_to(:unit)
end
it 'has core_header' do
expect(header).to respond_to(:core_header)
end
it 'has position' do
expect(header).to respond_to(:position)
end
end
end
|
# frozen_string_literal: true
module UploadHelper
def category_options
[[]].concat(Category.all.map { |category| [category.name, category.id] })
end
end
|
describe Ace::Compiler do
let :file do
<<-DOC
%{
test
%}
%require "#{VERSION}"
%language "ruby"
%terminal NUMBER
%terminal SEMICOLON ";"
%terminal ADD "+"
%terminal LPAREN "("
%terminal RPAREN ")"
%%
s: e
e: t ADD e
t: NUMBER | LPAREN e RPAREN
%%
hello
DOC
end
let :tokens do
Ace::Scanner.scan(file)
end
let :compiler do
Ace::Compiler.new(tokens)
end
subject do
compiler.compile
compiler
end
its(:body) { should =~ /test/ }
its(:body) { should =~ /hello/ }
its(:options) { should have_key :type }
it 'has the proper terminals' do
expect(subject.options[:terminals].map(&:first)).to eq [:NUMBER,
:SEMICOLON, :ADD, :LPAREN, :RPAREN]
end
context 'with an unmatched version' do
let(:file) { "%require \"0.0.0\"\n%%\n%%\n" }
it 'raises an error' do
expect do
subject
end.to raise_error(IncompatibleVersionError)
end
end
end
|
class Schedule < Markdown
MARKDOWN = <<MARKDOWN
### Coming Soon!
For now please just go to the prayer page and pray!
MARKDOWN
render do
DIV(style: { marginTop: 75, marginBottom: 100 }) do
papers
end
end
end
|
class CommentSerializer
include FastJsonapi::ObjectSerializer
attributes :content, :name, :entry_id, :created_at, :updated_at, :user_id
end
|
class EventsController < ApplicationController
def index
@events = Event.atlas(params[:atlas_id]).includes(:tags)
@atlas = Atlas.find_by_id(params[:atlas_id])
end
def show
@event = Event.find_by_id(params[:id])
@reports = Report.where(:event_id => @event.id).includes(:tag)
@tags = @event.tags.includes(:type).uniq # Ensures lack of duplicates
end
end
|
require 'rails_helper'
RSpec.describe ResumeTable, type: :model do
it {should belong_to(:profile_resume)}
it {should have_many(:resume_table_cell)}
it {should have_many(:resume_table_medium)}
it {should validate_presence_of(:row)}
it {should validate_presence_of(:column)}
it {should validate_presence_of(:profile_resume)}
end
|
#encoding: UTF-8
class TopFive
include Mongoid::Document
include Mongoid::Timestamps
store_in collection: "top_five", database: "dishgo"
field :name, localize: true
field :description, localize: true
field :beautiful_url, type: String
field :end_date, type: DateTime
field :active, type: Boolean, default: false
has_and_belongs_to_many :dish, class_name: "Dish", inverse_of: nil
has_and_belongs_to_many :users, class_name: "User", inverse_of: nil
has_many :dishcoins, class_name: "Dishcoin", inverse_of: :top_five
has_many :prizes, class_name: "Prize", inverse_of: :top_five
has_many :individual_prizes, class_name: "IndividualPrize", inverse_of: :top_five
belongs_to :user
before_save :beautify_url
scope :is_active, -> { where(active: true) }
def number_of_dishes
return 4
end
def ordered_dishes
# Order it according to result, or according to our set list. Fuck Blackstrap.
if end_date and end_date <= DateTime.now
return self.dish.top_five
else
return self.dish.sort_by{|e| dish_ids.index(e.id) }
end
end
def reward_prizes
prizes.each do |prize|
skip_these_users = []
dishcoins.each do |dishcoin|
next if !dishcoin.rating
if dishcoin.rating.restaurant == prize.restaurant
skip_these_users << dishcoin.user.id.to_s
end
end
prize.individual_prizes.remaining.each do |ind_pri|
dcs = dishcoins.not_in(user_id:skip_these_users).ne(user_id:nil)
if dcs.length > 0
dc = dcs[SecureRandom.random_number(dcs.length)-1]
ind_pri.user = dc.user
users << dc.user
ind_pri.save
skip_these_users << dc.user.id.to_s
end
end
end
save
end
def only_best_rating
user_hash = {}
dishcoins.ne(rating_id:nil).each do |d|
user_hash[d.user_id] ||= []
next unless d.rating
user_hash[d.user_id] << d.rating
end
user_hash.each do |k,v|
puts "[#{k.to_s}]"
v.sort_by{|r| -r.rating }.each do |r|
puts "\t#{r.rating}"
if r.rating <= 3
r.invalid_rating = true
r.save
end
end
end
dish.each do |d|
d.recalculate_rating
end
dish.each do |d|
puts "#{d.name} => #{d.contest_rating} / #{d.rating} / total rating: #{d.ratings.count}"
end
nil
end
def serializable_hash options = {}
hash = super()
hash[:id] = self.id
hash[:finished] = self.end_date < DateTime.now if self.end_date
if options[:export_localized]
hash[:name] = self.name_translations
hash[:description] = self.description_translations
hash[:dishes] = self.ordered_dishes.collect{|e| e.serializable_hash({export_localized:true, include_reviews:options[:include_reviews], include_quality_reviews: hash[:finished]})}
hash[:prizes] = self.prizes.top_five.collect{|e| e.serializable_hash({export_localized:true})}
# # If there are no prizes, then this isnt a contest, so it never has to be "finished"
# if hash[:prizes].empty?
# hash[:finished] = false
# end
if hash[:finished]
hash[:winners] = self.users.collect{|e| e.nickname}
end
end
return hash
end
def best_pic
pic = self.dish.top_five.find_all{|e| !e.img_src_orig.blank?}.first.img_src_orig
if pic
return pic
else
return "https://d5ca3b0520fac45026ad-6caa6fe89e7dac3eaf12230f0985b957.ssl.cf5.rackcdn.com/facebook_share.png"
end
end
def beautify_url
return if self.beautiful_url.to_s.length > 0
string = []
begin
beauty = self.name.split(" ").join("_").downcase + string.join("")
string << (65 + rand(26)).chr
end while TopFive.where(beautiful_url:beauty).count > 0
self.beautiful_url = beauty
end
end
|
require 'data_mapper'
require 'dm-timestamps'
class Peep
include DataMapper::Resource
property :id, Serial
property :message, String
property :posted_by_name, String
property :posted_by_username, String
property :created_at, DateTime
end |
#!/usr/bin/env ruby
# encoding: utf-8
require 'lg_world'
require 'lg_viewer'
require 'test/unit'
module LifeGame
class LifeGameTest < Test::Unit::TestCase
def test_read_object
world = []
File.open('objects/blinker.txt') do |f|
f.each_line do |line|
line.chop!
tmp = line.split(", ")
tmp.map! {|v| v.to_i}
world << tmp
end
end
print world
assert_equal [[0, 1, 0], [0, 1, 0], [0, 1, 0]], world
end
def test_surround
lg = LifeGame::World.new([[0, 1, 0], [0, 1, 0], [0, 1, 0]])
a = lg.surround(1, 1)
assert_equal 2, a
b = lg.surround(0, 0)
assert_equal 2, b
c = lg.surround(0, 1)
assert_equal 3, c
end
def test_willbeBorn
lg = LifeGame::World.new([[0, 1, 0], [0, 1, 0], [0, 1, 0]])
a = lg.willbeBorn(0, 1)
assert_equal 1, a
end
def test_compound_next
lg = LifeGame::World.new([[0, 1, 0], [0, 1, 0], [0, 1, 0]])
@nextworld = lg.world.map{|x| x.clone}
assert_equal [[0, 1, 0], [0, 1, 0], [0, 1, 0]], @nextworld
lg.height.times do |y|
lg.width.times do |x|
case lg.world[y][x]
when 0
@nextworld[y][x] = lg.willbeBorn(x, y)
when 1
@nextworld[y][x] = lg.deadOr(x, y)
end
end
end
assert_equal [[0, 0, 0], [1, 1, 1], [0, 0, 0]], @nextworld
puts ""
end
def test_next
lg = LifeGame::World.new([[0, 1, 0], [0, 1, 0], [0, 1, 0]])
@nextworld = lg.next
assert_equal [[0, 0, 0], [1, 1, 1], [0, 0, 0]], @nextworld
end
end
end
|
class CreateApvndmstrs < ActiveRecord::Migration[5.1]
def change
create_table :apvndmstrs do |t|
t.string :vend_code
t.string :vend_name
t.string :vend_status
t.timestamps
end
end
end
|
require 'rails_helper'
RSpec.describe FindForOauthService do
let!(:user) { create(:user) }
let(:auth) { OmniAuth::AuthHash.new(provider: 'facebook', uid: '123456') }
describe 'user already exist' do
subject { FindForOauthService.new(auth, user.email) }
context 'user exist by email' do
it 'returns user by email' do
expect(subject.call).to eq user
end
it 'does not create new user' do
expect { subject.call }.to_not change(User, :count)
end
it 'create new authorization' do
expect { subject.call }.to change(user.authorizations, :count)
end
end
context 'user has authorization' do
let!(:authorization) do
create(:authorization, user: user, provider: 'facebook', uid: '123456')
end
it 'does not create new user' do
expect { subject.call }.to_not change(User, :count)
end
it 'does not create new authorization' do
expect { subject.call }.to_not change(Authorization, :count)
end
it 'returns the user' do
expect(subject.call).to eq user
end
end
context 'user has not authorization' do
context 'user already exists' do
it 'does not create new user' do
expect { subject.call }.to_not change(User, :count)
end
it 'create authorization for new user' do
expect { subject.call }.to change(user.authorizations, :count).by(1)
end
it 'returns the user' do
expect(subject.call).to eq user
end
end
end
end
describe 'user does not exist' do
subject { FindForOauthService.new(auth, 'user@example.ru') }
it 'creates new user' do
expect { subject.call }.to change(User, :count).by(1)
end
it 'create authorization for new user' do
expect { subject.call }.to change(Authorization, :count).by(1)
expect(subject.call.email).to eq 'user@example.ru'
end
it 'returns new user' do
expect(subject.call).to eq User.find_by(email: 'user@example.ru')
end
end
end
|
module ThemesOnRails
class Configuration
def initialize(hash)
@hash = default_config.merge(hash)
end
def asset_pipeline
hash["asset_pipeline"]
end
private
attr_reader :hash
def default_config
{
"asset_pipeline" => true
}
end
end
end
|
#
# Cookbook Name:: graphviz
# Recipe:: default
#
# Copyright 2014, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
if #{node[:languages][:ruby][:version]} <> "1.9.3"
include_recipe "ruby::default"
end
execute "prepare repo for graphviz" do
command "wget -O #{node['graphviz']['repo']} #{node['graphviz']['download_repo']}"
action :run
not_if { File.exists?("#{node['graphviz']['repo']}" ) }
end
%w{graphviz graphviz-lang-ocaml graphviz-lang-perl graphviz-lang-php graphviz-lang-python graphviz-lang-ruby graphviz-lang-tcl graphviz-libs graphviz-plugins-core graphviz-plugins-gd graphviz-plugins-x graphviz-qt graphviz-x ann-libs compat-readline5 freeglut gd gdbm-devel gtkglext-libs gts guile libXaw libXpm libmng netpbm ocaml ocaml-runtime phonon-backend-gstreamer php-cli php-common qt qt-sqlite qt-x11 tcl tk}.each do |pkg|
package pkg do
action :install
end
end
|
# frozen_string_literal: true
# typed: true
module AlphaCard
##
# Implementation of Alpha Card Services Capture transaction.
#
# @example
# capture = AlphaCard::Capture.new(transaction_id: '981562', amount: '10.05')
# capture.process
#
# #=> #<AlphaCard::Response:0x1a0fda ...>
#
class Capture < Transaction
attribute :transaction_id, required: true
# Format: xx.xx
attribute :amount, required: true
attribute :tracking_number
attribute :shipping_carrier
attribute :order_id
##
# Transaction type (default is 'capture')
#
# @attribute [r] type
attribute :type, default: 'capture', writeable: false
##
# Original AlphaCard transaction variables names
ORIGIN_TRANSACTION_VARIABLES = {
transaction_id: :transactionid,
order_id: :orderid,
}.freeze
end
end
|
class BrandsController < ApplicationController
before_action :set_brand, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, only: [:new, :create, :edit, :destroy], unless: :valid_api_key?
protect_from_forgery except: :create
def index
@brands = Brand.active.includes(products: [:product_images, :default_product_images]).order(:name)
end
def search
end
def show
@search = policy_scope(Product).where(brand_id: @brand.id).search(params[:q])
@products = @search.result.includes(:brand, :product_images, :stocks).newest.page(params[:page]).per(24)
end
def new
@brand = Brand.new
end
def edit
end
def create
@brand = Brand.new(brand_params)
respond_to do |format|
if @brand.save
format.html { redirect_to @brand, notice: 'Brand was successfully created.' }
format.json { render action: 'show', status: :created, location: @brand }
else
format.html { render action: 'new' }
format.json { render json: @brand.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @brand.update(brand_params)
format.html { redirect_to @brand, notice: 'Brand was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @brand.errors, status: :unprocessable_entity }
end
end
end
def destroy
@brand.destroy
respond_to do |format|
format.html { redirect_to brands_url }
format.json { head :no_content }
end
end
private
def set_brand
@brand = Brand.friendly.find(params[:id])
end
def brand_params
params.require(:brand).permit(
:id,
:name,
:description,
:logo,
:meta_title,
:meta_description
)
end
end
|
module Vertica
module Messages
class CancelRequest < FrontendMessage
message_id nil
def initialize(backend_pid, backend_key)
@backend_pid = backend_pid
@backend_key = backend_key
end
def to_bytes
message_string([
80877102.to_network_int32,
@backend_pid.to_network_int32,
@backend_key.to_network_int32
])
end
end
end
end
|
require 'test_helper'
class LibrarianSignupRequestsControllerTest < ActionDispatch::IntegrationTest
setup do
@librarian_signup_request = librarian_signup_requests(:one)
end
test "should get index" do
get librarian_signup_requests_url
assert_response :success
end
test "should get new" do
get new_librarian_signup_request_url
assert_response :success
end
test "should create librarian_signup_request" do
assert_difference('LibrarianSignupRequest.count') do
post librarian_signup_requests_url, params: { librarian_signup_request: { librarian_id: @librarian_signup_request.librarian_id } }
end
assert_redirected_to librarian_signup_request_url(LibrarianSignupRequest.last)
end
test "should show librarian_signup_request" do
get librarian_signup_request_url(@librarian_signup_request)
assert_response :success
end
test "should get edit" do
get edit_librarian_signup_request_url(@librarian_signup_request)
assert_response :success
end
test "should update librarian_signup_request" do
patch librarian_signup_request_url(@librarian_signup_request), params: { librarian_signup_request: { librarian_id: @librarian_signup_request.librarian_id } }
assert_redirected_to librarian_signup_request_url(@librarian_signup_request)
end
test "should destroy librarian_signup_request" do
assert_difference('LibrarianSignupRequest.count', -1) do
delete librarian_signup_request_url(@librarian_signup_request)
end
assert_redirected_to librarian_signup_requests_url
end
end
|
# == Schema Information
#
# Table name: users
#
# id :bigint not null, primary key
# aasm_state :string
# authenticity_token :string
# ban_reason :string
# first_name :string
# image :string
# last_name :string
# nickname :string
# provider :string
# token :string
# uid :string
# urls :string
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_users_on_authenticity_token (authenticity_token) UNIQUE
# index_users_on_token (token)
# index_users_on_uid (uid)
#
require 'test_helper'
class UserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
require_relative "board"
require_relative "boardcase"
require_relative "player"
class Game
attr_accessor :players, :board
def initialize
puts "Please enter first player's name"
player1_name = gets.chomp
player1 = Player.new(player1_name,"X")
puts "Please enter second player's name"
player2_name = gets.chomp
player2 = Player.new(player2_name,"O")
@players = [player1, player2]
@board = Board.new
launch_game
end
def launch_game
9.times do |turn|
play(turn)
if is_over == true
puts "Congrats #{@players[turn % 2].name}"
play_again
break
end
end
end
def play_again
puts "Do you want to play again? Type yes"
again = gets.chomp
if again == "yes"
Game.new
end
end
def play(turn)
i = turn % 2
puts "#{@players[i].name}, on what board do you want to play #{@players[i].symbol}?"
choice = gets.chomp.to_i
while @board.error_number(choice) == true || @board.error_letter(choice) == true
puts "#{@players[i].name} you are not allowed to play on this boardcase !"
puts "#{@players[i].name}, on what board do you want to play #{@players[i].symbol}?"
choice = gets.chomp.to_i
end
@board.change_value(choice, @players[i].symbol)
@board.print_case_value
end
def is_over
if @board.game_stops == true
true
end
end
end
#------------------------------------#
Game.new
|
# frozen_string_literal: true
FactoryBot.define do
factory :vendor do
name { 'Vodafone' }
end
end
|
json.array!(@cursos) do |curso|
json.extract! curso, :curso, :completado, :estudiante_id
json.url curso_url(curso, format: :json)
end
|
require 'ohol-family-trees/tiled_placement_log'
#require 'ohol-family-trees/key_plain'
#require 'ohol-family-trees/key_value_y_x'
require 'ohol-family-trees/key_value_y_x_first'
require 'ohol-family-trees/id_index'
require 'ohol-family-trees/cache_control'
require 'ohol-family-trees/content_type'
require 'fileutils'
require 'json'
require 'progress_bar'
require 'set'
module OHOLFamilyTrees
class OutputFinalPlacements
def span_path
"#{output_path}/spans.json"
end
def processed_path
"#{output_path}/processed_keyplace.json"
end
ZoomLevels = 24..24
attr_reader :output_path
attr_reader :filesystem
attr_reader :objects
def initialize(output_path, filesystem, objects)
@output_path = output_path
@filesystem = filesystem
@objects = objects
end
def spans
return @spans if @spans
@spans = {}
filesystem.read(span_path) do |f|
list = JSON.parse(f.read)
list.each do |span|
@spans[span['start'].to_s] = span
end
end
#p @spans
@spans
end
def processed
return @processed if @processed
@processed = {}
filesystem.read(processed_path) do |f|
@processed = JSON.parse(f.read)
end
#p @processed
@processed
end
def checkpoint
x = JSON.pretty_generate(spans.values.sort_by {|span| span['start']})
filesystem.write(span_path, CacheControl::NoCache.merge(ContentType::Json)) do |f|
f << x
end
filesystem.write(processed_path, CacheControl::NoCache.merge(ContentType::Json)) do |f|
f << JSON.pretty_generate(processed)
end
end
def base_time(logfile, basefile)
if basefile && processed[basefile.path]
base_span = processed[basefile.path]['spans']
.sort_by {|span| span['end']}
.last
#p base_span
if base_span
return base_span['end']
end
end
end
def base_tileset(time, zoom)
if time
cutoff = time - 14 * 24 * 60 * 60
tile_list = read_index(time, zoom, cutoff)
loader = KeyValueYXFirst.new(filesystem, output_path, zoom)
return TileSet.new(tile_list, loader)
end
end
def process(logfile, options = {})
base_time = base_time(logfile, options[:basefile])
time_processed = Time.now.to_i
time_tiles = time_processed
time_objects = time_processed
should_write_tiles = true
should_write_objects = true
record = processed[logfile.path]
if record &&
record['root_time'] == ((options[:rootfile] && options[:rootfile].timestamp) || 0) &&
record['base_time'] == (base_time || 0)
if logfile.cache_valid_at?(record['time'] || 0)
should_write_tiles = false
time_tiles = record['time']
end
if logfile.cache_valid_at?(record['time_objects'] || 0)
should_write_objects = false
time_objects = record['time_objects']
end
end
return unless should_write_tiles || should_write_objects
processed[logfile.path] = {
'time' => time_tiles,
'time_objects' => time_objects,
'root_time' => (options[:rootfile] && options[:rootfile].timestamp) || 0,
'base_time' => base_time || 0,
'spans' => [],
}
p logfile.path
ZoomLevels.each do |zoom|
tile_width = 2**(32 - zoom)
TiledPlacementLog.read(logfile, tile_width, {
:floor_removal => objects.floor_removal,
:object_over => objects.object_over,
:base_time => base_time,
:base_tiles => base_tileset(base_time, zoom),
}) do |span, tileset|
if span.s_length > 1
spans[span.s_start.to_s] = {
'start' => span.s_start,
'end' => span.s_end,
'base' => span.s_base,
}
#p spans
if should_write_tiles
write_tiles(tileset.updated_tiles, span.s_end, zoom)
write_index(tileset.tile_index, span.s_end, zoom)
end
if should_write_objects
index = tileset.object_index(tile_width)
total = index.map {|k,v| v.length}.sum
cutoff = (total*0.01).to_i
triples = index.map {|id,list| [id,list,list.length<cutoff]}
#sorted = index.sort_by {|k,v| v.length}
#sorted.each do |id, v|
# p [id, v.length, v.length.to_f/total, objects.names[id.to_s]]
#end
#p sorted.reverse.take(5)
write_object_index(triples, span.s_end)
write_objects(triples, span.s_end)
end
processed[logfile.path]['spans'] << {
'start' => span.s_start,
'end' => span.s_end,
'base' => span.s_base,
}
elsif processed[logfile.path]['spans'].length < 1
processed[logfile.path]['spans'] << {
'start' => span.s_base,
'end' => span.s_base,
'base' => span.s_base,
}
end
#p processed
end
end
checkpoint
end
def timestamp_fixup(logfile)
if processed[logfile.path]
unless logfile.cache_valid_at?(processed[logfile.path]['time'] || 0)
processed[logfile.path]['time'] = logfile.date.to_i
checkpoint
end
unless logfile.cache_valid_at?(processed[logfile.path]['time_objects'] || 0)
processed[logfile.path]['time_objects'] = logfile.date.to_i
checkpoint
end
end
end
def write_tiles(tiles, dir, zoom)
p "write tiles #{dir}/#{zoom}"
writer = KeyValueYXFirst.new(filesystem.with_metadata(CacheControl::OneWeek.merge(ContentType::Text)), output_path, zoom)
bar = ProgressBar.new(tiles.length)
tiles.each_pair do |coords,tile|
bar.increment!
next if tile.empty?
writer.write(tile, dir)
end
end
def write_index(triples, dir, zoom)
writer = TileIndex.new(filesystem.with_metadata(CacheControl::OneWeek.merge(ContentType::Text)), output_path, "kp")
writer.write_index(triples, dir, zoom)
end
def read_index(dir, zoom, cutoff)
reader = TileIndex.new(filesystem, output_path, "kp")
reader.read_index(dir, zoom, cutoff)
end
def write_objects(object_triples, dir)
p "write objects #{dir}"
writer = KeyValueYXFirst.new(filesystem.with_metadata(CacheControl::OneWeek.merge(ContentType::Text)), output_path, 0)
bar = ProgressBar.new(object_triples.length)
object_triples.each do |id,list_coords,inc|
bar.increment!
next if list_coords.empty?
next unless inc
path = "#{output_path}/#{dir}/ks/#{id}.txt"
#p path
triples = list_coords.map {|coords| coords + [id]}
writer.write_triples(triples, path)
end
end
def write_object_index(triples, dir)
writer = IdIndex.new(filesystem.with_metadata(CacheControl::OneWeek.merge(ContentType::Text)), output_path, "ks")
writer.write_index(triples, dir)
end
end
end
|
class Like < ApplicationRecord
belongs_to :user
belongs_to :space, counter_cache: true
end
|
class Payment < ApplicationRecord
has_many :orders
validates :name, presence: true, uniqueness: {case_sensitive: false}
end
|
#encoding: utf-8
require_relative 'sliding_piece'
class Queen < SlidingPiece
def initialize(board, pos, color)
super
@icon = (color == :white ? "♕" : "♛")
@value = 9
end
def piece_deltas
SIDE_DELTAS + DIAGONAL_DELTAS
end
end |
Given(/^I have shared the following peeps:$/) do |peeps|
peeps.hashes.each do |peep|
fill_in(:message, :with => peep['message'])
click_button 'Share'
end
end
Then(/^I should see "(.*?)" before "(.*?)"$/) do |message, message2|
first_position = page.body.index(message)
second_position = page.body.index(message2)
first_position.should < second_position
end |
#def nth_fibonacci(n)
# first = 1
# second = 1
# current = nil
#
# (n - 2).times do
# current = first + second
# first = second
# second = current
# end
#
# current
#end
# Solve Fibonacci with an Enumerator
class Fibonacci
def self.get_nth_fib(n)
fib_enum = Enumerator.new do |yielder|
first = 1
second = 1
loop do
yielder << first
first, second = second, first + second
end
end
fib_enum.take(n).last
end
end
p Fibonacci.get_nth_fib(5) == 5
p Fibonacci.get_nth_fib(6) == 8
p Fibonacci.get_nth_fib(7) == 13
p Fibonacci.get_nth_fib(70000)
|
class SuperAdmin::SubCategoriesController < SuperAdmin::SuperAdminController
add_breadcrumb "SUB CATEGORIES", "/super_admin/sub_categories"
layout "super_admin"
def index
@sub_categories = Category.where("parent_id IS NOT NULL").order("name asc")
end
def new
@category = Category.new
#render :layout => false
end
def create
@category = Category.new(category_params)
unless params[:category][:parent_id].blank?
if @category.save
flash[:notice] = "Sub Category was successfully Added."
render :json => {:success => true, :url => super_admin_sub_categories_path}.to_json
else
@errors = @category.errors
render :json => {:success => false, :html => render_to_string(:partial => '/layouts/errors')}.to_json
end
else
@category.errors.add(:parent_category, "Can't be Blank")
@errors = @category.errors
render :json => {:success => false, :html => render_to_string(:partial => '/layouts/errors')}.to_json
end
end
def update
@category = Category.find_by_id(params[:id])
unless params[:category][:parent_id].blank?
if @category.update_attributes(category_params)
flash[:notice] = "Category was successfully Added."
render :json => {:success => true, :url => super_admin_sub_categories_path}.to_json
else
@category = @user.errors
render :json => {:success => false, :html => render_to_string(:partial => '/layouts/errors')}.to_json
end
else
@category.errors.add(:Parent_category, "Can't be Blank")
@errors = @category.errors
render :json => {:success => false, :html => render_to_string(:partial => '/layouts/errors')}.to_json
end
end
def edit
@category = Category.find_by_id(params[:id])
#render :layout => false
end
def disable_category
@category = Category.find_by_id(params[:id])
if @category.update_attributes(:status => params[:status])
@sub_categories = Category.where("parent_id IS NOT NULL")
render :partial => "super_admin/sub_categories/list"
end
end
def category_params
params.require(:category).permit(:name, :parent_id, :parent_type)
end
end
|
require 'test_helper'
describe ZipCodeLocation do
describe '.get_geolocation_for(zip_code)' do
it "retrieves the latitude and longitude for a given zip code" do
stub_request(:get, "https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:88034100&key®ion=br").
to_return(status: 200,
body: Rails.root.join("test/fixtures/88034100.json").read,
headers: { "Content-Type" => "application/json" })
point = ZipCodeLocation.get_geolocation_for("88034100")
point[:lat].must_equal "-27.5759124"
point[:lng].must_equal "-48.5082472"
end
end
end
|
class ShippingErrorsController < ApplicationController
before_filter { @shop = Shop.find(params[:shop_id]) }
def index
@shipping_errors = @shop.shipping_errors.order(:message)
end
end |
require 'rqrcode'
module LabelGen
class QrRender
def self.build_url(number)
I18n.translate('label_gen.qr_url', :number => number)
end
def initialize(code, optns = {})
@qr = code
@dark_rgb = optns[:dark_rgb] || "000000"
@light_rgb = optns[:light_rgb] || "FFFFFF"
@length_overall = (optns[:length] || @qr.modules.count * 2) * 1.0
end
attr_reader :qr, :dark_rgb, :light_rgb, :length_overall
def fill(pdf)
qr.modules.each_index do |i|
qr.modules.each_index do |j|
pdf.fill_color module_color(i,j)
pdf.fill_rectangle(module_top_left(i,j, pdf.bounds.top_left),
module_length, module_length)
end
end
return true
end # fill
private
# Determine the square size to fill based on
# the number of modules and the overall length
def module_length
@module_length ||= length_overall / qr.modules.count
end
# Get the top-left corner where the
# module is located relative to
# the given origin, wich is the top_left
# of the current pdf bounding box
#
# @return Array [x, y]
def module_top_left(mod_i, mod_j, bounds_origin)
x = bounds_origin[0] + mod_i*module_length
y = bounds_origin[1] - mod_j*module_length
[x, y]
end
def module_color(mod_i, mod_j)
qr.dark?(mod_i,mod_j) ? dark_rgb : light_rgb
end
end
end
|
# frozen_string_literal: true
require_relative('../users_request')
require('ostruct')
describe UsersRequest do
let!(:users_request) { UsersRequest.new }
describe '#customize_object' do
context 'give two objects' do
let!(:object) do
OpenStruct.new(
{
id: 1,
email: 'george.bluth@reqres.in',
first_name: 'George',
last_name: 'Bluth',
avatar: 'url'
}
)
end
let!(:expected) do
[
{
name: 'George Bluth',
email: 'george.bluth@reqres.in'
}
]
end
it 'must be return only name and email' do
expect(users_request.send(:customize_object, [object])).to eq(expected)
end
end
end
describe '#json_to_object' do
context 'give a data with json format' do
let!(:string_json) do
'{ "name": "Michael Lawson", "email": "michael.lawson@reqres.in" }'
end
it 'must be return a object format' do
expect(users_request.send(:json_to_object, string_json).class).to eq(OpenStruct)
end
end
end
end
|
module Boxzooka
class OrdersResponseResult < BaseElement
scalar :order_id,
node_name: 'OrderID'
scalar :status
collection :error_messages,
flat: :true,
entry_node_name: 'ErrorMessage',
entry_field_type: :scalar,
entry_type: :string
def success?
status == 'Success'
end
def error?
status == 'Error'
end
end
end
|
require 'spec_helper'
describe Arachni::Reactor::Tasks do
subject { described_class.new }
let(:task) { described_class::Persistent.new{} }
let(:another_task) { described_class::Persistent.new{} }
describe '#<<' do
it 'adds a task to the list' do
subject << task
subject.should include task
end
it 'assigns an #owner to the task' do
subject << task
task.owner.should == subject
end
it 'returns self' do
(subject << task).should == subject
end
end
describe '#include?' do
context 'when it includes the given task' do
it 'returns true' do
subject << task
expect(subject.include?( task )).to be_truthy
end
end
context 'when it does not includes the given task' do
it 'returns false' do
subject << task
expect(subject.include?( another_task )).to be_falsey
end
end
end
describe '#delete' do
context 'when it includes the given task' do
it 'removes it' do
subject << task
subject.delete task
subject.should_not include task
end
it 'returns it' do
subject << task
subject.delete( task ).should == task
end
it 'removes the #owner association' do
subject << task
subject.delete( task ).should == task
task.owner.should be_nil
end
end
context 'when it does not include the given task' do
it 'returns nil' do
subject.delete( task ).should be_nil
end
end
end
describe '#size' do
it 'returns the size of the list' do
subject << task
subject << another_task
subject.size.should == 2
end
end
describe '#empty?' do
context 'when the list is empty' do
it 'returns true' do
subject.should be_empty
end
end
context 'when the list is not empty' do
it 'returns false' do
subject << task
subject.should_not be_empty
end
end
end
describe '#any?' do
context 'when the list is not empty' do
it 'returns true' do
subject << task
subject.should be_any
end
end
context 'when the list is empty' do
it 'returns false' do
subject.should_not be_any
end
end
end
describe '#clear' do
it 'removes all tasks' do
subject << task
subject << another_task
subject.clear
subject.should be_empty
end
end
describe '#call' do
it 'calls all tasks' do
called_one = false
called_two = false
subject << described_class::Persistent.new do
called_one = true
end
subject << described_class::Persistent.new do
called_two = true
end
subject.call
called_one.should be_truthy
called_two.should be_truthy
end
it 'returns self' do
subject.call.should == subject
end
context 'when arguments have been provided' do
it 'passes them to the tasks' do
called_one = nil
called_two = nil
subject << described_class::Persistent.new do |_, arg|
called_one = arg
end
subject << described_class::Persistent.new do |_, arg|
called_two = arg
end
subject.call( :stuff )
called_one.should == :stuff
called_two.should == :stuff
end
end
end
end
|
get '/' do
@questions = Question.order(views_count: :desc).all
erb :index
end
|
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'pry'
require 'carrierwave'
require 'carrierwave-google-storage'
# require 'carrierwave/google/storage'
FeatureUploader = Class.new(CarrierWave::Uploader::Base) do
# def filename; 'image.png'; end
end
def source_environment_file!
if File.exists?('.env')
File.readlines('.env').each do |line|
key, value = line.split('=')
ENV[key] = value.chomp
end
end
ENV['GCLOUD_KEYFILE'] = Dir.pwd + "/.gcp-keyfile.json"
end
RSpec.configure do |config|
source_environment_file!
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
# config.filter_run :focus
config.run_all_when_everything_filtered = true
config.order = :random
if config.files_to_run.one?
config.default_formatter = 'doc'
end
Kernel.srand config.seed
config.before(:all, type: :feature) do
CarrierWave.configure do |config|
config.storage = :gcloud
config.gcloud_bucket = ENV['GCLOUD_BUCKET']
config.gcloud_bucket_is_public = true
config.gcloud_authenticated_url_expiration = 600
config.store_dir = 'uploaded_files'
config.gcloud_attributes = {
expires: 600
}
config.gcloud_credentials = {
gcloud_project: ENV['GCLOUD_PROJECT'],
gcloud_keyfile: ENV['GCLOUD_KEYFILE']
}
end
end
end |
require 'spec_helper'
module TwitterCli
describe LoginProcessor do
conn = PG.connect(:dbname => ENV['database'])
describe '#execute' do
context 'when user wants to logout' do
it "should handle the login of valid user" do
conn.exec('begin')
login_processor = LoginProcessor.new(conn)
allow(login_processor).to receive(:get_name) { 'anugrah' }
allow(login_processor).to receive(:get_password) { 'megamind' }
user_interface = UserInterface.new('anugrah')
allow(user_interface).to receive(:get_input).and_return('logout')
login_processor.user_interface = user_interface
expect(login_processor.execute).to eq("logging out")
end
end
end
end
end
|
require 'spec_helper'
describe Kindergarten::HeadGoverness do
before(:each) do
@governess = Kindergarten::HeadGoverness.new("child")
end
it "should include CanCan ability" do
@governess.should be_kind_of(CanCan::Ability)
end
describe :governing do
it "should guard the child" do
expect {
@governess.guard(:free, "Willy")
}.to raise_error(Kindergarten::AccessDenied)
end
it "should keep a closed eye" do
expect {
@governess.unguarded do
@governess.guard(:free, "Willy")
end
}.to_not raise_error(Kindergarten::AccessDenied)
end
end
describe :washing do
it "should scrub attributes" do
attr = { :a => 1, :b => 2, :c => 3 }
scrubbed = @governess.scrub(attr, :a, :c)
scrubbed.should_not be_has_key(:b)
end
it "should return a ScrubbedHash after scrubbing" do
attr = { :a => 1, :b => 2, :c => 3 }
scrubbed = @governess.scrub(attr, :a, :c)
scrubbed.should be_kind_of(Kindergarten::ScrubbedHash)
end
it "should rinse attributes" do
attr = { :a => 1, :b => "2a", :c => 3 }
rinsed = @governess.rinse(attr, :a => /(\d+)/, :b => /(\D+)/)
rinsed.should_not be_has_key(:c)
rinsed[:a].should eq "1"
rinsed[:b].should eq "a"
end
it "should pass attributes" do
attr = { :a => "1", :b => "2a", :c => "3" }
rinsed = @governess.rinse(attr, :a => :pass, :c => :pass)
rinsed.should_not be_has_key(:b)
rinsed[:a].should eq "1"
rinsed[:c].should eq "3"
end
it "should return a RinsedHash after rinsing" do
attr = { :a => "1", :b => "2a", :c => "3" }
rinsed = @governess.rinse(attr, :a => /(\d+)/, :b => /(\d+)/)
rinsed.should be_kind_of(Kindergarten::RinsedHash)
end
end
end
|
class RenameCreditEntries < ActiveRecord::Migration[6.0]
def change
rename_table :credit_entries, :credit_items
end
end
|
# config/initializers/swagger-docs.rb
Swagger::Docs::Config.register_apis({
"1.0" => {
:api_extension_type => :json,
:api_file_path => "public/apidocs",
:base_path => "http://localhost:3000",
:clean_directory => true,
:base_api_controller => ActionController::API,
:attributes => {
:info => {
"title" => "Quidbox API",
"description" => "Quidbox API documentation",
"contact" => ""
}
}
}
})
class Swagger::Docs::Config
def self.transform_path(path, api_version)
# Make a distinction between the APIs and API documentation paths.
"apidocs/#{path}"
end
end
|
# frozen_string_literal: true
require_relative 'lib/animals_classes'
ANIMALS_TREE = [Animals, Chordates, Mammals, Primates, Hominids, People, HomoSapiens].freeze
ANIMALS_TREE.each do |cls|
puts cls.new
end
|
require '../util'
desc 'Creates a RDS'
task :create do
subnet_ids = aws <<-SH
aws ec2 describe-subnets
--filters 'Name=tag-key,Values=Name'
'Name=tag-value,Values=default'
--query 'Subnets[*].SubnetId'
SH
security_gruop_ids = aws <<-SH
aws ec2 describe-security-groups
--filters 'Name=tag-key,Values=Name'
'Name=tag-value,Values=default'
--query 'SecurityGroups[*].GroupId'
SH
# Creates a DB parameter group
# @see 『Amazon Web Services実践入門』初版 技術評論社 p.194
aws <<-SH, binding
aws rds create-db-parameter-group
--db-parameter-group-name test-param-mysql56
--description mysql56-parameter
--db-parameter-group-family MySQL5.6
SH
# Sets the parameters
# @see $ aws rds modify-db-parameter-group help
aws <<-SH, binding
aws rds modify-db-parameter-group
--db-parameter-group-name test-param-mysql56
--parameters
'ParameterName=character_set_client,ParameterValue=utf8'
SH
# Displays the parameters
# @see $ aws rds describe-db-parameters help
aws <<-SH, binding
aws rds describe-db-parameters
--db-parameter-group-name test-param-mysql56
SH
# Creates a DB option group
# @see 『Amazon Web Services実践入門』初版 技術評論社 pp.195-196
aws <<-SH, binding
aws rds create-option-group
--option-group-name test-mysql56-option
--option-group-description mysql56-option
--engine-name mysql
--major-engine-version 5.6
SH
# Adds a DB option
# @see $ aws rds add-option-to-option-group help
aws <<-SH, binding
aws rds add-option-to-option-group
--option-group-name test-mysql56-option
--options
'OptionName=MEMCACHED,VpcSecurityGroupMemberships=[<%= security_gruop_ids.join(',') %>],OptionSettings=[{Name=BACKLOG_QUEUE_LIMIT,Value=2048}]'
SH
# Creates a DB subnet group
# @see 『Amazon Web Services実践入門』初版 技術評論社 pp.195-196
aws <<-SH, binding
aws rds create-db-subnet-group
--db-subnet-group-name test-mysql56.subnet
--db-subnet-group-description mysql56.subnet
--subnet-ids <%= subnet_ids.join(' ') %>
SH
# Creates a RDS
# @see 『Amazon Web Services実践入門』初版 技術評論社 pp.200-203
aws <<-SH, binding
aws rds create-db-instance
--db-name test
--db-instance-identifier test-rds
--allocated-storage 5
--db-instance-class db.t2.micro
--engine MySQL
--master-username root
--master-user-password password
--vpc-security-group-ids <%= security_gruop_ids.join(' ') %>
--db-subnet-group-name test-mysql56.subnet
--preferred-maintenance-window Tue:04:00-Tue:04:30
--db-parameter-group-name test-param-mysql56
--backup-retention-period 1
--preferred-backup-window 04:30-05:00
--port 3306
--multi-az
--engine-version 5.6.23
--auto-minor-version-upgrade
--license-model general-public-license
--option-group-name test-mysql56-option
--no-publicly-accessible
SH
end
desc 'Accesses the RDS instance'
task :access do
rds = aws <<-SH, binding
aws rds describe-db-instances
--db-instance-identifier test-rds
SH
ec2s = get_instance tag: 'test-rds', query: 'Reservations[*]'
ec2s = create_instance tag: 'test-rds' if ec2s.empty?
dns = ec2s[0]['Instances'][0]['PublicDnsName']
ssh host: dns, cmd: 'sudo yum install -y mysql'
ssh host: dns, cmd: "echo show databases | mysql -h #{rds['DBInstances'][0]['Endpoint']['Address']} -u root -ppassword"
end
desc 'Deletes the RDS instance'
task :delete do
destroy_instance tag: 'test-rds'
# Deletes a RDS
# @see 『Amazon Web Services実践入門』初版 技術評論社 pp.215-218
aws <<-SH, binding
aws rds delete-db-instance
--db-instance-identifier test-rds
--skip-final-snapshot
SH
end
|
class RenamePartyColumns < ActiveRecord::Migration[5.2]
def change
rename_column :parties, :movie_api_id, :movie_id
rename_column :parties, :start_time_day, :start_time
end
end
|
class UserMailer < ActionMailer::Base
def signup_notification(user)
setup_email(user)
@subject += I18n.t('restful_authentication.activation_required_email_subject')
@body[:url] = "http://YOURSITE/activate/#{user.activation_code}"
end
def activation(user)
setup_email(user)
@subject += I18n.t('restful_authentication.activation_complete_email_subject')
@body[:url] = "http://YOURSITE/"
end
def password_reset_notification(user)
setup_email(user)
@subject += I18n.t('restful_authentication.password_reset_email_subject')
@body[:url] = "http://beta.golometrics.com/reset_password/#{user.password_reset_code}"
end
protected
def setup_email(user)
@recipients = "#{user.email}"
@from = "do-not-reply@golometrics.com"
@subject = "beta.golometrics.com password reset request"
@sent_on = Time.now
@body[:user] = user
end
end
|
class CreatePublicationMastertheses < ActiveRecord::Migration
def change
create_table :publication_mastertheses do |t|
t.integer :publication_id
t.integer :masterthesis_id
t.timestamps null: false
end
end
end
|
require "spec_helper"
# rubocop:disable Style/SpaceInsideBrackets,Style/MultilineArrayBraceLayout
# rubocop:disable Metrics/BlockLength
describe PuppetDBQuery::Tokenizer do
TOKENIZER_DATA = [
[ 'hostname=\'puppetdb-mike-217922\'',
[:hostname, :_equal, "puppetdb-mike-217922"]
],
[ 'disable_puppet = true',
[:disable_puppet, :_equal, true]
],
[ 'fqdn~"app-dev" and group=develop and vertical~tracking and cluster_color~BLUE',
[:fqdn, :_match, "app-dev", :_and, :group, :_equal, :develop, :_and, :vertical, :_match,
:tracking, :_and, :cluster_color, :_match, :BLUE]
],
[ 'fqdn~"kafka" and group=develop and vertical=tracking',
[:fqdn, :_match, "kafka", :_and, :group, :_equal, :develop, :_and, :vertical, :_equal,
:tracking]
],
[ '(group="develop-ci" or group=develop or group=mock) and (operatingsystemmajrelease="6")',
[:_begin, :group, :_equal, "develop-ci", :_or, :group, :_equal, :develop, :_or, :group,
:_equal, :mock, :_end, :_and, :_begin, :operatingsystemmajrelease, :_equal, "6", :_end]
],
[ "server_type=zoo or server_type='mesos-magr') and group!='infrastructure-ci'",
[:server_type, :_equal, :zoo, :_or, :server_type, :_equal, "mesos-magr", :_end, :_and,
:group, :_not_equal, "infrastructure-ci"]
],
[ "server_type~'mesos-magr' and group='ops-ci' and operatingsystemmajrelease=7 and" \
" vmtest_vm!=true and disable_puppet!=true and puppet_artifact_version!=NO_VERSION_CHECK",
[:server_type, :_match, "mesos-magr", :_and, :group, :_equal, "ops-ci", :_and,
:operatingsystemmajrelease, :_equal, 7, :_and, :vmtest_vm, :_not_equal, true, :_and,
:disable_puppet, :_not_equal, true, :_and, :puppet_artifact_version, :_not_equal,
:NO_VERSION_CHECK]
],
].freeze
TOKENIZER_DATA.each do |q, a|
describe "translates correctly #{q.inspect}" do
subject { PuppetDBQuery::Tokenizer.new(q) }
it "into tokens" do
expect(subject.map { |n| n }).to eq(a)
end
end
end
end
|
5 topics on assessment
algorithms
modeling
schema-design
sql
debugging
sherif abushadi god like review
-----------------------------------
recursion vs iteration
# problem: reverse a string using iteration vs recursion
def rev_iter(string)
new_str = ""
strings.chars.each do |letter|
new_str = letter + new_str
end
end
#test
# str = 'hello'
# p rev_iter(str) == str.reverse
def rev_recu(string, new_str = "") # must have new_str = "" so it "passes in through the door with recursion"
chars = string.chars
new_str << chars.pop
string = chars.join
return if string.length.zero? # this line will give us the kick out (exiting recursion)
#need to do something before going into recursion.
rev_recu(string, new_str)
end
#test
# str = 'hello'
# p rev_iter(str) == str.reverse
------------------------------------
modules
# modules are used for two things in ruby.
# 1. namespacing
module A
module B
module C
class X
end
end
end
end
p A::B::C::X.new
# 2. makes methods and classes available when module is called
module A
def x
puts "hi from x"
end
def y
puts "hi from y"
end
end
# extend puts self on each of the methods.
# module A
# extend self
# end
# A.x
# A.y
# --------
class M
include A
end
#--------
M.new.x
M.new.y
# --------
------------------------------------
mvc
extend self is equivalent to def self.do_something end
class Model # i hold data. Model holds anything related to data, validation, connection to database.
attr_reader :data
def initialize
@data = "hello"
end
end
# class Controller # i make decisions
module Controller
extend self
def run
# view = View.new
model = Model.new
View.render(model.data)
end
end
# class View # i show stuff. Gives display out to the user.
module View
extend self
def render(text)
puts text
end
end
Controller.new.run
------------------------------------
parsing csv
require 'csv'
# p CSV.readlines('data.csv') #comes in as an array
#
p CSV.readlines('data.csv', #comes in as an hash
headers: true,
header_converters: :symbol).map do | row |
row[:school] != "no"
end
sites.select{|site| site != "no"}.count
#writing to CSV
CSV.open("new_data.csv", 'w+') do |row|
row<< [ '' , '' , '' ]
end
------------------------------------
to_s
class A
def intialize
@data = "123"
@lata = "bye"
end
def to_s
"i am a class of type #{self.class} and i hold #{@data}"
end
def inspect
"i am the same class"
end
end
p A.new
puts A.new
------------------------------------
UPDATE TABLE
Read massive amounts of SQL from articles.
------------------------------------
Nested data structures
Read week 3 under discussions on github.
------------------------------------ |
DeleteCheckUserMutation = GraphQL::Relay::Mutation.define do
name 'DeleteCheckUser'
input_field :id, !types.Int
return_field :success, types.Boolean
resolve -> (_root, inputs, _ctx) {
user = User.where(id: inputs[:id]).last
if user.nil?
raise ActiveRecord::RecordNotFound
else
ability = Ability.new(user)
raise I18n.t('permission_error', "Sorry, you are not allowed to perform this operation") if ability.cannot?(:destroy, user)
User.delete_check_user(user)
{ success: true }
end
}
end
|
require 'test_helper'
class SubmissionMailerTest < ActionMailer::TestCase
def setup
@writer = create(:writer)
@profile = create(:profile, screen_writer: @writer)
@submission = create(:submission, writer: @writer)
@reviewer = create(:reviewer)
end
test "new_submission_notification" do
mail = SubmissionMailer.new_submission_notification(@submission)
assert_equal "New submission: Mysubmission", mail.subject
assert_equal [@reviewer.email], mail.to
assert_equal ["teambbarters@gmail.com"], mail.from
end
end
|
require 'rails_helper'
feature 'recipe', type: :feature do
let(:user) { create(:user) }
scenario 'post recipe' do
# ログイン前には投稿ボタンがない
visit root_path
expect(page).to have_no_link('レシピを書く')
# ログイン処理
visit new_user_session_path
fill_in 'user_email', with: user.email
fill_in 'user_password', with: user.password
find('input[name="commit"]').click
expect(current_path).to eq root_path
expect(page).to have_link('レシピを書く')
# レシピを投稿する
expect {
click_link('レシピを書く')
expect(current_path).to eq new_recipe_path
fill_in 'recipe_title', with: 'さつまいも'
fill_in 'recipe_catch_copy', with: 'さつまいも'
find('input[class="recipe_submit_button"]','保存する').click
}.to change(Recipe, :count).by(1)
end
end
|
#!/usr/bin/env ruby
require 'mkmf'
$CFLAGS = '-std=c99 -Os'
inc_paths = %w(
/usr/include/postgresql
/usr/local/include/postgresql
/opt/local/include
/opt/local/include/postgresql90
/opt/local/include/postgresql85
/opt/local/include/postgresql84
/sw/include
)
lib_paths = %w(
/usr/lib
/usr/local/lib
/opt/lib
/opt/local/lib
/sw/lib
)
find_header('libpq-fe.h', *inc_paths) or raise 'unable to locate postgresql headers'
find_library('pq', 'main', *lib_paths) or raise 'unable to locate postgresql lib'
create_makefile('slow_hash_aset')
|
require 'minitest/autorun'
# Board
class BasicBoardTest < Minitest::Test
require_relative '../../lib/connect4/board.rb'
def setup
@board = Board.new([[0], [], [], [], [], [], []])
end
def test_moves_in_incomplete_column
@board.move(1, 1)
assert_equal(1, @board[1][0])
end
def test_notices_game_not_won
refute(@board.game_won?(0))
end
def test_prints_just_one_token
out = capture_io { @board.p }[0]
assert_equal(1, out.scan(/⬤/).length)
end
def test_spots_free
assert(@board.free?(0))
end
def test_doesnt_yell_if_free
assert_empty(capture_io { @board.yell_unless_free?(0) }[0])
end
def test_knows_not_all_full
refute(@board.all?)
end
end
class PopulatedBoardTest < Minitest::Test
require_relative '../../lib/connect4/board.rb'
def setup
arr = [0, 1, 0, 1, 0, 1]
@board = Board.new([arr, arr, arr, arr[1..6], arr, arr, arr])
end
def test_notices_game_not_won
refute(@board.game_won?(3))
end
def test_prints41_tokens
out = capture_io { @board.p }[0]
assert_equal(41, out.scan(/⬤/).length)
end
def test_notices_full
refute(@board.free?(0))
end
def test_yells_if_not_free
refute_empty(capture_io { @board.yell_unless_free?(0) }[0])
end
end
class DrawnBoardTest < Minitest::Test
require_relative '../../lib/connect4/board.rb'
def setup
arr = [0, 1, 0, 1, 0, 1]
@board = Board.new([arr, arr, arr, arr.reverse, arr, arr, arr])
end
def test_knows_all_full
assert(@board.all?)
end
def test_doesnt_think_game_won
7.times { |column| refute(@board.game_won?(column)) }
end
end
class WonBoardTest < Minitest::Test
require_relative '../../lib/connect4/board.rb'
def setup
@arr = [[1, 1, 1, 0], [1, 1, 0], [1, 0], [0], [1], [0], [0]]
end
7.times do |column|
define_method("test_spots_row_win_col#{column}".to_sym) do
board = Board.new([[1], [1], [0], [0], [0], [0], [1]])
result = board.game_won?(column)
column.between?(2, 5) ? assert(result) : refute(result)
end
end
def test_spots_column_win
board = Board.new([[1], [1], [0, 0, 0, 0], [1], [], [], []])
assert(board.game_won?(2))
end
7.times do |column|
define_method("test_spots_backslash_diagonal_win_col#{column}".to_sym) do
result = Board.new(@arr).game_won?(column)
column < 4 ? assert(result) : refute(result)
end
end
7.times do |column|
define_method("test_spots_forwardslash_diagonal_win_col#{column}".to_sym) do
result = Board.new(@arr.reverse).game_won?(column)
column > 2 ? assert(result) : refute(result)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.