text stringlengths 10 2.61M |
|---|
#!/usr/bin/env ruby
$: << File.dirname(__FILE__)
require 'fadownloader_common'
## TODO: don't download images if their metadata matches
## TODO: add EXIF tags to jpeg images -- original url, keywords, image name and image description
## TODO: get username and password from osx keychain
## TODO: generate empty config file if it doesn't exist
## TODO: use a HEAD request and compare metadata
appconfig = AppConfig.instance
FileUtils.mkpath appconfig[:settings_directory]
#####################
## parse command line
#####################
optparse = OptionParser.new do |opts|
opts.banner = "Usage: fadownloader.rb [options] artist1 artist2 ..."
appconfig.verbose = true
opts.on('-q', '--quiet', 'Output less info') do appconfig.verbose = false end
opts.on('-d', '--download-directory dir', String, "Specify download directory (default: #{appconfig.download_directory})") do |v|
appconfig.download_directory = v if v
end
opts.on_tail('-h', '--help', 'Display this screen') do puts opts; exit end
end
optparse.parse!
#############
## initialize
#############
logs "Being verbose"
#agent = Mechanize.new { |a| a.log = Logger.new("mech.log") }
agent = Mechanize.new
agent.max_history = 0
agent.user_agent = "FADownloader-ruby/1.0 watchlist https://github.com/afurry/fadownloader"
## initialise database
db = AppDatabase.new(appconfig[:database_filepath])
## load config
begin
appconfig.loadconfig
rescue
$stderr.puts "Couldn't load configuration -- #{$!.inspect}"
$stderr.puts ""
$stderr.puts "Please create a file '#{appconfig[:config_filepath]}' with contents like this:"
$stderr.puts "username: <your username>"
$stderr.puts "password: <your password>"
$stderr.puts ""
$stderr.puts "And run this program again"
exit 1
end
## load cookies
agent.cookie_jar.load(appconfig[:cookies_filepath], :cookiestxt) if File.exists?(appconfig[:cookies_filepath])
## Login
logs 'Going to front page to check login'
page = agent.get(appconfig[:url_base])
page = check_and_login(agent, page)
# Go to watchlist page
logs 'Loading watchlist submissions'
url = appconfig[:url_base] + "/" + appconfig[:url_watchlist_submissions]
page = agent.get(url)
didsleep = false
while true do
form = page.form_with(:name => 'messages-form')
if form == nil
logs "No images on page, exiting"
exit
end
didsleep = false
checkboxes = form.checkboxes_with(:name => /submissions/)
logs 'Got ' + checkboxes.length.to_s + ' images on watchlist page'
if checkboxes.length == 0
logs "No new submissions in watchlist, exiting"
exit
end
# extract images to download from these checkboxes
pictures = Hash.new
checkboxes.each do |box|
image_url = '/view/' + box.value + '/'
pictures[image_url] = box.value
end
logs "Nothing new to download" if pictures.length == 0
FileUtils.mkpath appconfig.download_directory
## download gathered links
counter = 0
pictures.keys.natural_sort.reverse.each do |key|
counter += 1
# image without an href -- deleted image, don't download, already marked for removal by FA
link = page.link_with(:href => key)
if link == nil
logs "Image " + key + " was deleted by author, marking as viewed"
form.checkbox_with(:value => pictures[key]).check
next
end
log_print "Getting image #{key} (#{counter} of #{pictures.length})"
## get image
filename = downloadfrompage(key, agent, db)
## if success, mark image for removal from watchlist
form.checkbox_with(:value => pictures[key]).check if filename != nil
end
numchecked = form.checkboxes_with(:name => /submissions/, :checked => true).length
if numchecked == 0
logs "No images checked, exiting"
exit
end
logs "Marking #{numchecked} images as viewed"
button = form.button_with(:value => "remove_checked")
page = form.click_button(button)
end
|
#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
BackboneDataBootstrap::Application.load_tasks
namespace :konacha do
task :run_with_headless do
require "headless"
Headless.ly do
Rake::Task["konacha:run"].invoke
end
end
end
task default: ["konacha:run_with_headless", :spec]
|
class AddFailDatetimeToStopSmokingInfo < ActiveRecord::Migration[5.2]
def change
add_column :stop_smoking_infos, :fail_datetime, :datetime
add_column :stop_smoking_infos, :fail_flag, :boolean , default: false , null:false
end
end
|
module PixivApi
class Response
class Identity < Response
attr_reader :id
def initialize(*)
super
@attributes.fetch(:id)
end
end
end
end
|
require "rails_helper"
RSpec.describe "Ordering model", type: :model do
class User < ApplicationRecord
include Orderable
scope :order_by_email, ->(direction) {
order(email: direction)
}
end
describe ".order_by" do
it "orders by a scope" do
second_record = create(:user, email: "second@email.com")
first_record = create(:user, email: "first@email.com")
ordered = User.order_by(:email, :asc)
expect(ordered.first).to eq(first_record)
expect(ordered.second).to eq(second_record)
end
it "falls through to a column if the scope does not exist" do
second_record = create(:user, first_name: "second")
first_record = create(:user, first_name: "first")
ordered = User.order_by(:first_name, :asc)
expect(ordered.first).to eq(first_record)
expect(ordered.second).to eq(second_record)
end
end
end
|
require 'rails/generators'
require 'rails/generators/active_record'
module InhouseEvents
module Generators
class InstallGenerator < Rails::Generators::Base
include ActiveRecord::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
desc 'Create an initializer and routing for InhouseEvents.'
def create_configuration
template 'inhouse_events.rb', 'config/initializers/inhouse_events.rb'
end
def require_inhouse_events_js
inject_into_file 'app/assets/javascripts/application.js',
before: "//= require_tree .\n" do
<<-"JS"
//= require inhouse_events
JS
end
end
def add_routes
route 'mount InhouseEvents::Engine, at: "/inhouse_events"'
end
def create_events_table_migration
migration_template('inhouse_events_migration.rb.erb',
'db/migrate/create_inhouse_events.rb')
end
end
end
end
|
require('minitest/autorun')
require('minitest/reporters')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
require_relative('../bicycle.rb')
class TestBicycle < Minitest::Test
def setup
@bike = Bicycle.new()
end
def test_bicycle_has_two_wheels
assert_equal(2, @bike.number_of_wheels)
end
end
|
class Elo < ActiveRecord::Base
STARTER_BOUNDRY = 30
INITIAL_RATING = 1500
PRO_RATING = 1700
K_FACTOR_STARTER = 25
K_FACTOR_PRO = 10
K_FACTOR_OTHER = 15
belongs_to :player
def self.expected(own_rating, opponent_rating)
1.0 / ( 1.0 + ( 10.0 ** ((opponent_rating - own_rating) / 400.0) ) )
end
end
|
require 'rails_helper'
RSpec.describe CommentHelper do
let!(:question_comment) { create(:comment, commentable: create(:question)) }
let!(:answer_comment) { create(:comment, commentable: create(:answer)) }
describe '#comment_path' do
it 'question_comment' do
expect(helper.comment_path(question_comment))
.to eq "/questions/#{question_comment.commentable.id}"
end
it 'answer_comment' do
expect(helper.comment_path(answer_comment))
.to eq "/questions/#{answer_comment.commentable.question.id}"
end
end
end
|
class DropboxBackupWorker
include Sidekiq::Worker
DEBOUNCE_TIME = 2.minutes
def self.perform_debounced(user_id)
$redis.with do |conn|
jid = conn.get("dropbox_backup_jid:#{user_id}")
if jid.nil? # Create job
jid = perform_in(DEBOUNCE_TIME, user_id)
else # Reset timer
job = Sidekiq::ScheduledSet.new.find_job(jid)
job.reschedule(DEBOUNCE_TIME.from_now)
end
conn.set("dropbox_backup_jid:#{user_id}", jid, {ex: DEBOUNCE_TIME})
end
end
def perform(user_id)
# Generate the backup
user = User.find(user_id)
backup = ListBackup.new(user)
# Upload the backup
client = Dropbox::API::Client.new(token: user.dropbox_token, secret: user.dropbox_secret)
begin
client.upload('library-backup.json', backup.to_json)
rescue Dropbox::API::Error::Unauthorized
user.update(dropbox_token: nil, dropbox_secret: nil)
return
rescue Dropbox::API::Error::StorageQuota
# TODO: notify the user
return
end
# Update the last_backup timestamp
user.update(last_backup: DateTime.now)
end
end
|
describe Game do
subject {Game.new()}
describe "#switch_player" do
it "should change who's turn it is" do
expect(subject.current_turn).to eq 'x'
subject.switch_player
expect(subject.current_turn).to eq 'o'
end
it "should lower the number of remaining turns by 1" do
subject.switch_player
expect(subject.remaining_turns).to eq 8
end
end
describe "#do_turn" do
it "should place the current player's marker in a field then switch the current player" do
expect(subject.current_turn).to eq 'x'
subject.do_turn(1,1)
expect(subject.current_turn).to eq 'o'
expect(subject.board.get_element_value(1,1)).to eq 'x'
end
it "should only place markers in empty fields" do
subject.do_turn(1,1)
expect {subject.do_turn(1,1)}.to_not change {subject.board.get_element_value(1,1)}
end
it "should not change turn if an invalid move is attempted" do
expect(subject.current_turn).to eq 'x'
subject.do_turn(1,1)
subject.do_turn(1,1)
expect(subject.current_turn).to eq 'o'
end
end
describe "#game_over?" do
it "should return true if remaining turns reach 0" do
#will be changed when i start mocking
subject.do_turn(0,0)
subject.do_turn(0,1)
subject.do_turn(0,2)
subject.do_turn(1,0)
subject.do_turn(1,1)
subject.do_turn(1,2)
subject.do_turn(2,0)
subject.do_turn(2,1)
subject.do_turn(2,2)
expect(subject.game_over?(2,2)).to eq true
end
it "should return true if win_check is true" do
allow(subject).to receive(:win_check).and_return(true)
expect(subject.game_over?(0,0)).to eq true
end
end
describe "#win_check" do
it "should return false if the game isn't won" do
subject.do_turn(0,0)
expect(subject.win_check(0,0)).to eq false
end
it "should return true if row 0 contains all the same token" do
subject.do_turn(0,1)
subject.do_turn(1,2)
subject.do_turn(0,2)
subject.do_turn(2,2)
subject.do_turn(0,0)
expect(subject.win_check(0,0)).to eq true
end
it "should return true if row 1 contains all the same token" do
subject.do_turn(1,0)
subject.do_turn(0,0)
subject.do_turn(1,1)
subject.do_turn(2,0)
subject.do_turn(1,2)
expect(subject.win_check(1,2)).to eq true
end
it "should return true if row 2 contains all the same token" do
subject.do_turn(2,0)
subject.do_turn(0,0)
subject.do_turn(2,1)
subject.do_turn(1,2)
subject.do_turn(2,2)
expect(subject.win_check(2,2)).to eq true
end
it "should return true if column 0 contains all the same token" do
subject.do_turn(1,0)
subject.do_turn(1,2)
subject.do_turn(2,0)
subject.do_turn(2,2)
subject.do_turn(0,0)
expect(subject.win_check(0,0)).to eq true
end
it "should return true if column 1 contains all the same token" do
subject.do_turn(1,1)
subject.do_turn(1,2)
subject.do_turn(2,1)
subject.do_turn(2,2)
subject.do_turn(0,1)
expect(subject.win_check(0,1)).to eq true
end
it "should return true if column 2 contains all the same token" do
subject.do_turn(1,2)
subject.do_turn(1,1)
subject.do_turn(2,2)
subject.do_turn(2,1)
subject.do_turn(0,2)
expect(subject.win_check(0,2)).to eq true
end
it "should return true if the TL BR diagonal contains all the same token" do
subject.do_turn(0,0)
subject.do_turn(1,0)
subject.do_turn(1,1)
subject.do_turn(2,0)
subject.do_turn(2,2)
expect(subject.win_check(2,2)).to eq true
end
it "should return true if the BL TR diagonal contains all the same token" do
subject.do_turn(0,2)
subject.do_turn(1,0)
subject.do_turn(1,1)
subject.do_turn(2,1)
subject.do_turn(2,0)
expect(subject.win_check(2,0)).to eq true
end
end
end
|
class AddNameAndStorageLevelToFileGroups < ActiveRecord::Migration
def up
add_column :file_groups, :name, :string
add_column :file_groups, :storage_level, :string
FileGroup.all.each do |file_group|
file_group.name ||= "File group #{file_group.id}"
file_group.storage_level ||= 'external'
file_group.save!
end
end
def down
remove_column :file_groups, :name
remove_column :file_groups, :storage_level
end
end
|
class AddContentToJobColumn < ActiveRecord::Migration
def change
add_column :job_columns, :content, :string
end
end
|
require 'rails_helper'
RSpec.feature "Contacts Features", type: :feature do
scenario "List Contacts" do
Given "I visit the home page" do
visit "/"
end
When "I click on the Conctacts link" do
click_link "Contacts"
end
Then "I should be on the Contacts page" do
expect(page).to have_content("Listing Contacts")
end
end
scenario "List Contacts" do
Given "I visit the home page" do
visit "/"
end
When "I click on the Conctacts link" do
click_link "Contacts"
end
Then "I should be on the Contacts page" do
expect(page).to have_content("Listing Contacts")
end
end
scenario "List Contacts" do
Given "I visit the home page" do
visit "/"
end
When "I click on the Conctacts link" do
click_link "Contacts"
end
Then "I should be on the Contacts page" do
expect(page).to have_content("Listing Contacts")
end
end
scenario "List Contacts" do
Given "I visit the home page" do
visit "/"
end
When "I click on the Conctacts link" do
click_link "Contacts"
end
Then "I should be on the Contacts page" do
expect(page).to have_content("Listing Contacts")
end
end
scenario "List Contacts" do
Given "I visit the home page" do
visit "/"
end
When "I click on the Conctacts link" do
click_link "Contacts"
end
Then "I should be on the Contacts page" do
expect(page).to have_content("Listing Contacts")
end
end
end
|
require 'trip_planner/edge'
class Node
attr_reader :name, :edges
def initialize(name, edges = [])
@name = name
@edges = edges
end
def create_edge(destination, depart_at, arrive_at, cost)
edges.push Edge.new(self, destination, depart_at, arrive_at, cost)
end
end
|
class Admin < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
validates :name, :presence => true
validates :password, :presence => true
validates :password, :length => { :minimum => 6 }, :unless => proc { |admin| admin.password.blank? }
validates :password_confirmation, :presence => true, :unless => proc { |admin| admin.password.blank? }
validates :email, :presence => true
validates_format_of :email,
:with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i,
:message => "Doesn't Looks the correct email ID",
:unless => proc { |user| user.email.blank? }
validates :email, :uniqueness => true, :unless => proc { |admin| admin.email.blank? }
end
|
class RenameSensesToSensesRawInEntries < ActiveRecord::Migration
def up
rename_column :entries, :senses, :senses_raw
end
def down
end
end
|
require 'rails_helper'
describe Api::V1::EpisodesController do
describe "GET Episode #show" do
before(:each) do
@api_key = FactoryGirl.create(:api_key)
@episode = FactoryGirl.create :episode
end
it "returns the information for a specific episode in a hash" do
my_get "seasons/#{@episode.season_id}/episodes/#{@episode.id}",
nil, { "HTTP_AUTHORIZATION"=>"Token token=\"#{@api_key.access_token}\"" }
season_response = JSON.parse(response.body, symbolize_names: true)
expect(response.body).not_to be_empty
end
end
describe "GET Episode #index" do
before(:each) do
@api_key = FactoryGirl.create(:api_key)
@episode = FactoryGirl.create :episode
end
it "returns the information about all episodes in a season in a hash" do
my_get "seasons/#{@episode.season_id}/episodes",
nil, { "HTTP_AUTHORIZATION"=>"Token token=\"#{@api_key.access_token}\"" }
expect(response.body).not_to be_empty
expect(response).to have_http_status(200)
end
it "returns the information about all episodes in a show in a hash" do
my_get "shows/#{@episode.show_id}/episodes",
nil, { "HTTP_AUTHORIZATION"=>"Token token=\"#{@api_key.access_token}\"" }
expect(response.body).not_to be_empty
expect(response).to have_http_status(200)
end
end
describe "GET current episodes" do
before(:each) do
@api_key = FactoryGirl.create(:api_key)
@episode = FactoryGirl.create :episode
end
it "returns the episode with current view time" do
my_get "episodes/current", nil, { "HTTP_AUTHORIZATION"=>"Token token=\"#{@api_key.access_token}\"" }
expect(response.body).not_to be_empty
expect(response).to have_http_status(200)
end
end
end
|
class AddForeignKeyToSalesAndUsers < ActiveRecord::Migration
def change
add_foreign_key :sales, :users
end
end
|
#! /usr/bin/env ruby -S rspec
require 'spec_helper'
describe 'the dns_mx function' do
let(:scope) { PuppetlabsSpec::PuppetInternals.scope }
it 'should exist' do
expect(Puppet::Parser::Functions.function('dns_mx')).to eq('function_dns_mx')
end
it 'should raise a ArgumentError if there is less than 1 arguments' do
expect { scope.function_dns_mx([]) }.to raise_error(ArgumentError)
end
it 'should raise a ArgumentError if there is more than 2 arguments' do
expect { scope.function_dns_mx(['foo', 'bar', 'baz']) }.to raise_error(ArgumentError)
end
it 'should return a list of MX records when doing a lookup' do
results = scope.function_dns_mx(['google.com'])
expect(results).to be_a Array
expect(results).to all( be_a Array )
results.each do |res|
expect(res.length).to eq(2)
expect(res[0]).to be_a Integer
expect(res[1]).to be_a String
end
end
it 'should return a list of MX preferences when doing a lookup specifying that' do
results = scope.function_dns_mx(['google.com', 'preference'])
expect(results).to be_a Array
expect(results).to all( be_a Integer )
end
it 'should return a list of MX exchanges when doing a lookup specifying that' do
results = scope.function_dns_mx(['google.com', 'exchange'])
expect(results).to be_a Array
expect(results).to all( be_a String )
end
it 'should raise a ArgumentError for invalid values to second argument' do
expect { scope.function_dns_mx(['google.com', 'foo']) }.to raise_error(ArgumentError)
end
it 'should raise an error on empty reply' do
expect { scope.function_dns_mx(['foo.example.com']) }.to raise_error(Resolv::ResolvError)
end
end
|
require "bcrypt"
require "digest"
require "cloud-notes/data"
require "cloud-notes/note"
module CloudNotes
class User
class InvalidUserNameError < StandardError
end
class InvalidPasswordError < StandardError
end
class UnauthorizedError < StandardError
end
class UserExistsError < StandardError
end
def self.check_user_name(user_name)
unless user_name=~ /\A[A-Za-z0-9_-]+\Z/
raise InvalidUserNameError, "user name is invalid"
end
end
def self.create(data_dir, user_name, password)
check_user_name(user_name)
user_dir= data_dir+"users"+user_name
password_data= Data.new(user_dir+"password_hash")
user= password_data.writelock do
unless password_data.read.empty?
raise UserExistsError, "user exists"
end
password_data.write(BCrypt::Password.create(password, :cost => 13).to_s)
Note.save(data_dir, "#{user_name}/welcome", "Welcome #{user_name} to the best cloud note taking plattform.")
note_name_prefix_data= Data.new(user_dir+"note_name_prefix")
note_name_prefix_data.write("#{user_name}/")
write_access_data= Data.new(user_dir+"write_access")
write_access_data.write("true")
self.new(data_dir, user_name)
end
user.send(:finish_authorization)
user
end
def initialize(data_dir, user_name)
@data_dir= data_dir
self.class.check_user_name(user_name)
@user_dir= data_dir+"users"+user_name
@user_name= user_name
@authorized= false
@writey_access= false
@note_name_prefix= nil
end
attr_reader :note_name_prefix
def name
@user_name
end
def authorize(password)
password_data= Data.new(@user_dir+"password_hash")
password_data.readlock do
bcrypt_stuff= password_data.read
unless not bcrypt_stuff.empty? and BCrypt::Password.new(password_data.read) == password
raise InvalidPasswordError, "invalid password"
end
end
finish_authorization
end
def finish_authorization
write_access_data= Data.new(@user_dir+"write_access")
@write_access= write_access_data.read == "true"
note_name_prefix_data= Data.new(@user_dir+"note_name_prefix")
@note_name_prefix= note_name_prefix_data.read
@authorized= true
end
private :finish_authorization
def check_authorized
unless @authorized
raise UnauthorizedError, "not authorized"
end
end
def login_token(salt)
check_authorized
password_data= Data.new(@user_dir+"password_hash")
password_data.readlock do
Digest::SHA256.hexdigest(password_data.read+salt)
end
end
def authorize_with_token(token, salt)
password_data= Data.new(@user_dir+"password_hash")
password_data.readlock do
bcrypt_stuff= password_data.read
unless not bcrypt_stuff.empty? and Digest::SHA256.hexdigest(bcrypt_stuff+salt) == token
raise InvalidPasswordError, "invalid password"
end
end
finish_authorization
end
def authorized?
@authorized
end
def change_password(new_password)
check_authorized
password_data= Data.new(@user_dir+"password_hash")
password_data.writelock do
password_data.write(BCrypt::Password.create(new_password, :cost => 13).to_s)
end
end
def test_prefix(note_name)
@note_name_prefix and
note_name[0, @note_name_prefix.size] == @note_name_prefix
end
def get_note(note_name, password= nil)
note= Note.read(@data_dir, note_name, password)
unless note.password_correct? or test_prefix(note_name)
raise UnauthorizedError, "not authorized for this note"
end
note.content
end
def set_note(note_name, note_content, password)
check_authorized
unless @write_access
raise UnauthorizedError, "not authorized"
end
unless test_prefix(note_name)
raise UnauthorizedError, "not authorized for this note"
end
Note.save(@data_dir, note_name, note_content, password)
end
def list_notes(note_dir)
check_authorized
unless test_prefix(note_dir)
raise UnauthorizedError, "not authorized for this directory"
end
Note.list(@data_dir, note_dir)
end
end
end
|
class Api::V1::ProjectsController < Api::V1::BaseController
def show
@project = Project.revealed.find(params[:id])
render json: ProjectSerializer.new(@project).serialized_json
end
end
|
#encoding: utf-8
class Restaurant
include Mongoid::Document
include Mongoid::Timestamps
store_in collection: "restaurants", database: "dishgo"
field :lat, type: Float
field :lon, type: Float
field :subdomain, type: String
field :host, type: String
field :preview_token, type: String
field :locs, type: Array
field :menu, type: Hash
# field :images, type: Array
field :name, type: String
field :multi_name, localize: true
field :city, type: String
field :email, type: String
field :email_addresses, type: Array
field :address_line_1, type: String
field :address_line_2, type: String
field :province, type: String
field :postal_code, type: String
field :phone, type: String
field :website, type: String
field :facebook, type: String
field :facebook_page_id, type: String
field :foursquare, type: String
field :twitter, type: String
field :urbanspoon, type: String
field :instagram, type: String
field :languages, type: Array, default: ['en','fr']
field :default_language, type: String
field :category, type: Array
field :listed, type: Boolean, default: false
field :with_menu, type: Boolean, default: false
field :show_hours, type: Boolean, default: true
field :show_map, type: Boolean, default: true
field :show_menu, type: Boolean, default: true
field :show_ask, type: Boolean, default: true
field :show_gallery, type: Boolean, default: false
field :show_app_install, type: Boolean, default: false
field :reservation_widget, type: String
field :reservation_widget_active, type: Boolean, default: false
field :does_delivery, type: Boolean, default: false
field :rating, type: Float
field :beautiful_url, type: String
field :hours, type: Hash
belongs_to :font, class_name: "Font", index: true
has_many :global_images, class_name: "GlobalImage", inverse_of: :restaurant
has_one :logo, class_name: "GlobalImage", inverse_of: :restaurant_logo, validate: false
has_many :menu_images, class_name: "GlobalImage", inverse_of: :restaurant_menu_images
has_many :cover_photos, class_name: "CoverPhoto", inverse_of: :restaurant
field :logo_settings, type: Hash
field :website_settings, type: Hash
has_many :sources, :class_name => "Sources"
has_many :image, :class_name => "Image", inverse_of: :restaurant, validate: false
has_many :icons, :class_name => "Icon", inverse_of: :restaurant
has_many :gallery_images, :class_name => "Image", inverse_of: :restaurant_gallery
has_many :website_images, :class_name => "WysiwygImage", inverse_of: :restaurant
has_many :pages, :class_name => "Page", inverse_of: :restaurant
has_many :prizes, :class_name => "Prize", inverse_of: :restaurant
has_many :section, :class_name => "Section", inverse_of: :restaurant
has_many :dishes, :class_name => "Dish", inverse_of: :restaurant
has_many :options, :class_name => "DishOption", inverse_of: :restaurant
has_many :individual_options, :class_name => "IndividualOption", inverse_of: :restaurant
# has_many :draft_menu, :class_name => "Section", inverse_of: :draft_restaurant
# has_many :published_menu, :class_name => "Section", inverse_of: :published_restaurant
has_many :menus, :class_name => "Menu", inverse_of: :restaurant
has_many :menu_files, :class_name => "MenuFiles", inverse_of: :restaurant
has_many :orders, :class_name => "Order"
belongs_to :user, :class_name => "User", index: true, inverse_of: :owns_restaurants
has_one :odesk, :class_name => "Odesk", inverse_of: :restaurant, validate: false
has_one :cache, :class_name => "Cache", inverse_of: :restaurant, validate: false
has_many :ratings, :class_name => "Rating", inverse_of: :restaurant
has_many :page_views, :class_name => "PageView", inverse_of: :restaurant
has_many :page_views_hourly, :class_name => "PageViewHour", inverse_of: :restaurant
has_many :page_views_daily, :class_name => "PageViewDay", inverse_of: :restaurant
belongs_to :design, index: true
accepts_nested_attributes_for :image, :allow_destroy => false
index({ name: 1 }, { name: "name_index" })
index({ _id:1 }, { unique: true, name:"id_index" })
index({ locs: "2dsphere" }, { name:"location_index"})
index({ subdomain: 1}, {name: "subdomain_index"})
index({ with_menu: 1}, {name: "with_menu_index"})
index({ host: 1}, {name: "host_index"})
index({ facebook_page_id: 1}, {name: "facebook_page_id_index"})
index({ preview_token: 1}, {name: "preview_token_index"})
scope :has_menu, -> { ne(with_menu:false) }
# scope :has_menu, -> { any_in(:_id => includes(:section).select{ |w| w.section.size > 0 }.map{ |r| r.id }) }
scope :only_with_menu, -> { where(with_menu:true) }
before_save :set_with_menu
before_save :beautify_url
def set_with_menu
if !with_menu
if menus.count > 0
self.with_menu = true
end
end
end
def by_loc loc=nil
# if kd = KdTree.new and ids = kd.find(loc[0],loc[1])
# return Restaurant.where(id:ids,listed:true)
# end
if loc
cords = [loc[1],loc[0]]
else
cords = [-74.155815,45.458972]
end
return Restaurant.where(:locs => { "$near" => { "$geometry" => { "type" => "Point", :coordinates => cords }, "$maxDistance" => 50000}}, listed: true)
end
def dish_images
resto = Restaurant.where(:name=>/cun/i).first
images = resto.image.reject{|e| e.rejected}
sections = resto.section
sub = sections.collect{|r| r.subsection}.flatten
dishes = sub.collect{|r| r.dish}.flatten
dishes.each_with_index do |x,i|
x.image = []
if Random.rand(2) == 1
num = Random.rand(images.size)
# puts "making image [#{num}] -> #{images[num].local_file}"
x.image << images[num]
else
# puts "no image"
end
x.save(:validate=>false)
end
nil
end
def copy_menu_from_restaurant restaurant
self.languages = restaurant.languages
self.does_delivery = restaurant.does_delivery
self.category = restaurant.category
self.hours = restaurant.hours
restaurant.menus.each do |menu|
menu_dup = menu.dup
menu_dup.restaurant_id = self.id
menu_dup.save
menu.published_menu.pub.each do |section|
section_dup = section.dup
section_dup.restaurant_id = self.id
section_dup.published_menu_id = menu_dup.id
section_dup.save
section.dishes.each do |dish|
dish_dup = dish.dup
dish_dup.restaurant_id = self.id
dish_dup.section_id = section_dup.id
dish_dup.save
dish.image.each do |image|
image_dup = image.dup
image_dup.restaurant_id = self.id
image_dup.dish_id = dish_dup.id
image_dup.save
end
id_match = {}
if dish.sizes
sizes_dup = dish.sizes.dup
sizes_dup.restaurant_id = self.id
sizes_dup.dish_which_uses_this_as_size_options_id = dish_dup.id
sizes_dup.save
dish.sizes.individual_options.each do |ind_opt|
ind_opt_dup = ind_opt.dup
ind_opt_dup.restaurant_id = self.id
ind_opt_dup.options_id = sizes_dup.id
ind_opt_dup.save
id_match[ind_opt.id.to_s] = ind_opt_dup.id.to_s
end
end
dish.options.each do |option|
option_dup = option.dup
option_dup.restaurant_id = self.id
option_dup.dish_id = dish_dup.id
option_dup.save
option.individual_options.each do |ind_opt|
ind_opt_dup = ind_opt.dup
ind_opt_dup.restaurant_id = self.id
ind_opt_dup.options_id = option_dup.id
# Set size_id to point to new size object ids.
ind_opt_dup.size_prices.each do |size_price|
size_price['size_id'] = id_match[size_price['size_id']]
end
ind_opt_dup.save
end
end
end
end
menu_dup.reload
menu_dup.reset_draft_menu
end
self.listed = true
if logo_copy = restaurant.logo and logo_copy = logo_copy.dup
logo_copy.restaurant_logo_id = self.id
logo_copy.save
end
self.save
self.reload
self.publish_menu
end
# def copy_section_from_restaurant section
# section_dup = section.dup
# section_dup.restaurant = self
# section_dup.dishes = section.dishes.collect do |dish|
# dish_dup = dish.dup
# dish_dup.restaurant = self
# dish_dup.image = dish.image.collect do |image|
# image_dup = image.dup
# image_dup.restaurant = self
# image_dup.save
# next image_dup
# end
# id_match = {}
# if dish.sizes
# sizes_dup = dish.sizes.dup
# sizes_dup.restaurant = self
# sizes_dup.individual_options = dish.sizes.individual_options.collect do |ind_opt|
# ind_opt_dup = ind_opt.dup
# ind_opt_dup.restaurant = self
# ind_opt_dup.save
# id_match[ind_opt.id.to_s] = ind_opt_dup.id.to_s
# next ind_opt_dup
# end
# dish_dup.sizes = sizes_dup
# end
# dish_dup.options = dish.options.collect do |option|
# option_dup = option.dup
# option_dup.restaurant = self
# option_dup.individual_options = option.individual_options.collect do |ind_opt|
# ind_opt_dup = ind_opt.dup
# ind_opt_dup.restaurant = self
# # Set size_id to point to new size object ids.
# ind_opt_dup.size_prices.each do |size_price|
# size_price['size_id'] = id_match[size_price['size_id']]
# end
# ind_opt_dup.save
# next ind_opt_dup
# end
# option_dup.save
# next option_dup
# end
# dish_dup.save
# next dish_dup
# end
# section_dup.save
# self.published_menu << section_dup
# self.draft_menu = self.published_menu
# self.draft_menu.each do |draft_section|
# draft_section.reset_draft_menu
# end
# self.save
# end
def beautify_url
return if self.beautiful_url.to_s.length > 0
string = []
begin
beauty = self.name.to_s.gsub(/[^[:alpha:] ]/,'').split(" ").join("_").downcase
if !string.empty?
beauty = beauty + "_" + string.join("_").downcase
end
if string.empty?
string << self.city.to_s
else
string << (65 + rand(26)).chr
end
end while Restaurant.where(beautiful_url:beauty).count > 0
self.beautiful_url = beauty
end
def menu_to_json
icon_list = self.icons.collect{|e| e.individual_option_id}
menu_to_spit_out = self.published_menu.pub
if menu_to_spit_out.empty?
menu_to_spit_out = Restaurant.where(name:/tuckshop/i).first.published_menu.pub
end
menu = menu_to_spit_out.collect do |section|
hash = section.as_document
hash[:id] = section.id
hash["dishes"] = section.dishes.pub.collect do |dish|
dish.custom_to_hash icon_list
end
next hash
end
return Oj.dump(menu)
end
def draft_menu_to_json
menu = self.draft_menu.unscoped.draft.collect do |section|
hash = section.as_document
hash[:id] = section.id
hash.merge!(section.draft)
hash["dishes"] = section.draft_dishes.unscoped.draft.collect do |dish|
dish.custom_to_hash_draft
end
next hash
end
return Oj.dump(menu)
end
def print_reviews
puts name
ratings.each do |review|
next if !review.created_at
puts review.dish.name
puts "Time: #{review.created_at.in_time_zone("Eastern Time (US & Canada)")} Rating: #{review.rating} Review: '#{review.review}'"
puts "------------------------"
end
end
def enough_info?
enough = true
enough = false if self.address_line_1.blank?
enough = false if self.phone.blank?
enough = false if self.name.blank? or self.name == "New Restaurant"
return enough
end
def calculate_rating
rating_count = ratings.count
return 0 if rating_count == 0
rating_total = 0
ratings.each do |rate|
rating_total += rate.rating
end
rating = (rating_total.to_f / rating_count.to_f).round_half
end
def serializable_hash options = {}
hash = super options
if self.logo
hash[:logo] = self.logo.as_document
end
hash["multi_name"] = self.multi_name_translations
return hash
end
def as_document options = {}
hash = super()
if !options[:skip_logo] and self.logo
hash["logo"] = self.logo.as_json
end
if !options[:pages] and self.pages
hash["pages"] = self.pages.as_json
end
if !options[:pages] and self.gallery_images
hash["gallery_images"] = self.gallery_images.as_json
end
if !options[:cover_photos]
hash["cover_photos"] = self.cover_photos.as_json
end
if options[:include_images] and self.image
hash["image"] = self.image.profile_images.limit(options[:include_images]).as_json
end
if options[:prizes]
hash["prizes"] = self.prizes.available_to_win.count
end
hash["multi_name"] = self.multi_name_translations
return hash
end
#JSON GENERATORS
def onlinesite_json
return self.menus.pub.collect{|e| e.menu_json }.as_json.to_json
end
def api_menu_to_json
default_menu = self.menus.def.first
sections = []
sections = default_menu.published_menu.pub if default_menu
other_sections = self.menus.not_def.collect do |more_sections|
next more_sections.published_menu.pub
end
section_ids = [sections, other_sections].flatten.compact.collect{|e| e.id}
menu_hash = self.languages.inject({}) do |res,lang|
sections = Section.find(section_ids).sort_by{|m| section_ids.index(m.id) }
menu = sections.collect do |section|
hash = section.as_document
hash[:id] = section.id
hash["position"] = section_ids.index(section.id)
hash["name"] = section.name_translations[lang]
hash["dishes"] = section.dishes.pub.collect do |dish|
dish.api_custom_to_hash(lang)
end
next hash
end
res[lang] = Oj.dump(menu)
next res
end
return menu_hash
end
#long running publish menu
def publish_menu
CacheJson.new.delay.publish_menu(self.id)
end
def cache_job
CacheJson.new.delay.rebuild_cache(self.id)
end
end
|
class AddValueOfToSToPhoneBookEntry < ActiveRecord::Migration
def change
add_column :phone_book_entries, :value_of_to_s, :string
end
end
|
class EventAttendancesController < ApplicationController
before_action :require_login
def create
attendance = EventAttendance.new
attendance.attended_event_id = params[:event_id]
attendance.event_attendee_id = params[:attendee_id]
attendance.save
flash[:notice] = 'You have successfully registered your attendance to this event.'
redirect_back(fallback_location: root_path)
end
def destroy
EventAttendance.where(attended_event_id: params[:event_id], event_attendee_id: params[:attendee_id]).destroy_all
flash[:notice] = 'You have successfully canceled your attendance to this event.'
redirect_back(fallback_location: root_path)
end
end
|
class ChangeColumnToItem < ActiveRecord::Migration[5.0]
def change
add_column :items, :size_id,:integer, null: false
add_column :items, :state_id,:integer, null: false
add_column :items, :fee_side_id, :integer, null: false
add_column :items, :method_id, :integer, null: false
add_column :items, :region_id, :integer, null: false
add_column :items, :date_id, :integer, null: false
remove_column :items, :size,:string, null: false
remove_column :items, :state,:string, null: false
remove_column :items, :fee_side, :string, null: false
remove_column :items, :method, :string, null: false
remove_column :items, :region, :string, null: false
remove_column :items, :date, :string, null: false
end
end
|
class RouteElement < ActiveRecord::Base
ELEMENT_ACTIONS = ['none', 'match', 'not_match', 'set']
attr_accessible :call_route_id, :var_in, :var_out, :pattern, :replacement, :action, :mandatory, :position
belongs_to :call_route, :touch => true
acts_as_list :scope => :call_route
validates :action,
:presence => true,
:inclusion => { :in => ELEMENT_ACTIONS }
def to_s
"#{pattern} => #{var_in} #{var_out}"
end
def move_up?
#return self.position.to_i > RouteElement.where(:call_route_id => self.call_route_id ).order(:position).first.position.to_i
end
def move_down?
#return self.position.to_i < RouteElement.where(:call_route_id => self.call_route_id ).order(:position).last.position.to_i
end
end
|
class Licitacao < ApplicationRecord
self.table_name = 'licitacoes'
has_many :itens_licitacoes, foreign_key:'numero_licitacao', class_name: 'ItemLicitacao'
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'faker'
100.times do
movie = Movie.create!(
name: Faker::Book.title,
year: rand(1900..2020),
genre: ["action", "horreur", "comédie", "drame"].sample,
synopsis: Faker::Lorem.sentence(word_count: 10, supplemental: true, random_words_to_add: 10),
director: Faker::Book.author,
allocine_rating: rand(0.0...5.0).round(1),
my_rating: nil,
already_seen: false)
end |
require('minitest/autorun')
require('minitest/reporters')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
require_relative('../room')
require_relative('../song')
class SongTest < Minitest::Test
def setup()
@song = Song.new("America: Horse with no name")
end
def test_song_has_name()
assert_equal("America: Horse with no name", @song.name)
end
end
|
#!/usr/bin/env ruby
# Definition for singly-linked list.
class ListNode
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def add_two_numbers(l1, l2)
addon = 0
list_return = cur = ListNode.new 0
l1_val = l1.val
l2_val = l2.val
loop do
val = l1_val + l2_val + addon
if val == 0 and l1.next.nil? and l2.next.nil?
break
end
addon = 0
if val >= 10
val = val - 10
addon = 1
end
ln = ListNode.new val
cur.next = ln
cur = ln
if !l1.next.nil?
l1 = l1.next
l1_val = l1.val
else
l1_val = 0
end
if !l2.next.nil?
l2 = l2.next
l2_val = l2.val
else
l2_val = 0
end
end
if !list_return.next.nil?
list_return = list_return.next
end
list_return
end
|
require "test_helper"
class GroupsControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
# called before every test
def setup
@request.env["HTTP_REFERER"] = "/groups"
end
# create
test "user must be signed in to create a group" do
get :create
assert_response :redirect
end
test "signed in users can create a group" do
sign_in users(:loserLarry)
assert_difference "Group.count", +1 do
get :create, params: { group: { name: "Test Group" } }
end
end
# read
test "user must be signed in to see groups" do
get :index
assert_response :redirect
end
test "signed in users can see groups" do
sign_in users(:loserLarry)
get :index
assert_response :success
end
test "user can see public group when not signed in" do
get :show, params: { id: groups(:publicGroup).id }
assert_response :success
end
test "signed in users can see a public group" do
sign_in users(:loserLarry)
get :show, params: { id: groups(:publicGroup).id }
assert_response :success
end
test "user can see private group when not signed in" do
get :show, params: { id: groups(:privateGroup).id }
assert_response :success
end
test "signed in users can see a private group" do
sign_in users(:loserLarry)
get :show, params: { id: groups(:privateGroup).id }
assert_response :success
end
test "user cannot see secret group when not signed in" do
get :show, params: { id: groups(:secretGroup).id }
assert_response :redirect
end
test "signed in users not in secret group cannot see it" do
sign_in users(:loserLarry)
get :show, params: { id: groups(:secretGroup).id }
assert_response :redirect
end
test "signed in users in secret group can see it" do
sign_in users(:memberMike)
get :show, params: { id: groups(:secretGroup).id }
assert_response :success
end
# update
test "owner can change group name in group" do
user = users(:ownerAlice)
sign_in user
post :update, params: { id: groups(:publicGroup).id, group: { name: "newName" } }
groups(:publicGroup).reload
assert_equal "newName", groups(:publicGroup).name
post :update, params: { id: groups(:privateGroup).id, group: { name: "newName" } }
groups(:privateGroup).reload
assert_equal "newName", groups(:privateGroup).name
post :update, params: { id: groups(:secretGroup).id, group: { name: "newName" } }
groups(:secretGroup).reload
assert_equal "newName", groups(:secretGroup).name
sign_out user
end
test "non-member cannot change group name in group" do
user = users(:loserLarry)
sign_in user
post :update, params: { id: groups(:publicGroup).id, group: { name: "newName" } }
groups(:publicGroup).reload
assert_equal "public", groups(:publicGroup).name
post :update, params: { id: groups(:privateGroup).id, group: { name: "newName" } }
groups(:privateGroup).reload
assert_equal "private", groups(:privateGroup).name
post :update, params: { id: groups(:secretGroup).id, group: { name: "newName" } }
groups(:secretGroup).reload
assert_equal "secret", groups(:secretGroup).name
sign_out user
end
test "member cannot change group name in group" do
user = users(:memberMike)
sign_in user
post :update, params: { id: groups(:publicGroup).id, group: { name: "newName" } }
groups(:publicGroup).reload
assert_equal "public", groups(:publicGroup).name
post :update, params: { id: groups(:privateGroup).id, group: { name: "newName" } }
groups(:privateGroup).reload
assert_equal "private", groups(:privateGroup).name
post :update, params: { id: groups(:secretGroup).id, group: { name: "newName" } }
groups(:secretGroup).reload
assert_equal "secret", groups(:secretGroup).name
sign_out user
end
test "moderator cannot change group name in group" do
user = users(:moderatorMaven)
sign_in user
post :update, params: { id: groups(:publicGroup).id, group: { name: "newName" } }
groups(:publicGroup).reload
assert_equal "public", groups(:publicGroup).name
post :update, params: { id: groups(:privateGroup).id, group: { name: "newName" } }
groups(:privateGroup).reload
assert_equal "private", groups(:privateGroup).name
post :update, params: { id: groups(:secretGroup).id, group: { name: "newName" } }
groups(:secretGroup).reload
assert_equal "secret", groups(:secretGroup).name
sign_out user
end
test "any signed in user can join public groups" do
user = users(:loserLarry)
sign_in user
get :join, params: { id: groups(:publicGroup).id }
assert user.in_group?(groups(:publicGroup))
end
test "signed in users cannot join private groups they were not invited to" do
user = users(:loserLarry)
sign_in user
get :join, params: { id: groups(:privateGroup).id }
assert_not user.in_group?(groups(:privateGroup))
end
test "signed in users cannot join secret groups they were not invited to" do
user = users(:loserLarry)
sign_in user
get :join, params: { id: groups(:secretGroup).id }
assert_not user.in_group?(groups(:secretGroup))
end
test "signed in users can leave public group" do
user = users(:memberMike)
sign_in user
get :leave, params: { id: groups(:publicGroup).id }
assert_not user.in_group?(groups(:publicGroup))
end
test "signed in users can leave private group" do
user = users(:memberMike)
sign_in user
get :leave, params: { id: groups(:privateGroup).id }
assert_not user.in_group?(groups(:privateGroup))
end
test "signed in users can leave secret group" do
user = users(:memberMike)
sign_in user
get :leave, params: { id: groups(:secretGroup).id }
assert_not user.in_group?(groups(:secretGroup))
end
test "leaving public group user is not in doesn't crash" do
user = users(:loserLarry)
sign_in user
get :leave, params: { id: groups(:publicGroup).id }
assert_not user.in_group?(groups(:publicGroup))
end
test "leaving private group user is not in doesn't crash" do
user = users(:loserLarry)
sign_in user
get :leave, params: { id: groups(:privateGroup).id }
assert_not user.in_group?(groups(:privateGroup))
end
test "leaving secret group user is not in doesn't crash" do
user = users(:loserLarry)
sign_in user
get :leave, params: { id: groups(:secretGroup).id }
assert_not user.in_group?(groups(:secretGroup))
end
test "not signed in users can not join public groups" do
get :join, params: { id: groups(:publicGroup).id }
assert_not users(:inviteIvan).in_group?(groups(:publicGroup))
end
test "not signed in users can not join private groups" do
get :join, params: { id: groups(:privateGroup).id }
assert_not users(:inviteIvan).in_group?(groups(:privateGroup))
end
test "not signed in users can not join secret groups" do
get :join, params: { id: groups(:secretGroup).id }
assert_not users(:inviteIvan).in_group?(groups(:secretGroup))
end
# delete
test "owner can delete group" do
user = users(:ownerAlice)
sign_in user
groups(:publicGroup, :privateGroup, :secretGroup).each do |group|
assert_difference -> { Group.count }, -1 do
delete :destroy, params: { id: group.id }
end
end
end
test "moderator cannot delete group" do
user = users(:moderatorMaven)
sign_in user
groups(:publicGroup, :privateGroup, :secretGroup).each do |group|
assert_no_difference -> { Group.count } do
delete :destroy, params: { id: group.id }
end
end
end
test "memeber cannot delete group" do
user = users(:memberMike)
sign_in user
groups(:publicGroup, :privateGroup, :secretGroup).each do |group|
assert_no_difference -> { Group.count } do
delete :destroy, params: { id: group.id }
end
end
end
test "non-member cannot delete group" do
user = users(:loserLarry)
sign_in user
groups(:publicGroup, :privateGroup, :secretGroup).each do |group|
assert_no_difference -> { Group.count } do
delete :destroy, params: { id: group.id }
end
end
end
test "group views can be accessed through their custom urls" do
sign_in users(:loserLarry)
get :show, params: { id: groups(:customUrlGroup).custom_url }
assert_response :success
end
test "the group path of groups with a custom url should be their custom url" do
assert_match(/.*HOOPLA/, group_path(groups(:customUrlGroup)))
end
test "the group path of groups without a custom url should be their group id" do
id = groups(:publicGroup).id
assert_match(/.*#{id}/, group_path(groups(:publicGroup)))
end
test "routes to a groups's id should redirect to their custom url when present" do
sign_in users(:loserLarry)
get :show, params: { id: groups(:customUrlGroup).id }
assert_response :moved_permanently
end
end
|
# server.rb
require 'sinatra'
require 'sinatra/namespace'
require 'mongoid'
require_relative '../models/bird'
require_relative '../serializers/bird_serializer'
require_relative '../helpers/bird_helper'
require "json-schema"
require 'pry'
# DB Setup
Mongoid.load! 'config/mongoid.config'
namespace '/api/v1' do
before do
content_type 'application/json'
end
helpers BirdHelper
get '/' do
'Welcome to BirdList!'
end
get '/birds' do
birds = Bird.only_visible
%i[name family].each do |filter|
birds = Birds.send(filter, params[filter]) if params[filter]
end
birds.map { |bird| BirdSerializer.new(bird) }.to_json
end
get '/birds/:id' do
halt_if_not_record_found!
serialize(bird)
end
post '/birds' do
params = validate_post_json(request.body.read)
bird = Bird.new(params)
halt 400, serialize(bird) unless bird.save
response.headers['Location'] = "#{base_url}/api/v1/birds/#{bird.id}"
status 201
end
patch '/birds/:id' do
halt_if_not_record_found!
halt 422, serialize(bird) unless bird.update_attributes(json_params)
serialize(bird)
end
delete '/birds/:id' do
halt_if_not_record_found!
Bird.destroy if bird
status 200
end
end
|
class Feature < ActiveRecord::Base
self.table_name = 'FEATURES'
#self.primary_key = 'PRODUCT_ID'
self.sequence_name = 'FEATURE_ID_SEQ'
validates :feature_name, presence: true
validates :feature_type, presence: true, length: {minimum: 3}
has_many :productsfeatures
has_many :products, :through => :productsfeatures
belongs_to :admin
before_save :audit_update
before_create :audit_update
def audit_update
self.modified_date = DateTime.now
if self.created_date.blank?
self.created_date = DateTime.now
end
end
def type_with_value
" #{feature_type}: #{feature_name} "
end
end
|
module MoneyMover
module Dwolla
class CustomerBeneficialOwnerResource < BaseResource
endpoint_path "/customers/:customer_id/beneficial-owners", action: [:list, :create]
endpoint_path "/beneficial-owners/:id", action: [:update, :destroy, :find]
def certify_beneficial_ownership(id)
path = "/customers/#{id}/beneficial-ownership"
errors.clear
response = client.post path, { status: 'certified' }
unless response.success?
add_errors_from response
end
errors.empty?
end
end
end
end
|
namespace :swe do
desc 'Clear SWAPI cache'
task clear_swapi_cache: :environment do
Film.delete_all
Person.delete_all
Planet.delete_all
CachedResource.delete_all
end
end
|
require 'spec_helper_acceptance'
require 'erb'
test_name 'simp_openldap::server with tls'
describe 'simp_openldap::server with tls' do
servers = hosts_with_role(hosts, 'server')
let(:server_manifest) {
<<-EOS
include 'simp_openldap::server'
EOS
}
servers.each do |server|
context "simp_openldap::server #{server}" do
let(:server_fqdn) { fact_on(server, 'fqdn') }
let(:base_dn) { fact_on(server, 'domain').split('.').map{ |d| "dc=#{d}" }.join(',') }
context 'with tls enabled' do
let(:hieradata) { ERB.new(File.read(File.expand_path('templates/hieradata_tls.yaml.erb', File.dirname(__FILE__)))).result(binding) }
shared_examples_for 'a tls enabled system' do
it 'should be able to connect using tls and use ldapsearch' do
on(server, "ldapsearch -ZZ -LLL -D cn=LDAPAdmin,ou=People,#{base_dn} -H ldap://#{server_fqdn} -x -w suP3rP@ssw0r!")
end
it 'should reject non-tls connections' do
on(server, "ldapsearch -LLL -D cn=LDAPAdmin,ou=People,#{base_dn} -H ldap://#{server_fqdn} -x -w suP3rP@ssw0r!", :acceptable_exit_codes=> [13])
end
it 'should only accept tlsv1.2 connections' do
result = on(server, "echo 'Q' | openssl s_client -connect localhost:636 -tls1_2")
expect(result.stdout).to include('Server certificate')
['tls1','tls1_1'].each do |cipher|
result = on(server,
"echo 'Q' | openssl s_client -connect localhost:636 -#{cipher}",
:acceptable_exit_codes => 1
)
end
result = on(server,
"echo 'Q' | openssl s_client -connect localhost:636 -ssl3",
:acceptable_exit_codes => 1
)
end
end
context 'LDAP server configuration' do
# /root/.ldaprc was created by a previous test and will not
# be overwritten because of 'replace => false' in the file resource.
# Needs to be configured with certs info.
it 'should remove /root/.ldaprc so it will be created with certs info' do
on(server, 'rm -f /root/.ldaprc')
end
it 'should configure server with tls enabled and with no errors' do
set_hieradata_on(server, hieradata)
apply_manifest_on(server, server_manifest, :catch_failures => true)
end
it 'should be idempotent' do
apply_manifest_on(server, server_manifest, :catch_changes => true)
end
it_should_behave_like 'a tls enabled system'
end
context 'with a new set of PKI certificates' do
it 'should populate new certificates into simp-testing' do
Dir.mktmpdir do |cert_dir|
run_fake_pki_ca_on(server, hosts, cert_dir)
hosts.each { |sut| copy_pki_to(sut, cert_dir, '/etc/pki/simp-testing') }
end
end
# Refresh the certs via Puppet
it 'should reconfigure LDAP server with new certs' do
apply_manifest_on(server, server_manifest, :catch_failures => true)
end
it_should_behave_like 'a tls enabled system'
end
end
end
end
end
|
class Api::V1::VendorsController < ApiController
before_action :set_vendor, only: [:show, :update, :destroy]
def index
@vendors = Vendor.all
render(
json: @vendors,
each_serializer: Api::V1::VendorSerializer,
root: false,
status: 200
)
end
def show
render json: @vendor
end
def create
@vendor = Vendor.new(vendor_params)
if @vendor.save
render json: @vendor, status: :created, location: false
else
render_unprocessable_entity_response(@vendor.errors)
# render json: @vendor.errors, status: :unprocessable_entity
end
end
def update
@vendor = Vendor.find(params[:id])
if @vendor.update(vendor_params)
head :no_content
else
render_unprocessable_entity_response(@vendor.errors)
# render json: @vendor.errors, status: :unprocessable_entity
end
end
def destroy
@vendor.destroy
head :no_content
end
private
def set_vendor
@vendor = Vendor.find(params[:id])
end
def vendor_params
params.require(:vendor).permit(:first_name, :last_name, :phone, :email)
end
end
|
class SipAccountSerializer < ActiveModel::Serializer
embed :ids, :include => true
attributes :id, :auth_name, :caller_name, :sip_accountable_id, :is_registrated
has_many :phone_numbers
has_many :calls
def is_registrated
if object.registration
true
else
false
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + "/../ui/community/product_qna_page")
require File.expand_path(File.dirname(__FILE__) + "/../ui/home_page")
require File.expand_path(File.dirname(__FILE__) + "/../ui/login/login_popup")
require File.expand_path(File.dirname(__FILE__) + "/../ui/community/user_profile_page")
require File.expand_path(File.dirname(__FILE__) + "/../ui/community/admin_qna_page")
require 'yaml'
class QnA
include QaConstants
attr_reader :qa_moderation_enabled
def initialize
@product_qna_page = ProductQnAPage.new
@home_page = HomePage.new
@login_popup = LoginPopup.new
@admin_qna_page = AdminQnaPage.new
# Moderation config
@qa_moderation_enabled = qa_moderation_enabled?
end
def qa_moderation_enabled?
config = YAML.load_file("#{Rails.root}/config/app/viewpoints.yml")
qa_moderation_status = config["qa_moderation_enabled"]
if qa_moderation_status == nil
flag = false
elsif qa_moderation_status == "true"
flag = true
else
flag = false
end
return flag
end
def login(user_object)
@home_page.open
if !user_object.blank?
if user_object.new_password == nil
password = "secret"
else
password = user_object.new_password
end
user_model = UserInfo.new(user_object.screen_name, user_object.email, password, password, "70701")
@home_page.navigate_to_login
@login_popup.login(user_model)
end
end
def visit_qa_admin(admin)
login(admin)
@admin_qna_page.visit_admin
@admin_qna_page.visit_answers_moderation
end
def visit_product_moderation(admin)
login(admin)
@admin_qna_page.visit_admin
@admin_qna_page.visit_product_moderation
end
def merge_products(admin, primary_product, secondary_product)
visit_product_moderation(admin)
@admin_qna_page.filter_products
@admin_qna_page.merge_products(primary_product, secondary_product)
end
def question_exists?(question_model)
LinkElement.new("link=#{question_model.title}").exists?
end
def answer_exists?(answer_model)
@product_qna_page.text_exists?(answer_model.text)
end
def visit_question(product, question_model)
visit product
@product_qna_page.navigate_to_question question_model.title
end
def visit(product)
@product_qna_page.visit product
@product_qna_page.visit_answers_tab
#s@product_qna_page.sort_by_date_asked
end
def visit_cat(category_name)
@product_qna_page.visit_cat(category_name)
end
def ask_question(product, user_info, question_model)
login user_info
visit product
@product_qna_page.navigate_to_ask_new_question
@product_qna_page.submit_question question_model
end
def edit_question(product, user_info, old_question_model, new_question_model)
login user_info
visit_question product, old_question_model
@product_qna_page.edit_question_enable
@product_qna_page.submit_question(new_question_model, true)
end
def answer_question(product, user_info, question_model, answer_model)
login user_info
visit_question product, question_model
@product_qna_page.answer_enable
@product_qna_page.submit_answer answer_model
end
def edit_answer(product, user_info, question_model, old_answer_model, new_answer_model)
login user_info
visit_question product, question_model
@product_qna_page.edit_answer_enable(old_answer_model)
@product_qna_page.submit_answer new_answer_model
end
def vote_answer(product, user_info, question_model, answer_model, flag)
login user_info
visit_question product, question_model
@product_qna_page.vote(flag, answer_model)
end
def vote_count(product, question_model, answer_model)
visit_question product, question_model
@product_qna_page.helpful_votes_count answer_model
end
def select_best_answer(product, user_info, question_model, answer_model)
login user_info
visit_question product, question_model
@product_qna_page.select_best_answer answer_model
end
def deselect_best_answer(product, user_info, question_model, answer_model)
login user_info
visit_question product, question_model
@product_qna_page.deselect_best_answer answer_model
end
def get_points_for_user(user_info)
user_info.reload
user_info.reputable_stat.points[Reputable::Stat::ALLTIME]
end
def answers_moderation_default_search(admin_info, user_info, type)
visit_qa_admin(admin_info)
@admin_qna_page.filter_qna(user_info, type, nil, nil, nil)
end
def activate(admin_info, user_info, type, model)
answers_moderation_default_search(admin_info, user_info, type)
if @admin_qna_page.exists_in_moderation_queue?(model, type)
@admin_qna_page.activate(model, type)
end
end
def reject(admin_info, user_info, type, model)
answers_moderation_default_search(admin_info, user_info, type)
if @admin_qna_page.exists_in_moderation_queue?(model, type)
@admin_qna_page.reject(model, type)
end
end
def add_featured_question(admin_info, owner, question, type)
login(admin_info)
@admin_qna_page.visit_admin
@admin_qna_page.visit_featured_questions
@admin_qna_page.add_featured_question(owner, question, type)
end
end |
describe "Block parameters" do
it "assign to local variable" do
i = 0
a = [1,2,3]
a.each {|i| ;}
i.should == 3
end
it "captures variables from the outer scope" do
a = [1,2,3]
sum = 0
var = nil
a.each {|var| sum += var}
sum.should == 6
var.should == 3
end
end
describe "Block parameters (to be removed from MRI)" do
it "assigns to a global variable" do
$global_for_block_assignment = 0
a = [1,2,3]
a.each {|$global_for_block_assignment| ;}
$global_for_block_assignment.should == 3
end
it "calls method=" do
class T
def n; return @n; end
def n=(val); @n = val + 1; end
def initialize; @n = 0; end
end
t = T.new
t.n.should == 0
a = [1,2,3]
a.each {|t.n| }
t.n.should == 4
end
end |
require 'rails_helper'
RSpec.describe PostsController, type: :controller do
let(:member) { create(:user) }
let(:other_member) { create(:user, name: "Other Member", email: "other_member@bloc.io") }
let(:admin) { create(:user, name: "Admin", email: "admin@bloc.io", role: :admin) }
let(:my_book_club) { create(:book_club) }
let(:my_topic) { create(:topic, book_club: my_book_club, user: member) }
let(:my_post) { create(:post, topic: my_topic, user: member) }
context "member" do
before(:each) do
member.confirm
sign_in(member)
end
describe "GET #show" do
it "returns a success response" do
get :show, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to be_success
end
it "renders the #show view" do
get :show, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to render_template :show
end
end
describe "GET #new" do
it "returns a success response" do
get :new, params: { topic_id: my_topic.id }
expect(response).to be_success
end
it "renders the #new view" do
get :new, params: { topic_id: my_topic.id }
expect(response).to render_template :new
end
it "instantiates @post" do
get :new, params: { topic_id: my_topic.id }
expect(assigns(:post)).not_to be_nil
end
end
describe "GET #edit" do
it "returns a success response" do
get :edit, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to be_success
end
it "renders the #edit view" do
get :edit, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to render_template :edit
end
it "assigns post to be updated to @post" do
get :edit, params: { topic_id: my_topic.id, id: my_post.id }
post_instance = assigns(:post)
expect(post_instance.id).to eq my_post.id
expect(post_instance.body).to eq my_post.body
end
it "does not allow a member to edit a post they don't own" do
sign_out(member)
other_member.confirm
sign_in(other_member)
get :edit, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to redirect_to(request.referrer || root_path)
end
end
describe "POST #create" do
it "increases the number of Post by 1" do
expect{
post :create, params: { topic_id: my_topic.id, post: { body: Faker::Lorem.paragraph } }
}.to change(Post, :count).by(1)
end
it "assigns the new post to Post.last" do
post :create, params: { topic_id: my_topic.id, post: { body: Faker::Lorem.paragraph } }
expect(assigns(:post)).to eq Post.last
end
it "redirects to the created post" do
post :create, params: { topic_id: my_topic.id, post: { body: Faker::Lorem.paragraph } }
expect(response).to redirect_to [my_topic, Post.last]
end
end
describe "PUT update" do
it "updates the requested post with expected attributes" do
new_body = Faker::Lorem.paragraph
put :update, params: { topic_id: my_topic.id, id: my_post.id, post: { body: new_body } }
updated_post = assigns(:post)
expect(updated_post.id).to eq my_post.id
expect(updated_post.body).to eq new_body
end
it "redirects to the updated post" do
new_body = Faker::Lorem.paragraph
put :update, params: { topic_id: my_topic.id, id: my_post.id, post: { body: new_body } }
expect(response).to redirect_to [my_topic, my_post]
end
it "does not allow a member to update a post they don't own" do
sign_out(member)
other_member.confirm
sign_in(other_member)
new_body = Faker::Lorem.paragraph
put :update, params: { topic_id: my_topic.id, id: my_post.id, post: { body: new_body } }
expect(response).to redirect_to(request.referrer || root_path)
end
end
describe "DELETE destroy" do
it "deletes the requested post" do
delete :destroy, params: { topic_id: my_topic.id, id: my_post.id }
count = Post.where({id: my_post.id}).size
expect(count).to eq 0
end
it "redirects to topic page" do
delete :destroy, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to redirect_to [my_book_club, my_topic]
end
it "does not allow a member to delete a post they don't own" do
sign_out(member)
other_member.confirm
sign_in(other_member)
delete :destroy, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to redirect_to(request.referrer || root_path)
end
end
end
context "admin" do
before(:each) do
admin.confirm
sign_in(admin)
end
describe "GET #show" do
it "returns a success response" do
get :show, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to be_success
end
it "renders the #show view" do
get :show, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to render_template :show
end
end
describe "GET #new" do
it "returns a success response" do
get :new, params: { topic_id: my_topic.id }
expect(response).to be_success
end
it "renders the #new view" do
get :new, params: { topic_id: my_topic.id }
expect(response).to render_template :new
end
it "instantiates @post" do
get :new, params: { topic_id: my_topic.id }
expect(assigns(:post)).not_to be_nil
end
end
describe "GET #edit" do
it "returns a success response" do
get :edit, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to be_success
end
it "renders the #edit view" do
get :edit, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to render_template :edit
end
it "assigns post to be updated to @post" do
get :edit, params: { topic_id: my_topic.id, id: my_post.id }
post_instance = assigns(:post)
expect(post_instance.id).to eq my_post.id
expect(post_instance.body).to eq my_post.body
end
end
describe "POST #create" do
it "increases the number of Post by 1" do
expect{
post :create, params: { topic_id: my_topic.id, post: { body: Faker::Lorem.paragraph } }
}.to change(Post, :count).by(1)
end
it "assigns the new post to Post.last" do
post :create, params: { topic_id: my_topic.id, post: { body: Faker::Lorem.paragraph } }
expect(assigns(:post)).to eq Post.last
end
it "redirects to the created post" do
post :create, params: { topic_id: my_topic.id, post: { body: Faker::Lorem.paragraph } }
expect(response).to redirect_to [my_topic, Post.last]
end
end
describe "PUT update" do
it "updates the requested post with expected attributes" do
new_body = Faker::Lorem.paragraph
put :update, params: { topic_id: my_topic.id, id: my_post.id, post: { body: new_body } }
updated_post = assigns(:post)
expect(updated_post.id).to eq my_post.id
expect(updated_post.body).to eq new_body
end
it "redirects to the updated post" do
new_body = Faker::Lorem.paragraph
put :update, params: { topic_id: my_topic.id, id: my_post.id, post: { body: new_body } }
expect(response).to redirect_to [my_topic, my_post]
end
end
describe "DELETE destroy" do
it "deletes the requested post" do
delete :destroy, params: { topic_id: my_topic.id, id: my_post.id }
count = Post.where({id: my_post.id}).size
expect(count).to eq 0
end
it "redirects to topic page" do
delete :destroy, params: { topic_id: my_topic.id, id: my_post.id }
expect(response).to redirect_to [my_book_club, my_topic]
end
end
end
end
|
class ChangeUsersColumnNameAndAddColumn < ActiveRecord::Migration
def change
rename_column :users, :title, :first_name
add_column :users, :last_name, :string
end
end
|
#4. Ler um vetor com 50 números. Informar a posição em que está o maior número.
#Se o maior número existir mais de uma vez, informe todas as posições onde existir este número.
lista_numeros = [1, 2, 5, 3, 5, 4, 5]
puts "Maior numero: #{lista_numeros.max}"
puts "Indice(s) do maior: #{lista_numeros.each_index.select {|i| lista_numeros[i] == lista_numeros.max}}"
|
class ReviewPhoto < ApplicationRecord
belongs_to :review, optional: true
attachment :review_image
end
|
module JobSeekersControllerHelperFunctions
def check_for_already_applied
if authorized_ids(@job_seeker).include?(Integer(session[:job_to_be_added].id))
session[:job_to_be_added] = nil
redirect_to :profile, :notice => "You have already applied for this job"
else
@job_seeker.jobs << session[:job_to_be_added]
Notifier.delay.send_email_to_employer(session[:job_to_be_added], @job_seeker)
session[:job_to_be_added] = nil
redirect_to :profile, :notice => "You have successfully applied for this job"
end
end
def apply_to_job_after_login
unless session[:job_to_be_added].nil?
@job_seeker = JobSeeker.find(session[:id])
check_for_already_applied
end
end
def check_if_employer_can_see_job_seeker_profile?
unless employer_authorised_to_see_profile?
flash[:error] = "You are not allowed to see this particular profile"
redirect_to root_path
end
end
def employer_authorised_to_see_profile?
employer = Employer.find(session[:id])
if (get_authorized_ids(employer).include?(params["id"].to_i))
return true
else
return false
end
end
def get_authorized_ids(employer)
authorized_ids = []
employer.jobs.each do |job|
authorized_ids.concat(job.job_seeker_ids)
end
return authorized_ids
end
end |
json.set! playlist_follower.id do
json.extract! playlist_follower, :playlist_id, :user_id
end |
# frozen_string_literal: true
module MachineLearningWorkbench::Optimizer::NaturalEvolutionStrategies
# Exponential Natural Evolution Strategies
class XNES < Base
attr_reader :log_sigma
def initialize_distribution mu_init: 0, sigma_init: 1
@mu = case mu_init
when Range # initialize with random in range
raise ArgumentError, "mu_init: `Range` start/end in `Float`s" \
unless mu_init.first.kind_of?(Float) && mu_init.last.kind_of?(Float)
mu_rng = Random.new rng.rand 10**Random.new_seed.size
NArray[*ndims.times.map { mu_rng.rand mu_init }]
when Array
raise ArgumentError unless mu_init.size == ndims
NArray[mu_init]
when Numeric
NArray.new([1,ndims]).fill mu_init
when NArray
raise ArgumentError unless mu_init.size == ndims
mu_init.ndim < 2 ? mu_init.reshape(1, ndims) : mu_init
else
raise ArgumentError, "Something is wrong with mu_init: #{mu_init}"
end
@sigma = case sigma_init
when Array
raise ArgumentError unless sigma_init.size == ndims
NArray[*sigma_init].diag
when Numeric
NArray.new([ndims]).fill(sigma_init).diag
when NArray
raise ArgumentError unless sigma_init.size == ndims**2
sigma_init.ndim < 2 ? sigma_init.reshape(ndims, ndims) : sigma_init
else
raise ArgumentError, "Something is wrong with sigma_init: #{sigma_init}"
end
# Works with the log of sigma to avoid continuous decompositions (thanks Sun Yi)
@log_sigma = NMath.log(sigma.diagonal).diag
end
def train picks: sorted_inds
g_mu = utils.dot(picks)
g_log_sigma = popsize.times.inject(NArray.zeros sigma.shape) do |sum, i|
u = utils[i]
ind = picks[i, true]
ind_sq = ind.outer_flat(ind, &:*)
sum + (ind_sq - eye) * u
end
@mu += sigma.dot(g_mu.transpose).transpose * lrate
@log_sigma += g_log_sigma * (lrate/2)
@sigma = log_sigma.exponential
end
# Estimate algorithm convergence as total variance
def convergence
sigma.trace
end
def save
[mu.to_a, log_sigma.to_a]
end
def load data
raise ArgumentError unless data.size == 2
@mu, @log_sigma = data.map &:to_na
@sigma = log_sigma.exponential
end
end
end
|
class GroupsCommands
class << self
def set_groups_columns
Group.arrange_serializable.each do |group|
Group.where(:id=>group['id']).update(:menu_columns=> group_column(group)) if group['ancestry'] == nil
end
end
def group_column(group)
count = tree_count(group).count
case count
when 0..19
return "1"
when 20..60
return "2"
else
return "3"
end
end
def tree_count(tree, p = 0)
id = tree["id"]
(tree["children"] || [])
.flat_map { |sub| tree_count(sub, id) }
.unshift("id" => id, "parent_id" => p)
end
def set_site_title
Group.find_each do |group|
group.update(:site_title=>group.title.gsub(/^(\d*\.*)*/, '').strip )
end
end
def set_new_item_time
Group.with_new_items.each do |group|
Group.where("id IN (?)",[group.id, group.root_id]).update_all(:last_new_item => group.item_created_at)
end
end
end
end |
module ApplicationHelper
def weekend(date)
return false if date.nil?
return (date.saturday? || date.sunday?)
end
def remove_zero(table_date)
return (table_date == 0 ? "" : table_date)
end
def keep_dash(table_data)
return (table_data ==0 ? "-" : table_data)
end
end |
class Partnership < ActiveRecord::Base
has_many :memberships
has_many :ownerships
has_many :users, :through => :memberships
has_many :projects, :through => :ownerships
has_many :design_cases
end
|
require 'minitest/autorun'
require 'robostripper'
class YellowPage < Robostripper::Resource
end
YellowPage.add_item :details do
phone "p.phone"
street ".street-address"
city { scan(".city-state").split(",")[0] }
state { scan(".city-state").split(",")[1].scan(/[A-Z]{2}/)[0] }
zip { scan(".city-state").split(",")[1].scan(/\d{5}/)[0] }
address { [ street, city, state, zip ].join(" ") }
payments { scan(".payment").split(",").map(&:strip) }
end
class RobostripperTest < MiniTest::Test
def test_http_headers
headers_hash = Robostripper::HTTP::HEADERS
assert_equal %w(Accept Accept-Charset Accept-Language User-Agent), headers_hash.keys
assert headers_hash["User-Agent"] =~ /Mozilla/
end
def test_yellowpage_resource_example
url = "http://www.yellowpages.com/silver-spring-md/mip/quarry-house-tavern-3342829"
yp = YellowPage.new(url)
assert_equal "(301) 587-8350", yp.details.phone
assert_equal "8401 Georgia Ave", yp.details.street
assert_equal "Silver Spring", yp.details.city
assert_equal "MD", yp.details.state
assert_equal "20910", yp.details.zip
assert_equal "8401 Georgia Ave Silver Spring MD 20910", yp.details.address
assert_equal ["master card", "discover", "amex", "visa"], yp.details.payments
end
end
|
class CashRegister
attr_accessor :discount, :purchases, :total, :transaction
def initialize(discount=nil)
self.total = 0
self.discount = discount if discount != nil
self.purchases = []
end
def add_item(name, price, quantity=1)
self.transaction = [name, price, quantity]
quantity.times do
self.purchases.push self.transaction[0]
self.total += self.transaction[1]
end
end
def apply_discount
if discount
self.total = self.total - self.total*self.discount/100
result = "After the discount, the total comes to $#{self.total}."
else
result = "There is no discount to apply."
end
return result
end
def items
return self.purchases
end
def void_last_transaction
quantity = self.transaction[2]
quantity.times do
self.purchases.pop
self.total -= self.transaction[1]
end
end
end
|
require 'yaml'
require './helpers/persistence_handler'
class Yaml_Builder
def initialize()
@persistence_handler = PersistenceHandler.new
end
def create(machine_name, software)
path = @persistence_handler.vm_installpath?.value.concat(machine_name) << '/'
path_file = path.concat("#{machine_name}") << '.yaml'
File.open(path_file , "w") {|f| f.write(yaml_body(software).to_yaml) }
end
private
# @param [Array] items_to_install; an arraylist with all program items
def yaml_body(software)
[{'hosts' => @persistence_handler.vagrant_hosts?.value, 'sudo' => @persistence_handler.vagrant_sudo?.value, 'tasks' =>
[{
'name' => 'General | Install required packages.',
'action' => 'apt pkg={{ item }} state=installed',
'tags' => 'common',
'with_items' => software
}]}
]
end
end |
require 'spec_helper'
describe SpreeImporter::Importers::Product do
it "should target Spree::Products" do
@importer = SpreeImporter::Importers::Product.new
@importer.target.should == Spree::Product
end
it "should set attributes on products from csv file" do
base = get_importer "gin-lane-product-list"
instances = base.import :product
instances.each do |i|
i.name.should_not be_nil
i.sku.should_not be_nil
i.price.should_not be_nil
end
end
it "should throw an exception for a badlly formatted date string" do
csv = CSV.parse "available_on\ninvalidate", headers: true
headers = { "available_on" => SpreeImporter::Field.new("available_on", headers: true, index: 0) }
importer = SpreeImporter::Importers::Product.new
importer.each_instance(headers.with_indifferent_access, csv){ }
importer.errors.length.should eql 1
importer.errors.first.row.should eql 1
importer.errors.first.column.should eql "available_on"
end
context "importing the whole shebang" do
before :each do
@base = get_importer "gin-lane-product-list"
@material = @base.import :property, property_name: "material", create_record: true
@size = @base.import :option, option_name: "size", create_record: true
@color = @base.import :option, option_name: "color", create_record: true
@taxonomies = @base.import :taxonomy
@products = @base.import :product
end
it "should import products with prototypes, properties, and options" do
@material = @products.first.properties.first
@material.name.should eql "material"
@material.presentation.should eql "Material"
@products.length.should eql 5
@products.first.option_types.length.should eql 2
# it should handle redundant uploads, bithc
@base.import :product
@products.length.should eql 5
product = Spree::Variant.find_by_sku("STN-FW13-DUMMY-NO-SIZE").product
product.taxons.count.should eql 1
product.taxons.first.pretty_name.should eql "Hat -> UBERHAT"
end
it "should generate skus for variants" do
product = Spree::Variant.find_by_sku("STN-FW13-DUMMY-NO-SIZE").product
product.variants.each do |v|
v.sku.should eql "#{product.sku}-#{v.option_values.first.name.upcase}"
end
end
it "shouldn't import motherlicking blank optionsfuckfuckfuckright?gotdamn" do
@product = Spree::Variant.find_by_sku("STN-FW13-DUMMY-NO-SIZE").product
@product.option_types.length.should eql 1
end
it "should import a sku pattern if specified" do
@products[0].sku_pattern.should eql SpreeImporter.config.default_sku
@products[1].sku_pattern.should eql "<master>-<color>-<size>"
end
end
end
|
Rails.application.routes.draw do
root "books#index"
resources :books
end
|
And(/^I'm on the contacts page$/) do
click_link "Contacts"
end
Given(/^I click on all Physicians$/) do
click_link "All Physicians"
end
When(/^I add the user$/) do
find(:xpath, "//tr[td[contains(.,'User2')]]/td/a", :text => '').click
end
Then(/^my contact list should be updated$/) do
assert page.has_content?("Your contacts have been updated")
end
When(/^I click the delete contact button$/) do
find(:xpath, "//tr[td[contains(.,'User2')]]/td/a", :text => 'delete').click
end
Then(/^the contact should be removed from my contact list$/) do
assert page.has_content?("has been removed from your contacts")
end
When(/^I click the make a call button$/) do
find(:xpath, "//tr[td[contains(.,'User2')]]/td/a", :text => 'call').click
end
When(/^I click the message button$/) do
find(:xpath, "//tr[td[contains(.,'User2')]]/td/a", :text => 'message').click
end
Then(/^A web chat should be initiated$/) do
assert page.find("#publisher")
end
Then(/^the compose page should open$/) do
assert page.has_content?("Compose")
end
Then(/^End call$/) do
page.find("#end_call").click
end
When(/^I can schedule an appointment$/) do
# As cucumber does not support JS Pop Ups backend unit tests were performed
@apt = Appointment.new
@parameters = Hash.new
@appointment = Hash.new
@appointment = {:price => 40 , :datetime => "2016-11-22 19:25:15"}
@parameters = {:id => 2, :appointment => @appointment}
@initiator = User.find(1)
@apt.create_appointment(@parameters,@initiator)
@apt.save
end
Then(/^I should be able to make a paymet as the other user$/) do
# As cucumber does not support JS Pop Ups backend unit tests were performed
@apt = Appointment.find(1)
@pays = Hash.new
@pays = { :card_number => "4929642537248212", :card_verification => "123", :card_expires_on => "11-2021", :first_name => "Jacob", :last_name => "Varghese"}
@pays_params = Hash.new
@pays_params = {:payment => @pays}
end
|
module UserDecorator
def favorite_game_display
return if listed_games_relations('favorite').empty?
relations = listed_games_relations('favorite').rank(:list_order)
content_tag(:h2) do
"Favorite Games ".html_safe.concat(
content_tag(:small) do
link_to('More...', user_list_path(self, List.preset('favorite')))
end.html_safe)
end.concat(
content_tag(:ul, :class => 'thumbnails', :id => "sortable-for-#{id}") do
relations.map do |relation|
content_tag(:li, game_description_popover(relation.game), :class => 'span1', :id => relation.id)
end.join('').html_safe
end)
end
def recent_reviews
return if ratings.has_review.empty?
content_tag(:h2, 'Recent Game Reviews').concat(
render(ratings.has_review.order('created_at DESC'))).concat(
link_to('More Game Reviews', user_ratings_path(self)))
end
def list_link(list)
link_to pluralize(listed_games(list).size, 'game', 'games'), user_list_path(self, List.preset(list))
end
def bio_display
if bio.nil? or bio.empty?
render 'history/changelog', :object => self
else
content_tag(:div, :class => 'well') do
simple_format(bio)
end.concat(changelog(self))
end
end
end
|
namespace :saved_searches do
desc 'create saved searches for all users based on their leads'
task create_from_leads: :environment do
searches_created = 0
Lead.where.not(user: nil).where(status: %w(pending cancelled invoiced)).find_each do |lead|
boat = lead.boat
user = lead.user
res = SavedSearch.safe_create(user, manufacturers: [boat.manufacturer_id], models: [boat.model_id])
searches_created += 1 if res
end
puts "#{searches_created} Saved Searches was created"
end
end
|
require "zenform/config_parser/csv_parser"
require "zenform/config_parser/json_parser"
require "yaml"
module Zenform
module ConfigParser
DEFAULT_CONFIG_PATH = "./zendesk_config"
TEMPLATE_PATH = File.expand_path("../../config/parse_format.yml", File.dirname(__FILE__))
class << self
def parse(project_path)
YAML.load_file(TEMPLATE_PATH).inject({}) do |config, (content, format)|
config.merge content => load_config(project_path, format)
end
end
private
def load_config(project_path, format)
file_path = File.expand_path format["path"], project_path
case format["file_type"]
when "csv"
Zenform::ConfigParser::CSVParser.parse file_path, format
when "json"
Zenform::ConfigParser::JSONParser.parse file_path, format
end
end
end
end
end
|
class Word < ActiveRecord::Base
has_many :votes, dependent: :destroy
belongs_to :author
accepts_nested_attributes_for :author
validates :name, :definition, :example, presence: true
extend FriendlyId
friendly_id :name
def up_votes
self.votes.where(value: 1).count
end
def down_votes
self.votes.where(value: -1).count
end
end
|
module Darknet
module Weights
FILE = "yolov3.weights"
URL = "https://pjreddie.com/media/files/#{FILE}"
def self.exists?
File.exist?(file_path)
end
def self.file_path
File.expand_path(FILE, Darknet.dir)
end
def self.download
unless exists?
# download weights file...
%x{ wget #{URL} -O #{file_path} }
end
end
end
end
|
class CreateAlbums < ActiveRecord::Migration[5.2]
def change
create_table :albums do |t|
t.string :title # porte le titre de l'album et est de type string.
t.string :artist # porte nom de l'artiste et est de type string.
end
end
end
|
require 'swagger_helper'
describe 'Tracks API' do
# Create a user
let(:user) {create(:user)}
# Create a record
let!(:record) {create(:record, created_by: user.id)}
# Create the tracks
let!(:tracks) {create_list(:track, 20, record_id: record.id)}
# Create the Authorization header
let(:Authorization) {"Bearer #{token_generator(user.id)}"}
path '/records/{record_id}/tracks' do
get 'Get all record tracks' do
tags 'Tracks'
security [apiKey: []]
consumes 'application/json'
parameter name: :record_id, :in => :path, :type => :string
response '200', 'Track' do
let(:record_id) {record.id}
run_test!
end
response '404', 'Record not found' do
let(:record_id) {0}
run_test!
end
end
post 'Creates a track' do
tags 'Tracks'
security [apiKey: []]
consumes 'application/json'
parameter name: :record_id, :in => :path, :type => :string
parameter name: :track, in: :body, schema: {
type: :object,
properties: {
name: {type: :string, example: Faker::Lorem.sentence},
number: {type: :integer, example: Faker::Number.between(1, 20)},
duration: {type: :integer, example: Faker::Number.between(120, 360)}
},
required: ['name', 'number', 'duration']
}
response '201', 'Track created' do
let(:record_id) {create(:record, created_by: user.id).id}
let(:track) {create(:track, record_id: record.id)}
run_test!
end
response '422', 'Invalid request' do
let(:record_id) {create(:record, created_by: user.id).id}
let(:track) {{}}
run_test!
end
end
end
path '/records/{record_id}/tracks/{id}' do
get 'Gets a track' do
tags 'Tracks'
security [apiKey: []]
consumes 'application/json'
parameter name: :record_id, :in => :path, :type => :string
parameter name: :id, :in => :path, :type => :string
response '200', 'Track' do
let(:record_id) {record.id}
let(:id) {tracks.first.id}
run_test!
end
response '404', 'Track not found' do
let(:record_id) {record.id}
let(:id) {0}
run_test!
end
end
put 'Updates a track' do
tags 'Tracks'
security [apiKey: []]
consumes 'application/json'
parameter name: :record_id, :in => :path, :type => :string
parameter name: :id, :in => :path, :type => :string
parameter name: :track, in: :body, schema: {
type: :object,
properties: {
name: {type: :string, example: Faker::Lorem.sentence},
number: {type: :integer, example: Faker::Number.between(1, 20)},
duration: {type: :integer, example: Faker::Number.between(120, 360)}
},
required: ['name', 'number', 'duration']
}
response '204', 'Track updated' do
let(:record_id) {record.id}
let(:id) {tracks.first.id}
let(:track) {build(:track)}
run_test!
end
end
delete 'Deletes a track' do
tags 'Tracks'
security [apiKey: []]
consumes 'application/json'
parameter name: :record_id, :in => :path, :type => :string
parameter name: :id, :in => :path, :type => :string
response '204', 'Track deleted' do
let(:record_id) {record.id}
let(:id) {tracks.first.id}
run_test!
end
response '404', 'Track not found' do
let(:record_id) {record.id}
let(:id) {0}
run_test!
end
end
end
end |
class CreateFacts < ActiveRecord::Migration[6.0]
def change
create_table :facts do |t|
t.references :group, null: false, foreign_key: true
t.string :title, null: false, default: ''
t.string :where, null: false, default: ''
t.boolean :pinned, null: false, default: false
t.date :start_on, null: false
t.date :stop_on, null: false
t.integer :happenings_count, null: false, default: 0
t.timestamps
end
end
end
|
module Taobao
class Base
def initialize(options)
options.each_pair do |key, value|
self.try("#{key}=", value)
end
end
end
end
|
# frozen_string_literal: true
require 'my_service_name'
require 'grape'
require 'grape-swagger'
require 'oat-swagger'
require 'grape/route_helpers'
require 'endpoints/root'
require 'endpoints/add_six'
require 'endpoints/test_endpoint'
require 'helpers/request_metadata'
require 'helpers/new_relic_instrumentation'
require 'helpers/log'
require 'helpers/bugsnag'
require 'helpers/json_parser'
require 'helpers/json_formatter'
require 'helpers/error_formatter'
require 'helpers/auth'
module MyServiceName
class Web < Grape::API
JSON_HAL_MEDIA_TYPE = 'application/hal+json'
JSON_MEDIA_TYPE = 'application/json'
helpers Helpers::RequestMetadata
helpers Helpers::NewRelicInstrumentation
helpers Helpers::Log
helpers Helpers::Bugsnag
helpers Helpers::Auth
# https://github.com/ruby-grape/grape#table-of-contents
content_type :json_hal, JSON_HAL_MEDIA_TYPE
content_type :json, JSON_MEDIA_TYPE
parser :json_hal, Helpers::JsonParser
parser :json, Helpers::JsonParser
formatter :json_hal, Helpers::JsonFormatter
error_formatter :json_hal, Helpers::ErrorFormatter
format :json_hal
default_format :json_hal
before do
setup_request_metadata
setup_new_relic_instrumentation
setup_logger_request_metadata
setup_bugsnag_request_metadata
logger.info "#{env['REQUEST_METHOD']} #{env['REQUEST_URI']}"
validate_api_key
end
# mount endpoints here
mount Endpoints::Root
mount Endpoints::AddSix
mount Endpoints::Test
###
add_swagger_documentation(
hide_documentation_path: true,
models: OatSwagger::Serializer.swagger_models,
)
end
end
|
module MassAssignmentBackport
def self.included(mod)
mod.send :include, AccessibleFor
mod.extend ClassMethods
end
module ClassMethods
def attr_accessible *args
options = args.last.kind_of?(Hash) ? args.pop : {}
role = options[:as] || :default
[role].flatten.each { |name| accessible_for name => args }
end
def accessible_attributes role=:default
accessible_by role
end
end
def sanitize_for_mass_assignment values, role=:default, &block
sanitize_for role, values, &block
end
end
|
class AddIndexes < ActiveRecord::Migration
def change
add_index :clubs, :name
add_index :officers, :last_name
add_index :officers, :first_name
add_index :officers, :email
end
end
|
class Stat < ActiveRecord::Base
before_validation :calcule_ratio
def self.create_initial
self.create({
count_mutant_dna: 0,
count_human_dna: 0,
ratio: 0.0
})
end
def add_record(isMutant)
attrs = {
count_human_dna: isMutant ? self.count_human_dna : self.count_human_dna + 1,
count_mutant_dna: isMutant ? self.count_mutant_dna + 1 : self.count_mutant_dna,
ratio: calcule_ratio
}
self.update(attrs)
end
private
def calcule_ratio
self.ratio = self.count_human_dna == 0 ? 1 : self.count_mutant_dna / self.count_human_dna
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'mongo'
require 'lite_spec_helper'
describe Mongo::Crypt::ExplicitDecryptionContext do
require_libmongocrypt
include_context 'define shared FLE helpers'
let(:credentials) { Mongo::Crypt::KMS::Credentials.new(kms_providers) }
let(:mongocrypt) { Mongo::Crypt::Handle.new(credentials, logger: logger) }
let(:context) { described_class.new(mongocrypt, io, value) }
let(:logger) { nil }
let(:io) { double("Mongo::ClientEncryption::IO") }
# A binary string representing a value previously encrypted by libmongocrypt
let(:encrypted_data) do
"\x01\xDF2~\x89\xD2+N}\x84;i(\xE5\xF4\xBF \x024\xE5\xD2\n\x9E\x97\x9F\xAF\x9D\xC7\xC9\x1A\a\x87z\xAE_;r\xAC\xA9\xF6n\x1D\x0F\xB5\xB1#O\xB7\xCA\xEE$/\xF1\xFA\b\xA7\xEC\xDB\xB6\xD4\xED\xEAMw3+\xBBv\x18\x97\xF9\x99\xD5\x13@\x80y\n{\x19R\xD3\xF0\xA1C\x05\xF7)\x93\x9Bh\x8AA.\xBB\xD3&\xEA"
end
let(:value) do
{ 'v': BSON::Binary.new(encrypted_data, :ciphertext) }
end
describe '#initialize' do
context 'when mongocrypt is initialized with local KMS provider options' do
include_context 'with local kms_providers'
it 'initializes context' do
expect do
context
end.not_to raise_error
end
end
context 'when mongocrypt is initialized with AWS KMS provider options' do
include_context 'with AWS kms_providers'
it 'initializes context' do
expect do
context
end.not_to raise_error
end
end
context 'when mongocrypt is initialized with Azure KMS provider options' do
include_context 'with Azure kms_providers'
it 'initializes context' do
expect do
context
end.not_to raise_error
end
end
context 'when mongocrypt is initialized with GCP KMS provider options' do
include_context 'with GCP kms_providers'
it 'initializes context' do
expect do
context
end.not_to raise_error
end
end
context 'when mongocrypt is initialized with KMIP KMS provider options' do
include_context 'with KMIP kms_providers'
it 'initializes context' do
expect do
context
end.not_to raise_error
end
end
context 'with verbose logging' do
include_context 'with local kms_providers'
before(:all) do
# Logging from libmongocrypt requires the C library to be built with the -DENABLE_TRACE=ON
# option; none of the pre-built packages on Evergreen have been built with logging enabled.
#
# It is still useful to be able to run these tests locally to confirm that logging is working
# while debugging any problems.
#
# For now, skip this test by default and revisit once we have determined how we want to
# package libmongocrypt with the Ruby driver (see: https://jira.mongodb.org/browse/RUBY-1966)
skip "These tests require libmongocrypt to be built with the '-DENABLE_TRACE=ON' cmake option." +
" They also require the MONGOCRYPT_TRACE environment variable to be set to 'ON'."
end
let(:logger) do
::Logger.new(STDOUT).tap do |logger|
logger.level = ::Logger::DEBUG
end
end
it 'receives log messages from libmongocrypt' do
expect(logger).to receive(:debug).with(/mongocrypt_ctx_explicit_decrypt_init/)
context
end
end
end
end
|
# class Garden
# def initialize(plants)
# sill_a = plants.split("\n").first.split('')
# sill_b = plants.split("\n").last.split('')
# end
# def alice
# plants = kindergarten.index('alice')
# end
# end
# kindergarten = ['Bob', 'Alice', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry'].sort!
# kindergarten.each.downcase!
# garden = Garden.new("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV")
# garden.alice
# # => [:violets, :radishes, :violets, :radishes]
# garden.bob
# # => [:clover, :grass, :clover, :clover]
#mathildas solution
class Garden
def initialize(seeds)
@seeds = seeds
@students = ['Bob', 'Alice', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry'].sort!
@student_seed_dictionary = create_student_seed_dictionary
find_student
end
def create_student_seed_dictionary
student_seed_dictionary = {}
seed = @seeds.split("\n")
seed[0].split('').zip(seed[1].split('')).each_slice(2).with_index do |array_pair, i|
plants_array = array_pair.flatten.map do |letter|
plants[letter]
end
student_seed_dictionary[@students[i]] = plants_array
end
student_seed_dictionary
binding.pry
end
def plants
{
'G' => :grass,
'V' => :violets,
'R' => :radieshes,
'C' => :clover
}
end
def find_student
@student_seed_dictionary.each do |key, value|
instance_eval "def #{key.downcase}; #{value}; end"
end
end
end
garden = Garden.new("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV")
puts garden.alice
# => [:violets, :radishes, :violets, :radishes]
puts garden.bob
# => [:clover, :grass, :clover, :clover]
|
namespace :db do
desc "truncates everything in the database"
task truncate: :environment do
conn = ActiveRecord::Base.connection
conn.tables.each do |t|
sql = "TRUNCATE #{t} CASCADE"
puts sql
conn.execute(sql)
end
end
end
|
require 'usagewatch'
require 'system'
require 'sys/filesystem'
require_relative('instance')
require 'mac-address'
require 'sys/proctable'
require 'rest-client'
require 'json'
class GetMachineInfo
def execute
usw = Usagewatch
cpu = usw.uw_cpuused
id = MacAddress.address
shutdown = shutdown_check(cpu, id)
execute_shutdown if shutdown
stat = Sys::Filesystem.stat("/")
process_list = Sys::ProcTable.ps.sort_by(&:pctcpu).reverse.take(10).map{|p| [p.name, p.pctcpu]}
instance = Instance.new(cpu:cpu,
disk_usage: stat.percent_used,
processes: process_list,
id: id,
os: System::OS.name,
machine_name: Socket.gethostname,
threshold: @threshold)
instance.to_hash
end
private
def get_api_instances_endpoint(id)
(ENV['API_URL'] || 'http://localhost:9292') + "/instance/#{id}/threshold"
end
def get_token_url
ENV['TOKEN_URL'] || 'http://localhost:9292/token'
end
def get_client_id
ENV['OAUTH2_CLIENT_ID'] || '4de2fd79af6950291687a9df6f9ab4de93246f020a3e440186bb77fdaba25b0f'
end
def get_client_secret
ENV['OAUTH2_CLIENT_SECRET'] || '6e6009447cfd2d1a0a8792805fd9efa1a6f01c6faa7b7382659b1b1446b57f2a'
end
def get_token
RestClient.post get_token_url, {:client_id => get_client_id, :client_secret => get_client_secret}.to_json, :content_type => :json, :accept => :json
end
def format_token_header(token)
"Bearer " + token["access_token"]
end
def shutdown_check(cpu, id)
url = get_api_instances_endpoint(id)
begin
@threshold = RestClient::Request.execute(method: :get, url: url, headers: {authorization: format_token_header(JSON.parse(get_token))})
rescue Exception => err
p err
@threshold = nil
end
if @threshold.nil? || @threshold.empty?
@threshold = ""
return false
else
Integer(@threshold) < Integer(cpu) unless @threshold.nil?
end
end
def execute_shutdown
p "Shutdown machine"
system 'shutdown -h now'
end
end
|
# ==== DOCUMENT ====
class ArangoDocument < ArangoServer
def initialize(key: nil, collection: @@collection, database: @@database, body: {}, from: nil, to: nil) # TESTED
if collection.is_a?(String)
@collection = collection
elsif collection.is_a?(ArangoCollection)
@collection = collection.collection
else
raise "collection should be a String or an ArangoCollection instance, not a #{collection.class}"
end
if database.is_a?(String)
@database = database
elsif database.is_a?(ArangoDatabase)
@database = database.database
else
raise "database should be a String or an ArangoDatabase instance, not a #{database.class}"
end
if key.is_a?(String) || key.nil?
@key = key
unless key.nil?
body["_key"] = @key
@id = "#{@collection}/#{@key}"
end
elsif key.is_a?(ArangoDocument)
@key = key.key
@id = key.id
else
raise "key should be a String, not a #{key.class}"
end
if body.is_a?(Hash)
@body = body
else
raise "body should be a Hash, not a #{body.class}"
end
if from.is_a?(String)
@body["_from"] = from
elsif from.is_a?(ArangoDocument)
@body["_from"] = from.id
elsif from.nil?
else
raise "from should be a String or an ArangoDocument instance, not a #{from.class}"
end
if to.is_a?(String)
@body["_to"] = to
elsif to.is_a?(ArangoDocument)
@body["_to"] = to.id
elsif to.nil?
else
raise "to should be a String or an ArangoDocument instance, not a #{to.class}"
end
@idCache = "DOC_#{@id}"
end
attr_reader :key, :id, :body, :idCache
alias name key
# === RETRIEVE ===
def to_hash
{
"key" => @key,
"id" => @id,
"collection" => @collection,
"database" => @database,
"body" => @body,
"idCache" => @idCache
}.delete_if{|k,v| v.nil?}
end
alias to_h to_hash
def collection
ArangoCollection.new(collection: @collection, database: @database)
end
def database
ArangoDatabase.new(database: @database)
end
# === GET ===
def retrieve # TESTED
result = self.class.get("/_db/#{@database}/_api/document/#{@id}", @@request)
self.return_result result: result
end
def retrieve_edges(collection: , direction: nil) # TESTED
query = {"vertex" => @id, "direction" => direction }.delete_if{|k,v| v.nil?}
request = @@request.merge({ :query => query })
collection = collection.is_a?(String) ? collection : collection.collection
result = self.class.get("/_db/#{@database}/_api/edges/#{collection}", request)
return result.headers["x-arango-async-id"] if @@async == "store"
return true if @@async
result = result.parsed_response
@@verbose ? result : result["error"] ? result["errorMessage"] : result["edges"].map{|edge| ArangoDocument.new(key: edge["_key"], collection: collection, database: @database, body: edge)}
end
def in(edgeCollection) # TESTED
self.retrieve_edges collection: edgeCollection, direction: "in"
end
def out(edgeCollection) # TESTED
self.retrieve_edges collection: edgeCollection, direction: "out"
end
def any(edgeCollection) # TESTED
self.retrieve_edges collection: edgeCollection
end
def from # TESTED
result = self.class.get("/_db/#{@database}/_api/document/#{self.body["_from"]}", @@request)
collection = result["_id"].split("/")[0]
return result.headers["x-arango-async-id"] if @@async == "store"
return true if @@async
result = result.parsed_response
@@verbose ? result : result["error"] ? result["errorMessage"] : ArangoDocument.new(key: result["_key"], collection: collection, database: @database, body: result)
end
def to # TESTED
result = self.class.get("/_db/#{@database}/_api/document/#{self.body["_to"]}", @@request)
collection = result["_id"].split("/")[0]
return result.headers["x-arango-async-id"] if @@async == "store"
return true if @@async
result = result.parsed_response
@@verbose ? result : result["error"] ? result["errorMessage"] : ArangoDocument.new(key: result["_key"], collection: collection, database: @database, body: result)
end
# def header
# result = self.class.head("/_db/#{@database}/_api/document/#{@id}", follow_redirects: true, maintain_method_across_redirects: true)
# @@verbose ? result : result["error"] ? result["errorMessage"] : result
# end
# === POST ====
def create(body: {}, waitForSync: nil, returnNew: nil) # TESTED
body = @body.merge(body)
query = {"waitForSync" => waitForSync, "returnNew" => returnNew}.delete_if{|k,v| v.nil?}
body["_key"] = @key if body["_key"].nil? && !key.nil?
request = @@request.merge({ :body => @body.to_json, :query => query })
result = self.class.post("/_db/#{@database}/_api/document/#{@collection}", request)
return_result result: result, body: @body
end
alias create_document create
alias create_vertex create
def self.create(body: {}, waitForSync: nil, returnNew: nil, database: @@database, collection: @@collection) # TESTED
collection = collection.is_a?(String) ? collection : collection.collection
database = database.is_a?(String) ? database : database.database
query = {"waitForSync" => waitForSync, "returnNew" => returnNew}.delete_if{|k,v| v.nil?}
unless body.is_a? Array
request = @@request.merge({ :body => body.to_json, :query => query })
result = post("/_db/#{database}/_api/document/#{collection}", request)
return result.headers["x-arango-async-id"] if @@async == "store"
return true if @@async
result = result.parsed_response
@@verbose ? result : result["error"] ? result["errorMessage"] : ArangoDocument.new(key: result["_key"], collection: result["_id"].split("/")[0], body: body)
else
body = body.map{|x| x.is_a?(Hash) ? x : x.is_a?(ArangoDocument) ? x.body : nil}
request = @@request.merge({ :body => body.to_json, :query => query })
result = post("/_db/#{database}/_api/document/#{collection}", request)
return result.headers["x-arango-async-id"] if @@async == "store"
return true if @@async
result = result.parsed_response
i = -1
@@verbose ? result : !result.is_a?(Array) ? result["errorMessage"] : result.map{|x| ArangoDocument.new(key: x["_key"], collection: collection, database: database, body: body[i+=1])}
end
end
def create_edge(body: {}, from:, to:, waitForSync: nil, returnNew: nil, database: @database, collection: @collection) # TESTED
body = @body.merge(body)
edges = []
from = [from] unless from.is_a? Array
to = [to] unless to.is_a? Array
from.each do |f|
body["_from"] = f.is_a?(String) ? f : f.id
to.each do |t|
body["_to"] = t.is_a?(String) ? t : t.id
edges << body.clone
end
end
edges = edges[0]
ArangoDocument.create(body: edges, waitForSync: waitForSync, returnNew: returnNew, database: database, collection: collection)
end
def self.create_edge(body: {}, from:, to:, waitForSync: nil, returnNew: nil, database: @@database, collection: @@collection) # TESTED
edges = []
from = [from] unless from.is_a? Array
to = [to] unless to.is_a? Array
body = [body] unless body.is_a? Array
body = body.map{|x| x.is_a?(Hash) ? x : x.is_a?(ArangoDocument) ? x.body : nil}
body.each do |b|
from.each do |f|
b["_from"] = f.is_a?(String) ? f : f.id
to.each do |t|
b["_to"] = t.is_a?(String) ? t : t.id
edges << b.clone
end
end
end
edges = edges[0] if edges.length == 1
ArangoDocument.create(body: edges, waitForSync: waitForSync, returnNew: returnNew, database: database, collection: collection)
end
# === MODIFY ===
def replace(body: {}, waitForSync: nil, ignoreRevs: nil, returnOld: nil, returnNew: nil) # TESTED
query = {
"waitForSync" => waitForSync,
"returnNew" => returnNew,
"returnOld" => returnOld,
"ignoreRevs" => ignoreRevs
}.delete_if{|k,v| v.nil?}
request = @@request.merge({ :body => body.to_json, :query => query })
unless body.is_a? Array
result = self.class.put("/_db/#{@database}/_api/document/#{@id}", request)
self.return_result result: result, body: body
else
result = self.class.put("/_db/#{@database}/_api/document/#{@collection}", request)
i = -1
return result.headers["x-arango-async-id"] if @@async == "store"
return true if @@async
result = result.parsed_response
@@verbose ? result : !result.is_a?(Array) ? result["errorMessage"] : result.map{|x| ArangoDocument.new(key: x["_key"], collection: @collection, database: @database, body: body[i+=1])}
end
end
def update(body: {}, waitForSync: nil, ignoreRevs: nil, returnOld: nil, returnNew: nil, keepNull: nil, mergeObjects: nil) # TESTED
query = {
"waitForSync" => waitForSync,
"returnNew" => returnNew,
"returnOld" => returnOld,
"ignoreRevs" => ignoreRevs,
"keepNull" => keepNull,
"mergeObjects" => mergeObjects
}.delete_if{|k,v| v.nil?}
request = @@request.merge({ :body => body.to_json, :query => query })
unless body.is_a? Array
result = self.class.patch("/_db/#{@database}/_api/document/#{@id}", request)
return result.headers["x-arango-async-id"] if @@async == "store"
return true if @@async
result = result.parsed_response
if @@verbose
unless result["error"]
@key = result["_key"]
@id = "#{@collection}/#{@key}"
@body = body
end
result
else
return result["errorMessage"] if result["error"]
@key = result["_key"]
@id = "#{@collection}/#{@key}"
@body = @body.merge(body)
return self
end
else
result = self.class.patch("/_db/#{@database}/_api/document/#{@collection}", request)
i = -1
return result.headers["x-arango-async-id"] if @@async == "store"
return true if @@async
result = result.parsed_response
@@verbose ? result : !result.is_a?(Array) ? result["errorMessage"] : result.map{|x| ArangoDocument.new(key: x["_key"], collection: @collection, database: @database, body: body[i+=1])}
end
end
# === DELETE ===
def destroy(body: nil, waitForSync: nil, ignoreRevs: nil, returnOld: nil) # TESTED
query = {
"waitForSync" => waitForSync,
"returnOld" => returnOld,
"ignoreRevs" => ignoreRevs
}.delete_if{|k,v| v.nil?}
request = @@request.merge({ :body => body.to_json, :query => query })
unless body.is_a? Array
result = self.class.delete("/_db/#{@database}/_api/document/#{@id}", request)
return_result result: result, caseTrue: true
else
result = self.class.delete("/_db/#{@database}/_api/document/#{@collection}", request)
return_result result: result, caseTrue: true
end
end
# === UTILITY ===
def return_result(result:, body: {}, caseTrue: false, key: nil)
return result.headers["x-arango-async-id"] if @@async == "store"
return true if @@async
result = result.parsed_response
if @@verbose || !result.is_a?(Hash)
resultTemp = result
unless result["errorMessage"]
result.delete_if{|k,v| k == "error" || k == "code"}
@key = result["_key"]
@collection = result["_id"].split("/")[0]
@body = result.merge(body)
end
return resultTemp
else
return result["errorMessage"] if result["error"]
return true if caseTrue
result.delete_if{|k,v| k == "error" || k == "code"}
@key = result["_key"]
@collection = result["_id"].split("/")[0]
@id = "#{@collection}/#{@key}"
@body = result.merge(body)
key.nil? ? self : result[key]
end
end
end
|
Sequel.migration do
up do
add_column :people, :location, String
from(:people).update(:location=>'Budapest')
end
down do
drop_column :people, :location
end
end
|
class FreshbookUser
attr_reader :user
FRIDAY_LAST_WEEK = Date.today - 7.days
START_OF_THE_WEEK = FRIDAY_LAST_WEEK.strftime '%Y-%m-%d'
END_OF_THE_WEEK = Date.yesterday.strftime '%Y-%m-%d'
def initialize token
@user = FreshBooks::Client.new ENV['freshbooks_url'], token
end
def staff
@user.staff.current
end
def entries
@user.time_entry.list(
:per_page => 100,
:date_from => START_OF_THE_WEEK,
:date_to => END_OF_THE_WEEK
)
end
def invalid_token
self.entries.to_s.include? 'Authentication failed'
end
def no_record
self.entries['time_entries']['total'] == '0'
end
def project project_id
@user.project.get :project_id => project_id
end
def time_entries
[self.entries['time_entries']['time_entry']].flatten
end
end
|
class AddSpyPlayerIdAndFirstPlayerIdToGames < ActiveRecord::Migration[5.0]
def change
add_column :games, :spy_player_id, :integer
add_column :games, :first_player_id, :integer
end
end
|
class PeopleAndPhotos < ActiveRecord::Migration[4.2]
def change
create_table :buildings_photos, id: false do |t|
t.references :building, foreign_key: true
t.references :photo, foreign_key: true
end
create_table :people_photos, id: false do |t|
t.references :person, foreign_key: true
t.references :photo, foreign_key: true
end
if table_exists?(:buildings_photos)
Photo.where.not(building_id: nil).each do |photo|
building = Building.find photo.building_id
photo.buildings << building
end
end
end
end
|
Rails.application.routes.draw do
root to: "home#show"
get "/api/getplanetnames", to: "home#index"
resources :users, only: [:new, :create, :update]
resources :spaces, only: [:index, :new, :create]
resources :reservations, only: [:create, :destroy]
resources :orders, only: [:index, :show, :create]
resources :tweets, only: [:create]
resources :charges, only: [:new, :create]
get "/cart", to: "reservations#show"
get "/login", to: "sessions#new"
post "/login", to: "sessions#create"
delete "/logout", to: "sessions#destroy"
get "/dashboard", to: "dashboard#show"
get "/auth/twitter", as: :twitter_login
get "/auth/twitter/callback", to: "sessions#create"
namespace :admin do
get "/dashboard", to: "users#show"
resources :spaces, only: [:index, :edit, :update]
resources :unapproved_spaces, only: [:index, :update]
resources :reservations, only: [:index, :edit, :update]
resources :planets, only: [:index, :edit, :update]
resources :styles, only: [:index, :edit, :update]
resources :users, only: [:index, :edit, :update]
end
get "hosts/:space_slug/new", to: "hosts#new"
post "/hosts", to: "hosts#create"
get "spaces/:space_slug", to: "spaces#show", as: :space
get "spaces/:space_slug/edit", to: "spaces#edit", as: :edit_space
patch "/spaces/:space_slug", to: "spaces#update"
get "planets/:planet_slug", to: "planets#show", as: :planet
patch "/planets/:planets_slug", to: "planets#update"
get "styles/:style_slug", to: "styles#show", as: :style
get "users/:username/edit", to: "users#edit", as: :edit_user
get "/:username", to: "users#show", as: :listings
end
|
require 'rails_helper'
describe 'root routing' do
it 'routes /fighters to the index action' do
expect(get('/')).to route_to('pages#index')
end
end
describe 'routing for fighters' do
it 'routes /fighters to the index action' do
expect(get('/fighters')).to route_to('fighters#index')
end
it 'routes /fighters/:id to the show action' do
expect(get('/fighters/2')).to route_to(
controller: 'fighters',
action: 'show',
id: '2'
)
end
it 'routes /fighters/new to the new action' do
expect(get('/fighters/new')).to route_to('fighters#new')
end
it 'routes /fighters to the create action' do
expect(post('/fighters')).to route_to('fighters#create')
end
it 'routes /fighters/:id/edit to the edit action' do
expect(get('/fighters/4/edit')).to route_to(
controller: 'fighters',
action: 'edit',
id: '4'
)
end
it 'routes /fighters/:id to the update action' do
expect(put('/fighters/6')).to route_to(
controller: 'fighters',
action: 'update',
id: '6'
)
end
it 'routes /fighters/:id to the destroy action' do
expect(delete('/fighters/3')).to route_to(
controller: 'fighters',
action: 'destroy',
id: '3'
)
end
end
describe 'routing for duels' do
it 'routes /duels to the index action' do
expect(get('/duels')).to route_to('duels#index')
end
it 'routes /duels/:id to the show action' do
expect(get('/duels/2')).to route_to(
controller: 'duels',
action: 'show',
id: '2'
)
end
it 'routes /duels/new to the new action' do
expect(get('/duels/new')).to route_to('duels#new')
end
it 'routes /duels to the create action' do
expect(post('/duels')).to route_to('duels#create')
end
end
|
require 'rubyonacid/factory'
include RubyOnAcid
shared_examples_for "a factory" do
describe "getUnit()" do
it "returns a value between 0.0 and 1.0 (inclusive) for a key" do
value = js("it.getUnit('any_key');")
value.should_not be_nil
value.should >= 0.0
value.should <= 1.0
end
end
describe "#get" do
it "allows setting a maximum" do
js("it.get('a', 2.0);").should <= 2.0
js("it.get('b', 10.0);").should <= 10.0
js("it.get('c', 100.0);").should <= 100.0
js("it.get('d', 1000.0);").should <= 1000.0
end
it "allows setting a minimum" do
js("it.get('a', 2.0, 3.0)").should >= 2.0
js("it.get('b', -1.0, 0.0)").should >= -1.0
js("it.get('c', -100.0, 100.0)").should >= -100.0
js("it.get('d', 1000.0, 1000.1)").should >= 1000.0
end
it "uses a default minimum of 0.0" do
js("it.get('a')").should >= 0.0
js("it.get('a', 10.0)").should >= 0.0
end
it "uses a default maximum of 1.0" do
js("it.get('a')").should <= 1.0
end
end
end
|
# coding: utf-8
class Catalog::CategoryItemImage < ActiveRecord::Base
attr_accessible :category_item_id, :image_alt, :image_content_type, :image_file_name, :image_file_size, :image_updated_at, :short_description, :image_height, :image_width, :image_ratio
belongs_to :catalog_category_item, :inverse_of => :category_item_images
attr_accessible :image, :delete_image
attr_accessor :delete_image
has_attached_file :image, :styles => { small: '100x100>',
middle: '250x250>',
fancybox: '1000x1000>'
},
:url => '/assets/catalog/item_images/:id/:style/:basename.:extension',
:path => ':rails_root/public/assets/catalog/item_images/:id/:style/:basename.:extension'
before_save :check_rename_image
def check_rename_image
if image_file_name_changed?
new_name = image_file_name
old_name = image_file_name_was
image.styles.keys.each do | key |
file_path = image.path(key)
folder = File.dirname(file_path)
new_path = folder + '/' + new_name
old_path = folder + '/' + old_name
FileUtils.mv old_path, new_path
end
end
end
rails_admin do
label 'Картинка для продуктов'
label_plural 'Картинки для продуктов'
# label 'Картинка'
# label_plural 'Картинки'
# list do
# field :name
# field :album
# field :image
# end
edit do
field :short_description
field :image, :paperclip do
#label :image
end
#field :image_file_name
field :image_width do
hide
end
field :image_height do
hide
end
field :image_ratio do
hide
end
field :image_alt
#field :parent_category
#field :category_items
#field :category_images
end
end
end
|
require 'rails_helper'
RSpec.describe 'Locations API', type: :request do
let!(:panel_provider) { create(:panel_provider) }
let!(:user) { create(:user) }
let!(:country) { create(:country, panel_provider: panel_provider) }
let!(:location_group_east) { create(:location_group, country_id: country.id) }
let!(:location_group_west) { create(:location_group, country_id: country.id) }
let!(:locations) { create_list(:location, 20) }
let(:headers) { valid_headers }
let(:provider_id) { panel_provider.id }
let(:country_code) { country.code }
describe 'GET /locations' do
before do
panel_provider.countries << country
country.location_groups << location_group_east
country.location_groups << location_group_west
location_group_east.locations << locations[0, 12]
location_group_west.locations << locations[10, 19]
end
context 'public api' do
before { get "/locations/#{provider_id}?country_code=#{country_code}", headers: headers }
context 'when country exists' do
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
it 'returns location list' do
expect(json).not_to be_empty
expect(json.size).to eq(20)
end
end
context 'when country does not exist' do
let(:country_code) { 'foocode' }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
it 'returns not found message' do
expect(response.body).to match(/Couldn't find Country/)
end
end
end
context 'private api' do
before { get "/locations/#{provider_id}?country_code=#{country_code}", headers: headers }
context 'when country exists' do
let(:user) { create(:user, panel_provider_id: panel_provider.id) }
let(:headers) { valid_headers_private_api }
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
it 'returns location list' do
expect(json).not_to be_empty
expect(json.size).to eq(20)
end
end
context 'when country does not exist' do
let(:user) { create(:user, panel_provider_id: panel_provider.id) }
let(:headers) { valid_headers_private_api }
let(:country_code) { 'foocode' }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
it 'returns not found message' do
expect(response.body).to match(/Couldn't find Country/)
end
end
context 'when user has no rights to access private api' do
let(:headers) { valid_headers_private_api }
it 'returns status code 403' do
expect(response).to have_http_status(403)
end
it 'returns not forbidden message' do
expect(response.body).to match(/Forbidden/)
end
end
end
end
end |
class Post < ApplicationRecord
include Rails.application.routes.url_helpers
has_one_attached :avatar
def avatar_url
avatar.attached? ? url_for(avatar) : nil
end
end
|
# race car application
# input : array of racer names
# output: no valuable output (besides pretty race and congradulatory comments to winner)
require_relative 'racer_utils'
require 'pry'
class RubyRacer
attr_reader :players, :track_length
def initialize(players=[a,b], track_length=30)
@players = players
@player_colors = ["\033[92m","\033[91m","\033[96m", "\033[94m","\033[95m", "\033[93m"] # green, red, light-blue, blue, pink, yellow
@track_length = track_length
@die = Die.new
@racers_hash = {}
players.each {|player| @racers_hash[player] = 1 }
end
# Returns +true+ if one of the players has reached
# the finish line, +false+ otherwise
def finished?(player)
@racers_hash[player] >= track_length-1
end
# Rolls the dice and advances +player+ accordingly
def advance_player!(player)
single_roll = @die.roll # save new dice roll
@racers_hash[player] += single_roll
end
def determine_winners
winner_so_far = @players.first
winners = []
# binding.pry
@players.each do |p|
if @racers_hash[winner_so_far] < @racers_hash[p]
winner_so_far = p
winners = [p]
elsif if @racers_hash[winner_so_far] == @racers_hash[p]
winners << p
end
end
end
winners
end
# Prints the current game board
# The board should have the same dimensions each time
# and you should use the "reputs" helper to print over
# the previous board
def print_board
color_end = "\033[0m"
loop_counter = 0
@players.each do |p|
print " | " * (@racers_hash[p] - 1) + @player_colors[loop_counter % @player_colors.size]
print " #{@players[loop_counter][0]} "
print color_end
print " | " * (@track_length - (@racers_hash[p] < track_length-1 ? @racers_hash[p] : track_length-1) - 1)
loop_counter += 1
puts
end
end
end
# 1 -> num_of_racers < 95
def get_racers(num_of_racers)
num_of_racers = 1 if num_of_racers < 1
num_of_racers = 94 if num_of_racers > 94
length_of_alphabet = 26
racers = []
case num_of_racers
when 1..26; then racers = 97.upto(96 + num_of_racers).to_a.map{|num| num.chr}
when 27..52; then racers = 'a'.upto('z').to_a + 65.upto(64 + (num_of_racers - length_of_alphabet)).to_a.map{|num| num.chr}
else racers = 33.upto(33 + num_of_racers).to_a.map{|num| num.chr} # inverse of 'A'.ord.chr = 'A'
end
racers
end
def startRace(num_of_racers, track_length)
names_array = get_racers(num_of_racers)
game = RubyRacer.new(names_array, track_length)
clear_screen! # This clears the screen, so the fun can begin
move_to_home! # This moves the cursor back to the upper-left of the screen
game.print_board # put starting screen
somebody_finished = false
until somebody_finished do
names_array.each do |player|
move_to_home! # This moves the cursor back to the upper-left of the screen
game.advance_player!(player) # We print the board first so we see the initial, starting board
game.print_board
if game.finished?(player)
somebody_finished = true
end
names_array.size >= 10 ? sleep(0.05) : sleep(0.1) # if number if racers is > 10 then sleep less time
end
end
result = game.determine_winners
if result.size == 1
puts "#{result.first} Won!!!!"
else
puts "#{result.join(', ')} TIED!!!! A #{result.size} way tie."
end
puts "*Slap on the butt.* Thanks for playing."
end
|
require 'test_helper'
class MealPlansControllerTest < ActionController::TestCase
setup do
@meal_plan = meal_plans(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:meal_plans)
end
test "should get new" do
get :new
assert_response :success
end
test "should create meal_plan" do
assert_difference('MealPlan.count') do
post :create, meal_plan: { calories: @meal_plan.calories, carbs: @meal_plan.carbs, fat: @meal_plan.fat, name: @meal_plan.name, protein: @meal_plan.protein }
end
assert_redirected_to meal_plan_path(assigns(:meal_plan))
end
test "should show meal_plan" do
get :show, id: @meal_plan
assert_response :success
end
test "should get edit" do
get :edit, id: @meal_plan
assert_response :success
end
test "should update meal_plan" do
patch :update, id: @meal_plan, meal_plan: { calories: @meal_plan.calories, carbs: @meal_plan.carbs, fat: @meal_plan.fat, name: @meal_plan.name, protein: @meal_plan.protein }
assert_redirected_to meal_plan_path(assigns(:meal_plan))
end
test "should destroy meal_plan" do
assert_difference('MealPlan.count', -1) do
delete :destroy, id: @meal_plan
end
assert_redirected_to meal_plans_path
end
end
|
class BoardPostUpvotesController < ApplicationController
before_action :set_board_post_upvote, only: [:show, :edit, :update, :destroy]
# GET /board_post_upvotes
# GET /board_post_upvotes.json
def index
@board_post_upvotes = BoardPostUpvote.all
end
# GET /board_post_upvotes/1
# GET /board_post_upvotes/1.json
def show
end
# GET /board_post_upvotes/new
def new
@board_post_upvote = BoardPostUpvote.new
end
# GET /board_post_upvotes/1/edit
def edit
end
# POST /board_post_upvotes
# POST /board_post_upvotes.json
def create
@board_post_upvote = BoardPostUpvote.new(board_post_upvote_params)
respond_to do |format|
if @board_post_upvote.save
format.html { redirect_to @board_post_upvote.board_post, notice: 'Board post upvote was successfully created.' }
format.json { render :show, status: :created, location: @board_post_upvote }
else
format.html { render :new }
format.json { render json: @board_post_upvote.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /board_post_upvotes/1
# PATCH/PUT /board_post_upvotes/1.json
def update
respond_to do |format|
if @board_post_upvote.update(board_post_upvote_params)
format.html { redirect_to @board_post_upvote, notice: 'Board post upvote was successfully updated.' }
format.json { render :show, status: :ok, location: @board_post_upvote }
else
format.html { render :edit }
format.json { render json: @board_post_upvote.errors, status: :unprocessable_entity }
end
end
end
# DELETE /board_post_upvotes/1
# DELETE /board_post_upvotes/1.json
def destroy
@board_post_upvote.destroy
respond_to do |format|
format.html { redirect_to board_post_upvotes_url, notice: 'Board post upvote was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_board_post_upvote
@board_post_upvote = BoardPostUpvote.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def board_post_upvote_params
params.require(:board_post_upvote).permit(:user_id, :board_post_id)
end
end
|
require 'happymapper'
require 'netvisor/element_base'
module Netvisor
class VatPercentage
include ElementBase
include HappyMapper
attribute :vatcode, String
content :percentage, Integer
end
end
|
# frozen_string_literal: true
require 'find'
# Encoding: utf-8
# @author Nikolay Yurin <yurinnick@outlook.com>
require 'yaml'
# DockerfileParser main class
class DockerfileParser
@commands = %w[FROM MAINTAINER RUN CMD EXPOSE ENV ADD COPY ENTRYPOINT
VOLUME USER WORKDIR ONBUILD]
# Parse Dockerfile from specified path
# @return [Array<Hash>] parser Dockerfile
def self.load_file(path)
loads(File.read(path))
end
def self.loads(s)
dockerfile_array = split_dockerfile(s)
parse_commands(dockerfile_array).each_cons(2).map do |item|
process_steps(dockerfile_array, item[0], item[1][:index])
end
end
def self.split_dockerfile(str)
str.gsub(/(\s\\\s)+/i, '').gsub("\n", ' ').squeeze(' ').split(' ')
end
def self.parse_commands(dockerfile_array)
dockerfile_array.each_with_index.map do |cmd, index|
{ index: index, command: cmd } if @commands.include?(cmd)
end.compact! << { index: dockerfile_array.length, command: 'EOF' }
end
def self.process_steps(dockerfile_array, step, next_cmd_index)
{ command: step[:command],
params: split_params(
step[:command],
dockerfile_array[step[:index] + 1..next_cmd_index - 1]
) }
end
def self.split_params(cmd, params)
case cmd
when 'FROM' then params.join('').split(':')
when 'RUN' then params.join(' ').split(/\s(\&|\;)+\s/).map(&:strip)
when 'ENV'
{ name: params[0], value: params[1..-1].join(' ') }
when 'COPY', 'ADD' then { src: params[0], dst: params[1] }
else
params = params.join(' ') if params.is_a?(Array)
YAML.safe_load(params.to_s)
end
end
private_class_method :parse_commands
private_class_method :process_steps
private_class_method :split_params
private_class_method :split_dockerfile
end
module Docker
include Rmk::Tools
def docker_build(name, docker_file: 'Dockerfile', docker_dir: '.', depends: [], tags: ['latest'], hub: '', build_args: {})
docker_dir = File.join(dir, docker_dir)
docker_file = File.join(dir, docker_file)
job("#{hub}#{name}", docker_file, depends) do |docker_file, _depends, implicit_dependencies| # rubocop:disable Lint/ShadowingOuterLocalVariable
DockerfileParser.load_file(docker_file).each do |cmd|
case cmd[:command]
when 'COPY', 'ADD'
unless cmd[:params][:src].start_with?('--') || cmd[:params][:src].start_with?('https://')
begin
Find.find(File.join(docker_dir, cmd[:params][:src])) do |path|
implicit_dependencies[path] = true if File.file?(path)
end
rescue StandardError => e
raise "Unable to read '#{cmd[:params][:src]}' required for #{docker_file}: #{e}"
end
end
end
end
docker_tags = tags.map { |tag| "#{hub}#{name}:#{tag}" }
build_args_cmd = build_args.map { |k, v| "--build-arg #{k}=#{v}" }.join(' ')
system("docker build -f #{docker_file} -t #{docker_tags.first} #{build_args_cmd} #{docker_dir} ")
docker_tags[1..-1].each do |t|
system("docker tag #{docker_tags.first} #{t}")
end
docker_tags
end
end
def docker_push(tags)
job("docker/#{tags.name}", tags) do |tags| # rubocop:disable Lint/ShadowingOuterLocalVariable
tags.each do |tag|
system("docker push #{tag}")
end
tags.first
end
end
end
|
class Rightboat::LeadsApprover
def self.approve_recent
deadline = RBConfig[:leads_approve_delay].hours.ago
Lead.pending.joins(:last_lead_trail).where('lead_trails.created_at < ?', deadline).each do |x|
x.update(status: 'approved')
end
rescue StandardError => e
Rightboat::CleverErrorsNotifier.try_notify(e, nil, nil, where: self.class.name)
raise e
end
end
|
require "test_helper"
class DeviceAttachmentsControllerTest < ActionDispatch::IntegrationTest
setup do
@device_attachment = device_attachments(:one)
end
test "should get index" do
get device_attachments_url, as: :json
assert_response :success
end
test "should create device_attachment" do
assert_difference('DeviceAttachment.count') do
post device_attachments_url, params: { device_attachment: { avatar: @device_attachment.avatar, device_id: @device_attachment.device_id } }, as: :json
end
assert_response 201
end
test "should show device_attachment" do
get device_attachment_url(@device_attachment), as: :json
assert_response :success
end
test "should update device_attachment" do
patch device_attachment_url(@device_attachment), params: { device_attachment: { avatar: @device_attachment.avatar, device_id: @device_attachment.device_id } }, as: :json
assert_response 200
end
test "should destroy device_attachment" do
assert_difference('DeviceAttachment.count', -1) do
delete device_attachment_url(@device_attachment), as: :json
end
assert_response 204
end
end
|
class CmsContentLoaders::Base < CivilService::Service
validate :ensure_no_conflicting_content
attr_reader :convention, :content_set, :content_names, :conflict_policy
def initialize(convention:, content_set:, content_names: nil, conflict_policy: :error)
@convention = convention
@content_set = content_set
@conflict_policy = conflict_policy
@content_names = content_names
end
private
def inner_call
load_content
success
end
def load_content(&block)
content_set.all_template_paths_with_names(subdir).each do |path, name|
next if content_names.present? && !content_names.include?(name)
content, attrs = content_set.template_content(path)
model = load_item(name, content, attrs)
next if model == :skip
block.call(model) if block
end
end
def load_item(name, content, attrs)
if existing_content_identifiers.include?(name)
return :skip if conflict_policy == :skip
if conflict_policy == :overwrite
convention_association.where(identifier_attribute => name).destroy_all
end
end
convention_association.create!(
identifier_attribute => name,
content_attribute => content,
**attrs
)
end
def subdir
raise NotImplementedError, 'CmsContentLoaders::Base subclasses must implement #subdir'
end
def identifier_attribute
raise NotImplementedError,
'CmsContentLoaders::Base subclasses must implement #identifier_attribute'
end
def content_attribute
raise NotImplementedError,
'CmsContentLoaders::Base subclasses must implement #content_attribute'
end
def convention_association
raise NotImplementedError,
'CmsContentLoaders::Base subclasses must implement #convention_associationd'
end
def taken_special_identifiers
{}
end
def existing_content_identifiers
@existing_content_identifiers ||= Set.new(convention_association.pluck(identifier_attribute))
end
def ensure_no_conflicting_content
return unless conflict_policy == :error
content_set.all_template_names(subdir).each do |name|
if taken_special_identifiers[name]
errors.add(:base, "#{convention.name} already has a #{taken_special_identifiers[name]}")
end
if existing_content_identifiers.include?(name)
errors.add(:base, "A #{subdir.singularize} named #{name} already exists in \
#{convention.name}")
end
end
end
end
|
module ZeroJobs
class Job < ActiveRecord::Base
set_table_name :zero_jobs
class DumpError < StandardError
end
def self.enqueue(obj, mess)
job = self.create(:object => obj, :message => mess)
if job.new_record?
raise ArgumentError.new("Can't save job : #{job.errors.full_message}")
else
JobSender.send_job(job)
end
job
end
def perfom
self.object.send(self.message)
end
def terminate!
self.destroy
end
def log_error(e)
self.update_attributes(:failed_at => Time.now, :last_error => e.message + "\n" + e.backtrace.join("\n"))
end
def object
@object ||= load(self.raw_object)
end
def object=(value)
self.raw_object = self.dump(value)
end
def dump(obj)
case obj
when Class then class_to_string(obj)
when ActiveRecord::Base then active_record_instance_to_string(obj)
else obj
end
end
def load(str)
begin
hash = JSON.parse(str.to_s)
rescue JSON::ParserError => e
return nil
end
case hash['type']
when 'class' then hash['class_name'].constantize
when 'active_record_instance' then hash['class_name'].constantize.find(hash['id'].to_i)
else nil
end
end
def active_record_instance_to_string(obj)
raise DumpError.new("Can't dump unsaved instance. Need an id to retreive it later") if obj.new_record?
{:type => :active_record_instance, :class_name => obj.class.name, :id => obj.id}.to_json
end
def class_to_string(obj)
{:type => :class, :class_name => obj.name}.to_json
end
end
end |
class AddDefaultValueToPenaltiesInStrokes < ActiveRecord::Migration
def change
change_column :strokes, :penalties, :integer, limit: 1, default: 0, null: false
end
end
|
# require_relative 'null_piece'
# require_relative 'board'
require "byebug"
class Piece
attr_accessor :position
attr_reader :color, :type
def initialize(board = nil, position = nil, color = nil, type = :xx)
@board = board
@position = position
@color = color
@type = type
end
def valid_moves
# debugger
puts "about to go into incheck loop"
sleep(1)
puts "right now position is " + @position.to_s
unless @board.in_check?(color)
temp = moves
return temp
end
result = []
moves.each do |move|
result << move unless move_into_check?(move)
end
result
end
def move_into_check?(end_pos)
copy = @board.deep_dup
copy.move_piece(position, end_pos)
copy.in_check?(color)
end
end
|
class Theme < ActiveHash::Base
self.data = [
{id: 1, body: 'おしゃれな河童たちの最先端トレンドはこれだ'},
{id: 2, body: '急募!関西人と大阪人を見分ける方法'},
{id: 3, body: 'ハリウッド忍者の特徴を教えてください'},
{id: 4, body: '成績優秀、スポーツ万能、なんでもできるタカシ君がアルバイトの面接に落ちました。なぜ?'},
{id: 5, body: 'このラーメン屋には二度と行きたくない!その理由とは'},
{id: 6, body: '帰ってきたウルトラマンは、何故帰ってきたのでしょう?'},
{id: 7, body: 'メルヘン検定1級の試験内容とは?'},
{id: 8, body: '世界で一番優しい嘘とはどんな嘘?'},
{id: 9, body: '絶対GACKTが言わなそうなセリフを言ってください'},
{id: 10, body: '女子力ってどんな力?'},
{id: 11, body: '乗客がタクシー運転手に激怒、なぜ?'},
{id: 12, body: '迷惑メールと知りつつも思わず開封してしまったタイトル(件名)とは?'},
{id: 13, body: '藤岡弘が一度やってみたかった贅沢とは?'},
{id: 14, body: '新型冷蔵庫の新機能とは?'},
{id: 15, body: '「間違いなく、その場しのぎ」と思われる言葉をいってください。'},
{id: 16, body: 'マニアックすぎて売れない写真集のタイトル'},
{id: 17, body: '「何で空は青いの?」子供の質問に答えてください。'},
{id: 18, body: '10年後の自分から手紙が届いた。何て書いてあった?'},
{id: 19, body: '富士山頂にて謎のボタンを発見。押すとどうなる?'},
{id: 20, body: '夜空を眺めながら彼氏に語られたら嫌な話とは?'},
{id: 21, body: '酢豚の中にパイナップルが入っている理由とは?'},
{id: 22, body: 'どんな人でも当選させるという凄腕選挙参謀。その驚くべき戦略とは?'},
{id: 23, body: 'こんな避難訓練は嫌だ!'},
{id: 24, body: '普通のレスラーと覆面レスラーの違いをなんでもいいので一つ挙げなさい。'},
{id: 25, body: 'サッカーに新しい反則が追加されました。どんな反則?'},
{id: 26, body: '履歴書に決して書いてはいけない趣味とは?'},
{id: 27, body: '「この人、カレー好きなんだろな。」なぜそう思った?'},
{id: 28, body: 'マザコン男の見分け方を教えて下さい。'},
{id: 29, body: '絶対500万枚売れるアルバムタイトルを書いて下さい'},
{id: 30, body: '「ジョジョの奇妙な冒険」でお馴染みのセリフ「無駄無駄無駄無駄無駄無駄ァーッ!!」さて、何が無駄?'}
]
end |
class TopicsController < ApplicationController
before_action :set_parent_topic, only: [:new]
before_action :set_topic, only: [:show, :edit, :update, :destroy]
def index
@total = FinderTopicService.count
@limit = Topic.limit_default
@page = params[:page].present? ? params[:page] : 0
@topics = FinderTopicService.find_by_topic(nil, @limit, @page)
end
def show
end
def new
@topic = Topic.new
@topic.topic = @parent_topic
end
def edit
@parent_topic = @topic.topic
end
def create
@topic = Topic.new(topic_params)
# @topic.topic = @parent_topic
respond_to do |format|
if @topic.save
format.html { redirect_to topics_url, notice: I18n.translate('topic.message.success_create') }
else
format.html { render :new }
end
end
end
def update
respond_to do |format|
if @topic.update(topic_params)
format.html { redirect_to @topic, notice: I18n.translate('topic.message.success_update') }
else
format.html { render :edit }
end
end
end
def destroy
@topic.destroy
respond_to do |format|
format.html { redirect_to topics_url, notice: I18n.translate('topic.message.success_destroy') }
end
end
private
def set_topic
@topic = Topic.find(params[:id])
end
def set_parent_topic
@parent_topic = Topic.find(params[:topic_id]) if params[:topic_id].present?
end
def topic_params
params.require(:topic).permit(:description, :status, :topic_id, :limit, :page)
end
end
|
module Myimdb
module Search
class Google < Base
include HTTParty
format :json
headers 'Content-Type' => 'application/json'
base_uri 'ajax.googleapis.com'
class << self
def search_text( text, options={} )
text = text + " site:#{options[:restrict_to]}" if !options[:restrict_to].blank?
response = get( '/ajax/services/search/web', :query=> {:v=> '1.0', :q=> text} )
parse_search_result( response )
end
def search_images( text, options={} )
sizes = {
'large' => 'l',
'medium' => 'm',
'small' => 'i'
}
search_options = { :v=> '1.0', :q=> text }
search_options.merge!(:imgsz=> sizes[options[:size].to_s]) if !options[:size].blank?
text = text + " site:#{options[:restrict_to]}" if !options[:restrict_to].blank?
response = get( '/ajax/services/search/images', :query=> search_options )
parse_search_result( response )
end
private
def parse_search_result( response )
response['responseData'] and response['responseData']['results'].collect do |response_element|
{
:url => response_element['url'],
:title => response_element['titleNoFormatting']
}
end
end
end
end
end
end |
require File.expand_path('../test_helper', __FILE__)
class ExecutorTest < MiniTest::Unit::TestCase
def setup
@repo = create_empty_repo
end
def test_stderr_should_raise
assert_raises(Girth::Executor::Error) { @repo.git.exec("show","TAIL") }
end
def test_should_have_version
assert_match /\A\d[\d.]*\d\z/, Girth::Executor.version
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.