text stringlengths 10 2.61M |
|---|
require 'deep_clone'
module SudokuHelpers
def self.log(str)
puts str if LOGS
end
def self.logln(str)
puts str if LOGS
end
def self.print_board(board)
return unless board.is_a?(Array)
puts "Board: "
0.upto(SIZE_MATRIX - 1).each do |row|
0.upto(SIZE_MATRIX - 1).each do |column|
print "#{board[row * SIZE_MATRIX + column].value}, "
print ' ' if (row * SIZE_MATRIX + column) % 3 == 2
end
print "\n"
print "\n" if row % 3 == 2
end
end
# http://aima.cs.berkeley.edu/2nd-ed/newchap05.pdf
# When- FORWARD CHECKING ever a variable X is assigned, the forward checking process looks at each unassigned variable
# Y that is connected to X by a constraint and deletes from Y ’s domain any value that is inconsistent
# with the value chosen for X.
def self.forward_check(assigned_element, domain_value, board, available_domains)
# deep clone for safety, I don't want to mutate any of the domains
new_domains = DeepClone.clone available_domains
new_domains[assigned_element.index] = nil
# > Looks at each unassigned variable Y that is connected to X
get_neighbors(assigned_element, board).reject do |e|
new_domains[e.index].nil?
end.each do |element|
# new_domains[element.index].each do |new_domain_value|
# if !fits_in?(element, new_domain_value, board)
# > deletes from Y ’s domain any value that is inconsistent with the value chosen for X.
new_domains[element.index] = new_domains[element.index] - [domain_value]
# In case, the domain is empty after removal it means that
# I've wrong domain value and we need to select something else
if new_domains[element.index].empty?
return nil
end
# end
# end
end
return new_domains
end
def self.get_neighbors(element, board)
(get_row(element, board) + get_col(element, board) + get_sqr(element, board)).uniq
end
def self.fits_in?(element, value, board)
!get_neighbors(element, board).map { |e| e.value }.include?(value)
end
def self.get_row(element, board)
0.upto(8).map do |column|
# log "column - #{column}"; log "\trow - #{element.row}"; log "\tvalue: #{board[element.row * SIZE_MATRIX + column].value}\n";
board[element.row * SIZE_MATRIX + column]
end
end
def self.get_col(element, board)
0.upto(8).map do |row|
# log "column - #{element.column}"; log "\trow - #{row}"; log "\tvalue: #{board[row * SIZE_MATRIX + element.column].value}\n";
board[row * SIZE_MATRIX + element.column]
end
end
def self.get_sqr(element, board)
elements = []
0.upto(2).each do |i|
0.upto(2).each do |j|
row = j + 3 * (element.row / 3)
column = i + 3 * (element.column / 3)
# log "column - #{column} \trow - #{row} \tvalue: #{board[row * 9 + column].value} | fitting: #{value} | #{element}";
elements.push board[row * SIZE_MATRIX + column]
end
end
elements
end
def self.get_next_empty_element(board, domain=nil)
board.each_with_index do |element, index|
if domain
return element if domain[element.index]
else
return element if element.value == 0
end
end
return nil
end
def self.get_next_empty_with_smallest_domain(board, domain)
board.reject { |e| domain[e.index].nil? }.sort { |a, b|
domain[a.index].count <=> domain[b.index].count
}.last
end
end
|
FactoryGirl.define do
factory :skill_group do
name { Faker::Lorem.word }
description { Faker::Lorem.word }
sequence(:sequence)
end
end
|
# frozen_string_literal: true
class Cell
attr_accessor :row, :column, :grid, :content, :visited
def initialize(row, column, content)
@row = row
@column = column
@content = content
@visited = false
end
def visited?
@visited
end
def get_neighbors(grid)
neighbors = Array.new
top = grid[@row - 1][@column]
right = grid[@row][@column + 1]
bottom = grid[@row + 1][@column]
left = grid[@row][@column - 1]
if !top.nil? && !top.visited && !top.wall?
neighbors << top
end
if !right.nil? && !right.visited && !right.wall?
neighbors << right
end
if !bottom.nil? && !bottom.visited && !bottom.wall?
neighbors << bottom
end
if !left.nil? && !left.visited && !left.wall?
neighbors << left
end
if neighbors.length > 0
return neighbors
else
return nil
end
end
def fill
@content = "*"
end
def unfill
@content = " " if !wall? && !start? && !end?
end
def wall?
return true if @content == '+' || @content == '-' || @content == '|'
return false
end
def start?
return true if @content == 'S'
return false
end
def end?
return true if @content == 'E'
return false
end
end
class Maze
@current = nil
def initialize
# Represent the whole grid
@grid = Array.new
# Represent all the path passed by the 'pointer
@stack = Array.new
file = File.read('map.txt')
matrix = file.split("\n")
matrix.each_with_index do |line, row|
submap = []
line.split('').each_with_index do |content, column|
submap << Cell.new(row, column, content)
end
@grid << submap
end
end
def paint
@grid.each do |line|
line.each do |cell|
print cell.content
end
puts ''
end
sleep(0.03)
puts "==================================="
end
def solve
@current = get_start_cell
walk(@grid, @current, @stack)
# while !@current.end?
# walk(@grid, @current, @stack)
# sleep(0.03)
# paint
# end
end
def print_solution
@stack.each do |cell|
print "#{cell.row} : #{cell.column}\n"
end
end
private
def get_start_cell
@grid.each do |line|
line.each do |cell|
if cell.start?
return cell
end
end
end
return nil
end
def walk(grid, current, stack)
return current if current.end?
current.visited = true
current.fill
stack << current
paint
neighbors = current.get_neighbors(grid)
if neighbors == nil
return
end
neighbors.each do |n|
c = walk(grid, n, stack)
return if !c.nil?
end
# if next_cell != nil
# next_cell.visited = true
# next_cell.fill
# stack << current
# current = next_cell
# paint
# walk(grid, current, stack)
# elsif stack.length > 0
# #dead-end
# # return
# grid[current.row][current.column].unfill
# current = stack.pop
# # walk(grid, current, stack)
# return
# end
end
def walk_solution
@grid.each do |line|
line.each do |cell|
cell.unfill
end
end
@stack.each do |cell|
@grid[cell.row][cell.column].fill
sleep(0.03)
paint
end
end
end
m = Maze.new
m.solve
|
#
# Cookbook Name:: cuckoo
# Spec:: default
#
require 'spec_helper'
describe 'cuckoo::_virtualbox' do
context 'When all attributes are default, on ubuntu platform' do
cached(:chef_run) do
runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '14.04')
runner.converge(described_recipe)
end
before(:all) do
stub_command('/usr/bin/vboxmanage list extpacks | grep 5.0.16').and_return(false)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
it 'includes apt::default recipe' do
expect(chef_run).to include_recipe('apt::default')
end
it 'adds the oracle-virtualbox apt_reposotory' do
expect(chef_run).to add_apt_repository('oracle-virtualbox')
end
it 'installs the virtualbox package' do
expect(chef_run).to install_package("virtualbox-#{chef_run.node.virtualbox.version}")
end
it 'installs the dkms package' do
expect(chef_run).to install_package('dkms')
end
it 'adds the cuckoo user to virtualbox group' do
expect(chef_run).to modify_group('vboxusers').with(
members: [chef_run.node.cuckoo.host.user],
append: true
)
end
end
end
|
module V1
class SimulationInputsController < SecuredController
before_action :ensure_user_completed_questionnaire!
before_action :ensure_user_selected_portfolio!
before_action :ensure_user_selected_expenses!
def index
if params[:ids] && params[:ids].present?
# Purposefully getting an array, rather than current_user.sim_inputs
inputs = SimulationInput.where(id: params[:ids], user_id: current_user.id)
render json: inputs if stale?(etag: inputs)
else # Standard index action (no IDS array parameter)
if last_modified = current_user.simulation_input.try(:updated_at)
# Purposefully getting an array, rather than current_user.questionnaire
render json: SimulationInput.where(user_id: current_user.id) if stale?(etag: last_modified, last_modified: last_modified)
else
render json: {simulation_inputs: []}
end
end
end
def show
simulation_input = current_user.simulation_input
render json: simulation_input if stale?(simulation_input)
end
def create
inputs = current_user.build_simulation_input(input_params)
if inputs.save
render json: inputs, status: :created
else
render json: inputs.errors, status: :unprocessable_entity
end
end
def update
inputs = current_user.simulation_input
if inputs.update_attributes(input_params)
render json: inputs, status: :ok
else
render json: inputs.errors, status: :unprocessable_entity
end
end
private
def input_params
params.require(:simulation_input).permit(:user_is_male,
:married, :male_age, :female_age, :user_retired, :retirement_age_male,
:retirement_age_female, :assets, :expenses_inflation_index,
:life_insurance, :income, :current_tax_rate, :salary_increase,
:retirement_income, :retirement_expenses, :retirement_tax_rate,
:income_inflation_index, :include_home, :home_value, :sell_house_in,
:new_home_relative_value, :expenses_multiplier,
:fraction_for_single_income)
end
end
end
|
module Pompeu
class AndroidSource
def initialize textDB, languages, default_language, android_path, target
@textDB = textDB
@languages = languages
@android_path = android_path
@default_language = default_language
@target = target
end
#imports data form android xml files to the database
def import_all
@languages.each do |language|
import language
end
end
def import language
file = android_file_path(language)
if File.exist? file
android_file = AndroidFile.from_files file, @target
android_file.to_db @textDB, language.code
end
end
# writes the data to android string.xml files
def export(_appname = nil)
@languages.each do |language|
folder = android_folder(language)
unless File.exist?(folder)
Logging.logger.warn "Pompeu - creating folder for android language #{language.code}: #{folder}"
Dir.mkdir folder
end
file = android_file_path(language)
android_file = AndroidFile.from_db @textDB, language.code, @target
android_file.to_files file
end
end
def android_file_path language
File.join android_folder(language), "strings.xml"
end
def android_folder language
android_lang = language.for "android"
values_folder = language.code == @default_language ? "values" : "values-#{android_lang}"
File.join @android_path, values_folder
end
end
end |
$LOAD_PATH << 'lib'
require 'reviewr'
class MockGit < Reviewr::Git
attr_accessor :commands
def initialize
@responses = {}
@commands = []
end
def execute(cmd)
@commands << cmd
@responses[cmd] || ""
end
def register(cmd, response)
@responses[cmd] = response
end
end
class MockPony
class << self
def mail(opts)
@sent = opts
end
def sent
@sent ||= {}
end
end
end
Reviewr::Git.instance = MockGit.new
# Ugly stubbing so cucumber isn't sending email
Pony.class_eval("def self.mail(opts = {}); MockPony.mail(opts); end")
Pony.class_eval("def self.sent; MockPony.sent; end")
|
require 'dry/container'
module Containers
class NotifierContainer
extend Dry::Container::Mixin
register 'osx_notifier' do
OsxNotifier.new
end
register 'say_notifier' do
SayNotifier.new
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + "/product_base_page")
class ReviewLandingPage < ProductBasePage
def initialize
@success_message = "Congratulations! Your review has been published"
@message_element = "infomsg"
end
def success_message?
selenium.wait_for_element_to_present @message_element
selenium.is_text_present @success_message
end
end
|
require File.expand_path('../redmine_test_patch', __FILE__)
module EasyExtensions
module GroupsControllerTestPatch
extend RedmineTestPatch
repair_test :test_edit do
get :edit, :id => 10
assert_response :success
assert_template 'edit'
assert_select 'div#tab-content-general'
assert_select 'a[href=/groups/10/edit?tab=users]'
assert_select 'a[href=/groups/10/edit?tab=memberships]'
end
repair_test :test_new_membership do
assert_difference 'Group.find(10).members.count' do
post :edit_membership, :id => 10, :membership => {:project_ids => [2], :role_ids => ['1', '2']}
end
end
repair_test :test_xhr_new_membership do
assert_difference 'Group.find(10).members.count' do
xhr :post, :edit_membership, :id => 10, :membership => {:project_ids => [2], :role_ids => ['1', '2']}
assert_response :success
assert_template 'edit_membership'
assert_equal 'text/javascript', response.content_type
end
assert_match /OnlineStore/, response.body
end
end
end
|
class Admin::CourtsController < Admin::ApplicationController
# GET /courts
# GET /courts.json
def index
@courts = Court.by_name
respond_to do |format|
format.html # index.html.erb
format.json { render json: @courts }
end
end
# GET /courts/1
# GET /courts/1.json
def show
@court = Court.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @court }
end
end
# GET /courts/new
# GET /courts/new.json
def new
@court = Court.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @court }
end
end
# GET /courts/1/edit
def edit
@court = Court.find(params[:id])
@court_contacts = @court.contacts.order(:sort)
end
# POST /courts
# POST /courts.json
def create
@court = Court.new(params[:court])
respond_to do |format|
if @court.save
purge_all_pages
format.html { redirect_to edit_admin_court_path(@court), notice: 'Page was successfully created.' }
format.json { render json: @court, status: :created, location: @court }
else
format.html { render action: "new" }
format.json { render json: @court.errors, status: :unprocessable_entity }
end
end
end
# PUT /courts/1
# PUT /courts/1.json
def update
@court = Court.find(params[:id])
respond_to do |format|
if @court.update_attributes(params[:court])
purge_all_pages
format.html { redirect_to edit_admin_court_path(@court), notice: 'Page was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @court.errors, status: :unprocessable_entity }
end
end
end
# DELETE /courts/1
# DELETE /courts/1.json
def destroy
@court = Court.find(params[:id])
@court.destroy
purge_all_pages
respond_to do |format|
format.html { redirect_to admin_courts_url }
format.json { head :no_content }
end
end
end
|
class TopController < ApplicationController
def index
all_stories = UchigawaKun::Application.config.stories
@stories = Hash[all_stories.to_a.reverse]
end
end
|
## Dash Insert
# Have the function DashInsert(str) insert dashes ('-') between each two
# odd numbers in str. For example if str is 454793 the output should be
# 7547-9-3. Dont Count Zero as an odd number.
def DashInsert(str)
dashed = ''
str.chars.each_with_index do |char, i|
dashed << char
dashed << '-' if str[i].to_i.odd? && str[i + 1].to_i.odd?
end
dashed
end
|
#===============================================================================
# * Sprite_Projectile
#-------------------------------------------------------------------------------
# Projectiles in the game, game cannot be saved if any projectile exist
#===============================================================================
class Sprite_Projectile < Sprite_Character
#--------------------------------------------------------------------------
# * Public character Variables
#--------------------------------------------------------------------------
attr_reader :executed
#--------------------------------------------------------------------------
# * Object Initialization
#--------------------------------------------------------------------------
def initialize(viewport, character)
@tile_id = character.tile_id
@character_name = character.character_name
@executed = false
super(viewport, character)
end
#--------------------------------------------------------------------------
# * Frame Update
#--------------------------------------------------------------------------
def update
super
update_dispose
end
#--------------------------------------------------------------------------
# * Dispose when executed
#--------------------------------------------------------------------------
def update_dispose
return unless @executed
return if animation?
self.dispose
@character.deactivate
end
#--------------------------------------------------------------------------
def update_deactivate
return unless @executed
return if animation?
deactivate
end
#--------------------------------------------------------------------------
# * Determine if Graphic Changed
#--------------------------------------------------------------------------
def graphic_changed?
@character_index != @character.character_index
end
#--------------------------------------------------------------------------
# * Update Transfer Origin Bitmap
#--------------------------------------------------------------------------
def update_bitmap
if graphic_changed?
@character_index = @character.character_index
set_character_bitmap
end
end
#--------------------------------------------------------------------------
# * Execute effect on collide
#--------------------------------------------------------------------------
def execute_collide
start_collide_animation
@character.execute_action
end
#--------------------------------------------------------------------------
# * Execute animation when collided
#--------------------------------------------------------------------------
def start_collide_animation
@character.transparent = true
if !animation? && @character.item.tool_animation > 0
animation = $data_animations[@character.item.tool_animation]
start_animation(animation)
end
@executed = true
end
#--------------------------------------------------------------------------
# * Set Character Bitmap
#--------------------------------------------------------------------------
def set_character_bitmap
self.bitmap = Cache.Arms(@character_name)
sign = @character_name[/^[\!\$]./]
if sign && sign.include?('$')
@cw = bitmap.width / 3
@ch = bitmap.height / 4
else
@cw = bitmap.width / 12
@ch = bitmap.height / 8
end
self.ox = @cw / 2
self.oy = @ch
end
#--------------------------------------------------------------------------
# * Set New Effect
#--------------------------------------------------------------------------
def setup_new_effect
end
end
|
class Specinfra::Command::Base::User < Specinfra::Command::Base
class << self
def check_exists(user)
"id #{escape(user)}"
end
def check_belongs_to_group(user, group)
"id #{escape(user)} | awk '{print $3}' | grep -- #{escape(group)}"
end
def check_belongs_to_primary_group(user, group)
"id -gn #{escape(user)}| grep ^#{escape(group)}$"
end
def check_has_uid(user, uid)
regexp = "^uid=#{uid}("
"id #{escape(user)} | grep -- #{escape(regexp)}"
end
def check_has_home_directory(user, path_to_home)
"getent passwd #{escape(user)} | cut -f 6 -d ':' | grep -w -- #{escape(path_to_home)}"
end
def check_has_login_shell(user, path_to_shell)
"getent passwd #{escape(user)} | cut -f 7 -d ':' | grep -w -- #{escape(path_to_shell)}"
end
def check_has_authorized_key(user, key)
key.sub!(/\s+\S*$/, '') if key.match(/^\S+\s+\S+\s+\S*$/)
"grep -w -- #{escape(key)} ~#{escape(user)}/.ssh/authorized_keys"
end
def get_minimum_days_between_password_change(user)
"chage -l #{escape(user)} | grep '^Minimum.*:' | awk -F ': ' '{print $2}'"
end
def get_maximum_days_between_password_change(user)
"chage -l #{escape(user)} | grep '^Maximum.*:' | awk -F ': ' '{print $2}'"
end
def get_uid(user)
"id -u #{escape(user)}"
end
def get_gid(user)
"id -g #{escape(user)}"
end
def get_home_directory(user)
"getent passwd #{escape(user)} | awk -F: '{ print $6 }'"
end
def get_login_shell(user)
"getent passwd #{escape(user)} | cut -f 7 -d ':'"
end
def update_home_directory(user, directory)
"usermod -d #{escape(directory)} #{escape(user)}"
end
def update_login_shell(user, shell)
"usermod -s #{escape(shell)} #{escape(user)}"
end
def update_uid(user, uid)
"usermod -u #{escape(uid)} #{escape(user)}"
end
def update_gid(user, gid)
"usermod -g #{escape(gid)} #{escape(user)}"
end
def add(user, options)
command = ['useradd']
command << '-g' << escape(options[:gid]) if options[:gid]
command << '-d' << escape(options[:home_directory]) if options[:home_directory]
command << '-p' << escape(options[:password]) if options[:password]
command << '-s' << escape(options[:shell]) if options[:shell]
command << '-m' if options[:create_home]
command << '-r' if options[:system_user]
command << '-u' << escape(options[:uid]) if options[:uid]
command << escape(user)
command.join(' ')
end
def update_encrypted_password(user, encrypted_password)
%Q!echo #{escape("#{user}:#{encrypted_password}")} | chpasswd -e!
end
def get_encrypted_password(user)
"getent shadow #{escape(user)} | awk -F: '{ print $2 }'"
end
end
end
|
module Stinger
module Schemas
class ComparesNumberOfColumnsAction
extend LightService::Action
expects :compare_columns, :to_columns, :compare, :report, :table
executed do |ctx|
next ctx if ctx.compare_columns.length == ctx.to_columns.length
if ctx.compare_columns.length < ctx.to_columns.length
missing_columns = column_names_from(ctx.to_columns) -
column_names_from(ctx.compare_columns)
msg = "#{missing_columns.join(', ')} " \
"field(s) for `#{ctx.compare}` shard are missing"
ctx.report[ctx.table] << msg
end
if ctx.compare_columns.length > ctx.to_columns.length
extra_columns = column_names_from(ctx.compare_columns) -
column_names_from(ctx.to_columns)
msg = "#{extra_columns.join(', ')} " \
"field(s) for `#{ctx.compare}` shard are extra"
ctx.report[ctx.table] << msg
end
ctx.skip_remaining!
end
def self.column_names_from(columns)
columns.map do |column|
column.fetch(:field)
end
end
end
end
end
|
# Your Names
# 1) Steve Jones
#
# We spent 1.5 hours on this challenge.
# Bakery Serving Size portion calculator.
# Two stages of refactoring.
# 1. Readability. aka renaming variables.
# 2. Logic and redudancy. aka keeping your code DRY.
# You ALWAYS do readability first.
# Because it is unlikely to break anything.
# AND can make refactoring logic easier as well.
# library, container, counter.
# container = []
# list_of_students = []
def serving_size_calc(item_to_make, available_ingredients)
available_foods = {"cookie" => 1, "cake" => 5, "pie" => 7}
#error_counter = 3
# I have 10 ingredients. 10 bags of flour.
# I know if I divide 10 % 5, I can make 2 cakes.
# library is the __________.
# Iterate through each item in the library...
#available_foods.each do |food|
# The food variable represents the current food/key in the library.
# IF the current_food is NOT equal to the item_to_make...
# if available_foods[food] != available_foods[item_to_make]
if available_foods.include?(item_to_make) == false
# THEN, subtract one from error counter.
# p error_counter += -1
raise ArgumentError.new("#{item_to_make} is not a valid input")
end
# end
# 1. Hash#include?(item_to_make)
# Hash[key] => value
# library["Banana"] => nil
# if error_counter == 0...
# Even if we dont understand how this is working.
# The purpose is to raise an error if item_to_make is not in the library.
# if error_counter > 0
# raise ArgumentError.new("#{item_to_make} is not a valid input")
# end
# serving_size is actually the ingredients_needed_for_item_to_make.
# ingredients_needed
# ingredients_needed = available_foods.values_at(item_to_make)[0]
# 2. IS there a simple way, to return to value, for a key in a hash.
ingredients_needed = available_foods[item_to_make]
# Array[index] => element
# Hash[key] => value
# ingredients_needed = available_foods[item_to_make]
# Where have we seen [0] before...
# - Calling an index on an array.
# So we can assume that values_at returns an array.
# values_at returns an array or all values that macth the key, item_to_make.
# HOWEVER, becuase a hash cannot have duplicates keys, we will ALWAYS have a single element array.
# library.values_at("cake")
# => [5]
# [5][0]
# => 5
# So essentially this is converting the single element array into an integer.
leftover_ingredients = available_ingredients % ingredients_needed
# leftover_ingredients = available_ingredients % ingredients_needed
# aka the remainder.
# Why are they calling leftover ingredits.
# leftover_ingredients = order_quantity % serving_size
# leftover_ingredients = available_ingredients % serving_size
case leftover_ingredients # remainder
when 0
# When there is no remainder, do this...
return "Calculations complete: Make #{available_ingredients/ingredients_needed} of #{item_to_make}"
else
# If there is a remainder, do this...
# ingredients != items
return "Calculations complete: Make #{available_ingredients/ingredients_needed} of #{item_to_make}, you have #{leftover_ingredients} leftover items."
end
end
p serving_size_calc("pie", 7)
p serving_size_calc("pie", 8)
p serving_size_calc("cake", 5)
p serving_size_calc("cake", 7)
p serving_size_calc("cookie", 1)
p serving_size_calc("cookie", 10)
# p serving_size_calc("THIS IS AN ERROR", 5)
=begin
# Reflection
- What did you learn about making code readable by working on this challenge?
I learned that it's incredibly important to choose variable names that accurately refer to the function of the variable. Virtually none of the variables in this code did what
their names implied, and that made understanding the code incredibly frustrating.
- Did you learn any new methods? What did you learn about them?
I was reminded about the Hash#include? method. It's a much more efficient way to determine whether or not an input value is a key in a hash.
- What did you learn about accessing data in hashes?
I learned that accessing data in a hash via key generally makes more sense than converting the hash to an array (by calling the values_at method, for example) and accessing
the array. In other words, the direct method is more efficient than the more indirect method.
- What concepts were solidified when working through this challenge?
What really stood out to me was the importance of writing good variable names. This challenge also highlighted the importance of keeping the code as parsimonious as possible.
=end |
module GoogleApiHelper
@@GOOGLE_API_KEY = 'AIzaSyAi-E59X3_vswQ9fwc5xhxoZhPTYe_kARs'
@@BASE_URI = 'https://maps.googleapis.com/maps/api'
@@chunk_size = 30
def build_url(api, format)
"#{@@BASE_URI}/#{api}/#{format}"
end
def call_api(api, format, params)
url = build_url(api, format)
params = params.merge({key: @@GOOGLE_API_KEY})
return JSON.parse(RestClient.get(url, params: params))
end
def get_lat_long(address)
response = call_api('geocode', 'json', {address: address})
if response["results"] and response["results"][0]
return response["results"][0]["geometry"]["location"]
end
end
def destinations_dist_from_source(source, destinations)
responses = []
for chunk in destinations.each_slice(@@chunk_size) do
destinations = chunk.join("|")
responses.append(call_api('distancematrix', 'json', {origins: source, destinations: destinations}))
end
responses
end
#Source: String
#Destinations: Listing Array
#Max_Dist: Integer
#Max_Time: Integer
def filter_listings_by_dist_from_source(source, listings, max_dist, max_time)
listing_addresses = listings.collect {|listing| listing.address.to_s}
responses = destinations_dist_from_source(source, listing_addresses)
filtered_listings = []
for response in responses do
if (response["status"] == "OK")
response["rows"][0]["elements"].each_with_index do |result, index|
if (result["distance"]["value"] <= max_dist and result["duration"]["value"] <= max_time)
filtered_listings.append(listings[index])
end
end
end
end
return filtered_listings
end
end
|
require_relative './base'
# rubocop:disable Naming/UncommunicativeMethodParamName
class Pltt::Actions::List < Pltt::Actions::Base
def run(my: false, label: nil)
require 'terminal-table'
table = Terminal::Table.new
gitlab_api.issues(scope: my ? 'assigned-to-me' : 'all', label: label).each do |issue|
table.add_row [
issue.iid.to_s.magenta,
issue.title.green + "\n#{issue.web_url.dark_gray}",
issue.state.gray,
issue.milestone&.title,
issue.labels.map { |i| "[~#{i}]" }.join
]
end
puts table
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :message do
content { Faker::Lorem.paragraph(5) }
service
status
end
end
|
# frozen_string_literal: true
def template(src_file, dist_file)
if src_file_path = template_file(src_file)
src_file_string = StringIO.new(ERB.new(File.read(src_file_path)).result(binding))
random_string = SecureRandom.hex
upload! src_file_string, "/tmp/#{random_string}"
execute :sudo, "mv /tmp/#{random_string} #{dist_file}"
execute :sudo, "rm -f /tmp/#{random_string}"
info "copying: #{src_file_path} to: #{dist_file}"
else
error "error: can't be moved"
end
end
def template_file(name)
if File.exist?((file = "lib/templates/#{name}"))
file
end
end
|
module Solid
class << self
def extend_liquid!
LiquidExtensions.load!
end
end
module LiquidExtensions
module ClassHighjacker
def load!
original_class = Liquid.send(:remove_const, demodulized_name)
original_classes[demodulized_name] = original_class unless original_classes.has_key?(demodulized_name) # avoid loosing reference to original class
Liquid.const_set(demodulized_name, self)
end
def unload!
if original_class = original_classes[demodulized_name]
Liquid.send(:remove_const, demodulized_name)
Liquid.const_set(demodulized_name, original_class)
end
end
def demodulized_name
@demodulized_name ||= self.name.split('::').last
end
protected
def original_classes
@@original_classes ||= {}
end
end
module TagHighjacker
def load!
original_tag = Liquid::Template.tags[tag_name.to_s]
original_tags[tag_name] = original_tag unless original_tags.has_key?(tag_name) # avoid loosing reference to original class
Liquid::Template.register_tag(tag_name, self)
end
def unload!
Liquid::Template.register_tag(tag_name, original_tags[tag_name])
end
def tag_name(name=nil)
@tag_name = name unless name.nil?
@tag_name
end
protected
def original_tags
@@original_tags ||= {}
end
end
BASE_PATH = File.join(File.expand_path(File.dirname(__FILE__)), 'liquid_extensions')
%w(if_tag unless_tag for_tag assign_tag variable).each do |mod|
require File.join(BASE_PATH, mod)
end
ALL = [IfTag, UnlessTag, ForTag, AssignTag, Variable]
class << self
def load!
ALL.each(&:load!)
end
def unload!
ALL.each(&:unload!)
end
end
end
end
|
class FirestopSurveyJob < ActiveRecord::Base
class << self
def reporter_class
FirestopSurveyReporter
end
def projectcompletion_reporter_class
FirestopSurveyProjectCompletionReporter
end
end
end
|
module ActiveRecord
class LostConnection < WrappedDatabaseException
end
module ConnectionAdapters
module Sqlserver
module Errors
LOST_CONNECTION_EXCEPTIONS = {
:odbc => ['ODBC::Error','ODBC_UTF8::Error','ODBC_NONE::Error'],
:adonet => ['TypeError','System::Data::SqlClient::SqlException']
}.freeze
LOST_CONNECTION_MESSAGES = {
:odbc => [/link failure/, /server failed/, /connection was already closed/, /invalid handle/i],
:adonet => [/current state is closed/, /network-related/]
}.freeze
def lost_connection_exceptions
exceptions = LOST_CONNECTION_EXCEPTIONS[connection_mode]
@lost_connection_exceptions ||= exceptions ? exceptions.map{ |e| e.constantize rescue nil }.compact : []
end
def lost_connection_messages
LOST_CONNECTION_MESSAGES[connection_mode]
end
end
end
end
end
|
require 'json_structure/type'
require 'json_structure/object'
require 'json_structure/array'
require 'json_structure/number'
require 'json_structure/string'
require 'json_structure/null'
require 'json_structure/any_of'
require 'json_structure/value'
require 'json_structure/any'
require 'json_structure/boolean'
require 'json_structure/version'
module JsonStructure
def self.build(&block)
Builder.new.instance_eval(&block)
end
class Builder
%w[
Type
Object_
Array
Number
Integer
String
Null
AnyOf
Value
Any
Boolean
].each do |name|
klass = JsonStructure.const_get(name)
method = name
.gsub(/([a-z])([A-Z])/, '\1_\2')
.gsub(/_+$/, '')
.downcase
define_method(method) do |*args|
klass.new(*args)
end
end
end
end
|
class AddRestaurantContact < ActiveRecord::Migration
def change
add_column :restaurants, :contact, :string
end
end
|
class ListNode
attr_accessor :value, :next
def initialize(value = nil)
@value = value
@next = nil
end
end
class LinkedList
def initialize(value)
@head = ListNode.new(value)
end
def search(value)
p1 = @head
while p1
return p1 if p1.value == value
p1 = p1.next
end
nil
end
def insert(node, new_node)
new_node.next = node.next
node.next = new_node
end
# Assumes node is not a tail
def delete_after(node)
node.next = node.next.next
end
end
|
require 'httparty'
class NewYorkTimes
include HTTParty
base_uri 'http://api.nytimes.com/svc'
SECTIONS = %w(science sports)
def most_popular(options = {})
section = options[:section]
type = options[:type] || 'mostviewed'
page = options[:page] || 1
self.class.get("http://api.nytimes.com/svc/mostpopular/v2/#{type}/#{options[:section]}/#{page}.json?api-key=sample-key") ['results']
end
def most_popular_all_sections(options = {})
results = []
SECTIONS.each do |section|
results.concat(most_popular({section: section}.merge(options)))
end
results
end
end
|
class RegistrationForm < ActiveRecord::Base
belongs_to :camp
has_many :camp_registrations
end
|
require 'spec_helper'
RSpec.describe ActionComponent::Constraints do
class ConstraintsTest
include ActionComponent::Constraints
required :apple, :banana, carrot: String
optional durian: Hash
def check(opts)
check_constraints!(opts)
end
end
subject { ConstraintsTest.new }
it "passes if all required attributes are supplied" do
subject.check(apple: 1, banana: 2, carrot: "hello", other: "ignored")
end
it "requires required attributes" do
expect { subject.check(apple: 1) }.to raise_error(ActionComponent::ConstraintError, "banana is required for component ConstraintsTest")
expect { subject.check(apple: 1, banana: 1) }.to raise_error(ActionComponent::ConstraintError, "carrot is required for component ConstraintsTest")
end
it "enforces type for required attributes" do
expect { subject.check(apple: 1, banana: 1, carrot: 1) }.to raise_error(ActionComponent::ConstraintError, "carrot must be a String")
end
it "enforces type for optional attributes" do
expect { subject.check(apple: 1, banana: 1, carrot: "hello", durian: 1) }.to raise_error(ActionComponent::ConstraintError, "durian must be a Hash")
end
end
|
# == Schema Information
#
# Table name: subscriptions
#
# id :integer not null, primary key
# user_id :integer not null
# podcast_id :integer not null
# score :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Subscription < ActiveRecord::Base
attr_accessible :user_id, :podcast_id, :score
validates :user_id, :podcast_id, presence: true
validates :user_id, uniqueness: { scope: :podcast_id }
belongs_to :user
belongs_to :podcast
scope :actives, joins(:podcast).where(podcasts: {active: true}).includes(:podcast)
end
|
template do
AWSTemplateFormatVersion "2010-09-09"
Description (<<-EOS).undent
Kumogata Sample Template
You can use Here document!
EOS
Parameters do
PolicyName do
Description "input your policyname"
Type "String"
end
end
Resources do
myRole do
Type "AWS::IAM::Role"
Properties do
AssumeRolePolicyDocument do
Version "2012-10-17"
Statement [
_{
Effect "Allow"
Principal do
Service ["ec2.amazonaws.com"]
end
Action ["sts:AssumeRole"]
}
]
end
Path "/"
end
end
myInstanceProfile do
Type "AWS::IAM::InstanceProfile"
Properties do
Path "/"
Roles [_{Ref "myRole"}]
end
end
myPolicy do
Type "AWS::IAM::Policy"
Properties do
Roles [ _{ Ref "myRole" }]
PolicyName {Ref "PolicyName" }
PolicyDocument do
Version "2012-10-17"
Statement [
_{
Effect "Allow"
Action "sts:AssumeRole"
Resource "arn:aws:iam::076059259205:role/cross_acount_access"
}
]
end
end
end
end
end
|
require 'date'
# 指定年月の第〇番目の〇曜日の日付を返す。該当する日付が存在しないときはfalseを返す
# @param int year 年を指定
# @param int month 月を指定
# @param int week 週番号(第〇週目)を指定
# @param int weekday 曜日0(日曜)から6(土曜)の数値を指定
# @return int result_day | false
def get_nth_week_day(year, month, week, weekday)
# 週の指定が正しいか判定
if week < 1 || week > 5
return false
end
# 曜日の指定が正しいか判定
if weekday < 0 || weekday > 6
return false
end
# 指定した年月の月初日(1日)の曜日を取得する
t = Time.local(year, month, 1, 0, 0, 0, 0)
# 曜日番号。0(日曜日) 〜 6(土曜日)
weekday_of_first = t.wday
# 月初日の曜日を基にして第1〇曜日の日付を求める
first_day = weekday - weekday_of_first + 1
if first_day <= 0
first_day += 7
end
# 第1〇曜日に7の倍数を加算して、結果の日付を求める
result_day = first_day + 7 * (week - 1)
# 計算結果が妥当な日付かどうかチェックする
if date_valid?(year, month, result_day)
result_day
else
false
end
end
# 日付のvalidationを行う関数
# see(https://masaki0303.hatenadiary.org/entry/20110606)
def date_valid?(y, m, d)
if Date.valid_date?(y, m, d)
true
else
false
end
end
# 今日の日付を取得する
now = Time.new
year = now.year
month = now.month
# 第1月曜日の日付を取得する
first_monday = get_nth_week_day(year, month, 1, 1);
t = Time.local(year, month, first_monday, 0, 0, 0, 0)
str = t.strftime("%Y年%m月%d日(月)")
puts str
# 第1火曜日の日付を取得する
first_tuesday = get_nth_week_day(year, month, 1, 2);
t = Time.local(year, month, first_tuesday, 0, 0, 0, 0)
str = t.strftime("%Y年%m月%d日(火)")
puts str
|
# frozen_string_literal: true
module SC::Billing::Stripe::Webhooks::Products
class CreateOperation < ::SC::Billing::Stripe::Webhooks::BaseOperation
set_event_type 'product.created'
def call(event)
product_data = fetch_data(event)
return if product_exists?(product_data)
::SC::Billing::Stripe::Product.create(
stripe_id: product_data.id,
name: product_data.name
)
end
private
def product_exists?(product_data)
!::SC::Billing::Stripe::Product.where(stripe_id: product_data.id).empty?
end
end
end
|
require 'spec_helper'
describe Rectangle do
after(:each) do
Rectangle.count = 0
end
let(:rectangle) { Rectangle.new(4,5) }
it "returns a length and width upon initialization" do
expect(rectangle.length).to eq(4)
expect(rectangle.width).to eq(5)
end
describe "#area" do
it "returns the area" do
expect(rectangle.area).to eq(20)
end
end
describe "#perimeter" do
it "returns the perimeter" do
expect(rectangle.perimeter).to eq(18)
end
end
describe "#self.count" do
it "counts the number of objects created" do
rectangle
expect(Rectangle.count).to eq(1)
Rectangle.new(5,6)
expect(Rectangle.count).to eq(2)
end
end
describe "#self.count=" do
it "sets the number of objects create" do
Rectangle.count = 55
expect(Rectangle.count).to eq(55)
end
end
end |
class Admissions::BlogPostsController < Admissions::AdmissionsController
before_filter :set_post, only: [:edit, :update, :confirm_destroy, :destroy]
load_resource find_by: :permalink
authorize_resource
def index
# authorize! :index, @posts
# @posts = BlogPost.roots.super_skinny.ordered
if params[:keyword_search] && !params[:keyword_search].blank?
@keyword_str = params[:keyword_search]
keywords = params[:keyword_search].strip.split
if keywords.size != 1
@posts = Array.new
keywords.each_with_index do |keyword,index|
@posts << BlogPost.where(["title like ? or tagline like ? or body like ? or meta_title like ? or meta_keywords like ? or meta_description like ?", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%"]).order("created_at DESC")
end
else
@keyword = params[:keyword_search].downcase
@posts = BlogPost.where(["permalink like ? or tagline like ? or body like ? or meta_title like ? or meta_keywords like ? or meta_description like ?", "%#{@keyword}%", "%#{@keyword_str}%", "%#{@keyword_str}%", "%#{@keyword_str}%", "%#{@keyword_str}%", "%#{@keyword_str}%"]).order("created_at DESC").paginate(page: params[:page], per_page: @per_page || params[:per_page])
end
else
@posts = BlogPost.paginate(page: params[:page], per_page: @per_page || params[:per_page])
end
# @tag = Tag.new#so we can admin tags
order = params[:order]
dir = (params[:dir].blank? || params[:dir] == "asc") ? "asc" : "desc"
@status_id = params[:status_id]
unless @status_id.blank?
@posts = @posts.where(status_id: @status_id)
end
unless order.blank?
@posts = @posts.order("#{order} #{dir}")
else
if @posts.class.to_s == 'Array'
@posts = @posts.flatten.uniq
@posts = @posts.paginate(page: params[:page], per_page: @per_page || params[:per_page])
else
@posts = @posts.ordered
end
end
end
def show
end
def new
# authorize! :new, @blog_post
@blog_post = BlogPost.new
render :new
end
def create
# authorize! :create, @blog_post
@blog_post = BlogPost.new(params[:blog_post])
# @blog_post.build_tag_taggables
@blog_post.user = current_user
if @blog_post.save
redirect_to admin_blog_posts_path, notice: "Post Saved."
else
render :new, notice: "Sorry, something went wrong."
end
end
def edit
# authorize! :edit, @blog_post
end
def update
# authorize! :update, @blog_post
if params[:clear_image] == "true"
@blog_post.image = nil
end
if @blog_post.update_attributes(params[:blog_post])
@blog_post.clear_audiences if params[:blog_post][:audience_ids].blank?
redirect_to admin_blog_posts_path
else
flash[:error] = "Sorry, something went wrong."
render :edit
end
end
def update_order
end
def confirm_destroy
end
def destroy
# authorize! :destroy, @blog_post
@blog_post.destroy
redirect_to admin_blog_posts_path,
notice: "Successfully destroyed #{@blog_post.title}."
end
private
def set_post
@blog_post = BlogPost.find_by_permalink!(params[:id])
end
def authorize
end
end
|
MRuby::Gem::Specification.new("mruby-irb_like_debugger") do |spec|
spec.license = "MIT"
spec.authors = "Daniel Inkpen"
spec.add_dependency("mruby-sleep")
spec.add_dependency("mruby-eval")
spec.add_dependency("mruby-io")
spec.add_dependency("mruby-bin-mruby")
spec.add_dependency("mruby-kernel-ext")
spec.add_dependency("mruby-simple_tcp_client", github: "Dan2552/mruby-simple_tcp_client", branch: "main")
end
|
#require_relative './config/environment.rb'
module Paramable
def to_param
name.downcase.gsub(' ', '-')
end
end
|
# frozen_string_literal: true
class ContactMailer < ApplicationMailer
def contact(options)
@name = options[:name]
@email = options[:email]
@message = options[:message]
mail to: "contact@dolentcaramel.co"
end
end
|
module NTFS
# The _ATTRIB_TYPE enumeration.
# Every entry in the MFT is made of a list of attributes. These are the attrib types.
AT_STANDARD_INFORMATION = 0x00000010 # Base data: MAC times, version, owner, security, quota, permissions
AT_ATTRIBUTE_LIST = 0x00000020 # Used for a list of attributes that spans one MFT file record
AT_FILE_NAME = 0x00000030 # MAC times, size, flags, (and of course) file name
AT_VOLUME_VERSION = 0x00000040 # No information
AT_OBJECT_ID = 0x00000040 # Object GUID, birth GUIDs & domain GUID
AT_SECURITY_DESCRIPTOR = 0x00000050 # User & Group SIDs, system and descr ACLs
AT_VOLUME_NAME = 0x00000060 # Vol name (label)
AT_VOLUME_INFORMATION = 0x00000070 # Major, minor & flags (chkdsk & others)
AT_DATA = 0x00000080 # File data, aux stream data
AT_INDEX_ROOT = 0x00000090 # Root of an index - usually root of directory
AT_INDEX_ALLOCATION = 0x000000a0 # Larger index structures use index allocation for overflow
AT_BITMAP = 0x000000b0 # Cluster allocation bitmap
AT_SYMBOLIC_LINK = 0x000000c0 # Haven't seen it yet
AT_REPARSE_POINT = 0x000000c0 # Reparse data
AT_EA_INFORMATION = 0x000000d0 # Extended attribute information
AT_EA = 0x000000e0 # Extended attribute data
AT_PROPERTY_SET = 0x000000f0 # Haven't seen it
AT_LOGGED_UTILITY_STREAM = 0x00000100 # Encrypted File System data
AT_END = 0xffffffff # End of attributes
# OBSOLETE TYPES
# AT_VOLUME_VERSION and AT_SYMBOLIC_LINK have been depreciated, but remain in the type constants for
# backward compatibility. The name hash can't contain them since the type is used as a key.
# NT names for the attributes.
TypeName = {
AT_STANDARD_INFORMATION => '$STANDARD_INFORMATION',
AT_ATTRIBUTE_LIST => '$ATTRIBUTE_LIST',
AT_FILE_NAME => '$FILE_NAME',
# AT_VOLUME_VERSION => '$VOLUME_VERSION', # This type is depreciated.
AT_OBJECT_ID => '$OBJECT_ID',
AT_SECURITY_DESCRIPTOR => '$SECURITY_DESCRIPTOR',
AT_VOLUME_NAME => '$VOLUME_NAME',
AT_VOLUME_INFORMATION => '$VOLUME_INFORMATION',
AT_DATA => '$DATA',
AT_INDEX_ROOT => '$INDEX_ROOT',
AT_INDEX_ALLOCATION => '$INDEX_ALLOCATION',
AT_BITMAP => '$BITMAP',
# AT_SYMBOLIC_LINK => '$SYMBOLIC_LINK', # This type is depreciated.
AT_REPARSE_POINT => '$REPARSE_POINT',
AT_EA_INFORMATION => '$EA_INFORMATION',
AT_EA => '$EA',
AT_PROPERTY_SET => '$PROPERTY_SET',
AT_LOGGED_UTILITY_STREAM => '$LOGGED_UTILITY_STREAM'
}
end # module NTFS
|
#===============================================================================
# Personalizzazione controller di Holy87
# Difficoltà utente: ★
# Versione 1.1
# Licenza: CC. Chiunque può scaricare, modificare, distribuire e utilizzare
# lo script nei propri progetti, sia amatoriali che commerciali. Vietata
# l'attribuzione impropria.
#
# Changleog
# 1.2 => Aggiunta la visualizzazione dello stato della batteria
# 1.1 => Possibilità di inserire pulsanti del pad riservati (che non possono
# essere assegnati)
#===============================================================================
# Questo script vi permette di utilizzare aggiungere nelle opzioni di gioco due
# nuovi comandi che permetteranno al giocatore di configurare a piacimento i
# tasti del proprio controller e la potenza della vibrazione.
#===============================================================================
# Istruzioni: inserire lo script sotto Materials, prima del Main e sotto gli
# script XInput e Opzioni di gioco. I due script sono necessari per il corretto
# funzionamento, altrimenti va in crash all'avvio.
# Sotto è possibile configurare i testi per le voci e i comandi personalizzabili.
#===============================================================================
#===============================================================================
# ** Impostazioni dello script
#===============================================================================
module ControllerSettings
#--------------------------------------------------------------------------
# * Testi per il menu Opzioni
#--------------------------------------------------------------------------
CONTROLLER_COMMAND = 'Configura Game Pad'
CONTROLLER_HELP = 'Imposta i comandi del controller PC'
BATTERY_COMMAND = 'Stato della batteria'
BATTERY_HELP = 'Visualizza lo stato della batteria del controller.'
BATTERY_HIGH = 'Carica'
BATTERY_OK = 'Buona'
BATTERY_LOW = 'Bassa'
BATTERY_CRITICAL = 'Scarica'
BATTERY_NO_STATE = 'Non rilevata'
BATTERY_DISCONNECTED = 'Disconnesso'
VIBRATION_COMMAND = 'Vibrazione'
VIBRATION_HELP = 'Imposta la potenza della vibrazione del controller'
RESET_COMMAND = 'Ripristina comandi'
NO_KEY_SET = 'Nessun pulsante assegnato'
HELP_INPUT = 'Premi un tasto sul pad per assegnarlo'
HELP_KEY = 'Puoi cambiare i tasti del controller.
Seleziona Ripristina o premi CTRL per resettare.'
# Mostrare lo stato della batteria nel menu?
SHOW_BATTERY_INFO = true
# Scegli le icone per lo stato della batteria. Se non le inserisci, non
# verranno mostrate.
# -2: Non collegato
# -1: Batteria non rilevata
# 0,1,2,3: Batteria da scarica a carica
BATTERY_INFO_ICONS = {-1 => 534, 0 => 535, 1 => 536, 2 => 550, 3 => 551}
#--------------------------------------------------------------------------
# * Tasti configurabili nella schermata.
#--------------------------------------------------------------------------
INPUTS = [:UP, :DOWN, :LEFT, :RIGHT, :C, :B, :A, :L, :R, :START]
#--------------------------------------------------------------------------
# * Tasti da escludere nella selezione
#--------------------------------------------------------------------------
EXCLUDED = [:L_AXIS_X, :L_AXIS_Y, :R_AXIS_X, :R_AXIS_Y]
#--------------------------------------------------------------------------
# * Pulsanti del pad che non possono essere utilizzati perché riservati
#--------------------------------------------------------------------------
RESERVED = [:START]
#--------------------------------------------------------------------------
# * Descrizione dei comandi
#--------------------------------------------------------------------------
INPUT_DESCRIPTION = {
:UP => 'Su',
:DOWN => 'Giù',
:LEFT => 'Sinistra',
:RIGHT => 'Destra',
:C => 'Accetta/Interagisci',
:B => 'Menu/Indietro',
:A => 'Corri',
:L => 'Precedente',
:R => 'Successivo',
:START => 'Pausa'
}
end
#===============================================================================
# ** ATTENZIONE: NON MODIFICARE SOTTO QUESTO SCRIPT SE NON SAI COSA TOCCARE! **
#===============================================================================
$imported = {} if $imported == nil
$imported['H87-PadSettings'] = 1.0
#===============================================================================
# ** ControllerSettings
#-------------------------------------------------------------------------------
# Some core methods
#===============================================================================
module ControllerSettings
#--------------------------------------------------------------------------
# * Key scene command creation
#--------------------------------------------------------------------------
def self.create_keys_command
command = {:type => :advanced, :method => :call_keys,
:text => CONTROLLER_COMMAND, :help => CONTROLLER_HELP,
:condition => 'Input.controller_connected?'}
command
end
#--------------------------------------------------------------------------
# * Vibration command creation
#--------------------------------------------------------------------------
def self.create_vibration_command
command = {:type => :bar, :method => :update_vibration,
:text => VIBRATION_COMMAND, :help => VIBRATION_HELP,
:condition => 'Input.controller_connected?',
:var => 0, :max => 100, :val_mt => :get_vibration,
:distance => 10, :default => 100}
command
end
def self.create_battery_command
command = {:type => :advanced, :text => BATTERY_COMMAND,
:help => BATTERY_HELP, :condition => 'false',
:val_mt => :get_battery_state}
command
end
#--------------------------------------------------------------------------
# * Excluded keys from the configuration
#--------------------------------------------------------------------------
def self.excluded_commands; EXCLUDED; end
end
#--------------------------------------------------------------------------
# * Insert to Options list
#--------------------------------------------------------------------------
H87Options.push_keys_option(ControllerSettings.create_keys_command)
H87Options.push_keys_option(ControllerSettings.create_vibration_command)
if ControllerSettings::SHOW_BATTERY_INFO
H87Options.push_keys_option(ControllerSettings.create_battery_command)
end
#===============================================================================
# ** Vocab
#-------------------------------------------------------------------------------
# Scome vocabs
#===============================================================================
module Vocab
#--------------------------------------------------------------------------
# * Command Input friendly name
#--------------------------------------------------------------------------
def self.command_name(input)
ControllerSettings::INPUT_DESCRIPTION[input]
end
#--------------------------------------------------------------------------
# * Help text to input
#--------------------------------------------------------------------------
def self.input_window_text
ControllerSettings::HELP_INPUT
end
#--------------------------------------------------------------------------
# * Help text to key config
#--------------------------------------------------------------------------
def self.key_config_help
ControllerSettings::HELP_KEY
end
end
#===============================================================================
# ** Option
#-------------------------------------------------------------------------------
# Custom game pad methods
#===============================================================================
class Option
#--------------------------------------------------------------------------
# * Calls the key configuration scene
#--------------------------------------------------------------------------
def call_keys
Sound.play_ok
SceneManager.call(Scene_KeyConfig)
end
#--------------------------------------------------------------------------
# * Updates the user vibration (and vibrate)
#--------------------------------------------------------------------------
def update_vibration(value)
$game_system.set_vibration_rate(value)
Input.vibrate(100, 100, 20) if SceneManager.scene_is?(Scene_Options)
end
#--------------------------------------------------------------------------
# * Gets the user configured vibration
#--------------------------------------------------------------------------
def get_vibration
$game_system.vibration_rate
end
#--------------------------------------------------------------------------
# * Gets the current battery state
#--------------------------------------------------------------------------
def get_battery_state
Input.battery_level
end
end
#===============================================================================
# ** Scene_Options
#-------------------------------------------------------------------------------
# Controller check process
#===============================================================================
class Scene_Options < Scene_MenuBase
alias h87contr_settings_update update unless $@
alias h87contr_settings_start start unless $@
#--------------------------------------------------------------------------
# * Start
#--------------------------------------------------------------------------
def start
h87contr_settings_start
@connected = Input.controller_connected?
end
#--------------------------------------------------------------------------
# * Update process
#--------------------------------------------------------------------------
def update
h87contr_settings_update
update_controller_connection
end
#--------------------------------------------------------------------------
# * Checks if the controller is connected/disconnected during this
# scene, and refresh the window
#--------------------------------------------------------------------------
def update_controller_connection
if @connected != Input.controller_connected?
@connected = Input.controller_connected?
@old_battery_state = Input.battery_level
@option_window.refresh
end
if Input.battery_level != @old_battery_state
@option_window.refresh
@old_battery_state = Input.battery_level
end
end
end
#===============================================================================
# ** Scene_KeyConfig
#-------------------------------------------------------------------------------
# Keys configuration scene
#===============================================================================
class Scene_KeyConfig < Scene_MenuBase
#--------------------------------------------------------------------------
# * Start
#--------------------------------------------------------------------------
def start
super
create_help_window
create_keys_window
create_input_window
end
#--------------------------------------------------------------------------
# * Help window creation
#--------------------------------------------------------------------------
def create_help_window
super
@help_window.set_text(Vocab.key_config_help)
end
#--------------------------------------------------------------------------
# * Keys list window creation
#--------------------------------------------------------------------------
def create_keys_window
y = @help_window.height
@keys_window = Window_PadKeys.new(0, y, Graphics.width, Graphics.height - y)
@keys_window.set_handler(:ok, method(:check_command))
@keys_window.set_handler(:cancel, method(:return_scene))
@keys_window.set_handler(:reset, method(:reset_keys))
@keys_window.activate
@keys_window.index = 0
end
#--------------------------------------------------------------------------
# * Input window creation
#--------------------------------------------------------------------------
def create_input_window
@input_window = Window_Input_Key.new(method(:check_selected_key))
end
#--------------------------------------------------------------------------
# * Checks the selected command
#--------------------------------------------------------------------------
def check_command
if @keys_window.item == :reset
reset_keys
else
open_input_window
end
end
#--------------------------------------------------------------------------
# * Reset all custom keymap
#--------------------------------------------------------------------------
def reset_keys
$game_system.create_default_key_set
@keys_window.refresh
@keys_window.activate
end
#--------------------------------------------------------------------------
# * Opens the key input window
#--------------------------------------------------------------------------
def open_input_window
@input_window.open
end
#--------------------------------------------------------------------------
# * Checks what the user chosen. If the controller is accidentally
# disconnected, returns to the previous scene.
#--------------------------------------------------------------------------
def check_selected_key
key = @input_window.selected_key
if key == 0
return_scene
else
$game_system.xinput_key_set[@keys_window.item] = key
@keys_window.refresh
@keys_window.activate
end
end
end
#===============================================================================
# ** Window_PadKeys
#-------------------------------------------------------------------------------
# This window contains the editable commands
#===============================================================================
class Window_PadKeys < Window_Selectable
#--------------------------------------------------------------------------
# * Object initialization
#--------------------------------------------------------------------------
def initialize(x, y, width, height)
super
@data = ControllerSettings::INPUTS + [:reset]
refresh
end
#--------------------------------------------------------------------------
# * Item max
#--------------------------------------------------------------------------
def item_max; @data ? @data.size : 0; end
#--------------------------------------------------------------------------
# * Item (as Symbol)
#--------------------------------------------------------------------------
def item; @data[index]; end
#--------------------------------------------------------------------------
# * Draw item
#--------------------------------------------------------------------------
def draw_item(index)
key = @data[index]
if key
if key != :reset
draw_key_command(key, index)
else
draw_reset_command(index)
end
end
end
#--------------------------------------------------------------------------
# * Draws a command with friendly name and controller input
#--------------------------------------------------------------------------
def draw_key_command(key, index)
rect = item_rect_for_text(index)
change_color(normal_color)
draw_text(rect.x, rect.y, rect.width/2, line_height, Vocab.command_name(key))
if $game_system.xinput_key_set[key]
change_color(crisis_color)
draw_text(rect.width/2, rect.y, rect.width/2, line_height, Vocab.gamepad_key($game_system.xinput_key_set[key]), 1)
else
change_color(knockout_color)
draw_text(rect.width/2, rect.y, rect.width/2, line_height, ControllerSettings::NO_KEY_SET, 1)
end
end
#--------------------------------------------------------------------------
# * Draws the reset command
#--------------------------------------------------------------------------
def draw_reset_command(index)
rect = item_rect_for_text(index)
change_color(normal_color)
draw_text(rect, ControllerSettings::RESET_COMMAND, 1)
end
#--------------------------------------------------------------------------
# * Handling Processing for OK and Cancel Etc.
#--------------------------------------------------------------------------
def process_handling
return unless open? && active
process_reset if handle?(:reset) && Input.trigger?(:CTRL)
super
end
#--------------------------------------------------------------------------
# * CTRL key called
#--------------------------------------------------------------------------
def process_reset
call_reset_handler
end
#--------------------------------------------------------------------------
# * Calls the reset process
#--------------------------------------------------------------------------
def call_reset_handler
call_handler(:reset)
end
end
#===============================================================================
# ** Window_Input_Key
#-------------------------------------------------------------------------------
# This window awaits the user input with the game pad
#===============================================================================
class Window_Input_Key < Window_Base
attr_reader :selected_key
#--------------------------------------------------------------------------
# * Object initialization
# @param [Method] method
#--------------------------------------------------------------------------
def initialize(method)
width = calc_width
height = fitting_height(2)
@closing_method = method
@selected_key = nil
@esc_counter = 0
super(0, 0, width, height)
center_window
self.openness = 0
refresh
end
#--------------------------------------------------------------------------
# * Refreshj
#--------------------------------------------------------------------------
def refresh
contents.clear
draw_text(0, 0, contents_width, contents_height, Vocab.input_window_text, 1)
end
#--------------------------------------------------------------------------
# * Window opening with input check
#--------------------------------------------------------------------------
def open
@old_packet = XInput.get_state.packet_number
super
end
#--------------------------------------------------------------------------
# * Update process with key scanning
#--------------------------------------------------------------------------
def update
super
check_key_delete
check_forced_close
update_key_scan
end
#--------------------------------------------------------------------------
# * Detects the first user input. If the controller is disconnected,
# closes the window.
#--------------------------------------------------------------------------
def update_key_scan
return unless open?
return if @closing
unless Input.controller_connected?
@selected_key = 0
close
return
end
keymap = XInput.get_key_state.keys - ControllerSettings.excluded_commands
key_selection(keymap)
end
#--------------------------------------------------------------------------
# * Key selection process
# @param [Array] keymap
#--------------------------------------------------------------------------
def key_selection(keymap)
if keymap.any? && XInput.get_state.packet_number != @old_packet
if ControllerSettings::RESERVED.include?(keymap.first)
selection_fail
else
selection_ok(keymap.first)
end
end
end
#--------------------------------------------------------------------------
# * Command selection success
#--------------------------------------------------------------------------
def selection_ok(key)
@selected_key = key
Sound.play_ok
close
end
#--------------------------------------------------------------------------
# * Command selection failed
#--------------------------------------------------------------------------
def selection_fail
Sound.play_buzzer
end
#--------------------------------------------------------------------------
# * Closes the window for ESC key (on keyboard)
#--------------------------------------------------------------------------
def check_forced_close
return if @esc_counter > 0 or !open?
if Input.legacy_trigger?(:B)
Sound.play_cancel
close
end
end
#--------------------------------------------------------------------------
# * Deletes the current key assignation
#--------------------------------------------------------------------------
def check_key_delete
return unless open?
return if @closing
if Input.legacy_press?(:B)
@esc_counter += 1
if @esc_counter >= 50
@esc_counter = 0
selection_ok(nil)
end
else
@esc_counter = 0
end
end
#--------------------------------------------------------------------------
# * Centra la finestra nel campo
#--------------------------------------------------------------------------
def center_window
self.x = (Graphics.width - self.width)/2
self.y = (Graphics.height - self.height)/2
end
#--------------------------------------------------------------------------
# * Closes the window calling the refresh method
#--------------------------------------------------------------------------
def close
super
@closing_method.call
end
#--------------------------------------------------------------------------
# * Gets the window width
#--------------------------------------------------------------------------
def calc_width; Graphics.width; end
end
#===============================================================================
# ** Window_GameOptions
#===============================================================================
class Window_GameOptions < Window_Selectable
alias bt_draw_advanced draw_advanced unless $@
#--------------------------------------------------------------------------
# *
# @param [Rect] rect
# @param [Option] item
#--------------------------------------------------------------------------
def draw_advanced(rect, item)
if item.value_method == :get_battery_state
draw_battery_info(rect, item)
else
bt_draw_advanced(rect, item)
end
end
#--------------------------------------------------------------------------
# * disegna le informazioni sullo stato della batteria
# @param [Rect] rect
# @param [Option] item
#--------------------------------------------------------------------------
def draw_battery_info(rect, item)
icons = ControllerSettings::BATTERY_INFO_ICONS
icon = icons[item.value] || 0
case item.value
when -2
text = ControllerSettings::BATTERY_DISCONNECTED
color = normal_color
when -1
text = ControllerSettings::BATTERY_NO_STATE
color = normal_color
when 0
text = ControllerSettings::BATTERY_CRITICAL
color = knockout_color
when 1
text = ControllerSettings::BATTERY_LOW
color = crisis_color
when 2
text = ControllerSettings::BATTERY_OK
color = normal_color
when 3
text = ControllerSettings::BATTERY_HIGH
color = power_up_color
else
text = sprintf('Not found value %d', Input.battery_level)
color = normal_color
end
x = get_state_x(rect)
width = rect.width / 2
draw_icon(icon, x, rect.y)
change_color(color, Input.controller_connected?)
draw_text(x, rect.y, width, line_height, text, 1)
end
end |
require 'rubygems'
require 'bundler'
require 'fakeweb'
require File.dirname(__FILE__) + '/../lib/launchrock.rb'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'minitest/autorun'
require 'mocha/setup'
FakeWeb.allow_net_connect = false
class MiniTest::Unit::TestCase
def fakeweb_raw_post(url, resp)
FakeWeb.register_uri(:post, "#{Launchrock::Connection.base_uri}#{url}",
:body => resp.to_json,
:content_type => 'application/json')
end
def fakeweb_post(uri, resp, success=true)
fakeweb_raw_post(uri, [{:response => resp.merge(:status => (success ? 'OK' : 'FAILURE'))}])
end
end
|
module Api
module Endpoints
class Bookings < Grape::API
namespace :bookings do
desc 'Bookings by date range',
summary: 'Bookings by date range',
detail: 'Returns a list of bookings, given a date range.',
is_array: true,
success: Entities::Booking
params do
requires :from, type: Date
requires :to, type: Date
end
get do
booking_controller = BookingsController.new
bookings = booking_controller.bookings_by_dates_range(declared(params))
present :bookings, bookings, with: Entities::Booking
end
desc 'Create a Booking',
summary: 'Create a Booking',
detail: 'Create a reservation for a movie'
params do
requires :movie_id, type: Integer
requires :customer_id, type: Integer
requires :date, type: Date
end
post do
begin
BookingsController.new.create(declared(params))
rescue StandardError => e
status 400
e
end
end
end
end
end
end
|
#!/usr/bin/env ruby
VERSION='1.0.0'
$:.unshift File.expand_path('../../lib', __FILE__)
require 'hashie'
require 'devops_api'
require 'pry'
require 'awesome_print'
require 'ruby-progressbar'
class Api
include DevopsApi
end
begin
opts = Slop.parse(strict: true, help: true) do
banner "Domain Cutover List Hosted Zones, version #{VERSION}\n\nUsage: domain_import_r53 [options]"
on 'p', 'profile', '[required] The name of the AWS credential profile to use.', argument: true
on 'f', 'file', '[required] The location of the csv file to be tested.', argument: true
on 'v', 'version' do
puts 'domain cutover, version #{version}'
exit 0
end
end
opts_slop = opts
opts = Hashie::Mash.new(opts_slop.to_hash)
# Profile required test
raise 'AWS Profile name required!' unless opts.profile?
raise 'Location of config YAML [-f PATHTOYAML] required!' unless opts.file?
opts.file = File.expand_path( opts.file )
raise "Config YAML file not found at \"#{opts.file}\"." unless File.exist?( opts.file )
api = Api.new(opts.profile)
caller_reference = "domain_import_#{Time.now.strftime("%Y%m%d%H%M%S")}"
yml = YAML.load_file( opts.file )
domains = yml['domains'].map{|d| Hashie::Mash.new(d) }
puts '# Domains to import #################################################'
puts ''
puts domains.map{ |d| d.name }.join("\n")
puts ''
# this logic should be placed in a function
found_delegation_sets = api.r53.list_reusable_delegation_sets
delegation_set = found_delegation_sets.delegation_sets.empty? ? api.r53.create_reusable_delegation_set({
caller_reference: caller_reference,
hosted_zone_id: "Z1PU2N3W0LJTNW"
}) : found_delegation_sets.delegation_sets.first
puts '# Name Servers to Use ###############################################'
puts ''
ap delegation_set
puts ''
puts '# Creating Hosted Zones #############################################'
puts ''
@status = nil
domains.each do |domain|
begin
puts "Creating HZ #{domain.name}."
hosted_zone = {
name: "#{domain.name}.",
caller_reference: "#{caller_reference}.#{rand(999)}",
delegation_set_id: delegation_set.id
}
# create hosted zone
hz_resp = api.r53.create_hosted_zone(hosted_zone)
# wait for change
puts ''
@status = api.r53.get_change( { id: hz_resp.change_info.id } ).change_info.status
pb = ProgressBar.create( title: 'Create HZ Live? ', format: '%t %B', progress_mark: '✘', total: 1000 )
while @status == 'PENDING' do
pb.increment
@status = api.r53.get_change( { id: hz_resp.change_info.id } ).change_info.status
sleep 0.25
end
pb.stop
puts "Create HZ is now #{@status}."
puts ''
rescue Aws::Route53::Errors::HostedZoneAlreadyExists, Aws::Route53::Errors::ConflictingDomainExists => e
puts "!!! HZ for #{domain.name} already exsists !!!"
puts ''
rescue => e
raise e
end
hz_find_resp = api.r53.list_hosted_zones.hosted_zones.select{|hz| hz.name == "#{domain.name}." }
hz_resp = api.r53.get_hosted_zone({
id: hz_find_resp[0].id
})
puts ''
ap hz_resp
puts ''
puts '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'
puts ''
end
puts '# Cut and Paste for CSC #############################################'
puts ''
puts domains.map{ |d| d.name }.join(',')
puts ''
rescue => e
puts ''
puts e.class
puts e.message
puts e.backtrace.join("\n")
puts ''
puts opts_slop
end
|
# frozen_string_literal: true
class CopyProductPriceIntoLineItem < ActiveRecord::Migration[6.0]
def change
add_column :line_items, :price, :integer, default: 1
end
end
|
class Medication < ApplicationRecord
has_many :prescriptions
has_many :users, :through => :prescriptions
end |
class Topic < ApplicationRecord
validates :user_id, presence: true
validates :description, presence: true
validates :image, presence: true
belongs_to :user
has_many :favorites
has_many :favorite_users,through: :favorites, source: 'user'
has_many :bookmarks
has_many :bookmark_users,through: :bookmarks, source: 'user'
mount_uploader :image, ImageUploader
end
|
require 'date'
class Echo
def initialize
puts 'Say something'
end
def output
while @user_input = gets.chomp
case @user_input
when 'exit'
puts 'Goodbye'
break
else
puts "#{Date.today}" + ' | ' + "#{Time.now.strftime('%H:%M')}" + " | You said: '#{@user_input}'!"
puts 'Say something'
end
end
end
end |
# <URL:http://code.google.com/apis/chart/#chtt>
module GoogleChart
module Title
def self.included(klass)
klass.register!(:title)
end
def title=(title)
@title = CGI::escape(title)
end
def title
"chtt=#{@title}" if @title
end
end
end
|
class FieldValuesController < ApplicationController
# GET /field_values
# GET /field_values.json
def index
@field_values = FieldValue.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @field_values }
end
end
# GET /field_values/1
# GET /field_values/1.json
def show
@field_value = FieldValue.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @field_value }
end
end
# GET /field_values/new
# GET /field_values/new.json
def new
@field_value = FieldValue.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @field_value }
end
end
# GET /field_values/1/edit
def edit
@field_value = FieldValue.find(params[:id])
end
# POST /field_values
# POST /field_values.json
def create
@field_value = FieldValue.new(params[:field_value])
respond_to do |format|
if @field_value.save
format.html { redirect_to @field_value, notice: 'Field value was successfully created.' }
format.json { render json: @field_value, status: :created, location: @field_value }
else
format.html { render action: "new" }
format.json { render json: @field_value.errors, status: :unprocessable_entity }
end
end
end
# PUT /field_values/1
# PUT /field_values/1.json
def update
@field_value = FieldValue.find(params[:id])
respond_to do |format|
if @field_value.update_attributes(params[:field_value])
format.html { redirect_to @field_value, notice: 'Field value was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @field_value.errors, status: :unprocessable_entity }
end
end
end
# DELETE /field_values/1
# DELETE /field_values/1.json
def destroy
@field_value = FieldValue.find(params[:id])
@field_value.destroy
respond_to do |format|
format.html { redirect_to field_values_url }
format.json { head :no_content }
end
end
end
|
class AddActivityYearToSelfEvaluation < ActiveRecord::Migration[5.0]
def change
add_column :self_evaluations, :activity_year, :string
end
end
|
describe ManageIQ::Providers::Amazon::InstanceTypes do
context "disable instance_types via Settings" do
it "contains t2.nano without it being disabled" do
allow(Settings.ems.ems_amazon).to receive(:disabled_instance_types).and_return([])
expect(described_class.names).to include("t2.nano")
end
it "does not contain t2.nano that is disabled" do
allow(Settings.ems.ems_amazon).to receive(:disabled_instance_types).and_return(['t2.nano'])
expect(described_class.names).not_to include('t2.nano')
end
end
context "add instance_types via Settings" do
let(:additional) do
{
"makeups.xlarge" => {
:name => "makeups.xlarge",
:family => "Compute Optimized",
:description => "Cluster Compute Quadruple Extra Large",
:memory => 23.gigabytes,
:vcpu => 16,
},
"makeups.2xlarge" => {
:name => "makeups.2xlarge",
:family => "Compute Optimized",
:description => "Cluster Compute Quadruple Extra Large",
:memory => 23.gigabytes,
:vcpu => 32,
},
}
end
context "with no additional instance_types set" do
let(:settings) do
{:ems => {:ems_amazon => {:additional_instance_types => nil}}}
end
it "returns standard instance_types" do
stub_settings(settings)
expect(described_class.names).not_to include("makeups.xlarge", "makeups.2xlarge")
end
end
context "with additional" do
let(:settings) do
{:ems => {:ems_amazon => {:additional_instance_types => additional}}}
end
it "returns the custom instance_types" do
stub_settings(settings)
expect(described_class.names).to include("makeups.xlarge", "makeups.2xlarge")
end
end
context "with additional instance_types and disabled instance_types" do
let(:settings) do
{
:ems => {
:ems_amazon => {
:disabled_instance_types => ["makeups.2xlarge"],
:additional_instance_types => additional
}
}
}
end
it "disabled_instance_types overrides additional_instance_types" do
stub_settings(settings)
expect(described_class.names).to include("makeups.xlarge")
expect(described_class.names).not_to include("makeups.2xlarge")
end
end
end
end
|
module ActiveRecordFiles::Persistence
attr_reader :id
def new_record?
!id
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'validations' do
it { is_expected.to validate_presence_of(:email) }
it { is_expected.to validate_uniqueness_of(:email) }
end
describe '#with_whitelist_domain_email' do
let(:response) { User.with_whitelist_domain_email(email) }
context 'with invalid domain' do
let(:email) { "user@other#{ENV['email_domain']}" }
it 'returns nil' do
expect(response).to eq nil
end
end
context 'with valid domain' do
let(:email) { "#{Faker::Internet.user_name}@#{ENV['email_domain']}" }
context 'with existing user' do
let!(:user) { create(:user, email: email) }
it 'returns existing user' do
expect {
expect(response).to eq user
}.not_to change(User, :count)
end
end
context 'with no user' do
it 'returns new user' do
expect {
expect(response).to be_is_a(User)
}.to change(User, :count).by(1)
end
end
end
end
end
|
require 'formula'
class Snappy < Formula
homepage 'http://snappy.googlecode.com'
url 'https://snappy.googlecode.com/files/snappy-1.1.1.tar.gz'
sha1 '2988f1227622d79c1e520d4317e299b61d042852'
bottle do
cellar :any
revision 1
sha1 '3d55ae60e55bef5a27a96d7b1b27f671935288a9' => :mavericks
sha1 '7a26958f44511136965ae2b306ae79efddd4b44f' => :mountain_lion
sha1 'e5e3f3b4f0227910851fcc832aea0f2b7b5f2292' => :lion
end
option :universal
depends_on 'pkg-config' => :build
def install
ENV.universal_binary if build.universal?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
end
end
|
class RemoveBrokerIdFromRequest < ActiveRecord::Migration
def change
remove_column :requests, :broker_id, :integer
end
end
|
describe ROM::Redis::Relation do
include_context 'container'
subject { rom.relations[:users] }
before do
configuration.relation(:users)
end
it '#set' do
expect(subject.set(:a, 1).to_a).to eq(['OK'])
end
it '#hset' do
expect(subject.hset(:who, :is, :john).to_a).to eq([true])
end
it '#hget' do
subject.hset(:users, :john, :doe).to_a
expect(subject.hgetall(:users).to_a).to eq([{ 'john' => 'doe' }])
end
end
|
namespace :import_images do
desc "Imports placeholder images using the Faker gem"
task generate_profile_pictures: :environment do
# Grab half of all Authors, and set their profile images to Faker data;
Author.limit(Author.count/2).find_each do |author|
author.profile_image = Faker::Avatar.image
author.save
end
end
end
|
module Cloudant
module QueryBuilder
# TODO: Add a check to determine if options value is valid for key.
# ex: {include_docs: true} is valid, {include_docs: 6} is not.
def build_query_string(opts,type)
query_str = ""
fields = get_fields(type)
fields.each do |field|
val = opts[field].to_s
current = "#{field}=#{val}" if val != ""
query_str << "&" << current if (query_str != "" && current)
query_str << "?" << current if (query_str == "" && current)
end
query_str
end
def get_fields(type)
case type
when "view"
return [:reduce,:include_docs,:descending,:endkey,:endkey_docid,:group,:group_level,:inclusive_end,:key,:keys,:limit,:skip,:stale,:startkey,:startkey_docid]
when "all_docs"
return [:include_docs,:descending,:endkey,:conflicts,:inclusive_end,:key,:limit,:skip,:startkey,:keys]
when "changes"
return [:include_docs,:descending,:feed,:filter,:heartbeat,:conflicts,:limit,:since,:style,:timeout,:doc_ids]
when "doc"
return [:local_seq,:attachments,:att_encoding_info,:atts_since,:conflicts,:deleted_conflicts,:latest,:meta,:open_revs,:rev,:revs,:revs_info]
end
end
# Built the query string for attachments
def build_attachment_query(args)
q = ""
q << "#{database}"
q << "/#{args[:id]}"
q << "/#{args[:name]}"
q << "?rev=#{args[:rev]}" if args[:rev]
q
end
end
end |
cask 'sip' do
version '0.9.5'
sha256 '3735b97790ba10f0a070105d5452ca503c3f84a1edcf63226bce7d23c85fe34a'
url 'http://sipapp.io/download/sip.dmg'
appcast 'http://sipapp.io/sparkle/sip.xml',
checkpoint: '985852e024717f0172fbef5107b83d8d855ff2a50a32ea21d042c73c3c28455e'
name 'Sip'
homepage 'http://sipapp.io/'
app 'Sip.app'
end
|
# RELEASE 2: NESTED STRUCTURE GOLF
# Hole 1
# Target element: "FORE"
array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]]
# attempts:
# ============================================================
# p array[1][1][2][0]
# ============================================================
# Hole 2
# Target element: "congrats!"
hash = {outer: {inner: {"almost" => {3 => "congrats!"}}}}
# attempts:
# ============================================================
#p hash[:inner][3]
#p hash[:outer][:inner][3]
#p hash [:outer][:inner]["almost"][3]
# ============================================================
# Hole 3
# Target element: "finished"
nested_data = {array: ["array", {hash: "finished"}]}
# attempts:
# ============================================================
# p nested_data[:array][1][:hash]
# ============================================================
# RELEASE 3: ITERATE OVER NESTED STRUCTURES
number_array = [5, [10, 15], [20,25,30], 35]
number_array.map! do |item|
if item.is_a? Array
item.map! {|subitem| subitem + 5}
else
item + 5
end
end
p number_array
# Bonus:
startup_names = ["bit", ["find", "fast", ["optimize", "scope"]]]
startup_names.map! do |item|
if item.is_a? Array
item.map! do |subitem|
if subitem.is_a? Array
subitem.map! {|subsubitem| subsubitem << "ly"}
else
subitem << "ly"
end
end
else
item << "ly"
end
end
p startup_names
=begin
* What are some general rules you can apply to nested arrays?
To access a value in a nested array you can chain indices together in the
form array[index][subararry index][subsubarray index]. Nested arrays
can be iterated over just like normal arrays but with added depth (see below).
* What are some ways you can iterate over nested arrays?
You can use enumerable methods like .each or .map(!) but you may have to add
a statement checking whether the item inside the array is another array or
some other non-enumerable item. It helps to know what your array looks like
before you try to iterate over it.
* Did you find any good new methods to implement or did you re-use
one you were already familiar with? What was it and why did you
decide that was a good option?
We used .map! which was not a new method to us, but we did learn that
.collect! is a synonym for .map!. .map! was a good choice because it
changes an array in-place and we needed a destructive method.
We also used .is_a? (a synonym for .kind_of?) which returns true if
the object is an instance of the class provided or of a subclass. This
method was not new to us but it was very useful.
=end |
# == Schema Information
#
# Table name: friendships
#
# id :integer not null, primary key
# friend_fb_id :integer
# user_id :integer
# created_at :datetime
# updated_at :datetime
#
class Friendship < ActiveRecord::Base
belongs_to :friends, class_name: "User", foreign_key: "friend_fb_id", primary_key: :fb_id, inverse_of: :friendships
belongs_to :user
validates :user_id, :friend_fb_id, presence: true
validate :unique_friendship, on: :create
def unique_friendship
if Friendship.exists?(user_id: user_id, friend_fb_id: friend_fb_id)
errors.add(:friendship, "has existed.")
end
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{roles_data_mapper}
s.version = "0.3.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Kristian Mandrup"]
s.date = %q{2011-01-10}
s.description = %q{Makes it easy to set a role strategy on your User model in DataMapper}
s.email = %q{kmandrup@gmail.com}
s.extra_rdoc_files = [
"LICENSE",
"README.markdown"
]
s.files = [
".document",
".rspec",
"Changelog.textile",
"Gemfile",
"LICENSE",
"README.markdown",
"Rakefile",
"VERSION",
"lib/generators/data_mapper/roles/core_ext.rb",
"lib/generators/data_mapper/roles/roles_generator.rb",
"lib/generators/data_mapper/roles/templates/many_roles/role.rb",
"lib/generators/data_mapper/roles/templates/many_roles/user_role.rb",
"lib/generators/data_mapper/roles/templates/one_role/role.rb",
"lib/roles_data_mapper.rb",
"lib/roles_data_mapper/base.rb",
"lib/roles_data_mapper/namespaces.rb",
"lib/roles_data_mapper/role.rb",
"lib/roles_data_mapper/role_class.rb",
"lib/roles_data_mapper/strategy.rb",
"lib/roles_data_mapper/strategy/multi.rb",
"lib/roles_data_mapper/strategy/multi/many_roles.rb",
"lib/roles_data_mapper/strategy/multi/roles_mask.rb",
"lib/roles_data_mapper/strategy/shared.rb",
"lib/roles_data_mapper/strategy/single.rb",
"lib/roles_data_mapper/strategy/single/admin_flag.rb",
"lib/roles_data_mapper/strategy/single/one_role.rb",
"lib/roles_data_mapper/strategy/single/role_string.rb",
"roles_data_mapper.gemspec",
"spec/generator_spec_helper.rb",
"spec/roles_data_mapper/generators/roles_generator_spec.rb",
"spec/roles_data_mapper/strategy/api_examples.rb",
"spec/roles_data_mapper/strategy/multi/many_roles_spec.rb",
"spec/roles_data_mapper/strategy/multi/roles_mask_spec.rb",
"spec/roles_data_mapper/strategy/single/admin_flag_spec.rb",
"spec/roles_data_mapper/strategy/single/one_role_spec.rb",
"spec/roles_data_mapper/strategy/single/role_string_spec.rb",
"spec/roles_data_mapper/strategy/user_setup.rb",
"spec/spec_helper.rb",
"tmp/rails/config/routes.rb"
]
s.homepage = %q{http://github.com/kristianmandrup/roles_for_dm}
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{Implementation of Roles generic API for DataMapper}
s.test_files = [
"spec/generator_spec_helper.rb",
"spec/roles_data_mapper/generators/roles_generator_spec.rb",
"spec/roles_data_mapper/strategy/api_examples.rb",
"spec/roles_data_mapper/strategy/multi/many_roles_spec.rb",
"spec/roles_data_mapper/strategy/multi/roles_mask_spec.rb",
"spec/roles_data_mapper/strategy/single/admin_flag_spec.rb",
"spec/roles_data_mapper/strategy/single/one_role_spec.rb",
"spec/roles_data_mapper/strategy/single/role_string_spec.rb",
"spec/roles_data_mapper/strategy/user_setup.rb",
"spec/spec_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<activesupport>, [">= 3.0.1"])
s.add_runtime_dependency(%q<sugar-high>, ["~> 0.3.1"])
s.add_runtime_dependency(%q<require_all>, ["~> 1.2.0"])
s.add_runtime_dependency(%q<roles_generic>, ["~> 0.3.2"])
s.add_runtime_dependency(%q<rails3_artifactor>, [">= 0.3.2"])
s.add_runtime_dependency(%q<logging_assist>, [">= 0.2.0"])
s.add_runtime_dependency(%q<dm-core>, ["~> 1.0"])
s.add_runtime_dependency(%q<dm-types>, ["~> 1.0"])
s.add_runtime_dependency(%q<dm-migrations>, ["~> 1.0"])
s.add_runtime_dependency(%q<dm-validations>, ["~> 1.0"])
s.add_runtime_dependency(%q<dm-sqlite-adapter>, ["~> 1.0"])
s.add_development_dependency(%q<rspec>, [">= 2.0.1"])
s.add_development_dependency(%q<generator-spec>, [">= 0.7.0"])
s.add_runtime_dependency(%q<dm-core>, ["~> 1.0"])
s.add_runtime_dependency(%q<dm-types>, ["~> 1.0"])
s.add_runtime_dependency(%q<dm-migrations>, ["~> 1.0"])
s.add_runtime_dependency(%q<dm-validations>, ["~> 1.0"])
s.add_runtime_dependency(%q<activesupport>, [">= 3.0.1"])
s.add_runtime_dependency(%q<require_all>, ["~> 1.2.0"])
s.add_runtime_dependency(%q<sugar-high>, [">= 0.3.1"])
s.add_runtime_dependency(%q<roles_generic>, [">= 0.3.2"])
s.add_runtime_dependency(%q<rails3_artifactor>, [">= 0.3.2"])
s.add_runtime_dependency(%q<logging_assist>, [">= 0.2.0"])
else
s.add_dependency(%q<activesupport>, [">= 3.0.1"])
s.add_dependency(%q<sugar-high>, ["~> 0.3.1"])
s.add_dependency(%q<require_all>, ["~> 1.2.0"])
s.add_dependency(%q<roles_generic>, ["~> 0.3.2"])
s.add_dependency(%q<rails3_artifactor>, [">= 0.3.2"])
s.add_dependency(%q<logging_assist>, [">= 0.2.0"])
s.add_dependency(%q<dm-core>, ["~> 1.0"])
s.add_dependency(%q<dm-types>, ["~> 1.0"])
s.add_dependency(%q<dm-migrations>, ["~> 1.0"])
s.add_dependency(%q<dm-validations>, ["~> 1.0"])
s.add_dependency(%q<dm-sqlite-adapter>, ["~> 1.0"])
s.add_dependency(%q<rspec>, [">= 2.0.1"])
s.add_dependency(%q<generator-spec>, [">= 0.7.0"])
s.add_dependency(%q<dm-core>, ["~> 1.0"])
s.add_dependency(%q<dm-types>, ["~> 1.0"])
s.add_dependency(%q<dm-migrations>, ["~> 1.0"])
s.add_dependency(%q<dm-validations>, ["~> 1.0"])
s.add_dependency(%q<activesupport>, [">= 3.0.1"])
s.add_dependency(%q<require_all>, ["~> 1.2.0"])
s.add_dependency(%q<sugar-high>, [">= 0.3.1"])
s.add_dependency(%q<roles_generic>, [">= 0.3.2"])
s.add_dependency(%q<rails3_artifactor>, [">= 0.3.2"])
s.add_dependency(%q<logging_assist>, [">= 0.2.0"])
end
else
s.add_dependency(%q<activesupport>, [">= 3.0.1"])
s.add_dependency(%q<sugar-high>, ["~> 0.3.1"])
s.add_dependency(%q<require_all>, ["~> 1.2.0"])
s.add_dependency(%q<roles_generic>, ["~> 0.3.2"])
s.add_dependency(%q<rails3_artifactor>, [">= 0.3.2"])
s.add_dependency(%q<logging_assist>, [">= 0.2.0"])
s.add_dependency(%q<dm-core>, ["~> 1.0"])
s.add_dependency(%q<dm-types>, ["~> 1.0"])
s.add_dependency(%q<dm-migrations>, ["~> 1.0"])
s.add_dependency(%q<dm-validations>, ["~> 1.0"])
s.add_dependency(%q<dm-sqlite-adapter>, ["~> 1.0"])
s.add_dependency(%q<rspec>, [">= 2.0.1"])
s.add_dependency(%q<generator-spec>, [">= 0.7.0"])
s.add_dependency(%q<dm-core>, ["~> 1.0"])
s.add_dependency(%q<dm-types>, ["~> 1.0"])
s.add_dependency(%q<dm-migrations>, ["~> 1.0"])
s.add_dependency(%q<dm-validations>, ["~> 1.0"])
s.add_dependency(%q<activesupport>, [">= 3.0.1"])
s.add_dependency(%q<require_all>, ["~> 1.2.0"])
s.add_dependency(%q<sugar-high>, [">= 0.3.1"])
s.add_dependency(%q<roles_generic>, [">= 0.3.2"])
s.add_dependency(%q<rails3_artifactor>, [">= 0.3.2"])
s.add_dependency(%q<logging_assist>, [">= 0.2.0"])
end
end
|
require 'rails_helper'
describe Importer::Cnab do
let(:cnab_input) { File.expand_path('spec/fixtures/cnab.txt') }
let(:importer) { described_class.new(cnab_input) }
context 'import file' do
it { expect{importer.import!}.to_not raise_error }
it { expect(importer.import!.size).to eq 21 }
end
context 'after import' do
it { expect{importer.import!}.to change{Event.count}.by(21) }
it { expect{importer.import!}.to change{Store.count}.by(5)}
end
end
|
require 'json'
GLB_H_SIZE = 4
GLB_H_MAGIC = "glTF".b
GLB_H_VERSION = [2].pack("L*")
GLB_JSON_TYPE = "JSON".b
GLB_BUFF_TYPE = "BIN\x00".b
FF = "\x00".b
SLIDE_MATERIAL_NAME="Slide"
SLIDE_TEXTURE_NAME = "Slide-all"
class VCISlide
attr_accessor :template_vci_path, :vci_script_path, :image_path, :page_size, :output_path, :meta_title, :meta_version, :meta_author, :meta_description, :max_page_index, :max_page_index
def initialize template_vci_path=nil, vci_script_path=nil, image_path=nil, page_size=nil, max_page_index=nil, output_path=nil
@template_vci_path = template_vci_path
@vci_script_path = vci_script_path
@image_path = image_path
@page_size = page_size
@output_path = output_path
@meta_title = "untitled"
@meta_version = 1.0
@meta_author = "unknown"
@meta_description = "none"
@max_page_index = max_page_index
end
def generate
property, glb_buff_data = load_template(@template_vci_path)
image, img_idx = load_image(property, @image_path, SLIDE_TEXTURE_NAME)
src, src_idx = load_script(property, page_size, max_page_index)
data = mk_data(property, glb_buff_data, image, img_idx, src, src_idx)
meta = {
title:@meta_title,
version:@meta_version,
author:@meta_author,
description:@meta_description
}
json = mk_json(property, image, img_idx, src, src_idx, data, @page_size, meta)
json, data = align(json, data)
store(@output_path, json, data)
end
#
# Store as GLB
#
def store output_path, json, data
glb = GLB_H_MAGIC
glb += GLB_H_VERSION
glb += [(GLB_H_SIZE * 3) + (GLB_H_SIZE * 2) + json.size + (GLB_H_SIZE * 2) + data.size].pack("L*")
glb += [json.size].pack("L*")
glb += GLB_JSON_TYPE
glb += json
glb += [data.size].pack("L*")
glb += GLB_BUFF_TYPE
glb += data
open(output_path, 'wb') do |f|
f.write(glb)
end
end
def align json, data
json_padding = padding_size(json.size)
json = json + (" " * json_padding)
data_padding = padding_size(data.size)
data = data + (FF * data_padding)
return [json, data]
end
def padding_size(data_size)
if data_size == 0 then
return 0
else
m = data_size % 4
return m > 0 ? 4 - m : 0
end
end
#
# Load Template
#
def load_template template_vci_path
load_template_from_data open(template_vci_path)
end
def load_template_from_data file
io = file
glb_h_magic = io.read(GLB_H_SIZE)
glb_h_version = io.read(GLB_H_SIZE).unpack("L*")[0]
glb_h_length = io.read(GLB_H_SIZE).unpack("L*")[0]
glb_json_length = io.read(GLB_H_SIZE).unpack("L*")[0]
glb_json_type = io.read(GLB_H_SIZE)
glb_json_data = io.read(glb_json_length).force_encoding("utf-8")
glb_buff_length = io.read(GLB_H_SIZE).unpack("L*")[0]
glb_buff_type = io.read(GLB_H_SIZE)
glb_buff_data = io.read(glb_buff_length)
[JSON.parse(glb_json_data), glb_buff_data]
end
# load image
def load_image property, image_path, slide_texture_name
image = open(image_path, 'rb').read
img_idx = find_image_index property, slide_texture_name
[image, img_idx]
end
def find_image_index property, slide_texture_name
property["images"].find{|x| x["name"] == slide_texture_name }["bufferView"]
end
# Lua Script
def load_script property, page_size, max_page_index
require 'erb'
template = ERB.new open(@vci_script_path).read
src = template.result(binding)
src_idx = property["extensions"]["VCAST_vci_embedded_script"]["scripts"][0]["source"]
return [src, src_idx]
end
def mk_data property, glb_buff_data, image, img_idx, src, src_idx
data = ""
property["bufferViews"].each_with_index do |x, i|
case i
when img_idx
data += image + FF * padding_size(image.size)
when src_idx
data += src + FF * padding_size(src.size)
else
len = x["byteLength"]
data += glb_buff_data[x["byteOffset"], len] + FF * padding_size(len)
end
end
data
end
#
# Create JSON
#
def mk_json property, image, img_idx, src, src_idx, data, page_size, meta
# Update meta data
vci_meta = property["extensions"]["VCAST_vci_meta"]
vci_meta["title"] = meta[:title]
vci_meta["version"] = meta[:version]
vci_meta["author"] = meta[:author]
vci_meta["description"] = meta[:description]
# Adjust for page size
material = property["materials"].find{|x| x["name"] == SLIDE_MATERIAL_NAME}
# material["pbrMetallicRoughness"]["baseColorTexture"]["extensions"]["KHR_texture_transform"]["scale"] = [(1.0 / page_size).floor(5), 1]
material["pbrMetallicRoughness"]["baseColorTexture"]["extensions"]["KHR_texture_transform"]["scale"] = [(1.0 / max_page_index[:x]).floor(5), (1.0 / max_page_index[:y]).floor(5)]
# buffers/Update bufferViews
property["bufferViews"][img_idx]["byteLength"] = image.size
property["bufferViews"][src_idx]["byteLength"] = src.size
xs = property["bufferViews"]
(1..xs.size-1).each do |i|
px = xs[i - 1]
len = px["byteLength"]
offset = px["byteOffset"] + len + padding_size(len)
xs[i]["byteOffset"] = offset
end
property["buffers"][0]["byteLength"] = data.size
json = property.to_json.gsub('/', '\/')
json.force_encoding("ASCII-8BIT")
end
end
|
class LandingController < ApplicationController
layout 'landing'
before_action :set_request, only: [:register]
def info
@user = User.new
end
def register
logger.info "Sending a register email #{params[:user][:email]}"
@user = User.new
@user.email = params[:user][:email]
UserNotifierMailer.send_info_email(@user).deliver
respond_to do |format|
format.html { redirect_to landing_info_path, notice: 'for showing interest on our product, will only contact you to notify new functionality or critical updates.' }
end
end
private
def set_request
params.require(:user).permit(:email)
end
end
|
class Painel::BaseController < ApplicationController
before_action :authenticate_user!, :funcionario?, :ativo?
layout 'painel'
private
def ativo?
unless current_user.status != false
sign_out @user
redirect_to previous_url(current_user)
end
end
def funcionario?
if current_user.level != 'user'
return true
else
sign_out @user
redirect_to previous_url(current_user)
end
end
def previous_url(resource)
session[:previous_url] || painel_root_path
end
end
|
require "tic_tac_toe_rz/core/mark"
module TicTacToeRZ
module Core
class Board
include Enumerable
WIN_PLACES = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]]
def self.win_places
WIN_PLACES
end
def self.from(marks)
TicTacToeRZ::Core::Board.new(marks.map { |m| TicTacToeRZ::Core::BLANK.mark(m) }.to_a)
end
def self.empty_board
board = TicTacToeRZ::Core::Board.new([])
board.reset
end
def initialize(marks)
@marks = marks
end
def each(&block)
@marks.each do |m|
block.call(m)
end
end
def reset
@marks = Array.new(9, TicTacToeRZ::Core::Mark.new)
return self
end
def to_s
rows = @marks.each_slice(3)
row_strings = rows.map { |row| Array(row).join(" | ") }
row_strings.join("\n--+---+--\n")
end
def pos(index)
@marks[index]
end
def move(mark, index)
@marks[index] = @marks[index].mark(mark)
end
def speculative_move(mark, index)
board = TicTacToeRZ::Core::Board.from(Array.new(@marks))
board.move(mark, index)
return board
end
def legal?(index)
@marks[index].blank?
end
def full?
@marks.none? { |m| m.blank? }
end
def attack_sets
WIN_PLACES.map { |places| places.map { |n| @marks.at n }}
end
IndexedCell = Struct.new(:index, :mark)
def indexed_attack_sets
WIN_PLACES.map { |places| places.map { |n| IndexedCell.new(n, @marks.at(n)) }}
end
def empty_spaces
@marks.map.with_index { |mark, index| index if mark.blank? }.compact
end
end
end
end
|
module SimpleSpark
module Endpoints
# Provides access to the /recipient-lists endpoint
# @note See: https://developers.sparkpost.com/api/recipient-lists
class RecipientLists
attr_accessor :client
def initialize(client)
@client = client
end
# List all recipient lists
# @return [Array] an array of abbreviated recipient list objects
# @note See: https://developers.sparkpost.com/api/recipient-lists/#recipient-lists-get-list-all-recipient-lists
def list
@client.call(method: :get, path: 'recipient-lists')
end
# Create a recipient list
# @param values [Hash] the values to create the recipient list with, valid keys: [:id, :name, :description, :attributes, :recipients]
# @param num_rcpt_errors [Integer] max number of recipient errors that this call can return
# @return [Hash] details about created list
# @note See: https://developers.sparkpost.com/api/recipient-lists#recipient-lists-post-create-a-recipient-list
def create(values, num_rcpt_errors = nil)
query_params = num_rcpt_errors.nil? ? '' : "?num_rcpt_errors=#{num_rcpt_errors.to_i}"
@client.call(method: :post, path: "recipient-lists#{query_params}", body_values: values)
end
# Retrieve recipient list details
# @param id [Integer] the recipient list ID to retrieve
# @param show_recipients [Boolean] if true, return all the recipients contained in the list
# @return [Hash] details about a specified recipient list
# @note See: https://developers.sparkpost.com/api/recipient-lists/#recipient-lists-get-retrieve-a-recipient-list
def retrieve(id, show_recipients = false)
params = { show_recipients: show_recipients }.compact
@client.call(method: :get, path: "recipient-lists/#{id}", query_values: params)
end
# Update a recipient list
# @param id [Integer] the recipient list ID to update
# @param values [Hash] hash of values to update, valid keys: [:name, :description, :attributes, :recipients]
# @return [Hash] details on update operation
# @note See: https://developers.sparkpost.com/api/recipient-lists/#recipient-lists-put-update-a-recipient-list
def update(id, values)
@client.call(method: :put, path: "recipient-lists/#{id}", body_values: values)
end
# Delete a recipient list
# @param id [String] the ID
# @note See: https://developers.sparkpost.com/api/recipient-lists#recipient-lists-delete-delete-a-recipient-list
def delete(id)
@client.call(method: :delete, path: "recipient-lists/#{id}")
end
end
end
end
|
# Tag some key information for Datadog so we can view it across all traces
# See https://docs.datadoghq.com/tracing/guide/add_span_md_and_graph_it/ for more info
module DatadogTagging
def self.included(base)
base.helper_method :current_enabled_features
end
def current_enabled_features
@current_enabled_features ||= Flipper.features.select { |feature| feature.enabled?(current_admin) }.map(&:name)
end
def set_datadog_tags
span = Datadog::Tracing.active_span
return if span.nil?
tags = current_enabled_features.reduce({}) do |hash, name|
hash.merge("features.#{name}" => "enabled")
end
span.set_tags(tags)
user_hash = RequestStore.store[:current_user]
unless user_hash.blank?
span.set_tags(user_hash)
end
end
end
|
=begin
# Ruby Unless Modifier
SYNTAX:
code unless condition #Executes the code when condition is false
=end
x = false
puts "x is false. Hence, statment executed" unless x |
class AddOderItemIdToItemComments < ActiveRecord::Migration
def change
add_column :item_comments, :order_item_id, :integer
end
end
|
class Staffs::BaseController < ApplicationController
layout 'staffs_application'
protected
def after_sign_in_path_for(resource)
staffs_path
end
end
|
class Book
def initialize(title)
@title = title
end
attr_reader :title
attr_accessor :author, :page_count, :genre
def turn_page
puts "Flipping the page...wow, you read fast!"
end
end
|
class ContactMailer < ActionMailer::Base
default from: 'no-reply@dungeonmasters.com.br'
def contact_email(params)
@from_email = params[:email]
@message = params[:message]
mail(from: @from_email, to: ENV["mail_to"], subject: 'Email de contato - Dungeon Masters')
end
end
|
class AddTableIdToGuests < ActiveRecord::Migration[5.1]
def change
add_reference :guests, :table, foreign_key: true, index: true
end
end
|
# == Schema Information
#
# Table name: pcomb_detail_records
#
# id :integer not null, primary key
# representative_number :integer
# representative_type :integer
# record_type :integer
# requestor_number :integer
# policy_type :string
# policy_number :integer
# business_sequence_number :integer
# valid_policy_number :string
# policy_combinations :string
# predecessor_policy_type :string
# predecessor_policy_number :integer
# predecessor_filler :string
# predecessor_business_sequence_number :string
# successor_policy_type :string
# successor_policy_number :integer
# successor_filler :string
# successor_business_sequence_number :string
# transfer_type :string
# transfer_effective_date :date
# transfer_creation_date :date
# partial_transfer_due_to_labor_lease :string
# labor_lease_type :string
# partial_transfer_payroll_movement :string
# ncci_manual_number :integer
# manual_coverage_type :string
# payroll_reporting_period_from_date :date
# payroll_reporting_period_to_date :date
# manual_payroll :float
# created_at :datetime not null
# updated_at :datetime not null
#
require 'test_helper'
class PcombDetailRecordTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
class Kill < ActiveRecord::Base
belongs_to :killer, class_name: 'Player'
belongs_to :target, class_name: 'Player'
belongs_to :game
validate :only_one_player_or_confirmed
# this probably breaks it
# attr_reader :killer_id
# attr_reader :target_id
# attr_reader :game_id
after_initialize :defaults
scope :pending, -> { where(confirmed: false) }
scope :confirmed, -> { where(confirmed: true) }
def defaults
if self.new_record?
self.confirmed = false
end
end
def pending_target
if self.confirmed?
raise "This kill has already been confirmed!"
end
raise "Pending killer, not target" if self.target
self.killer.target
end
def pending_killer
if self.confirmed?
raise "This kill has already been confirmed!"
end
raise "Pending target, not killer" if self.killer
self.target.killer
end
def kill_time
# convenience alias
if !self.confirmed?
raise "Kill #{self.id} was never confirmed!"
end
# NOTE: IF THERE IS A REASON TO MODIFY KILLS AFTER CONFIRMATION
# THEN THIS METHOD WILL NO LONGER BE ACCURATE, AND IT WILL BE
# IMPORTANT TO CREATE A SEPARATE LOCKED IN TIME
return self.updated_at
end
def kill_loc
# who knows...
end
def confirm(player_hash)
# sets the empty target/killer pair
role, id = player_hash.first
self[role] = id
self.confirmed = true
self.save
end
def only_one_player_or_confirmed
# kills should only have one field filled in (player/target)
# unless it's confirmed - then both fields should be filled
# TODO
# I'm holding off on completing this method because
# will the interim saves done by the start model trigger
# validation and then an error?
if false
errors.add(:players, 'this is bad')
end
end
end
|
# Puppet Type for editing text files
# (c)2011 Markus Strauss <Markus@ITstrauss.eu>
# License: see LICENSE file
Puppet.debug "Editfile::Yaml: Loading provider"
begin
require 'hashie'
rescue LoadError
Puppet.err('Editfile::Yaml needs hashie. Please run "gem install hashie".')
end
Puppet::Type.type(:editfile).provide(:yaml, :parent => Puppet::Provider) do
desc "Editing YAML files.
Usage:
editfile { 'add/replace in a yaml file':
provider => yaml,
path => 'my.yaml',
match => 'key.subkey',
ensure => { subsubkey1 => value1, subsubkey2 => { subhashkey => subhashvalue } },
}
Generates:
---
key.subkey:
subsubkey1: value1
subsubkey2:
subhashkey: subhashvalue
"
# # the file must exist, otherwise we refuse to manage it
# confine :exists => @resource[:path]
def create
Puppet.debug "Editfile::Yaml: Creating hash #{pretty_value} on key #{pretty_key}."
eval( "read_file.#{key} = #{pretty_value}")
myflush
end
def destroy
Puppet.debug "Editfile::Yaml: Destroying key #{pretty_key}."
read_file[ @resource[:match] ] = nil
myflush
end
def exists?
if @resource[:ensure] == :absent
matches_found?
else
line_found?
end
end
private
def matches_found?
check_file and key_exists
end
def key_exists
key_exist = begin
!eval("read_file.#{key}").nil?
rescue
false
end
Puppet.debug "Editfile::Yaml: Key #{@resource[:match]} exists? #{key_exist}"
key_exist
end
def value_exists
value_exists = ( eval("read_file.#{key}") == value )
Puppet.debug "Editfile::Yaml: Value #{pretty_value} exists on key #{@resource[:match]}? #{value_exists}"
value_exists
end
def line_found?
matches_found? and value_exists
end
def check_file
file_here = File.exists?( @resource[:path] )
Puppet.debug "Editfile::Yaml: File #{@resource[:path]} exists? #{file_here}"
file_here
end
def value
# @value ||= Hashie::Mash.new( @resource[:line] )
@resource[:line]
end
def pretty_value
value.inspect
end
def key
# @key ||= Hashie::Mash.new( @resource[:match] )
@resource[:match]
end
def pretty_key
key.inspect
end
def read_file
return @data if @data
Puppet.debug "Editfile::Yaml: Reading file '#{@resource[:path]}'"
begin
@data = Hashie::Mash.new( YAML.load_file( @resource[:path] ) )
rescue
Puppet.debug "Editfile::Yaml: File does NOT exist. Starting with an empty hash."
@data = Hashie::Mash.new
end
end
def myflush
Puppet.debug "Editfile::Yaml: Flushing to file #{@resource[:path]}."
File.open( @resource[:path], "w" ) do |f|
f.write( @data.to_yaml )
f.close
end
end
end
|
# == Schema Information
#
# Table name: images
#
# id :integer not null, primary key
# name :string default("")
# description :string default("")
# taken_at :datetime
# created_at :datetime
# updated_at :datetime
# gallery_id :integer
# image_file_id :string
#
require "rails_helper"
describe Image, type: :model do
let!(:gallery) { create(:gallery) }
let(:image) { create(:image, gallery: gallery) }
describe "relationships" do
it "should belong to a gallery" do
assoc = Image.reflect_on_association(:gallery).macro
expect(assoc).to eq :belongs_to
end
end
describe "#is_owned_by?" do
let(:user) { create(:user) }
it "should return false for non-associated user" do
expect(image.is_owned_by?(user)).to eq false
end
it "should return true for an associated user" do
gallery.user_id = user.id
expect(image.is_owned_by?(user)).to eq true
end
end
end
|
class PlanetsController < ApplicationController
before_action :set_planet, only: %i(show destroy)
def index
planets = if planet_filter == 'giant'
Planet.giant
elsif planet_filter == 'terrestrial'
Planet.terrestrial
else
Planet.all
end
@planets = planets.order('planets.name ' + sort_direction)
end
def show
end
def new
@planet = Planet.new
end
def create
@planet = Planet.new(planet_params)
respond_to do |format|
if @planet.save
format.html { redirect_to planets_url }
format.json { render :show, status: :created, location: @planet }
else
format.html { render :new }
format.json { render json: @planet.errors, status: :unprocessable_entity }
end
end
end
def destroy
@planet.destroy
respond_to do |format|
format.html { redirect_to planets_url }
format.json { head :no_content }
end
end
private
def set_planet
@planet = Planet.find(params[:id])
end
def planet_params
params.require(:planet).permit(:name, :planet_type, :star_id)
end
def sort_direction
%w(ASC DESC).include?(params[:direction]) ? params[:direction] : 'ASC'
end
def planet_filter
params[:filter]
end
end
|
#===============================================================================
# ** Window_Save_Details
#-------------------------------------------------------------------------------
# Mostra i dettagli del salvataggio e viene gestita all'interno di Scene_File.
#===============================================================================
class Window_SaveDetails < Window_Base
# Inizializzazione
def initialize(x, y, width)
super(x, y, width, 200)
end
# Cambio delle informazioni del salvataggio
def update_header(header, save_number)
return if @save_number == save_number
@save_number = save_number
@header = header
extract_contents if @header
refresh
end
# Restituisce le informazioni del salvataggio
def header
@header
end
# Aggiornamento
def refresh
self.contents.clear
if @header.nil?
write_clear_save
else
write_save_data
end
end
def extract_contents
@play_time = header[:playtime_s]
@gold = header[:gold]
@map_name = header[:map_name]
@actors = header[:characters]
@player = header[:player_name]
@story = header[:story]
end
# Scrive il testo di un salvataggio vuoto
def write_clear_save
texts = Vocab.slot_empty_info.split("|")
texts.each_with_index do |text, line|
draw_text(0, line_height * line, contents_width, line_height, text)
end
end
# Mostra i dati del salvataggio
def write_save_data
draw_player_name(0, 0)
draw_save_date(contents_width / 2, 0)
draw_gold(0, line_height)
draw_story(0, line_height * 6)
draw_missions(0, line_height * 5)
draw_play_time(contents_width / 2, line_height)
draw_party_members(0, line_height * 2)
draw_location(0, line_height * 6)
end
# Disegna i membri del gruppo
def draw_party_members(x, y)
return if @actors.nil?
@actors.each_with_index { |actor, i| draw_character_info(actor, x + (i * 96), y) }
end
# Disegna il nome del giocatore
def draw_player_name(x, y)
change_color system_color
draw_text(x, y, contents_width - x, line_height, Vocab.player_name)
change_color normal_color
xx = contents.text_size(Vocab.player_name).width
draw_text(x + xx, y, contents_width - xx - x, line_height, @player)
end
# Disegna la data di salvataggio
def draw_save_date(x, y)
save_date = DataManager.savefile_time_stamp(@save_number)
change_color system_color
draw_text(x, y, contents_width - x, line_height, Vocab.save_date)
xx = contents.text_size(Vocab.save_date).width
change_color normal_color
draw_text(x + xx, y, contents_width - (x + xx), line_height, get_date(save_date))
end
# Ottiene il testo della data del salvataggio
def get_date(save_date)
day = save_date.mday
month = save_date.mon
year = save_date.year
hour = save_date.hour
min = save_date.min
pre_text = "%d/%d/%d - %d:%d"
sprintf(pre_text, day, month, year, hour, min)
end
# Mostra il tempo di gioco
def draw_play_time(x, y)
change_color system_color
draw_text(x, y, contents_width - x, line_height, Vocab.play_time)
change_color normal_color
xx = x + contents.text_size(Vocab.play_time).width
draw_text(xx, y, contents_width - xx, line_height, @play_time)
end
# Disegna l'oro del giocatore
def draw_gold(x, y)
change_color system_color
draw_text(x, y, contents_width - x, line_height, Vocab.gold)
change_color normal_color
xx = contents.text_size(Vocab.gold).width
draw_text(xx, y, contents_width - x - xx, line_height, @gold)
end
# Mostra la posizione del giocatore
def draw_location(x, y)
draw_text(x, y, contents_width, line_height, @map_name)
end
# Mostra la percentuale della storia
def draw_story(x, y)
st = (@story.to_f / CPanel::MAX_STORY * 100).to_i
draw_text(x, y, contents_width, line_height, sprintf(Vocab.story, st), 2)
end
# Disegna le informazioni dell'eroe
def draw_character_info(actor, x, y)
draw_face(actor[0], actor[1], x, y, 96)
draw_hp_bar(actor, x, y + 90)
draw_level(actor, x + 2, y + 2)
end
# Disegna la barra degli HP
def draw_hp_bar(actor, x, y)
contents.fill_rect(x, y, 94, 6, Color.new(0, 0, 0))
contents.fill_rect(x + 1, y + 1, 92, 4, gauge_back_color)
w = [actor[3].to_f / actor[4] * 92.0, 92].min
contents.gradient_fill_rect(x + 1, y + 1, w, 4, hp_gauge_color1, hp_gauge_color2)
end
# Disengna il livello
def draw_level(actor, x, y)
change_color system_color
back_g = back_level
contents.blt(x, y + 5, back_g, back_g.rect)
draw_text(x, y, 90, line_height, Vocab.level_a)
change_color normal_color
xx = x + contents.text_size(Vocab.level_a).width
draw_text(xx, y, 90, line_height, actor[2])
end
def back_level
bitmap = Bitmap.new(70, line_height - 10)
color1 = gauge_back_color
color2 = gauge_back_color.deopacize(0)
bitmap.gradient_fill_rect(0, 5, 70, line_height - 10, color1, color2)
bitmap
end
# Disegna il testo delle missioni completate
def draw_missions(x, y)
change_color normal_color
draw_text(x, y, contents_width - 4, line_height, header[:missions], 2)
xx = contents.text_size(header[:missions]).width + 1
change_color system_color
draw_text(x, y, contents_width - xx - 4, line_height, Vocab.missions, 2)
end
end |
class Ship < ApplicationRecord
belongs_to :cruise_line
has_many :ship_images
has_many :reviews
has_many :voyages
end
|
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
#Users
can [:read, :follow, :unfollow], User
can :manage, User, id: user.id
#Posts
can :read, Post
can :manage, Post, user_id: user.id
#Comments
can :create, Comment
end
end
|
module GenText
class VM
# @param program Array of <code>[:method_id, *args]</code>.
# @return [Boolean] true if +program+ may result in calling
# {IO#pos=} and false otherwise.
def self.may_set_out_pos?(program)
program.any? do |instruction|
[:rescue_, :capture].include? instruction.first
end
end
# Executes +program+.
#
# If +program+ may result in calling {IO#pos=} (see {VM::may_set_out_pos?}
# then after the execution the +out+ may contain garbage after its {IO#pos}.
# It is up to the caller to truncate the garbage or to copy the useful data.
#
# @param program Array of <code>[:method_id, *args]</code>.
# @param [IO] out
# @param [Boolean] do_not_run if true then +program+ will not be run
# (some checks and initializations will be performed only).
# @return [void]
def run(program, out, do_not_run = false)
#
if $DEBUG
STDERR.puts "PROGRAM:"
program.each_with_index do |instruction, addr|
STDERR.puts " #{addr}: #{inspect_instruction(instruction)}"
end
end
#
return if do_not_run
# Init.
@stack = []
@out = out
@pc = 0
@halted = false
# Run.
STDERR.puts "RUN TRACE:" if $DEBUG
until halted?
instruction = program[@pc]
method_id, *args = *instruction
STDERR.puts " #{@pc}: #{inspect_instruction(instruction)}" if $DEBUG
self.__send__(method_id, *args)
if $DEBUG then
STDERR.puts " PC: #{@pc}"
STDERR.puts " STACK: #{@stack.inspect}"
end
end
end
# @return [Integer]
attr_reader :pc
# @return [IO]
attr_reader :out
# @return [Boolean]
def halted?
@halted
end
# Sets {#halted?} to true.
#
# @return [void]
def halt
@halted = true
end
# NOP
#
# @return [void]
def generated_from(*args)
@pc += 1
end
# Pushes +o+ to the stack.
#
# @param [Object] o
# @return [void]
def push(o)
@stack.push o
@pc += 1
end
# {#push}(o.dup)
#
# @param [Object] o
# @return [void]
def push_dup(o)
push(o.dup)
end
# {#push}(rand(+r+) if +r+ is specified; rand() otherwise)
#
# @param [Object, nil] r
# @return [void]
def push_rand(r = nil)
push(if r then rand(r) else rand end)
end
# Pops the value from the stack.
#
# @return [Object] the popped value.
def pop
@stack.pop
@pc += 1
end
# If {#pop} is true then {#pc} := +addr+.
#
# @param [Integer] addr
# @return [void]
def goto_if(addr)
if @stack.pop then
@pc = addr
else
@pc += 1
end
end
# @return [void]
def dec
@stack[-1] -= 1
@pc += 1
end
# If the value on the stack != 0 then {#goto}(+addr).
#
# @param [Integer] addr
# @return [void]
def goto_if_not_0(addr)
if @stack.last != 0 then
@pc += 1
else
@pc = addr
end
end
# If rand > +v+ then {#goto}(addr)
#
# @param [Numeric] v
# @param [Integer] addr
# @return [void]
#
def goto_if_rand_gt(v, addr)
if rand > v then
@pc = addr
else
@pc += 1
end
end
# @param [Integer] addr
# @return [void]
def goto(addr)
@pc = addr
end
# Writes {#pop} to {#out}.
#
# @return [void]
def gen
@out.write @stack.pop
@pc += 1
end
# - p := {#pop};
# - +binding_+.eval(set variable named +name+ to a substring of {#out} from
# p to current position);
# - if +discard_output+ is true then set {IO#pos} of {#out} to p.
#
# @param [Binding] binding_
# @param [String] name
# @param [Boolean] discard_output
# @return [void]
def capture(binding_, name, discard_output)
capture_start_pos = @stack.pop
capture_end_pos = @out.pos
captured_string = begin
@out.pos = capture_start_pos
@out.read(capture_end_pos - capture_start_pos)
end
@out.pos =
if discard_output then
capture_start_pos
else
capture_end_pos
end
binding_.eval("#{name} = #{captured_string.inspect}")
@pc += 1
end
# {#push}(eval(+ruby_code+, +file+, +line+))
#
# @param [Binding] binding_
# @param [String] ruby_code
# @param [String] file original file of +ruby_code+.
# @param [Integer] line original line of +ruby_code+.
# @return [void]
def eval_ruby_code(binding_, ruby_code, file, line)
@stack.push binding_.eval(ruby_code, file, line)
@pc += 1
end
# {#push}({#out}'s {IO#pos})
#
# @return [void]
def push_pos
@stack.push(@out.pos)
@pc += 1
end
# {#push}({#out}'s {IO#pos}, {#pc} as {RescuePoint})
#
# @param [Integer, nil] pc if specified then it is pushed instead of {#pc}.
# @return [void]
def push_rescue_point(pc = nil)
@stack.push RescuePoint[(pc or @pc), @out.pos]
@pc += 1
end
# {#pop}s until a {RescuePoint} is found then restore {#out} and {#pc} from
# the {RescuePoint}.
#
# @param [Proc] on_failure is called if no {RescuePoint} is found
# @return [void]
def rescue_(on_failure)
@stack.pop until @stack.empty? or @stack.last.is_a? RescuePoint
if @stack.empty? then
on_failure.()
else
rescue_point = @stack.pop
@pc = rescue_point.pc
@out.pos = rescue_point.out_pos
end
end
# @param [Integer] addr
# @return [void]
def call(addr)
@stack.push(@pc + 1)
@pc = addr
end
# @return [void]
def ret
@pc = @stack.pop
end
# Let stack contains +wa+ = [[weight1, address1], [weight2, address2], ...].
# This function:
#
# 1. Picks a random address from +wa+ (the more weight the
# address has, the more often it is picked);
# 2. Deletes the chosen address from +wa+;
# 3. If there was the only address in +wa+ then it does {#push}(nil);
# otherwise it does {#push_rescue_point};
# 4. {#goto}(the chosen address).
#
# @return [void]
def weighed_choice
weights_and_addresses = @stack.last
# If no alternatives left...
if weights_and_addresses.size == 1 then
_, address = *weights_and_addresses.first
@stack.push nil
@pc = address
# If there are alternatives...
else
chosen_weight_and_address = sample_weighed(weights_and_addresses)
weights_and_addresses.delete chosen_weight_and_address
_, chosen_address = *chosen_weight_and_address
push_rescue_point
@pc = chosen_address
end
end
RescuePoint = Struct.new :pc, :out_pos
private
# @param [Array<Array<(Numeric, Object)>>] weights_and_items
# @return [Array<(Numeric, Object)>]
def sample_weighed(weights_and_items)
# The algorithm is described in
# http://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf
weights_and_items.max_by { |weight, item| rand ** (1.0 / weight) }
end
def inspect_instruction(instruction)
method_id, *args = *instruction
"#{method_id} #{args.map(&:inspect).join(", ")}"
end
end
end
|
module Stride
class Client
def initialize(cloud_id, conversation_id, permanent_token = nil)
self.cloud_id = cloud_id
self.conversation_id = conversation_id
self.permanent_token = permanent_token
end
# `message_body` is a formatted message in JSON
# See: https://developer.atlassian.com/cloud/stride/blocks/message-format/
def send_message(message_body)
Message.new(access_token, cloud_id, conversation_id, message_body).send!
end
# Convenience method for sending a plain text message
def send_text_message(message_text)
TextMessage.new(access_token, cloud_id, conversation_id, message_text).send!
end
def send_user_message(user_id, message_body)
UserMessage.new(access_token, cloud_id, user_id, message_body).send!
end
def send_user_markdown_message(user_id, markdown)
send_user_message(user_id, MarkdownDocument.fetch!(access_token, markdown).as_json)
end
def send_markdown_message(markdown)
send_message(MarkdownDocument.fetch!(access_token, markdown).as_json)
end
def user(user_id)
User.fetch!(access_token, cloud_id, user_id)
end
def conversation
Conversation.fetch!(access_token, cloud_id, conversation_id)
end
def conversation_roster
ConversationRoster.fetch!(access_token, cloud_id, conversation_id)
end
def me
Me.fetch!(access_token)
end
private
attr_accessor :cloud_id, :conversation_id, :permanent_token
def access_token
permanent_token || token.access_token
end
def token
return @token if have_token?
@token = Token.fetch!
end
def have_token?
!@token.nil? && @token.unexpired?
end
end
end
|
class CreateCars < ActiveRecord::Migration
def change
create_table :cars do |t|
t.string :god
t.string :marka
t.string :model
t.string :dvigatel
t.string :tip
t.string :moschnost
t.string :privod
t.string :tip_kuzova
t.string :kpp
t.string :kod_kuzova
t.string :kod_dvigatelya
t.string :rinok
t.string :vin
t.string :frame
t.string :komplektaciya
t.belongs_to :user
t.timestamps
end
end
end
|
require 'test_helper'
class OrderTest < ActiveSupport::TestCase
# NB: we can't use transactional fixtures when testing code that manually manages a
# transaction, so we turn them off for this test, but that means we also need to
# clean up the database after each test manually, which we do using the
# DatabaseCleaner gem.
#
self.use_transactional_fixtures = false
def setup
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.start
end
def teardown
# ::ActiveRecord::Base.establish_connection
DatabaseCleaner.clean
end
test 'should process concurrent orders with low stock' do
product = create(:product, stock: 1)
assert_difference 'Order.count', 1 do
assert_raises OutOfStockError do
::ActiveRecord::Base.clear_all_connections!
# simultaneously process an order in two separate processes to simulate
# concurrent requests
Parallel.map([1, 2]) do |i|
::ActiveRecord::Base.retrieve_connection
Order.process(product.id)
end
end
end
assert_equal 0, product.reload.stock
end
test 'should process concurrent orders with ample stock' do
product = create(:product, stock: 3)
assert_difference 'Order.count', 2 do
::ActiveRecord::Base.clear_all_connections!
Parallel.map([1, 2]) do |i|
::ActiveRecord::Base.retrieve_connection
Order.process(product.id)
end
end
assert_equal 1, product.reload.stock
end
test 'should get shipping status' do
product = create(:product, stock: 1)
order = Order.process(product.id)
order.update(fedex_id: '198yGaAf074')
body = JSON.dump({status: 'shipped'})
url = "https://fedex.com/api/shipping/status?id=#{order.fedex_id}"
mock(HTTP).get(url) { HTTP::Response.new(body: body, version: 2, status: 200) }
assert_equal 'shipped', order.get_shipping_status
end
end
|
require 'rails_helper'
RSpec.describe RequestBuilders::Runtastic::Response do
subject { described_class.new(raw_response: raw_response, request: dummy_request) }
let(:dummy_request) { RequestBuilders::Runtastic::Request.new(:get, 'http://some.url/') }
let(:raw_response) do
double('RawHttpResponse', code: code, return_code: return_code, return_message: return_message, body: body, success?: success?)
end
let(:code) { 200 }
let(:return_code) { '' }
let(:return_message) { '' }
let(:body) { '{ "some_key": "some data" }' }
let(:success?) { true }
describe '#to_hash' do
it 'should parse the "body" as JSON' do
expect(subject.to_hash).to eq(some_key: 'some data')
end
end
describe '#result' do
it 'should return the "body"' do
result = subject.result
expect(result).to eq(body)
end
end
describe 'when the response succeeds' do
describe '#success?' do
it 'should return true' do
expect(subject.success?).to be_truthy
end
end
describe '#fail?' do
it 'should return false' do
expect(subject.fail?).to be_falsey
end
end
describe '#empty?' do
it 'should return false' do
expect(subject.empty?).to be_falsey
end
end
describe 'when endpoint returns an empty response' do
let(:body) { nil }
describe '#empty?' do
it 'should return true' do
expect(subject.empty?).to be_truthy
end
end
end
end
describe 'when the response fails' do
let(:code) { 500 }
let(:success?) { false }
describe '#success?' do
it 'should return false' do
expect(subject.success?).to be_falsey
end
end
describe '#fail?' do
it 'should return true' do
expect(subject.fail?).to be_truthy
end
end
describe '#empty?' do
it 'should return false' do
expect(subject.empty?).to be_falsey
end
end
describe 'when endpoint returns an empty response' do
let(:body) { nil }
describe '#empty?' do
it 'should return false' do
expect(subject.empty?).to be_truthy
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe ProjectsController, type: :controller do
describe "projects#index action" do
it "loads when user is logged in" do
user = FactoryBot.create(:user)
sign_in user
get :index
expect(response).to have_http_status(:success)
end
it "should redirect if no user is logged in" do
get :index
expect(response).to redirect_to new_user_session_path
end
end
describe "projects#create action" do
it "should create a new project in the database" do
user = FactoryBot.create(:user)
sign_in user
post :create, params: { project: { name: 'Hello!', description: 'a description of the job' } }
project = Project.last
expect(project.name).to eq("Hello!")
expect(project.description).to eq('a description of the job')
end
it "should redirect to the root page once form is submitted" do
user = FactoryBot.create(:user)
sign_in user
post :create, params: { project: { name: 'Hello!', description: 'a description of the job' } }
expect(response).to have_http_status(:redirect)
end
it "should redirect if no user is logged in" do
post :create
expect(response).to redirect_to new_user_session_path
end
end
describe "projects#show action" do
it "should show the summary page if a project is found" do
user = FactoryBot.create(:user)
sign_in user
project = FactoryBot.create(:project)
get :show, params: { id: project.id }
expect(response).to have_http_status(:success)
end
it "should redirect to home page if no project is found" do
user = FactoryBot.create(:user)
sign_in user
get :show, params: { id: 'error' }
expect(response).to redirect_to root_path
end
it "should show the sum of the records" do
user = FactoryBot.create(:user)
sign_in user
project_1 = FactoryBot.create(:project, name: "Project 1")
project_2 = FactoryBot.create(:project, name: "Project 2")
FactoryBot.create(:record, duration_of_work: 3, project_id: project_1.id)
FactoryBot.create(:record, duration_of_work: 2.25, project_id: project_2.id)
FactoryBot.create(:record, duration_of_work: 1.75, project_id: project_1.id)
FactoryBot.create(:record, duration_of_work: 0.75, project_id: project_2.id)
get :show, params: { id: project_2.id }
expect(assigns(:summary)).to eq 3.00
end
it "should redirect if no user is logged in" do
project = FactoryBot.create(:project)
get :show, params: { id: project.id }
expect(response).to redirect_to new_user_session_path
end
end
describe "projects#update action" do
it "should make changes to the project name" do
user = FactoryBot.create(:user)
sign_in user
project = FactoryBot.create(:project, name: "Initial Name")
patch :update, params: { id: project, project: { name: 'Changed' } }
expect(response).to have_http_status(:found)
project.reload
expect(project.name).to eq 'Changed'
end
it "should make change to the project description" do
user = FactoryBot.create(:user)
sign_in user
project = FactoryBot.create(:project, description: "Initial Description")
patch :update, params: { id: project, project: { description: 'Changed' } }
expect(response).to have_http_status(:found)
project.reload
expect(project.description).to eq 'Changed'
end
it "should redirect if no user is logged in" do
project = FactoryBot.create(:project, description: "Initial Description")
patch :update, params: { id: project, project: { description: 'Changed' } }
expect(response).to redirect_to new_user_session_path
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
#This is a very incomplete list- features to be added: Logins, accessibility, tasks to be completed later, view of completed tasks, and sorting and filtering of all tasks
starwars = [{:what_am_i => 'Question', :answer_or_question => 'Are you a person?', :node_number => 1},
{:what_am_i => 'Answer', :answer_or_question => 'Obi Wan', :node_number => 2},
{:what_am_i => 'Answer', :answer_or_question => 'X-Wing', :node_number => 3}
]
starwars.each do |task|
Starwar.create!(task)
end |
require_relative '../lib/dropbox_utility'
require 'test/unit'
class TestDropboxUtility < Test::Unit::TestCase
DropboxUtility::authenticate
def test_session
assert_not_nil DropboxUtility::session
end
def test_client
assert_not_nil DropboxUtility::client
end
def test_authentication_file
assert File.exists?(DropboxUtility::Config::AUTH_FILE)
end
def test_delete_authentication_file
DropboxUtility::delete_authentication_file
assert !File.exists?(DropboxUtility::Config::AUTH_FILE)
end
end |
RSpec.feature "Users can mark reports as QA completed" do
context "signed in as a BEIS user" do
let!(:beis_user) { create(:beis_user) }
before { authenticate!(user: beis_user) }
after { logout }
scenario "they can mark a report as QA completed" do
report = create(:report, state: :in_review)
visit report_path(report)
click_link t("action.report.mark_qa_completed.button")
click_button t("default.button.confirm")
expect(page).to have_content "QA completed"
expect(report.reload.state).to eql "qa_completed"
end
context "when the report is already marked as QA completed" do
scenario "it cannot be marked as QA completed" do
report = create(:report, state: :qa_completed)
visit report_path(report)
expect(page).not_to have_link t("action.report.mark_qa_completed.button")
end
end
end
context "signed in as a partner organisation user" do
let(:partner_org_user) { create(:partner_organisation_user) }
before { authenticate!(user: partner_org_user) }
after { logout }
scenario "they cannot mark a report as QA completed" do
report = create(:report, state: :in_review, organisation: partner_org_user.organisation)
visit report_path(report)
expect(page).not_to have_link t("action.report.mark_qa_completed.button")
end
end
end
|
require 'rspec'
require './lib/merchant'
describe Merchant do
it 'exists' do
merchant = Merchant.new({id: "5",name: "Brian",created_at: "10-05-1988",updated_at: "06-03-2021"}, self)
expect(merchant).to be_a(Merchant)
end
it 'has attributes' do
merchant = Merchant.new({id: "5",name: "Brian",created_at: "10-05-1988",updated_at: "06-03-2021"}, self)
expect(merchant.id).to eq(5)
expect(merchant.name).to eq("Brian")
expect(merchant.created_at).to eq("10-05-1988")
expect(merchant.updated_at).to eq("06-03-2021")
expect(merchant.repo).to eq(self)
end
it 'can change name' do
merchant = Merchant.new({id: "5",name: "Brian",created_at: "10-05-1988",updated_at: "06-03-2021"}, self)
expect(merchant.name).to eq("Brian")
merchant.change_name("Ezze")
expect(merchant.name).to eq("Ezze")
end
end
|
class Api::V1::TeamsController < ApplicationController
before_action :get_team, only: [:show, :update, :destroy]
before_action :authenticate_token!, only: [:create, :update, :destroy]
def index
@teams = Team.all.order(:id)
render 'teams/index.json.jbuilder', team: @teams
end
def create
@team = Team.new(team_params)
if @user.admin
if @team.save
render 'teams/show.json.jbuilder', team: @team
else
render json: {
errors: @team.errors
}, status: 400
end
else
render json: {
errors: ["You are not authorized to create new items."]
}
end
end
def show
render 'teams/show.json.jbuilder', team: @team
end
def update
if @user.admin
if @team.update(team_params)
render 'teams/show.json.jbuilder', team: @team
else
render json: {
errors: @team.errors
}, status: 400
end
else
render json: {
errors: ["You are not authorized to modify items."]
}, status: 403
end
end
def destroy
if @user.admin
@team.destroy
render 'teams/show.json.jbuilder', team: @team
else
render json: {
errors: ["You are not authorized to delete items."]
}, status: 403
end
end
def schedule
team = Team.find_by(id: params[:team_id])
@games = team.get_games
render 'teams/schedule.json.jbuilder', games: @games
end
private
def get_team
@team = Team.find_by(id: params[:id])
end
def team_params
params.require(:team).permit(:name, :mascot, :stadium_location, :sub_sport_id)
end
end |
class Income < ApplicationRecord
VALID_USR_REGEX = /USR-[a-zA-z0-9]{8}-[a-zA-z0-9]{4}-[a-zA-z0-9]{4}-[a-zA-z0-9]{4}-[a-zA-z0-9]{12}/
validates :user_guid, presence: true, format: { with: VALID_USR_REGEX }
validates :name, presence: true
validates :date, presence: true
validates :amount, presence: true, numericality: true
end
|
class NodesController < ApplicationController
respond_to :json, :xml
after_filter :set_access_control_header
def set_access_control_header
headers['Access-Control-Allow-Origin'] = '*'
end
def index
respond_with(Node.all_public params[:since], params[:groups])
end
end
|
class AlterRestaurants < ActiveRecord::Migration[5.2]
def up
if column_exists? :restaurants, "cuisine"
remove_column(
:restaurants,
"cuisine"
)
end
end
def down
unless column_exists? :restaurants, "cuisine"
add_column(
:restaurants,
"cuisine",
:string, :null => false
)
end
end
end
|
class Bikes < Netzke::Basepack::Grid
def configure(c)
super
c.model = "Bike"
c.force_fit = true
# columns with :id set, have :min_chars set in init_component
# See: http://stackoverflow.com/questions/17738962/netzke-grid-filtering
c.columns = [
{ :name => :shop_id, :text => 'Shop ID', :default_value => Bike.last.id.to_i + 1},
:serial_number,
{ :id => :bike_brand__brand, :name => :bike_brand__brand, :text => 'Brand'},
{ :name => :model, :text => 'Model',
:scope => lambda { |rel|
if session[:selected_bike_brand_id]
rel.where(:bike_brand_id => session[:selected_bike_brand_id])
else
rel.all
end
}
},
#needs to have type :action or else won't work in grid, because... netzke
{ :name => "color", :text => "Frame Color", :type => :action, :editor => { :xtype => "xcolorcombo"}, :renderer => :color_block,
:default_value => '000000'},
{ :id => :bike_style__style, :name => :bike_style__style, :text => 'Style', :default_value => BikeStyle.first.id},
{ :name => :seat_tube_height, :text => 'Seat Tube (in)'},
{ :name => :top_tube_length, :text => 'Top Tube (in)'},
{ :name => :bike_wheel_size__display_string, :text => 'Wheel Size'},
:value,
{ :id => :bike_condition__condition, :name => :bike_condition__condition, :text => 'Condition', :default_value => BikeCondition.first.id},
{ :id => :bike_purpose__purpose, :name => :bike_purpose__purpose, :text => 'Purpose', :default_value => BikePurpose.first.id},
{ :name => :owner, :getter => lambda { |rec|
user = rec.owner
user.nil? ? "" : "#{user.first_name} #{user.last_name}"
}
}
]
# Default the sorting to ASC on shop_id
c.data_store.sorters = [{ property: 'shop_id', direction: 'ASC' }]
@bike = Bike.all
c.prohibit_update = true if cannot? :update, @bike
c.prohibit_create = true if cannot? :create, @bike
c.prohibit_delete = true if cannot? :delete, @bike
end
def default_fields_for_forms
# :field_label MUST be defined in order for search to work
[
{ :name => :bike_brand__brand, :field_label => 'Brand', :min_chars => 1 },
{ :name => :model, :field_label => 'Model'},
{ :name => :shop_id, :field_label => 'Shop ID'},
{ :name => :serial_number, :field_label => 'Serial Number'},
{ :name => "color", :xtype => "xcolorcombo"},
{ :name => :bike_style__style, :field_label => 'Style', :min_chars => 1},
{ :name => :seat_tube_height, :field_label => 'Seat Tube (in)'},
{ :name => :top_tube_length, :field_label => 'Top Tube (in)'},
{ :name => :bike_wheel_size__display_string, :field_label => 'Wheel Size'},
{ :name => :value, :field_label => 'Value'},
{ :name => :bike_condition__condition, :field_label => 'Condition', :min_chars => 1},
{ :name => :bike_purpose__purpose, :field_label => 'Purpose', :min_chars => 1}
]
end
#override with nil to remove actions
def default_bbar
[ :apply, :add_in_form, :search ]
end
js_configure do |c|
c.mixin :init_component
end
endpoint :select_bike_brand do |params, this|
# store selected boss id in the session for this component's instance
session[:selected_bike_brand_id] = params[:bike_brand_id]
end
end
|
module Scmimport
class Git < Scmimport::Scm
def initialize(config)
super(config)
@fullpath = "#{config['basedirectory']}/#{config['name']}"
end
def updates
if not File.directory?(@fullpath)
@g = Git.clone(config.repourl, name: config.name, path: @fullpath, log: Logger.new(STDOUT))
else
@g = Git.open(@fullpath, log: Logger.new(STDOUT))
end
@g.log.since(@config['last_revision']).each do |commit|
doc = {
author_name: commit.author.name,
author_email: commit.author.email,
date: commit.author.date,
revision: commit.sha
# TODO: add more juicy stuff here including getting some metrics from the diff
}
@config.db.save_doc(doc)
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.