text stringlengths 10 2.61M |
|---|
# -*- coding: utf-8 -*-
# Configures your navigation
SimpleNavigation::Configuration.run do |navigation|
navigation.selected_class = nil
a_opts = {:class => "dropdown-toggle","data-toggle" => "dropdown", "role"=>"button","aria-expanded" => 'false'}
html_opts = {class: 'dropdown'}
# Define the primary navigation
navigation.items do |primary|
root_url = root_path if current_account.nil? || current_user
root_url = client_root_path if current_client_user
root_url = admin_root_path if current_admin
#opts = {:class => "dropdown", :link => a_opts }
opts = {html: html_opts, link_html: a_opts}
primary.item :home, content_tag(:span, "Home"),root_url
if current_client_user || current_user
primary.item :dns, content_tag(:span, "DNS")+content_tag(:span,"",:class => 'caret'), '#',opts do |sub_nav|
if current_client_user
sub_nav.item :dnszones,content_tag(:span, "DNS Zones"), client_dns_zones_path
sub_nav.item :isp_dnszones,content_tag(:span, "ISPConfig DNS Zones"),client_isp_dnszones_path
end
sub_nav.item :dnsrecords, content_tag(:span, "DNS Records"), dns_host_records_path
sub_nav.dom_attributes = {:class => 'dropdown-menu', :role => 'menu'}
end
end
if current_user
primary.item :user_data, content_tag(:span,"Account")+content_tag(:span,"", :class => 'caret'), "#", opts do |user_nav|
user_nav.item :user_edit, content_tag(:span,"Edit information"),edit_user_registration_path
user_nav.dom_attributes = {:class => 'dropdown-menu', :role => 'menu'}
end
end
if current_admin
primary.item :users, content_tag(:span,"User management")+content_tag(:span,"",:class => 'caret'), '#', opts do |sub_nav|
sub_nav.item :userlist, content_tag(:span, "Known users"), admins_users_path
sub_nav.dom_attributes = {:class => 'dropdown-menu', :role => 'menu'}
end
primary.item :app_settings, content_tag(:span, I18n.t('settings.global.head')),settings_path
primary.item :admin_data, content_tag(:span, "Account"), admin_edit_path
end
if current_account
primary.item :user_logout, content_tag(:span, "Logout"), send("destroy_#{current_account.class.name.underscore}_session_path"), :method => :delete
end
primary.item :user_login, content_tag(:span, "Login or register"),user_session_path unless current_account
primary.dom_attributes = {class: 'nav navbar-nav'}
end
end
|
# Write a method that determines and returns the ASCII string value of a string
# that is passed in as an argument. The ASCII string value is the sum of the
# ASCII values of every character in the string. (You may use String#ord to
# determine the ASCII value of a character.)
# split the string, use .ord, add it up
def ascii_value(string)
arr = string.split(//)
sum = 0
arr.each do |v|
sum += v.ord
end
sum
end
p ascii_value('Four score') == 984
p ascii_value('Launch School') == 1251
p ascii_value('a') == 97
p ascii_value('') == 0
|
FactoryBot.define do
factory :item do
association :user
category_id {1}
fare_id {1}
condition_id {1}
days_id {1}
prefecture_id {1}
title {Faker::Lorem.sentence}
description {Faker::Lorem.sentence}
pride {9999999}
after(:build) do |item|
item.image.attach(io: File.open('public/images/test_image.png'), filename: 'test_image.png')
end
end
end
|
module Square
# BookingsApi
class BookingsApi < BaseApi
# Retrieve a collection of bookings.
# To call this endpoint with buyer-level permissions, set
# `APPOINTMENTS_READ` for the OAuth scope.
# To call this endpoint with seller-level permissions, set
# `APPOINTMENTS_ALL_READ` and `APPOINTMENTS_READ` for the OAuth scope.
# @param [Integer] limit Optional parameter: The maximum number of results
# per page to return in a paged response.
# @param [String] cursor Optional parameter: The pagination cursor from the
# preceding response to return the next page of the results. Do not set this
# when retrieving the first page of the results.
# @param [String] customer_id Optional parameter: The
# [customer](entity:Customer) for whom to retrieve bookings. If this is not
# set, bookings for all customers are retrieved.
# @param [String] team_member_id Optional parameter: The team member for
# whom to retrieve bookings. If this is not set, bookings of all members are
# retrieved.
# @param [String] location_id Optional parameter: The location for which to
# retrieve bookings. If this is not set, all locations' bookings are
# retrieved.
# @param [String] start_at_min Optional parameter: The RFC 3339 timestamp
# specifying the earliest of the start time. If this is not set, the current
# time is used.
# @param [String] start_at_max Optional parameter: The RFC 3339 timestamp
# specifying the latest of the start time. If this is not set, the time of
# 31 days after `start_at_min` is used.
# @return [ListBookingsResponse Hash] response from the API call
def list_bookings(limit: nil,
cursor: nil,
customer_id: nil,
team_member_id: nil,
location_id: nil,
start_at_min: nil,
start_at_max: nil)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v2/bookings',
'default')
.query_param(new_parameter(limit, key: 'limit'))
.query_param(new_parameter(cursor, key: 'cursor'))
.query_param(new_parameter(customer_id, key: 'customer_id'))
.query_param(new_parameter(team_member_id, key: 'team_member_id'))
.query_param(new_parameter(location_id, key: 'location_id'))
.query_param(new_parameter(start_at_min, key: 'start_at_min'))
.query_param(new_parameter(start_at_max, key: 'start_at_max'))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Creates a booking.
# The required input must include the following:
# - `Booking.location_id`
# - `Booking.start_at`
# - `Booking.team_member_id`
# - `Booking.AppointmentSegment.service_variation_id`
# - `Booking.AppointmentSegment.service_variation_version`
# To call this endpoint with buyer-level permissions, set
# `APPOINTMENTS_WRITE` for the OAuth scope.
# To call this endpoint with seller-level permissions, set
# `APPOINTMENTS_ALL_WRITE` and `APPOINTMENTS_WRITE` for the OAuth scope.
# For calls to this endpoint with seller-level permissions to succeed, the
# seller must have subscribed to *Appointments Plus*
# or *Appointments Premium*.
# @param [CreateBookingRequest] body Required parameter: An object
# containing the fields to POST for the request. See the corresponding
# object definition for field details.
# @return [CreateBookingResponse Hash] response from the API call
def create_booking(body:)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::POST,
'/v2/bookings',
'default')
.header_param(new_parameter('application/json', key: 'Content-Type'))
.body_param(new_parameter(body))
.header_param(new_parameter('application/json', key: 'accept'))
.body_serializer(proc do |param| param.to_json unless param.nil? end)
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Searches for availabilities for booking.
# To call this endpoint with buyer-level permissions, set
# `APPOINTMENTS_READ` for the OAuth scope.
# To call this endpoint with seller-level permissions, set
# `APPOINTMENTS_ALL_READ` and `APPOINTMENTS_READ` for the OAuth scope.
# @param [SearchAvailabilityRequest] body Required parameter: An object
# containing the fields to POST for the request. See the corresponding
# object definition for field details.
# @return [SearchAvailabilityResponse Hash] response from the API call
def search_availability(body:)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::POST,
'/v2/bookings/availability/search',
'default')
.header_param(new_parameter('application/json', key: 'Content-Type'))
.body_param(new_parameter(body))
.header_param(new_parameter('application/json', key: 'accept'))
.body_serializer(proc do |param| param.to_json unless param.nil? end)
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Bulk-Retrieves a list of bookings by booking IDs.
# To call this endpoint with buyer-level permissions, set
# `APPOINTMENTS_READ` for the OAuth scope.
# To call this endpoint with seller-level permissions, set
# `APPOINTMENTS_ALL_READ` and `APPOINTMENTS_READ` for the OAuth scope.
# @param [BulkRetrieveBookingsRequest] body Required parameter: An object
# containing the fields to POST for the request. See the corresponding
# object definition for field details.
# @return [BulkRetrieveBookingsResponse Hash] response from the API call
def bulk_retrieve_bookings(body:)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::POST,
'/v2/bookings/bulk-retrieve',
'default')
.header_param(new_parameter('application/json', key: 'Content-Type'))
.body_param(new_parameter(body))
.header_param(new_parameter('application/json', key: 'accept'))
.body_serializer(proc do |param| param.to_json unless param.nil? end)
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Retrieves a seller's booking profile.
# @return [RetrieveBusinessBookingProfileResponse Hash] response from the API call
def retrieve_business_booking_profile
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v2/bookings/business-booking-profile',
'default')
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Lists booking profiles for team members.
# @param [TrueClass | FalseClass] bookable_only Optional parameter:
# Indicates whether to include only bookable team members in the returned
# result (`true`) or not (`false`).
# @param [Integer] limit Optional parameter: The maximum number of results
# to return in a paged response.
# @param [String] cursor Optional parameter: The pagination cursor from the
# preceding response to return the next page of the results. Do not set this
# when retrieving the first page of the results.
# @param [String] location_id Optional parameter: Indicates whether to
# include only team members enabled at the given location in the returned
# result.
# @return [ListTeamMemberBookingProfilesResponse Hash] response from the API call
def list_team_member_booking_profiles(bookable_only: false,
limit: nil,
cursor: nil,
location_id: nil)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v2/bookings/team-member-booking-profiles',
'default')
.query_param(new_parameter(bookable_only, key: 'bookable_only'))
.query_param(new_parameter(limit, key: 'limit'))
.query_param(new_parameter(cursor, key: 'cursor'))
.query_param(new_parameter(location_id, key: 'location_id'))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Retrieves a team member's booking profile.
# @param [String] team_member_id Required parameter: The ID of the team
# member to retrieve.
# @return [RetrieveTeamMemberBookingProfileResponse Hash] response from the API call
def retrieve_team_member_booking_profile(team_member_id:)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v2/bookings/team-member-booking-profiles/{team_member_id}',
'default')
.template_param(new_parameter(team_member_id, key: 'team_member_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Retrieves a booking.
# To call this endpoint with buyer-level permissions, set
# `APPOINTMENTS_READ` for the OAuth scope.
# To call this endpoint with seller-level permissions, set
# `APPOINTMENTS_ALL_READ` and `APPOINTMENTS_READ` for the OAuth scope.
# @param [String] booking_id Required parameter: The ID of the
# [Booking](entity:Booking) object representing the to-be-retrieved
# booking.
# @return [RetrieveBookingResponse Hash] response from the API call
def retrieve_booking(booking_id:)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v2/bookings/{booking_id}',
'default')
.template_param(new_parameter(booking_id, key: 'booking_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Updates a booking.
# To call this endpoint with buyer-level permissions, set
# `APPOINTMENTS_WRITE` for the OAuth scope.
# To call this endpoint with seller-level permissions, set
# `APPOINTMENTS_ALL_WRITE` and `APPOINTMENTS_WRITE` for the OAuth scope.
# For calls to this endpoint with seller-level permissions to succeed, the
# seller must have subscribed to *Appointments Plus*
# or *Appointments Premium*.
# @param [String] booking_id Required parameter: The ID of the
# [Booking](entity:Booking) object representing the to-be-updated booking.
# @param [UpdateBookingRequest] body Required parameter: An object
# containing the fields to POST for the request. See the corresponding
# object definition for field details.
# @return [UpdateBookingResponse Hash] response from the API call
def update_booking(booking_id:,
body:)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::PUT,
'/v2/bookings/{booking_id}',
'default')
.template_param(new_parameter(booking_id, key: 'booking_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'Content-Type'))
.body_param(new_parameter(body))
.header_param(new_parameter('application/json', key: 'accept'))
.body_serializer(proc do |param| param.to_json unless param.nil? end)
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Cancels an existing booking.
# To call this endpoint with buyer-level permissions, set
# `APPOINTMENTS_WRITE` for the OAuth scope.
# To call this endpoint with seller-level permissions, set
# `APPOINTMENTS_ALL_WRITE` and `APPOINTMENTS_WRITE` for the OAuth scope.
# For calls to this endpoint with seller-level permissions to succeed, the
# seller must have subscribed to *Appointments Plus*
# or *Appointments Premium*.
# @param [String] booking_id Required parameter: The ID of the
# [Booking](entity:Booking) object representing the to-be-cancelled
# booking.
# @param [CancelBookingRequest] body Required parameter: An object
# containing the fields to POST for the request. See the corresponding
# object definition for field details.
# @return [CancelBookingResponse Hash] response from the API call
def cancel_booking(booking_id:,
body:)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::POST,
'/v2/bookings/{booking_id}/cancel',
'default')
.template_param(new_parameter(booking_id, key: 'booking_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'Content-Type'))
.body_param(new_parameter(body))
.header_param(new_parameter('application/json', key: 'accept'))
.body_serializer(proc do |param| param.to_json unless param.nil? end)
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
end
end
|
class LdapController < ApplicationController
def index
@groups = User.get_all_ldap_groups
respond_to do |format|
format.json { render json: @groups.to_json }
end
end
def create
@ldap_role_mapping = LdapRoleMapping.new(ldap_group: params['ldap_group'], role: params['role'])
respond_to do |format|
if @ldap_role_mapping.save
format.json { render json: @ldap_role_mapping }
format.js { render json: @ldap_role_mapping }
else
format.json { render json: @ldap_role_mapping.errors}
format.js { render json: @ldap_role_mapping.errors}
end
end
end
def destroy
@ldap_role_mapping = LdapRoleMapping.find(params['mapping_id'])
respond_to do |format|
if @ldap_role_mapping.destroy!
format.json { render json: @ldap_role_mapping.errors}
format.js { render json: @ldap_role_mapping.errors}
else
format.json { render json: @ldap_role_mapping.errors}
format.js { render json: @ldap_role_mapping.errors}
end
end
end
end
|
#!/usr/bin/env jruby
ENABLE_REMOTE_REQUIRE = true
REMOTE_REPOSITORIES = ['http://dl.dropbox.com/u/12189743/InstallationFiles']
DEFAULT_LOGFILE_NAME = 'bootstrap_installer.log'
DEFAULT_SETTINGS_FILE = 'defaultSettings'
CUSTOM_SETTINGS_FILE = 'customSettings'
class MainInstaller
class << self
#Load the module from a remote location
#This will fail in remote mode if the remote file is not present
def remoteRequire(moduleName)
unless defined?(@@registeredModules)
@@registeredModules = {}
end
registeredModule = @@registeredModules[moduleName]
if registeredModule
return registeredModule[:status]
else
fullModuleName = %{#{moduleName}.rb}
localCopy = File.exists?(fullModuleName)
remoteRepository = REMOTE_REPOSITORIES.first
fullModuleNameURI = "#{remoteRepository}/common_installer/#{fullModuleName}"
if ENABLE_REMOTE_REQUIRE and (not localCopy)
cmd = %{wget -q #{fullModuleNameURI}}
fullCmd = %{#{cmd} > /dev/null 2>&1}
targetDir = moduleName =~ /components\// ? 'components' : '.'
success = false
Dir.chdir(targetDir) do |dir|
success = Kernel.system(fullCmd)
end
unless success
msg = %{Error: File #{fullModuleName} not found at #{fullModuleNameURI}. Exiting ... }
if Object.respond_to?(:logger)
logger.error(msg)
else
puts(msg)
end
Kernel.exit(1)
end
end
status = require(moduleName)
unless localCopy
logger.debug(%{Obtaining #{fullModuleName} from #{fullModuleNameURI}})
end
@@registeredModules[moduleName] = {:status => status}
return status
end
end
end
end
def remoteRequire(moduleName)
MainInstaller.remoteRequire(moduleName)
end
remoteRequire 'installerLogger'
remoteRequire 'commandLine'
remoteRequire 'ioHelpers'
remoteRequire 'osHelpers'
remoteRequire 'core'
remoteRequire 'buildHelper'
remoteRequire 'networkHelper'
#puts "ARGV #{ARGV.inspect}"
Core.runInstaller
|
class User
attr_reader :username, :email, :password, :id
def initialize(username:, email:, password:, id:)
@username = username
@email = email
@password = password
@id = id
end
def self.signup(username:, email:, password:)
if ENV['ENVIRONMENT'] == 'test'
connection = PG.connect(dbname: 'celebnb_test')
else
connection = PG.connect(dbname: 'celebnb')
end
result = connection.exec_params("INSERT INTO users (username, email, password) VALUES($1, $2, $3);", [username, email, password])
end
def self.signin(username:, password:)
if ENV['ENVIRONMENT'] == 'test'
connection = PG.connect(dbname: 'celebnb_test')
else
connection = PG.connect(dbname: 'celebnb')
end
result = connection.exec_params("SELECT * FROM users WHERE username = $1 AND password = $2;", [username, password])
if result.ntuples == 0
nil
else
User.new(username: result[0]['username'], password: result[0]['password'], email: result[0]['email'], id: result[0]['id'])
end
end
end
|
require 'open-uri'
require 'nokogiri'
require 'csv'
require 'kconv'
def fetch_page(url)
sleep(2)
charset = nil
html = open(url) do |f|
raise "Got 404 error" if f.status[0] == "404"
charset = f.charset # 文字種別を取得
f.read # htmlを読み込んで変数htmlに渡す
end
doc = Nokogiri::HTML.parse(html.toutf8, nil, 'utf-8')
return doc
end
def address2prefecture(address)
result = /(...??[都道府県])/.match(address)
if result
return result[0]
else
return nil
end
end
# スクレイピング先の情報
shop_name = "SENSE OF PLACE by URBAN RESEARCH"
short_shop_name = "SENSE OF PLACE"
target_url = "http://senseofplace.jp/shoplist"
File.open("seeds.rb", "w") do |file|
# リソースを取得
branch_list_page = fetch_page(target_url)
branches = []
branch_list_page.css('.shopdetail').each do |s|
branch_name = s.css('.name').inner_text.strip
address = s.css(".address").inner_text.split(" ")[1]
begin
branch_address = /([^a-zA-Z0-9]{1,3}?[都道府県市][^\s]*[0-9]([0-9\-番号丁目])+)/.match(address)[0].strip
puts "\t* #{branch_name} | #{branch_address}"
rescue
branch_address = ""
puts "\t---> [Error] failed to extract address str (#{branch_name})"
end
# 配列に保存
branches.push({name: branch_name, url: target_url, address: branch_address})
# seedsに書き出し
branch_prefecture = address2prefecture(branch_address)
if branch_prefecture
code = %(prefecture_id = Prefecture.find_by(name: "#{branch_prefecture}").id\n)
code += %(Shop.find_by(name: "#{shop_name}").branches.create(name: "#{short_shop_name} #{branch_name}", address:"#{branch_address}", prefecture_id: prefecture_id)\n)
file.write(code)
end
end
end
|
require 'test_helper'
class StructureMedicamentsControllerTest < ActionDispatch::IntegrationTest
setup do
@structure_medicament = structure_medicaments(:one)
end
test "should get index" do
get structure_medicaments_url
assert_response :success
end
test "should get new" do
get new_structure_medicament_url
assert_response :success
end
test "should create structure_medicament" do
assert_difference('StructureMedicament.count') do
post structure_medicaments_url, params: { structure_medicament: { medicament_id: @structure_medicament.medicament_id, price: @structure_medicament.price, status: @structure_medicament.status, structure_id: @structure_medicament.structure_id, user_id: @structure_medicament.user_id } }
end
assert_redirected_to structure_medicament_url(StructureMedicament.last)
end
test "should show structure_medicament" do
get structure_medicament_url(@structure_medicament)
assert_response :success
end
test "should get edit" do
get edit_structure_medicament_url(@structure_medicament)
assert_response :success
end
test "should update structure_medicament" do
patch structure_medicament_url(@structure_medicament), params: { structure_medicament: { medicament_id: @structure_medicament.medicament_id, price: @structure_medicament.price, status: @structure_medicament.status, structure_id: @structure_medicament.structure_id, user_id: @structure_medicament.user_id } }
assert_redirected_to structure_medicament_url(@structure_medicament)
end
test "should destroy structure_medicament" do
assert_difference('StructureMedicament.count', -1) do
delete structure_medicament_url(@structure_medicament)
end
assert_redirected_to structure_medicaments_url
end
end
|
class Location < ActiveRecord::Base
attr_accessible :type, :location_prototype, :area
belongs_to :location_prototype, :foreign_key => "location_code"
belongs_to :game
belongs_to :area
has_many :tasks
def name
location_prototype.name
end
def layout
location_prototype.layout
end
def template
location_prototype.template
end
def actions
location_prototype.actions
end
end |
class SessionsController < ApplicationController
def create
@user = User.find_or_create_from_auth_hash(auth_hash)
sign_in(@user)
redirect_to root_path
end
def destroy
sign_out
redirect_to root_path, :notice => "Successfully signed out!"
end
def update
if current_user.update_attribute(:company_name, params[:company_name])
#current_user.save
render :inline => current_user.company_name
else
render :nothing => true, :status => :bad_request
end
end
def fail
redirect_to root_path, :alert => "Error authenticating"
end
protected
def auth_hash
request.env['omniauth.auth']
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :approved_status do
code { Faker::Code.isbn[0..24] }
label { Faker::Lorem.characters(256) }
end
end
|
class RenameCustomFieldMapping < ActiveRecord::Migration
def up
if table_exists?(:custom_field_mapping)
rename_table :custom_field_mapping, :custom_field_mappings
end
end
def down
if table_exists?(:custom_field_mappings)
rename_table :custom_field_mappings, :custom_field_mapping
end
end
end
|
#==============================================================================
# ** Scene_Shop
#------------------------------------------------------------------------------
# This class performs shop screen processing.
#==============================================================================
class Scene_Shop < Scene_MenuBase
#--------------------------------------------------------------------------
# * Instance Vars
#--------------------------------------------------------------------------
attr_accessor :shopname
#--------------------------------------------------------------------------
# * Object Initialization
#--------------------------------------------------------------------------
def initialize
super
@shopname = "Shop"
end
#--------------------------------------------------------------------------
# * Execute Purchase
# >> source is the bits payer, recipient is who take the bita
# thus source will gain the item, recipient will lose item.
#--------------------------------------------------------------------------
def do_buy(number)
bits = number * buying_price
source = Vocab::Player
recipient = Vocab::Coinbase
info = sprintf("%s bought %s(%d) at %s.", $game_party.leader.name, @item.name, number, @shopname)
BlockChain.new_transaction(bits, @item, number, source, recipient, info)
$game_party.gain_item_origin(@item, number)
end
#--------------------------------------------------------------------------
# * Execute Sale
#--------------------------------------------------------------------------
def do_sell(number)
bits = number * selling_price
source = Vocab::Coinbase
recipient = Vocab::Player
info = sprintf("%s bought %s(%d) from %s.",$game_party.leader.name, @item.name, number, @shopname)
BlockChain.new_transaction(bits, @item, number, source, recipient, info)
$game_party.gain_item_origin(@item, -number)
end
#--------------------------------------------------------------------------
# * Buy [OK]
#--------------------------------------------------------------------------
def on_buy_ok
@item = @buy_window.item
sync_blockchain
@buy_window.hide
@number_window.set(@item, max_buy, buying_price, currency_unit)
@number_window.show.activate
end
#--------------------------------------------------------------------------
# * Sell [OK]
#--------------------------------------------------------------------------
def on_sell_ok
@item = @sell_window.item
sync_blockchain
@status_window.item = @item
@category_window.hide
@sell_window.hide
@number_window.set(@item, max_sell, selling_price, currency_unit)
@number_window.show.activate
@status_window.show
end
#--------------------------------------------------------------------------
# * Synchronize BlockChain
#--------------------------------------------------------------------------
def sync_blockchain
BlockChain.recover_nodes
$game_party.sync_blockchain(@item)
end
end
|
#
# Cookbook Name:: cubrid
# Attributes:: demodb
#
# Copyright 2012, Esen Sagynov <kadishmal@gmail.com>
#
# Distributed under MIT license
#
# the default target directory to install CUBRID
default['cubrid']['home'] = "/opt/cubrid"
# the directory where to install the demodb database
set['cubrid']['demodb_dir'] = "#{node['cubrid']['home']}/databases/demodb"
# the full path of a script which install the demodb database
set['cubrid']['demodb_script'] = "#{node['cubrid']['home']}/demo/make_cubrid_demo.sh"
|
class AddShowroomIdToWesellItems < ActiveRecord::Migration
def change
add_column :wesell_items, :showroom_id, :integer, default: nil
end
end
|
class AddActividadToLoabores < ActiveRecord::Migration
def change
add_column :labores, :actividad, :string
end
end
|
module Agents
class TezosBalanceAgent < Agent
include FormConfigurable
can_dry_run!
no_bulk_receive!
default_schedule "never"
description do
<<-MD
The tezos balance agent fetches tezos's balance from tezos explorer
`expected_receive_period_in_days` is used to determine if the Agent is working. Set it to the maximum number of days
that you anticipate passing without this Agent receiving an incoming Event.
MD
end
event_description <<-MD
Events look like this:
{
"value": xxxx,
...
"crypto": "XTZ"
}
MD
def default_options
{
'wallet_address' => '',
'expected_receive_period_in_days' => '2',
'changes_only' => 'true'
}
end
form_configurable :expected_receive_period_in_days, type: :string
form_configurable :wallet_address, type: :string
form_configurable :changes_only, type: :boolean
def validate_options
unless options['wallet_address'].present?
errors.add(:base, "wallet_address is a required field")
end
if options.has_key?('changes_only') && boolify(options['changes_only']).nil?
errors.add(:base, "if provided, changes_only must be true or false")
end
unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
errors.add(:base, "Please provide 'expected_receive_period_in_days' to indicate how many days can pass before this Agent is considered to be not working")
end
end
def working?
event_created_within?(options['expected_receive_period_in_days']) && !recent_error_logs?
end
def check
handle interpolated[:wallet_address]
end
private
def handle(wallet)
uri = URI.parse("https://api.tzstats.com/explorer/account/#{wallet}?")
request = Net::HTTP::Get.new(uri)
request["Authority"] = "api.tzstats.com"
request["Cache-Control"] = "max-age=0"
request["Upgrade-Insecure-Requests"] = "1"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
log response.code
parsed_json = JSON.parse(response.body)
payload = { 'crypto' => "XTZ", 'address' => parsed_json["address"], 'value' => parsed_json["total_balance"] }
if interpolated['changes_only'] == 'true'
if payload.to_s != memory['last_status']
memory['last_status'] = payload.to_s
create_event payload: payload
end
else
create_event payload: payload
if payload.to_s != memory['last_status']
memory['last_status'] = payload.to_s
end
end
end
end
end
|
class AddDefArrayColumnToWords < ActiveRecord::Migration
def change
add_column :words, :def_array, :string_array
end
end
|
require 'mail'
require 'securerandom'
# displays and updates users
# user creation is handled by WelcomeController
class UsersController < ApplicationController
before_action :set_locale
# render a view listing all known users
def index
@users = User.all
end
# render user details
def show
@user = User.find(params[:id])
# avoid displaying empty string for user email
if @user.email
@email_safe = @user.email
else
t = I18n.t('users.email.empty')
@email_safe = t
logger.debug @email_safe
end
end
# despite the name, this will actually update an user created by the tracker.
# the user should not know this, so from his perspective it is creating a new entry
def new
unless params[:email] then
render plain: "no email", :status => 400
return
end
# email format validation. we should also validate the MX, or use an external service (neverbounce.com, apilayer.com)
begin
email = Mail::Address.new(params[:email])
unless email.domain
# this gem accepts email addresses without domain
render plain: "invalid email", :status => 400
return
end
rescue Mail::Field::ParseError
render plain: "invalid email", :status => 400
return
end
@user = User.find(session[:current_user_id])
@user.email = email.address
@user.save
render :json => @user
end
private
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
end
|
class ControlqnyntsController < ApplicationController
before_action :set_controlqnynt, only: [:show, :edit, :update, :destroy]
# GET /controlqnynts
# GET /controlqnynts.json
def index
@controlqnynts = Controlqnynt.all
@controlqnyntsb = Controlqnynt.all.order(:vendida => :desc)
end
# GET /controlqnynts/1
# GET /controlqnynts/1.json
def show
end
# GET /controlqnynts/new
def new
@controlqnynt = Controlqnynt.new
end
# GET /controlqnynts/1/edit
def edit
end
# POST /controlqnynts
# POST /controlqnynts.json
def create
@controlqnynt = Controlqnynt.new(controlqnynt_params)
respond_to do |format|
if @controlqnynt.save
format.html { redirect_to @controlqnynt, notice: 'Controlqnynt was successfully created.' }
format.json { render :show, status: :created, location: @controlqnynt }
else
format.html { render :new }
format.json { render json: @controlqnynt.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /controlqnynts/1
# PATCH/PUT /controlqnynts/1.json
def update
respond_to do |format|
if @controlqnynt.update(controlqnynt_params)
format.html { redirect_to @controlqnynt, notice: 'Controlqnynt was successfully updated.' }
format.json { render :show, status: :ok, location: @controlqnynt }
else
format.html { render :edit }
format.json { render json: @controlqnynt.errors, status: :unprocessable_entity }
end
end
end
# DELETE /controlqnynts/1
# DELETE /controlqnynts/1.json
def destroy
@controlqnynt.destroy
respond_to do |format|
format.html { redirect_to controlqnynts_url, notice: 'Controlqnynt was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_controlqnynt
@controlqnynt = Controlqnynt.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def controlqnynt_params
params.require(:controlqnynt).permit(:numero, :limite, :vendida)
end
end
|
json.array! @users, :id, :username, :image_url
#
# @users.each do |user|
# json.set! user.id do
# json.set! :id, user.id
# json.set! :username, user.username
# json.set! :image_url, user.image_url
#
# end
# end
|
# frozen_string_literal: true
require 'rails_helper'
describe 'campaign overview page', type: :feature, js: true do
let(:slug) { 'spring_2016' }
let(:user) { create(:user) }
let(:admin) { create(:admin) }
let(:campaign) do
create(:campaign,
id: 10001,
title: 'My awesome Spring 2016 campaign',
slug: slug,
description: 'This is the best campaign')
end
before do
Capybara.current_driver = :poltergeist
end
context 'as an user' do
it 'should not show the edit buttons' do
login_as(user, scope: user)
visit "/campaigns/#{campaign.slug}"
expect(page).to have_no_css('.campaign-description .rails_editable-edit')
end
end
context 'as an admin' do
before do
login_as(admin, scope: :user)
visit "/campaigns/#{campaign.slug}"
end
it 'shows the description input field when in edit mode' do
find('.campaign-description .rails_editable-edit').click
find('#campaign_description', visible: true)
end
it 'updates the campaign when you click save' do
new_description = 'This is my new description'
find('.campaign-description .rails_editable-edit').click
fill_in('campaign_description', with: new_description)
find('.campaign-description .rails_editable-save').click
expect(page).to have_content('Campaign updated')
expect(campaign.reload.description).to eq(new_description)
end
end
end
|
class Api::V1::BookingsController < Api::V1::BaseController
skip_before_action :verify_authenticity_token, only: [ :create, :update ]
def index
set_parent
@bookings = @parent.bookings.joins(:session).order("start_time ASC")
end
def new
@booking = Booking.new
end
# before creating a new booking, checks to see if the user
# has already booked that session id
def create
set_parent
set_session
if @session.bookings.where(user_id: @parent.id) != []
render_booked
else
@booking = Booking.new(booking_params)
@booking.parent = @parent
@booking.session = @session
if @booking.save
render json: { booking: @booking, status: :success }
else
render_error
end
end
end
def update
set_parent
set_session
@booking = Booking.find(booking_params)
if @booking.update(booking_params)
render json: { booking: @booking, status: :updated }
else
render_error
end
end
private
def set_parent
@parent = User.find(params[:user_id])
end
def set_session
@session = Session.find(params[:session_id])
end
def booking_params
params.require(:booking).permit(:user_id, :session_id, :confirmed, :cancelled)
end
def render_error
render json: { error: @booking.errors.full_messages }
end
def render_booked
render json: { error: :already_booked }
end
# def render_full
# render json: { error: :session_full }
# end
end
|
#!/Users/spamram/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
# Goal:
# Find the sum of the numbers on the diagonals in a 1001 by 1001 spiral.
def solve
step, n, sum = 2, 1, 1
1.upto(2000) do |i|
step += 2 if (i-1) % 4 == 0 unless i == 1
n += step
sum += n
end
sum
end
puts solve |
require 'rails_helper'
RSpec.describe Task, type: :model do
it { should validate_presence_of(:external_id) }
it { should have_many(:orders).through(:task_orders) }
it { should belong_to(:user) }
end
|
require 'spec_helper'
describe 'Comments pages', type: :controller do
subject { page }
let(:user) { FactoryGirl.create(:user) }
let(:author) { FactoryGirl.create(:user, name: 'Author') }
let(:user_image) { FactoryGirl.create(:user_image, user: author) }
before { sign_in user }
describe 'when image do not passed' do
before { visit user_image_path(user_image) }
it 'responds with 404' do
expect(status_code).to eq 404
end
end
describe 'when image passed' do
before do
ActionOnImage.run user_image: user_image, x: true
visit user_image_path(user_image)
end
it { should have_content(user_image.user.name) }
describe 'invalid form' do
it 'message is blank' do
expect { click_button 'оставить отзыв' }.not_to change(Comment, :count)
end
end
describe 'valid form' do
before { fill_in 'comment[content]', with: 'Lorem ipsum' }
it 'message present' do
expect { click_button 'оставить отзыв' }.to change(Comment, :count).by(1)
end
end
end
end
|
require 'spec_helper'
describe TextBelt::PhoneValidator do
let(:valid_phone) { '202-555-0198' }
let(:integer_phone) { 8_765_3210 }
let(:invalid_number) { '666666666666666' }
describe '#validate' do
it 'raises no error if the phone number and country are valid' do
expect(described_class.validate(valid_phone, 'US')).to be_nil
end
it 'raises an error if phone_number is not the right type' do
expect{
described_class.validate(integer_phone, "US")
}.to raise_error(TextBelt::Errors::IntegerPhoneError)
end
it 'raises an error if phone_number is not parseable' do
expect{
described_class.validate(invalid_number, "US")
}.to raise_error(TextBelt::Errors::InvalidPhoneNumberError)
end
end
end
|
require 'spec_helper'
describe LogsController do
shared_examples 'an irc scoped action' do
it do
assigns(:network).should == 'freenode'
end
it do
assigns(:channel).should == 'ruby'
end
end
before do
FactoryGirl.create(:log)
end
describe 'GET :index' do
before do
get :index, :network => 'freenode', :channel => 'ruby'
end
it_behaves_like 'an irc scoped action'
it { should respond_with(:success) }
it { assigns(:logs).should_not be_nil }
end
describe 'GET :index with search param' do
before do
Log.should_receive(:search_text).with('term').and_return(Log)
get :index, :network => 'freenode', :channel => 'ruby', :search => 'term'
end
it_behaves_like 'an irc scoped action'
it { should respond_with(:success) }
it { assigns(:logs).should_not be_nil }
end
describe 'GET :index .rss' do
before do
get :index, :network => 'freenode', :channel => 'ruby', :format => :rss
end
it_behaves_like 'an irc scoped action'
it { should respond_with(:success) }
it { assigns(:logs).should_not be_nil }
end
describe 'POST :create' do
before do
post :create, :network => 'freenode', :channel => 'ruby',
:log => { :sender => 'nick', :line => 'What is ruby 1.9.2?' }
end
it_behaves_like 'an irc scoped action'
it { should respond_with(:success) }
it do
assigns(:log).should be_valid
assigns(:log).should be_persisted
end
end
describe 'GET :random .txt' do
before do
log = FactoryGirl.build_stubbed(:log)
Log.should_receive(:random).and_return(log)
get :random, :network => 'freenode', :channel => 'ruby', :format => :txt
end
it_behaves_like 'an irc scoped action'
it { should respond_with(:success) }
it { assigns(:log).should_not be_nil }
end
describe 'GET :search .txt' do
before do
FactoryGirl.create(:log, :line => 'search me')
get :search, :network => 'freenode', :channel => 'ruby', :format => :txt,
:term => 'search me'
end
it_behaves_like 'an irc scoped action'
it { should respond_with(:success) }
it { assigns(:log).should_not be_nil }
end
describe 'GET :previous .txt' do
before do
log = FactoryGirl.build_stubbed(:log)
Log.should_receive(:previous).with(3).and_return(log)
get :previous, :network => 'freenode', :channel => 'ruby', :format => :txt,
:offset => "3"
end
it_behaves_like 'an irc scoped action'
it { should respond_with(:success) }
it { assigns(:log).should_not be_nil }
end
end
|
class Item < ApplicationRecord
has_many :user_items, dependent: :destroy
has_many :users, through: :user_items
has_many :ratings, dependent: :destroy
belongs_to :category
validates :name, presence: true, uniqueness: true
validates :price, presence: true
validates :category_id, presence: true
def self.search(search)
where("name LIKE ?", "%#{search}%")
end
end
|
# CREATING A NEW HASH
pedro_teacher = {
"name" => "Pedro",
"age" => 27,
"parents" => ["Dad", "Mom"]
}
# READ
pedro_teacher["name"] # "Pedro"
pedro_teacher["age"] # 27
pedro_teacher["parents"] # ["Dad", "Mom"]
pedro_teacher["parents"][1] # "Mom"
# UPDATE
pedro_teacher["name"] = "Pedro Miranda"
pedro_teacher["parents"][1] = "Super Mom"
# CREATE A NEW KEY-VALUE PAIR
pedro_teacher["single"] = false
# DELETING A KEY-VALUE PAIR
pedro_teacher.delete("name")
# You can have complex hashes
lw_teachers = {
"matheus" => {
"name" => "Matheus",
"age" => 31,
"parents" => ["Martenick", "Leila"]
},
"pedro" => pedro_teacher
}
# READ the value by the key
lw_teachers["matheus"]["name"] # "Matheus"
lw_teachers["matheus"]["age"] # "Matheus"
lw_teachers["matheus"]["parents"][0] # "Martenick" |
def roll_call_dwarves(names)
names.each_with_index {|name, index| puts "#{index + 1}. #{name}"}
end
def summon_captain_planet(elements)
elements.collect {|element| element.capitalize + "!"}
end
def long_planeteer_calls(calls)
calls.any? {|call| call.length > 4}
end
def find_the_cheese(food)
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
food.find {|cheese| cheese_types.include?(cheese)}
end
|
require 'test_helper'
class GroupTest < ActiveSupport::TestCase
def setup
@group = Group.create(name: "Example group")
end
test "associated users should be destroyed" do
@group.save
@group.users.create!(email: "example@test.com",
password: "password",
password_confirmation: "password")
assert_difference 'Group.count', -1 do
@group.destroy
end
end
end
|
class AddShowColumnToCategorization < ActiveRecord::Migration
def change
add_column('categorizations', 'show', 'boolean')
end
end
|
class Madlib
def initialize
@noun = nil
@verb = nil
@adjective = nil
@adverb = nil
end
def noun(noun_word)
@noun = noun_word
end
def verb(verb_word)
@verb = verb_word
end
def adjective(adjective_word)
@adjective = adjective_word
end
def adverb(adverb_word)
@adverb = adverb_word
end
def result
"Do you #{@verb} your #{@adjective} #{@noun} #{@adverb}? That's hilarious!"
end
end
|
class Pair
def initialize(l, r)
@left = l
@right = r
end
def left
return @left
end
def left=(s)
@left = s
end
def right
return @right
end
def right=(s)
@right = s
end
end |
require 'rails_helper'
RSpec.feature "user edits a book" do
let(:user) { create(:user) }
let(:book) { create(:book) }
before do
sign_in(user.email, user.password)
visit "/books/#{book.id}"
click_link "Edit book"
expect(page).to have_current_path("/books/#{book.id}/edit")
expect(page).to have_content("Edit The Great Gatsby")
end
scenario "successfully" do
fill_in "Title", with: "The Great Catsby"
fill_in "Author", with: "F Scoop Whiskgerald"
fill_in "Year of release", with: "2004"
fill_in "Number of pages", with: "120"
fill_in "Description", with: "A cat tragedy"
click_button "Save"
expect(page).to have_current_path("/books/#{book.id}")
expect(page).to have_content("Book was successfully updated")
expect(page).to have_content("The Great Catsby")
expect(page).to_not have_content("The Great Gatsby")
expect(page).to have_content("F Scoop Whiskgerald")
end
scenario "unsuccessfully" do
fill_in "Title", with: ""
fill_in "Author", with: "F Scoop Whiskgerald"
fill_in "Year of release", with: "2004"
fill_in "Number of pages", with: "120"
fill_in "Description", with: "A cat tragedy"
click_button "Save"
expect(page).to have_current_path("/books/#{book.id}")
expect(page).to have_content("Book was not saved")
expect(page).to have_content("Title can't be blank")
end
end
|
require "rails_helper"
describe "Ring Group Call Query API", :graphql do
describe "ringGroupCall" do
let(:query) do
<<-'GRAPHQL'
query($id: ID!) {
ringGroupCall(id: $id) {
id
}
}
GRAPHQL
end
it "gets the specified ring group call" do
user = create(:user)
ring_group = create(:ring_group, users: [user])
call = create(:ring_group_call, ring_group: ring_group)
result = execute query, as: user, variables: {
id: call.id,
}
returned_call = result[:data][:ringGroupCall]
expect(returned_call[:id]).to eql(call.id.to_s)
end
end
describe "ringGroupCall voicemail" do
let(:query) do
<<-'GRAPHQL'
query($id: ID!) {
ringGroupCall(id: $id) {
id
voicemail {
id
url
}
}
}
GRAPHQL
end
it "gets the calls voicemail" do
user = create(:user)
ring_group = create(:ring_group, users: [user])
call = create(:ring_group_call, ring_group: ring_group)
voicemail = create(:voicemail, voicemailable: call)
result = execute query, as: user, variables: {
id: call.id,
}
voicemail_result = result[:data][:ringGroupCall][:voicemail]
expect(voicemail_result[:id]).to eql(voicemail.id.to_s)
expect(voicemail_result[:url]).not_to be(nil)
end
end
describe "ringGroupCall answeredCall" do
let(:query) do
<<-'GRAPHQL'
query($id: ID!) {
ringGroupCall(id: $id) {
id
answeredCall {
id
}
}
}
GRAPHQL
end
it "gets the answered call that resulted from the ring group call" do
user = create(:user)
ring_group = create(:ring_group, users: [user])
ring_group_call = create(:ring_group_call, ring_group: ring_group)
answered_call = create(:incoming_call, :completed, ring_group_call: ring_group_call)
result = execute query, as: user, variables: {
id: ring_group_call.id,
}
answered_call_result = result[:data][:ringGroupCall][:answeredCall]
expect(answered_call_result[:id]).to eql(answered_call.id.to_s)
end
end
end
|
class Gallery < ActiveRecord::Base
has_many :gallery_resources, :dependent => :destroy
belongs_to :event
accepts_nested_attributes_for :gallery_resources,
:allow_destroy => true,
:reject_if => lambda { |a| a['resource'].nil? }
end
|
json.galleries do
@galleries.each do |gallery|
json.set! gallery.id do
json.partial! "api/gallery/gallery", gallery: gallery
end
end
end
|
#!/usr/bin/env ruby
#
# Created on 2013-09-26.
# Copyright (c) 2013. All rights reserved.
# create a script to bootstrap a rails project
#
begin
require 'rubygems'
rescue LoadError
# no rubygems to load, so we fail silently
end
require 'optparse'
require 'open3'
OPTIONS = {
:app_name => nil,
:ruby_verison => nil
}
MANDATORY_OPTIONS = %w( )
parser = OptionParser.new do |opts|
opts.banner = <<BANNER
Usage: #{File.basename($0)} [options] <projectname>
Options are:
BANNER
opts.separator ""
opts.on("-a", "--app=name", String, "Application Name"){|v| OPTIONS[:app_name] = v.gsub('=', '')}
opts.on("-r", "--ruby=version", String, "Ruby Version"){|v| OPTIONS[:ruby_verison] = v.gsub('=', '')}
opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
opts.parse!(ARGV)
if MANDATORY_OPTIONS && MANDATORY_OPTIONS.find { |option| OPTIONS[option.to_sym].nil? }
puts opts; exit
end
end
def prompt_appname
puts "Application Name: "
system "stty -echo"
OPTIONS[:app_name] = $stdin.gets.chomp
system "stty echo"
end
prompt_appname unless OPTIONS[:app_name]
def prompt_ruby
puts "Ruby Version: "
system "stty -echo"
OPTIONS[:ruby_verison] = $stdin.gets.chomp
system "stty echo"
end
prompt_ruby unless OPTIONS[:ruby_verison]
###########################################################
# 1. create project dir
app_dir = "#{OPTIONS[:app_name]}-devops"
`mkdir #{app_dir}`
###########################################################
# 2. create rvm config
# .ruby-version
# .ruby-gemset
`touch #{app_dir}/.ruby-version`
`echo ruby-#{OPTIONS[:ruby_verison]} >> #{app_dir}/.ruby-version`
`touch #{app_dir}/.ruby-gemset`
`echo #{OPTIONS[:app_name]} >> #{app_dir}/.ruby-gemset`
###########################################################
# # 3. create Gemfile
# `touch #{app_dir}/Gemfile`
# `echo "source 'https://rubygems.org'\n" >> #{app_dir}/Gemfile`
# `echo "ruby '#{OPTIONS[:ruby_verison]}'\n" >> #{app_dir}/Gemfile`
|
class Artist < ApplicationRecord
belongs_to :passport_country, class_name: 'Country', foreign_key: 'passport_country_id', optional: true
belongs_to :company, optional: true
belongs_to :tax, optional: true
belongs_to :superannuation, optional: true
belongs_to :bank_account, optional: true
belongs_to :member
has_many :artist_city
has_many :city, through: :artist_city
has_many :artist_medium
has_many :medium, through: :artist_medium
has_many :profile
#validation
validates_presence_of(:dob, :member)
end
|
require 'binary_struct'
module Ext3
# ////////////////////////////////////////////////////////////////////////////
# // Data definitions.
DIR_ENTRY_ORIGINAL = BinaryStruct.new([
'L', 'inode_val', # Inode address of metadata.
'S', 'entry_len', # Length of entry.
'S', 'name_len', # Length of name.
])
# Here follows the name in ASCII.
SIZEOF_DIR_ENTRY_ORIGINAL = DIR_ENTRY_ORIGINAL.size
DIR_ENTRY_NEW = BinaryStruct.new([
'L', 'inode_val', # Inode address of metadata.
'S', 'entry_len', # Length of entry.
'C', 'name_len', # Length of name.
'C', 'file_type', # Type of file (see FT_ below).
])
# Here follows the name in ASCII.
SIZEOF_DIR_ENTRY_NEW = DIR_ENTRY_NEW.size
class DirectoryEntry
FT_UNKNOWN = 0
FT_FILE = 1
FT_DIRECTORY = 2
FT_CHAR = 3
FT_BLOCK = 4
FT_FIFO = 5
FT_SOCKET = 6
FT_SYM_LNK = 7
attr_reader :inode, :len, :name
attr_accessor :fileType
def initialize(data, new_entry = true)
raise "Ext3::DirectoryEntry.initialize: Nil directory entry data" if data.nil?
@isNew = new_entry
# Both entries are same size.
siz = SIZEOF_DIR_ENTRY_NEW
@de = @isNew ? DIR_ENTRY_NEW.decode(data[0..siz]) : DIR_ENTRY_ORIGINAL.decode(data[0..siz])
# If there's a name get it.
@name = data[siz, @de['name_len']] if @de['name_len'] != 0
@inode = @de['inode_val']
@len = @de['entry_len']
@fileType = @de['file_type'] if @isNew
end
def isDir?
@fileType == FT_DIRECTORY
end
def isSymLink?
@fileType == FT_SYM_LNK
end
def dump
out = "\#<#{self.class}:0x#{'%08x' % object_id}>\n"
out += "Inode : #{inode}\n"
out += "Len : #{len}\n"
out += "Name len: 0x#{'%04x' % @de['name_len']}\n"
out += "Type : #{fileType}\n" if @isNew
out += "Name : #{name}\n"
end
end # class
end # module
|
class CreateTargetHealthAttributeRatings < ActiveRecord::Migration[5.2]
def change
create_table :target_health_attribute_ratings do |t|
t.string :rating, foreign_key: true, null: true
t.references :target, foreign_key: true
t.references :health_attribute, foreign_key: true
end
end
end
|
# ext/moment/extconf.rb
ENV['RC_ARCHS'] = '' if RUBY_PLATFORM =~ /darwin/
require 'mkmf'
require 'date'
extension_name = 'moment'
LIBDIR = RbConfig::CONFIG['libdir']
INCLUDEDIR = RbConfig::CONFIG['includedir']
# HEADER_DIRS = [INCLUDEDIR]
# setup constant that is equal to that of the file path that holds that static libraries that will need to be compiled against
# LIB_DIRS = [LIBDIR, File.expand_path(File.join(File.dirname(__FILE__), "lib"))]
# LIBDIR = RbConfig::CONFIG['libdir']
# INCLUDEDIR = RbConfig::CONFIG['includedir']
# # LIB_DIRS = [LIBDIR, File.expand_path(File.join(File.dirname(__FILE__), "lib"))]
HEADER_DIRS = [
# First search /opt/local for macports
'/opt/local/include',
# Then search /usr/local for people that installed from source
'/usr/local/include',
# Check the ruby install locations
INCLUDEDIR,
# Finally fall back to /usr
'/usr/include',
]
LIB_DIRS = [
# First search /opt/local for macports
'/opt/local/lib',
# Then search /usr/local for people that installed from source
'/usr/local/lib',
# Check the ruby install locations
LIBDIR,
File.expand_path(File.join(File.dirname(__FILE__), "lib")),
# Finally fall back to /usr
'/usr/lib',
]
libs = ['-lmoment']
dir_config("moment", HEADER_DIRS, LIB_DIRS)
unless find_header('TimeParser.h')
abort "TimeParser is missing. please install TimeParser"
end
# iterate though the libs array, and append them to the $LOCAL_LIBS array used for the makefile creation
libs.each do |lib|
$LOCAL_LIBS << "#{lib} "
end
create_makefile("moment/moment")
|
require 'rubygems'
require 'spork'
#uncomment the following line to use spork with the debugger
#require 'spork/ext/ruby-debug'
Spork.prefork do
# Loading more in this block will cause your tests to run faster. However,
# if you change any configuration or code from libraries loaded here, you'll
# need to restart spork for it take effect.
$LOAD_PATH << "test"
ENV["RAILS_ENV"] = "test"
Rails.env = 'test'
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require "minitest/rails"
require "turn/autorun"
require "factory_girl_rails"
require "webmock/minitest"
#Turn.config.format = :progress
class ActiveSupport::TestCase
# Add more helper methods to be used by all tests here...
def setup
raise("Rails.env == #{Rails.env}, i.e. Spork is a piece of shit") unless Rails.env == 'test'
# Delete all test Redis keys before each test
keys = Redis.current.keys
Redis.current.del(keys) if keys.present?
set_up_robot
stub_request(:any, Rails.configuration.app['faye']['url'])
stub_request(:any, /#{Rails.configuration.app['moderator']['url']}/)
#stub_request(:any, /#{Rails.configuration.app['elasticsearch']['url']}/)
stub_request(:any, /mixpanel.com/)
stub_request(:any, /facebook.com/)
stub_request(:any, /amazonaws.com/)
FactoryGirl.create(:snap_invite_ad)
end
def set_up_robot
Robot.instance_variable_set(:@user, nil)
robot = User.create!(gender: 'male', created_at: 10.years.ago)
FactoryGirl.create(:account, registered: true, user_id: robot.id, created_at: 10.years.ago)
User.where(id: robot.id).update_all(username: Robot.username)
end
def result
@result ||= JSON.load(response.body)
end
def current_user
@current_user ||= FactoryGirl.create(:registered_user)
end
def hash_must_include(actual, expected)
(expected.to_a - actual.to_a).must_be_empty
end
def result_must_include(object_type, object_id, expected)
actual = result.detect{ |obj| obj['object_type'] == object_type && obj['id'] == object_id }
hash_must_include actual, expected
end
def result_wont_include(object_type, object_id)
actual = result.detect{ |obj| obj['object_type'] == object_type && obj['id'] == object_id }
actual.must_be_nil
end
end
end
Spork.each_run do
# This code will be run each time you run your specs.
end
|
class UsersController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource
def index
@users = User.includes(:users_roles, :roles).order(:full_name).paginate(:page => params[:page])
end
def show
@user = User.find(params[:id])
@roles = @user.roles
end
end |
class CreateFunnels < ActiveRecord::Migration
def change
create_table :funnels do |t|
t.string :name
t.references :app
t.timestamps
end
create_table :events_funnels do |t|
t.references :event
t.references :funnel
t.timestamps
end
add_index :funnels, :app_id
add_index :events_funnels, [:event_id, :funnel_id]
end
end
|
my_hash = {fib: "bib",llama: "drama",contortion: "Jortion", slimy: "limey"}
#I can use the .fetch method, I think:
puts my_hash.fetch(:fib)
#I was correct. It will return an error if I give it a wrong key, unless I give it a default.
puts my_hash.fetch(:pounce,"bounced.")
#puts my_hash.fetch(:pounce)
#The example used a different method, .has_value?
#It is a more appropriate method for testing "if" it has the value.
if my_hash.has_value?(:pounce)
puts "yup"
else
puts "nope"
end |
class CryptoWizard::CLI
def call
puts "Welcome to the Cryptocurrency Wizard!"
list_currencies
menu
end
def list_currencies
@listings = CryptoWizard::Listings.listing
@listings.each.with_index(1) do |coin, i|
puts "#{i}. NAME: #{coin.name} - PRICE: $#{coin.price} - MARKET CAP: $#{coin.market_cap} - SUPPLY: #{coin.supply}"
end
end
def menu
input = nil
while input != 'exit'
puts "please the # cryptocurrency that you would like to see, list to be shown listings, or exit to exit"
input = gets.strip.downcase
if input.to_i > 0
puts @listings[input.to_i - 1].name
puts "PRICE($):"
puts @listings[input.to_i - 1].price
puts "SUPPLY:"
puts @listings[input.to_i - 1].supply
puts "MARKET CAP($):"
puts @listings[input.to_i - 1].market_cap
elsif input == "list"
list_currencies
elsif input == "exit"
goodbye
else
puts "not sure what you mean, enter list for listings, or exit to exit"
end
end
end
def goodbye
puts "Have a good day"
end
end
# if input.to_i > 0
# the_coin = @listings[input.to_i - 1]
# puts "#{the_coin.name} - #{the_coin.price} - #{the_coin.mc} - #{the_coin.url}"
# puts @prices[input.to_i - 1]
# elsif input == 'list'
# list_currencies
# else
# puts "not sure what you're looking for, enter list or exit."
# end
# end
# end
|
require_relative 'node'
class BinaryHeap
attr_reader :root
def initialize(root)
@root = root
end
def insert(root, node)
if node.rating < @root.rating
hold = root
@root = node
node = hold
insert(@root, node)
elsif node.rating < root.rating
hold = root
root = node
node = hold
insert(root, node)
else
if root.left.nil?
@root.left = root
root.left = node
elsif root.right.nil?
# && root.left != nil might need this again
# @root.right = root this breaks the root.left.right. insert
root.right = node
elsif root.left != nil && root.right != nil && root.left.left != nil && root.left.right != nil
# root.right = root (this creates an infinite loop)
insert(root.right, node)
elsif root.left != nil && root.right !=nil
insert(root.left, node)
end
end
end
# Recursive Depth First Search
def find(root, data)
return nil if data.nil? || root.nil?
return root if root.title == data
right = find(root.right, data)
left = find(root.left, data)
return right if right != nil
return left if left != nil
return nil if right.nil? && left.nil?
end
def delete(root, data)
return nil if data.nil?
dead_node = find(root, data)
dead_node.nil? ? nil : dead_node.title = nil
end
# Recursive Breadth First Search
def printf(children=nil)
start = [@root]
finish = []
while start.length > 0
rootx = start.shift
start << rootx.left if rootx.left != nil
start << rootx.right if rootx.right != nil
finish << ("#{rootx.title}: #{rootx.rating}")
end
finish.each { |movie| puts movie }
end
end
|
# List of Digits
# Input
# - positive integer
# Output
# - returns a list (array maybe) of the digits in the number
# Test Cases
# puts digit_list(12345) == [1, 2, 3, 4, 5] # => true
# puts digit_list(7) == [7] # => true
# puts digit_list(375290) == [3, 7, 5, 2, 9, 0] # => true
# puts digit_list(444) == [4, 4, 4] # => true
# Data structures
# Input
# - Integer
# Output
# - Array of numbers
# Algorithm
# - turn the input into a string
# - split the string
# - turn the string back into an int then save it in an array
def digit_list(num)
num.to_s.split(//).map(&:to_i)
end
puts digit_list(12_345) == [1, 2, 3, 4, 5] # => true
puts digit_list(7) == [7] # => true
puts digit_list(375_290) == [3, 7, 5, 2, 9, 0] # => true
puts digit_list(444) == [4, 4, 4] # => true
|
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "seb_elink/version"
Gem::Specification.new do |gem|
gem.name = "seb_elink"
gem.required_ruby_version = '>= 2'
gem.date = "2017-12-14"
gem.version = SebElink::VERSION
gem.authors = ["Epigene"]
gem.email = ["cto@creative.gs", "augusts.bautra@gmail.com"]
gem.summary = "Ruby wrapper for communicating with SEB.lv i-bank payment API."
gem.homepage = "https://github.com/CreativeGS/seb_elink"
gem.license = "BSD-3-Clause"
gem.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
gem.bindir = "exe"
gem.executables = gem.files.grep(%r{^exe/}) { |f| File.basename(f) }
gem.require_paths = ["lib"]
gem.add_development_dependency "bundler", "~> 1.16"
gem.add_development_dependency "rake", "~> 10.0"
gem.add_development_dependency "rspec", "~> 3.7"
gem.add_development_dependency "pry", "~> 0.11.3"
gem.add_development_dependency "simplecov", "~> 0.15.1"
gem.add_development_dependency "coveralls"
end
|
# typed: false
# frozen_string_literal: true
# This file was generated by GoReleaser. DO NOT EDIT.
class Tfstore < Formula
desc "Login to the AWS management console."
homepage "https://github.com/youyo/tfstore"
version "0.0.5"
on_macos do
if Hardware::CPU.arm?
url "https://github.com/youyo/tfstore/releases/download/v0.0.5/tfstore_0.0.5_Darwin_arm64.tar.gz"
sha256 "95262bade7c363aa7deaa75665dbf73b0293869235a95ba11e5b175840973e2e"
def install
bin.install "tfstore"
zsh_completion.install '_tfstore'
end
end
if Hardware::CPU.intel?
url "https://github.com/youyo/tfstore/releases/download/v0.0.5/tfstore_0.0.5_Darwin_x86_64.tar.gz"
sha256 "68b6eb0de40153f342c6d238d9c2496da047e64ed6e1beb2a5b499360ac776a7"
def install
bin.install "tfstore"
zsh_completion.install '_tfstore'
end
end
end
on_linux do
if Hardware::CPU.arm? && Hardware::CPU.is_64_bit?
url "https://github.com/youyo/tfstore/releases/download/v0.0.5/tfstore_0.0.5_Linux_arm64.tar.gz"
sha256 "9d292bf53d5214fa5d6cb4ca957c100d2a3d2f3516214d13902e122b1c7f27d1"
def install
bin.install "tfstore"
zsh_completion.install '_tfstore'
end
end
if Hardware::CPU.intel?
url "https://github.com/youyo/tfstore/releases/download/v0.0.5/tfstore_0.0.5_Linux_x86_64.tar.gz"
sha256 "616113dcaae165fe67a579e7e5448cb3e02fb3049f3b8337dc78fa246be7a411"
def install
bin.install "tfstore"
zsh_completion.install '_tfstore'
end
end
end
test do
system "#{bin}/tfstore --version"
end
end
|
##
# Helper mixin for tests (especially compute-based ones). Provide access to the
# client in use via the #client method to use.
module ClientHelper
# Check to see if an compute operation is finished.
#
# @param op [Google::Apis::ComputeV1::Operation] the operation object returned from an api call
# @return [Bolean] true if the operation is no longer executing, false
# otherwise
def operation_finished?(op)
region = op.region
zone = op.zone
name = op.name
if zone.nil?
result = client.get_region_operation(region, name)
else
result = client.get_zone_operation(zone, name)
end
!%w(PENDING RUNNING).include?(result.status)
end
# Check to see if an SQL operation is finished.
#
# @param op [Google::Apis::SqladminV1beta4::Operation] the operation object
# returned from an SQL Admin api call
# @return [Boolean] true if the operation is no longer executing, false
# otherwise
def sql_operation_finished?(op)
result = client.get_operation(op.name)
!%w(PENDING RUNNING).include?(result.status)
end
# Pause execution until an operation (compute or sql) returned
# from a passed block is finished.
#
# @example Pause until server is provisioned
# @result = wait_until_complete { client.insert_server(name, zone, opts) }
# @yieldreturn The resulting operation object from a block.
# @return the result of the operation
def wait_until_complete
result = yield
case result.kind
when "compute#operation"
region = result.region
zone = result.zone
Fog.wait_for { operation_finished?(result) }
if zone.nil?
client.get_region_operation(region, result.name)
else
client.get_zone_operation(zone, result.name)
end
when "sql#operation"
Fog.wait_for { sql_operation_finished?(result) }
client.get_operation(result.name)
else
result
end
end
end
|
class InvestigationinjurylocationsController < ApplicationController
before_action :set_investigationinjurylocation, only: [:show, :edit, :update, :destroy]
# GET /investigationinjurylocations
# GET /investigationinjurylocations.json
def index
@investigationinjurylocations = Investigationinjurylocation.all
end
# GET /investigationinjurylocations/1
# GET /investigationinjurylocations/1.json
def show
end
# GET /investigationinjurylocations/new
def new
@investigationinjurylocation = Investigationinjurylocation.new
end
# GET /investigationinjurylocations/1/edit
def edit
end
# POST /investigationinjurylocations
# POST /investigationinjurylocations.json
def create
@investigationinjurylocation = Investigationinjurylocation.new(investigationinjurylocation_params)
respond_to do |format|
if @investigationinjurylocation.save
format.html { redirect_to @investigationinjurylocation.investigation, notice: 'Investigationinjurylocation was successfully created.' }
format.json { render :show, status: :created, location: @investigationinjurylocation }
else
format.html { render :new }
format.json { render json: @investigationinjurylocation.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /investigationinjurylocations/1
# PATCH/PUT /investigationinjurylocations/1.json
def update
respond_to do |format|
if @investigationinjurylocation.update(investigationinjurylocation_params)
format.html { redirect_to @investigationinjurylocation.investigation, notice: 'Investigationinjurylocation was successfully updated.' }
format.json { render :show, status: :ok, location: @investigationinjurylocation }
else
format.html { render :edit }
format.json { render json: @investigationinjurylocation.errors, status: :unprocessable_entity }
end
end
end
# DELETE /investigationinjurylocations/1
# DELETE /investigationinjurylocations/1.json
def destroy
@investigationinjurylocation.destroy
respond_to do |format|
format.html { redirect_to investigationinjurylocations_url, notice: 'Investigationinjurylocation was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_investigationinjurylocation
@investigationinjurylocation = Investigationinjurylocation.find(params[:id])
end
# Only allow a list of trusted parameters through.
def investigationinjurylocation_params
params.require(:investigationinjurylocation).permit(:investigation_id, :injurylocation_id)
end
end
|
# Your code goes here!
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
def match (dictionary_array)
dictionary_array.select do |array|
array.chars.sort == word.chars.sort
end
end
#split word into array
#get size of the word
#iterate through dictionary for each letter of word array
#get
end
|
class Post < ApplicationRecord
belongs_to :author
has_attached_file :image, styles: { small: "100x100", med: "200x200", large: "400x400" }
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
validates :title, :presence => true,
:length => { :minimum => 5, :maximum => 40}
validates :introduction, :presence => true,
:length => { :minimum => 5}
validates :body, :presence => true,
:length => { :minimum => 5}
end
|
require 'rails_helper'
RSpec.describe Admin::PapersController, type: :controller do
shared_examples "do not search" do
it "has same @papers as papers" do
papers = [paper1, paper2, paper3]
get :index, params: params
expect(assigns(:papers)).to match_array papers
end
end
describe "search ability in #index" do
let(:admin) { FactoryGirl.create(:user, :admin) }
let(:activity) { FactoryGirl.create(:activity_with_custom_field) }
let(:params) {
{
activity_id: activity.permalink,
commit: commit,
search_field: search_field,
search_type: search_type,
search_key: search_key,
}
}
let(:search_field) { }
let(:search_type) { }
let(:search_key) { }
let!(:paper1) { FactoryGirl.create(:paper, activity: activity) }
let!(:paper2) { FactoryGirl.create(:paper, activity: activity) }
let!(:paper3) { FactoryGirl.create(:paper, activity: activity) }
before do
sign_in admin
end
context "Commit is not 'Search'" do
let(:commit) { "Clear Search" }
it_behaves_like "do not search"
end
context "Commit is 'Search'" do
let(:commit) { "Search" }
context "when search_field is not one of the fixed key or the custom fields" do
let(:search_field) { "__NOT_EXIST__" }
it_behaves_like "do not search"
end
context "with 'equal'" do
let(:search_type) { "equal" }
context "when search on fixed fields" do
let(:bio_1) { Faker::Lorem.sentence(11) }
let(:bio_2) { bio_1 + "__DIFFERENT__" }
let!(:paper1) { FactoryGirl.create(:paper, activity: activity, speaker_bio: bio_1) }
let!(:paper2) { FactoryGirl.create(:paper, activity: activity, speaker_bio: bio_1) }
let!(:paper3) { FactoryGirl.create(:paper, activity: activity, speaker_bio: bio_2) }
let(:search_field) { "speaker_bio" }
let(:search_key) { bio_1 }
it "returns matched results" do
valid_papers = [paper1, paper2]
get :index, params: params
expect(assigns(:papers)).to match_array valid_papers
end
end
context "when search on custom fields" do
let(:custom_1) { {"#{activity.custom_fields[0].id}"=>"Talk(30 mins)"} }
let(:custom_2) { {"#{activity.custom_fields[0].id}"=>"Session(55 mins)"} }
let!(:paper1) { FactoryGirl.create(:paper, activity: activity, answer_of_custom_fields: custom_1) }
let!(:paper2) { FactoryGirl.create(:paper, activity: activity, answer_of_custom_fields: custom_1) }
let!(:paper3) { FactoryGirl.create(:paper, activity: activity, answer_of_custom_fields: custom_2) }
let(:search_field) { activity.custom_fields[0].name }
let(:search_key) { "Talk(30 mins)" }
it "returns matched results" do
valid_papers = [paper1, paper2]
get :index, params: params
expect(assigns(:papers)).to match_array valid_papers
end
end
end
context "with 'like'" do
let(:search_type) { "like" }
context "when search on fixed fields" do
let(:bio_1) { "#{Faker::Lorem.sentence(10)} UNIQUE_SEARCH_KEY #{Faker::Lorem.sentence(10)}" }
let(:bio_2) { "#{Faker::Lorem.sentence(10)} OTEHR #{Faker::Lorem.sentence(10)}" }
let!(:paper1) { FactoryGirl.create(:paper, activity: activity, speaker_bio: bio_1) }
let!(:paper2) { FactoryGirl.create(:paper, activity: activity, speaker_bio: bio_1) }
let!(:paper3) { FactoryGirl.create(:paper, activity: activity, speaker_bio: bio_2) }
let(:search_field) { "speaker_bio" }
let(:search_key) { "UNIQUE_SEARCH_KEY" }
it "returns matched results" do
valid_papers = [paper1, paper2]
get :index, params: params
expect(assigns(:papers)).to match_array valid_papers
end
end
context "when search on custom fields" do
let(:custom_1) { {"#{activity.custom_fields[0].id}"=>"#{Faker::Lorem.sentence(10)} UNIQUE_SEARCH_KEY #{Faker::Lorem.sentence(10)}"} }
let(:custom_2) { {"#{activity.custom_fields[0].id}"=>"#{Faker::Lorem.sentence(10)} OTEHR #{Faker::Lorem.sentence(10)}"} }
let!(:paper1) { FactoryGirl.create(:paper, activity: activity, answer_of_custom_fields: custom_1) }
let!(:paper2) { FactoryGirl.create(:paper, activity: activity, answer_of_custom_fields: custom_1) }
let!(:paper3) { FactoryGirl.create(:paper, activity: activity, answer_of_custom_fields: custom_2) }
let(:search_field) { activity.custom_fields[0].name }
let(:search_key) { "UNIQUE_SEARCH_KEY" }
it "returns matched results" do
valid_papers = [paper1, paper2]
get :index, params: params
expect(assigns(:papers)).to match_array valid_papers
end
end
end
end
end
end
|
class PaymentInfo < ActiveRecord::Base
belongs_to :writer
belongs_to :guest_writer
enum card_type: [:visa,:mastercard]
enum payment_mode: [:debit_card,:credit_card,:netbanking]
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
after_action :store_location
def store_location
# store last url - this is needed for post-login redirect to whatever the user last visited.
return unless request.get?
if (request.path != "/sign_in" &&
request.path != "/sign_up" &&
request.path != "/password/new" &&
request.path != "/password/edit" &&
request.path != "/confirmation" &&
request.path != "/sign_out" &&
!request.xhr?) # don't store ajax calls
session[:previous_url] = request.fullpath
end
end
def after_sign_in_path_for(resource)
if session[:previous_url] == '/bookings/new_booking_and_signup'
'/bookings/confirm_details'
elsif current_lead.present?
session[:previous_url] || profile_bookings_path
elsif current_agent.present?
'/dashboard/overview' #TODO: redirect to agent portal
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) { |u|
u.permit(:email, :password, :first_name, :last_name, :phone_number, :birthday, [bookings_attributes: [:unit_type, :book_date, :agent_id]], :office_number, :mobile_number, :city)
}
devise_parameter_sanitizer.permit(:account_update) { |u|
u.permit(:avatar, :email, :phone_number, :birthday, :current_password, :password, [bookings_attributes: [:unit_type, :book_date, :agent_id]])
}
end
end
|
# This is the parent class from which all objects
# within the game inherit (such as tank, bullet, etc.)
#
# When GameObject is initialized, it registers itself with
# ObjectPool and prepares an empty array of @components.
#
# Update and draw simply cycle through @components and
# delegates those calls to each of them.
# * Note that update should happen before draw
#
class GameObject
def initialize(object_pool)
@components = []
@object_pool = object_pool
@object_pool.objects << self
end
def components
@components
end
def update
@components.map(&:update)
end
def draw(viewport)
@components.each { |c| c.draw(viewport) }
end
def removable?
@removable
end
def mark_for_removal
@removable = true
end
protected
def object_pool
@object_pool
end
end
|
class PhoneNumber
def initialize(number)
number = number.gsub(/\D/, '').to_s
if number.length == 10
@phone_number = number.prepend("1")
elsif number.length == 11
@phone_number = number
elsif number.length == 12 && number[0] == "+"
@phone_number = number[1..-1]
elsif number.length == 0
@phone_number = nil
else
raise Exception
end
end
def localized
@phone_number[1..-1]
end
def national
@phone_number
end
def e164
@phone_number.prepend("+")
end
end
|
# frozen_string_literal: true
require 'test_helper'
class Jekyll::Tags::IncludeSassTagTest < JekyllUnitTest
def test_that_it_has_a_version_number
refute_nil ::Jekyll::IncludeSass::VERSION
end
def test_it_does_something_useful
refute_nil ::Jekyll::Tags::IncludeSassTag
end
def test_include_sass
content = <<CONTENT
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
{% include_sass sass_file.sass %}
</style>
</head>
<body>
</body>
</html>
CONTENT
create_post(content, { "read_posts" => true })
assert_match "font: 100% Helvetica, sans-serif;", @result
end
def test_include_scss
content = <<CONTENT
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
{% include_sass scss_file.scss %}
</style>
</head>
<body>
</body>
</html>
CONTENT
create_post(content, { "read_posts" => true })
assert_match "font: 100% Helvetica, sans-serif;", @result
end
def create_post(content, override = {}, converter_class = Jekyll::Converters::Markdown)
site = fixture_site
info = { :filters => [Jekyll::Filters], :registers => { :site => site } }
@converter = site.converters.find { |c| c.class == converter_class }
payload = { "highlighter_prefix" => @converter.highlighter_prefix,
"highlighter_suffix" => @converter.highlighter_suffix }
@result = Liquid::Template.parse(content).render!(payload, info)
@result = @converter.convert(@result)
end
end
|
class MovieSearch
attr_reader :last_search, :search_input
attr_accessor :response_data
def initialize(last_search)
@last_search = last_search
@search_input = last_search.user_input
@response_data ||= cache_results
end
def cache_results
self.response_data = Rails.cache.fetch("api_search/#{search_input}") do
_api_response = RestClient.get("http://www.omdbapi.com/?t=#{search_input}&apikey=#{ENV.fetch('OMDB_API_KEY', nil)}")
{body: JSON.parse(_api_response.body), user_input: search_input}
end
end
end |
class CreateDynamicAnnotationFieldInstances < ActiveRecord::Migration[4.2]
def change
create_table :dynamic_annotation_field_instances, id: false do |t|
t.string :name, primary_key: true, null: false
t.string :field_type, foreign_key: true, null: false
t.string :annotation_type, foreign_key: true, null: false
t.string :label, null: false
t.text :description
t.boolean :optional, default: true
t.text :settings
t.string :default_value
t.timestamps null: false
end
end
end
|
require 'fastercsv'
class Report < ActiveRecord::Base
MAX_LIMIT = 65534 # Max number of results
serialize(:conditions)
belongs_to(:device)
belongs_to(:user)
STATE_QUEUED = 0
STATE_PROCESSING = 1
STATE_COMPLETE = 2
STATE_ERROR = 3
@@report_types = {
'all' => {:model => 'Reading', :table => 'readings', :label => 'Readings'},
'speeding' => {:model => 'Reading', :table => 'readings', :label => 'Speeding'},
'geofence' => {:model => 'Reading', :table => 'readings', :label => 'Geofence'},
'trip' => {:model => 'TripEvent', :table => 'trip_events', :label => 'Trips'},
'idle' => {:model => 'IdleEvent', :table => 'idle_events', :label => 'Idling'},
'stop' => {:model => 'StopEvent', :table => 'stop_events', :label => 'Stops'},
'runtime' => {:model => 'RuntimeEvent', :table => 'runtime_events', :label => 'Runtime'},
'gpio1' => {:model => 'Reading', :table => 'readings', :label => 'GPIO1'},
'gpio2' => {:model => 'Reading', :table => 'readings', :label => 'GPIO2'}
}
def self.enqueue(device_id, user_id, name, report_type, start_dt, end_dt)
if(@@report_types.has_key?(report_type))
@@report_types[report_type][:label]
else
raise("Invalid report type for export: #{report_type}.")
end
report = Report.new({:user_id => user_id, :device_id => device_id, :name => name, :report_type => report_type, :start_date => start_dt, :end_date => end_dt})
report.name = "device_#{report.device_id.to_s}_#{report.report_type_label.downcase}_#{start_dt.in_time_zone.strftime("%Y-%m-%d")}_to_#{end_dt.in_time_zone.strftime("%Y-%m-%d")}.csv"
report.record_count = report.compute_record_count()
report.save()
end
def report_type_label
if(@@report_types.has_key?(report_type))
case report_type
when 'gpio1' then
device.profile.gpio1_name or 'GPIO1'
when 'gpio2' then
device.profile.gpio2_name or 'GPIO2'
else
@@report_types[report_type][:label]
end
else
report_type
end
end
def state_label
case state
when STATE_QUEUED then
label = "Queued"
when STATE_PROCESSING then
percent_complete = ((records_processed.to_f / record_count.to_f) * 100).round
label = "Processing #{records_processed} of #{record_count} (#{percent_complete}%)"
when STATE_COMPLETE then
label = "Complete"
when STATE_ERROR then
label = "Error"
end
if(saved)
label += " (saved)"
end
label
end
def self.process_next(logger = nil)
if(logger.nil?)
logger = Logger.new(STDOUT)
end
report = Report.find(:first, :conditions => {:state => [STATE_QUEUED, STATE_PROCESSING]}, :order => "created_at ASC")
if(!report.nil?)
report.process(logger)
end
end
def compute_record_count
if(@@report_types.has_key?(report_type))
# pre-processing
pre_process()
# compute row count
eval(@@report_types[report_type][:model] + ".count(:all, :conditions => self.get_conditions())")
else
raise("Unknown report type: #{report_type} in compute_record_count")
end
end
def pre_process
case report_type
when 'trip' then
needy_events = TripEvent.find(:all, :conditions => ["device_id = ? AND created_at BETWEEN ? AND ? AND duration IS NOT NULL AND (distance IS NULL OR idle IS NULL)", self.device_id, start_date_str, end_date_str])
needy_events.each do |event|
event.update_stats
end
end
end
def records
# pre-processing
pre_process()
# load records
if(@@report_types.has_key?(report_type))
records = eval(@@report_types[report_type][:model] + ".find(:all, :order => \"created_at DESC\", :limit => MAX_LIMIT, :conditions => self.get_conditions())")
else
raise("Unknown report type: #{report_type} in process")
end
end
def process(logger = nil)
if(logger.nil?)
logger = Logger.new(STDOUT)
end
logger.info("Processing #{self.name}...")
records_processed = 0
update_attributes({:state => STATE_PROCESSING, :processed_at => Time.now, :records_processed => records_processed})
# generate csv
csv_string = FasterCSV.generate do |csv|
# add header
case report_type
when 'trip' then
csv << ['Start Address', 'Stop Address', 'Duration', 'Miles', 'Started']
when 'idle', 'stop', 'runtime' then
csv << ["Location", "#{report_type.capitalize} Duration (m)", "Started", "Latitude", "Longitude"]
else
csv << ["Location","Speed (mph)","Started","Latitude","Longitude","Event Type"]
end
# add data rows
records.each do |record|
row = []
case report_type
when 'trip' then
trip = record
row << trip.reading_start.short_address_with_rg
if trip.reading_stop
row << trip.reading_stop.short_address_with_rg
row << minutes_to_hours(trip.duration)
row << sprintf('%2.1f',trip.distance || 0.0)
else
row << '-'
start_time = trip.reading_start.created_at.to_i
end_time = Time.now.to_i
duration = (end_time-start_time)/60
row << "In progress: #{minutes_to_hours(duration)}"
row << '-'
end
row << displayLocalDT(trip.created_at)
when 'idle', 'stop', 'runtime' then
event = record
local_time = event.get_local_time(event.created_at.in_time_zone.inspect)
address = event.reading.nil? ? "#{event.latitude};#{event.longitude}" : event.reading.short_address_with_rg
row = [address,((event.duration.to_s.strip.size > 0) ? event.duration : 'Unknown'),local_time, event.latitude,event.longitude]
else
reading = record
local_time = reading.get_local_time(reading.created_at.in_time_zone.inspect)
row = [reading.short_address_with_rg,reading.speed,local_time,reading.latitude,reading.longitude,reading.event_type]
end
csv << row
records_processed += 1
update_attributes({:records_processed => records_processed})
logger.info("Processed #{records_processed} of #{record_count}.")
# check to see if report was deleted mid-processing
if(!Report.exists?(self.id))
logger.info("Report was deleted, aborting processing.")
break
end
end
end
# save to db
update_attributes({:state => STATE_COMPLETE, :data => csv_string, :completed_at => Time.now()})
logger.info("Completed processing of #{self.name}")
if(self.elapsed_time > REPORT_NOTIFY_THRESHOLD)
Notifier.deliver_notify_report(self)
end
end
def get_conditions()
case report_type
when 'all' then
return get_device_and_dates_conditions()
when 'speeding' then
return get_device_and_dates_conditions("AND speed > #{(device.account.max_speed or -1)}")
when 'geofence' then
return get_device_and_dates_conditions("AND geofence_id != 0")
when 'gpio1' then
return get_device_and_dates_conditions("AND gpio1 IS NOT NULL")
when 'gpio2' then
return get_device_and_dates_conditions("AND gpio2 IS NOT NULL")
when 'trip', 'idle', 'stop' then
return get_device_and_dates_with_duration_conditions()
when 'runtime' then
return get_device_and_dates_with_duration_conditions(false)
end
raise("Conditions not found for report type: \"#{report_type}\".")
end
def get_device_and_dates_conditions(optional_clause = nil, table_name = "")
if(!table_name.blank?)
table_name += "."
end
"#{table_name}device_id = #{self.device_id} AND #{table_name}created_at BETWEEN '#{start_date_str}' AND '#{end_date_str}' #{optional_clause}"
end
def get_device_and_dates_with_duration_conditions(possible_suspects = true)
if(Time.now < self.end_date)
return "device_id = #{self.device_id} AND ((created_at BETWEEN '#{start_date_str}' AND '#{end_date_str}') OR (duration IS NULL))#{suspect_clause(possible_suspects)}"
end
get_device_and_dates_conditions(suspect_clause(possible_suspects))
end
def suspect_clause(possible_suspects)
if(possible_suspects)
@suspect_clause ||= " AND (suspect = 0 OR suspect IS NULL)"
end
end
def elapsed_time
elapsed_time = self.completed_at - self.created_at
end
def displayLocalDT(timestamp)
timestamp.in_time_zone.strftime("%a %b %e %Y %l:%M:%S %p")
end
def minutes_to_hours(min)
if min < 60
(min % 60).to_s + " min"
else
hr = min / 60
hr.to_s + (hr == 1 ? " hr" : " hrs") + ", " + (min % 60).to_s + " min"
end
end
def start_date_str
start_date.utc.to_s(:db)
end
def end_date_str
end_date.utc.to_s(:db)
end
end
|
module SessionsHelper
def user_signed_in?
# Returns true if the user is logged in, false otherwise.
!current_user.nil?
end
end
|
require 'test/unit'
require_relative '../tree_tagger_config'
class TreeTaggerConfigTest < Test::Unit::TestCase
def test_tokenize_cmd
tagger = TextlabNLP::TreeTaggerConfig.new(config: { path: '/foo' }, lang: :fra)
assert_equal("/foo/cmd/utf8-tokenize.perl -a /foo/lib/french-abbreviations-utf8 -f", tagger.tokenize_cmd)
end
def test_prefered_encoding
config = TextlabNLP::TreeTaggerConfig.for_lang(:swe)
assert_equal("utf-8", config.prefered_encoding)
config = TextlabNLP::TreeTaggerConfig.for_lang(:fra)
assert_equal("utf-8", config.prefered_encoding)
config = TextlabNLP::TreeTaggerConfig.for_lang(:eng)
assert_equal("latin1", config.prefered_encoding)
end
end |
class CreateMobileMoneys < ActiveRecord::Migration
def up
create_table :mobile_moneys do |t|
t.string "uuid"
t.string "phone_number"
t.string "mno_name"
t.string "mno_transacation_ref"
t.string "mno_transacation_id"
t.string "status"
t.timestamps
end
end
def down
drop_table :mobile_moneys
end
end
|
class ImportsController < ApplicationController
def create
importer = GmailImporter.new(params[:email], params[:password])
importer.delay.import(50)
flash[:success] = "Importing your mail now"
redirect_to root_url
end
end
|
=begin
* Name: fletching.rb
* The fletching skill handler
* Author: Davidi2 (David Insley)
* Date: October 26, 2013
=end
require 'java'
java_import 'net.scapeemulator.game.task.Action'
java_import 'net.scapeemulator.game.model.player.interfaces.ComponentListenerAdapter'
java_import 'net.scapeemulator.game.msg.impl.ScriptMessage'
java_import 'net.scapeemulator.game.model.player.ScriptInputListener'
module Fletching
SPACER = '<br><br><br><br><br>'
class << self
def bind_handlers
RECIPES.each do |hash, recipes|
bind :item_on_item, :first => ItemOnItemDispatcher::reverse_hash(hash)[0], :second => ItemOnItemDispatcher::reverse_hash(hash)[1] do
Fletching::show_fletching_interface(player, recipes)
end
end
end
def show_fletching_interface(player, recipes)
id = recipes.size == 1 ? 309 : (301 + recipes.size)
for i in (0...recipes.size)
player.send InterfaceItemMessage.new(id, i + 2, 200, recipes.values[i].product_id)
string_index = 7 + (4 * i) + recipes.size - 2
item_name = Item.new(recipes.values[i].product_id).definition.name
player.set_interface_text(id, string_index, "<br><br><br><br><br>#{item_name}");
end
player.get_interface_set.open_chatbox id
listener = FletchingInterfaceListener.new
player.get_interface_set.get_chatbox.set_listener(listener)
listener.set_context(player, recipes)
end
end
class FletchingTask < Action
def initialize(player, recipe, amt)
super(player, recipe.delay, true)
@recipe = recipe
@amt = amt
@count = 0
end
def execute
if(!@cleared)
mob.get_walking_queue.reset
@cleared = true
end
if @recipe.check_reqs(mob)
@recipe.fletch(mob)
@count += 1
if @count >= @amt
mob.cancel_animation
stop
end
else
mob.cancel_animation
stop
end
end
end
class FletchingInterfaceListener < ComponentListenerAdapter
def set_context(player, recipes)
@player = player
@recipes = recipes
end
def inputPressed(component, component_id, dynamic_id)
parent_id = component.get_current_id
offset = parent_id == 309 ? 3 : (4 + (parent_id - 303))
component_id -= offset
recipe = @recipes.values[component_id / 4]
option = 3 - (component_id % 4)
case option
when 0..1
amt = 5 ** option
when 2
amt = parent_id == 309 ? 'X' : 10
when 3
amt = parent_id == 309 ? recipe.calculate_max(@player) : 'X'
end
if amt == 'X'
close
input_listener = FletchingInputListener.new
input_listener.set_context(@player, recipe)
@player.get_script_input.show_integer_script_input input_listener
else
@player.get_interface_set.get_chatbox.reset
@player.start_action FletchingTask.new(@player, recipe, amt)
end
end
def componentClosed(unused)
component = player.get_interface_set.get_chatbox
component.remove_listener
component.reset
end
def close
component = @player.get_interface_set.get_chatbox
component.remove_listener
component.reset
end
end
class FletchingInputListener < ScriptInputListener
def set_context(player, recipe)
@player = player
@recipe = recipe
end
def intInputReceived(value)
@player.start_action FletchingTask.new(@player, @recipe, value) if value > 0
@player.get_script_input.reset
end
end
end
Fletching::create_recipes
Fletching::bind_handlers |
class JobApplication < ApplicationRecord
belongs_to :job
belongs_to :employee
has_many :users, through: :employees
end
|
class Message
attr_reader :content, :time
def initialize(content)
@content = content
@time = Time.now
end
end
|
require "rails_helper"
RSpec.describe FindProjectActivities do
let(:user) { create(:beis_user) }
let(:service_owner) { create(:beis_organisation) }
let(:other_organisation) { create(:partner_organisation) }
let!(:fund_1_organisation_project) { create(:project_activity_with_implementing_organisations, organisation: other_organisation, source_fund_code: 1) }
let!(:fund_2_organisation_project) { create(:project_activity_with_implementing_organisations, organisation: other_organisation, source_fund_code: 2) }
let!(:other_project) { create(:project_activity_with_implementing_organisations, source_fund_code: 1) }
describe "#call" do
context "when the organisation is the service owner" do
it "returns all project activities" do
result = described_class.new(organisation: service_owner, user: user).call
expect(result).to match_array [fund_1_organisation_project, fund_2_organisation_project, other_project]
end
it "filters by the fund code" do
result = described_class.new(organisation: service_owner, user: user, fund_code: 1).call
expect(result).to match_array [fund_1_organisation_project, other_project]
end
end
context "when the organisation is not the service owner" do
it "returns project activities for this organisation" do
result = described_class.new(organisation: other_organisation, user: user).call
expect(result).to match_array [fund_1_organisation_project, fund_2_organisation_project]
end
it "filters by the fund code" do
result = described_class.new(organisation: other_organisation, user: user, fund_code: 1).call
expect(result).to match_array [fund_1_organisation_project]
end
end
end
end
|
require 'spec_helper'
describe Task do
describe "associations" do
it "should belongs to user" do
should belong_to(:user)
end
end
describe "checking validations" do
it "should validate presence of" do
should validate_presence_of :caption
should validate_presence_of :description
should validate_presence_of :user_id
end
end
end
|
#
# Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands.
#
# This file is part of New Women Writers.
#
# New Women Writers is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# New Women Writers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with New Women Writers. If not, see <http://www.gnu.org/licenses/>.
#
class Author < ActiveRecord::Base
# associations
has_many :author_urls, :dependent => :delete_all
has_many :pseudonyms, :dependent => :delete_all
has_many :receptions, :dependent => :destroy
has_and_belongs_to_many :countries
has_and_belongs_to_many :languages
has_many :to_relations,
:dependent => :delete_all,
:class_name => 'Relation',
:foreign_key => 'author_id'
has_many :from_relations,
:dependent => :delete_all,
:class_name => 'Relation',
:foreign_key => 'relative_id'
has_many :works, :dependent => :destroy
has_many :changes, :as => :object
has_and_belongs_to_many :to_relatives,
:class_name => 'Author',
:join_table => 'relations',
:association_foreign_key => 'relative_id',
:foreign_key => 'author_id'
has_and_belongs_to_many :from_relatives,
:class_name => 'Author',
:join_table => 'relations',
:association_foreign_key => 'author_id',
:foreign_key => 'relative_id'
has_and_belongs_to_many :relation_types,
:class_name => 'RelationType',
:join_table => 'relations',
:association_foreign_key => 'relation_type_id',
:foreign_key => 'author_id'
# :association_foreign_key => 'author_id',
# :foreign_key => 'relation_type'
# class methods
=begin
validates_presence_of :name
validates_presence_of :year_born
validates_presence_of :year_death
validates_inclusion_of :gender, :in=> %w( M F U)
validates_inclusion_of :year_born, :in=> 1700..1900, :message => "should be between 1700 and 1900"
validates_inclusion_of :year_death, :in=> 1700..1900, :message => "should be between 1700 and 1900"
=end
def fullgender
case gender
when 'F': 'female'
when 'M': 'male'
else 'unknown'
end
end
def self.all
find(:all)
end
def self.women
find(:all, :conditions => "gender = 'F' ", :order => "name")
end
def self.others
find(:all, :conditions => "gender <> 'F' ", :order => "name")
end
def short_name
name[0, 25]
end
# Returns hash with author id of relative=> relation discription and name of relative : e.g. {"7"=>"Mother of Sand, Solange"} 7 is id of Solange
def get_children
if(gender=='M') : typefield='parent_male' else typefield='parent_female' end
children={}
self.to_relations.collect.each do |r|
children.merge!(r.relative.id=>r.relation_type.send(typefield) +' of '+ r.relative.name)
end
return children
end
# Returns hash with author id of relative=> relation discription and name of relative : e.g. {"6"=>"Daughter of Sand, George"} 6 is id of George
def get_parents
if(gender=='M') : typefield='child_male' else typefield='child_female' end
parents={}
self.from_relations.collect.each do |r|
parents.merge!(r.author.id => r.relation_type.send(typefield) +' of '+ r.author.name)
end
return parents
end
def get_relations
if(gender=='M')
parentfield='parent_male'
childfield='child_male'
else
parentfield='parent_female'
childfield='child_female'
end
relations={}
self.to_relations.collect.each do |r|
relations.merge!(r.id=>r.relation_type.send(parentfield) +' of '+ r.relative.name)
end
self.from_relations.collect.each do |r|
relations.merge!(r.id => r.relation_type.send(childfield) +' of '+ r.author.name)
end
return relations
end
def get_types
if(gender=='M')
parentfield='parent_male'
childfield='child_male'
else
parentfield='parent_female'
childfield='child_female'
end
thistypes={}
reltypes=RelationType.all
reltypes.each do |r|
thistypes.merge!(r.id=>r.send(parentfield))
thistypes.merge!(r.id*100 => r.send(childfield))
end
return thistypes
end
def validate
# errors.add('year_born', 'must be before year death') if year_born >= year_death
end
end
|
class AddDeviceToSubreddits < ActiveRecord::Migration
def change
add_column :subreddits, :device_id, :integer
end
end
|
class Dashboard::Card::TitleComponent < ApplicationComponent
attr_reader :title
attr_reader :subtitle
attr_reader :tooltip_definitions
renders_one :ltfu_toggle, Dashboard::Card::LtfuToggleComponent
renders_one :tooltip, Dashboard::Card::TooltipComponent
def initialize(title:, subtitle: nil, tooltip_definitions: nil)
@title = title
@subtitle = subtitle
@tooltip_definitions = tooltip_definitions
end
end
|
require File.join(File.dirname(__FILE__), '..', 'spec_helper')
def glob_files(*path_elements)
Dir.glob(File.join(*path_elements))
end
def load_erb_yaml(path, context)
ryaml = ERB.new(File.read(path), 0)
YAML.load(ryaml.result(context))
end
module ERBMetaMixin
# Needed to make the YAML load work...
def project_files
glob_files(@root_dir, 'lib', '**/*.rb')
end
# Needed to make the YAML load work...
def spec_files
glob_files(@root_dir, 'spec', '**/*_spec.rb')
end
end
describe "Twitter::Meta cache policy" do
include ERBMetaMixin
before(:each) do
@root_dir = project_root_dir
@meta = Twitter::Meta.new(@root_dir)
@expected_pkg_info = load_erb_yaml(File.join(@root_dir, 'pkg-info.yml'), binding)
@expected_project_files = project_files
@expected_spec_files = spec_files
end
it "should store value returned from project_files in @project_files after first glob" do
@meta.instance_eval("@project_files").should eql(nil)
@meta.project_files
@meta.instance_eval("@project_files").should eql(@expected_project_files)
@meta.project_files
@meta.instance_eval("@project_files").should eql(@expected_project_files)
end
it "should store value returned from spec_files in @spec_files after first glob" do
@meta.instance_eval("@spec_files").should eql(nil)
@meta.spec_files
@meta.instance_eval("@spec_files").should eql(@expected_spec_files)
@meta.spec_files
@meta.instance_eval("@spec_files").should eql(@expected_spec_files)
end
end
describe "Twitter::Meta" do
include ERBMetaMixin
before(:each) do
@root_dir = project_root_dir
@meta = Twitter::Meta.new(@root_dir)
@expected_yaml_hash = load_erb_yaml(File.join(@root_dir, 'pkg-info.yml'), binding)
@expected_project_files = project_files
@expected_spec_files = spec_files
end
it "should load and return YAML file into Hash object upon #pkg_info call" do
yaml_hash = @meta.pkg_info
yaml_hash.should.eql? @expected_yaml_hash
end
it "should return the embedded hash responding to key 'spec' of #pkg_info call upon #spec_info call" do
yaml_hash = @meta.spec_info
yaml_hash.should.eql? @expected_yaml_hash['spec']
end
it "should return list of files matching ROOT_DIR/lib/**/*.rb upon #project_files call" do
project_files = @meta.project_files
project_files.should.eql? @expected_project_files
end
it "should return list of files matching ROOT_DIR/spec/**/*.rb upon #spec_files call" do
spec_files = @meta.spec_files
spec_files.should.eql? @expected_spec_files
end
it "should return Gem specification based on YAML file contents and #project_files and #spec_files return values" do
spec = @meta.gem_spec
expected_spec_hash = @expected_yaml_hash['spec']
expected_spec_hash.each do |key, val|
unless val.is_a?(Hash)
spec.send(key).should.eql? expected_spec_hash[key]
end
end
end
end
|
class ChangeBlockedToBool < ActiveRecord::Migration
def change
change_column :users, :blocked, :boolean
end
end
|
class UserTwitterUsageTest < ActionDispatch::IntegrationTest
include Capybara::DSL
attr_reader :service
test "user can favorite a tweet" do
VCR.use_cassette("curious_tweets#favorite") do
visit "/"
assert_equal 200, page.status_code
click_link "login"
assert_equal dashboard_path, current_path
within(".list-group-item") do
fill_in "tweet", with: "this is a tweet"
click_on "Submit"
assert page.has_content("this is a tweet")
click_on css(".favorite")
assert page.has_content("favorite")
end
end
end
test "user can unfavorite a tweet" do
VCR.use_cassette("curious_tweets#unfavorite") do
assert_equal dashboard_path, current_path
within(".list-group-item") do
fill_in "tweet", with: "this is a tweet"
click_on "Submit"
assert page.has_content("this is a tweet")
click_on css(".favorite")
assert page.has_content("red")
click_on css(".glyphicon-heart")
refute page.has_content("favorite")
end
end
end
end
|
class AddNeedsReviewToPeople < ActiveRecord::Migration[4.2]
def change
add_column :people, :needs_review, :boolean, default: false
add_column :people, :needs_review_reason, :string
end
end
|
require 'test_helper'
module Api
module V1
class UsersControllerTest < ActionDispatch::IntegrationTest
test 'creates user' do
user_params = {
email: Faker::Internet.email,
password: Faker::Internet.password,
avatar: fixture_file_upload('images/axe.jpg', 'image/jpg')
}
post(
api_v1_users_path,
params: user_params
)
response = JSON.parse(@response.body)['data']['user']
user = User.find_by email: response['email']
assert_response :success
assert response['email'] == user_params[:email]
assert response['authentication_token'] == user.authentication_token
end
test 'updates user' do
user = users(:one)
old_service_count = user.services.count
headers = {
'X-User-Email': user.email,
'X-User-Token': user.authentication_token
}
user_params = {
password: Faker::Internet.password,
avatar: fixture_file_upload('images/axe.jpg', 'image/jpg'),
services_attributes: [
{
title: 'Emote',
description: 'Your average Twitch emote',
price: 4.99
},
{
title: 'Overlay',
description: 'Your average Twitch overlay',
price: 14.99
},
]
}
patch(
api_v1_user_path(user),
headers: headers,
params: user_params
)
new_service_count = user.reload.services.count
assert_response :success
assert new_service_count == old_service_count + 2
assert user.valid_password?(user_params[:password])
end
end
end
end
|
class AddIndexToTaskIdToDepends < ActiveRecord::Migration
def change
add_index :depends, :task_id
end
end
|
class QuestionFollow
attr_accessor :question_id, :user_id
def self.find_by_id(id)
attr = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
question_follows
WHERE
id = ?
SQL
QuestionFollow.new(*attr)
end
def self.followed_questions_for_user_id(user_id)
attrs = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT DISTINCT
following_qs.*
FROM
question_follows AS userid
JOIN
question_follows AS following_ids ON userid.user_id = following_ids.user_id
JOIN
questions AS following_qs ON following_qs.id = following_ids.question_id
WHERE
userid.user_id = ?
SQL
attrs.map{ |attr| Question.new(attr) }
end
def self.followers_for_question_id(question_id)
attrs = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
users.*
FROM
question_follows
JOIN
users ON users.id = question_follows.user_id
WHERE
question_follows.question_id = ?
SQL
attrs.map{ |attr| User.new(attr) }
end
def self.most_followed_questions(n)
attrs = QuestionsDatabase.instance.execute(<<-SQL, n)
SELECT
questions.*
FROM
question_follows
JOIN
questions ON question_follows.question_id = questions.id
GROUP BY
question_id
ORDER BY
COUNT(question_id) DESC
LIMIT
?
SQL
attrs.map{ |attr| Question.new(attr) }
end
# id, question_id, user_id
def initialize(hash = {})
@id= hash['id']
@question_id = hash['question_id']
@user_id = hash['user_id']
end
end
|
class SubGenre < ApplicationRecord
belongs_to :genre
has_one :category, through: :genre
has_many :artists
has_many :albums, through: :artists
end
|
class Blast < ActiveRecord::Base
belongs_to :list
has_many :questions
validates :list_id, presence: true
validates :message, presence: true, length: { maximum: 160 }
def citizens
list.citizens
end
def has_question?
questions.first.present?
end
def send_question(citizen)
# TODO: will eventually walk through question order
questions.first.create_listener(citizen)
TwilioOutbound.perform_async(citizen.e164_phone, questions.first.prompt)
end
end
|
Pod::Spec.new do |s|
s.name = 'ApplePurchaseManager'
s.version = '0.0.1'
s.authors = { 'daniulaolu' => '287929070@qq.com' }
s.homepage = 'https://github.com/MrLujh/ApplePurchaseManager'
s.summary = 'ApplePurchase'
s.source = { :git => 'https://github.com/MrLujh/ApplePurchaseManager.git',
:tag => s.version.to_s }
s.license = { :type => "MIT", :file => "LICENSE" }
s.platform = :ios, '8.0'
s.requires_arc = true
s.source_files = 'ApplePurchaseManager/**/*.{h,m}'
s.ios.deployment_target = '7.0'
s.dependency 'SVProgressHUD'
s.frameworks = 'StoreKit'
end |
class Deck
attr_accessor :deck
def initialize(deck)
if deck
@deck = deck
else
@deck = [*1..52]
@deck.shuffle! #山札のシャッフル
end
end
def distribution
@deck.pop
end
end
class Card
def initialize(number)
@number = number
end
attr_accessor :number
def stringify
for i in @deck
@number = (i-1)%13 + 1
if i/13 == 0
@deck[@index] = {"S" => @number}
elsif i/13 == 1
@deck[@index] = {"C" => @number}
elsif i/13 == 2
@deck[@index] = {"D" => @number}
elsif i/13 == 3
@deck[@index] = {"H" => @number}
end
@index += 1
end
end
end
class Player
attr_accessor :hands, :sum, :bet, :betting
def initialize
@hands = []
@sum = 0
@bet = 100
@betting = 0
end
def hands
@hands
end
def draw(deck,hands)
if hands
@hands = hands
@hands.push(deck.distribution)
else
@hands.push(deck.distribution)
end
end
def a_is
flag = false
@hands.each{ |number|
if number%13 == 1
flag = true
end
}
return flag
end
def total
flag = false
@sum = 0
for number in @hands
#J,Q,Kの処理
if number%13 >10 || number%13 == 0
number = 10
end
#Aの処理
if number%13 == 1 && (@sum+11) < 22
number = 11
flag = true
elsif number%13 == 1 && (@sum+11) > 21
number = 1
end
@sum += number%13
if @sum > 21 && flag
@sum -= 10
flag = false
end
end
return @sum
end
def nobust
if @sum > 21
false
else
true
end
end
def blackjack
if @hands.size == 2 && @sum == 21
true
else
false
end
end
def win
return @bet += @betting
end
def lose
return @bet -= @betting
end
end
class Dealer < Player
def judge_d
if @sum < 17
true
end
end
end
#require '../lib/blackjack'
require 'json'
$deckfile = './app/json/deck.json'
$gamefile = './app/json/game.json'
$gamesfile = './app/json/games.json'
class BlackjackController < ApplicationController
#include Blackjack
def home
=begin
session[:deck] = nil
session[:phands] = nil
session[:dhands] = nil
=end
File.open($deckfile, 'w') do |file|
data = {"deck"=>[]}
JSON.dump(data, file)
end
File.open($gamefile, 'w') do |game|
data = {"player"=>{"hands"=>[],"sum"=>nil,"bet"=>100,"betting"=>0}, "dealer"=>{"hands"=>[],"sum"=>nil}}
JSON.dump(data,game)
end
File.open($gamesfile, 'w') do |file|
data = {"player1":{"hands": [],"sum": nil}, "player2":{"hands": [],"sum": nil},"player3":{"hands": [],"sum": nil},"player4":{"hands": [],"sum": nil}, "dealer":{"hands": [],"sum": nil}}
file.write JSON.pretty_generate(data)
end
render 'home.html.erb'
end
def select_bet
p = Player.new
=begin
p = Player.new
if session[:bet]
@bet = session[:bet]
else
@bet = p.bet
end
=end
data = nil
File.open($gamefile) do |file|
data = JSON.load(file)
end
if data["player"]["bet"]
@bet = data["player"]["bet"]
else
@bet = p.bet
end
render 'select_bet.html.erb'
end
def game_bet
deckdata = nil
gamedata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamefile) do |file|
gamedata = JSON.load(file)
end
gamedata["player"]["hands"] = []
gamedata["dealer"]["hands"] = []
deck = Deck.new(false)
p = Player.new
d = Dealer.new
p.draw(deck,gamedata["player"]["hands"])
d.draw(deck,gamedata["dealer"]["hands"])
p.draw(deck,gamedata["player"]["hands"])
@betting = params[:bet].to_i
p.betting = params[:bet].to_i
@phands = p.hands
@dhands = d.hands
@psum = p.total
@dsum = d.total
@bet = gamedata["player"]["bet"]
if p.blackjack
@bet = p.win
@result = "you win あなたの残額は#{@bet}ドルです"
end
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
File.open($gamefile, 'w') do |file|
gamedata["player"]["hands"] = p.hands
gamedata["player"]["sum"] = p.total
gamedata["player"]["betting"] = @betting
gamedata["player"]["bet"] = @bet
gamedata["dealer"]["sum"] = d.total
JSON.dump(gamedata, file)
end
render 'game.html.erb'
end
def game_reset
p = Player.new
gamedata = nil
File.open($deckfile, 'w') do |file|
deckdata = {"deck"=>[]}
JSON.dump(deckdata, file)
end
File.open($gamefile) do |file|
gamedata = JSON.load(file)
end
File.open($gamefile, 'w') do |file|
gamedata["player"]["hands"] = []
gamedata["player"]["sum"] = nil
gamedata["player"]["betting"] = 0
gamedata["player"]["bet"] = 100
gamedata["dealer"]["hands"] = []
gamedata["dealer"]["sum"] = nil
JSON.dump(gamedata, file)
end
@bet = p.bet
render 'select_bet.html.erb'
end
def game_hit
deckdata = nil
gamedata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamefile) do |file|
gamedata = JSON.load(file)
end
deck = Deck.new(deckdata["deck"])
p = Player.new
d = Dealer.new
p.draw(deck,gamedata["player"]["hands"])
d.hands = gamedata["dealer"]["hands"]
@phands = p.hands
@dhands = d.hands
@psum = p.total
@dsum = d.total
@betting = gamedata["player"]["betting"]
@bet = gamedata["player"]["bet"]
p.betting = gamedata["player"]["betting"]
p.bet = gamedata["player"]["bet"]
if p.nobust
@psum
else
@psum = "bust"
@bet = p.lose
@result = "Player lose あなたの残額は#{@bet}ドルです"
end
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
File.open($gamefile, 'w') do |file|
gamedata["player"]["hands"] = p.hands
gamedata["player"]["sum"] = p.total
gamedata["player"]["betting"] = @betting
gamedata["player"]["bet"] = @bet
JSON.dump(gamedata, file)
end
render 'game.html.erb'
end
def game_double
deckdata = nil
gamedata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamefile) do |file|
gamedata = JSON.load(file)
end
deck = Deck.new(deckdata["deck"])
p = Player.new
d = Dealer.new
p.draw(deck,gamedata["player"]["hands"])
d.hands = gamedata["dealer"]["hands"]
@phands = p.hands
@dhands = d.hands
@psum = p.total
@dsum = d.total
gamedata["player"]["betting"] *= 2
@betting = gamedata["player"]["betting"]
@bet = gamedata["player"]["bet"]
p.betting = gamedata["player"]["betting"]
p.bet = gamedata["player"]["bet"]
@flag = true
if p.nobust
@psum
else
@psum = "bust"
@bet = p.lose
@result = "Player lose あなたの残額は#{@bet}ドルです"
end
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
File.open($gamefile, 'w') do |file|
gamedata["player"]["hands"] = p.hands
gamedata["player"]["sum"] = p.total
gamedata["player"]["betting"] = @betting
gamedata["player"]["bet"] = @bet
JSON.dump(gamedata, file)
end
render 'game.html.erb'
end
def game_stand
deckdata = nil
gamedata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamefile) do |file|
gamedata = JSON.load(file)
end
deck = Deck.new(deckdata["deck"])
p = Player.new
d = Dealer.new
p.hands = gamedata["player"]["hands"]
d.draw(deck,gamedata["dealer"]["hands"])
@phands = p.hands
@psum = p.total
@dhands = d.hands
@dsum = d.total
p.betting = gamedata["player"]["betting"]
p.bet = gamedata["player"]["bet"]
@bet = gamedata["player"]["bet"]
while d.judge_d
d.draw(deck,session[:dhands])
@dhands = d.hands
@dsum = d.total
end
if d.nobust
@dsum
if p.total > @dsum && p.total < 22
@bet = p.win
@result = "Player win あなたの残額は#{@bet}ドルです"
elsif p.total < @dsum
@bet = p.lose
@result = "Player lose あなたの残額は#{@bet}ドルです"
elsif p.total == @dsum
@result = "draw あなたの残額は#{@bet}ドルです"
end
else
@dsum = "bust"
@bet = p.win
@result = "Player win あなたの残額は#{@bet}ドルです"
end
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
File.open($gamefile, 'w') do |file|
gamedata["player"]["bet"] = @bet
gamedata["dealer"]["hands"] = d.hands
gamedata["dealer"]["sum"] = d.total
JSON.dump(gamedata, file)
end
render 'game.html.erb'
end
def game_stands
gamesdata = nil
deckdata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamesfile) do |file|
gamesdata = JSON.load(file)
end
deck = Deck.new(deckdata["deck"])
p = Player.new
d = Dealer.new
d.hands = gamesdata["dealer"]["hands"]
@dhands = d.hands
@dsum = d.total
@pnumber = session[:pnumber]
@presults = session[:presults]
@flag = 1
while d.judge_d
d.draw(deck,gamesdata["dealer"]["hands"])
@dhands = d.hands
@dsum = d.total
end
if d.nobust
gamesdata.each_with_index do |(p, v), i|
if i < @pnumber.size
@dsum
if v["sum"] > @dsum && v["sum"] < 22
@presults[i] = "Player#{i+1} win"
elsif v["sum"] < @dsum
@presults[i] = "Player#{i+1} lose"
elsif v["sum"] == @dsum
@presults[i] = "Player#{i+1} draw"
end
end
end
else
@dsum = "bust"
gamesdata.each_with_index do |(p, v), i|
if @presults[i] == nil
@presults[i] = "Player#{i+1} win"
end
end
end
@gamesdata = gamesdata
session[:dhands] = d.hands
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
File.open($gamesfile, 'w') do |file|
gamesdata["dealer"]["hands"] = d.hands
gamesdata["dealer"]["sum"] = d.total
file.write JSON.pretty_generate(gamesdata)
end
render 'games_stay.html.erb'
end
def games
gamesdata = nil
deckdata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamesfile) do |file|
gamesdata = JSON.load(file)
end
deck = Deck.new(false)
d = Dealer.new
i = 0
pnumber = []
pclass = []
params[:n].to_i.times do
pnumber[i] = i+1
pclass[i] = Player.new
i += 1
end
@pnumber = pnumber
@pclass = pclass
@psums = []
@presults = []
@plhands = []
@count = 1
i = 1
pclass.each do |p|
p.draw(deck,gamesdata["player#{i}"]["hands"])
i += 1
end
d.draw(deck,gamesdata["dealer"]["hands"])
i = 1
pclass.each do |p|
p.draw(deck,gamesdata["player#{i}"]["hands"])
i += 1
end
i = 0
params[:n].to_i.times do
@plhands[i] = pclass[i].hands
i += 1
end
@dhands = d.hands
i = 0
params[:n].to_i.times do
@psums[i] = pclass[i].total
i += 1
end
@dsum = d.total
i = 0
pclass.each do |p|
if p.blackjack
@presults[i] = "Player#{i+1} win"
end
i += 1
end
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
i = 0
params[:n].to_i.times do
File.open($gamesfile, 'w') do |file|
gamesdata["player#{i+1}"]["hands"] = pclass[i].hands
gamesdata["player#{i+1}"]["sum"] = pclass[i].total
file.write JSON.pretty_generate(gamesdata)
end
i += 1
end
File.open($gamesfile, 'w') do |file|
gamesdata["dealer"]["hands"] = d.hands
gamesdata["dealer"]["sum"] = d.total
file.write JSON.pretty_generate(gamesdata)
end
@gamesdata = gamesdata
session[:pnumber] = pnumber
session[:pclass] = pclass
session[:presults] = @presults
session[:count] = @count
render 'games.html.erb'
end
def games_hit1
deckdata = nil
gamesdata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamesfile) do |file|
gamesdata = JSON.load(file)
end
deck = Deck.new(deckdata["deck"])
p = Player.new
d = Dealer.new
p.draw(deck,gamesdata["player1"]["hands"])
d.hands = gamesdata["dealer"]["hands"]
@phands = p.hands
@dhands = d.hands
@psum = p.total
@dsum = d.total
@pnumber = session[:pnumber]
@pclass = session[:pclass]
@presults = session[:presults]
@count = session[:count]
if p.nobust
@psum
else
@psum = "bust"
@presults[0] = "Player1 lose"
end
@gamesdata = gamesdata
session[:presults] = @presults
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
File.open($gamesfile, 'w') do |file|
gamesdata["player1"]["hands"] = p.hands
gamesdata["player1"]["sum"] = p.total
file.write JSON.pretty_generate(gamesdata)
end
render 'games.html.erb'
end
def games_hit2
deckdata = nil
gamesdata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamesfile) do |file|
gamesdata = JSON.load(file)
end
deck = Deck.new(deckdata["deck"])
p = Player.new
d = Dealer.new
p.draw(deck,gamesdata["player2"]["hands"])
d.hands = gamesdata["dealer"]["hands"]
@phands = p.hands
@dhands = d.hands
@psum = p.total
@dsum = d.total
@pnumber = session[:pnumber]
@presults = session[:presults]
@count = session[:count]
if p.nobust
@psum
else
@psum = "bust"
@presults[1] = "Player2 lose"
end
@gamesdata = gamesdata
session[:presults] = @presults
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
File.open($gamesfile, 'w') do |file|
gamesdata["player2"]["hands"] = p.hands
gamesdata["player2"]["sum"] = p.total
file.write JSON.pretty_generate(gamesdata)
end
render 'games_stay.html.erb'
end
def games_hit3
deckdata = nil
gamesdata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamesfile) do |file|
gamesdata = JSON.load(file)
end
deck = Deck.new(deckdata["deck"])
p = Player.new
d = Dealer.new
p.draw(deck,gamesdata["player3"]["hands"])
d.hands = gamesdata["dealer"]["hands"]
@phands = p.hands
@dhands = d.hands
@psum = p.total
@dsum = d.total
@pnumber = session[:pnumber]
@presults = session[:presults]
@count = session[:count]
if p.nobust
@psum
else
@psum = "bust"
@presults[2] = "Player3 lose"
end
@gamesdata = gamesdata
session[:presults] = @presults
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
File.open($gamesfile, 'w') do |file|
gamesdata["player3"]["hands"] = p.hands
gamesdata["player3"]["sum"] = p.total
file.write JSON.pretty_generate(gamesdata)
end
render 'games_stay.html.erb'
end
def games_hit4
deckdata = nil
gamesdata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamesfile) do |file|
gamesdata = JSON.load(file)
end
deck = Deck.new(deckdata["deck"])
p = Player.new
d = Dealer.new
p.draw(deck,gamesdata["player4"]["hands"])
d.hands = gamesdata["dealer"]["hands"]
@phands = p.hands
@dhands = d.hands
@psum = p.total
@dsum = d.total
@pnumber = session[:pnumber]
@presults = session[:presults]
@count = session[:count]
if p.nobust
@psum
else
@psum = "bust"
@presults[3] = "Player4 lose"
end
@gamesdata = gamesdata
session[:presults] = @presults
File.open($deckfile, 'w') do |file|
deckdata["deck"] = deck.deck
JSON.dump(deckdata, file)
end
File.open($gamesfile, 'w') do |file|
gamesdata["player4"]["hands"] = p.hands
gamesdata["player4"]["sum"] = p.total
file.write JSON.pretty_generate(gamesdata)
end
render 'games_stay.html.erb'
end
def games_stay
session[:count] += 1
deckdata = nil
gamesdata = nil
File.open($deckfile) do |file|
deckdata = JSON.load(file)
end
File.open($gamesfile) do |file|
gamesdata = JSON.load(file)
end
deck = Deck.new(deckdata["deck"])
d = Dealer.new
d.hands = gamesdata["dealer"]["hands"]
@dhands = d.hands
@dsum = d.total
@gamesdata = gamesdata
@pnumber = session[:pnumber]
@presults = session[:presults]
@count = session[:count]
session[:count] = @count
render 'games_stay.html.erb'
end
end |
require 'vcr'
VCR.configure do |c|
c.configure_rspec_metadata!
c.default_cassette_options = {
match_requests_on: [
:method,
VCR.request_matchers.uri_without_param(
:timestamp, :body_md5, :auth_signature, :auth_timestamp, :auth_key
)
],
serialize_with: :json,
preserve_exact_body_bytes: true,
decode_compressed_response: true,
record: ENV['RECORD_VCR'] || ENV['CI'] ? :none : :once
}
c.ignore_localhost = true
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock
c.ignore_hosts 'codeclimate.com'
c.filter_sensitive_data('<API_KEY>') do
ENV['ACTIVE_CAMPAIGN_API_KEY']
end
c.filter_sensitive_data('<API_ENDPOINT>') do
ENV['ACTIVE_CAMPAIGN_API_ENDPOINT']
end
end
|
class Carte < ActiveRecord::Base
has_many :items, dependent: :destroy
accepts_nested_attributes_for :items, allow_destroy: true
mount_uploader :image, Uploader
# limit 2mo
validates :name, presence: true
validates :image, presence: true, file_size: { maximum: 2097152 }
after_destroy :remove_image_folder
private
def remove_image_folder
store_dir = image.store_dir
remove_image!
FileUtils.remove_dir("#{Padrino.root}/public/#{store_dir}", :force => true)
end
end
|
module API
module V1
class Conversations < Grape::API
include API::V1::Defaults
resource :conversations do
desc "Return all conversations"
get "" do
Conversation.all
end
desc "Return a conversation"
params do
requires :id, type: Integer, desc: "ID of the user"
end
get ":id" do
Conversation.where(id: permitted_params[:id]).first!
end
desc "Return a conversation"
params do
requires :user_token, type: String, desc: "ID of the user"
requires :recipient_id, type: Integer, desc: "ID of the user"
end
get "/:user_token/:recipient_id" do
user_token = ApiKey.find_by(access_token: params[:user_token])
if user_token.present?
Conversation.between(user_token.user_id, params[:recipient_id] ).first!
else
error!({error_code: 422, error_message: "Impossible de traiter la requette."},422)
return
end
end
end
end
end
end |
require_relative '../test_helper'
class BotUser2Test < ActiveSupport::TestCase
test "should get events" do
assert_kind_of String, BotUser.new.bot_events
end
test "should be a bot" do
assert BotUser.new.is_bot
end
test "should have settings as JSON schema" do
t = create_team
b = create_bot_user team: t
b.set_settings = [{ type: 'object', name: 'foo_bar' }, { name: 'smooch_template_locales' }, { name: 'smooch_workflows', type: 'array', items: { properties: { smooch_message_smooch_bot_tos: { properties: {} } } } }]
b.save!
assert_kind_of String, b.settings_as_json_schema(false, t.slug)
assert_kind_of String, b.settings_ui_schema
end
test "should get users" do
assert_nothing_raised do
BotUser.alegre_user
BotUser.fetch_user
BotUser.keep_user
BotUser.smooch_user
BotUser.check_bot_user
end
end
test "should not change role when change team bot settings" do
team = create_team
team_bot = create_team_bot team_author_id: team.id
tbi = TeamBotInstallation.where(team_id: team.id, user_id: team_bot.id).last
tbi.role = 'admin'
tbi.save
assert_equal 'admin', TeamBotInstallation.find(tbi.id).role
team_bot.set_headers = { 'X-Header' => 'ABCDEFG' }
team_bot.save
assert_equal 'admin', TeamBotInstallation.find(tbi.id).role
end
test "should get team author" do
team = create_team
team_bot = create_team_bot team_author_id: team.id
assert_equal team, team_bot.team_author
end
test "should uninstall bot" do
b = create_team_bot set_approved: true
t = create_team
assert_difference 'TeamBotInstallation.count', 1 do
b.install_to!(t)
end
assert_nothing_raised do
b.installed
b.installation
end
assert_equal 2, b.installations_count
assert_difference 'TeamBotInstallation.count', -1 do
b.uninstall_from!(t)
end
assert_nothing_raised do
b.installed
b.installation
end
assert_equal 1, b.installations_count
end
test "should get GraphQL result" do
t = create_team
b = create_team_bot team: t
pm = create_project_media team: t
j = b.graphql_result('id, dbid', pm, t)
assert_equal pm.id, j['dbid']
end
test "should not get GraphQL result" do
t = create_team
b = create_team_bot team: t
pm = create_project_media team: t
RelayOnRailsSchema.stubs(:execute).raises(StandardError.new)
j = b.graphql_result('id, dbid', pm, t)
assert j.has_key?('error')
RelayOnRailsSchema.unstub(:execute)
end
test "should notify bot and get response" do
url = random_url
WebMock.stub_request(:post, url).to_return(body: { success: true, foo: 'bar' }.to_json)
team = create_team
team_bot = create_team_bot team_author_id: team.id, set_events: [{ event: 'create_project_media', graphql: nil }], set_request_url: url
data = {
event: 'create_project_media',
team: team,
time: Time.now,
data: nil,
user_id: team_bot.id,
}
assert_equal 'bar', JSON.parse(team_bot.call(data).body)['foo']
end
test "should notify Sentry when bot raises exception on notification" do
CheckSentry.expects(:notify).once
BotUser.any_instance.stubs(:notify_about_event).raises(StandardError)
t = create_team
pm = create_project_media team: t
b = create_team_bot team_author_id: t.id, set_approved: true, set_events: [{ event: 'create_project_media', graphql: nil }]
BotUser.notify_bots('create_project_media', t.id, 'ProjectMedia', pm.id, b)
end
test "should not ignore requests by default" do
b = create_team_bot
assert !b.should_ignore_request?
end
test "should notify Sentry when external bot URL can't be called" do
CheckSentry.expects(:notify).once
url = random_url
WebMock.stub_request(:post, url).to_timeout
t = create_team
pm = create_project_media team: t
b = create_team_bot team_author_id: t.id, set_approved: true, set_events: [{ event: 'create_project_media', graphql: nil }], set_request_url: url
assert_nothing_raised do
b.call({})
end
end
end
|
class Mproperty < ApplicationRecord
belongs_to :mpoint, inverse_of: :mproperties
validates :voltcl, presence: true, numericality: {:greater_than_or_equal_to => (0.4), :less_than_or_equal_to => 35}
validates :mpoint_id, presence: true, numericality: { only_integer: true }
validates :cosfi, presence: false, numericality: {:greater_than_or_equal_to => (-1), :less_than_or_equal_to => 1}, allow_blank: true
validates :propdate, presence: true
after_initialize :set_default
def set_default
if self.propdate.nil? then self.propdate = DateTime.current().beginning_of_day() end
if self.voltcl.nil? then self.voltcl = 10 end
return true
end
end
|
class AddGlasses < ActiveRecord::Migration[5.0]
def change
create_table :glasses do |t|
t.integer :wine_id, null: false
t.integer :user_id, null: false
t.date :date, null: false
t.integer :rating
t.string :notes
end
end
end
|
require 'rails_helper'
describe 'us1 - Studio Index' do
it "studio index has all studios, under each are their movies" do
studio1 = Studio.create(name: "studio01", location: "location01")
studio2 = Studio.create(name: "studio02", location: "location02")
studio3 = Studio.create(name: "studio03", location: "location04")
movie01 = studio1.movies.create(title: "movie01", year: "2001", genre: "genre1")
movie11 = studio1.movies.create(title: "movie11", year: "2011", genre: "genre2")
movie02 = studio2.movies.create(title: "movie02", year: "2002", genre: "genre1")
movie22 = studio2.movies.create(title: "movie22", year: "2022", genre: "genre2")
movie03 = studio3.movies.create(title: "movie03", year: "2003", genre: "genre1")
movie33 = studio3.movies.create(title: "movie33", year: "2033", genre: "genre2")
visit "/studios"
within("#studio-#{studio1.id}")do
expect(page).to have_content("Studio: #{studio1.name}")
expect(page).to_not have_content("Studio: #{studio2.name}")
expect(page).to have_content("Location: #{studio1.location}")
expect(page).to_not have_content("Location: #{studio3.location}")
expect(page).to have_content("Movies:")
expect(page).to have_link(movie01.title)
expect(page).to have_link(movie11.title)
expect(page).to_not have_link(movie02.title)
expect(page).to_not have_link(movie33.title)
end
within("#studio-#{studio2.id}")do
expect(page).to have_content("Studio: #{studio2.name}")
expect(page).to have_content("Location: #{studio2.location}")
expect(page).to have_content("Movies:")
expect(page).to have_link(movie02.title)
expect(page).to have_link(movie22.title)
expect(page).to_not have_link(movie01.title)
expect(page).to_not have_link(movie33.title)
end
within("#studio-#{studio3.id}")do
expect(page).to have_content("Studio: #{studio3.name}")
expect(page).to have_content("Location: #{studio3.location}")
expect(page).to have_content("Movies:")
expect(page).to have_link(movie03.title)
expect(page).to have_link(movie33.title)
expect(page).to_not have_link(movie01.title)
expect(page).to_not have_link(movie22.title)
click_link(movie03.title)
end
expect(current_path).to eq("/movies/#{movie03.id}")
end
end
# Story 1 - STUDIO INDEX - show movies
# As a visitor,
# When I visit the studio index page
# I see a list of all of the movie studios
# And underneath each studio, I see the names of all of its movies.
|
class WriteAReviewSearchController < ApplicationController
before_filter :handle_review_it_mode
PAGE_SIZE = 24
def index
# last_modified = [
# review_suggestions_featured_item, review_suggestions_standard_item
# ].map { |i| i.updated_at.utc }.max
# return unless stale? :last_modified => last_modified,
# :public => cache_control_public?
@keyword = params[:q]
@keyword.strip unless @keyword.nil?
@web_analytics.page_type = 'Write a Review'
page_stack = ['Write a Review', 'Search']
if @keyword.blank?
@web_analytics.page_name = 'Form'
@web_analytics.page_stack = (page_stack << @web_analytics.page_name)
render :index
else
search_method = "search_#{App.write_a_review['product_search_strategy']}"
unless private_methods.include?(search_method)
raise "Unimplemented product search strategy '#{search_method}'"
end
send search_method
return if @redirect
page_stack << 'Results'
@web_analytics.page_name = if @page_results.total_entries == 0
'No Results'
elsif @page_results.size == 0
'Out of Results'
else
"Page #{@page_results.current_page}"
end
@web_analytics.page_stack = (page_stack << @web_analytics.page_name)
render :results
end
end
private
def review_suggestions_featured_item
@review_suggestions_featured_item ||= DisplayTaxonomyItem.find_by_name DisplayTaxonomyItem::REVIEW_SUGGESTIONS_FEATURED_NAME
end
helper_method :review_suggestions_featured_item
def review_suggestions_standard_item
@review_suggestions_standard_item ||= DisplayTaxonomyItem.find_by_name DisplayTaxonomyItem::REVIEW_SUGGESTIONS_STANDARD_NAME
end
helper_method :review_suggestions_standard_item
def search_db
@page_results = Product.paginate(:per_page => PAGE_SIZE, :page => params[:page],
:conditions => ['title LIKE ?', '%%'+@keyword+'%%'],
:include => [:stat, :category, :local_photos, :remote_photos]
)
end
def search_sdc_and_endeca
page = (params[:page] || 1).to_i
expected_sdc_product_count = params[:sexp]
expected_endeca_product_count = params[:eexp]
# track the number of endeca results we've already shown
@shown_endeca_product_count = (params[:esho] || 0).to_i
products = []
# sdc results
page_first_record = (PAGE_SIZE * (page-1))+1
@found_sdc_product_count = 0
if params[:ecat].blank?
# only query SDC if we haven't already or we're on a page still in the range of expect results
if expected_sdc_product_count.blank? || page_first_record <= expected_sdc_product_count.to_i
sdc_data = query_sdc(@keyword, PAGE_SIZE, page, params[:scat])
# ignore all SDC results if they only contain offers
unless sdc_data.blank? || sdc_data[:content_type] == 'offers'
@found_sdc_product_count = sdc_data[:total_matches].to_i
if sdc_data[:products] && sdc_data[:products].size > 0
begin
products = PartnerProduct.save_from_sdc_to_db(sdc_data, nil, nil, false)
rescue => e
logger.info "Exception processing SDC results #{e}: #{e.backtrace.join("\n")}"
end
end
end
else
@found_sdc_product_count = expected_sdc_product_count.to_i
end
end
@found_endeca_product_count = 0
if params[:scat].blank?
# search endeca
sdc_page_count = (@found_sdc_product_count / PAGE_SIZE.to_f).ceil
full_endeca_page_count = ((page <= sdc_page_count) ? 0 : (page - sdc_page_count - 1))
endeca_offset = @shown_endeca_product_count
endeca_offset += ((full_endeca_page_count-1)*PAGE_SIZE) if full_endeca_page_count > 0
endeca_res, endeca_products, endeca_categories = query_endeca(@keyword, PAGE_SIZE,
endeca_offset, params[:ecat])
@found_endeca_product_count = endeca_res.metainfo.aggregate_total_number_of_matching_records.to_i
if products.size < PAGE_SIZE
# back-fill with endeca products
fill = PAGE_SIZE-products.size
@shown_endeca_product_count += fill
endeca_products[0..(fill-1)].each do |p|
logger.debug "adding endeca product '#{p.title} (#{p.id})'" if logger.debug
products << p
end
end
@narrow_links = []
unless endeca_categories.blank?
@narrow_links = endeca_categories.collect do |c|
{ :name => c.dim_value_name, :category_id => c.dim_value_id }
end
end
end
# create composite paginator
total_found_product_count = @found_sdc_product_count + @found_endeca_product_count
@page_results = WillPaginate::Collection.create(page, PAGE_SIZE, total_found_product_count) do |pager|
pager.replace products
end
end
def search_forwards_to_shc
kmart_url = "http://www.kmart.com/shc/s/search_10151_10104?keyword=#{@keyword}&sid=comm_kmart_other"
sears_url = "http://www.sears.com/shc/s/search_10153_12605?keyword=#{@keyword}&sid=comm_sears_other"
@cobrand.id == Cobrand['mysears'].id ? redirect_to(sears_url) : redirect_to(kmart_url)
@redirect = true
end
def query_sdc(q, page_size, page_number, category_id=nil)
begin
sdc_opts = { :trackingId => App.sdc_tracking_ids['default'], :keyword => q,
:numItems => page_size, :pageNumber => page_number, :showSoftProducts => false,
:showProductsWithoutOffers => true
}
sdc_opts[:categoryId] = category_id if category_id
Sdc3::GeneralSearch.execute sdc_opts
rescue => e
logger.error "write_a_review_search: SDC search failed: #{$!.message} #{$!.backtrace.join("\n")}"
return {}
end
end
def query_endeca(q, page_size, offset, n)
endeca_res = Endeca::ProductSearchQuery.execute :q => q, :show => page_size,
:offset => offset, :N => n
if endeca_res.aggregate_records.blank?
return endeca_res, [], []
else
ids = endeca_res.aggregate_records.map { |r| r.record_spec.to_i }
products = Product.find_from_review_ids ids, :include => [:stat, :category, :remote_photos, :partner_products, :local_photos]
categories = endeca_res.refinement_dim_values("Category")
return endeca_res, products, categories
end
end
def handle_review_it_mode
set_review_it_mode if params[:review_it] == true
end
end
|
class ServicesController < ApplicationController
def index
@services = Practitioner.first.services
end
def new
@practitioner = Practitioner.first
@service = @practitioner.services.new
end
def create
@practitioner = Practitioner.first
@service = @practitioner.services.new(service_params)
if @service.save
flash[:notice] = "Your service has been added."
redirect_to services_path
else
flash[:notice] = "Please try again."
render :new
end
end
def edit
@practitioner = Practitioner.first
@service = @practitioner.services.find(params[:id])
end
def update
@practitioner = Practitioner.first
@service = @practitioner.services.find(params[:id])
if @service.update(service_params)
flash[:notice] = "Your service has been updated."
redirect_to services_path
else
flash[:notice] = "Please try again."
render :edit
end
end
def destroy
@practitioner = Practitioner.first
@service = @practitioner.services.find(params[:id])
@service.destroy
redirect_to services_path
end
private
def service_params
params.require(:service).permit(:name, :description, :cost, :duration, :attached_image)
end
end
|
FactoryGirl.define do
factory :dummy_module_platform,
class: Dummy::Module::Platform,
traits: [
:metasploit_model_base,
:metasploit_model_module_platform
] do
ignore do
# have to use module_type from metasploit_model_module_platform trait to ensure module_instance will support
# module platforms.
module_class { FactoryGirl.create(:dummy_module_class, module_type: module_type) }
end
module_instance {
FactoryGirl.build(
:dummy_module_instance,
module_class: module_class,
# disable module_instance factory from building module_platforms since this factory is already building one
module_platforms_length: 0
)
}
platform { generate :dummy_platform }
after(:build) do |module_platform|
module_instance = module_platform.module_instance
if module_instance
unless module_instance.module_platforms.include? module_platform
module_instance.module_platforms << module_platform
end
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.