text stringlengths 10 2.61M |
|---|
class Story < ApplicationRecord
has_and_belongs_to_many :character
has_many :stories_sequence
has_many :stories_note
belongs_to :universe
belongs_to :user
belongs_to :genre
end |
cask 'sonos-s2' do
version :latest # I could get a version from the url but this app is auto update so why bother?
sha256 :no_check
# 7dcab807a75f9faef5941f96eff3e823771187e9f6fea3892d2674f192c0a02f SonosDesktopController120.dmg
# download page: https://support.sonos.com/s/downloads?language=en_US
# - macOS S2 app link: https://www.sonos.com/redir/controller_software_mac2 # as of 2023-03-11
# FYI this link redirects to the current version, i.e. right now:
# https://update-software.sonos.com/software/veqbtaxi/Sonos_71.1-38240.dmg
# I last had version "12.0" and now it's "71.1"!? clearly this version scheme is radical and irrelevant IMO given that the app auto-updates so to install it I just need to grab latest version and then it will update itself thereafter.
# LOL ok so the version is marked as 15.2.1 while the file shows 71.1?! oh sonos...
# release notes: https://support.sonos.com/en/article/release-notes-for-sonos-s2
url "https://www.sonos.com/en-us/redir/controller_software_mac2"
name 'Sonos S2'
homepage 'https://support.sonos.com/s/sonos-s2-overview?language=en_US'
# Sonos S2 compatibility: https://support.sonos.com/s/article/4786?language=en_US
auto_updates true
app 'Sonos.app'
# this is the release notes page (can see latest release here too)
appcast 'https://support.sonos.com/en/article/release-notes-for-sonos-s2'
zap trash: [
'~/Library/Application Support/SonosV2',
'~/Library/Application Support/com.sonos.macController2'
]
end
|
class PastExam < ApplicationRecord
belongs_to :course
belongs_to :uploader, class_name: :User
mount_base64_uploader :file, PastExamUploader
def serializable_hash(options = nil)
options = options.try(:dup) || {}
super({ **options, except: [:uploader_id, :course_id] }).tap do |result|
result[:uploader] = uploader
result[:course] = course
end
end
end
|
class DeleteColumnOnComments < ActiveRecord::Migration[6.0]
def change
remove_column :comments, :user_park_id, :integer
end
end
|
module Exercise
module Fp
class << self
# Обратиться к параметрам фильма можно так:
# film["name"], film["rating_kinopoisk"], film["rating_imdb"],
# film["genres"], film["year"], film["access_level"], film["country"]
def rating(array)
filtered_ratings = array.reject { |film| film['country'].nil? || film['country'].split(',').size < 2 }
.map { |film| film['rating_kinopoisk'].to_f }
.reject(&:zero?)
return 0 if filtered_ratings.empty?
filtered_ratings.reduce(:+) / filtered_ratings.size
end
def chars_count(films, threshold)
films.select { |film| film['rating_kinopoisk'].to_f >= threshold }
.map { |film| film['name'].count('и') }
.reduce(:+)
end
end
end
end
|
# EventHub module
module EventHub
# Message class
class Message
include Helper
VERSION = "1.0.0".freeze
# Headers that are required (value can be nil) in order to pass valid?
REQUIRED_HEADERS = [
"message_id",
"version",
"created_at",
"origin.module_id",
"origin.type",
"origin.site_id",
"process.name",
"process.step_position",
"process.execution_id",
"status.retried_count",
"status.code",
"status.message"
].freeze
attr_accessor :header, :body, :raw, :vhost, :routing_key
# Build accessors for all required headers
REQUIRED_HEADERS.each do |header|
name = header.tr(".", "_")
define_method(name) do
self.header.get(header)
end
define_method("#{name}=") do |value|
self.header.set(header, value)
end
end
def self.from_json(raw)
data = JSON.parse(raw)
Message.new(data.get("header"), data.get("body"), raw)
rescue => e
Message.new(
{
"status" =>
{
"code" => STATUS_INVALID,
"message" => "JSON parse error: #{e}"
}
},
{
"original_message_base64_encoded" => Base64.encode64(raw)
},
raw
)
end
def initialize(header = nil, body = nil, raw = nil)
@header = header || {}
@body = body || {}
@raw = raw
# set message defaults, that we have required headers
@header.set("message_id", UUIDTools::UUID.timestamp_create.to_s, false)
@header.set("version", VERSION, false)
@header.set("created_at", now_stamp, false)
@header.set("origin.module_id", "undefined", false)
@header.set("origin.type", "undefined", false)
@header.set("origin.site_id", "undefined", false)
@header.set("process.name", "undefined", false)
@header.set("process.execution_id",
UUIDTools::UUID.timestamp_create.to_s, false)
@header.set("process.step_position", 0, false)
@header.set("status.retried_count", 0, false)
@header.set("status.code", STATUS_INITIAL, false)
@header.set("status.message", "", false)
end
def valid?
# check for existence and defined value
REQUIRED_HEADERS.all? do |key|
@header.all_keys_with_path.include?(key) &&
!send(key.tr(".", "_").to_sym).nil?
end
end
def success?
status_code == STATUS_SUCCESS
end
def retry?
status_code == STATUS_RETRY
end
def initial?
status_code == STATUS_INITIAL
end
def retry_pending?
status_code == STATUS_RETRY_PENDING
end
def invalid?
status_code == STATUS_INVALID
end
def schedule?
status_code == STATUS_SCHEDULE
end
def schedule_retry?
status_code == STATUS_SCHEDULE_RETRY
end
def schedule_pending?
status_code == STATUS_SCHEDULE_PENDING
end
def to_json
{"header" => header, "body" => body}.to_json
end
def to_s
"Msg: process " \
"[#{process_name}, #{process_step_position}, #{process_execution_id}]" \
", status [#{status_code},#{status_message},#{status_retried_count}]"
end
# copies the message and set's provided status code (default: success),
# actual stamp, and a new message id
def copy(status_code = STATUS_SUCCESS)
# use Marshal dump and load to make a deep object copy
copied_header = Marshal.load(Marshal.dump(header))
copied_body = Marshal.load(Marshal.dump(body))
copied_header.set("message_id", UUIDTools::UUID.timestamp_create.to_s)
copied_header.set("created_at", now_stamp)
copied_header.set("status.code", status_code)
Message.new(copied_header, copied_body)
end
def append_to_execution_history(processor_name)
header.set("execution_history", []) unless
header.get("execution_history")
header.get("execution_history") << \
{"processor" => processor_name, "timestamp" => now_stamp}
end
def self.translate_status_code(code)
STATUS_CODE_TRANSLATION[code]
end
end
end
|
task :guard => :"guard:default"
namespace :guard do
desc "Run guard with the default adapter"
task :default do
system "guard"
end
desc "Run guard in WIP mode with the default adapter"
task :wip do
system "GUARD_MODE=wip guard"
end
desc "Run guard with the HTTP adapter"
task :http do
system "HARVEST_INTERFACE=http guard"
end
desc "Run guard with the web adapter"
task :web do
system "HARVEST_INTERFACE=web guard"
end
namespace :http do
desc "Run guard in WIP mode with the HTTP adapter"
task :wip do
system "GUARD_MODE=wip HARVEST_INTERFACE=http guard"
end
end
namespace :web do
desc "Run guard in WIP mode with the web adapter"
task :wip do
system "GUARD_MODE=wip HARVEST_INTERFACE=web guard"
end
end
end |
#!/usr/bin/env ruby
require 'bundler/setup'
require 'rubygems'
require 'sinatra'
require 'json'
require 'logger'
CONFIG_LOCATION = '/etc/nagios/conf.d/'.freeze
# Initialize logger
class Mylog
def self.log
if @logger.nil?
@logger = Logger.new STDOUT
@logger.level = Logger::DEBUG
@logger.datetime_format = '%Y-%m-%d %H:%M:%S '
end
@logger
end
end
def build_host_config(config_parameters)
"define host {\n"\
' address ' + config_parameters['ip'].to_s + "\n"\
" check_command check-host-alive\n"\
' host_name ' + config_parameters['hostname'].to_s + "\n"\
' hostgroups ' + config_parameters['hostgroups'].to_s + "\n"\
" max_check_attempts 5\n"\
" use generic-host\n"\
"}\n"
end
def build_service_configs(config_parameters)
service_config_string = ''
config_parameters['services'].each do |service|
service_config_string << "define service {\n"
service_config_string << " host_name #{config_parameters['hostname']}\n"
service.each do |key, value|
service_config_string << ' ' + key.to_s + ' ' + value.to_s + "\n"
end
service_config_string << "}\n"
end
service_config_string
end
def check_config
`nagios -v /etc/nagios/nagios.cfg`
$?
end
def restart_nagios
`systemctl restart nagios`
$?
end
delete '/:host' do
config_filepath = "#{CONFIG_LOCATION}#{params[:host]}.cfg"
if File.exist?(config_filepath)
begin
File.delete(config_filepath)
if restart_nagios == 0
status 200
Mylog.log.info 'restart of nagios successful return 200'
else
status 500
Mylog.log.error 'restart of nagios failed return 500'
end
rescue => e
status 500
Mylog.log.error "error deleting file, received exception #{e.message} return 500"
end
else
status 404
Mylog.log.info "config file #{config_filepath} does not exist, returning 404"
end
end
post '/new' do
config_parameters = JSON.parse(request.body.read)
host_config_string = build_host_config(config_parameters)
service_config_string = build_service_configs(config_parameters)
config_filepath = "#{CONFIG_LOCATION}#{config_parameters['hostname']}.cfg"
if File.exist?(config_filepath)
status 409
Mylog.log.info "config file #{config_filepath} already exist, returning 409"
else
begin
config_file = File.new(config_filepath, 'w')
config_file.puts(service_config_string)
config_file.puts(host_config_string)
config_file.close
rescue => e
status 500
Mylog.log.error "error creating file, received exception #{e.message} return 500"
end
if check_config == 0
Mylog.log.info 'config check passed, restarting nagios services'
if restart_nagios == 0
status 200
Mylog.log.info 'restart of nagios successful return 200'
else
status 500
Mylog.log.error 'restart of nagios failed return 500'
end
else
status 400
Mylog.log.error 'config check failed, did not restart nagios services return 400'
File.delete(config_filepath)
end
end
end
|
require 'spec_helper'
describe 'bluepill' do
let(:facts) do
{
:operatingsystem => 'CentOS',
:operatingsystemrelease => '6.3'
}
end
context 'default parameters' do
it do
should contain_bluepill__rsyslog
should contain_package('activesupport').with({ :provider => 'gem' })
should contain_package('bluepill').with({ :provider => 'gem' })
should contain_file('/var/run/bluepill')
should include_class('r9util::rubygems')
end
end
context 'without rsyslog' do
let(:params) do
{ :use_rsyslog => false }
end
it { should_not contain_bluepill__rsyslog }
end
context 'with UNDEFINED rubygems class' do
let(:params) do
{ :rubygems_class => 'UNDEFINED' }
end
it do
should_not include_class('r9util::rubygems')
should_not include_class('UNDEFINED')
end
end
context 'with custom rubygems class' do
let(:pre_condition) do "class foo{}" end
let(:params) do
{ :rubygems_class => 'foo' }
end
it do
should include_class('foo')
end
end
end
|
class CreateConcepts < ActiveRecord::Migration
def change
create_table :concepts do |t|
t.string :name
t.float :percentage
t.float :amount
t.string :code
t.float :top
t.timestamps
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/>.
#
# These class attributes behave something like the class
# inheritable accessors. But instead of copying the hash over at
# the time the subclass is first defined, the accessors simply
# delegate to their superclass unless they have been given a
# specific value. This stops the strange situation where values
# set after class definition don't get applied to subclasses.
class Class
def superclass_delegating_reader(*names)
class_name_to_stop_searching_on = self.superclass.name.blank? ? "Object" : self.superclass.name
names.each do |name|
class_eval <<-EOS
def self.#{name} # def self.only_reader
if defined?(@#{name}) # if defined?(@only_reader)
@#{name} # @only_reader
elsif superclass < #{class_name_to_stop_searching_on} && # elsif superclass < Object &&
superclass.respond_to?(:#{name}) # superclass.respond_to?(:only_reader)
superclass.#{name} # superclass.only_reader
end # end
end # end
def #{name} # def only_reader
self.class.#{name} # self.class.only_reader
end # end
def self.#{name}? # def self.only_reader?
!!#{name} # !!only_reader
end # end
def #{name}? # def only_reader?
!!#{name} # !!only_reader
end # end
EOS
end
end
def superclass_delegating_writer(*names)
names.each do |name|
class_eval <<-EOS
def self.#{name}=(value) # def self.only_writer=(value)
@#{name} = value # @only_writer = value
end # end
EOS
end
end
def superclass_delegating_accessor(*names)
superclass_delegating_reader(*names)
superclass_delegating_writer(*names)
end
end
|
class User < ApplicationRecord
# Include default users modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :creator, foreign_key: :creator_id, class_name: 'User', optional: true
has_and_belongs_to_many :roles
has_one :user_profile
has_many :plans
has_many :hubs
has_many :merchant
has_many :consignments
accepts_nested_attributes_for :user_profile, update_only: true
# Set user gender
enum gender: { male: 1, female: 2, others: 3 }
# Set user status
enum status: { active: 1, block: 0 }
# validation
validates :email, :first_name, :last_name, :phone_number, presence: true
validates :email, uniqueness: true
def full_name
"#{self.first_name} #{self.last_name}"
end
# prevent from login if user is inactive
def active_for_authentication?
super && self.active? # i.e. super && self.active
end
def inactive_message
'Sorry, this account has been deactivated.'
end
# generating array of symbols of currently logged in user
def role_symbols
(roles || []).map { |r| r.title.to_sym }
end
# checking the user has the role or not
def has_role?(role)
role_symbols.include? role
end
end
|
class ChatRoomsController < ApplicationController
def index
@user = current_user
# @me = User.find(params[:user_id])
@profile = current_user.profile
@chat_rooms = @user.owned_chatrooms + @user.chat_rooms
# @chat_room = @me.user_chat_rooms
# @user_name = @user.profile.fname
if params[:language]
@result_skills = Skill.where("lower(language) LIKE ?", "%#{params[:language].downcase}%")
@result_users = User.joins(:user_skills, :skills).where(user_skills: {skill_id: @result_skills}).order('skills.rating ASC').uniq
else
@skills = Skill.all
end
end
def show
@user = current_user
@profile = current_user.profile
@chat_room = ChatRoom.includes(:messages).find_by(id: params[:id])
# if user owned_chatrooms then only he/she can check that chat room and write a message
# chat_room
# id. user_id
# 12 8
# user_chat_room
# chat_room_id user_id
# 12 9
#. 12 27
#. 12 32
# @chat_room.users.map(&:id)
if @chat_room.owner.id == @user.id || @chat_room.user_chat_rooms.map(&:user_id).include?(@user.id)
# # [9, 27, 32]
@message = Message.new
else
redirect_to chat_rooms_path
end
end
def new
@user = User.find(params[:user_id])
# User.find_by(id: params[:user_id])
@profile = current_user.profile
@chat_room = ChatRoom.new
end
def create
# @user = current_user
@user = User.find(params[:user_id])
@profile = current_user.profile
@chat_room = current_user.owned_chatrooms.build(chat_room_params)
if @chat_room.save
@user.user_chat_rooms.create(chat_room_id: @chat_room.id)
flash[:success] = 'Chat room added!'
redirect_to chat_rooms_path
else
render 'new'
end
end
def destroy
@chat_room = ChatRoom.find(params[:id])
# @chat_room = current_user.owned_chatrooms.find(params[:id])
@chat_room.destroy
redirect_to chat_rooms_path
end
private
def chat_room_params
params.require(:chat_room).permit(:title)
end
end
|
class ActsAsLoggable::UserAction < ActiveRecord::Base
attr_accessible :action
has_many :logs
def to_s
self.action
end
end
|
class AddFromShareToSharePrizes < ActiveRecord::Migration
def change
add_column :share_prizes, :from_share, :string
end
end
|
require "libblacklist/version"
require 'ffi'
module Libblacklist
module Action
AUTH_OK = 0
AUTH_FAIL = 1
ABUSIVE_BEHAVIOUR = 2
BAD_USER = 3
end
module LibBlacklist
extend FFI::Library
ffi_lib 'blacklist'
attach_variable :errno, :int
# struct blacklist *blacklist_open(void)
attach_function :blacklist_open, [], :pointer
# void blacklist_close(struct blacklist *)
attach_function :blacklist_close, [:pointer], :void
# int blacklist(int action, int fd, char *msg)
attach_function :blacklist, [:int, :int, :string], :int
# int blacklist_r(struct blacklist *, int action, int fd, char *msg)
attach_function :blacklist_r, [:pointer, :int, :int, :string], :int
# int blacklist_sa(int action, int fd, struct sockaddr *, socklen_t salen, char *msg)
attach_function :blacklist_sa, [:pointer, :int, :int, :pointer, :size_t, :string], :int
# int blacklist_sa_r(struct blacklist *, int action, int fd, struct sockaddr *, socklen_t salen, char *msg)
attach_function :blacklist_sa_r, [:pointer, :int, :int, :pointer, :size_t, :string], :int
end
def open
handle = LibBlacklist.blacklist_open
if handle.null?
raise SystemCallError.new("blacklist_open", LibBlacklist.errno)
else
return FFI::AutoPointer.new(handle, LibBlacklist.method(:blacklist_close))
end
end
def close(handle)
raise ArgumentError unless handle.kind_of? FFI::Pointer
LibBlacklist.blacklist_close(handle)
end
def blacklist(action, io, msg)
action = Integer(action)
fd = io.fileno
msg = msg.to_s
LibBlacklist.blacklist(action, fd, msg)
end
def blacklist_r(handle, action, io, msg)
raise ArgumentError unless handle.kind_of? FFI::Pointer
action = Integer(action)
fd = io.fileno
msg = msg.to_s
LibBlacklist.blacklist_r(handle, action, fd, msg)
end
def blacklist_sa(action, io, sockaddr, msg)
action = Integer(action)
fd = io.fileno
sa = sockaddr.to_sockaddr
msg = msg.to_s
LibBlacklist.blacklist_sa(action, fd, sa, sa.bytesize, msg)
end
def blacklist_sa_r(handle, action, io, sockaddr, msg)
raise ArgumentError unless handle.kind_of? FFI::Pointer
action = Integer(action)
fd = io.fileno
sa = sockaddr.to_sockaddr
msg = msg.to_s
LibBlacklist.blacklist_sa(handle, action, fd, sa, sa.bytesize, msg)
end
module_function :open
module_function :close
module_function :blacklist
module_function :blacklist_r
module_function :blacklist_sa
module_function :blacklist_sa_r
end
class BlacklistD
def initialize
@handle = Libblacklist.open
end
def close
Libblacklist.close(@handle)
@handle = nil
end
def auth_ok(io, addr: nil)
blacklist(io: io, addr: addr, action: Libblacklist::Action::AUTH_OK, msg: "ok")
end
def auth_fail(io, addr: nil)
blacklist(io: io, addr: addr, action: Libblacklist::Action::AUTH_FAIL, msg: "auth fail")
end
def abusive(io, addr: nil)
blacklist(io: io, addr: addr, action: Libblacklist::Action::ABUSIVE_BEHAVIOUR, msg: "abusive")
end
def bad_user(io, addr: nil)
blacklist(io: io, addr: addr, action: Libblacklist::Action::BAD_USER, msg: "bad user")
end
private
def blacklist(io:, action:, addr:, msg:)
raise "Closed" unless @handle
if addr
Libblacklist.blacklist_sa_r(@handle, action, io, addr, msg)
else
Libblacklist.blacklist_r(@handle, action, io, msg)
end
end
end
|
=begin
AUTOSALVATAGGIO v1.0
Questo script serve per salvare automaticamente il gioco in determinate occasioni.
=end
#==============================================================================
# ** Vocab
#==============================================================================
module Vocab
def self.autosave_success
'Salvataggio automatico eseguito.';
end
def self.autosave_failed
'Errore di salvataggio!';
end
def self.autosave_option
'Salvataggio automatico';
end
def self.autosave_help
'Attiva o disattiva il salvataggio automatico|in determinate situazioni del gioco.';
end
end
#==============================================================================
# ** Game_System
#==============================================================================
class Game_System
attr_accessor :autosave_setting
# determina se l'autosalvataggio è abilitato
def autosave_enabled?
@autosave_setting;
end
end
#==============================================================================
# ** Game_Temp
#==============================================================================
class Game_Temp
attr_accessor :temp_fog
end
#==============================================================================
# ** DataManager
#==============================================================================
module DataManager
# Alias dei metodi
# noinspection RubyResolve
class << self
alias sgwr_autos save_game_without_rescue
alias lgwr_autos load_game_without_rescue
end
# avvia autosalvataggio
# forced: salva anche se l'opzione è disattivata
def self.autosave(forced = false, show_popup = true)
return if @actual_saveslot.nil?
return unless forced or $game_system.autosave_enabled?
autosave_result = save_game(@actual_saveslot)
if autosave_result
Logger.info "✔ Autosalvataggio riuscito"
else
Logger.error "❌ Autosalvataggio fallito"
end
if show_popup
autosave_result ? popup_save_ok : popup_save_failed
end
autosave_result
end
# mostra il popup di salvataggio riuscito
def self.popup_save_ok
return unless SceneManager.scene_is? Scene_Map
$game_map.add_popup([1254, Vocab.autosave_success], Tone.new(0, 180, 0, 100))
end
# mostra il popup di salvataggio fallito
def self.popup_save_failed
return unless SceneManager.scene_is? Scene_Map
$game_map.add_popup([1254, Vocab.autosave_failed], Tone.new(180, 0, 0, 100))
end
# Execute Save (No Exception Processing)
def self.save_game_without_rescue(index)
sgwr_autos(index)
@actual_saveslot = index
return true
end
# Execute Load (No Exception Processing)
def self.load_game_without_rescue(index)
lgwr_autos(index)
@actual_saveslot = index
return true
end
end
#==============================================================================
# ** Game_Interpreter
#==============================================================================
class Game_Interpreter
# Prenota l'autosalvataggio quando tutti gli eventi sono terminati.
def autosave(forced = false)
return unless forced or $game_system.autosave_enabled?
$game_map.prepare_to_autosave = true
end
end
#==============================================================================
# ** Game_Map
#==============================================================================
class Game_Map
alias h87_autosave_update update unless $@
alias h87_autosave_initialize initialize unless $@
# flag per preparazione all'autosave una volta
# finiti gli eventi.
attr_accessor :prepare_to_autosave
def initialize
h87_autosave_initialize
@prepare_to_autosave = false
end
def update
h87_autosave_update
check_autosave
end
# chiama un autosave forzato quando gli eventi non vengono
# eseguiti.
def check_autosave
return if @interpreter.running?
return unless @prepare_to_autosave
@prepare_to_autosave = false
DataManager.autosave(true)
end
end
#==============================================================================
# ** Option
#==============================================================================
class Option
# aggiorna lo stato dell'autosalvataggio
def update_autosave(value)
$game_system.autosave_setting = value
end
# ottiene lo stato dell'autosalvataggio
def get_autosave
$game_system.autosave_enabled?
end
end
H87Options.push_game_option(
{:type => :switch, #tipo variabile
:text => Vocab.autosave_option, #testo mostrato
:help => Vocab.autosave_help, #descrizione
:method => :update_autosave,
:val_mt => :get_autosave,
:on => 'ON', :off => 'OFF'
}
) |
class CheckInput
def initialize(inp)
begin
inp = inp.downcase
if inp.empty?
puts 'Entry was empty.'.red
puts ' '
RepeatLetters.new
end
rescue
end
case inp.to_s
when 'quit', 'q', 'exit'
puts 'Quitting, thank you come again.'.light_blue
exit
end
end
end
|
def source
'"Here are some beers \u{1f37a} \u{1f37a} \u{1f37a} and pizzas \u{1f355} \u{1f355} \u{1f355}"'
end
def expected_tokens
[
{
type: 'T_DOUBLE_QUOTE',
value: '"'
},
{
type: 'T_LITERAL_STRING',
value: 'Here are some beers '
},
{
type: 'T_QUOTED_UNICODE_CHAR_OPEN',
value: '\\u{'
},
{
type: 'T_UNICODE_CHAR',
value: '1f37a'
},
{
type: 'T_QUOTED_UNICODE_CHAR_CLOSE',
value: '}'
},
{
type: 'T_LITERAL_STRING',
value: ' '
},
{
type: 'T_QUOTED_UNICODE_CHAR_OPEN',
value: '\\u{'
},
{
type: 'T_UNICODE_CHAR',
value: '1f37a'
},
{
type: 'T_QUOTED_UNICODE_CHAR_CLOSE',
value: '}'
},
{
type: 'T_LITERAL_STRING',
value: ' '
},
{
type: 'T_QUOTED_UNICODE_CHAR_OPEN',
value: '\\u{'
},
{
type: 'T_UNICODE_CHAR',
value: '1f37a'
},
{
type: 'T_QUOTED_UNICODE_CHAR_CLOSE',
value: '}'
},
{
type: 'T_LITERAL_STRING',
value: ' and pizzas '
},
{
type: 'T_QUOTED_UNICODE_CHAR_OPEN',
value: '\\u{'
},
{
type: 'T_UNICODE_CHAR',
value: '1f355'
},
{
type: 'T_QUOTED_UNICODE_CHAR_CLOSE',
value: '}'
},
{
type: 'T_LITERAL_STRING',
value: ' '
},
{
type: 'T_QUOTED_UNICODE_CHAR_OPEN',
value: '\\u{'
},
{
type: 'T_UNICODE_CHAR',
value: '1f355'
},
{
type: 'T_QUOTED_UNICODE_CHAR_CLOSE',
value: '}'
},
{
type: 'T_LITERAL_STRING',
value: ' '
},
{
type: 'T_QUOTED_UNICODE_CHAR_OPEN',
value: '\\u{'
},
{
type: 'T_UNICODE_CHAR',
value: '1f355'
},
{
type: 'T_QUOTED_UNICODE_CHAR_CLOSE',
value: '}'
},
{
type: 'T_DOUBLE_QUOTE',
value: '"'
}
]
end
def expected_ast
{
__type: 'program',
body: [
{
__type: 'literal-string',
value: "Here are some beers \u{1f37a} \u{1f37a} \u{1f37a} and pizzas \u{1f355} \u{1f355} \u{1f355}"
}
]
}
end
load 'spec_builder.rb'
|
RESPONSE = '{"gladiator":{"personal_data":{"name": "Staros", "gender":"male", "age":27},
"skills":["swordsman","spearman","bowmen"],
"amunition":
{"weapon":
{"trident":{"damage":"7", "ability":"long-range strike"},
"net":{"damage":"1", "ability":"stack"},
"dagger":{"damage":"4"}},
"armor":[{"head":"no","torso":"belt","limbs":"braser"}]
}}}'
response = JSON.parse(RESPONSE)
Gladiator = Struct.new(*response["gladiator"].keys.collect(&:to_sym)) do
def how_old?
p "His age is #{personal_data["age"]}"
end
def self.print_how_old?
end
def spearman?
p "Our gladiadiator #{skills.select{|x| x== "spearman" }[0]}! He will make a good retiarius"
end
def have_weapon?
weapon = []
amunition.each{|x| Hash[*x].each_pair{|key, value| if key == "weapon" then value.each_pair{|key, value| weapon<<key} end}}
p "Glagiator #{personal_data["name"]} is carrying a #{weapon.join(", ")}"
end
def generate_actions(data, actions)
data.each do |k, v|
if v.is_a?(Hash)
v.each do |k, v|
if k == "name"
define_singleton_method ("greeting") do
p "Going to death #{v}, salute you!"
end
elsif k == "weapon"
v.each_pair do |k, v|
actions.each_pair do|action, way|
define_singleton_method ("#{action}_vis_#{k}") do
way.call(k, v)
end
end
end
end
end
end
end
end
end
|
require_relative 'servo'
class Agent
attr_accessor :Q
def initialize(servo_1, servo_2, nb_actions, alpha, epsilon, gamma)
@Q = Array.new(servo_1.steps*servo_2.steps){Array.new(nb_actions) {rand}}
@initial_state = state servo_1, servo_2
@alpha = alpha
@epsilon = epsilon
@gamma = gamma
end
def find_best_action(state)
max = -99999
best_action = 0
@Q[state].each_with_index do |r, i|
if r > max
max = r
best_action = i
end
end
best_action
end
def state(servo_1, servo_2)
servo_1.state * servo_2.steps + servo_2.state
end
def find_action(state)
rand < @epsilon ? rand(4) : find_best_action(state)
end
def update(state, action, reward, new_state)
@epsilon *= 0.999
@Q[state][action] += @alpha * (reward + @gamma * @Q[new_state][find_best_action(new_state)] - @Q[state][action])
end
end |
class Api::V1::MerchantItemsController < ApplicationController
def index
merchant = Merchant.find(params[:id])
render json: ItemSerializer.new(merchant.items)
end
def show
item = Item.find(params[:id])
merchant = item.merchant.id
render json: MerchantSerializer.new(Merchant.find(merchant))
end
end
|
require_relative 'internal'
require_relative 'twitter'
require_relative 'rss'
require_relative 'configuration'
module Noizee
class Gestalt
def listen
if events.empty? then
sources.each do |source|
events.concat source.get
end
end
events.sort_by!(&:created_at).reverse!
sleep 1
!events.empty?
end
def pop
events.pop
end
def events
@events ||= Array.new
end
def sources
@sources || setup_sources
end
def setup_sources
@sources = [Noizee::Internal.new]
{
twitter: Noizee::Twitter,
rss: Noizee::RSS
}.each_pair do |key, klass|
@sources << klass.new if Noizee::Configuration.has_key? key
end
@sources
end
end
end
|
#! /usr/bin/env ruby-rvm-env 2.1
require 'pathname'
require_relative '../utility/lib/executor'
require_relative '../utility/lib/ruby_version'
class AllProjectPuller
def call
root_dir = "#{Dir.home}/Sites"
all_directories = Pathname.glob("#{root_dir}/apps/*") +
Pathname.glob("#{root_dir}/gems/*").reverse +
Pathname.glob("#{root_dir}/configs") +
Pathname.glob("#{root_dir}/utilities/*") +
Pathname.glob("#{root_dir}/scripts")
SmartDirFilter.new.call(all_directories).each do |d|
fork do
Dir.chdir(d) do
ProjectPuller.new.call
end
end
end
Process.waitall
end
end
module PAP
ROOT = Pathname(Dir.home).join("Sites/pap")
end
class SmartDirFilter
def call(dirs)
if updated_in_last_60_minutes?
dirs_with_errors(dirs)
else
dirs
end
end
def updated_in_last_60_minutes?
PAP::ROOT.mtime > Time.now - 60 * 60
end
def dirs_with_errors(dirs)
dirs.select{|d| error_logs.include?(d.basename.to_s) }
end
def error_logs
PAP::ROOT.children(false).map{|f| f.to_s.match("error") && f.to_s.sub('_error.log','')}.compact
end
end
class ProjectPuller
def call
start_timer
puts "#{Dir.pwd} => #{gemset}" if ENV["DEBUG"] == "1"
clear_logs
output_string = "#{dir.ljust(50, '_')} => "
from_branch development_branch do
ex('git pull')
setup_app
end
output_string += (@executions.any?(&:error?) ? "Fail" : "Pass")
rescue => e
output_string += "Fail"
log_error_with_backtrace(e.message, e.backtrace)
ensure
stop_timer
output_string += " (time: #{timer}s)"
puts output_string
end
def setup_app
run_setup_script ||
old_setup
end
def old_setup
install_gems
Dir.chdir(migration_dir) do
migrate
end
end
def install_gems
if File.exist?("Gemfile")
ex "rvm #{gemset} do bundle install"
end
end
def run_setup_script
ex "rvm #{gemset} do bin/setup" if File.exist?("bin/setup")
end
def migrate
if ['../../db/schema.rb', 'db/schema.rb'].any?{|f| Dir.exist?(f)}
ex "rvm #{gemset} do rake db:migrate db:test:prepare", ignore: "sec:"
end
end
def gemset
@gemset = RubyVersion.current
end
def migration_dir
Dir.exist?('spec/dummy') ? 'spec/dummy' : '.'
end
def from_branch(branch, &block)
original_branch = g_branchname
stash_changes
clear_branch
ex "git co #{branch}" unless branch == original_branch
yield
ensure
clear_branch
ex "git co #{original_branch}" unless branch == original_branch
unstash
end
def development_branch
return @development_branch if @development_branch
branches = ex "git branch --list {master,dev}"
@development_branch = %w[dev master].detect{|b| branches.include?(b)}
end
def g_branchname
%x{git rev-parse --abbrev-ref HEAD 2>/dev/null}.gsub(/\n/, '')
end
def stash_changes
if !git_changes.empty?
ex 'git stash clear; git stash'
end
end
def unstash
if !git_changes.empty?
ex 'git stash pop'
end
end
def git_changes
@git_changes ||= ex "git st --porcelain --untracked-files=no | tr -d ' '"
end
def clear_branch
ex 'git reset --hard'
ex 'git co .'
end
def dir
@dir ||= Dir.pwd
end
def ex(*args)
execution = Executor.new(self, *args)
executions << execution
execution.call
end
def executions
@executions ||= Array.new
end
def log(text)
File.open(log_path, 'a') do |f|
f.write "#{text}\n\n"
end
end
def log_error(text)
File.open(error_log_path, 'a') do |f|
f.write "#{text}"
end
end
def log_error_with_backtrace(message, trace)
File.open(error_log_path, 'a') do |f|
f.write "#{message}"
f.write "#{trace}"
end
end
def clear_logs
ex "mkdir -p #{PAP::ROOT}"
File.delete(log_path) if File.exist?(log_path)
File.delete(error_log_path) if File.exist?(error_log_path)
end
def log_path
"#{PAP::ROOT}/#{self}.log"
end
def error_log_path
"#{PAP::ROOT}/#{self}_error.log"
end
def to_s
dir.gsub(/.*\/(.*)/, '\1')
end
def start_timer
@start_time = Time.now
end
def stop_timer
@stop_time = Time.now
end
def timer
@stop_time - @start_time
end
end
AllProjectPuller.new.call
|
class RStoriesController < ApplicationController
# GET /r_stories/new
def new
@r_story = RStory.new
end
# POST /r_stories
def create
#story = RStory.new(params[:story])
story = RStory.new(story_params)
story.tags = params[:tags].join(', ')
story.save!
render plain: story.inspect
end
private
def story_params
params.require(:r_story)
.permit(:title, :content, :published, :tags)
end
end
|
#!/usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'
require 'optparse'
require 'daemons'
require 'fileutils'
require File.expand_path(File.join(File.dirname(__FILE__), 'lib/hubspot_config'))
PWD = File.expand_path(File.dirname(__FILE__))
PIDS_DIR_PATH = File.join(PWD, 'pids')
CURRENT_MODE_FILE_PATH = File.join(PWD, 'pids', 'hs-static-current-mode')
options = {}
opt_parser = OptionParser.new do |opt|
opt.banner = "Usage: hs_static COMMAND [OPTIONS]"
opt.separator ""
opt.separator "Commands"
opt.separator " start: Start static server (in the background)"
opt.separator " run: Start static server, but run in the forground (so you can see the log immediately)"
opt.separator " stop: Stop static server"
opt.separator " restart: Restart static server"
opt.separator " log: Tail the server log (useful when you are running the server in the background)"
opt.separator ""
opt.separator " precompile: Precompiles assets to a target directory (does _not_ run the static server)."
opt.separator " precompile_assets_only: Precompiles assets to a target directory (doesn't build bundle html or concatenate files)."
opt.separator ""
opt.separator " update_deps: Downloads the latest dependencies for a project."
opt.separator ""
opt.separator " jasmine: Runs jasmine tests for the projects specified via '-p'"
opt.separator " clean: Convenience command that deletes everything in a target directory"
opt.separator ""
opt.separator "Options"
opt.on("-m", "--mode MODE", "Which mode, local, compressed, or precompiled?") do |mode|
options[:mode] = mode
end
opt.on("-t", "--target PRECOMPILED_FOLDER", "Specify the directory where you want precompiled assets to go. Required for the precompile and clean commands.") do |target_static_dir|
options[:target_static_dir] = target_static_dir
end
opt.on("-b", "--build-name BUILD_NAME", "Specify an build name while precompiling. Note that you must specify each as <project_name>:<build_name>") do |build_name|
parts = build_name.split ':'
raise "Each build name must inclue the project name and build name joined by a colon (eg. <project_name>:<build_name>), #{build_name} is invalid." unless parts.length == 2
project_name, build_name = parts
options[:build_names] ||= {}
options[:build_names][project_name] = build_name
end
opt.on("-p", "--static-project PROJECTS", "Adds one or more static folders to watch (this paramater can be included multiple times). This is in addition to static_projects set in ~/.hubspot/config.yaml.") do |static_project|
options[:static_projects] ||= []
options[:static_projects] << static_project
end
opt.on("-P", "--port PORT", "What port the static server runs on. This overrides the port set in ~/.hubspot/config.yaml.") do |port|
options[:port] = port
end
opt.on("-r", "--restrict PROJECT", "Only builds precompiled assets for a single project (the other projects are still used as dependencies).") do |restricted_project|
options[:restricted_project] = restricted_project
end
opt.on("-l", "--limit_to FILES", "Only precompiles the files listed (comma separated, no directories needed)") do |limit_to_files|
options[:limit_to_files] = limit_to_files
end
opt.on("-a", "--archive-dir DIR", "Custom location of the static acrhive (defaults to ~/.hubspot/static-archive/)") do |archive_dir|
options[:archive_dir] = archive_dir
end
opt.on("-e", "--extra-config CONFIG", "Fancy magical stuff... be wary.") do |extra_config|
options[:extra_config] = extra_config
end
opt.on("-c", "--clear-cache", "Clear the asset cache on startup.") do
options[:clear_cache] = true
end
opt.on("--production-builds-only", "Only use versions of dependencies that are deployed to production") do
options[:only_use_production_builds] = true
# Set it here so that the hubspot config instantiated in this process gets the config too
ENV['PROD_BUILDS_ONLY'] = '1'
end
opt.on("--temp CUSTOM_TEMP_FOLDER", "Specify a custom tmp folder") do |custom_temp_folder|
options[:custom_temp_folder] = custom_temp_folder
end
opt.on("--headless", "Flag to make jasmine tests run in a headless phantomjs browser") do
options[:headless] = true
end
opt.on("-h", "--help", "help") do
puts opt_parser
end
end
opt_parser.parse!
def clean_up_mode_param(mode)
mode.downcase!
case mode
when "dev", "development", "local"
"development"
when "compressed"
"compressed"
when "precompiled", "precompile", "prod", "production"
"precompiled"
else
raise "No such mode: #{mode}"
end
end
def write_current_mode(options)
Dir.mkdir PIDS_DIR_PATH unless File.directory?(PIDS_DIR_PATH)
File.open(CURRENT_MODE_FILE_PATH, 'w') do |f|
f.write(options[:mode])
end
end
def read_pid(path)
if File.exists? path
File.open path, 'r' do |f|
return f.read().strip
end
end
end
def kill_process_if_exists(pid, signal='SIGINT')
begin
Process.kill(signal, pid.to_i)
rescue Errno::ESRCH
puts "No such process exists: #{pid}"
else
puts "Killed process: #{pid}"
end
end
def process_exists?(pid)
return false unless pid
begin
Process.kill(0, pid.to_i)
rescue Errno::ESRCH
false
else
true
end
end
def delete_current_mode
FileUtils.rm(CURRENT_MODE_FILE_PATH) if File.exists? CURRENT_MODE_FILE_PATH
end
def get_current_mode
if File.exists? CURRENT_MODE_FILE_PATH
File.open CURRENT_MODE_FILE_PATH, 'r' do |f|
return f.read()
end
end
end
def command_pid_path
File.join(PWD, 'pids', 'hs-static-server.pid')
end
def server_pid_path
File.join(PWD, 'tmp', 'pids', 'server.pid')
end
def get_pids
pid_to_kill = read_pid command_pid_path
server_pid_to_kill = read_pid server_pid_path
return pid_to_kill, server_pid_to_kill
end
def delete_command_pid
FileUtils.rm(command_pid_path) if File.exists? command_pid_path
end
def delete_server_pid
FileUtils.rm(server_pid_path) if File.exists? server_pid_path
end
def check_if_already_running
current_mode = get_current_mode
command_pid, server_pid = get_pids
command_process_exists = process_exists? command_pid
server_process_exists = process_exists? server_pid
if current_mode and (command_process_exists or server_process_exists)
puts "The static daemon is already running (in #{current_mode} mode), you should stop or restart it."
Process.exit
else
# Delete any leftovers (eg. a "run" daemon that was killed with ctrl-c)
delete_current_mode
delete_command_pid
delete_server_pid
end
end
def shared_config_var(options)
vars = ''
if options[:extra_config]
config_string = options[:extra_config]
config_string.gsub!(/\\|"/) { |c| "\\#{c}" }
vars += " EXTRA_CONFIG=\"#{config_string}\""
end
vars += " ARCHIVE_DIR=\"#{options[:archive_dir]}\"" if options[:archive_dir]
vars += " PROD_BUILDS_ONLY=1" if options[:only_use_production_builds]
vars += " CUSTOM_TEMP_DIR=#{options[:custom_temp_folder]}" if options[:custom_temp_folder]
vars += " PORT=#{options[:port]}" if options[:port]
vars
end
def run_mode_vars(options)
mode = options[:mode]
target = options[:target_static_dir]
extra_vars = 'RUN_FROM_SCRIPT=1 '
extra_vars += " " + shared_config_var(options)
if mode == "precompiled" and target
extra_vars += "TARGET_STATIC_FOLDER=\"#{target}\" "
elsif mode == "precompiled" and not target
raise "You must specify a target static directory (--target) when in the precompiled mode"
end
extra_vars
end
def static_projects_var(options)
return '' unless options[:static_projects]
comma_separated_projects = options[:static_projects].join(', ')
"HUBSPOT_STATIC_PROJECTS=\"#{comma_separated_projects}\" "
end
def start(options, daemon_options)
write_current_mode options
hubspot_config = HubspotConfig.new
port = options[:port] || hubspot_config.port
puts "Starting static daemon on :#{port}"
$stdout.flush
extra_vars = run_mode_vars(options)
extra_vars += " " + static_projects_var(options)
application = Daemons.run_proc "hs-static-server", daemon_options do
exec "cd #{PWD}; #{extra_vars} rails server -d -p #{port}"
end
end
def run(options, daemon_options)
daemon_options[:ontop] = true
write_current_mode options
extra_vars = run_mode_vars options
extra_vars += " " + static_projects_var(options)
hubspot_config = HubspotConfig.new
port = options[:port] || hubspot_config.port
application = Daemons.run_proc "hs-static-server", daemon_options do
exec "cd #{PWD}; #{extra_vars} rails server -p #{port}"
end
end
def log(current_mode)
log_path = File.join(PWD, 'log', "#{current_mode}.log")
exec "tail -f #{log_path}"
end
def stop(current_mode)
pid_to_kill, server_pid_to_kill = get_pids
if server_pid_to_kill
kill_process_if_exists server_pid_to_kill, 9
delete_server_pid
end
if pid_to_kill
kill_process_if_exists pid_to_kill
delete_command_pid
end
delete_current_mode
end
def precompile_vars(options)
mode = options[:mode]
restricted_project = options[:restricted_project]
limit_to_files = options[:limit_to_files]
target = File.expand_path(options[:target_static_dir])
build_names = options[:build_names]
extra_vars = static_projects_var(options)
extra_vars += " " + shared_config_var(options)
extra_vars += " RESTRICT_TO=\"#{restricted_project}\"" if restricted_project
extra_vars += " LIMIT_TO=\"#{limit_to_files}\"" if limit_to_files
extra_vars += " TARGET_STATIC_FOLDER=\"#{target}\""
extra_vars += " RAILS_ENV=#{mode} "
if build_names
# Convert to <name>:<build>,<name2>:<build2>,...
build_name_string = build_names.map { |x,y| x + ':' + y }.join(',')
extra_vars += " BUILD_NAMES=#{build_name_string}"
end
extra_vars
end
def precompile_assets_only(options)
vars = precompile_vars(options)
unless system "#{vars} INGNORE_BUNDLE_DIRECTIVES=1 bundle exec ruby script/precompile_project_assets_and_munge_build_names.rb"
raise "Error procompiling assets"
end
end
def precompile(options)
vars = precompile_vars(options)
unless system "#{vars} bundle exec ruby script/precompile_project_assets_plus.rb"
raise "Error procompiling assets and bundle html"
end
end
def clean(options)
target = File.expand_path(options[:target_static_dir])
s = ''
while not ["y", "n"].include? s
print "Remove everything inside the #{target} folder? [Yn] "
s = $stdin.gets.chomp.downcase
end
if s == "y"
exec "rm -rf #{target}/*"
end
end
def clear_cache_if_needed(options)
clear_cache if options[:clear_cache]
end
def clear_cache
puts "\nClearing the static cache..."
system "rm -rf #{PWD}/tmp/cache"
end
def update_dependiences(options)
# HACK :(
ENV['SKIP_GATHERING_LOCAL_BUILD_NAMES'] = '1'
hubspot_config = HubspotConfig.new
local_archive = hubspot_config.local_static_archive
projects = options[:static_projects] || hubspot_config.static_project_paths
raise "No projects specified (use \"-p\" or add to static_projects in ~/.hubspot/conf.yaml)" unless projects
begin
projects.each do |project|
local_archive.update_dependencies_for project, { :served_projects_paths_set => Set.new(projects) }
end
rescue ArchiveDownloadError
puts "\nHTTP errors when downloading dependencies!"
rescue
puts "\nUnknown errors when downloading dependencies!\n"
raise
end
end
def run_jasmine_tests(options)
hubspot_config = HubspotConfig.new options
port = options[:port] || hubspot_config.port
headless = options[:headless] or false
base_jasmine_path = hubspot_config.served_projects_path_map['jasmine']
# Get the dep path if it isn't served locally
unless base_jasmine_path
base_jasmine_path = hubspot_config.served_dependency_path_map['jasmine']
end
unless base_jasmine_path
abort('Jasmine must be a dependecy for the projects you want to test (and remember to updates-deps and restart hs-static after adding that dep)')
end
if options[:restricted_project]
projects_to_test = [options[:restricted_project]]
else
projects_to_test = hubspot_config.static_projects_with_specs
end
projects_to_test.each do |project|
project_alias = hubspot_config.aliased_project_name(project)
jasmine_path = "#{base_jasmine_path}/static/"
# Interpolate jasmine build version (if jasmine isn't being served locally)
if not hubspot_config.static_project_names.include? 'jasmine'
jasmine_version = (hubspot_config.dependencies_for[project_alias] || {})['jasmine']
unless jasmine_version
abort("Jasmine must be a dependecy for the #{project} (and remember to updates-deps and restart hs-static after adding that dep)")
end
jasmine_path.gsub! '/static/', "/#{jasmine_version}/"
end
# If running a headless test during a build on jenkins
if headless && options[:mode] == 'precompiled'
project_path = hubspot_config.served_projects_path_map[project]
spec_prefix = "#{options[:target_static_dir]}/#{project}/static/test/"
spec_prefix.gsub! '/static/', "/static-#{options[:build_names][project]}/" if options[:build_names] and options[:build_names][project]
require File.expand_path(File.join(File.dirname(__FILE__), 'lib/hubspot_static_deps'))
# Grab the latest jasmine version on s3
static_deps = StaticDependencies::build_from_filesystem(project_path)
jasmine_version = static_deps.fetch_latest_static_build_name_for_project('jasmine')
jasmine_url_prefix = "http://#{DEFAULT_STATIC_DOMAIN}/jasmine/#{jasmine_version}/"
print "Trying url #{jasmine_url_prefix} for jasmine\n"
color_logs = false
path = "#{jasmine_url_prefix}test/ProjectSpecRunnerHeadless.html?project=#{project}"
puts "Running precompiled headless specs for #{project}:"
# So this runs phantonjs:
# - on a file in the jasmine project on the filesystem
# - using the lastest jasmine build on s3
# - against the spcs that are already precompiled from the build prcoess
cmd = "phantomjs #{jasmine_path}js/run_jasmine_test.coffee #{path} #{jasmine_url_prefix} #{spec_prefix} #{color_logs}"
print "\n", "cmd: #{cmd.inspect}", "\n\n"
exec cmd
# If running a headless test locally
elsif headless
url = "http://localhost:#{port}/jasmine/static/test/ProjectSpecRunnerHeadless.html?project=#{project}"
puts "Running headless specs for #{project}: #{url}"
local_jasmine_location = "http://localhost:#{port}/jasmine/static/"
local_spec_location = "http://localhost:#{port}/#{project}/static/test/"
cmd = "phantomjs #{jasmine_path}js/run_jasmine_test.coffee #{url} #{local_jasmine_location} #{local_spec_location}"
print "\n", "cmd: #{cmd.inspect}", "\n\n"
exec cmd
# If running tests in browser locally
else
url = "http://localhost:#{port}/jasmine/static/test/ProjectSpecRunner.html?project=#{project}"
puts "Opening jasmine spec runner: #{url}"
pid = spawn "open #{url}"
Process.detach pid
end
end
end
ENV['RAILS_ENV'] = options[:mode] = clean_up_mode_param(options[:mode] || 'local')
daemon_options = {
:app_name => "hs-static-server",
# :ARGV => ['start', '-f', '--', 'param_for_myscript']
:dir_mode => :script,
:dir => 'pids',
:multiple => false,
:ontop => false,
:mode => :load,
# :backtrace => true,
# :monitor => true
}
case ARGV[0]
when "start"
clear_cache_if_needed options
check_if_already_running
start options, daemon_options
when "run"
clear_cache_if_needed options
check_if_already_running
run options, daemon_options
when "log"
log get_current_mode()
when "stop"
stop get_current_mode()
when "restart"
clear_cache_if_needed options
stop get_current_mode()
start options, daemon_options
when "precompile_assets_only", "precompile-assets-only"
clear_cache_if_needed options
if options[:target_static_dir]
precompile_assets_only options
else
puts "You must specify a target directory when precompiling! (via -t or --target)"
end
when "precompile_without_bundle_html", "precompile-without-bundle-html"
clear_cache_if_needed options
if options[:target_static_dir]
precompile_project_assets_and_munge_build_names options
else
puts "You must specify a target directory when precompiling! (via -t or --target)"
end
when "precompile"
clear_cache_if_needed options
if options[:target_static_dir]
precompile options
else
puts "You must specify a target directory when precompiling! (via -t or --target)"
end
when "clean"
if options[:target_static_dir]
clean options
else
puts "You must specify a target directory when cleaning precompiled assets! (via -t or --target)"
end
when "update_deps", "update-deps"
# Force cache clear
clear_cache
update_dependiences options
when "jasmine"
run_jasmine_tests options
else
puts opt_parser
end
|
class Event < ApplicationRecord
validates :name, :location, presence: true
validates :description, length: { minimum: 10 }
validates :price, numericality: { greater_than_or_equal_to: 0 }
validates :capacity, numericality: { only_integer: true, greater_than: 0 }
has_many :registrations, dependent: :destroy
scope :upcoming, -> { where('starts_at >= ?', Time.now).order(:starts_at) }
def free?
price.blank? || price.zero?
end
def spots_left
if capacity.nil?
0
else
capacity - registrations.size
end
end
def sold_out?
spots_left.zero?
end
end
|
class BrandsController < ApplicationController
layout 'dashboard'
def index
@brands = Brand.all
end
def new
@brand = Brand.new
end
def show
@brand = Brand.all
end
def edit
@brand = Brand.find(params[:id])
end
def update
@brand = Brand.find(params[:id])
if @brand.update(brands_params)
flash[:notice] = "Seactualizo la marca correctamente"
redirect_to brands_path
else
flash[:alert] = "No es posible actualizar la marca en este momento"
reder 'edit'
end
end
def delete
@brand = Brand.find(params[:id])
if @brand.destroy
flash[:notice] = "Se Elimino la marca correctamente"
redirect_to brands_path
else
flash[:alert] = "No es posible Eliminar la marca en este momento"
reder 'edit'
end
end
def create
@brand = Brand.new(brands_params)
if @brand.save
flash[:notice] = "Se ingreso una marca nueva"
redirect_to brands_path
else
flash[:alert] = "Se ingreso una marca nueva"
reder 'edit'
end
end
private
def brands_params
params.require(:brand).permit(:nombre,:codigo)
end
end
|
require_relative "card.rb"
class CardDeck
attr_accessor :cards, :count
def initialize
@cards = []
suits = [:Diamonds, :Spades, :Clubs, :Hearts]
suits.each do |s|
(1..13).each do |r|
cards << Card.new(s,r)
end
end
end
def count()
@cards.length
end
end
|
class Address < ApplicationRecord
# 購入者住所
belongs_to :purchase
end
|
module Merit
# Points are a simple integer value which are given to "meritable" resources
# according to rules in +app/models/merit/point_rules.rb+. They are given on
# actions-triggered.
module PointRulesMethods
# Define rules on certaing actions for giving points
def score(points, *args, &block)
options = args.extract_options!
options_to = options.fetch(:to) { :action_user }
actions = Array.wrap(options[:on])
Array.wrap(options_to).each do |to|
rule = Rule.new
rule.score = points
rule.to = to
rule.block = block
rule.category = options.fetch(:category) { :default }
rule.model_name = options[:model_name] if options[:model_name]
actions.each do |action|
defined_rules[action] ||= []
defined_rules[action] << rule
end
end
end
# Currently defined rules
def defined_rules
@defined_rules ||= {}
end
end
end
|
# frozen_string_literal: true
# Helper functions for the RSS viewer
module RssAppHelpers
# It's a utility function so it has :reek:FeatureEnvy
def linkify(text)
return '' unless !text.nil? && text.is_a?(String)
# return the text unchanged if links are already embedded
return text if text =~ /<a/
text.gsub(%r{(https?://\S+)}, '<a href="\1" target="_blank">\1</a>')
rescue => e
warn "rescue: #{e.inspect}"
''
end
# It's a utility function so it has :reek:FeatureEnvy
def process_cdata(string)
pos = string =~ /<!\[CDATA\[/
warn 'CDATA found after string beginning' if !pos.nil? && pos.positive?
string.gsub(/<!\[CDATA\[([^\]]+)\]\]>/, '\1')
end
module_function :linkify
module_function :process_cdata
end
|
#!/usr/bin/env ruby
# $Id$
require 'test/unit'
require 'fileutils'
require 'tempfile'
SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__
# Test TestLineNumbers module
class TestLineNumbers1 < Test::Unit::TestCase
@@TEST_DIR = File.expand_path(File.dirname(__FILE__))
@@TOP_SRC_DIR = File.join(@@TEST_DIR, '..', 'lib')
require File.join(@@TOP_SRC_DIR, 'tracelines19.rb')
@@rcov_file = File.join(@@TEST_DIR, 'rcov-bug.rb')
File.open(@@rcov_file, 'r') {|fp|
first_line = fp.readline[1..-2]
@@rcov_lnums = eval(first_line, binding, __FILE__, __LINE__)
}
def test_for_file
rcov_lines = TraceLineNumbers.lnums_for_file(@@rcov_file)
assert_equal(@@rcov_lnums, rcov_lines)
end
def test_for_string
string = "# Some rcov bugs.\nz = \"\nNow is the time\n\"\n\nz =~ \n /\n 5\n /ix\n"
rcov_lines = TraceLineNumbers.lnums_for_str(string)
assert_equal([2, 9], rcov_lines)
end
def test_for_string_array
load(@@rcov_file, 0)
rcov_lines =
TraceLineNumbers.lnums_for_str_array(SCRIPT_LINES__[@@rcov_file])
assert_equal(@@rcov_lnums, rcov_lines)
end
end
|
require 'test_helper'
class PortfolioCommentsControllerTest < ActionDispatch::IntegrationTest
def setup
@comment = comments(:orange)
end
test "should redirect create when not logged in" do
assert_no_difference 'Comment.count' do
post comments_path, params: { comment: { content: "Lorem ipsum" } }
end
assert_redirected_to login_url
end
test "should redirect destroy when not logged in" do
assert_no_difference 'Comment.count' do
delete comment_path(@comment)
end
assert_redirected_to login_url
end
test "should redirect destroy for wrong comment" do
log_in_as(users(:michael))
comment = comments(:ants)
assert_no_difference 'Comment.count' do
delete comment_path(comment)
end
assert_redirected_to root_url
end
end
|
class Api::V1::ApiController < ApplicationController
skip_before_action :verify_authenticity_token
skip_before_action :redirect_to_new_version!
before_action :authenticate!
include ActionController::HttpAuthentication::Token::ControllerMethods
def array_json(collection, serializer)
ActiveModel::Serializer::CollectionSerializer.new(
collection, serializer: serializer
)
end
def meta_attributes(collection, extra_meta = {})
{
current_page: collection.current_page,
next_page: collection.next_page,
prev_page: collection.prev_page,
total_pages: collection.total_pages
}.merge(extra_meta)
end
protected
def authenticate!
authenticate_token || render_unauthorized
end
def authenticate_token
authenticate_with_http_token do |token, options|
@current_admin_user = AdminUser.find_by(access_token: token)
end
end
def render_unauthorized(realm = "Application")
self.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
render json: { message: 'Bad credentials' }, status: :unauthorized
end
end |
class Country < ActiveRecord::Base
belongs_to :panel_provider
has_many :location_groups, dependent: :destroy
has_and_belongs_to_many :target_groups, -> (country) { where(parent_id: nil, panel_provider_id: country.panel_provider_id) }
has_many :locations, through: :location_groups
end
|
class Teacher::HomeController < TeachersController
before_action :set_university
def index
@courses = Course.where(teacher_name: current_teacher.name)
end
private
def set_university
@university = University.find(current_teacher.university_id)
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate_account!
def current_character
@current_character ||= current_account.character
end
def current_room
@current_room ||= current_account.character.current_room
end
def current_morph
@current_morph ||= current_account.character.current_morph
end
def current_ability
@current_ability ||= Ability.new(current_account)
end
end
|
require_relative 'item'
class StandardItem < Item
QUALITY_REDUCTION_BEFORE_SELL_IN = 1
QUALITY_REDUCTION_AFTER_SELL_IN = 2
SELL_IN_REDUCTION = 1
def update_quality
self.sell_in <= 0 ? past_sell_by_date : within_sell_by_date
prevent_quality_from_going_below_zero
end
def within_sell_by_date
sell_in_decreases_by_one
quality_decreases_by_one
end
def past_sell_by_date
sell_in_decreases_by_one
quality_decreases_by_two
end
def sell_in_decreases_by_one
self.sell_in -= SELL_IN_REDUCTION
end
def quality_decreases_by_two
self.quality -= QUALITY_REDUCTION_AFTER_SELL_IN
end
def quality_decreases_by_one
self.quality -= QUALITY_REDUCTION_BEFORE_SELL_IN
end
def prevent_quality_from_going_below_zero
self.quality = 0 if (self.quality <= 0) && (self.sell_in <= 0)
end
end
|
require 'spec_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
describe ClientmailsController do
# This should return the minimal set of attributes required to create a valid
# Clientmail. As you add validations to Clientmail, be sure to
# adjust the attributes here as well.
let(:valid_attributes) { { "mail" => "MyString" } }
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# ClientmailsController. Be sure to keep this updated too.
let(:valid_session) { {} }
describe "GET index" do
it "assigns all clientmails as @clientmails" do
clientmail = Clientmail.create! valid_attributes
get :index, {}, valid_session
assigns(:clientmails).should eq([clientmail])
end
end
describe "GET show" do
it "assigns the requested clientmail as @clientmail" do
clientmail = Clientmail.create! valid_attributes
get :show, {:id => clientmail.to_param}, valid_session
assigns(:clientmail).should eq(clientmail)
end
end
describe "GET new" do
it "assigns a new clientmail as @clientmail" do
get :new, {}, valid_session
assigns(:clientmail).should be_a_new(Clientmail)
end
end
describe "GET edit" do
it "assigns the requested clientmail as @clientmail" do
clientmail = Clientmail.create! valid_attributes
get :edit, {:id => clientmail.to_param}, valid_session
assigns(:clientmail).should eq(clientmail)
end
end
describe "POST create" do
describe "with valid params" do
it "creates a new Clientmail" do
expect {
post :create, {:clientmail => valid_attributes}, valid_session
}.to change(Clientmail, :count).by(1)
end
it "assigns a newly created clientmail as @clientmail" do
post :create, {:clientmail => valid_attributes}, valid_session
assigns(:clientmail).should be_a(Clientmail)
assigns(:clientmail).should be_persisted
end
it "redirects to the created clientmail" do
post :create, {:clientmail => valid_attributes}, valid_session
response.should redirect_to(Clientmail.last)
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved clientmail as @clientmail" do
# Trigger the behavior that occurs when invalid params are submitted
Clientmail.any_instance.stub(:save).and_return(false)
post :create, {:clientmail => { "mail" => "invalid value" }}, valid_session
assigns(:clientmail).should be_a_new(Clientmail)
end
it "re-renders the 'new' template" do
# Trigger the behavior that occurs when invalid params are submitted
Clientmail.any_instance.stub(:save).and_return(false)
post :create, {:clientmail => { "mail" => "invalid value" }}, valid_session
response.should render_template("new")
end
end
end
describe "PUT update" do
describe "with valid params" do
it "updates the requested clientmail" do
clientmail = Clientmail.create! valid_attributes
# Assuming there are no other clientmails in the database, this
# specifies that the Clientmail created on the previous line
# receives the :update_attributes message with whatever params are
# submitted in the request.
Clientmail.any_instance.should_receive(:update).with({ "mail" => "MyString" })
put :update, {:id => clientmail.to_param, :clientmail => { "mail" => "MyString" }}, valid_session
end
it "assigns the requested clientmail as @clientmail" do
clientmail = Clientmail.create! valid_attributes
put :update, {:id => clientmail.to_param, :clientmail => valid_attributes}, valid_session
assigns(:clientmail).should eq(clientmail)
end
it "redirects to the clientmail" do
clientmail = Clientmail.create! valid_attributes
put :update, {:id => clientmail.to_param, :clientmail => valid_attributes}, valid_session
response.should redirect_to(clientmail)
end
end
describe "with invalid params" do
it "assigns the clientmail as @clientmail" do
clientmail = Clientmail.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
Clientmail.any_instance.stub(:save).and_return(false)
put :update, {:id => clientmail.to_param, :clientmail => { "mail" => "invalid value" }}, valid_session
assigns(:clientmail).should eq(clientmail)
end
it "re-renders the 'edit' template" do
clientmail = Clientmail.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
Clientmail.any_instance.stub(:save).and_return(false)
put :update, {:id => clientmail.to_param, :clientmail => { "mail" => "invalid value" }}, valid_session
response.should render_template("edit")
end
end
end
describe "DELETE destroy" do
it "destroys the requested clientmail" do
clientmail = Clientmail.create! valid_attributes
expect {
delete :destroy, {:id => clientmail.to_param}, valid_session
}.to change(Clientmail, :count).by(-1)
end
it "redirects to the clientmails list" do
clientmail = Clientmail.create! valid_attributes
delete :destroy, {:id => clientmail.to_param}, valid_session
response.should redirect_to(clientmails_url)
end
end
end
|
require 'spec_helper'
describe Admin::CourtsController do
render_views
before :each do
controller.should_receive(:enable_varnish).never
sign_in User.create!(name: 'hello', admin: true, email: 'lol@biz.info', password: 'irrelevant')
end
it "displays a list of courts" do
get :index
response.should render_template('admin/courts/index')
response.should be_success
end
it "purges the cache when a court is updated" do
court = Court.create!(name: 'A court of Law')
controller.should_receive(:purge_all_pages)
post :update, id: court.id, court: { name: 'Another court of law' }
response.should redirect_to(edit_admin_court_path(court.reload))
end
it "purges the cache when a new court is created" do
expect {
controller.should_receive(:purge_all_pages)
post :create, court: { name: 'A court of LAW' }
response.should redirect_to(edit_admin_court_path(assigns(:court)))
}.to change { Court.count }.by(1)
end
it "purges the cache when a court is destroyed" do
court = Court.create!(name: 'A court of Law')
expect {
controller.should_receive(:purge_all_pages)
post :destroy, id: court.id
response.should redirect_to(admin_courts_path)
}.to change { Court.count }.by(-1)
end
end
|
# == Schema Information
#
# Table name: notifications
#
# id :integer not null, primary key
# user_id :integer
# status :integer
# created_at :datetime not null
# updated_at :datetime not null
# notification_type :integer
# data :json
#
# Indexes
#
# index_notifications_on_created_at (created_at)
# index_notifications_on_status (status)
# index_notifications_on_user_id (user_id)
#
class Notification < ApplicationRecord
PER_PAGE = 10
belongs_to :user
enum status: [:read, :unread]
# there must exists a partial por each notification_type!
enum notification_type: [ :notice, :level_up, :points_earned,
:comment_activity, :comment_response, :badge_earned ]
validates :user, presence: true
validates :status, presence: true
validates :notification_type, presence: true
default_scope { order('created_at DESC') }
after_initialize :default_values
after_create :notify_user
def resource_avaliable?
if comment_activity?
Comment.exists?(data["comment_id"])
elsif comment_response?
Comment.exists?(data["response_id"])
elsif badge_earned?
Badge.exists?(data["badge_id"])
else
return true
end
end
private
def default_values
self.status ||= Notification.statuses[:unread]
self.notification_type ||= Notification.notification_types[:notice]
self.data ||= {}
end
def notify_user
user.notifier.notify('notifications:new', { notification_id: self.id })
end
end
|
class AddPriceIdsToSection < ActiveRecord::Migration
def change
add_column :sections, :dayof_price_id, :integer
add_column :sections, :presale_price_id, :integer
remove_column :prices, :section_id
end
end
|
# Undo a commit or range of commits.
#
# This reverse-merges one or more revision into the current working copy.
#
# > svn undo 45
# > svn undo 45:50
#
# This will merge in 45:44 and 50:45 respectively. The source to merge from
# is the current working copy URL by default, but you may specify your own:
#
# > svn undo 5034 ^/my-project/trunk
Subcheat::Command.define('undo') do
revision, url = arguments[0], arguments[1]
revision = case revision
when /^\d+$/ then "#{revision}:#{revision.to_i - 1}"
when /^\d+:\d+$/ then revision.split(':').reverse.join(':')
else
raise Subcheat::CommandException, "Bad revision: #{revision}"
end
url ||= attr('URL')
"svn merge -r #{revision} #{url}"
end
|
class NotAnInt < ArgumentError
end
class NotPositiveInt < ArgumentError
end
def put_n(text, times)
raise NotAnInt if !times.is_a? Integer
raise NotPositiveInt if !times.positive?
times.times { puts text }
end
def echo
puts "What do you want to echo?"
text = gets.strip
puts "How many times do you want to repeat it?"
times = gets.strip
put_n(text, times)
rescue
puts "I don't understand how many times do you want to echo the string!"
retry
end
|
class TranslateDeliveryTypes < ActiveRecord::Migration
def up
remove_column :delivery_types, :name
DeliveryType.create_translation_table!({
:name => :string
}, {
:migrate_data => true
})
end
def down
DeliveryType.drop_translation_table! :migrate_data => true
end
end
|
class Api::V1::BackgroundsController < ApplicationController
def show
background = Background.new(params[:location])
render json: BackgroundsSerializer.new(background)
end
end |
FactoryBot.define do
factory :link do
name { "Thinknetica" }
url { "http://thinknetica.com" }
end
trait :gist_link do
name { "Gist" }
url { "https://gist.github.com/jezman/a6c9a6c93f651b8b84ac6e08303e82ed" }
end
end
|
# frozen_string_literal: true
# This controller contain the methods shared for all admin controller
class Admin::ApplicationController < ApplicationController
before_action :authenticate_admin!
# Set nav for editor's section
def nav
'nav_admin'
end
private
# deny access unless current_user is an editor
def authenticate_admin!
access_denied! unless current_user.admin?
end
end
|
class RenameColumn < ActiveRecord::Migration
def change
rename_column :workunits, :performed_by_id, :performed_by_user_id
rename_column :workunits, :confirmed_by_id, :confirmed_by_user_id
end
end
|
require 'spec_helper'
describe Robot do
before :each do
@robot = Robot.new
end
it "should have 50 shield points" do
expect(@robot.shield_points).to eq(50)
end
describe "#wound" do
it "should first drain the shield" do
@robot.wound(20)
expect(@robot.health).to eq(100)
expect(@robot.shield_points).to eq(30)
end
context "with robot without shield points" do
before :each do
@robot.wound(50)
end
it "should start affecting actual health when shield points equal to zero" do
@robot.wound(20)
expect(@robot.shield_points).to eq(0)
expect(@robot.health).to eq(80)
end
end
context "with damage more than 50" do
before :each do
@robot.wound(80)
end
it "should start affecting actual health when shield points equal to zero" do
expect(@robot.shield_points).to eq(0)
expect(@robot.health).to eq(70)
end
end
end
end |
require 'csv'
require_relative 'base'
require_relative 'base_repository'
require_relative 'merchant'
require_relative 'merchant_repository'
require_relative 'invoice'
require_relative 'invoice_repository'
require_relative 'item'
require_relative 'item_repository'
require_relative 'invoice_item'
require_relative 'invoice_item_repository'
require_relative 'customer'
require_relative 'customer_repository'
require_relative 'transaction'
require_relative 'transaction_repository'
class SalesEngine
INDEX = 0
def format_csv(csv)
csv = CSV.read(csv)
csv.shift
csv
end
def startup
create_customer_repository
create_invoice_repository
create_invoice_item_repository
create_item_repository
create_merchant_repository
create_transaction_repository
end
private
def create_customer_repository
csv = "/Users/suzannejacobson/Documents/JumpstartTutorials/sales_engine/data/customers.csv"
csv_without_header = format_csv(csv)
customers = csv_without_header.each do |row|
customer_row = Customer.new(id: row[INDEX], first_name: row[1], last_name: row[2], created_at: row[3], updated_at: row[4])
CustomerRepository.add(customer_row)
end
end
def create_invoice_item_repository
csv = "/Users/suzannejacobson/Documents/JumpstartTutorials/sales_engine/data/invoice_items.csv"
csv_without_header = format_csv(csv)
invoice_items = csv_without_header.each do |row|
invoice_item_row = InvoiceItem.new(id: row[INDEX], item_id: row[1], invoice_id: row[2], quantity: row[3], unit_price: row[4], created_at: row[5], updated_at: row[6])
InvoiceItemRepository.add(invoice_item_row)
end
end
def create_invoice_repository
csv = "/Users/suzannejacobson/Documents/JumpstartTutorials/sales_engine/data/invoices.csv"
csv_without_header = format_csv(csv)
invoices = csv_without_header.each do |row|
invoice_row = Invoice.new(id: row[INDEX], customer_id: row[1], merchant_id: row[2], status: row[3], created_at: row[4], updated_at: row[5])
InvoiceRepository.add(invoice_row)
end
end
def create_item_repository
csv = "/Users/suzannejacobson/Documents/JumpstartTutorials/sales_engine/data/items.csv"
csv_without_header = format_csv(csv)
items = csv_without_header.each do |row|
item_row = Item.new(id: row[INDEX], name: row[1], description: row[2], unit_price: row[3], merchant_id: row[4], created_at: row[5], updated_at: row[6])
ItemRepository.add(item_row)
end
end
def create_merchant_repository
csv = "/Users/suzannejacobson/Documents/JumpstartTutorials/sales_engine/data/merchants.csv"
csv_without_header = format_csv(csv)
merchants = csv_without_header.each do |row|
merchant_row = Merchant.new(id: row[INDEX], name: row[1], created_at: row[2], updated_at: row[3])
MerchantRepository.add(merchant_row)
end
end
def create_transaction_repository
csv = "/Users/suzannejacobson/Documents/JumpstartTutorials/sales_engine/data/transactions.csv"
csv_without_header = format_csv(csv)
transactions = csv_without_header.each do |row|
transaction_row = Transaction.new(id: row[INDEX], invoice_id: row[1], credit_card_number: row[2], credit_card_expiration_date: row[3], result: row[4], created_at: row[5], updated_at: row[6])
TransactionRepository.add(transaction_row)
end
end
end |
# -*- encoding : utf-8 -*-
require File.dirname(__FILE__) + '/test_helper.rb'
require 'module_handler'
class Module_First
end
class Module_Second
end
describe 'ModuleHandler' do
before(:each) do
@bot = double()
end
context "ModuleHandler" do
before(:each) do
@handler = ModuleHandler.new
end
it "reload zero modules if none is found" do
dir = double()
expect(dir).to receive(:entries).and_return([])
expect(Dir).to receive(:new).and_return(dir)
@handler.reload(@bot, "modules_dir", [])
expect(@handler.modules).to eq([])
end
it "load all found modules except excluded and pass on privmsgs" do
dir = double()
firstModule = double()
secondModule = double()
expect(dir).to receive(:entries).and_return(["module_first.rb", "module_excluded.rb", "module_second.rb"])
expect(Dir).to receive(:new).and_return(dir)
expect(Kernel).to receive(:load).with("modules_dir/module_first.rb")
expect(Kernel).to receive(:load).with("modules_dir/module_second.rb")
expect(Module_First).to receive(:new).and_return(firstModule)
expect(Module_Second).to receive(:new).and_return(secondModule)
expect(firstModule).to receive(:init_module).with(@bot)
expect(secondModule).to receive(:init_module).with(@bot)
@handler.reload(@bot, "modules_dir", ["excluded"])
expect(@handler.modules).to eq([firstModule, secondModule])
end
end
context "ModuleHandler with one loaded module" do
before(:each) do
@handler = ModuleHandler.new
dir = double()
@firstModule = double()
expect(dir).to receive(:entries).and_return(["module_first.rb"])
expect(Dir).to receive(:new).and_return(dir)
expect(Kernel).to receive(:load).with("modules_dir/module_first.rb")
expect(Module_First).to receive(:new).and_return(@firstModule)
expect(@firstModule).to receive(:init_module).with(@bot)
@handler.reload(@bot, "modules_dir", [])
expect(@handler.modules).to eq([@firstModule])
end
it "provide reply_to as channel when targeting a channel" do
expect(@bot).to receive(:nick).and_return("bot_nick")
expect(@firstModule).to receive(:privmsg).with(@bot, "someone", "#channel", "message")
@handler.handle_privmsg("someone", "#channel", "message")
end
it "provide reply_to as sender when targeting the bot" do
expect(@bot).to receive(:nick).and_return("bot_nick")
expect(@firstModule).to receive(:privmsg).with(@bot, "someone", "someone", "message")
@handler.handle_privmsg("someone", "bot_nick", "message")
end
end
end
|
class LogsController < ApplicationController
# def new
# @log =Log.new
# end
def create
end
##
#Author:Sarah
#Creates a new instance of the log
# * *Args* :
# -+@task+ -> the current task
# -+@log+ -> the new instance of the log
# * *Returns* :
# - nothing
#
def new
@task_result=TaskResult.find(session[:task_result_id])
@task= Task.find(@task_result.task_id)
@log =Log.new
@log.task_result_id= session[:task_result_id]
@log.action=params[:change_action]
@log.time=params[:change_action_time]
@log.component_involved=params[:change_component_involved]
@log.element_id=params[:change_element_id]
@log.save
render :nothing => true
end
def update
@log = Log.find(params[:id])
@log.action=params[:change_action]
@log.time=params[:change_action_time]
@log.component_involved=params[:change_component_involved]
@log.save
render :nothing => true
end
end
|
class AddIdToAlumno < ActiveRecord::Migration
def change
add_column :alumnos, :id_carrera, :int
end
end
|
require 'rails_helper'
RSpec.describe Search do
describe '#initialize' do
subject { Search.new }
context 'when object is created' do
it 'should create new object' do
expect(subject).to be_kind_of(Search)
end
it 'should have the correct attrbitus' do
expect(subject).to have_attributes(
running: true,
object: nil,
search_term: nil,
search_value: nil,
searchable_fields: {
"1" => [
"url",
"external_id",
"name",
"details",
"shared_tickets",
"created_at",
"_id",
"tags",
"domain_names"
],
"2" => [
"url",
"external_id",
"name",
"alias",
"created_at",
"active",
"verified",
"shared",
"locale",
"timezone",
"last_login_at",
"email",
"phone",
"signature",
"organization_id",
"suspended",
"role",
"_id",
"tags"
],
"3" => [
"_id",
"url",
"external_id",
"created_at",
"type",
"subject",
"description",
"priority",
"status",
"submitter_id",
"assignee_id",
"organization_id",
"has_incidents",
"due_at",
"via",
"_id",
"tags"
]
}
)
end
end
end
describe '#start_program' do
subject do
search = Search.new
search.send(:start_program)
search
end
context 'when user exits' do
it 'should change running to false' do
allow_any_instance_of(Object).to receive(:gets).and_return('Exit')
expect(subject).to have_attributes(running: false)
end
end
context 'when incorrect input' do
context 'when user exits the second time' do
it 'should change running to false' do
allow_any_instance_of(Object).to receive(:gets).and_return('na', 'Exit')
expect(subject).to have_attributes(running: false)
end
end
context 'when user starts the program' do
it 'should change running to false' do
allow_any_instance_of(Object).to receive(:gets).and_return('na', 'Start')
expect(subject).to have_attributes(running: true)
end
end
end
context 'when user starts program the first time' do
it 'should change running to false' do
allow_any_instance_of(Object).to receive(:gets).and_return('Start')
expect(subject).to have_attributes(running: true)
end
end
end
describe '#select_object_type' do
subject do
search = Search.new
search.send(:select_object_type)
search
end
context 'when user quits' do
it 'should change running to false' do
allow_any_instance_of(Object).to receive(:gets).and_return('Exit')
expect(subject).to have_attributes(running: false, object: nil)
end
end
context 'when user input is invalid' do
context 'when invalid then quit' do
it 'should change running to false' do
allow_any_instance_of(Object).to receive(:gets).and_return('4', 'Exit')
expect(subject).to have_attributes(running: false, object: nil)
end
end
context 'when invalid then valid' do
it 'should have running as true and set object value' do
allow_any_instance_of(Object).to receive(:gets).and_return('4', '1')
expect(subject).to have_attributes(running: true, object: '1')
end
end
end
context 'when user input is valid the first time' do
it 'should have running as true and set object value' do
allow_any_instance_of(Object).to receive(:gets).and_return('1')
expect(subject).to have_attributes(running: true, object: '1')
end
end
end
describe '#select_field_type' do
subject do
search = Search.new
search.object = '1'
search.send(:select_field_type)
search
end
context 'when user quits' do
it 'should change running to false' do
allow_any_instance_of(Object).to receive(:gets).and_return('Exit')
expect(subject).to have_attributes(running: false, search_term: nil)
end
end
context 'when user input is invalid' do
context 'when invalid then quit' do
it 'should change running to false' do
allow_any_instance_of(Object).to receive(:gets).and_return('4', 'Exit')
expect(subject).to have_attributes(running: false, search_term: nil)
end
end
context 'when invalid then valid' do
it 'should have running as true and set object value' do
allow_any_instance_of(Object).to receive(:gets).and_return('4', 'name')
expect(subject).to have_attributes(running: true, search_term: 'name')
end
end
end
context 'when view searchable list is selected' do
it 'should call print_searchable_fields method' do
allow_any_instance_of(Object).to receive(:gets).and_return('1', 'Exit')
allow_any_instance_of(Search).to receive(:print_searchable_fields)
subject
expect(subject).to have_received(:print_searchable_fields).once
end
end
context 'when user enters valid search term' do
it 'should set search term' do
allow_any_instance_of(Object).to receive(:gets).and_return('name')
expect(subject).to have_attributes(running: true, search_term: 'name')
end
end
end
describe '#select_value' do
subject do
search = Search.new
search.object = '1'
search.send(:select_value)
search
end
context 'when false is selected' do
it 'should set search value as boolean' do
allow_any_instance_of(Object).to receive(:gets).and_return('false')
expect(subject).to have_attributes(running: true, search_value: false)
end
end
context 'when true is selected' do
it 'should set search value as boolean' do
allow_any_instance_of(Object).to receive(:gets).and_return('true')
expect(subject).to have_attributes(running: true, search_value: true)
end
end
context 'when empty entry' do
it 'should set search value as nil' do
allow_any_instance_of(Object).to receive(:gets).and_return('')
expect(subject).to have_attributes(running: true, search_value: nil)
end
end
context 'when string is entered' do
it 'should set the search value as the input' do
allow_any_instance_of(Object).to receive(:gets).and_return('test')
expect(subject).to have_attributes(running: true, search_value: 'test')
end
end
end
describe '#complete_search' do
subject do
search = Search.new
search.object = object
search.search_term = search_term
search.search_value = search_value
search.send(:complete_search)
end
context 'when search value is a string and search term is a boolean' do
let(:object) { '1' }
let(:search_term) { 'shared_tickets' }
let(:search_value) { 'invalid' }
let!(:organization) { create(:organization) }
it 'should return nil' do
expect(subject).to eq(nil)
end
end
context 'when search term is part of object' do
let(:object) { '1' }
let(:search_term) { 'url' }
let(:search_value) { 'test' }
let!(:organization) { create(:organization, url: 'test') }
it 'should return nil' do
expect(subject).to eq([organization])
end
end
context 'when search term is part of related object' do
let(:object) { '1' }
let(:search_term) { 'tags' }
let(:search_value) { 'test' }
let!(:organization) { create(:organization, :with_tags) }
it 'should return nil' do
expect(subject).to eq([organization])
end
end
context 'when nothing is found' do
let(:object) { '1' }
let(:search_term) { 'url' }
let(:search_value) { 'test' }
let!(:organization) { create(:organization, url: 'test1') }
it 'should return empty array' do
expect(subject).to be_empty
end
end
end
end |
#
# useful methods for cleaning the _ dictionary terms
#
namespace :dictionary do
namespace :clean do
def argf_file
begin
STDERR.puts "Found file - #{ARGF.filename}"
rescue
STDERR.puts $!
end
end
def skip
argf_file
ARGF.skip # skip clean:proper param
argf_file
end
desc "John Smith -> Smith, John | John Smith"
task proper: :environment do
skip
ARGF.each_with_index do |line, idx|
# print ARGF.filename, ":", idx, ";", line
words = line.split(' ')
all_caps = true
words.each do |word|
if /[[:upper:]]/.match(word[0]).nil?
all_caps = false
end
end
if all_caps and words.length > 1
entry = words.dup
last = "#{entry.pop},"
entry.unshift last
entry = entry.join(' ')
puts "#{entry} | #{line}"
else
puts line
end
end
end
# do they handle accented characters and non-latin scripts?
desc "αδιαφορα [adiaphora] -> adiaphora | αδιαφορα [adiaphora]"
task brackets: :environment do
skip
ARGF.each_with_index do |line, idx|
# print ARGF.filename, ":", idx, ";", line
if /(\p{Greek}+) \[(\X+)\]/.match(line).nil?
puts line
else
puts "#{$~[2]} | #{line}"
end
end
end
desc "adiaphora | αδιαφορα [adiaphora] -> adiaphora"
task strip: :environment do
skip
ARGF.each_with_index do |line, idx|
# print ARGF.filename, ":", idx, ";", line
if /(\X+) \| (\X+)/.match(line).nil?
puts line
else
puts "#{$~[1]}"
end
end
end
# i fixed up the file
# abbrv. -> abbreviation
desc "Absorption (Abs.) -> Absorption"
task parens: :environment do
skip
ARGF.each_with_index do |line, idx|
# print ARGF.filename, ":", idx, ";", line
if /(\X+) \(\X+\)/.match(line).nil?
puts line
else
puts "#{$~[1]} | #{line}"
end
end
end
# i fixed up the file, could have done it programmatically
# foo /bar -> foo / bar
# foo / bar baz -> foo baz / foo bar
desc "continence / incontinence -> continence"
task remove_slash: :environment do
skip
ARGF.each_with_index do |line, idx|
# print ARGF.filename, ":", idx, ";", line
if /(\X+?) \/ (\X+) \| (\X+)/.match(line).nil?
if /(\X+?) \/ (\X+)/.match(line).nil?
puts line
else
puts "#{$~[1]} | #{line}"
end
else
puts "#{$~[1]} | #{$~[3]}"
end
end
end
desc "continence/incontinence -> continence / incontinence"
task align_slash: :environment do
skip
ARGF.each_with_index do |line, idx|
# print ARGF.filename, ":", idx, ";", line
if /(.+\w)\/(\w.+)/.match(line).nil?
puts line
else
puts line
end
end
end
end # namespace :clean
end # namespace :dictionary
|
# Below are the declarations for constants that will be used in various code
# files in this gem.
module ApplePicker
GEM_NAME = 'apple-picker'
VERSION = '0.0.0'
end
|
class CouponsController < ApplicationController
before_action :authenticate_user!
before_action :set_coupon, only: [:show, :disable, :active]
def show
end
def disable
@coupon.disabled!
# redirect_to @coupon.promotion, notice: "Cupom #{@coupon.code} desabilitado com sucesso"
redirect_to @coupon.promotion, notice: t('.success', code: @coupon.code)
end
def active
@coupon.active!
redirect_to @coupon.promotion, notice: t('.success', code: @coupon.code)
end
def search
@coupon = Coupon.search(params[:q])
if @coupon
redirect_to @coupon
else
redirect_to promotions_path, notice: t('.not_found')
end
end
private
def set_coupon
@coupon = Coupon.find(params[:id])
end
end |
class Language < ApplicationRecord
validates :name, inclusion: { in: %w(ruby css js html),
message: "%{name} is not a valid Language" }
end
|
class RemoveRoomsFromUsers < ActiveRecord::Migration
def change
remove_column :users, :rooms, :string
end
end
|
module Jobs
class ReceiveMessageJob < Struct.new(:reception_id)
def perform
@reception = Reception.find(reception_id)
receive if @reception.just_arrived?
end
def receive
if @reception.process
Notifier.queue_all_notifications
else
raise "Message could not be received."
end
end
end
end
|
class CreateMultiChannels < ActiveRecord::Migration
def change
create_table :multi_channels do |t|
t.references :user, index: true, foreign_key: true
t.references :amazon, index: true, foreign_key: true
t.date :date
t.string :time
t.string :order_num
t.string :sku
t.string :goods_name
t.integer :number
t.integer :amount
t.integer :tax
t.integer :pladmin_id
t.boolean :destroy_check, default: false, null: false
t.timestamps null: false
end
end
end
|
require File.dirname(__FILE__) + '/../../../../spec/spec_helper'
require 'haisyo_listener'
describe HaisyoListener do
before do
@room = Room.new(title: 'test room').tap{|x| x.save! }
@user = User.new(name: 'test user', screen_name: 'test').tap{|x| x.save! }
@message = Message.create(body: "引用元メッセージ", user: @user, room: @room)
@listener = HaisyoListener.new({})
end
describe "message_buttons" do
it "onClickにJavaScriptコードを指定したボタン要素を作成する" do
context = { message: @message }
expected = <<EOS
<input type="button" onClick="$(function() {
$('#message').val('拝承。 > 引用元メッセージ');
$('.inputarea').submit();
});
">
EOS
expect(@listener.message_buttons(context)).to eq(expected)
end
end
end
|
require "formula"
require "language/go"
class Forego < Formula
homepage "https://github.com/ddollar/forego"
url "https://github.com/ddollar/forego/archive/v0.13.1.tar.gz"
sha1 "63ed315ef06159438e3501512a5b307486d49d5c"
head "https://github.com/ddollar/forego.git"
bottle do
sha1 "9eac8ca38f6a4557b30737529f8be85b7afb11bb" => :mavericks
sha1 "4a08f819f67056758915c4624868e3dc1b012431" => :mountain_lion
sha1 "1fdb5c2c67b2990a3e71f4d4bde9a872662718c3" => :lion
end
depends_on "go" => :build
go_resource "github.com/kr/godep" do
url "https://github.com/kr/godep.git", :revision => "edcaa96f040b31f4186738decac57f88d6061b8d"
end
go_resource "github.com/kr/fs" do
url "https://github.com/kr/fs.git", :revision => "2788f0dbd16903de03cb8186e5c7d97b69ad387b"
end
go_resource "code.google.com/p/go.tools" do
url "https://code.google.com/p/go.tools/", :revision => "140fcaadc586", :using => :hg
end
def install
ENV["GOPATH"] = buildpath
Language::Go.stage_deps resources, buildpath/"src"
cd "src/github.com/kr/godep" do
system "go", "install"
end
ldflags = "-X main.Version #{version} -X main.allowUpdate false"
system "./bin/godep", "go", "build", "-ldflags", ldflags, "-o", "forego"
bin.install "forego"
end
test do
(testpath/"Procfile").write("web: echo \"it works!\"")
assert `#{bin}/forego start` =~ /it works!/
end
end
|
class TransactionsController < ApplicationController
def index
@transactions = current_user.transactions.page(params[:page])
end
def show
end
def new
@transaction = current_user.transactions.new
@categories = current_user.categories
end
def create
@transaction = current_user.transactions.new(permitted_params)
if @transaction.save
redirect_to transactions_path
else
render :new
end
end
def edit
@transaction = current_user.transactions.find(params[:id])
@categories = current_user.categories
end
def update
transaction = current_user.transactions.find(params[:id])
if transaction.update(permitted_params)
redirect_to transactions_path
else
redirect_to edit_transaction_path(transaction)
end
end
def destroy
transaction = current_user.transactions.find(params[:id])
transaction.destroy
redirect_to transactions_path
end
private
def permitted_params
params[:transaction][:amount] = BigDecimal.new(params[:transaction][:amount].to_s)
params.require(:transaction).permit(
:flow,
:item,
:amount,
:repeat,
:single_occurrence,
:category_id
)
end
end
|
#!/usr/bin/env ruby
# frozen_string_literal: true
# Created by Paul A.Gureghian in May 2020. #
# This Ruby program keeps track of movie ratings. #
# Start of script. #
# Create a hash to hold movies / ratings. #
movies = {
Alien: 10.0,
Aliens: 9.0
}
puts "\n"
puts 'This program allows you to add, update, display and delete movies from a database.'
puts 'Enter "add", "update", "display", or "delete":'
choice = gets.chomp
# Create a case statement. #
case choice
when 'add'
puts 'Add a movie:'
title = gets.chomp.to_sym
if movies[title.to_sym].nil?
puts 'Rate the movie:'
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts 'Movie added to database:'
puts "#{movies}"
else
puts "That movie already exists and its rating is: #{movies[title.to_sym]}."
end
when 'update'
puts 'What movie do you want to update?:'
title = gets.chomp
if movies[title.to_sym].nil?
puts 'That movie does not exist.'
else
puts 'What is the new rating?'
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts 'Movie rating was updated:'
puts "#{movies}"
end
when 'display'
movies.each do |title, rating|
puts "#{title}: #{rating}"
end
when 'delete'
puts 'Enter a movie title to delete:'
title = gets.chomp
if movies[title.to_sym].nil?
puts 'That movie does not exist.'
else
movies.delete(title.to_sym)
puts 'Movie was deleted from the database.'
puts "#{movies}"
end
else
puts 'Error: Please enter "add", "update", "display", or "delete" into the prompt.'
end
# End of program. # |
module Github
class Importer
def import!(options = {})
Github::User.each(options) do |user|
begin
GithubResourcesImportingJob.perform_later(user.login)
rescue => e
RailsShowcase::ExceptionNotifier.notify(e)
end
end
end
end
end
|
module ActiveRecord
class Base
def self.before_update_filter(callback_method, options = {})
self.set_callback :save, :before do
if options[:or_params].nil? && options[:and_params].nil?
send callback_method
elsif !options[:or_params].nil? && options[:and_params].nil?
send callback_method if options[:or_params].map{ |attr| attribute_changed?(attr.to_s) }.any?
elsif options[:or_params].nil? && !options[:and_params].nil?
send callback_method if options[:and_params].map{ |attr| attribute_changed?(attr.to_s) }.all?
else
send callback_method if options[:and_params].map{ |attr| attribute_changed?(attr.to_s) }.all? || options[:or_params].map{ |attr| attribute_changed?(attr.to_s) }.any?
end
end
end
def self.after_update_filter(callback_method, options = {})
self.set_callback :save, :after do
if options[:or_params].nil? && options[:and_params].nil?
send callback_method
elsif !options[:or_params].nil? && options[:and_params].nil?
send callback_method if options[:or_params].map{ |attr| attribute_changed?(attr.to_s) }.any?
elsif options[:or_params].nil? && !options[:and_params].nil?
send callback_method if options[:and_params].map{ |attr| attribute_changed?(attr.to_s) }.all?
else
send callback_method if options[:and_params].map{ |attr| attribute_changed?(attr.to_s) }.all? || options[:or_params].map{ |attr| attribute_changed?(attr.to_s) }.any?
end
end
end
end
end
|
class League < ActiveRecord::Base
has_many :teams
belongs_to :sheet
end
|
require 'rails_helper'
describe StructuredEventSerializer do
describe '#to_json' do
it 'renders out a string' do
event = {
description: {
text: 'desc'
},
name: {
text: 'event name'
},
start: {
local: 'start'
},
venue: {
name: 'venue name',
address: {}
},
logo: {
original: {
url: 'img url'
}
},
}.with_indifferent_access
serializer = StructuredEventSerializer.new(event)
result = serializer.to_json
expect(JSON.parse(result)["name"]).to eq('event name')
end
end
end
|
require_relative '../lib/cash_register_class'
require_relative '../lib/transaction_class'
require 'minitest/autorun'
require "minitest/reporters"
Minitest::Reporters.use!
=begin
S - set up the necessary objects
E - execute the code against the object being tested
A - assert the results of the execution
T - tear down and clean up any lingering artifacts
=end
class CashRegisterTest < Minitest::Test
def setup
@item_cost = 20.00
@trans = Transaction.new(@item_cost)
@register = CashRegister.new(100.00)
end
def test_cash_register_can_accept_money
@trans.amount_paid = 10.00
@register.accept_money(@trans)
assert_equal(110.00, @register.total_money)
end
def test_cash_register_returns_correct_change
@trans.amount_paid = 22
assert_equal(2.00, @register.change(@trans))
end
def test_cash_register_can_display_valid_receipt
assert_output("You've paid $#{@item_cost}.\n") do
@register.give_receipt(@trans)
end
end
end |
RSpec.feature 'Users can edit a post that has been created', type: :feature, js: true do
scenario 'User edits a post' do
visit('/')
click_on('Signup')
fill_in('user[username]', with: 'user1')
fill_in('user[email]', with: 'test@example.com')
fill_in('user[password]', with: 'password')
click_on('Join the Rebel Alliance')
click_button('Open Chat')
click_on('user1')
find('textarea.message_text').set('test-string')
# fill_in('message_text', with: 'test-string')
click_on('Send Message')
expect(page).to have_content('Theres no messages here, say hello to your friend!')
end
end
|
# See GitHubV3API documentation in lib/github_v3_api.rb
class GitHubV3API
# Provides access to the GitHub Users API (http://developer.github.com/v3/users/)
#
# example:
#
# api = GitHubV3API.new(ACCESS_TOKEN)
#
# # get list of logged-in user
# a_user = api.current
# #=> returns an instance of GitHubV3API::User
#
# a_user.login
# #=> 'jwilger'
#
class UsersAPI
# Typically not used directly. Use GitHubV3API#users instead.
#
# +connection+:: an instance of GitHubV3API
def initialize(connection)
@connection = connection
end
# Returns a single GitHubV3API::User instance representing the
# currently logged in user
def current
user_data = @connection.get("/user")
GitHubV3API::User.new(self, user_data)
end
# Returns a GitHubV3API::User instance for the specified +username+.
#
# +username+:: the string login of the user, e.g. "octocat"
def get(username)
user_data = @connection.get("/users/#{username}")
GitHubV3API::User.new_with_all_data(self, user_data)
end
end
end
|
require 'roar/decorator'
require 'roar/json'
module UserRepresenter
include Roar::JSON
property :first_name
property :last_name
property :full_name
property :email
def full_name
"#{first_name} #{last_name}"
end
end
|
class Resetter < ActionMailer::Base
default from: 'admin@po-it.com'
def reset(user)
@token = user.token
mail(to: user.email, subject: 'Password Reset Link')
end
end |
class CreateLimitFees < ActiveRecord::Migration
def change
create_table :limit_fees do |t|
t.integer :period_id
t.integer :person_id
t.decimal :limit_fee
t.timestamp :created_on
t.timestamp :updated_on
t.string :remark
end
end
end
|
class Click
include RecordData
include Mongoid::Document
include Mongoid::Timestamps::Created
include Geocoder::Model::Mongoid
field :ip, type: String
field :url, type: String
field :article_id, type: String
field :user_id, type: String
field :country, type: String
field :city, type: String
field :coordinates, type: Array
geocoded_by :country
geocoded_by :city
belongs_to :article
after_validation :geocode
class << self
def clicks_per_article_per_day
map = %Q{
function(){
emit({created_at: this.created_at, article_id: this.article_id}, {count: 1});
}
}
reduce = %Q{
function(key, values) {
var count = 0;
values.forEach(function(v){
count += v['count'];
});
return {count: count};
}
}
click_count = map_reduce(map, reduce).out(inline: true)
return click_count
end
def get_click_data
daily_clicks = clicks_per_article_per_day
click_data = []
daily_clicks.each do |d|
id = d["_id"]
daily_clicks = d["value"]
date = d["_id"]["created_at"]
clicks = daily_clicks["count"]
click_data << {date: date, clicks: clicks.to_i}
end
return click_data
end
def clicks_per_country
map = %Q{
function() {
emit({country: this.country}, {count: 1});
}
}
reduce = %Q{
function(key, values) {
var count = 0;
values.forEach(function(v) {
count += v['count'];
});
return {count: count};
}
}
unique_clicks = map_reduce(map, reduce).out(inline: true)
return unique_clicks
end
def get_click_by_country_data
demographics = clicks_per_country
@impressions_data = []
demographics.each do |d|
id = d["_id"]
demo = d["value"]
country = id["country"]
visits = demo["count"]
@impressions_data << {label: country, value: visits.to_i}
end
return @impressions_data
end
end
end
|
module AdminPage
module Protocols
class Edit < ApplicationPage
MEDICATION_LIST_NAME = {id: "medication_list_name"}.freeze
MEDICATION_LIST_FOLLOWUP_DAYS = {id: "medication_list_follow_up_days"}.freeze
UPDATE_MEDICATION_LIST_BUTTON = {css: "input.btn-primary"}.freeze
def update_medication_list_followup_days(followup_days)
type(MEDICATION_LIST_FOLLOWUP_DAYS, followup_days)
click(UPDATE_MEDICATION_LIST_BUTTON)
end
def update_medication_list_name(name)
type(MEDICATION_LIST_NAME, name)
click(UPDATE_MEDICATION_LIST_BUTTON)
end
end
end
end
|
require 'rubygems'
require 'mtest'
require File.join(File.dirname(__FILE__), '..', 'lib', 'dicelib')
class String
def match?(rxp)
!match(rxp).nil?
end
end
class Array
def each_is?(arg)
meth, param = case arg
when Class
[:is_a?, arg]
when Symbol
[arg, nil]
end
answer = true
for i in self
unless (param.nil? ? i.__send__(meth) : i.__send__(meth, param) )
answer = false
end
end
answer
end
end
def run_tests(klass)
puts
results = {:pass => 0, :fail => 0, :err => 0}
(t = klass.new).methods.sort.each do |meth|
if meth =~ /^test_/
t.setup if t.respond_to?(:setup)
MTest(t.__send__(meth.to_sym)).each {|k,v| results[k] += v }
puts
end
end
print " Pass : "+"#{results[:pass]}"._g
print " | Fail : "+"#{results[:fail]}"._r
print " | Errors: "+"#{results[:err]}"._p+"\n"
end
|
module Brower
class Install
def initialize(pack)
@pack = "../../packages/#{pack}"
@outname = pack + ".zip"
@name = pack
self.get
self.install
end
def get
p = open(@pack)
packurl = p.gets
system("curl #{packurl} -o #{@outname}")
p.close
end
def install
system("unzip #{@outname}")
system("mv #{@name} $HOME/.Brower/#{@name}")
end
end
end
|
require './spec/spec_helper.rb'
def new_connection_url
Orientdb::ORM.connection_uri.tap { |uri| uri.database = 'brand_spanking_new' }.to_s
end
def existing_connection_url
Orientdb::ORM.connection_uri.to_s
end
describe Orientdb::ORM::Database do
describe '.exists?', :with_database do
it "does not find the new #{ URI(new_connection_url).database } database" do
expect( described_class.new(new_connection_url) ).not_to exist
end
it "finds the existing #{ URI(existing_connection_url).database } database" do
expect( described_class.new(existing_connection_url) ).to exist
end
end
describe '.create' do
subject { described_class.new(Orientdb::ORM.connection_url, storage: :memory) }
after { described_class.new(Orientdb::ORM.connection_url).delete }
it "creates the #{ URI(Orientdb::ORM.connection_url).database } database" do
expect{ subject.create }.to change{ subject.exists? }.from(false).to(true)
end
end
describe '.delete' do
subject { described_class.new(Orientdb::ORM.connection_url, storage: :memory) }
before { subject.create }
it "deletes the #{ URI(Orientdb::ORM.connection_url).database } database" do
expect{ subject.delete }.to change{ subject.exists? }.from(true).to(false)
end
end
end
|
class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.references :partida, index: true
t.references :unidad_medida, index: true
t.string :codigo
t.string :nombre
t.string :unidad_medida
t.string :foto_file_name
t.timestamps
end
end
end
|
class CreateArticleRelations < ActiveRecord::Migration
def change
create_table :article_relations do |t|
t.integer :kind
t.belongs_to :article, foreign_key: true
t.integer :related_article_id
end
end
end
|
class VisitorInfo < ActiveRecord::Base
include GeoKit::Geocoders
def self.update_analytics(business_card, request, geo_location)
user_agent = UserAgent.parse(request.user_agent)
if user_agent[0].product == 'Opera'
browser = 'Opera'
elsif !user_agent[2].nil? && user_agent[2].product == 'Chrome'
browser = 'Chrome'
elsif !user_agent[3].nil? && user_agent[3].product == 'Safari'
browser = 'Safari'
else
browser = user_agent[2].product
end
location = IpGeocoder.geocode('12.215.42.19')
business_card.visitor_infos.create(
:browser => browser,
:version => user_agent.version,
:platform => user_agent[0].comment.join(" "),
:ip_address => request.remote_addr,
:domain_name => request.host,
:province => geo_location.province,
:state => geo_location.state,
:country_code => geo_location.country_code,
:zip => geo_location.zip,
:city => geo_location.city
)
end
def self.get_browser_stats_by_business_card(business_card)
self.where(:business_card_id => business_card.id).find(:all)
end
def self.get_browser_stats(visitor_infos)
browsers = {}
for info in visitor_infos
if browsers.has_key?(info.browser)
browsers[info.browser] += 1
else
browsers[info.browser] = 1
end
end
browsers
end
def self.get_browser_version_stats(visitor_infos)
versions = {}
for info in visitor_infos
if !versions.has_key?(info.browser)
versions[info.browser] = {}
end
if !versions[info.browser].has_key?(info.version)
versions[info.browser][info.version] = 1
else
versions[info.browser][info.version] += 1
end
end
versions
end
def self.get_platform_stats(visitor_infos)
platforms = {}
for info in visitor_infos
if platforms.has_key?(info.platform)
platforms[info.platform] += 1
else
platforms[info.platform] = 1
end
end
platforms
end
def self.get_country_stats(visitor_infos)
countries = {}
for info in visitor_infos
if countries.has_key?(info.country_code)
countries[info.country_code] += 1
else
countries[info.country_code] = 1
end
end
countries
end
end
|
Rails.application.routes.draw do
devise_for :doctors, :controllers => {
registrations: 'doctor/registrations'
}
devise_for :patients, :controllers => {
registrations: 'patient/registrations'
}
get 'home/index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root to: 'patients#index'
resources :patients
end
|
class Garment < ActiveRecord::Base
serialize :properties
serialize :options
# Used when a garment is not built from random like in the seeded characters.
def self.forge! data
type = data[:garment_type]
data = data.except :garment_type
"Garment::#{type.camelize}".constantize.forge! data
end
def support_class
"Garment::#{code.camelize}".constantize
end
def base_price= base
raise "Material must be set first." if material.nil?
self.price = (base * material.price_factor).to_i
end
def material
@material ||= Material.lookup(material_code)
end
def color
@color ||= Color.lookup(color_code)
end
def material_title
material.name.titlecase
end
def color_and_material_phrase
if color_code.nil?
return material.name
end
if color.pattern == "solid"
return "#{color.name} #{material.name}"
end
if color.pattern == "plaid"
return "#{color.short_description} #{material.name}"
end
end
end
|
class AddColumnDeliveryOrderIdToDeliveryOrderDetails < ActiveRecord::Migration
def change
add_column :delivery_order_details, :delivery_order_id, :integer
end
end
|
class Types::UserType < Types::BaseObject
field :id, ID, null: true
field :name, String, null: true
end
|
module Events
class NoteOnHadoopInstance < Note
has_targets :hadoop_instance
has_activities :actor, :hadoop_instance, :global
end
end |
class ChangeIdsToIntegers < ActiveRecord::Migration
def change
change_column :user_events, :user_id, 'integer USING CAST(user_id AS integer)'
change_column :user_events, :event_id, 'integer USING CAST(event_id AS integer)'
change_column :user_groups, :user_id, 'integer USING CAST(user_id AS integer)'
change_column :user_groups, :group_id, 'integer USING CAST(group_id AS integer)'
end
end
|
class AddInterstateRebateFields < ActiveRecord::Migration
def change
add_column :jobs, :interstate_rebate_confirmed, :boolean, :default => true
add_column :jobs, :interstate_invoice_confirmed, :boolean, :default => true
add_column :jobs, :interstate_rebate_amount, :decimal, :scale => 2, :precision => 12, :default => 0
add_column :jobs, :interstate_rebate_notes, :text
end
end
|
class Education < ApplicationRecord
belongs_to :website
validates :location, :start, :end, :description, presence: true
end
|
require "./script.rb"
require "test/unit"
class TestTheScript < Test::Unit::TestCase
def test_basic
expected_hash = { :firstname => "Tony", :lastname => "Soprano" }
assert_equal expected_hash, hashify([:firstname, :lastname], ["Tony", "Soprano"])
end
def test_bonus
expected_keys = [:firstname, :lastname]
expected_values = ["Tony", "Soprano"]
actual_keys, actual_values = arrayify({ :firstname => "Tony", :lastname => "Soprano" })
assert_equal expected_keys, actual_keys
assert_equal expected_values, actual_values
end
end
|
class Varietal < ApplicationRecord
has_and_belongs_to_many :appellations
end
|
#!/usr/bin/env ruby
# encoding: UTF-8
require_relative 'TreasureKind.rb'
module NapakalakiGame
class Treasure
attr_reader :name, :bonus, :type
def initialize(n, bon, t)
@name=n
@bonus=bon
@type=t
end
def to_s
"\n\tTesoro: " + @name +
"\n\t\tBonus: " + @bonus.to_s +
"\n\t\tTreasureKind: " + @type.to_s
end
end
end |
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
# NODE_COUNT = 4
SUBNET="172.3.4"
# puts "------------------------------"
NODE_COUNT = ENV['NODE_COUNT'].to_i > 0 ? ENV['NODE_COUNT'].to_i : 4
sPath=ENV['SHARE_PATH']
# if sPath.to_s.length > 0
# puts "Shared folder is #{sPath}"
# else
# puts "
# Usage :
# Bash :
# mkdir ../forVm
# SHARE_PATH=../forVm vagrant up
# Win(cmd) :
# mkdir c:\Users\xxxx\forVm
# set SHARE_PATH=c:\Users\xxxx\forVm
# vagrant up
# "
# end
# puts "------------------------------"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "centos/7"
config.vm.synced_folder ".", "/vagrant", type: "nfs", nfs_udp: false
config.vm.provision "shell", path: "./script/vmhost.sh"
config.vm.provision "shell", inline: "echo #{SUBNET}.10 s1 >> /etc/hosts"
(1..NODE_COUNT).each do |i|
config.vm.provision "shell", inline: "echo #{SUBNET}.1#{i} n#{i} >> /etc/hosts"
end
config.vm.define "s1" do |server|
server.vm.hostname = "Server1"
server.vm.network :private_network, ip: "#{SUBNET}.10"
server.vm.provision "shell", path: "./script/vmserver.sh"
if sPath.to_s.length > 0
server.vm.synced_folder sPath, "/home/vagrant/forVm"
end
(1..NODE_COUNT).each do |i|
server.vm.provision "shell", inline: "echo n#{i} >> /etc/ansible/hosts"
end
server.vm.provider :virtualbox do |vb|
vb.customize [
"modifyvm", :id,
"--memory", "1024"
]
end
end
(1..NODE_COUNT).each do |i|
config.vm.define "n#{i}" do |node|
node.vm.hostname = "Node#{i}"
node.vm.network :private_network, ip: "#{SUBNET}.1#{i}"
node.vm.provider :virtualbox do |vb|
vb.customize [
"modifyvm", :id,
"--memory", "256"
]
end
end
end
end
|
# frozen_string_literal: true
module KepplerFrontend
module Editor
# CodeHandler
class FileFormat
def initialize; end
def validate(file)
content_type = File.extname(file)
result = false
utils_files.formats.each do |_key, value|
result = true if value.include?(content_type)
end
result
end
private
def utils_files
KepplerFrontend::Utils::FileFormat.new
end
def assets
KepplerFrontend::Urls::Assets.new
end
end
end
end
|
class Timesheet < ApplicationRecord
validates :start, presence: true
validates :finish, presence: true
validates :date, presence: true
validate :start_must_be_before_finish
validate :date_cannot_be_in_future
validate :timesheet_entries_must_not_overlap
def date_cannot_be_in_future
if date.present? && date > Date.today
errors.add(:date, "can't be in the future")
end
end
def start_must_be_before_finish
if start.present? && finish.present? && start >= finish
errors.add(:finish, "time must be after start time")
end
end
def timesheet_entries_must_not_overlap
same_date_timesheets = Timesheet.where(date: date).where.not(id:self.id)
if same_date_timesheets == nil
return
end
same_date_timesheets.each do |same_date_timesheet|
# Given entries have the same date, must ensure one finishes before the other starts
unless same_date_timesheet.finish < start or finish < same_date_timesheet.start
unless errors.added?(:This, "entry overlaps with an exiting timesheet entry")
errors.add(:This, "entry overlaps with an exiting timesheet entry")
end
end
end
end
end
|
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class YammerStaging < OmniAuth::Strategies::Yammer
option :name, 'yammer_staging'
option :client_options, {
site: 'https://www.staging.yammer.com',
authorize_url: '/dialog/oauth',
token_url: '/oauth2/access_token.json'
}
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.