text stringlengths 10 2.61M |
|---|
module Dijit
module Rails
MAJOR = 1
MINOR = 0
TINY = 0
VERSION = [MAJOR, MINOR, TINY].compact.join(".")
end
end
|
class AddUserIdToUserProfile < ActiveRecord::Migration
def change
add_column :user_profiles, :uid, :string
end
end
|
class DejaGnu < Formula
homepage "https://www.gnu.org/software/dejagnu/"
url "http://ftpmirror.gnu.org/dejagnu/dejagnu-1.5.2.tar.gz"
mirror "https://ftp.gnu.org/gnu/dejagnu/dejagnu-1.5.2.tar.gz"
sha1 "20a6c64e8165c1e6dbbe3638c4f737859942c94d"
head "http://git.sv.gnu.org/r/dejagnu.git"
def install
ENV.j1 # Or fails on Mac Pro
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--mandir=#{man}"
# DejaGnu has no compiled code, so go directly to "make check"
system "make", "check"
system "make", "install"
end
test do
system "#{bin}/runtest"
end
end
|
class PigLatinizer
def piglatinize(text)
arr = text.split(' ')
arr.map do |word|
if /^[aeiou]/i.match(word)
word + "way"
else
pig_chars = word.split(/([aeiou].*)/)
"#{pig_chars[1]}#{pig_chars[0]}ay"
end
end.join(' ')
end
end |
require "minitest/autorun"
require "minitest/pride"
require "./lib/linked_list"
class LinkedListTest < Minitest::Test
def test_head_is_nil
list = LinkedList.new
assert_nil list.head
end
def test_adds_a_node
list = LinkedList.new
list.append("doop")
expected = "doop"
actual = list.head.data
assert_equal expected, actual
end
def test_append_set_head_to_new_node
list = LinkedList.new
list.append("doop")
expected = Node
actual = list.head.class
assert_equal expected, actual
end
def test_next_node_equal_nil_when_one_node_exist
list = LinkedList.new
list.append("doop")
assert_nil list.head.next_node
end
def test_next_node_creates_an_object
list = LinkedList.new
list.append("doop")
list.append("deep")
expected = Node
actual = list.head.next_node.class
assert_equal expected, actual
assert_equal "deep", list.head.next_node.data
end
def test_list_can_count
list = LinkedList.new
list.append("doop")
list.append("deep")
expected = 2
actual = list.count
assert_equal expected, actual
end
def test_list_can_turn_into_a_string
list = LinkedList.new
list.append("doop")
list.append("deep")
expected = "doop deep"
actual = list.to_string
assert_equal expected, actual
end
def test_prepending_will_output_data
list = LinkedList.new
assert_equal "dop", list.prepend("dop")
end
def test_prepending_add_string_to_front
# skip
list = LinkedList.new
list.append("plop")
list.append("suu")
list.prepend("dop")
expected = "dop plop suu"
actual = list.to_string
assert_equal expected, actual
end
def test_prepending_creates_node_at_the_front
list = LinkedList.new
list.append("plop")
list.append("suu")
list.prepend("dop")
expected = "dop"
actual = list.head.data
assert_equal expected, actual
end
def test_prepending_creates_node_at_the_front_and_doesnt_destroy_old_nodes
list = LinkedList.new
list.append("plop")
list.append("suu")
list.prepend("dop")
expected = "plop"
actual = list.head.next_node.data
assert_equal expected, actual
end
def test_prepending_doesnt_ruin_count
list = LinkedList.new
list.append("plop")
list.append("suu")
list.prepend("dop")
expected = 3
actual = list.count
assert_equal expected, actual
end
def test_it_inserts_data
list = LinkedList.new
list.append("plop")
list.append("suu")
list.prepend("dop")
list.insert(1, "woo")
expected = "dop woo plop suu"
actual = list.to_string
assert_equal expected, actual
end
def test_list_of_strings
# skip
list = LinkedList.new
list.append("deep")
list.append("woo")
list.append("shi")
list.append("shu")
list.append("blop")
expected = "deep woo shi shu blop"
actual = list.to_string
assert_equal expected, actual
end
def test_it_can_find
list = LinkedList.new
list.append("deep")
list.append("woo")
list.append("shi")
list.append("shu")
list.append("blop")
expected = "shi"
actual = list.find(2,1)
assert_equal expected, actual
assert_equal "woo shi shu", list.find(1,3)
end
def test_check_if_deep_is_included
list = LinkedList.new
list.append("deep")
list.append("woo")
list.append("shi")
list.append("shu")
list.append("blop")
assert_equal true, list.includes?("deep")
end
def test_check_if_dep_is_included
list = LinkedList.new
list.append("deep")
list.append("woo")
list.append("shi")
list.append("shu")
list.append("blop")
assert_equal false, list.includes?("dep")
end
def test_pop_removes_last
list = LinkedList.new
list.append("deep")
list.append("woo")
list.append("shi")
list.append("shu")
list.append("blop")
assert_equal "blop", list.pop
assert_equal "shu", list.pop
assert_equal "deep woo shi" , list.to_string
end
end
|
#fronze_string_literal: true
module ::FormComponent
class TextFieldComponent < BaseInputComponent
def initialize(*)
super
@template = wrapper{|input_options| text_field(input_options) }
end
private
def text_field(method, options={})
super(@object_name, @attribute_name, options)
end
end
end |
require 'spec_helper'
require 'imdb'
require "zimdb"
describe MovieDB do
describe "#get_imdb_movie_data" do
context "Get multiple movie data from IMDb" do
MovieDB::Movie.send(:clear_data_store)
MovieDB::Movie.send(:get_multiple_imdb_movie_data, "0120338", "0120815", "0120915")
#MovieDB::Movie.send(:get_multiple_imdb_movie_data, "0120338")
MovieDB::DataExport.export_movie_data
it "Should return titles" do
MovieDB::Movie.instance_eval{filter_movie_attr("title")}.should == [["Titanic"], ["Saving Private Ryan"], ["Star Wars: Episode I - The Phantom Menace"]]
end
it "Should return directors" do
MovieDB::Movie.instance_eval{filter_movie_attr("director")}.should == [["James Cameron"], ["Steven Spielberg"], ["George Lucas"]]
end
end
end
describe "validation" do
context "invalid id number" do
it "should raise an error" do
# expect {MovieDB::Movie.send(:get_multiple_imdb_movie_data, "9024544")}.to raise_error('invalid imbd id')
end
end
end
end
|
require 'test_helper'
class ResourcesControllerTest < ActionController::TestCase
def setup
@controller.stub! :oauth_handshake, :return => true
end
test "should get index" do
get :index
assert_response :success, @response.body
assert_not_nil assigns(:resources)
end
end
|
class CreateSnacks < ActiveRecord::Migration
def change
create_table :snacks do |t|
t.integer :product_id
t.datetime :manufacture_date
t.datetime :best_before
t.string :brand
t.string :production_place
t.string :ingredient
t.string :weight
t.timestamps null: false
end
end
end
|
module GroupsHelper
def is_current_owner_logged_in?(owned)
current_user && current_user == owned.user
end
def is_current_user_belongs_to?(group)
current_user && current_user.is_member_of?(group)
end
def render_group_description(group)
simple_format(group.description)
end
end
|
require 'spec_helper'
module Alf
module Support
describe TupleScope, "to_s and inspect" do
let(:tuple){ {:a => 1, :b => 2} }
context 'with a simple TupleScope' do
let(:scope){ TupleScope.new(tuple) }
it "delegates to_s to the tuple" do
expect(scope.to_s).to eq(tuple.to_s)
end
it "delegates to the tuple" do
expect(scope.inspect).to eq(tuple.inspect)
end
end
end
end
end
|
class ContactsController < InheritedResources::Base
before_action :set_contact , only: [:show, :edit, :update, :destroy]
def index
@contacts = Contact.all
end
def show
end
def new
@contact = Contact.new
end
def edit
end
def create
@contact = Contact.new(contact_params)
respond_to do |format|
if @contact.save
ContactMailer.registration_confimation(@contact).deliver
format.html{ redirect_to @contact, notice: 'Contact was successfully created.' }
format.json{ render :show , status: :created, location: @contact }
else
format.html{ render :new }
format.json{ render :json , @contact.errors, status: :unprocessable_entiry}
end
end
end
private
def set_contact
@contact = Contact.find(params[:id])
end
def contact_params
params.require(:contact).permit(:name, :email, :message)
end
end
|
#!/usr/bin/env ruby
TEST_DIR = File.expand_path(File.dirname(__FILE__))
TOP_SRC_DIR = File.join(TEST_DIR, '..')
require File.join(TOP_SRC_DIR, 'lib', 'tracelines19.rb')
def dump_file(file, opts)
puts file
begin
fp = File.open(file, 'r')
rescue Errno::ENOENT
puts "File #{file} is not readable."
return
end
lines = fp.read
if opts[:print_source]
puts '=' * 80
puts lines
end
if opts[:print_parse]
puts '=' * 80
cmd = "#{File.join(TEST_DIR, 'parse-show.rb')} #{file}"
system(cmd)
end
if opts[:print_trace]
require 'tracer'
puts '=' * 80
tracer = Tracer.new
tracer.add_filter lambda {|event, f, line, id, binding, klass|
__FILE__ != f && event == 'line'
}
tracer.on{load(file)}
end
expected_lnums = nil
if opts[:expect_line]
fp.rewind
first_line = fp.readline.chomp
expected_str = first_line[1..-1]
begin
expected_lnums = eval(expected_str, binding, __FILE__, __LINE__)
rescue SyntaxError
puts '=' * 80
puts "Failed reading expected values from #{file}"
end
end
fp.close()
got_lnums = TraceLineNumbers.lnums_for_str(lines)
if expected_lnums
puts "expecting: #{expected_lnums.inspect}"
puts '-' * 80
if expected_lnums
if got_lnums != expected_lnums
puts "mismatch: #{got_lnums.inspect}"
else
puts 'Got what was expected.'
end
else
puts got_lnums.inspect
end
else
puts got_lnums.inspect
end
end
require 'getoptlong'
program = File.basename($0)
opts = {
:print_source => true, # Print source file?
:print_trace => true, # Run Tracer over file?
:expect_line => true, # Source file has expected (correct) list of lines?
:print_parse => true, # Show ParseTree output?
}
getopts = GetoptLong.new(
[ '--expect', '-e', GetoptLong::NO_ARGUMENT ],
[ '--no-expect', '-E', GetoptLong::NO_ARGUMENT ],
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--parse', '-p', GetoptLong::NO_ARGUMENT ],
[ '--no-parse', '-P', GetoptLong::NO_ARGUMENT ],
[ '--source', '-s', GetoptLong::NO_ARGUMENT ],
[ '--no-source', '-S', GetoptLong::NO_ARGUMENT ],
[ '--trace', '-t', GetoptLong::NO_ARGUMENT ],
[ '--no-trace', '-T', GetoptLong::NO_ARGUMENT ])
getopts.each do |opt, arg|
case opt
when '--help'
puts "usage
Usage: #{$program} [options] file1 file2 ...
Diagnostic program to make see what TraceLineNumbers does and compare
against other output.
options:
-e --expect Read source file expected comment (default)
-E --no-expect Don't look for source file expected comment
-p --parse Show ParseTree Output (default)
-P --no-parse Don't show ParseTree output
-s --source Show source file (default)
-S --no-source Don't print source
-t --trace Show Tracer output (default)
-T --no-trace Don't show Tracer output
"
when '--expect'
opts[:expect_line] = true
when '--no-expect'
opts[:expect_line] = false
when '--parse'
opts[:print_parse] = true
when '--no-parse'
opts[:print_parse] = false
when '--source'
opts[:print_source] = true
when '--no-source'
opts[:print_source] = false
when '--trace'
opts[:print_trace] = true
when '--no-trace'
opts[:print_trace] = false
else
puts "Unknown and ignored option #{opt}"
end
end
ARGV.each do |file|
dump_file(file, opts)
end
|
class TranslationEvent < ApplicationRecord
has_many :translations
end
|
# frozen_string_literal: true
RSpec.describe Storages::BuilderFactory, type: :factory do
subject(:factory) { described_class.new }
describe '.create_for' do
subject(:create_for) { factory.create_for(storage_name) }
context 'when storage builder does exists' do
let(:storage_name) { 'google_sheets' }
it { is_expected.to be_instance_of(Storages::GoogleSheetsBuilder) }
end
end
end
|
class UpdateContentPages < ActiveRecord::Migration
def self.up
rename_column :content_pages, :name, :title
remove_column :content_pages, :page_type
rename_column :content_pages, :page_locale, :locale
add_column :content_pages, :body_raw, :text, :default => ''
add_column :content_pages, :contentable_id, :integer
add_column :content_pages, :contentable_type, :string
end
def self.down
rename_column :content_pages, :title, :name
remove_column :content_pages, :body_raw
remove_column :content_pages, :contentable_id
remove_column :content_pages, :contentable_type
add_column :content_pages, :page_type, :string
rename_column :content_pages, :locale, :page_locale
end
end |
require "test_helper"
class LocalTransactionPresenterTest < ActiveSupport::TestCase
def subject(content_item)
LocalTransactionPresenter.new(content_item.deep_stringify_keys!)
end
test "#introduction" do
assert_equal "foo", subject(details: { introduction: "foo" }).introduction
end
test "#more_information" do
assert_equal "foo", subject(details: { more_information: "foo" }).more_information
end
test "#need_to_know" do
assert_equal "foo", subject(details: { need_to_know: "foo" }).need_to_know
end
end
|
# Make sure we’re using the latest Homebrew
update
# Add taps
tap "homebrew/bundle"
tap "homebrew/cask"
tap "homebrew/cask-fonts"
tap "homebrew/core"
tap "homebrew/services"
tap "koekeishiya/formulae"
# Core utilities
brew "python"
brew "git"
brew "gnu-tar"
brew "gnutls"
brew "stow"
brew "make"
brew "tmux"
brew "vim"
brew "wget"
# Usability
brew "koekeishiya/formulae/yabai"
brew "koekeishiya/formulae/skhd"
cask "kitty"
cask "font-source-code-pro"
cask "zerotier-one"
# cask "hyperswitch"
# cask "spectacle"
# Core apps
cask "1password"
cask "google-chrome"
cask "wavebox"
cask "marshallofsound-google-play-music-player"
# Useful utilities
brew "htop"
brew "sshfs"
brew "subversion"
brew "tree"
brew "ranger"
brew "ctags"
brew "dduan/formulae/tre"
brew "keith/formulae/tag"
# Useful apps
cask "balenaetcher"
cask "transmission"
cask "virtualbox"
cask "vlc"
# Creative apps
cask "spotify"
cask "musescore"
cask "gimp"
cask "bitwig-studio"
# Language support
brew "node"
brew "opam"
brew "haskell-stack"
# Publishing
cask "microsoft-office"
cask "mactex"
brew "pandoc"
brew "graphviz"
brew "librsvg"
# Remove outdated versions from the cellar
cleanup
|
When /^I run the rake task '(.+?)' with '(.*?)' as parameters$/ do |task_name, params|
args = params.split(',')
@rake_output = run_rake_task(task_name, *args)
end
When /^I run the rake task '(.+?)'$/ do |task_name|
@rake_output = run_rake_task(task_name)
end
Then /^the contents of STDOUT should contain '(.*?)'$/ do |expected_content|
@rake_output.stdout.include? expected_content
end
Then /^the task should have taken '(\d+?)' seconds$/ do |expected_time|
@rake_output.time.to_i == expected_time.to_i
end
|
class Api::V1::TripsController < ApplicationController
def index
render json: session_user.trips
end
def show
trip = Trip.find(params[:id])
render json: trip
end
def create
creator = User.find(trip_params[:creator_id])
trip = Trip.create(trip_params)
trip.users.push(creator)
userTrip = UserTrip.where(trip_id: trip.id)
render json: {trip: TripSerializer.new(trip), user_trip: userTrip}
end
def update
trip = Trip.find(params[:id])
trip.update(trip_params)
render json: trip
end
def destroy
trip = Trip.find(params[:id])
itins = trip.user_trips.map {|user_trip| user_trip.itineraries }.flatten
itins_destinations = itins.map {|itin| itin.itinerary_destinations }.flatten
user_trips = trip.user_trips.map {|user_trip| user_trip}
users = trip.users.map {|user| user}
comments = trip.comments.map {|comment| comment}
expenses = trip.expenses.map {|expense| expense}
todos = trip.todos.map {|todo| todo}
tripData = {
id: trip.id,
creator_id: trip.creator_id,
description: trip.description,
end_date: trip.end_date,
start_date: trip.start_date,
title: trip.title,
user_trips: user_trips,
users: users,
comments: comments,
expenses: expenses,
todos: todos
}
objects_to_delete = {
trip: tripData,
itineraries: itins,
itinerary_destinations: itins_destinations
}
itins.each {|itin| itin.destroy}
itins_destinations.each {|itinDes| itinDes.destroy}
trip.destroy
render json: objects_to_delete
end
def add_users
trip = Trip.find(params[:id])
add_users_to_trips = params[:usersToAdd].map {|user| User.find(user)}
add_users_to_trips.each {|user| trip.users.push(user)}
new_users = add_users_to_trips.map {|user| user.id}
add_user_trips_to_users = new_users.map {|user| UserTrip.where(trip_id: trip.id, user_id: user)[0]}
render json: {tripId: trip.id, newUsers: new_users, newUserTrips: add_user_trips_to_users.map {|userTrip| userTrip}}
end
private
def trip_params
params.require(:trip).permit(:start_date, :end_date, :title, :description, :creator_id)
end
end
|
require 'rails_helper'
describe Api::V1::TournamentsController do
let(:tournament_params) do
{ tournament_name: 'football_it_league', team_names: %w[M.City M.United Arsenal Chelsea] }
end
describe 'POST#create' do
it 'has to be success' do
process :create,
method: :post,
format: :json,
params: tournament_params
expect_status('200')
end
end
end
|
module Apicast
GENERATORS = [
Apicast::LuaAuthorizeGenerator,
Apicast::LuaGetTokenGenerator,
Apicast::LuaThreescaleUtilsGenerator,
Apicast::LuaAuthorizedCallbackGenerator
].map(&:new).freeze
end
|
class Item < ApplicationRecord
has_many :documents
attr_accessor :document_data
end
|
class Round < ApplicationRecord
belongs_to :game
belongs_to :question
belongs_to :answer
end
|
class GoodsController < ApplicationController
def index
@goods = Good.all
end
def new
@good = Good.new
end
def create
@good = Good.create(good_params)
redirect_to root_path
end
def show
id = params[:id]
@good = Good.find(id)
end
def edit
@good = Good.find(params[:id])
end
def update
@good = Good.find(params[:id])
@good.update_attributes!(good_params)
redirect_to root_path
end
def destroy
id = params[:id]
good = Good.find(id)
good.destroy
redirect_to root_path
end
private
def good_params
params.require(:good).permit(:name)
end
end |
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc.
# Authors: Adam Lebsack <adam@holonyx.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
module Restore::Worker
module_require_dependency :filesystem, 'worker'
class Sftp < Restore::Worker::Filesystem
require 'net/ssh'
require 'net/sftp'
class << self
# install the public ssh key on the server
def install_key(hostname, port, username, password, pubkey)
err = nil
Net::SSH.start( hostname, port, username, password, :paranoid => false) do |session|
shell = session.shell.open
shell.mkdir "-p ~/.ssh"
shell.echo "-n '#{pubkey}' >> ~/.ssh/authorized_keys2"
shell.exit
# give the above commands sufficient time to terminate
sleep 0.5
#err = shell.stderr if shell.stderr? && shell.stderr != "stdin: is not a tty\n"
end
raise err unless err.nil?
return {:installed => true}
end
# get a directory listing.
def list_directory(path, target_options)
children = []
begin
if target_options['password']
Net::SFTP.start(target_options['hostname'], target_options['extra'][:port].to_i, target_options['username'], target_options['password'], :paranoid => false) do |sftp|
children = list_directory2(sftp, path)
end
else
setup_keys(target_options['extra'][:key], target_options['extra'][:pubkey]) do |key_path|
Net::SFTP.start(target_options['hostname'], target_options['extra'][:port].to_i, target_options['username'], :paranoid => false, :keys => [key_path]) do |sftp|
children = list_directory2(sftp, path)
end
end
end
rescue Net::SSH::AuthenticationFailed => e
raise "Authentication failed"
end
return {:children => children, :loaded => true}
end # def list_directory
protected
def setup_keys(key, pubkey, &block)
t = Tempfile.new('id_rsa')
t.write key
t.close
pub = t.path+".pub"
File.open(pub, "w") do |f|
f.write pubkey
end
begin
yield t.path
ensure
t.unlink
File.unlink(pub)
end
end
def list_directory2(sftp, path)
children = []
handle = sftp.opendir('/'+path)
sftp.readdir(handle).each do |f|
f.filename == '.' and next
f.filename == '..' and next
stat = sftp.lstat("#{path}/#{f.filename}")
#logger.info "#{path}/#{f.filename}"
#logger.info stat.mtime.inspect
mtime = Time.at(stat.mtime) rescue nil
children << {
:filename => f.filename,
:type => parse_type(stat.permissions),
:size => stat.size,
:mtime => mtime
}
end
return children
end
def parse_type(perm)
if((perm & 0140000) == 0140000) # socket
return 'S'
elsif((perm & 0120000) == 0120000) # symlink
return 'L'
elsif((perm & 0100000) == 0100000) # regular file
return 'F'
elsif((perm & 060000) == 060000) # block device
return 'B'
elsif((perm & 040000) == 040000) # directory
return 'D'
elsif((perm & 020000) == 020000) # character device
return 'C'
elsif((perm & 010000) == 010000) # fifo
return 'I'
end
raise "could not determine file type"
end
end # class << self
end # class Sftp
end # module Restore::Worker |
# == Schema Information
#
# Table name: channels
#
# id :integer not null, primary key
# name :string(255)
# url :string(255)
# not_in_id :boolean
# slug :string(255)
# image :string(255)
# description :text
# time_zone_id :integer default(1), not null
#
require 'digest/md5'
require_relative 'channel_blocking'
require_relative 'channel_blocking_period'
class Channel < ActiveRecord::Base
belongs_to :time_zone
has_many :show_programs, :dependent => :delete_all
has_many :channel_blockings, :dependent => :delete_all
attr_accessible :id, :name, :url, :slug, :not_in_id, :description,
:time_zone_id,
:image, :image_cache, :remove_image,
:embed,
:background, :background_cache, :remove_background,
:embed_logo_watermark, :embed_logo_watermark_cache, :remove_embed_logo_watermark,
:top_banner, :right_banner, :stretch_button, #je09213urF
:embed_free_player, :embed_restricted_player,
:embed_free_preroll_ads, :embed_restricted_preroll_ads, :homepage_preroll_ads,
:embed_free_midroll_ads, :embed_restricted_midroll_ads, :homepage_midroll_ads,
:show_on_mobile,
:hls_mobile_url, :hls_mobile_id_url,
:rtsp_mobile_url, :rtsp_mobile_id_url,
:rtsp_mobile_url_hd, :rtsp_mobile_id_url_hd,
:hls_mobile_url_hd, :hls_mobile_id_url_hd,
:mobile_preroll_ads,
:embed_free_midroll_period, :embed_restricted_midroll_period, :homepage_midroll_period,
:embed_free_video_ads_in_id, :embed_restricted_video_ads_in_id, :homepage_video_ads_in_id, :mobile_video_ads_in_id,
:mobile_midroll_ads, :mobile_midroll_period
validates :name, :url, :slug, :presence => true, :uniqueness => true
def key
url ? Digest::MD5.hexdigest(url) : ''
end
end |
class AddSuffixToVariants < ActiveRecord::Migration
def change
change_table :variants do |t|
t.string :suffix, null: false, default: ''
end
end
end
|
module AppUp
class Repo < Struct.new(:shell, :options)
private :shell, :options
def files
ignores = options.has_key?(:ingore) ? options[:ignore] : Configuration::Config.ignore
default_files.reject {|f| ignores.any? {|i| f.match(i)} }
end
private
def default_files
if options[:diff]
diff(*options[:diff])
else
all
end
end
def all
shell.run "git ls-tree --full-tree -r HEAD --name-only"
end
def diff(start_sha, end_sha)
shell.run "git diff --name-only #{start_sha} #{end_sha}"
end
end
end
|
# encoding: utf-8
require 'spec/helper'
require 'minitest/spec'
require 'minitest/autorun'
require 'interval-tree'
describe "IntervalTree::Node" do
describe '.new' do
describe 'given ([], [], [], [])' do
it 'returns a Node object' do
IntervalTree::Node.new([], [], [], []).must_be_instance_of(IntervalTree::Node)
end
end
end
end
describe "IntervalTree::ExclusiveTree" do
describe '#center' do
describe 'given [(1...5),]' do
it 'returns 1' do
itvs = [(1...5),]
t = IntervalTree::ExclusiveTree.new([])
t.__send__(:center, itvs).must_equal 1
end
end
end
end
describe "IntervalTree::InclusiveTree" do
describe '#center' do
describe 'given [(1..4),]' do
it 'returns 1' do
itvs = [(1..4),]
t = IntervalTree::ExclusiveTree.new([])
t.__send__(:center, itvs).must_equal 1
end
end
end
end
|
Given /^I am logged in$/ do
visit "/"
end
When /^I click "(.*?)"$/ do |arg1|
click_link(arg1)
end
When /^I press "(.*?)"$/ do |arg1|
click_button(arg1)
end
When /^I fill in "(.*?)" with "(.*?)"$/ do |arg1, arg2|
fill_in(arg1, :with => arg2)
end
Then /^I should see "(.*?)"$/ do |arg1|
page.has_content?(arg1)
end
Given /^there is a game called "(.*?)"$/ do |arg1|
Factory(:game, :name=> arg1)
end
When /^I follow "(.*?)"$/ do |arg1|
click_link(arg1)
end
Then /^I should be on the game page for "(.*?)"$/ do |arg1|
visit game_path(:arg1)
end |
class AgencyArtist < ApplicationRecord
has_many :agency_artist_songs
belongs_to :agency
end
|
require 'spec_helper'
describe DeploymentTargetSerializer do
let(:deployment_target_model) { DeploymentTarget.new }
subject(:serialized) { described_class.new(deployment_target_model).as_json }
it 'exposes the attributes to be jsonified' do
expected_keys = [
:id,
:name,
:endpoint_url,
:auth_blob,
:metadata
]
expect(serialized.keys).to match_array expected_keys
expect(serialized[:metadata]).to be_nil
end
describe "metadata" do
subject { serialized[:metadata] }
context "with no associated metadata" do
it { should be_nil }
end
context "with associated metadata" do
fixtures :deployment_targets, :deployment_target_metadata
let(:deployment_target_model) { deployment_targets(:target_with_metadata) }
its([:id]) { should eq(deployment_target_metadata(:metadata1).id) }
end
end
end
|
# encoding: utf-8
require 'spec_helper'
describe Mail::Field do
describe "initialization" do
it "should be instantiated" do
expect {Mail::Field.new('To: Mikel')}.not_to raise_error
expect(Mail::Field.new('To: Mikel').field.class).to eq Mail::ToField
end
it "should allow you to init on an array" do
field = Mail::Field.new("To", ['test1@lindsaar.net', 'Mikel <test2@lindsaar.net>'])
expect(field.addresses).to eq ["test1@lindsaar.net", "test2@lindsaar.net"]
end
it "should allow us to pass an empty value" do
expect {Mail::Field.new('To')}.not_to raise_error
expect(Mail::Field.new('To').field.class).to eq Mail::ToField
end
it "should allow us to pass a value" do
expect {Mail::Field.new('To', 'Mikel')}.not_to raise_error
expect(Mail::Field.new('To', 'Mikel').field.class).to eq Mail::ToField
end
it "should match up fields to class names" do
structured_fields = %w[ Date From Sender Reply-To To Cc Bcc Message-ID In-Reply-To
References Keywords Resent-Date Resent-From Resent-Sender
Resent-To Resent-Cc Resent-Bcc Resent-Message-ID
Return-Path Received Subject Comments Mime-Version
Content-Transfer-Encoding Content-Description
Content-Disposition Content-Type ]
structured_fields.each do |sf|
words = sf.split("-").map { |a| a.capitalize }
klass = "#{words.join}Field"
expect(Mail::Field.new("#{sf}: ").field.class).to eq Mail.const_get(klass)
end
end
it "should match up fields to class names regardless of case" do
structured_fields = %w[ dATE fROM sENDER REPLY-TO TO CC BCC MESSAGE-ID IN-REPLY-TO
REFERENCES KEYWORDS resent-date resent-from rESENT-sENDER
rESENT-tO rESent-cc resent-bcc reSent-MESSAGE-iD
rEtURN-pAtH rEcEiVeD Subject Comments Mime-VeRSIOn
cOntenT-transfer-EnCoDiNg Content-Description
Content-Disposition cOnTENt-TyPe ]
structured_fields.each do |sf|
words = sf.split("-").map { |a| a.capitalize }
klass = "#{words.join}Field"
expect(Mail::Field.new("#{sf}: ").field.class).to eq Mail.const_get(klass)
end
end
it "should say anything that is not a known field is an optional field" do
unstructured_fields = %w[ Too Becc bccc Random X-Mail MySpecialField ]
unstructured_fields.each do |sf|
expect(Mail::Field.new("#{sf}: Value").field.class).to eq Mail::OptionalField
end
end
it "should split the name and values out of the raw field passed in" do
field = Mail::Field.new('To: Bob')
expect(field.name).to eq 'To'
expect(field.value).to eq 'Bob'
end
it "should split the name and values out of the raw field passed in if missing whitespace" do
field = Mail::Field.new('To:Bob')
expect(field.name).to eq 'To'
expect(field.value).to eq 'Bob'
end
it "should split the name and values out of the raw field passed in if having added inapplicable whitespace" do
field = Mail::Field.new('To : Bob ')
expect(field.name).to eq 'To'
expect(field.value).to eq 'Bob'
end
it "should return an unstuctured field if the structured field parsing raises an error" do
expect(Mail::ToField).to receive(:new).and_raise(Mail::Field::ParseError.new(Mail::ToField, 'To: Bob, ,,, Frank, Smith', "Some reason"))
field = Mail::Field.new('To: Bob, ,,, Frank, Smith')
expect(field.field.class).to eq Mail::UnstructuredField
expect(field.name).to eq 'To'
expect(field.value).to eq 'Bob, ,,, Frank, Smith'
end
it "should call to_s on its field when sent to_s" do
@field = Mail::SubjectField.new('Subject: Hello bob')
expect(Mail::SubjectField).to receive(:new).and_return(@field)
expect(@field).to receive(:to_s).once
Mail::Field.new('Subject: Hello bob').to_s
end
it "should pass missing methods to its instantiated field class" do
field = Mail::Field.new('To: Bob')
expect(field.field).to receive(:addresses).once
field.addresses
end
it "should respond_to? its own methods and the same methods as its instantiated field class" do
field = Mail::Field.new('To: Bob')
expect(field.respond_to?(:field)).to be_truthy
expect(field.field).to receive(:"respond_to?").once
field.respond_to?(:addresses)
end
it "should change its type if you change the name" do
field = Mail::Field.new("To: mikel@me.com")
expect(field.field.class).to eq Mail::ToField
field.value = "bob@me.com"
expect(field.field.class).to eq Mail::ToField
end
it "should create a field without trying to parse if given a symbol" do
field = Mail::Field.new('Message-ID')
expect(field.field.class).to eq Mail::MessageIdField
end
it "should inherit charset" do
charset = 'iso-2022-jp'
field = Mail::Field.new('Subject: こんにちは', charset)
expect(field.charset).to eq charset
end
it "should not strip out content that looks like the field name" do
pending "pr#766"
field = Mail::Field.new('Subject: subject: for your approval')
expect(field.value).to eq 'subject: for your approval'
end
end
describe "error handling" do
it "should populate the errors array if it finds a field it can't deal with" do
field = Mail::Field.new('Content-Transfer-Encoding: 8@bit')
expect(field.field.errors.size).to eq 1
expect(field.field.errors[0][0]).to eq 'Content-Transfer-Encoding'
expect(field.field.errors[0][1]).to eq '8@bit'
expect(field.field.errors[0][2].to_s).to match(/ContentTransferEncodingElement can not parse |17-bit|/)
end
end
describe "helper methods" do
it "should reply if it is responsible for a field name as a capitalized string - structured field" do
field = Mail::Field.new("To: mikel@test.lindsaar.net")
expect(field.responsible_for?("To")).to be_truthy
end
it "should reply if it is responsible for a field as a lower case string - structured field" do
field = Mail::Field.new("To: mikel@test.lindsaar.net")
expect(field.responsible_for?("to")).to be_truthy
end
it "should reply if it is responsible for a field as a symbol - structured field" do
field = Mail::Field.new("To: mikel@test.lindsaar.net")
expect(field.responsible_for?(:to)).to be_truthy
end
it "should say it is the \"same\" as another if their field types match" do
expect(Mail::Field.new("To: mikel").same(Mail::Field.new("To: bob"))).to be_truthy
end
it "should say it is not the \"same\" as another if their field types don't match" do
expect(Mail::Field.new("To: mikel").same(Mail::Field.new("From: mikel"))).to be_falsey
end
it "should say it is not the \"same\" as nil" do
expect(Mail::Field.new("To: mikel").same(nil)).to be_falsey
end
it "should say it is == to another if their field and names match" do
expect(Mail::Field.new("To: mikel")).to eq(Mail::Field.new("To: mikel"))
end
it "should say it is not == to another if their field names do not match" do
expect(Mail::Field.new("From: mikel")).not_to eq(Mail::Field.new("To: bob"))
end
it "should say it is not == to another if their field names match, but not their values" do
expect(Mail::Field.new("To: mikel")).not_to eq(Mail::Field.new("To: bob"))
end
it "should say it is not == to nil" do
expect(Mail::Field.new("From: mikel")).not_to eq(nil)
end
it "should sort according to the field order" do
list = [Mail::Field.new("To: mikel"), Mail::Field.new("Return-Path: bob")]
expect(list.sort[0].name).to eq "Return-Path"
end
end
describe 'user defined fields' do
it "should say it is the \"same\" as another if their field names match" do
expect(Mail::Field.new("X-Foo: mikel").same(Mail::Field.new("X-Foo: bob"))).to be_truthy
end
it "should say it is not == to another if their field names do not match" do
expect(Mail::Field.new("X-Foo: mikel")).not_to eq(Mail::Field.new("X-Bar: bob"))
end
end
describe "passing an encoding" do
it "should allow you to send in unencoded strings to fields and encode them" do
subject = Mail::SubjectField.new("This is あ string", 'utf-8')
expect(subject.encoded).to eq "Subject: =?UTF-8?Q?This_is_=E3=81=82_string?=\r\n"
expect(subject.decoded).to eq "This is あ string"
end
it "should allow you to send in unencoded strings to address fields and encode them" do
to = Mail::ToField.new('"Mikel Lindsああr" <mikel@test.lindsaar.net>', 'utf-8')
expect(to.encoded).to eq "To: =?UTF-8?B?TWlrZWwgTGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>\r\n"
end
it "should allow you to send in unencoded strings without quotes to address fields and encode them" do
to = Mail::ToField.new('Mikel Lindsああr <mikel@test.lindsaar.net>', 'utf-8')
expect(to.encoded).to eq "To: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>\r\n"
end
it "should allow you to send in unencoded strings to address fields and encode them" do
to = Mail::ToField.new("あdあ <ada@test.lindsaar.net>", 'utf-8')
expect(to.encoded).to eq "To: =?UTF-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\r\n"
end
it "should allow you to send in multiple unencoded strings to address fields and encode them" do
to = Mail::ToField.new(["Mikel Lindsああr <mikel@test.lindsaar.net>", "あdあ <ada@test.lindsaar.net>"], 'utf-8')
expect(to.encoded).to eq "To: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>, \r\n\s=?UTF-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\r\n"
end
it "should allow you to send in multiple unencoded strings to any address field" do
mail = Mail.new
mail.charset = 'utf-8'
array = ["Mikel Lindsああr <mikel@test.lindsaar.net>", "あdあ <ada@test.lindsaar.net>"]
field = Mail::ToField.new(array, 'utf-8')
expect(field.encoded).to eq "#{Mail::ToField::CAPITALIZED_FIELD}: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>, \r\n\s=?UTF-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\r\n"
field = Mail::FromField.new(array, 'utf-8')
expect(field.encoded).to eq "#{Mail::FromField::CAPITALIZED_FIELD}: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>, \r\n\s=?UTF-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\r\n"
field = Mail::CcField.new(array, 'utf-8')
expect(field.encoded).to eq "#{Mail::CcField::CAPITALIZED_FIELD}: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>, \r\n\s=?UTF-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\r\n"
field = Mail::ReplyToField.new(array, 'utf-8')
expect(field.encoded).to eq "#{Mail::ReplyToField::CAPITALIZED_FIELD}: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>, \r\n\s=?UTF-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\r\n"
end
it "should allow an encoded value in the Subject field and decode it automatically (issue 44)" do
skip if RUBY_VERSION < '1.9'
subject = Mail::SubjectField.new("=?ISO-8859-1?Q?2_=FAlt?=", 'utf-8')
expect(subject.decoded).to eq "2 últ"
end
it "should allow you to encoded text in the middle (issue 44)" do
skip if RUBY_VERSION < '1.9'
subject = Mail::SubjectField.new("ma=?ISO-8859-1?Q?=F1ana?=", 'utf-8')
expect(subject.decoded).to eq "mañana"
end
it "more tolerable to encoding definitions, ISO (issue 120)" do
skip if RUBY_VERSION < '1.9'
subject = Mail::SubjectField.new("ma=?ISO88591?Q?=F1ana?=", 'utf-8')
expect(subject.decoded).to eq "mañana"
end
it "more tolerable to encoding definitions, ISO-long (issue 120)" do
# Rubies under 1.9 don't handle encoding conversions
skip if RUBY_VERSION < '1.9'
# TODO: JRuby 1.7.0 has an encoding issue https://jira.codehaus.org/browse/JRUBY-6999
skip if defined?(JRUBY_VERSION) && JRUBY_VERSION >= '1.7.0'
subject = Mail::SubjectField.new("=?iso2022jp?B?SEVBUlQbJEIkSiQ0TyJNbRsoQg?=", 'utf-8')
expect(subject.decoded).to eq "HEARTなご連絡"
end
it "more tolerable to encoding definitions, UTF (issue 120)" do
to = Mail::ToField.new("=?utf-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>", 'utf-8')
expect(to.encoded).to eq "To: =?utf-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\r\n"
expect(to.decoded).to eq "\"あdあ\" <ada@test.lindsaar.net>"
end
it "more tolerable to encoding definitions, ISO (issue 120)" do
subject = Mail::SubjectField.new("=?UTF-8?B?UmU6IHRlc3QgZW52w61vIG1lbnNhamUgY29u?=", 'utf-8')
expect(subject.decoded).to eq "Re: test envío mensaje con"
end
it "more tolerable to encoding definitions, Windows (issue 120)" do
skip if RUBY_VERSION < '1.9'
# TODO: JRuby 1.7.0 has an encoding issue https://jira.codehaus.org/browse/JRUBY-6999
skip if defined?(JRUBY_VERSION) && JRUBY_VERSION >= '1.7.0'
subject = Mail::SubjectField.new("=?Windows1252?Q?It=92s_a_test=3F?=", 'utf-8')
expect(subject.decoded).to eq "It’s a test?"
end
it "should support ascii encoded utf-8 subjects" do
s = "=?utf-8?Q?simp?= =?utf-8?Q?le_=E2=80=93_dash_=E2=80=93_?="
subject = Mail::SubjectField.new(s, 'utf-8')
expect(subject.decoded).to eq("simple – dash – ")
end
it "should support ascii encoded windows subjects" do
skip if RUBY_VERSION < '1.9'
# TODO: JRuby 1.7.0 has an encoding issue https://jira.codehaus.org/browse/JRUBY-6999
skip if defined?(JRUBY_VERSION) && JRUBY_VERSION >= '1.7.0'
s = "=?WINDOWS-1252?Q?simp?= =?WINDOWS-1252?Q?le_=96_dash_=96_?="
subject = Mail::SubjectField.new(s, "UTF-8")
expect(subject.decoded).to eq("simple – dash – ")
end
end
describe Mail::Field::ParseError do
it "should be structured" do
error = nil
begin
Mail::DateTimeElement.new("invalid")
rescue Mail::Field::ParseError => e
error = e
end
expect(error).not_to be_nil
expect(error.element).to eq Mail::DateTimeElement
expect(error.value).to eq "invalid"
expect(error.reason).not_to be_nil
end
end
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "blue_shoes/version"
Gem::Specification.new do |s|
s.name = "blue_shoes"
s.version = BlueShoes::VERSION
s.authors = ["Team Shoes", "Steve Klabnik"]
s.email = "shoes@librelist.com"
s.homepage = "http://github.com/hacketyhack/blue_shoes"
s.summary = %q{A simple GUI toolkit.}
s.description = %q{Blue Shoes is a fork of Shoes, written with QT.}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency "qtbindings", "~> 4.6.3.0"
end
|
class ArticleController < ApplicationController
before_action :authorize_request
# GET /articles
def index
@articles = Article.all
render json: @articles, include: {user: {only: [:name]}}, status: :ok
end
# GET /articles/:id
def show
@article = Article.find(params[:id])
render json: @article, include: {user: {only: [:name]}}, status: :ok
rescue ActiveRecord::RecordNotFound
render json: { errors: 'Article not found' }, status: :not_found
end
# POST /articles
def create
@user = User.find(params[:user_id])
@article = Article.new(:user => @user, :title => params[:title], :description => params[:description])
if @article.save
render json: @article, status: :ok
else
render json: { errors: @article.errors.full_messages },
status: :unprocessable_entity
end
rescue ActiveRecord::RecordNotFound
render json: { errors: 'User not found' }, status: :not_found
end
# PUT /articles/:id
def update
@article = Article.find(params[:id])
if @article.update(article_params)
render json: { msg: "updated"}, status: :ok
else
render json: { errors: @article.errors.full_messages }, status: :unprocessable_entity
end
rescue ActiveRecord::RecordNotFound
render json: { errors: 'User not found' }, status: :not_found
end
# DELETE /articles/:id
def destroy
if Article.destroy(params[:id])
render json: { msg: "deleted"}, status: :ok
else
render json: { errors: @article.errors.full_messages }, status: :unprocessable_entity
end
end
private
def article_params
params.permit(:title, :description)
end
end
|
require 'rails_helper'
RSpec.describe IdentifierController, type: :controller do
before do
@company = FactoryGirl.create :company
@recruiter = FactoryGirl.create :recruiter
end
describe "GET #identify" do
context "successfully" do
before do
get :identify
end
it "should render identify template" do
expect(response).to render_template :identify
end
end
end
describe "POST #authenticate using email" do
context "authenticate company" do
before do
params = { email: @company.email }
post :authenticate, params
end
it "should redirect to new_company_session_path" do
expect(response).to redirect_to new_company_session_url(email: @company.email)
end
it "should display flash message" do
message = "please log in your details"
expect(flash[:notice]).to eq message
end
end
context "authenticate recruiter" do
before do
params = { email: @recruiter.email }
post :authenticate, params
end
it "should redirect to new_recruiter_session_path" do
expect(response).to redirect_to new_recruiter_session_url(email: @recruiter.email)
end
end
end
end
|
class RelationshipsController < ApplicationController
def create
@relationship = current_user.relationships.build(friend_id: params[:friend_id])
respond_to do |format|
if @relationship.save
format.html {redirect_to profile_path(current_user.id), notice: 'User Followed Successfully'}
else
format.html { redirect_to root, notice: 'User Not Followed'}
end
end
end
def destroy
@relationship = current_user.relationships.find(params[:id])
@relationship.destroy
respond_to do |format|
format.html {redirect_to profile_path(current_user.id), notice: 'Succesfully unfollowed user'}
end
end
private
def relationship_params
params.require(:relationship).permit(:user_id, :friend_id)
end
end
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2019-2020 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Mongo
# ClientEncryption encapsulates explicit operations on a key vault
# collection that cannot be done directly on a MongoClient. It
# provides an API for explicitly encrypting and decrypting values,
# and creating data keys.
class ClientEncryption
# Create a new ClientEncryption object with the provided options.
#
# @param [ Mongo::Client ] key_vault_client A Mongo::Client
# that is connected to the MongoDB instance where the key vault
# collection is stored.
# @param [ Hash ] options The ClientEncryption options.
#
# @option options [ String ] :key_vault_namespace The name of the
# key vault collection in the format "database.collection".
# @option options [ Hash ] :kms_providers A hash of key management service
# configuration information.
# @see Mongo::Crypt::KMS::Credentials for list of options for every
# supported provider.
# @note There may be more than one KMS provider specified.
# @option options [ Hash ] :kms_tls_options TLS options to connect to KMS
# providers. Keys of the hash should be KSM provider names; values
# should be hashes of TLS connection options. The options are equivalent
# to TLS connection options of Mongo::Client.
# @see Mongo::Client#initialize for list of TLS options.
#
# @raise [ ArgumentError ] If required options are missing or incorrectly
# formatted.
def initialize(key_vault_client, options = {})
@encrypter = Crypt::ExplicitEncrypter.new(
key_vault_client,
options[:key_vault_namespace],
Crypt::KMS::Credentials.new(options[:kms_providers]),
Crypt::KMS::Validations.validate_tls_options(options[:kms_tls_options])
)
end
# Generates a data key used for encryption/decryption and stores
# that key in the KMS collection. The generated key is encrypted with
# the KMS master key.
#
# @param [ String ] kms_provider The KMS provider to use. Valid values are
# "aws" and "local".
# @param [ Hash ] options
#
# @option options [ Hash ] :master_key Information about the AWS master key.
# Required if kms_provider is "aws".
# - :region [ String ] The The AWS region of the master key (required).
# - :key [ String ] The Amazon Resource Name (ARN) of the master key (required).
# - :endpoint [ String ] An alternate host to send KMS requests to (optional).
# endpoint should be a host name with an optional port number separated
# by a colon (e.g. "kms.us-east-1.amazonaws.com" or
# "kms.us-east-1.amazonaws.com:443"). An endpoint in any other format
# will not be properly parsed.
# @option options [ Array<String> ] :key_alt_names An optional array of
# strings specifying alternate names for the new data key.
# @option options [ String | nil ] :key_material Optional
# 96 bytes to use as custom key material for the data key being created.
# If :key_material option is given, the custom key material is used
# for encrypting and decrypting data.
#
# @return [ BSON::Binary ] The 16-byte UUID of the new data key as a
# BSON::Binary object with type :uuid.
def create_data_key(kms_provider, options={})
key_document = Crypt::KMS::MasterKeyDocument.new(kms_provider, options)
key_alt_names = options[:key_alt_names]
key_material = options[:key_material]
@encrypter.create_and_insert_data_key(key_document, key_alt_names, key_material)
end
# Encrypts a value using the specified encryption key and algorithm.
#
# @param [ Object ] value The value to encrypt.
# @param [ Hash ] options
#
# @option options [ BSON::Binary ] :key_id A BSON::Binary object of type :uuid
# representing the UUID of the encryption key as it is stored in the key
# vault collection.
# @option options [ String ] :key_alt_name The alternate name for the
# encryption key.
# @option options [ String ] :algorithm The algorithm used to encrypt the value.
# Valid algorithms are "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
# "AEAD_AES_256_CBC_HMAC_SHA_512-Random", "Indexed", "Unindexed".
# @option options [ Integer | nil ] :contention_factor Contention factor
# to be applied if encryption algorithm is set to "Indexed". If not
# provided, it defaults to a value of 0. Contention factor should be set
# only if encryption algorithm is set to "Indexed".
# @option options [ String | nil ] query_type Query type to be applied
# if encryption algorithm is set to "Indexed". Query type should be set
# only if encryption algorithm is set to "Indexed". The only allowed
# value is "equality".
#
# @note The :key_id and :key_alt_name options are mutually exclusive. Only
# one is required to perform explicit encryption.
#
# @return [ BSON::Binary ] A BSON Binary object of subtype 6 (ciphertext)
# representing the encrypted value.
#
# @raise [ ArgumentError ] if either contention_factor or query_type
# is set, and algorithm is not "Indexed".
def encrypt(value, options={})
@encrypter.encrypt(value, options)
end
# Encrypts a Match Expression or Aggregate Expression to query a range index.
#
# @example Encrypt Match Expression.
# encryption.encrypt_expression(
# {'$and' => [{'field' => {'$gt' => 10}}, {'field' => {'$lt' => 20 }}]}
# )
# @example Encrypt Aggregate Expression.
# encryption.encrypt_expression(
# {'$and' => [{'$gt' => ['$field', 10]}, {'$lt' => ['$field', 20]}}
# )
# {$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]
# Only supported when queryType is "rangePreview" and algorithm is "RangePreview".
# @note: The Range algorithm is experimental only. It is not intended
# for public use. It is subject to breaking changes.
#
# @param [ Hash ] expression Expression to encrypt.
# # @param [ Hash ] options
# @option options [ BSON::Binary ] :key_id A BSON::Binary object of type :uuid
# representing the UUID of the encryption key as it is stored in the key
# vault collection.
# @option options [ String ] :key_alt_name The alternate name for the
# encryption key.
# @option options [ String ] :algorithm The algorithm used to encrypt the
# expression. The only allowed value is "RangePreview"
# @option options [ Integer | nil ] :contention_factor Contention factor
# to be applied If not provided, it defaults to a value of 0.
# @option options [ String | nil ] query_type Query type to be applied.
# The only allowed value is "rangePreview".
#
# @note The :key_id and :key_alt_name options are mutually exclusive. Only
# one is required to perform explicit encryption.
#
# @return [ BSON::Binary ] A BSON Binary object of subtype 6 (ciphertext)
# representing the encrypted expression.
#
# @raise [ ArgumentError ] if disallowed values in options are set.
def encrypt_expression(expression, options = {})
@encrypter.encrypt_expression(expression, options)
end
# Decrypts a value that has already been encrypted.
#
# @param [ BSON::Binary ] value A BSON Binary object of subtype 6 (ciphertext)
# that will be decrypted.
#
# @return [ Object ] The decrypted value.
def decrypt(value)
@encrypter.decrypt(value)
end
# Adds a key_alt_name for the key in the key vault collection with the given id.
#
# @param [ BSON::Binary ] id Id of the key to add new key alt name.
# @param [ String ] key_alt_name New key alt name to add.
#
# @return [ BSON::Document | nil ] Document describing the identified key
# before adding the key alt name, or nil if no such key.
def add_key_alt_name(id, key_alt_name)
@encrypter.add_key_alt_name(id, key_alt_name)
end
# Removes the key with the given id from the key vault collection.
#
# @param [ BSON::Binary ] id Id of the key to delete.
#
# @return [ Operation::Result ] The response from the database for the delete_one
# operation that deletes the key.
def delete_key(id)
@encrypter.delete_key(id)
end
# Finds a single key with the given id.
#
# @param [ BSON::Binary ] id Id of the key to get.
#
# @return [ BSON::Document | nil ] The found key document or nil
# if not found.
def get_key(id)
@encrypter.get_key(id)
end
# Returns a key in the key vault collection with the given key_alt_name.
#
# @param [ String ] key_alt_name Key alt name to find a key.
#
# @return [ BSON::Document | nil ] The found key document or nil
# if not found.
def get_key_by_alt_name(key_alt_name)
@encrypter.get_key_by_alt_name(key_alt_name)
end
# Returns all keys in the key vault collection.
#
# @return [ Collection::View ] Keys in the key vault collection.
def get_keys
@encrypter.get_keys
end
alias :keys :get_keys
# Removes a key_alt_name from a key in the key vault collection with the given id.
#
# @param [ BSON::Binary ] id Id of the key to remove key alt name.
# @param [ String ] key_alt_name Key alt name to remove.
#
# @return [ BSON::Document | nil ] Document describing the identified key
# before removing the key alt name, or nil if no such key.
def remove_key_alt_name(id, key_alt_name)
@encrypter.remove_key_alt_name(id, key_alt_name)
end
# Decrypts multiple data keys and (re-)encrypts them with a new master_key,
# or with their current master_key if a new one is not given.
#
# @param [ Hash ] filter Filter used to find keys to be updated.
# @param [ Hash ] options
#
# @option options [ String ] :provider KMS provider to encrypt keys.
# @option options [ Hash | nil ] :master_key Document describing master key
# to encrypt keys.
#
# @return [ Crypt::RewrapManyDataKeyResult ] Result of the operation.
def rewrap_many_data_key(filter, opts = {})
@encrypter.rewrap_many_data_key(filter, opts)
end
# Create collection with encrypted fields.
#
# If :encryption_fields contains a keyId with a null value, a data key
# will be automatically generated and assigned to keyId value.
#
# @note This method does not update the :encrypted_fields_map in the client's
# :auto_encryption_options. Therefore, in order to use the collection
# created by this method with automatic encryption, the user must create
# a new client after calling this function with the :encrypted_fields returned.
#
# @param [ Mongo::Database ] database Database to create collection in.
# @param [ String ] coll_name Name of collection to create.
# @param [ Hash ] coll_opts Options for collection to create.
# @param [ String ] kms_provider KMS provider to encrypt fields.
# @param [ Hash | nil ] master_key Document describing master key to encrypt fields.
#
# @return [ Array<Operation::Result, Hash> ] The result of the create
# collection operation and the encrypted fields map used to create
# the collection.
def create_encrypted_collection(database, coll_name, coll_opts, kms_provider, master_key)
raise ArgumentError, 'coll_opts must contain :encrypted_fields' unless coll_opts[:encrypted_fields]
encrypted_fields = create_data_keys(coll_opts[:encrypted_fields], kms_provider, master_key)
begin
new_coll_opts = coll_opts.dup.merge(encrypted_fields: encrypted_fields)
[database[coll_name].create(new_coll_opts), encrypted_fields]
rescue Mongo::Error => e
raise Error::CryptError, "Error creating collection with encrypted fields \
#{encrypted_fields}: #{e.class}: #{e.message}"
end
end
private
# Create data keys for fields in encrypted_fields that has :keyId key,
# but the value is nil.
#
# @param [ Hash ] encrypted_fields Encrypted fields map.
# @param [ String ] kms_provider KMS provider to encrypt fields.
# @param [ Hash | nil ] master_key Document describing master key to encrypt fields.
#
# @return [ Hash ] Encrypted fields map with keyIds for fields
# that did not have one.
def create_data_keys(encrypted_fields, kms_provider, master_key)
encrypted_fields = encrypted_fields.dup
# We must return the partially formed encrypted_fields hash if an error
# occurs - https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#create-encrypted-collection-helper
# Thefore, we do this in a loop instead of using #map.
encrypted_fields[:fields].size.times do |i|
field = encrypted_fields[:fields][i]
next unless field.is_a?(Hash) && field.fetch(:keyId, false).nil?
begin
encrypted_fields[:fields][i][:keyId] = create_data_key(kms_provider, master_key: master_key)
rescue Error::CryptError => e
raise Error::CryptError, "Error creating data key for field #{field[:path]} \
with encrypted fields #{encrypted_fields}: #{e.class}: #{e.message}"
end
end
encrypted_fields
end
end
end
|
class API < Grape::API
version 'v1', :using => :header, :vendor => 'twitter'
format :json
default_format :json
helpers do
def warden
env['warden']
end
def current_user
@current_user ||= warden.user
end
def authenticate!
error!('401 Unauthorized', 401) unless warden.authenticated?
end
end
resource :statuses do
get :public_timeline do
"hi"
end
end
resource :account do
before { authenticate! }
get '/private' do
"Congratulations, you found the secret!"
end
end
end |
require 'spec_helper'
describe "occurences/show.html.erb" do
before(:each) do
@occurence = assign(:occurence, stub_model(Occurence))
end
it "renders attributes in <p>" do
render
end
end
|
FactoryBot.define do
factory :user do
nickname { Faker::Name.initials(number: 2) }
email { Faker::Internet.free_email }
password { 'abcd12' }
password_confirmation { password }
last_name { '一あア' }
first_name { '一あア' }
last_name_furigana { 'テスト' }
first_name_furigana { 'テストー' }
birthday { '1992-01-09' }
end
end
|
# frozen_string_literal: true
require 'support/entities/gizmo'
# @note Integration spec for a subclassed Stannum::Entity.
RSpec.describe Spec::Gizmo do
shared_context 'when initialized with attribute values' do
let(:attributes) do
{
id: 0,
name: 'Self-Sealing Stem Bolt',
description: 'No one is sure what a self-sealing stem bolt is.',
quantity: 1_000,
size: 'Small'
}
end
end
subject(:gadget) { described_class.new(**attributes) }
let(:attributes) { {} }
def tools
SleepingKingStudios::Tools::Toolbelt.instance
end
describe '.attributes' do
it 'should define the class method' do
expect(described_class.attributes).to be_a Stannum::Schema
end
describe '.[]' do
it 'should return the attribute' do
expect(described_class.attributes[:name])
.to be_a(Stannum::Attribute)
.and(
have_attributes(
name: 'name',
options: { required: true },
type: 'String'
)
)
end
end
describe '.each' do
let(:expected_keys) { %w[id name description quantity size] }
let(:expected_values) do
[
{
name: 'id',
type: 'Integer',
options: { primary_key: true, required: true }
},
{
name: 'name',
type: 'String',
options: { required: true }
},
{
name: 'description',
type: 'String',
options: { required: false }
},
{
name: 'quantity',
type: 'Integer',
options: { default: 0, required: true }
},
{
name: 'size',
type: 'String',
options: { required: true }
}
].map do |attributes|
an_instance_of(Stannum::Attribute).and(
have_attributes(attributes)
)
end
end
it { expect(described_class.attributes.each).to be_a Enumerator }
it { expect(described_class.attributes.each.size).to be 5 }
it 'should yield the attributes' do
expect { |block| described_class.attributes.each(&block) }
.to yield_successive_args(*expected_keys.zip(expected_values))
end
end
end
describe '.contract' do
let(:contract) { described_class.contract }
it { expect(contract).to be_a Stannum::Contract }
describe 'with an empty struct' do
let(:expected_errors) do
[
{
data: { required: true, type: Integer },
message: nil,
path: [:id],
type: 'stannum.constraints.is_not_type'
},
{
data: { required: true, type: String },
message: nil,
path: [:name],
type: 'stannum.constraints.is_not_type'
},
{
data: { required: true, type: String },
message: nil,
path: [:size],
type: 'stannum.constraints.is_not_type'
},
{
data: {},
message: nil,
path: [],
type: 'stannum.constraints.invalid'
},
{
data: {},
message: nil,
path: [:size],
type: 'stannum.constraints.invalid'
}
]
end
it { expect(contract.errors_for(gadget)).to be == expected_errors }
it { expect(contract.matches?(gadget)).to be false }
end
describe 'with a struct with invalid attributes' do
let(:attributes) do
{
id: 0,
name: 'Self-Sealing Stem Bolt',
description: :invalid_description,
quantity: -10,
size: 'Lilliputian'
}
end
let(:expected_errors) do
[
{
data: { required: false, type: String },
message: nil,
path: [:description],
type: 'stannum.constraints.is_not_type'
},
{
data: {},
message: nil,
path: [],
type: 'stannum.constraints.invalid'
},
{
data: {},
message: nil,
path: [:quantity],
type: 'stannum.constraints.invalid'
},
{
data: {},
message: nil,
path: [:size],
type: 'stannum.constraints.invalid'
}
]
end
it { expect(contract.errors_for(gadget)).to be == expected_errors }
it { expect(contract.matches?(gadget)).to be false }
end
describe 'with a struct with valid attributes' do
let(:attributes) do
{
id: 0,
name: 'Self-Sealing Stem Bolt',
description: 'No one is sure what a self-sealing stem bolt is.',
quantity: 0,
size: 'Small'
}
end
it { expect(contract.errors_for(gadget)).to be == [] }
it { expect(contract.matches?(gadget)).to be true }
end
end
describe '#[]' do
it { expect(gadget).to respond_to(:[]).with(1).argument }
describe 'with a string key' do
it { expect(gadget['size']).to be nil }
end
describe 'with a symbol key' do
it { expect(gadget[:size]).to be nil }
end
describe 'with a string key for a parent attribute' do
it { expect(gadget['name']).to be nil }
end
describe 'with a symbol key for a parent attribute' do
it { expect(gadget[:name]).to be nil }
end
wrap_context 'when initialized with attribute values' do
describe 'with a string key' do
it { expect(gadget['size']).to be == attributes[:size] }
end
describe 'with a symbol key' do
it { expect(gadget[:size]).to be == attributes[:size] }
end
describe 'with a string key for a parent attributes' do
it { expect(gadget['name']).to be == attributes[:name] }
end
describe 'with a symbol key for a parent attribute' do
it { expect(gadget[:name]).to be == attributes[:name] }
end
end
context 'when the attribute has a default value' do
describe 'with a string key' do
it { expect(gadget['quantity']).to be 0 }
end
describe 'with a symbol key' do
it { expect(gadget[:quantity]).to be 0 }
end
wrap_context 'when initialized with attribute values' do
describe 'with a string key' do
it { expect(gadget['quantity']).to be == attributes[:quantity] }
end
describe 'with a symbol key' do
it { expect(gadget[:quantity]).to be == attributes[:quantity] }
end
end
end
end
describe '#[]=' do
let(:value) { 'Colossal' }
it { expect(gadget).to respond_to(:[]=).with(2).arguments }
describe 'with a string key' do
it 'should update the value' do
expect { gadget['size'] = value }
.to change(gadget, :size)
.to be == value
end
end
describe 'with a symbol key' do
it 'should update the value' do
expect { gadget[:size] = value }
.to change(gadget, :size)
.to be == value
end
end
describe 'with a string key for a parent attribute' do
let(:value) { 'Inverse Chronoton Emitter' }
it 'should update the value' do
expect { gadget['name'] = value }
.to change(gadget, :name)
.to be == value
end
end
describe 'with a symbol key for a parent attribute' do
let(:value) { 'Inverse Chronoton Emitter' }
it 'should update the value' do
expect { gadget[:name] = value }
.to change(gadget, :name)
.to be == value
end
end
wrap_context 'when initialized with attribute values' do
describe 'with a string key' do
it 'should update the value' do
expect { gadget['size'] = value }
.to change(gadget, :size)
.to be == value
end
end
describe 'with a symbol key' do
it 'should update the value' do
expect { gadget[:size] = value }
.to change(gadget, :size)
.to be == value
end
end
describe 'with a string key for a parent attribute' do
let(:value) { 'Inverse Chronoton Emitter' }
it 'should update the value' do
expect { gadget['name'] = value }
.to change(gadget, :name)
.to be == value
end
end
describe 'with a symbol key for a parent attribute' do
let(:value) { 'Inverse Chronoton Emitter' }
it 'should update the value' do
expect { gadget[:name] = value }
.to change(gadget, :name)
.to be == value
end
end
end
context 'when the attribute has a default value' do
let(:value) { 100 }
describe 'with a nil value' do
it 'should not change the value' do
expect { gadget[:quantity] = nil }.not_to change(gadget, :quantity)
end
end
describe 'with a string key' do
it 'should update the value' do
expect { gadget['quantity'] = value }
.to change(gadget, :quantity)
.to be == value
end
end
describe 'with a symbol key' do
it 'should update the value' do
expect { gadget[:quantity] = value }
.to change(gadget, :quantity)
.to be == value
end
end
wrap_context 'when initialized with attribute values' do
describe 'with a nil value' do
it 'should reset the value' do
expect { gadget[:quantity] = nil }
.to change(gadget, :quantity)
.to be 0
end
end
describe 'with a string key' do
it 'should update the value' do
expect { gadget['quantity'] = value }
.to change(gadget, :quantity)
.to be == value
end
end
describe 'with a symbol key' do
it 'should update the value' do
expect { gadget[:quantity] = value }
.to change(gadget, :quantity)
.to be == value
end
end
end
end
end
describe '#assign_attributes' do
let(:description) do
'A self-sealing stem bolt is the entrepreneurial opportunity of a ' \
'lifetime.'
end
let(:expected) do
{
'id' => nil,
'name' => nil,
'description' => description,
'quantity' => 0,
'size' => nil
}
end
it { expect(gadget).to respond_to(:assign_attributes).with(1).argument }
it 'should update the included values' do
expect { gadget.assign_attributes(description: description) }
.to change(gadget, :attributes)
.to be == expected
end
wrap_context 'when initialized with attribute values' do
let(:expected) do
tools
.hash_tools
.convert_keys_to_strings(attributes)
.merge('description' => description)
end
it 'should update the included values' do
expect { gadget.assign_attributes(description: description) }
.to change(gadget, :attributes)
.to be == expected
end
end
end
describe '#attributes' do
let(:expected) do
{
'id' => nil,
'name' => nil,
'description' => nil,
'quantity' => 0,
'size' => nil
}
end
it { expect(gadget).to respond_to(:attributes).with(0).arguments }
it { expect(gadget.attributes).to be == expected }
wrap_context 'when initialized with attribute values' do
let(:expected) { tools.hash_tools.convert_keys_to_strings(attributes) }
it { expect(gadget.attributes).to be == expected }
end
end
describe '#attributes=' do
let(:description) do
'A self-sealing stem bolt is the entrepreneurial opportunity of a ' \
'lifetime.'
end
let(:hsh) { { description: description, quantity: nil } }
let(:expected) do
{
'id' => nil,
'name' => nil,
'description' => description,
'quantity' => 0,
'size' => nil
}
end
it { expect(gadget).to respond_to(:attributes=).with(1).argument }
it 'should set the attributes' do
expect { gadget.attributes = hsh }
.to change(gadget, :attributes)
.to be == expected
end
wrap_context 'when initialized with attribute values' do
it 'should set the attributes' do
expect { gadget.attributes = hsh }
.to change(gadget, :attributes)
.to be == expected
end
end
end
describe '#description' do
include_examples 'should have reader', :description, nil
wrap_context 'when initialized with attribute values' do
it 'should return the value' do
expect(gadget.description)
.to be == 'No one is sure what a self-sealing stem bolt is.'
end
end
end
describe '#description=' do
let(:value) do
'A self-sealing stem bolt is the entrepreneurial opportunity of a ' \
'lifetime.'
end
include_examples 'should have writer', :description=
it 'should update the description' do
expect { gadget.description = value }
.to change(gadget, :description)
.to be == value
end
wrap_context 'when initialized with attribute values' do
it 'should update the description' do
expect { gadget.description = value }
.to change(gadget, :description)
.to be == value
end
end
end
describe '#id' do
include_examples 'should have reader', :id, nil
wrap_context 'when initialized with attribute values' do
it { expect(gadget.id).to be 0 }
end
end
describe '#id=' do
include_examples 'should have writer', :id=
it 'should update the value' do
expect { gadget.id = 1 }
.to change(gadget, :id)
.to be 1
end
wrap_context 'when initialized with attribute values' do
it 'should update the value' do
expect { gadget.id = 1 }
.to change(gadget, :id)
.to be 1
end
end
end
describe '#name' do
include_examples 'should have reader', :name, nil
wrap_context 'when initialized with attribute values' do
it { expect(gadget.name).to be == 'Self-Sealing Stem Bolt' }
end
end
describe '#name=' do
let(:value) { 'Inverse Chronoton Emitter' }
include_examples 'should have writer', :name=
it 'should update the value' do
expect { gadget.name = value }
.to change(gadget, :name)
.to be == value
end
wrap_context 'when initialized with attribute values' do
it 'should update the value' do
expect { gadget.name = value }
.to change(gadget, :name)
.to be == value
end
end
end
describe '#quantity' do
include_examples 'should have reader', :quantity, 0
wrap_context 'when initialized with attribute values' do
it { expect(gadget.quantity).to be == 1_000 }
end
end
describe '#quantity=' do
include_examples 'should have writer', :quantity=
describe 'with nil' do
it { expect { gadget.quantity = nil }.not_to change(gadget, :quantity) }
end
describe 'with a value' do
it 'should update the value' do
expect { gadget.quantity = 100 }
.to change(gadget, :quantity)
.to be 100
end
end
wrap_context 'when initialized with attribute values' do
describe 'with nil' do
it 'should reset the value' do
expect { gadget.quantity = nil }
.to change(gadget, :quantity)
.to be 0
end
end
describe 'with a value' do
it 'should update the value' do
expect { gadget.quantity = 100 }
.to change(gadget, :quantity)
.to be 100
end
end
end
end
describe '#size' do
include_examples 'should have reader', :size
wrap_context 'when initialized with attribute values' do
it { expect(gadget.size).to be == 'Small' }
end
end
describe '#size=' do
let(:value) { 'Colossal' }
include_examples 'should have writer', :size=
it 'should update the value' do
expect { gadget.size = value }
.to change(gadget, :size)
.to be == value
end
wrap_context 'when initialized with attribute values' do
it 'should update the value' do
expect { gadget.size = value }
.to change(gadget, :size)
.to be == value
end
end
end
end
|
class Ethnicity < ActiveRecord::Base
has_and_belongs_to_many :targets
has_and_belongs_to_many :members
has_and_belongs_to_many :participant_surveys
default_scope order('position asc')
end
|
Rails.application.routes.draw do
resources :user_sessions
get 'login', to: 'user_sessions#new', as: :login
get 'logout', to: 'user_sessions#destroy', as: :logout
get 'admin', to: 'admin#index'
post 'admin', to: 'admin#create'
root to: redirect('/game')
resource :game, only: :show
namespace :api do
resources :levels, only: %w[index show]
resources :results, only: :create
get :status, to: 'status#show'
end
end
|
require "test_helper"
class ServiceCategoryTest < ActiveSupport::TestCase
test "should validate required fields" do
c = ServiceCategory.new
assert !c.valid?
c.name = "Category"
assert c.save
end
test "should delete only if no services" do
c = service_categories(:one)
!assert c.can_be_deleted?
c = service_categories(:two)
assert c.can_be_deleted?
c.destroy
assert_raise(ActiveRecord::RecordNotFound) { ServiceCategory.find(c.id) }
end
end |
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# vbox name
config.vm.box = "centos_6_5_64"
# vbox url
config.vm.box_url = "https://github.com/2creatives/vagrant-centos/releases/download/v6.5.1/centos65-x86_64-20131205.box"
# enable package caching
config.cache.auto_detect = true
# port forwarding
config.vm.network :forwarded_port, guest: 80, host: 8000
config.vm.network :forwarded_port, guest: 5984, host: 5984
# shared folders
config.vm.synced_folder "../pantheon-repos", "/opt/pantheon-repos"
config.vm.provision "ansible" do |ansible|
ansible.playbook = "ansible/playbook.yml"
ansible.groups = {
"vagrant" => ["default"]
}
ansible.vault_password_file = "../pantheon-private/get_vagrant_vault_password"
end
config.vm.provider "virtualbox" do |v|
v.memory = 1024
end
end
|
# encoding: utf-8
control "V-54033" do
title "Sensitive data stored in the database must be identified in the System Security Plan and AIS Functional Architecture documentation."
desc "A DBMS that does not have the correct confidentiality level identified or any confidentiality level assigned is not being secured at a level appropriate to the risk it poses.false"
impact 0.5
tag "check": "If no sensitive or classified data is stored in the database, listed in the System Security Plan and listed in the AIS Functional Architecture documentation, this check is Not a Finding.
Review AIS Functional Architecture documentation for the DBMS and note any sensitive data that is identified.
Review database table column data or descriptions that indicate sensitive data.
For example, a data column labeled "SSN" could indicate social security numbers are stored in the column.
Question the IAO or DBA where any questions arise.
General categories of sensitive data requiring identification include any personal data (health, financial, social security number and date of birth), proprietary or financially sensitive business data or data that might be classified.
If any data is considered sensitive and is not documented in the AISFA, this is a Finding."
tag "fix": "Include identification of any sensitive data in the AIS Functional Architecture and the System Security Plan.
Include data that appear to be sensitive with a discussion as to why it is not marked as such."
# Write Check Logic Here
end |
# frozen_string_literal: true
class UsersController < ApplicationController
def show
## We can remove the 2nd instance variable since we have the relation
## specified for Posts in our User model.
@user = User.find(params[:id])
respond_to do |format|
format.html
## Before this simply outputted the user's entire information in JSON
## format. I think to better reflect what this action does in its HTML
## view, I have refactored it just to include the user's id and name,
## excluding information such as the password_digest field. It also
## includes the user's posts to also reflect what the HTML view gives.
## I would normally use a serializer for this purpose to give even
## greater control, but did not feel the need for that in this challenge.
format.json do
render json: { id: @user.id, name: @user.name, posts: @user.posts }
end
end
end
end
|
# Tasks from https://gist.github.com/dimasumskoy/86e05e4af223212c68c746ca93dc1d0e
# 1 task
def count_chars(words = [])
result = {}
words.each { |word| result[word] = word.length }
result
end
# 2 task
def remove_duplicates(num1 = [], num2 = [])
return if num1.empty? || num2.empty?
num2.reject { |num| num1.any?(num) }
end
# 3 task
def group_and_count(num = [])
return puts "Нужен массив строк" if num.any?(String) # unless num.all?(Integer)
result = {}
num.each { |n| result[n] = num.count(n) }
result
end
# 4 task
def descend_numbers(num)
return unless num >= 0
num.to_s.split('').sort { |a, b| b <=> a}.join.to_i
end
# 5 task
def list_items(arr = [])
return if arr.empty?
arr.each_with_index { |word, index| puts "#{index + 1}. #{word}" }
end
|
class UserPoint::Buy < UserPoint
def self.apply!(user:, used_amount:)
return if used_amount.zero?
ApplicationRecord.transaction do
user_point = find_or_initialize_by(user_id: user.id)
raise 'Over the available points' if user_point.amount < used_amount
ApplicationRecord.transaction do
user_point.update!(amount: user_point.amount - used_amount)
UserPointLog.create_buy_log!(
user: user,
amount: used_amount,
)
end
end
end
end
|
class KapaiController < ApplicationController
#
# 更新弟子信息
#
def update_disciples
re, user = validate_session_key(get_params(params, :session_key))
return unless re
disciples = params[:disciples]
if disciples.nil? || !disciples.kind_of?(Array)
render_result(ResultCode::INVALID_PARAMETERS, {err_msg: URI.encode('invalid parameters')})
return
end
re, err_msg = Disciple.update_disciples(user, disciples)
unless re
logger.error(err_msg)
render_result(ResultCode::ERROR, {err_msg: URI.encode(err_msg)})
return
end
render_result(ResultCode::OK, {})
end
#
# 更新装备信息
#
def update_equipments
re, user = validate_session_key(get_params(params, :session_key))
return unless re
equipments = params[:equipments]
if equipments.nil? || !equipments.kind_of?(Array)
render_result(ResultCode::INVALID_PARAMETERS, {err_msg: URI.encode('invalid parameters')})
return
end
re, err_msg = Equipment.update_equipments(user, equipments)
unless re
logger.error(err_msg)
render_result(ResultCode::ERROR, {err_msg: URI.encode(err_msg)})
return
end
render_result(ResultCode::OK, {})
end
#
# 更新武功信息
#
def update_gongfus
re, user = validate_session_key(get_params(params, :session_key))
return unless re
gongfus = params[:gongfus]
if gongfus.nil? || !gongfus.kind_of?(Array)
logger.debug("invalid parameters. gongfus is not an array.")
render_result(ResultCode::INVALID_PARAMETERS, {err_msg: URI.encode('invalid parameters')})
return
end
re, err_msg = Gongfu.update_gongfus(user, gongfus)
unless re
logger.error(err_msg)
render_result(ResultCode::ERROR, {err_msg: URI.encode(err_msg)})
return
end
render_result(ResultCode::OK, {})
end
#
# 更新掌门诀
#
def update_zhangmenjues
re, user = validate_session_key(get_params(params, :session_key))
return unless re
zhangmenjues = params[:zhangmenjues]
if zhangmenjues.nil? || !zhangmenjues.kind_of?(Array)
logger.debug("### #{__method__},(#{__FILE__}, #{__LINE__}) invalid parameters. zhangmenjues is not an array.")
render_result(ResultCode::INVALID_PARAMETERS, {err_msg: URI.encode('invalid parameters')})
return
end
re, err_msg = Zhangmenjue.update_zhangmenjues(user, zhangmenjues)
unless re
logger.error(err_msg)
render_result(ResultCode::ERROR, {err_msg: URI.encode(err_msg)})
return
end
render_result(ResultCode::OK, {})
end
#
# 更新魂魄接口
#
def update_souls
re, user = validate_session_key(get_params(params, :session_key))
return unless re
souls = params[:souls]
if souls.nil? || !souls.kind_of?(Array)
logger.debug("### #{__method__},(#{__FILE__}, #{__LINE__}) invalid parameters. souls is not an array.")
render_result(ResultCode::INVALID_PARAMETERS, {err_msg: URI.encode('invalid parameters')})
return
end
re, err_msg = Soul.update_souls(user, souls)
unless re
logger.error(err_msg)
render_result(ResultCode::ERROR, {err_msg: URI.encode(err_msg)})
return
end
render_result(ResultCode::OK, {})
end
#
# 创建一个武功
#
def create_gongfu
re, user = validate_session_key(get_params(params, :session_key))
return unless re
type = get_params(params, :type)
gongfu = Gongfu.create_gongfu(user, type)
if gongfu.nil?
render_result(ResultCode::ERROR, {err_msg: URI.encode("create gongfu error")})
return
end
unless gongfu.save
err_msg = gongfu.errors.full_messages.join('; ')
logger.error("### #{__method__},(#{__FILE__}, #{__LINE__}) #{err_msg}")
render_result(ResultCode::ERROR, {err_msg: URI.encode(err_msg)})
return
end
render_result(ResultCode::OK, {id: gongfu.id})
end
#
# 创建一个装备
#
def create_equipment
re, user = validate_session_key(get_params(params, :session_key))
return unless re
type = get_params(params, :type)
eq = Equipment.new(e_type: type, level: 1, grow_strength: 0.0,
user_id: user.id, position: -1, disciple_id: -1)
unless eq.save
err_msg = eq.errors.full_messages.join('; ')
logger.error("### #{__method__},(#{__FILE__}, #{__LINE__}) #{err_msg}")
render_result(ResultCode::ERROR, {err_msg: URI.encode(err_msg)})
return
end
render_result(ResultCode::OK, {id: eq.id})
end
#
# 创建一个弟子
#
# 请求成功,返回弟子类型id和功夫类型id
#
def create_disciple
re, user = validate_session_key(get_params(params, :session_key))
return unless re
type = get_params(params, :type)
disciple = Disciple.create_disciple(user, type)
if disciple.nil?
render_result(ResultCode::ERROR, {err_msg: URI.encode("create disciple error")})
return
end
unless disciple.save
err_msg = disciple.errors.full_messages.join('; ')
logger.error("### #{__method__},(#{__FILE__}, #{__LINE__}) #{err_msg}")
render_result(ResultCode::ERROR, {err_msg: URI.encode(err_msg)})
return
end
# 弟子id和天赋武功id
#disciple_type = disciple.d_type.partition(/\d+/)[1]
#gf_type = disciple.gongfus[0].gf_type.partition(/\d+/)[1]
render_result(ResultCode::OK, {id: disciple.id, origin_gongfu_id: disciple.gongfus[0].id})
end
end
|
class UsersController < ApplicationController
def index
@users = User.all
end
def index_unapproved
if params [:approved] == false
@users = User.find_all_by_approved(false)
else
"All current users approved."
end
end
end
|
name 'instus-epel'
maintainer 'Instus'
maintainer_email 'instus.com@gmail.com'
license 'Apache-2.0'
description 'Installs/Configures EPEL'
version '0.1.0'
chef_version '>= 14.0'
issues_url 'https://github.com/instus/instus.epel/issues'
source_url 'https://github.com/instus/instus.epel'
%w( centos redhat ).each do |os|
supports os
end |
require "rails_helper"
RSpec.describe Messaging::Bsnl::Api do
def stub_credentials
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with("BSNL_IHCI_HEADER").and_return("ABCDEF")
allow(ENV).to receive(:[]).with("BSNL_IHCI_ENTITY_ID").and_return("123")
Configuration.create(name: "bsnl_sms_jwt", value: "a jwt token")
end
describe "#new" do
it "raises an error if configuration is missing" do
stub_request(:post, "https://bulksms.bsnl.in:5010/api/Get_Content_Template_Details").to_return(body: {"Content_Template_Ids" => ["A list of template details"]}.to_json)
expect { described_class.new }.to raise_error(Messaging::Bsnl::CredentialsError)
end
end
describe "#send_sms" do
it "strips +91 from recipient_number because BSNL expects 10 digit mobile numbers" do
stub_credentials
mock_template = double("DltTemplate")
allow(mock_template).to receive(:is_unicode).and_return "1"
allow(mock_template).to receive(:id).and_return "1234"
request = stub_request(:post, "https://bulksms.bsnl.in:5010/api/Send_Sms")
described_class.new.send_sms(recipient_number: "+911111111111", dlt_template: mock_template, key_values: {})
expect(request.with(body: {
"Header" => "ABCDEF",
"Target" => "1111111111",
"Is_Unicode" => "1",
"Is_Flash" => "0",
"Message_Type" => "SI",
"Entity_Id" => "123",
"Content_Template_Id" => "1234",
"Template_Keys_and_Values" => {}
})).to have_been_made
end
it "raises an exception if the API sends a non-200 response" do
stub_credentials
mock_template = double("DltTemplate")
allow(mock_template).to receive(:is_unicode).and_return "1"
allow(mock_template).to receive(:id).and_return "1234"
stub_request(:post, "https://bulksms.bsnl.in:5010/api/Send_Sms").to_return(status: 401, body: "a response")
expect {
described_class.new.send_sms(recipient_number: "+911111111111", dlt_template: mock_template, key_values: {})
}.to raise_error(Messaging::Bsnl::ApiError, "API returned 401 with a response")
end
end
describe "#get_template_details" do
it "gets all the templates added to DLT" do
stub_credentials
stub_request(:post, "https://bulksms.bsnl.in:5010/api/Get_Content_Template_Details").to_return(body: {"Content_Template_Ids" => ["A list of template details"]}.to_json)
expect(described_class.new.get_template_details).to contain_exactly("A list of template details")
end
end
describe "#name_template_variables" do
it "names the variables for a DLT template" do
stub_credentials
template_id = "a template id"
message_with_named_vars = "message with {#var1#} and {#var2#}"
request = stub_request(:post, "https://bulksms.bsnl.in:5010/api/Name_Content_Template_Variables").to_return(body: {"Error" => nil, "Template_Keys" => %w[var1 var2]}.to_json)
expect(described_class.new.name_template_variables(template_id, message_with_named_vars)).to eq("Error" => nil, "Template_Keys" => %w[var1 var2])
expect(request.with(body: {
Template_ID: template_id,
Entity_ID: "123",
Template_Message_Named: message_with_named_vars
})).to have_been_made
end
end
describe "#get_message_status_report" do
it "gets the message's status" do
stub_credentials
stub_request(:post, "https://bulksms.bsnl.in:5010/api/Message_Status_Report").to_return(body: {a: :hash}.to_json)
expect(described_class.new.get_message_status_report(123123)).to eq({"a" => "hash"})
end
end
describe "#get account balance" do
it "fetches our BSNL account balances" do
stub_credentials
stub_request(:post, "https://bulksms.bsnl.in:5010/api/Get_SMS_Count").to_return(body: {"Recharge_Details" => ["A list of recharge details"]}.to_json)
expect(described_class.new.get_account_balance).to eq(["A list of recharge details"])
end
end
end
|
class ScheduledJobsController < ApplicationController
before_action :set_scheduled_job, only: %i[ show edit update destroy ]
# GET /scheduled_jobs or /scheduled_jobs.json
def index
@scheduled_jobs = ScheduledJob.all
end
# GET /scheduled_jobs/1 or /scheduled_jobs/1.json
def show
end
# GET /scheduled_jobs/new
def new
@scheduled_job = ScheduledJob.new
end
# GET /scheduled_jobs/1/edit
def edit
end
# POST /scheduled_jobs or /scheduled_jobs.json
def create
@scheduled_job = ScheduledJob.new(scheduled_job_params)
respond_to do |format|
if @scheduled_job.save
format.html { redirect_to @scheduled_job, notice: "Scheduled job was successfully created." }
format.json { render :show, status: :created, location: @scheduled_job }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @scheduled_job.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /scheduled_jobs/1 or /scheduled_jobs/1.json
def update
respond_to do |format|
if @scheduled_job.update(scheduled_job_params)
format.html { redirect_to @scheduled_job, notice: "Scheduled job was successfully updated." }
format.json { render :show, status: :ok, location: @scheduled_job }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @scheduled_job.errors, status: :unprocessable_entity }
end
end
end
# DELETE /scheduled_jobs/1 or /scheduled_jobs/1.json
def destroy
@scheduled_job.destroy
respond_to do |format|
format.html { redirect_to scheduled_jobs_url, notice: "Scheduled job was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_scheduled_job
@scheduled_job = ScheduledJob.find(params[:id])
end
# Only allow a list of trusted parameters through.
def scheduled_job_params
params.require(:scheduled_job).permit(:name)
end
end
|
# frozen_string_literal: true
# module as namespace
module Fusuma
require 'logger'
require 'singleton'
# logger separate between stdout and strerr
class MultiLogger < Logger
include Singleton
attr_reader :err_logger
attr_accessor :debug_mode
def initialize
super(STDOUT)
@err_logger = Logger.new(STDERR)
@debug_mode = false
end
def info(msg)
super(msg)
end
def debug(msg)
return unless debug_mode?
super(msg)
end
def warn(msg)
err_logger.warn(msg)
end
def error(msg)
err_logger.error(msg)
end
def debug_mode?
debug_mode
end
class << self
def info(msg)
instance.info(msg)
end
def debug(msg)
instance.debug(msg)
end
def warn(msg)
instance.warn(msg)
end
def error(msg)
instance.error(msg)
end
end
end
end
|
module Urbanairship
module Push
module Payload
require 'urbanairship/common'
include Urbanairship::Common
# Notification Object for a Push Payload
def notification(alert: nil, ios: nil, android: nil, amazon: nil,
blackberry: nil, wns: nil, mpns: nil, actions: nil,
interactive: nil)
payload = compact_helper({
alert: alert,
actions: actions,
ios: ios,
android: android,
amazon: amazon,
blackberry: blackberry,
wns: wns,
mpns: mpns,
interactive: interactive
})
fail ArgumentError, 'Notification body is empty' if payload.empty?
payload
end
# iOS specific portion of Push Notification Object
def ios(alert: nil, badge: nil, sound: nil, extra: nil, expiry: nil,
category: nil, interactive: nil, content_available: nil)
compact_helper({
alert: alert,
badge: badge,
sound: sound,
extra: extra,
expiry: expiry,
category: category,
interactive: interactive,
'content-available' => content_available
})
end
# Amazon specific portion of Push Notification Object
def amazon(alert: nil, consolidation_key: nil, expires_after: nil,
extra: nil, title: nil, summary: nil, interactive: nil)
compact_helper({
alert: alert,
consolidation_key: consolidation_key,
expires_after: expires_after,
extra: extra,
title: title,
summary: summary,
interactive: interactive
})
end
# Android specific portion of Push Notification Object
def android(alert: nil, collapse_key: nil, time_to_live: nil,
extra: nil, delay_while_idle: nil, interactive: nil)
compact_helper({
alert: alert,
collapse_key: collapse_key,
time_to_live: time_to_live,
extra: extra,
delay_while_idle: delay_while_idle,
interactive: interactive
})
end
# BlackBerry specific portion of Push Notification Object
def blackberry(alert: nil, body: nil, content_type: 'text/plain')
{ body: alert || body, content_type: content_type }
end
# WNS specific portion of Push Notification Object
def wns_payload(alert: nil, toast: nil, tile: nil, badge: nil)
payload = compact_helper({
alert: alert,
toast: toast,
tile: tile,
badge: badge
})
fail ArgumentError, 'Must specify one message type' if payload.size != 1
payload
end
# MPNS specific portion of Push Notification Object
def mpns_payload(alert: nil, toast: nil, tile: nil)
payload = compact_helper({
alert: alert,
toast: toast,
tile: tile
})
fail ArgumentError, 'Must specify one message type' if payload.size != 1
payload
end
# Rich Message specific portion of Push Notification Object
def message(title: required('title'), body: required('body'), content_type: nil, content_encoding: nil,
extra: nil, expiry: nil, icons: nil, options: nil)
compact_helper({
title: title,
body: body,
content_type: content_type,
content_encoding: content_encoding,
extra: extra,
expiry: expiry,
icons: icons,
options: options
})
end
# Interactive Notification portion of Push Notification Object
def interactive(type: required('type'), button_actions: nil)
fail ArgumentError, 'type must not be nil' if type.nil?
compact_helper({ type: type, button_actions: button_actions })
end
def all
'all'
end
# Target specified device types
def device_types(types)
types
end
# Expiry for a Rich Message
def options(expiry: required('expiry'))
{ expiry: expiry }
end
# Actions for a Push Notification Object
def actions(add_tag: nil, remove_tag: nil, open_: nil, share: nil,
app_defined: nil)
compact_helper({
add_tag: add_tag,
remove_tag: remove_tag,
open: open_,
share: share,
app_defined: app_defined
})
end
end
end
end
|
class TripsController < ApplicationController
load_and_authorize_resource
# GET /trips
# GET /trips.json
def index
@trips = Trip.all
# @trips = Trip.where(user_id: current_user.id)
respond_to do |format|
format.html # index.html.erb
format.json {
render json: @trips.to_json(include: :markers)
}
end
end
# GET /trips/1
# GET /trips/1.json
def show
@trip = Trip.find(params[:id])
@markers = @trip.markers
@marker = Marker.new trip: @trip
respond_to do |format|
format.html # show.html.erb
format.json {
render :json => {
:trip => @trip,
:markers => @markers
}
}
end
end
# GET /trips/new
# GET /trips/new.json
def new
@trip = Trip.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @trip }
end
end
def trip_interface
@trip = Trip.new
@marker = @trip.markers.new
render :trip_interface
end
# GET /trips/1/edit
def edit
@trip = Trip.find(params[:id])
markers = @trip.markers.where(trip_id: @trip.id)
end
# POST /trips
# POST /trips.json
def create
@trip = Trip.new(name: params[:name], description: params[:description])
@trip.decode_base64 params[:fileData] if params[:fileData]
@trip.user = current_user
if @trip.save
render json: @trip
else
render json: @trip.errors.to_json, status: 422
end
end
# PUT /trips/1
# PUT /trips/1.json
def update
@trip = Trip.find(params[:id])
respond_to do |format|
if @trip.update_attributes(params[:trip])
format.html { redirect_to @trip, notice: 'Trip was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @trip.errors, status: :unprocessable_entity }
end
end
end
# DELETE /trips/1
# DELETE /trips/1.json
def destroy
@trip = Trip.find(params[:id])
@trip.destroy
respond_to do |format|
format.html { redirect_to root_url }
format.json { head :no_content }
end
end
end
|
class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the passed in user here. For example:
#
# user ||= User.new # guest user (not logged in)
# if user.admin?
# can :manage, :all
# else
# can :read, :all
# end
#
# The first argument to `can` is the action you are giving the user permission to do.
# If you pass :manage it will apply to every action. Other common actions here are
# :read, :create, :update and :destroy.
#
# The second argument is the resource the user can perform the action on. If you pass
# :all it will apply to every resource. Otherwise pass a Ruby class of the resource.
#
# The third argument is an optional hash of conditions to further filter the objects.
# For example, here the user can only update published articles.
#
# can :update, Article, :published => true
#
# See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities
alias_action :prepare_quiz, :generate_quiz, :show_quiz, :to => :quiz
user ||= User.new # guest user (not logged in)
can :manage, User, :id => user.id # allow the user to change its own profile
if user.has_role? :admin
can :manage, :all
else
can :read, UserGroup, :id => UserGroup.with_role(:viewer, user).map{ |group| group.id }
can :manage, UserGroup, :id => UserGroup.with_role(:owner, user).map{ |group| group.id }
can :manage, Attempt, :id => UserGroup.with_role([:owner, :viewer], user).map{ |group| group.attempts.map{|attempt| attempt.id } }.flatten.uniq
# can :read, QuestionGroup, :id => QuestionGroup.with_role(:viewer, user).map{ |group| group.id }
# can :manage, QuestionGroup, :id => QuestionGroup.with_role(:owner, user).map{ |group| group.id }
can :manage, QuestionGroup
can :read, Tag
can :manage, Question
cannot :quiz, Question
can :read, User, :id => UserGroup.with_role([:owner, :viewer], user).map{|group| group.users.map{|user| user.id } }.flatten.uniq
end
end
end
|
class ApplicationController < ActionController::Base
def sanitize_nested_params(params)
# we strip off '0' from [{ '0' => { :id => '1', :foo => '234'}}]
filter_params = params.select{ |k,v| k =~ /_attributes$/ }
filter_params.each_pair do |k,v|
filter_params[k] = v.map{ |x| x.values.first}
end
params.merge(filter_params)
end
end
|
module CoolXBRL
module EDINET
class Label
DEFAULT_LANGUAGE = :ja
STANDARD_LABEL = "http://www.xbrl.org/2003/role/label"
VERBOSE_LABEL = "http://www.xbrl.org/2003/role/verboseLabel"
class << self
def get_label(locator, preferred_label=nil)
#name, doc, href, role = create_params(locator, preferred_label, english_flag)
search_label(*create_params(locator, preferred_label))
end
def get_context_label(context)
search_context_label(*create_context_params(context))
end
def create_params(locator, preferred_label)
label_files = CoolXBRL::EDINET.label
role = preferred_label || STANDARD_LABEL
if /http\:\/\// =~ locator
return *label_files[:edinet], "../#{File.basename(locator)}", role
else
return *label_files[:presenter], locator, role
end
end
def create_context_params(context)
label_files = CoolXBRL::EDINET.label
role = STANDARD_LABEL
if /jp(crp|pfs)\d{6}\-(asr|ssr|q[1-5]r)\_[EG]\d{5}\-\d{3}/ =~ context
return *label_files[:presenter], context.gsub(/(?<=#{$&})/, "_"), role
else
return *label_files[:edinet], context, role
end
end
def search_context_label(name, doc, context, role)
#確実な検索。時間が掛かる
doc.xpath("//link:labelArc[@xlink:from='#{context}']/@xlink:to").each do |to|
label = doc.at_xpath("//link:label[@xlink:label='#{to.to_s}' and @xlink:role='#{role}']/text()").to_s
break label unless label.empty?
end
#不確実かもしれない検索。多少時間が速くなる
#doc.xpath("//link:label[contains(./@xlink:label, '#{context}') and @xlink:role='#{role}']/text()").to_s
end
def search_label(name, doc, href, role)
locator_label = doc.at_xpath("//link:loc[@xlink:href='#{href}']/@xlink:label").to_s
#確実な検索。時間が掛かる
doc.xpath("//link:labelArc[@xlink:from='#{locator_label}']/@xlink:to").each do |to|
label = doc.at_xpath("//link:label[@xlink:label='#{to.to_s}' and @xlink:role='#{role}']/text()").to_s
break label unless label.empty?
end
#不確実かもしれない検索。多少時間が速くなる
#doc.xpath("//link:label[contains(./@xlink:label, '#{locator_label}') and @xlink:role='#{role}']/text()").to_s
end
end
end
end
end |
require 'rails_helper'
describe "As a visitor" do
describe "When I visit a doctor's show page" do
it "I see all of that doctor's info" do
memorial = Hospital.create(name: "Grey Sloan Memorial Hospital")
meredith = Doctor.create(name: "Meredith Grey", specialty: "General Surgery", education: "Harvard University", hospital_id: memorial.id)
alex = Doctor.create(name: "Alex Karev", specialty: "Pediatric Surgery", education: "Harvard University", hospital_id: memorial.id)
visit hospital_path(memorial)
expect(page).to have_content(meredith.education)
expect(page).to have_content(alex.education)
expect(page).to have_content(memorial.name)
expect(page).to have_content("Doctors working at this hospital: 2")
expect(page).to have_content("Universities our doctors attended:")
end
end
end
|
class ApplicationController < ActionController::API
include Response
def not_found
json_response({message: "Endpoint not found"},:not_found)
end
end
|
class TwilioController < ActionController::API
def index
render xml: <<~XML
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Gather numDigits="4" timeout="10" action="#{access_twilio_index_path}">
<Say>Please enter your 4 digit code, followed by the pound sign.</Say>
</Gather>
<Say>Please call back to try again.</Say>
<Play digits="w*"/>
</Response>
XML
end
def access
value = params[:Digits]
phone_number = params[:To]
door = Door.find_by(phone_number: phone_number)
if door.nil?
render json: { error: ["Not Found"] }, status: :not_found
return
end
log = DoorKeeperService.open(door: door, value: value)
render xml:
if log.success
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>Thanks I'm buzzing you in now.</Say>
<Play digits="w9"/>
</Response>
XML
else
if log.denied_reason == DoorKeeperService::CODE_UNKNOWN
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>Sorry I don't recognize that code. Please call back to try again.</Say>
<Play digits="w*"/>
</Response>
XML
else
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>That code is not authorized for this door at this time.</Say>
<Play digits="w*"/>
</Response>
XML
end
end
end
end
|
require "itamae"
module Itamae
module Plugin
module Resource
class Cron < ::Itamae::Resource::Base
class Error < StandardError; end
define_attribute :action, default: :create
define_attribute :minute, type: String, default: '*'
define_attribute :hour, type: String, default: '*'
define_attribute :day, type: String, default: '*'
define_attribute :month, type: String, default: '*'
define_attribute :weekday, type: String, default: '*'
define_attribute :cron_user, type: String, default: 'root'
define_attribute :cron_name, type: String, default_name: true
define_attribute :command, type: String
def pre_action
case @current_action
when :create
attributes.exist = true
when :delete
attributes.exist = false
end
end
def set_current_attributes
if run_specinfra(:check_file_is_file, cron_file)
current.exist = true
fields = parse_crontab(backend.receive_file(cron_file))
current.minute = fields[:minute]
current.hour = fields[:hour]
current.day = fields[:day]
current.month = fields[:month]
current.weekday = fields[:weekday]
current.cron_user = fields[:cron_user]
current.command = fields[:command]
else
current.exist = false
end
end
def action_create(options)
f = Tempfile.open('itamae')
f.write(generate_cron)
f.close
temppath = ::File.join(runner.tmpdir, Time.now.to_f.to_s)
backend.send_file(f.path, temppath)
run_specinfra(:move_file, temppath, cron_file)
ensure
f.unlink if f
end
def action_delete(options)
if current.exist
run_specinfra(:remove_file, cron_file)
end
end
private
def generate_cron
<<-EOCRON
# DO NOT EDIT THIS MANUALLY
# BECAUSE THIS IS AUTO GENERATED BY Itamae
#{attributes.minute} #{attributes.hour} #{attributes.day} #{attributes.month} #{attributes.weekday} #{attributes.cron_user} #{attributes.command}
EOCRON
end
def cron_file
key = attributes.cron_name.gsub(%r{(\s+|/)}, '-')
"/etc/cron.d/itamae-#{key}"
end
def parse_crontab(crontab)
line = crontab.each_line.find {|l| !l.start_with?('#') }
r = line.chomp.match(/\A([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+(.+)\z/)
unless r
raise Error, "Invalid crontab format."
end
{minute: r[1], hour: r[2], day: r[3], month: r[4], weekday: r[5],
cron_user: r[6], command: r[7]}
end
end
end
end
end
|
require 'openssl'
require 'Base64'
require 'socket'
require 'digest/sha1'
require 'optparse'
require './protobuf/protocol.pb'
require './util.rb'
class Client
include MixUtil
def initialize(options = {})
@id = options[:id]
@client_name = "client#{@id}"
@key_dir = File.join(File.dirname(__FILE__), 'keys')
@send_real_percent = options[:send_real_percent] || 1
@sleep = options[:sleep] || 0.05
@level = options[:level] || 5
@public_key = load_rsa_pub(File.join(@key_dir,@client_name))
@private_key = load_rsa_priv(File.join(@key_dir,@client_name))
prepare_adress_book
end
def encrypt_message(addr,msg)
key = `openssl rand -base64 32`
enc_key = addr != "NOISE" ? public_key_encrypt(key,@address_book[addr]) : key
c = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
c.encrypt
c.iv = iv = c.random_iv
c.key = key
enc_msg = c.update(msg)
enc_msg << c.final
anonym_message = Protobuf::MixMessage.new
anonym_message.addr = addr
anonym_message.iv = iv
anonym_message.key = enc_key
anonym_message.msg = enc_msg
anonym_message.serialize_to_string
end
def run
while true
if rand(100) < @send_real_percent
addr = (@client_pool - [@client_name]).sample
content = "Super secret and anonym message!"
else
addr = "NOISE"
content = `openssl rand -base64 #{rand(500)+100}`
end
last_mix = ""
msg = encrypt_message(addr,content)
route = []
@level.times do
last_mix = (@server_pool - [last_mix]).sample
route << last_mix
msg = encrypt_message(last_mix, msg)
end
if addr == "NOISE"
puts "[N] -> #{route.reverse.join(" -> ")} [#{msg.size}B]"
else
puts "[Message] -> #{route.reverse.join(" -> ")} -> #{addr} [#{msg.size}B]"
end
socket = TCPSocket.open('localhost', last_mix)
socket.write(msg)
socket.close
sleep @sleep
end
end
end
options = {}
ARGV << '-h' if ARGV.empty?
parser = OptionParser.new do|opts|
opts.banner = "Usage: client.rb [options]"
opts.on('-i', '--id id', 'Client ID starting form 0') do |id|
options[:id] = id.to_i;
end
opts.on('-h', '--help', 'Displays Help') do
puts opts
exit
end
opts.on('-s', '--sleep time_in_s', 'sleep seconds between messges') do |sleep|
options[:sleep] = sleep.to_f;
end
opts.on('-p', '--send-real-percent percent', 'probablity to send real message [0..100]') do |percent|
options[:send_real_percent] = percent.to_i;
end
opts.on('-l', '--levels levels', 'mix levels [3..]') do |level|
options[:level] = level.to_i;
end
end
parser.parse!
Client.new(options).run
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2019-2021 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Mongo
module Crypt
module KMS
module GCP
# GCP Cloud Key Management Credentials object contains credentials for
# using GCP KMS provider.
#
# @api private
class Credentials
extend Forwardable
include KMS::Validations
# @return [ String ] GCP email to authenticate with.
attr_reader :email
# @return [ String ] GCP private key, base64 encoded DER format.
attr_reader :private_key
# @return [ String | nil ] GCP KMS endpoint.
attr_reader :endpoint
# @return [ String | nil ] GCP access token.
attr_reader :access_token
# @api private
def_delegator :@opts, :empty?
FORMAT_HINT = "GCP KMS provider options must be in the format: " +
"{ email: 'EMAIL', private_key: 'PRIVATE-KEY' }"
# Creates an GCP KMS credentials object form a parameters hash.
#
# @param [ Hash ] opts A hash that contains credentials for
# GCP KMS provider
# @option opts [ String ] :email GCP email.
# @option opts [ String ] :private_key GCP private key. This method accepts
# private key in either base64 encoded DER format, or PEM format.
# @option opts [ String | nil ] :endpoint GCP endpoint, optional.
# @option opts [ String | nil ] :access_token GCP access token, optional.
# If this option is not null, other options are ignored.
#
# @raise [ ArgumentError ] If required options are missing or incorrectly
# formatted.
def initialize(opts)
@opts = opts
return if empty?
if opts[:access_token]
@access_token = opts[:access_token]
else
@email = validate_param(:email, opts, FORMAT_HINT)
@private_key = begin
private_key_opt = validate_param(:private_key, opts, FORMAT_HINT)
if BSON::Environment.jruby?
# We cannot really validate private key on JRuby, so we assume
# it is in base64 encoded DER format.
private_key_opt
else
# Check if private key is in PEM format.
pkey = OpenSSL::PKey::RSA.new(private_key_opt)
# PEM it is, need to be converted to base64 encoded DER.
der = if pkey.respond_to?(:private_to_der)
pkey.private_to_der
else
pkey.to_der
end
Base64.encode64(der)
end
rescue OpenSSL::PKey::RSAError
# Check if private key is in DER.
begin
OpenSSL::PKey.read(Base64.decode64(private_key_opt))
# Private key is fine, use it.
private_key_opt
rescue OpenSSL::PKey::PKeyError
raise ArgumentError.new(
"The private_key option must be either either base64 encoded DER format, or PEM format."
)
end
end
@endpoint = validate_param(
:endpoint, opts, FORMAT_HINT, required: false
)
end
end
# Convert credentials object to a BSON document in libmongocrypt format.
#
# @return [ BSON::Document ] Azure KMS credentials in libmongocrypt format.
def to_document
return BSON::Document.new if empty?
if access_token
BSON::Document.new({ accessToken: access_token })
else
BSON::Document.new({
email: email,
privateKey: BSON::Binary.new(private_key, :generic),
}).tap do |bson|
unless endpoint.nil?
bson.update({ endpoint: endpoint })
end
end
end
end
end
end
end
end
end
|
class ListPositionsDecorator < SimpleDelegator
def list_position_arr
order(role: :asc, position_id: :desc)
.joins(:player, :position, :fpl_team_list)
.joins('JOIN rounds ON rounds.id = fpl_team_lists.round_id')
.joins('JOIN teams ON teams.id = players.team_id')
.joins(
'LEFT JOIN fixtures ON fixtures.round_id = rounds.id AND ' \
'(fixtures.team_h_id = teams.id OR fixtures.team_a_id = teams.id)'
).joins(
'LEFT JOIN teams AS opponents ON ' \
'((fixtures.team_h_id = opponents.id AND fixtures.team_a_id = teams.id) OR ' \
'(fixtures.team_a_id = opponents.id AND fixtures.team_h_id = teams.id))'
).pluck_to_hash(
:id,
:player_id,
:role,
:last_name,
:position_id,
:singular_name_short,
:team_id,
'teams.short_name AS team_short_name',
:status,
:total_points,
:player_fixture_histories,
:event_points,
:fpl_team_list_id,
:team_h_id,
:team_a_id,
'fpl_team_lists.round_id AS fpl_team_list_round_id',
'opponents.short_name AS opponent_short_name',
'(team_h_difficulty - team_a_difficulty) AS difficulty'
).map do |hash|
difficulty = hash['team_h_id'] == hash['team_id'] ? hash['difficulty'] * -1 : hash['difficulty']
hash['opponent_short_name'] = 'BYE' unless difficulty
difficulty_type =
if difficulty && difficulty < 0
'o'
elsif difficulty == 0
'e'
else
't'
end
hash[:difficulty_class] = "difficulty-#{difficulty_type}#{difficulty.abs unless difficulty == 0}" if difficulty
hash
end
end
end
|
require 'spec_helper'
describe FaradayMiddleware::ConvertSdataToHeaders do
def connection(include_mashify=true)
Faraday.new(url: sage_url(nil)) do |conn|
conn.request :json
conn.use FaradayMiddleware::Mashify if include_mashify
conn.use FaradayMiddleware::ConvertSdataToHeaders
conn.use FaradayMiddleware::ParseJson
conn.adapter Faraday.default_adapter
end
end
context "when on the first page"do
it "does not add a prev link" do
stub_get('sales_invoices').to_return(body: sdata_fixture('sales_invoices.json', 20, 0, 20))
response = connection.get('sales_invoices')
expect(response.headers).to be_empty
end
context "and there are more results than items_per_page" do
it "adds a next link" do
stub_get('sales_invoices').to_return(body: sdata_fixture('sales_invoices.json', 40, 0, 20))
response = connection.get('sales_invoices')
expect(response.headers['X-Sdata-Pagination-Links']).to_not be_nil
expect(response.headers['X-Sdata-Pagination-Links']).to include(%Q{<#{sage_url('sales_invoices?%24startIndex=20')}>; rel="next"})
end
end
end
context "when on the last page" do
before { stub_get('sales_invoices').to_return(body: sdata_fixture('sales_invoices.json', 40, 20, 20)) }
it "does not add a next link" do
response = connection.get('sales_invoices')
expect(response.headers).to_not include('rel="next"')
end
it "adds a prev link" do
response = connection.get('sales_invoices')
expect(response.headers['X-Sdata-Pagination-Links']).to_not be_nil
expect(response.headers['X-Sdata-Pagination-Links']).to include(%Q{<#{sage_url('sales_invoices?%24startIndex=0')}>; rel="prev"})
end
context "when requesting a value in the middle of the last page" do
before { stub_get('sales_invoices').to_return(body: sdata_fixture('sales_invoices.json', 40, 30, 20)) }
it "does not add a next link" do
response = connection.get('sales_invoices')
expect(response.headers).to_not include('rel="next"')
end
it "adds a prev link" do
response = connection.get('sales_invoices')
expect(response.headers['X-Sdata-Pagination-Links']).to_not be_nil
expect(response.headers['X-Sdata-Pagination-Links']).to include(%Q{<#{sage_url('sales_invoices?%24startIndex=10')}>; rel="prev"})
end
end
end
context "when there are fewer results than items_per_page" do
before { stub_get('sales_invoices').to_return(body: sdata_fixture('sales_invoices.json', 5, 0, 20)) }
it "adds no links" do
response = connection.get('sales_invoices')
expect(response.headers['X-Sdata-Pagination-Links']).to be_nil
end
end
context "when on a middle page" do
before { stub_get('sales_invoices').to_return(body: sdata_fixture('sales_invoices.json', 20, 10, 5)) }
it "adds a prev link" do
response = connection.get('sales_invoices')
expect(response.headers['X-Sdata-Pagination-Links']).to include(%Q{<#{sage_url('sales_invoices?%24startIndex=5')}>; rel="prev"})
end
it "adds a next link" do
response = connection.get('sales_invoices')
expect(response.headers['X-Sdata-Pagination-Links']).to include(%Q{<#{sage_url('sales_invoices?%24startIndex=15')}>; rel="next"})
end
end
it "places the resources in the body of the response" do
stub_get('sales_invoices').to_return(body: sdata_fixture('sales_invoices.json', 20, 10, 5))
response = connection(false).get('sales_invoices')
response.body.to_s.should eq(JSON.parse(sdata_fixture('sales_invoices.json', 20,10,5))['$resources'].to_s)
end
context "when there are existing query parameters" do
before { stub_get('sales_invoices?search=salad&from_date=2012-11-11').to_return(body: sdata_fixture('sales_invoices.json', 20, 10, 5)) }
it "it passes them through without modification" do
response = connection.get('sales_invoices?from_date=2012-11-11&search=salad')
expect(response.headers['X-Sdata-Pagination-Links']).to eq('<https://app.sageone.com/api/v1/sales_invoices?%24startIndex=15&from_date=2012-11-11&search=salad>; rel="next", <https://app.sageone.com/api/v1/sales_invoices?%24startIndex=5&from_date=2012-11-11&search=salad>; rel="prev"')
end
end
context 'when there is no SData' do
before { stub_get('sales_invoices/954380').to_return(body: fixture('sales_invoice.json')) }
it "does not create link headers" do
response = connection.get('sales_invoices/954380')
expect(response.headers['X-Sdata-Pagination-Links']).to be_nil
end
it "leaves the resources in the body of the response" do
response = connection(false).get('sales_invoices/954380')
response.body.to_s.should eq(JSON.parse(fixture('sales_invoice.json').read).to_s)
end
end
context 'within first page of results, but not from start_index of 0' do
before { stub_get('sales_invoices').to_return(body: sdata_fixture('sales_invoices.json', 20, 3, 5)) }
it "Adds a previous link to start_index=0" do
response = connection.get('sales_invoices')
expect(response.headers['X-Sdata-Pagination-Links']).to include(%Q{<#{sage_url('sales_invoices?%24startIndex=0')}>; rel="prev"})
end
it "Adds a next link to start_index=8" do
response = connection.get('sales_invoices')
expect(response.headers['X-Sdata-Pagination-Links']).to include(%Q{<#{sage_url('sales_invoices?%24startIndex=8')}>; rel="next"})
end
end
end |
require "paperclip/matchers/have_attached_file_matcher"
require "paperclip/matchers/validate_attachment_presence_matcher"
require "paperclip/matchers/validate_attachment_content_type_matcher"
require "paperclip/matchers/validate_attachment_size_matcher"
module Paperclip
module Shoulda
# Provides RSpec-compatible & Test::Unit-compatible matchers for testing Paperclip attachments.
#
# *RSpec*
#
# In spec_helper.rb, you'll need to require the matchers:
#
# require "paperclip/matchers"
#
# And _include_ the module:
#
# RSpec.configure do |config|
# config.include Paperclip::Shoulda::Matchers
# end
#
# Example:
# describe User do
# it { should have_attached_file(:avatar) }
# it { should validate_attachment_presence(:avatar) }
# it { should validate_attachment_content_type(:avatar).
# allowing('image/png', 'image/gif').
# rejecting('text/plain', 'text/xml') }
# it { should validate_attachment_size(:avatar).
# less_than(2.megabytes) }
# end
#
#
# *TestUnit*
#
# In test_helper.rb, you'll need to require the matchers as well:
#
# require "paperclip/matchers"
#
# And _extend_ the module:
#
# class ActiveSupport::TestCase
# extend Paperclip::Shoulda::Matchers
#
# #...other initializers...#
# end
#
# Example:
# require 'test_helper'
#
# class UserTest < ActiveSupport::TestCase
# should have_attached_file(:avatar)
# should validate_attachment_presence(:avatar)
# should validate_attachment_content_type(:avatar).
# allowing('image/png', 'image/gif').
# rejecting('text/plain', 'text/xml')
# should validate_attachment_size(:avatar).
# less_than(2.megabytes)
# end
#
module Matchers
end
end
end
|
class Area < ActiveRecord::Base
attr_accessible :area_prototype
belongs_to :area_prototype, :foreign_key => "area_code"
belongs_to :game
has_many :locations
def name
area_prototype.name
end
end |
class ChangeTotalTypeOfItems < ActiveRecord::Migration
def self.up
change_column :sales_return_items, :amount, :integer
change_column :sales_return_items, :total, :float
end
def self.down
change_column :sales_return_items, :amount, :float
change_column :sales_return_items, :total, :integer
end
end
|
require 'test_helper'
class Rayadmin::MarkinfosControllerTest < ActionController::TestCase
setup do
@markinfo = markinfos(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:markinfos)
end
test "should get new" do
get :new
assert_response :success
end
test "should create markinfo" do
assert_difference('Markinfo.count') do
post :create, markinfo: { }
end
assert_redirected_to markinfo_path(assigns(:markinfo))
end
test "should show markinfo" do
get :show, id: @markinfo
assert_response :success
end
test "should get edit" do
get :edit, id: @markinfo
assert_response :success
end
test "should update markinfo" do
patch :update, id: @markinfo, markinfo: { }
assert_redirected_to markinfo_path(assigns(:markinfo))
end
test "should destroy markinfo" do
assert_difference('Markinfo.count', -1) do
delete :destroy, id: @markinfo
end
assert_redirected_to markinfos_path
end
end
|
class Test < ApplicationRecord
belongs_to :subject
has_many :results
end
|
class User < ApplicationRecord
acts_as_voter
has_many :likes, dependent: :destroy
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :comments
has_one_attached :avatar
def avatar_thumbnail
if avatar.attached?
avatar.variant(resize_to_limit: [40, 40])
else
'/default_profile.jpg'
end
end
end
|
Pod::Spec.new do |s|
s.name = 'FASDFEWSSDGD'
s.version = '1.0.3'
s.summary = 'A view like UIAlertView on iOS.'
s.homepage = 'http://blog.csdn.net/codingfire'
s.authors = { ‘liuxuanshuo’ => ‘lxuanshuo@gmail.com' }
s.source = { :git => 'https://github.com/codeliu6572/CustomAlertView.git', :tag => '1.0.3' }
s.requires_arc = true
s.license = 'MIT'
s.ios.deployment_target = ‘8.0’
s.source_files = 'FASDFEWSSDGD/*'
end
|
class League
class DivisionPresenter < BasePresenter
presents :division
def bracket_data(rosters, matches)
rosters = rosters.index_by(&:id)
matches = matches.group_by(&:round_number)
rounds = matches.keys.sort
# rubocop:disable Rails/OutputSafety
{
rounds: rounds.map { |round| html_escape present(matches[round].first).round_s },
matches: rounds.map { |round| present_collection(matches[round]).map(&:bracket_data) },
teams: rosters.transform_values { |roster| present(roster).bracket_data },
}.to_json.html_safe
# rubocop:enable Rails/OutputSafety
end
end
end
|
#
# Cookbook Name:: snapshot_timer
# Recipe:: install_plugin
#
# Copyright (C) 2013 Ryan Cragun
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
rightscale_marker
return unless node[:snapshot_timer][:enable_plugin] == "true"
rightscale_enable_collectd_plugin "exec"
include_recipe "rightscale::default"
include_recipe "rightscale::install_tools"
require 'fileutils'
log " Installing snapshot_timer collectd plugin.."
template(::File.join(node[:rightscale][:collectd_plugin_dir], "snapshot_timer.conf")) do
backup false
source "snapshot_timer.conf.erb"
notifies :restart, resources(:service => "collectd")
variables(
:collectd_lib => node[:rightscale][:collectd_lib],
:instance_uuid => node[:rightscale][:instance_uuid],
:lineage => node[:snapshot_timer][:lineage],
:interval => node[:snapshot_timer][:interval]
)
end
directory ::File.join(node[:rightscale][:collectd_lib], "plugins") do
action :create
recursive true
end
cookbook_file(::File.join(node[:rightscale][:collectd_lib], "plugins", 'snapshot_timer.rb')) do
source "snapshot_timer.rb"
mode "0755"
notifies :restart, resources(:service => "collectd")
end
file "/var/spool/cloud/user-data.rb" do
owner "root"
group "root"
mode "0664"
action :touch
end
log " Installed collectd snapshot_timer plugin."
|
require_relative "lib/usercommunications/version"
Gem::Specification.new do |spec|
spec.name = "usercommunications"
spec.version = Usercommunications::VERSION
spec.authors = ["vineethmoturi"]
spec.email = ["moturivineeth321@gmail.com"]
spec.homepage = "http://website.com"
spec.summary = "Ruby gem, Created for SearchPod mail generation."
spec.description = "Ruby gem, Created for SearchPod mail generation."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
spec.metadata["allowed_push_host"] = "Set to 'http://mygemserver.com'"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/Godservent/usercommunications.git"
#spec.metadata["changelog_uri"] = "Put your gem's CHANGELOG.md URL here."
spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
spec.add_dependency "rails", "~> 6.1.4", ">= 6.1.4.1"
end
|
class User < ActiveRecord::Base
has_many :tweets
validates :name, presence: true
validates :salutation, presence: true
validates :email, presence: true
validates :email, presence:
end |
require 'date'
class Calendar
def initialize(birthday_date)
@birthday_date = birthday_date
end
def days_left
# modulos work for negatives
return (((@birthday_date - Date.today).to_i) % 365)
end
end
|
require 'spec_helper'
describe 'nmax', type: :acceptance do
context 'with valid arguments and input stream' do
let(:max) { 100 }
let!(:numbers) { (1..1000).to_a }
let(:file) { generate_file('data.txt', numbers) }
let(:max_numbers) { (901..1000).to_a.reverse }
it 'return max numbers' do
expect(nmax(max, file: file)).to eq "#{max_numbers.join("\n")}\n"
end
end
context 'with invalid arguments and input stream' do
let(:usage) { "Usage: cat FILE | nmax NUMBER_COUNT\n" }
it 'without arguments' do
expect(nmax).to eq usage
end
it 'with not number argument' do
expect(nmax('xxx')).to eq usage
end
it 'with two arguments' do
expect(nmax('1000 300')).to eq usage
end
end
end
|
require "rails_helper"
RSpec.describe HomeController do
render_views
describe "GET :faq" do
it "renders the view" do
get :faq
expect(response).to render_template(:faq)
end
end
end
|
require 'spec_helper'
describe GapIntelligence::RecordSet do
subject(:record_set) { described_class.new [1, 2, 3] }
it 'allows record sets to be created' do
expect(described_class).to respond_to(:new)
end
it 'accepts meta' do
expect(record_set).to respond_to(:meta)
end
it 'iterates over collection' do
expect { |block| record_set.each(&block) }.to yield_control
end
it 'returns element by index' do
expect(record_set[1]).to eq(2)
end
it 'responds to to_ary' do
expect(record_set).to respond_to(:to_ary)
end
context 'pagination' do
context 'with meta' do
let(:pagination) { {
'current_page' => 1,
'next_page' => 2,
'prev_page' => nil,
'total_pages' => 4,
'total_count' => 99
} }
subject(:record_set) { described_class.new [], meta: { 'pagination' => pagination } }
it 'responds to total_pages' do
expect(record_set.total_pages).to eq(pagination['total_pages'])
end
it 'responds to current_page' do
expect(record_set.current_page).to eq(pagination['current_page'])
end
it 'responds to limit_value' do
expect(record_set.limit_value).to eq(25)
end
end
context 'without meta' do
subject(:record_set) { described_class.new [], meta: nil }
it 'responds to total_pages' do
expect(record_set.total_pages).to eq(nil)
end
it 'responds to current_page' do
expect(record_set.current_page).to eq(nil)
end
it 'responds to limit_value' do
expect(record_set.limit_value).to eq(nil)
end
end
end
end
|
class InstancesController < ApplicationController
before_filter :fetch_player
def index
@instances = @player.instances.find(:all, :order => 'created_at')
@stats = {}
@instances.each { |instance| @stats[instance.id] = ETQWStats.parse(instance.data) }
end
def destroy
if @player.instances.find(params[:id]).destroy
flash[:notice] = "Successfully deleted instance # #{params[:id]} from player #{@player.name}"
else
flash[:error] = "Error while trying to delete instance # #{params[:id]} from player #{@player.name}"
end
redirect_to player_instances_path(@player)
end
def show
@instance = @player.instances.find(params[:player_id])
end
# Downloads the current xml feed from official server and saves it, if it is newer
def new
# redirect and show error if player not registered
if @player.nil?
flash[:error] = "Error: No registered Player found, sorry!"
end
xml = ETQWStats.download_for_user(@player.name)
stats = ETQWStats.parse(xml)
instance = Instance.new(:data => xml, :date => stats.user_info.updated_at)
saved_dates = @player.instances.map {|i| i.date.to_date}
unless saved_dates.include?(instance.date.to_date)
@player.instances << instance
if @player.save
flash[:notice] = "Saved a new Session for user #{@player.name} for #{instance.date.to_s(:long)} !"
else
flash[:error] = "Failure, while trying to capture the instance for player #{@player.name}"
end
else
flash[:error] = "Already downloaded the newest session for player #{@player.name}"
end
redirect_to player_instances_url(@player)
end
def import
instance = Instance.new
respond_to do |format|
format.xml { @xml = request.body }
format.html { @xml = params[:xml]}
end
begin
ETQWStats.parse(@xml)
instance.data = @xml
@player.instances << instance
if @player.save
flash[:notice] = "Successfully imported your statistics from a file."
redirect_to player_instances_path(@player)
else
flash[:error] = "Your statistics file could not be imported!"
end
rescue ArgumentError
flash[:error] = "Your supplied statistics file is not valid, sorry!"
end
end
#def compare
# @newer = ETQWStats.parse(@player.instances.find(params[:newer]).data)
# @older = ETQWStats.parse(@player.instances.find(params[:older]).data)
# @diff = @older - @newer
# render :partial => 'instance', :locals => {:stats => @diff}
#end
private
def fetch_player
@player = Player.find(params[:player_id])
end
end
|
# frozen_string_literal: true
module LabelHelper
def label_color(slug)
case slug
when /todo/ then 'bg-info'
when /in-progress/ then 'bg-primary'
when /qa/ then 'bg-warning'
when /done/ then 'bg-success'
else
'bg-info'
end
end
end
|
#require 'dm-timestamps'
class Post
include DataMapper::Resource
REXP_TAG = /#(\S+)/
property :id, Serial
property :posted_at, DateTime
validates_present :posted_at
property :message, String, :length => (1..420)
has n, :taggings
has n, :tags, :through => :taggings, :mutable => true
before :save, :create_tags
after :save, :add_tags
def time_str
self.posted_at.strftime("%Y-%m-%d %H:%M:%S")
end
def create_tags
if includes_tag?
scrape_tags.each do |tag_name|
if Tag.first(:name => tag_name).nil?
tag = Tag.create(:name => tag_name)
raise "failed to save tag" if tag.id.nil?
end
end
end
end
def add_tags
if includes_tag?
scrape_tags.each do |tag_name|
tag = Tag.first(:name => tag_name)
raise "<BUG> tag not found" if tag.nil?
tagging = Tagging.create(:post => self, :tag => tag)
raise "failed to save tagging" if tagging.id.nil?
end
end
end
private
def includes_tag?
REXP_TAG =~ self.message
end
def scrape_tags
self.message.scan(REXP_TAG).flatten
end
end
|
class Login < ActiveRecord::Base
attr_accessible :password, :username
validates :username, :presence => true
validates :password, :presence => true
def self.authenticate(username="", login_password="")
user = Login.find_by_username(username)
password = Login.find_by_password(login_password)
if user && password
return user
else
return false
end
end
end
|
class BasePresenter
def initialize(object, template)
@object = object
@template = template
end
private
def self.presents(name)
define_method(name) do
@object
end
end
def h
@template
end
def markdown(text)
Redcarpet::Markdown.new(Redcarpet::Render::HTML.new(:hard_wrap => true), :space_after_headers => true, :autolink => true).render(text).html_safe
end
def pluralize_without_count(count, noun, text = nil)
if count != 0
count == 1 ? "#{noun}#{text}" : "#{noun.pluralize}#{text}"
end
end
end |
require 'test_helper'
class PayloadControllerTest < ActionController::TestCase
setup do
@payload_attributes = payload_factory
end
test "should accept payload that creates a profile and measurements" do
assert_difference('Profile.count') do
assert_difference('Measurement.count', 4) do
post :create, @payload_attributes
end
end
assert_response :created
end
test "should not accept a payload without a profile or measurements" do
post :create, {'payload' => {'uid' => UUIDTools::UUID.random_create.to_s } }
assert_response :unprocessable_entity
end
end
|
# frozen_string_literal: true
module PgParty
VERSION = "1.6.0"
end
|
module Rails
module ConsoleMethods
def self.included(_base)
catch(:halt) do
ConsoleCreep.config.authorization.call
return true
end
exit("Exiting console.")
end
end
end
|
class DropCertificates < ActiveRecord::Migration
def down
drop_table :certificates
drop_table :certificates_drivers
end
end
|
class Mood < ActiveRecord::Base
has_many :songs
validates :name, presence: true, uniqueness: true
validates :description, presence: true
end
|
require 'account'
describe Account do
it 'creates an account with a default empty balance' do
account = Account.new
expect(account.balance).to eq 0
end
describe '#credit' do
it 'adds the amount stated as param to the balance' do
account = Account.new
account.credit(500, '10/01/2017')
expect(account.balance).to eq 500
end
end
describe '#debit' do
it 'deducts the amount stated as param from the balance' do
account = Account.new
account.debit(250, '10/01/2017')
expect(account.balance).to eq -250
end
end
end
|
FactoryBot.define do
factory :request_statistic do
truncated_time { generate(:truncated_time) }
tenant { generate(:name) }
number_of_hits { generate(:number_of_hits) }
number_of_lti_launches { generate(:number_of_lti_launches) }
number_of_errors { generate(:number_of_errors) }
end
end
|
require 'spec_helper'
require_relative '../../../lib/paths'
using StringExtension
using ArrayExtension
using SymbolExtension
module Jabverwock
RSpec.describe 'css test' do
class << self
def bodier
body = BODY.new
### JSFunction ####
h1 = HEADING.new.attr(:id__id01).contentIs "My First Page"
hv = h1.js.doc.byID.firstChild(:value).cut
h1.js.doc.byID.firstChild(:value).is_var(:myHead)
title = TITLE.new.attr(:id__demo).contentIs "DOM Tutorial"
title.js.doc.byID.childNodes(0,:value).is_var(:myTitle)
pp = P.new.attr(:id__id02)
pp.js.doc.byID.innerHTML(hv)
body.addChildren h1,title,pp
body
end
end
html = HTML.new
html.addChild bodier
doc = DOCTYPE.new
doc.addMember html
doc.pressTo(name: 'indexPressed.html', dist: KSUtil.pathForTest(__FILE__))
# show diff
KSUtil.myDiff(__FILE__)
end
end
|
require 'perlin_noise'
require 'delve/generator/map'
class Noise < Map
@@grains = {
:fine => 0.03,
:coarse => 0.1
}
def initialize width, height, grain
raise 'Cannot initialize noise generator when width is less than zero' if width < 0
raise 'Cannot initialize noise generator when height is less than zero' if height < 0
raise 'Cannot initialize noise generator when grain is not defined' unless grain
raise 'Cannot initialize noise generator with unknown grain' unless @@grains.include?(grain)
super width, height
@grain = @@grains[grain]
@inverse = 1/@grain
end
def generate
noise = Perlin::Noise.new 2
0.step((@width-1) * @grain, @grain) do |x|
0.step((@height-1) * @grain, @grain).each do |y|
yield(x*@inverse, y*@inverse, noise[x, y])
end
end
end
end
|
class CreateBookmarks < ActiveRecord::Migration
def self.up
create_table :bookmarks do |t|
t.text :meta
t.string :orig_title
t.string :orig_description
t.string :url
t.string :uid
t.timestamps
end
Bookmark.create_translation_table! :title => :string, :description => :text, :content => :text
end
def self.down
drop_table :bookmarks
Bookmark.drop_translation_table!
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.