text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
class BaseMonad
include Dry::Monads[:do, :maybe, :result]
def find(model, **query)
Maybe(model.find_by(**query))
end
end
|
#encoding: utf-8
module ModeloQytetet
class Jugador
attr_accessor :casilla_actual,:encarcelado, :saldo, :propiedades
attr_writer :carta
attr_reader :nombre, :factorEspeculador
def initialize(n)
@encarcelado = false
@nombre = n
@saldo = 7500
@casilla_actual = nil
@propiedades = Array.new
@carta = nil
@factorEspeculador = 1
end
def tengo_propiedades
return @propiedades.length != 0
end
def get_propiedad(numero)
@propiedades.at(numero)
end
def actualizar_posicion(casilla)
tengoPropietario= false
if casilla.numeroCasilla < @casilla_actual.numeroCasilla
modificar_saldo(1000)
end
@casilla_actual = casilla
if casilla.soy_edificable
tengoPropietario = casilla.tengo_propietario
if casilla.tengo_propietario&& !casilla.propietario_encarcelado
modificar_saldo(-casilla.cobrar_alquiler)
end
end
if casilla.tipo == TipoCasilla::IMPUESTO
modificar_saldo(-casilla.coste)
end
tengoPropietario
end
def comprar_titulo
puedoComprar = false
if @casilla_actual.soy_edificable
tengoPropietario = @casilla_actual.tengo_propietario
if !tengoPropietario
costeCompra = @casilla_actual.coste
if costeCompra<=@saldo
titulo = @casilla_actual.asignar_propietario(self)
titulo.casilla = @casilla_actual
@propiedades << titulo
modificar_saldo(-costeCompra)
puedoComprar = true
end
end
end
puedoComprar
end
def devolver_carta_libertad
aux=@carta
@carta=nil
return @carta
end
def ir_a_carcel(c)
@casilla_actual = c
@encarcelado = true
end
def modificar_saldo(cantidad)
@saldo += cantidad
end
def obtener_capital
capital = @saldo
for i in @propiedades.length
precioEdificarHotelyCasa = @propiedades.at(i).casilla.get_precio_edificar()
costeBase = @propiedades.at(i).casilla.coste
numCasas = @propiedades.at(i).casilla.numCasas
numHoteles = @propiedades.at(i).casilla.numHoteles
if(!@propiedades.at(i).getHipotecada())
capital += costeBase + (precioEdificarHotelyCasa * (numCasas + numHoteles))
else
capital -= @propiedades.at(i).hipotecaBase
end
end
return capital;
end
def obtener_propiedades_hipotecadas(hipotecada)
hipotecadas = Array.new
noHipotecadas = Array.new
for i in 0..@propiedades.length
if(@propiedades.at(i).hipotecada)
hipotecadas << @propiedades.at(i)
else
noHipotecadas << @propiedades.at(i)
end
end
if(hipotecada)
return hipotecadas
else
return noHipotecadas
end
end
def pagar_cobrar_por_casa_hotel(cantidad)
numeroTotal=cuantas_casas_hoteles_tengo
modificar_saldo(numeroTotal*cantidad)
end
def pagar_libertad(cantidad)
tengoSaldo = tengo_saldo(cantidad)
if tengoSaldo
modificar_saldo(-cantidad)
end
tengoSaldo
end
def puedo_edificar_casa(c)
esMia = es_de_mi_propiedad(c)
if esMia
costeEdificarCasa = c.get_precio_edificar
tengoSaldo = tengo_saldo(costeEdificarCasa)
tengoSaldo
end
false
end
def puedo_edificar_hotel(c)
esMia = es_de_mi_propiedad(c)
if esMia
costeEdificarHotel = c.get_precio_edificar
tengoSaldo = tengo_saldo(costeEdificarHotel)
tengoSaldo
end
false
end
def puedo_hipotecar(c)
es_de_mi_propiedad(c)
end
def puedo_pagar_hipoteca(c) #Sin implementar
end
def puedo_vender_propiedad(c)
(es_de_mi_propiedad(c) && !c.tituloPropiedad.hipotecada)
end
def tengo_carta_libertad
return @cartaLibertad != nil
end
def vender_propiedad(c)
precioVenta = c.vender_titulo
modificar_saldo(precioVenta)
eliminar_de_mis_propiedades(c)
end
def cuantas_casas_hoteles_tengo
@propiedades.inject(0) do |sum, p|
sum + p.casilla.numCasas + p.casilla.numHoteles
end
end
def eliminar_de_mis_propiedades(c)
@propiedades.delete(c.tituloPropiedad)
end
def es_de_mi_propiedad(c)
for i in @propiedades
if(c == i.casilla)
return true
end
end
return false
end
def tengo_saldo(cantidad)
ret = false
if(@saldo >= cantidad)
ret = true
end
return ret
end
def pagar_impuestos(cantidad)
modificar_saldo(cantidad)
end
def convertirme(fianza)
nuevoEspeculador = Especulador.new(self, fianza)
nuevoEspeculador.propiedades.each do |propiet|
propiet.propietario = nuevoEspeculador
end
return nuevoEspeculador
end
def to_s
"\nNombre: #{@nombre}" \
"\nSaldo: #{@saldo}" \
"\nCarta Libertad: #{!@carta.nil?}" \
"\nEncarcelado: #{@encarcelado}" \
"\nCasilla Actual: #{@casilla_actual.numeroCasilla}" \
"\nPropiedades:" \
"#{@propiedades}" \
"\nFactor Especulador: #{@factorEspeculador}"
end
protected :pagar_impuestos
end
end
|
class VietnamesesController < ApplicationController
before_action :set_vietnamese, only: [:show, :edit, :update, :destroy]
before_action :check_login
# GET /vietnameses
# GET /vietnameses.json
def index
if(params[:search] && params[:search]!="")
@vietnameses = Vietnamese.admin_search(params[:search]).paginate(:page => params[:page], :per_page => 12)
else
@vietnameses = Vietnamese.paginate(:page => params[:page], :per_page => 12)
end
end
# GET /vietnameses/1
# GET /vietnameses/1.json
def show
end
# GET /vietnameses/new
def new
@vietnamese = Vietnamese.new
end
# GET /vietnameses/1/edit
def edit
end
#create row for table Vietnamese
# POST /vietnameses
# POST /vietnameses.json
def create
if params[:vietnamese][:sound_word]
file_name = Vietnamese.upload(params[:vietnamese][:sound_word],"vietnamese")
else
file_name = ""
end
@arr_parram = vietnamese_params
@arr_parram[:sound_word] = file_name
@arr_parram[:word_vietnamese]= @arr_parram[:word_vietnamese].strip
@arr_parram[:word_japanese] = @arr_parram[:word_japanese].strip
@arr_parram[:deleted] = 0 # từ chưa được xóa
@arr_parram[:word_vietnamese_replace] =Vietnamese.replace_special_chars(@arr_parram[:word_vietnamese].strip)
@vietnamese = Vietnamese.new(@arr_parram)
respond_to do |format|
if @vietnamese.save
format.html { redirect_to @vietnamese, notice: 'Vietnamese was successfully created.' }
format.json { render action: 'show', status: :created, location: @vietnamese }
else
format.html { render action: 'new' }
format.json { render json: @vietnamese.errors, status: :unprocessable_entity }
end
end
end
# update row
# PATCH/PUT /vietnameses/1
# PATCH/PUT /vietnameses/1.json
def update
deleted= params[:deleted]
@arr_parram = vietnamese_params
files = @vietnamese.sound_word
if params[:vietnamese][:sound_word] && files!=""
file_name = Vietnamese.upload(params[:vietnamese][:sound_word], "vietnamese")
File.delete("public/vietnamese/" + files)
@arr_parram[:sound_word] = file_name
elsif files!=""
@arr_parram[:sound_word] = files
elsif params[:vietnamese][:sound_word]
file_name = Vietnamese.upload(params[:vietnamese][:sound_word], "vietnamese")
@arr_parram[:sound_word] = file_name
end
@arr_parram[:word_vietnamese]= @arr_parram[:word_vietnamese].strip
@arr_parram[:word_japanese] = @arr_parram[:word_japanese].strip
@arr_parram[:deleted] = deleted
@arr_parram[:word_vietnamese_replace] =Vietnamese.replace_special_chars(@arr_parram[:word_vietnamese].strip)
respond_to do |format|
if @vietnamese.update(@arr_parram)
format.html { redirect_to @vietnamese, notice: 'Vietnamese was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @vietnamese.errors, status: :unprocessable_entity }
end
end
end
# update column deleted = 1 for row deleted
# DELETE /vietnameses/1
# DELETE /vietnameses/1.json
def destroy
respond_to do |format|
if @vietnamese.update_attributes(:deleted => 1)
format.html { redirect_to vietnameses_path, notice: 'Vietnamese was successfully deleted.' }
format.json { head :no_content }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_vietnamese
@vietnamese = Vietnamese.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def vietnamese_params
params.require(:vietnamese).permit(:word_vietnamese, :word_japanese, :sound_word, :deleted, :note)
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
8.times do |n|
Rate.create(sell: [71.2, 70.3, 69.4, 72.9, 75.1].sample,
buy: [65.2, 67.7, 63.4, 64.9, 66.5].sample,
currency: 'EUR',
created_at: DateTime.parse("#{Date.today - n.days}"))
Rate.create(sell: [63.2, 62.3, 61.4, 64.9, 67.1].sample,
buy: [57.2, 59.7, 55.4, 56.9, 58.5].sample,
currency: 'USD',
created_at: DateTime.parse("#{Date.today - n.days}"))
end
|
# frozen_string_literal: true
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
ENV['SAUCE_BUILD_NAME'] = "Ruby EmuSim Local - #{Time.now.to_i}"
# parallel_test gem setting for how many to run in parallel
ENV['TEST_ENV_NUMBER'] = '25'
desc 'Android Emulator'
task :android do
ENV['DEVICE_NAME'] = 'Android GoogleAPI Emulator'
system('parallel_rspec -- -t platform:android -- spec')
end
desc 'iOS Simulator'
task :iphone do
ENV['DEVICE_NAME'] = 'iPhone Simulator'
system('parallel_rspec -- -t platform:ios -- spec')
end
desc 'Safari'
task :safari do
ENV['BROWSER_NAME'] = 'Safari'
ENV['PLATFORM_NAME'] = 'iOS'
ENV['DEVICE_NAME'] = 'iPhone Simulator'
system('parallel_rspec -- -t platform:web -- spec')
end
desc 'Chrome'
task :chrome do
ENV['BROWSER_NAME'] = 'Chrome'
ENV['PLATFORM_NAME'] = 'Android'
ENV['DEVICE_NAME'] = 'Android GoogleAPI Emulator'
system('parallel_rspec -- -t platform:web -- spec')
end
# For larger test suites probably don't want to use multitask for this
desc 'run all configs in parallel'
multitask parallel: %i[android iphone safari chrome]
|
class Advert2sController < ApplicationController
before_action :set_advert2, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /advert2s
# GET /advert2s.json
def index
@advert2s = Advert2.all
end
# GET /advert2s/1
# GET /advert2s/1.json
def show
end
# GET /advert2s/new
def new
@advert2 = Advert2.new
end
# GET /advert2s/1/edit
def edit
end
# POST /advert2s
# POST /advert2s.json
def create
@advert2 = Advert2.new(advert2_params)
respond_to do |format|
if @advert2.save
format.html { redirect_to @advert2, notice: 'Advert2 was successfully created.' }
format.json { render :show, status: :created, location: @advert2 }
else
format.html { render :new }
format.json { render json: @advert2.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /advert2s/1
# PATCH/PUT /advert2s/1.json
def update
respond_to do |format|
if @advert2.update(advert2_params)
format.html { redirect_to @advert2, notice: 'Advert2 was successfully updated.' }
format.json { render :show, status: :ok, location: @advert2 }
else
format.html { render :edit }
format.json { render json: @advert2.errors, status: :unprocessable_entity }
end
end
end
# DELETE /advert2s/1
# DELETE /advert2s/1.json
def destroy
@advert2.destroy
respond_to do |format|
format.html { redirect_to advert2s_url, notice: 'Advert2 was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_advert2
@advert2 = Advert2.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def advert2_params
params.require(:advert2).permit(:image, :link)
end
end
|
class AddCompanyToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :name, :string, null:false
add_column :users, :indutry_type, :string, null:false
add_column :users, :foundation_date, :date, null:false
add_column :users, :capital, :integer, null:false
add_column :users, :employee_number, :integer, null:false
add_column :users, :prefectures_id, :integer, null:false
add_column :users, :address, :string, null:false
add_column :users, :phone_number, :string, null: false, limit: 11, unique: true
end
end
|
##----------------------------------------------------------------------------##
## The Legend of NeonBlack's Maus Romancing Sa-Ga Script v1.0
## Created by Neon Black
##
## For both commercial and non-commercial use as long as credit is given to
## Neon Black and any additional authors. Licensed under Creative Commons
## CC BY 3.0 - http://creativecommons.org/licenses/by/3.0/.
##----------------------------------------------------------------------------##
##
##----------------------------------------------------------------------------##
## Revision Info:
## v1.0 - 3.3.2013
## Wrote and debugged main script
##----------------------------------------------------------------------------##
##
$imported ||= {} ##
$imported["CP_RELATIONSHIP"] = 1.0 ##
##
##----------------------------------------------------------------------------##
## Instructions:
## Place this script in the script editor below "Materials" and above "Main".
## This script requires Neon Black's Features and Effects name module. You can
## obtain it from http://cphouseset.wordpress.com/modules/. If you do not
## import it, you will get errors.
##
## This script allows additional features to be gained via relationships between
## two characters. The names, descriptions, and power of the features can be
## modified by the script as well as numerous other conditions. This script
## has both note tags and script calls that allow it to work. These are as
## follows.
##
##------
## Notebox Tags:
##
## relationship[+5 atk] -or- friends[-1% def] -or- lovers[+5.5% mmp] -etc-
## - The main tag used by this script and by far the most useful. The tag can
## be used to define if the bonus should apply to friends, lovers, or all
## relationship types. You can set any value, positive or negative, whole or
## decimal, percentage or integer. The last section of the code is the 3
## letter name of the stat to modify. Any stat from page 2 of a features
## box may be used. By default, all bonuses are added only when BOTH party
## members are in the battle party. At this time, extra parameter scripts
## will not work with this script.
## relationship[skill 5] -etc-
## - Allows a skill to be learned when a relation ship is formed. The skill
## will be learned as long as relationship type and party conditions are met
## so it is advised to use additional parameters for this tag (see below).
## The "relationship" value of this tag can be replaced with "lovers" or
## "friends" like the tag above.
## friends[weapon 2] -or- lovers[armor 3] -etc-
## - Allows weapons or armours of certain types to be equipped even if the
## actor would not normally be able to equip them. All the same rules as
## skills above apply.
## for actor[3] -or- for actor[1, 2, 3]
## - Allows additional parameters to be added to a bonus that allow only
## certain actors to recieve the bonus. This tag goes immediately after the
## bonus you want to tag, for example: relationship[+1% mmp] for actor[2]
## for level[4] -or- for level[3+] -or- for level[1-5]
## - Allows additional parameters to be added to a bonus that prevent the bonus
## from being added unless the relationship level is in the specified range.
## This works similar to the tag above.
## <relationship party> -and- </relationship party>
## - Allows all bonuses between the tags to be used as long as both party
## members are in the party, even if they are not in the battle party
## together.
## <relationship constant> -and- </relationship constant>
## - Similar to the tags above, however all bonuses between these tags are
## ALWAYS active, even if the actors are not in the party together.
## gender[male] -and- gender[female]
## - Used to determine the base gender of a character. By default, same sex
## couples are friends and opposite sex couples are lovers. If the
## HOMOSEXUAL option is disabled, same sex couples can only reach the defined
## cap in the lovers catagory.
##
##------
## Script Calls:
##
## Relationship.open
## - Quite simply, opens the status screen.
## Relationship.exp(actor1, actor2, exp)
## - Used to alter the exp of a relationship. The exp can be positive or
## negative. All other normal things that would happen occur automatically.
## Relationship.type(actor1, actor2, :switch)
## - Used to change the type of relationship two actors are in. This
## automatically breaks a max level relationship if one has been established.
## Note that :switch will switch the type of relationship from/to both
## friends/lovers, while you can use :lovers or :friends to define the type
## to switch to manually.
## Relationship.level(actor1, actor2) -or- Check.relationship_level(a1, a2)
## - Gets the relationship level of two actors. Can be used for conditional
## script calls and such.
## Relationship.between(actor1, actor2) -or- Check.relationship_between(a, b)
## - Gets the type of relationship two actors are in. Returns a value of
## either :lovers or :friends.
##----------------------------------------------------------------------------##
##
module CP # Do not touch ##
module RELATIONSHIP # these lines. ##
##
##----------------------------------------------------------------------------##
## Config:
## The config options are below. You can set these depending on the flavour of
## your game. Each option is explained in a bit more detail above it.
##
##------
# This hash contains the info for each level of friendship. The key is the
# level. The first value is the exp required to reach that level, the second
# value is the name of that level, the third value is the description for the
# level, and the last value is the bonus multiplier for the level.
FRIEND_LEVELS ={
1 => [1, "Stranger", "Only just met each other", 0.0],
2 => [5, "Aquaintance", "Know about each other at best", 0.0],
3 => [10, "Party Member", "Just work together", 1.0],
4 => [15, "Friends", "Are friendly with each other", 2.0],
5 => [20, "Good Friends", "Trust each other", 3.0],
6 => [25, "Teammate", "Would go to the other's aid", 4.0],
7 => [35, "Best Friends", "Rush to each other's aid", 6.0],
8 => [45, "Partners", "Trust each other with their lives", 8.0],
}
# Same as above, but for lover levels.
LOVER_LEVELS ={
1 => [1, "Stranger", "Only just met each other", 0.0],
2 => [5, "Aquaintance", "Know about each other at best", 0.0],
3 => [10, "Party Member", "Just work together", 1.0],
4 => [15, "Friends", "Are friendly with each other", 2.0],
5 => [20, "Good Friends", "Trust each other", 3.0],
6 => [25, "Crush", "Share a mutual attraction", 4.0],
7 => [30, "Close", "Getting to know each other", 5.0],
8 => [35, "Dating", "Getting to know each other", 6.0],
9 => [40, "Lovers", "Certain of each other's love", 8.0],
10 => [45, "Soul Mate", "Bound by fate", 10.0],
}
# And finally rival levels for negative amounds of EXP. This array starts at 0
# and goes DOWN into the negatives.
ENEMY_LEVELS ={
0 => [0, "Annoyance", "Barely tolerate each other", 0.0],
-1 => [-10, "Rival", "Fed up with each other", 0.0],
-2 => [-25, "Enemy", "Do not get along at all", -1.0],
}
# The caps for all other relationships of the same type when a relationship has
# reached max in that catagory.
FRIEND_CAP = 6
LOVER_CAP = 5
# The minimum levels required for a name and rank to appear in the menu.
FRIEND_MIN = 4
LOVER_MIN = 6
# If this is set to true, if a lover has not reached the minimum lover level to
# appear in the menu, but has enough EXP that they are the highest relationship
# AND they have reached the minimum level required for friends, they will appear
# as a friend. If you are confused by this option, please just turn it off.
LOVER_AS_FRIEND = true
# The symbol that separates the name and relationship ranking when a lover or
# friend is drawn in a window. Ignore the misspelling.
SEPERATOR = '-'
# The text to display when no characters can be classified as a closest relation
# of some sort.
NO_FRIEND = "Lone Wolf"
NO_LOVER = "Single"
NO_ENEMY = "No Enemies"
# While this value is false, same sex couples cannot go above LOVER_CAP in the
# lovers catagory. If it is set to true, they function the same as opposite
# sex couples. This is only to prevent bugs and not meant to portray any way
# of thinking.
HOMOSEXUAL = false
# This option determines if the character's lover is displayed in the status
# screen. This will display right below the equips if it is enabled.
STATUS_SCREEN = true
# Define if a menu option can be used to access a page displaying all
# relationship bonuses. Also allows you to name this option.
USE_MENU = true
MENU_NAME = "Relationships"
# Used in the scene mentioned above to display the closest friend and lover.
FRIEND_NAME = "Closest Friend"
LOVER_NAME = "Closest Relationship"
##----------------------------------------------------------------------------##
##
##
##----------------------------------------------------------------------------##
## The following lines are the actual core code of the script. While you are
## certainly invited to look, modifying it may result in undesirable results.
## Modify at your own risk!
###----------------------------------------------------------------------------
end
end
module DataManager
class << self
alias :cp_rshp_setup_new_game :setup_new_game
alias :cp_rshp_setup_battle :setup_battle_test
end
def self.setup_new_game(*args)
cp_rshp_setup_new_game(*args)
$game_party.all_members.each { |m| m.recover_all }
end
def self.setup_battle_test(*args)
cp_rshp_setup_battle(*args)
$game_party.all_members.each { |m| m.recover_all }
end
end
module SceneManager
class << self
alias :cp_rshp_run :run unless method_defined?(:cp_rshp_run)
end
def self.run
cp_module_check_features
cp_rshp_run
end
def self.cp_module_check_features
return if $imported["CP_FEATURES_EFFECTS"]
a1 = "One or more scripts require Neon Black's Features and Effects module."
a2 = "This can be obtained at http://cphouseset.wordpress.com/modules/"
a3 = "Please add this module and try again."
a4 = "Please contact the creator of the game to resolve this issue."
if $TEST || $BTEST
msgbox "#{a1}/n#{a2}/n#{a3}"
Thread.new{system("start http://cphouseset.wordpress.com/modules/#features")}
else
msgbox "#{a1}/n#{a4}"
end
end
end
module Relationship
def self.exp(act1, act2, exp)
old_lvl = $game_party.relationship_level(act1, act2)
mlvl = $game_party.change_rlevel_exp(act1, act2, exp)
if $game_party.relationship_level(act1, act2) < mlvl
$game_party.break_relationship(act1, act2)
elsif exp >= 0
$game_party.make_relationship(act1, act2)
end
if old_lvl != $game_party.relationship_level(act1, act2)
$game_party.reset_relationship
end
end
def self.type(act1, act2, val = :switch)
$game_party.break_relationship(act1, act2)
mlvl = $game_party.relationship_type_switch(act1, act2, val)
if $game_party.relationship_level(act1, act2) >= mlvl
$game_party.make_relationship(act1, act2)
end
$game_party.reset_relationship
end
def self.level(act1, act2)
$game_party.relationship_level(act1, act2)
end
def self.between(act1, act2)
$game_party.relationship_type(act1, act2)
end
def self.open
SceneManager.call(Scene_RelationshipStatus)
end
end
module Check
def self.relationship(act1, act2)
[relationship_between(act1, act2), relationship_level(act1, act2)]
end
def self.relationship_level(act1, act2)
$game_party.relationship_level(act1, act2)
end
def self.relationship_between(act1, act2)
$game_party.relationship_type(act1, act2)
end
end
class Game_Actors
def each
make_all_actors
@data.each do |actor|
next unless actor
yield actor
end
end
def size
make_all_actors
@data.size
end
def make_all_actors
return if @all_setup; @all_setup = true
$data_actors.each_with_index do |act, id|
next unless act
@data[id] ||= Game_Actor.new(id)
end
end
end
class Game_Actor < Game_Battler
alias :cp_rshp_init :initialize
def initialize(*args)
cp_rshp_init(*args)
@relationship_bonuses = {}
end
def reset_relationship
@relationship_bonuses = {}
relationship_features
refresh
end
alias :cp_rshp_features :all_features
def all_features
cp_rshp_features + relationship_features
end
def relationship_features
return [] unless @relationship_bonuses
battle_party_rsfeatures + current_party_rsfeatures + all_party_rsfeatures
end
def battle_party_rsfeatures
result = []
return result unless $game_party.battle_members.include?(self)
$game_party.battle_members.each do |mem|
next if mem.nil? || mem.id == self.id
result += mem.relationship_bonuses(@actor_id, :battle)
end
result
end
def current_party_rsfeatures
result = []
return result unless $game_party.all_members.include?(self)
$game_party.all_members.each do |mem|
next if mem.nil? || mem.id == self.id
result += mem.relationship_bonuses(@actor_id, :party)
end
result
end
def all_party_rsfeatures
result = []
$game_actors.each do |mem|
next if mem.nil? || mem.id == self.id
result += mem.relationship_bonuses(@actor_id, :game)
end
result
end
def rsfeatures_total_others
results = {}
$game_actors.each do |mem|
next if mem.nil? || mem.id == self.id
results[mem.id] = []
mem.relationship_bonuses(@actor_id, :battle).each do |ft|
results[mem.id].push([:battle, ft])
end
mem.relationship_bonuses(@actor_id, :party).each do |ft|
results[mem.id].push([:party, ft])
end
mem.relationship_bonuses(@actor_id, :game).each do |ft|
results[mem.id].push([:game, ft])
end
end
return results
end
def relationship_bonuses(id, scope)
@relationship_bonuses = {} if @relationship_bonuses.nil?
return @relationship_bonuses[id][scope] if @relationship_bonuses.include?(id)
make_relationship_features(@actor_id, id)
return @relationship_bonuses[id][scope]
end
def make_relationship_features(host, id)
@relationship_bonuses[id] = {:battle=>[], :party=>[], :game=>[]}
rlevel = $game_party.relationship_level(host, id)
multi = $game_party.relationship_multiplier(host, id)
rtype = $game_party.relationship_type(host, id, false)
actor.relationship_features.each do |scope, array|
array.each do |item|
next unless item[4] == rtype || item[4] == :relationship
next if !item[5][:actor].empty? && !item[5][:actor].include?(id)
next unless level_from_array(rlevel, item[5][:level])
@relationship_bonuses[id][scope].push(get_feature_from_array(item, multi))
end
@relationship_bonuses[id][scope].compact!
end
end
def level_from_array(rlevel, lvl)
case lvl
when /(\d+)[-](\d+)/i
return rlevel >= $1.to_i && rlevel <= $2.to_i
when /(\d+)[\+]/i
return rlevel >= $1.to_i
when /(\d+)/i
return rlevel == $1.to_i
else
return true
end
end
def get_feature_from_array(array, multi)
case array[0]
when :stat
return nil unless multi != 0
codes = CP::Features.get_feature(array[3], array[2])
return nil unless codes
ft = RPG::BaseItem::Feature.new(codes[0], codes[1], array[1] * multi)
when :skill
ft = RPG::BaseItem::Feature.new(43, array[1], 0)
when :weapon
ft = RPG::BaseItem::Feature.new(51, array[1], 0)
when :armor, :armour
ft = RPG::BaseItem::Feature.new(52, array[1], 0)
end
return ft
end
def gender
unless @composite_male.nil?
return @composite_male ? :male : :female
else
return actor.gender
end
end
end
class Game_Party < Game_Unit
def reset_relationship
$game_actors.each { |m| m.reset_relationship }
end
def relationship_type(act1, act2, rrival = true)
a1, a2 = [act1, act2].sort
init_relationship_table unless @relationship_table
table_type, exp_level = @relationship_table[[a1, a2]]
return table_type unless rrival
return exp_level > 0 ? table_type : :rivals
end
def relationship_level(act1, act2)
a1, a2 = [act1, act2].sort
init_relationship_table unless @relationship_table
table_type, exp_level = @relationship_table[[a1, a2]]
return 0 if table_type.nil? || exp_level.nil?
if table_type == :friends
top = @friends_hash[a1] ? @friends_hash[a1] == a2 : true
elsif table_type == :lovers
top = false if !CP::RELATIONSHIP::HOMOSEXUAL &&
$game_actors[a1].gender == $game_actors[a2].gender
top = @lovers_hash[a1] ? @lovers_hash[a1] == a2 : true
end
return [make_rlevel(table_type, exp_level),
make_rcap(table_type, top || true)].min
end
def make_rlevel(type, exp)
if exp > 0
lvl = 1
cp_relate_hashes(type).each do |key, array|
lvl = key if key > lvl && exp >= array[0]
end
else
lvl = 0
cp_relate_hashes(:rivals).each do |key, array|
lvl = key if key < lvl && exp <= array[0]
end
end
return lvl
end
def change_rlevel_exp(act1, act2, exp)
a1, a2 = [act1, act2].sort
init_relationship_table unless @relationship_table
type = @relationship_table[[a1, a2]][0]
@relationship_table[[a1, a2]][1] += exp
check_relationship_cap(a1, a2, type)
return cp_relate_hashes(type).keys.max
end
def check_relationship_cap(act1, act2, type = nil)
a1, a2 = [act1, act2].sort
table_type, exp = @relationship_table[[a1, a2]]
if type == :friends
return if table_type != type ||
(@friends_hash[a1].nil? && @friends_hash[a2].nil?) ||
(@friends_hash[a1] == a2 && @friends_hash[a2] == a1)
cap = CP::RELATIONSHIP::FRIEND_CAP
elsif type == :lovers
return if table_type != type ||
(@lovers_hash[a1].nil? && @lovers_hash[a2].nil?) ||
(@lovers_hash[a1] == a2 && @lovers_hash[a2] == a1)
cap = CP::RELATIONSHIP::LOVER_CAP
else
return
end
mexp = cp_relate_hashes(type)[cap][0]
@relationship_table[[a1, a2]][1] = mexp if exp > mexp
end
def relationship_type_switch(act1, act2, val)
a1, a2 = [act1, act2].sort
init_relationship_table unless @relationship_table
type = @relationship_table[[a1, a2]][0]
case val
when :switch
if type == :lovers
@relationship_table[[a1, a2]][0] = :friends
elsif type == :friends
@relationship_table[[a1, a2]][0] = :lovers
end
when :lovers
@relationship_table[[a1, a2]][0] = :lovers
when :friends
@relationship_table[[a1, a2]][0] = :friends
end
return cp_relate_hashes(@relationship_table[[a1, a2]][0]).keys.max
end
def make_rcap(type, top)
lvl = 999
if type == :lovers
lvl = CP::RELATIONSHIP::LOVER_CAP unless top
elsif type == :friends
lvl = CP::RELATIONSHIP::FRIEND_CAP unless top
end
return lvl
end
def relationship_multiplier(act1, act2)
init_relationship_table unless @relationship_table
rlevel = relationship_level(act1, act2)
a1, a2 = [act1, act2].sort
table_type = relationship_type(a1, a2)
multi = cp_relate_hashes(table_type)[rlevel][3] rescue multi = 0
return multi
end
def break_relationship(act1, act2)
a1, a2 = [act1, act2].sort
table_type, exp_level = @relationship_table[[a1, a2]]
case table_type
when :friends
return unless @friends_hash[a1] == a2 && @friends_hash[a2] == a1
@friends_hash[a1] = nil
@friends_hash[a2] = nil
when :lovers
return unless @lovers_hash[a1] == a2 && @lovers_hash[a2] == a1
@lovers_hash[a1] = nil
@lovers_hash[a2] = nil
end
end
def make_relationship(act1, act2)
a1, a2 = [act1, act2].sort
table_type, exp_level = @relationship_table[[a1, a2]]
case table_type
when :friends
return unless @friends_hash[a1].nil? && @friends_hash[a2].nil?
@friends_hash[a1] = a2
@friends_hash[a2] = a1
when :lovers
return unless @lovers_hash[a1].nil? && @lovers_hash[a2].nil?
@lovers_hash[a1] = a2
@lovers_hash[a2] = a1
end
$game_actors.each do |a3|
next if a3.nil? || a3.id == a1 || a3.id == a2
check_relationship_cap(a1, a3.id, table_type)
check_relationship_cap(a2, a3.id, table_type)
end
end
def cp_relate_hashes(table)
case table
when :lovers
return CP::RELATIONSHIP::LOVER_LEVELS
when :friends
return CP::RELATIONSHIP::FRIEND_LEVELS
when :rivals
return CP::RELATIONSHIP::ENEMY_LEVELS
else
return {}
end
end
def init_relationship_table
@relationship_table = {}
@lovers_hash = {}
@friends_hash = {}
$game_actors.each do |a1|
next unless a1
@lovers_hash[a1] = nil
@friends_hash[a1] = nil
$game_actors.each do |a2|
next if !a2 || a1.id >= a2.id
status = a1.gender == a2.gender ? :friends : :lovers
exp = 1
@relationship_table[[a1.id, a2.id]] = [status, exp]
end
end
end
def greatest_relationship(act, type)
if type == :friends
return @friends_hash[act] if @friends_hash[act]
elsif type == :lovers
return @lovers_hash[act] if @lovers_hash[act]
end
result = 0
exp = nil
$game_actors.each do |a|
next if a.nil? || a.id == act
rt = relationship_type(a.id, act)
rl = relationship_level(a.id, act)
next if !CP::RELATIONSHIP::LOVER_AS_FRIEND && type != rt
next if (type == :lovers && !@lovers_hash[a.id].nil? &&
@lovers_hash[a.id] != act) || (type == :friends &&
!@friends_hash[a.id].nil? && @friends_hash[a.id] != act)
a1, a2 = [a.id, act].sort
next if type == :lovers && (rt != :lovers ||
rl < CP::RELATIONSHIP::LOVER_MIN)
next if type == :friends && (rl < CP::RELATIONSHIP::FRIEND_MIN ||
(rt == :lovers && rl >= CP::RELATIONSHIP::LOVER_MIN))
_, aex = @relationship_table[[a1, a2]]
next unless exp.nil? || aex.abs > exp.abs
result, exp = a.id, aex
end
return result
end
end
class Scene_Menu < Scene_MenuBase
alias :cp_rshp_form_ok :on_formation_ok
def on_formation_ok(*args)
cp_rshp_form_ok(*args)
$game_party.all_members.each { |m| m.refresh }
@status_window.refresh
end
end
##------
## Scenes and windows below.
##------
class Scene_RelationshipStatus < Scene_MenuBase
def start
super
draw_all_windows
end
def draw_all_windows
@top_window = Window_RelationshipTop.new(@actor)
@bonus_window = Window_RelationshipBonus.new(@top_window)
@bonus_window.set_handler(:ok, method(:select_actor))
@bonus_window.set_handler(:cancel, method(:return_scene))
@bonus_window.set_handler(:pagedown, method(:next_actor))
@bonus_window.set_handler(:pageup, method(:prev_actor))
end
def select_actor
@actor = $game_actors[@bonus_window.valid_partners.keys[@bonus_window.index]]
on_actor_change
end
def on_actor_change
@top_window.actor = @actor
@top_window.refresh
@bonus_window.refresh
@bonus_window.activate
end
end
class Scene_Menu < Scene_MenuBase
alias :cp_rshp_cc_window :create_command_window
def create_command_window
cp_rshp_cc_window
@command_window.set_handler(:cp_rshp, method(:command_personal))
end
alias :cp_rshp_personal_ok :on_personal_ok
def on_personal_ok
cp_rshp_personal_ok
case @command_window.current_symbol
when :cp_rshp
Relationship.open
end
end
end
class Window_Base < Window
def draw_actor_friend(actor, x, y, width = 180)
act2 = $game_party.greatest_relationship(actor.id, :friends)
unless act2 == 0
rt = $game_party.relationship_type(actor.id, act2)
lvl = $game_party.relationship_level(actor.id, act2)
level = $game_party.cp_relate_hashes(rt)[lvl][1]
draw_relationship(act2, level, x, y, width)
else
draw_text(x + 24, y, width, line_height, CP::RELATIONSHIP::NO_FRIEND)
end
end
def draw_actor_lover(actor, x, y, width = 180)
act2 = $game_party.greatest_relationship(actor.id, :lovers)
unless act2 == 0
rt = $game_party.relationship_type(actor.id, act2)
lvl = $game_party.relationship_level(actor.id, act2)
level = $game_party.cp_relate_hashes(rt)[lvl][1]
draw_relationship(act2, level, x, y, width)
else
draw_text(x + 24, y, width, line_height, CP::RELATIONSHIP::NO_LOVER)
end
end
def draw_actor_rival(actor, x, y, width = 180)
act2 = $game_party.greatest_relationship(actor.id, :rivals)
unless act2 == 0
rt = $game_party.relationship_type(actor.id, act2)
lvl = $game_party.relationship_level(actor.id, act2)
level = $game_party.cp_relate_hashes(rt)[lvl][1]
draw_relationship(act2, level, x, y, width)
else
draw_text(x + 24, y, width, line_height, CP::RELATIONSHIP::NO_ENEMY)
end
end
def draw_relationship_between(act1, act2, x, y, width = 180)
lvl = $game_party.relationship_level(act1, act2)
case $game_party.relationship_type(act1, act2)
when :lovers
level = $game_party.cp_relate_hashes(:lovers)[lvl][1]
txt = $game_party.cp_relate_hashes(:lovers)[lvl][2]
when :friends
level = $game_party.cp_relate_hashes(:friends)[lvl][1]
txt = $game_party.cp_relate_hashes(:friends)[lvl][2]
when :rivals
level = $game_party.cp_relate_hashes(:rivals)[lvl][1]
txt = $game_party.cp_relate_hashes(:rivals)[lvl][2]
end
draw_relationship(act2, level, x, y, width)
lfs = contents.font.size
contents.font.size = contents.font.size / 6 * 5
draw_text(x, y + line_height, width, line_height, txt, 1)
contents.font.size = lfs
end
def draw_relationship(actor, level, x, y, width)
other = $game_actors[actor]
return unless other
draw_actor_icon(other, x, y)
lfs = contents.font.size
draw_text((x + width / 2) - 12, y, 24, line_height,
CP::RELATIONSHIP::SEPERATOR, 1)
contents.font.size = contents.font.size / 6 * 5
draw_actor_name(other, x + 24, y, (width / 2) - 36)
change_color(normal_color)
draw_text((x + width / 2) + 12, y, width / 2 - 16, line_height, level)
contents.font.size = lfs
end
def draw_actor_icon(actor, x, y)
character_name = actor.character_name
character_index = actor.character_index
return unless character_name
bitmap = Cache.character(character_name)
sign = character_name[/^[\!\$]./]
if sign && sign.include?('$')
cw = bitmap.width / 3
ch = bitmap.height / 4
else
cw = bitmap.width / 12
ch = bitmap.height / 8
end
n = character_index
src_rect = Rect.new(((n%4*3+1)*cw) + [(cw-24)/2, 0].max, (n/4*4)*ch,
[24, cw].min, 24)
contents.blt(x, y, bitmap, src_rect)
end
end
class Window_MenuCommand < Window_Command
alias :cp_rshp_ocomm :add_original_commands
def add_original_commands
cp_rshp_ocomm
if CP::RELATIONSHIP::USE_MENU
add_command(CP::RELATIONSHIP::MENU_NAME, :cp_rshp, main_commands_enabled)
end
end
end
class Window_Status < Window_Selectable
alias :cp_rshp_block3 :draw_block3
def draw_block3(y)
cp_rshp_block3(y)
return unless CP::RELATIONSHIP::STATUS_SCREEN
draw_actor_lover(@actor, 288, y + line_height * 5, 196)
end
end
class Window_RelationshipTop < Window_Base
attr_accessor :actor
def initialize(actor)
super(0, 0, Graphics.width, fitting_height(4))
@actor = actor
refresh
end
def refresh
contents.clear
draw_actor_face(@actor, 2, 0)
draw_actor_name(@actor, 106, line_height, 180)
draw_actor_nickname(@actor, 106, line_height * 2)
draw_favorites_block(290, contents.width - 290)
end
def draw_favorites_block(x, width)
change_color(system_color)
draw_text(x, 0, width, line_height, CP::RELATIONSHIP::FRIEND_NAME)
draw_text(x, line_height * 2, width, line_height,
CP::RELATIONSHIP::LOVER_NAME)
change_color(normal_color)
draw_actor_friend(@actor, x, line_height, width)
draw_actor_lover(@actor, x, line_height * 3, width)
end
end
class Window_RelationshipBonus < Window_Selectable
def initialize(parent)
@parent = parent
h = Graphics.height - @parent.height
super(@parent.x, @parent.y + @parent.height, Graphics.width, h)
refresh
activate
end
def col_max
return 2
end
def item_max
return valid_partners.size
end
def item_height
return line_height * 2 if item_max <= 0
return (valid_partners.values.collect{|s| s.size}.max + 2) * line_height + 8
end
def valid_partners
return @parent.actor.rsfeatures_total_others.select do |k,v|
$game_party.all_members.include?($game_actors[k]) || !v.empty?
end
end
def refresh
select(0)
create_contents
draw_all_items
end
def current_item_enabled?
return false if item_max <= 0
$game_party.all_members.include?($game_actors[valid_partners.keys[@index]])
end
def draw_item(index)
rect = item_rect(index)
rect.x += 2; rect.y += 4; rect.width -= 4
act = valid_partners.keys[index]
draw_relationship_between(@parent.actor.id, act, rect.x, rect.y,
rect.width)
valid_partners.values[index].each_with_index do |array, i|
text = array[1].vocab
case array[0]
when :battle
tf = $game_party.battle_members.include?($game_actors[act]) &&
$game_party.battle_members.include?(@parent.actor)
when :party
tf = $game_party.all_members.include?($game_actors[act]) &&
$game_party.all_members.include?(@parent.actor)
else
tf = true
end
change_color(normal_color, tf)
draw_text(rect.x + 2, rect.y + line_height * (i + 2), rect.width - 4,
line_height, text)
end
change_color(normal_color)
end
def update_padding_bottom
end
end
##------
## REGEXP and game objects below.
##------
module CP
module REGEXP
module RELATIONSHIP
## $1 Type $2 Op. $3 1. $4 .1 $5 % $6 stat
STAT_MODIF_2 = /(relationship|friends|lovers)\[(\+|-)(\d+)(\.\d+)?(%?) (.{3})\]/i
EXTRA_MODIF_2 = /(relationship|friends|lovers)\[(skill|weapon|armor|armour) (\d+)\]/i
FOR_ACTOR_2 = /for (actor|level)\[([\d, ]+)\]/i
FOR_LEVEL_2 = /for (level)\[(\d+)(\+|-)?(\d*)\]/i
CONSTANT1_2 = /<relationship constant>/i
CONSTANT2_2 = /<\/relationship constant>/i
PARTY1_2 = /<relationship party>/i
PARTY2_2 = /<\/relationship party>/i
GENDER_2 = /gender\[(male|female)]/i
end
end
end
class RPG::Actor < RPG::BaseItem
include CP::REGEXP::RELATIONSHIP
def relationship_features
create_reship_features if @relationship_features.nil?
return @relationship_features
end
def gender
create_reship_features if @gender_base.nil?
return @gender_base
end
def create_reship_features
@relationship_features = {:battle=>[], :party=>[], :game=>[]}
@gender_base = :male
type = :battle
self.note.split(/[\r\n]+/i).each do |line|
@reyash = nil
case line
when STAT_MODIF_2
n = $3.to_f + $4.to_f
fti = CP::Features.get_feature($6.to_s, $5.to_s)
if [21, 23].include?(fti[0])
n = $2.to_s == '-' ? (100.0 - n) / 100.0 :
$2.to_s == '+' ? (n + 100.0) / 100.0 : n
elsif fti[0] == 22
n = $2.to_s == '-' ? -n / 100.0 :
$2.to_s == '+' ? n / 100.0 : n
else
n *= -1 if $2.to_s == '-'
end
@reyash = [:stat, n, $5.to_s, $6.to_s, $1.to_sym]
ext = {:actor => [], :level => "all"}
when EXTRA_MODIF_2
@reyash = [$2.to_sym, $3.to_i, nil, nil, $1.to_sym]
ext = {:actor => [], :level => "0+"}
when CONSTANT1_2
type = :game if type == :battle
when CONSTANT2_2
type = :battle if type == :game
when PARTY1_2
type = :party if type == :battle
when PARTY2_2
type = :battle if type == :party
when GENDER_2
@gender_base = $1.to_sym
next
end
next unless @reyash
if line =~ FOR_ACTOR_2
ext[$1.to_sym] = $2.to_s.delete(' ').split(/,/).collect {|i| i.to_i}
end
if line =~ FOR_LEVEL_2
ext[$1.to_sym] = "#{$2.to_s}#{$3.to_s}#{$4.to_s}"
end
@reyash.push(ext)
@relationship_features[type].push(@reyash)
end
end
end
###--------------------------------------------------------------------------###
# End of script. #
###--------------------------------------------------------------------------### |
module Notifier
module PushBullet
def self.notify(message, title="SimpleCMS", url=nil)
return unless ENV['PUSHBULLET_ACCESS_TOKEN']
access_token = ENV['PUSHBULLET_ACCESS_TOKEN']
params = {
:title => title,
:body => message
}
if url
params[:type] = "link"
params[:url] = url
else
params[:type] = "note"
end
RestClient.post("https://#{access_token}@api.pushbullet.com/v2/pushes", params)
end
end
end
|
class CreateLearningDeliveries < ActiveRecord::Migration
def change
create_table :learning_deliveries do |t|
t.string :format_type
t.text :description
t.datetime :delivery_date
t.integer :delivery_kind
t.references :learning_dynamic, index: true
t.timestamps null: false
end
add_foreign_key :learning_deliveries, :learning_dynamics
end
end
|
module Sequel
# This module makes it easy to add deprecation functionality to other classes.
module Deprecation
# This sets the output stream for the deprecation messages. Set it to an IO
# (or any object that responds to puts) and it will call puts on that
# object with the deprecation message. Set to nil to ignore deprecation messages.
def self.deprecation_message_stream=(file)
@dms = file
end
# Set this to true to print tracebacks with every deprecation message,
# so you can see exactly where in your code the deprecated methods are
# being called.
def self.print_tracebacks=(pt)
@pt = pt
end
# Puts the messages unaltered to the deprecation message stream
def self.deprecate(message)
if @dms
@dms.puts(message)
caller.each{|c| @dms.puts(c)} if @pt
end
end
# Formats the message with a message that it will be removed in Sequel 2.0.
# This is the method that is added to the classes that include Sequel::Deprecation.
def deprecate(meth, message = nil)
::Sequel::Deprecation.deprecate("#{meth} is deprecated, and will be removed in Sequel 2.0.#{" #{message}." if message}")
end
end
class << self
include Sequel::Deprecation
def method_missing(m, *args) #:nodoc:
deprecate("Sequel.method_missing", "You should define Sequel.#{m} for the adapter.")
c = Database.adapter_class(m)
begin
# three ways to invoke this:
# 0 arguments: Sequel.dbi
# 1 argument: Sequel.dbi(db_name)
# more args: Sequel.dbi(db_name, opts)
case args.size
when 0
opts = {}
when 1
opts = args[0].is_a?(Hash) ? args[0] : {:database => args[0]}
else
opts = args[1].merge(:database => args[0])
end
rescue
raise Error::AdapterNotFound, "Unknown adapter (#{m})"
end
c.new(opts)
end
end
class Dataset
include Deprecation
MUTATION_RE = /^(.+)!$/.freeze
def clone_merge(opts = {}) #:nodoc:
deprecate("Sequel::Dataset#clone", "Use clone")
clone(opts)
end
def set_options(opts) #:nodoc:
deprecate("Sequel::Dataset#set_options")
@opts = opts
@columns = nil
end
def set_row_proc(&filter) #:nodoc:
deprecate("Sequel::Dataset#set_row_proc", "Use row_proc=")
@row_proc = filter
end
def remove_row_proc #:nodoc:
deprecate("Sequel::Dataset#remove_row_proc", "Use row_proc=nil")
@row_proc = nil
end
# Provides support for mutation methods (filter!, order!, etc.) and magic
# methods.
def method_missing(m, *args, &block) #:nodoc:
if m.to_s =~ MUTATION_RE
meth = $1.to_sym
super unless respond_to?(meth)
copy = send(meth, *args, &block)
super if copy.class != self.class
deprecate("Sequel::Dataset#method_missing", "Define Sequel::Dataset##{m}, or use Sequel::Dataset.def_mutation_method(:#{meth})")
@opts.merge!(copy.opts)
self
elsif magic_method_missing(m)
send(m, *args)
else
super
end
end
MAGIC_METHODS = {
/^order_by_(.+)$/ => proc {|c| proc {deprecate("Sequel::Dataset#method_missing", "Use order(#{c.inspect}) or define order_by_#{c}"); order(c)}},
/^first_by_(.+)$/ => proc {|c| proc {deprecate("Sequel::Dataset#method_missing", "Use order(#{c.inspect}).first or define first_by_#{c}"); order(c).first}},
/^last_by_(.+)$/ => proc {|c| proc {deprecate("Sequel::Dataset#method_missing", "Use order(#{c.inspect}).last or define last_by_#{c}"); order(c).last}},
/^filter_by_(.+)$/ => proc {|c| proc {|v| deprecate("Sequel::Dataset#method_missing", "Use filter(#{c.inspect}=>#{v.inspect}) or define filter_by_#{c}"); filter(c => v)}},
/^all_by_(.+)$/ => proc {|c| proc {|v| deprecate("Sequel::Dataset#method_missing", "Use filter(#{c.inspect}=>#{v.inspect}).all or define all_by_#{c}"); filter(c => v).all}},
/^find_by_(.+)$/ => proc {|c| proc {|v| deprecate("Sequel::Dataset#method_missing", "Use filter(#{c.inspect}=>#{v.inspect}).first or define find_by_#{c}"); filter(c => v).first}},
/^group_by_(.+)$/ => proc {|c| proc {deprecate("Sequel::Dataset#method_missing", "Use group(#{c.inspect}) or define group_by_#{c}"); group(c)}},
/^count_by_(.+)$/ => proc {|c| proc {deprecate("Sequel::Dataset#method_missing", "Use group_and_count(#{c.inspect}) or define count_by_#{c})"); group_and_count(c)}}
}
# Checks if the given method name represents a magic method and
# defines it. Otherwise, nil is returned.
def magic_method_missing(m) #:nodoc:
method_name = m.to_s
MAGIC_METHODS.each_pair do |r, p|
if method_name =~ r
impl = p[$1.to_sym]
return Dataset.class_def(m, &impl)
end
end
nil
end
end
module SQL
module DeprecatedColumnMethods #:nodoc:
AS = 'AS'.freeze
DESC = 'DESC'.freeze
ASC = 'ASC'.freeze
def as(a) #:nodoc:
Sequel::Deprecation.deprecate("Object#as is deprecated and will be removed in Sequel 2.0. Use Symbol#as or String#as.")
ColumnExpr.new(self, AS, a)
end
def AS(a) #:nodoc:
Sequel::Deprecation.deprecate("Object#AS is deprecated and will be removed in Sequel 2.0. Use Symbol#as or String#as.")
ColumnExpr.new(self, AS, a)
end
def desc #:nodoc:
Sequel::Deprecation.deprecate("Object#desc is deprecated and will be removed in Sequel 2.0. Use Symbol#desc or String#desc.")
ColumnExpr.new(self, DESC)
end
def DESC #:nodoc:
Sequel::Deprecation.deprecate("Object#DESC is deprecated and will be removed in Sequel 2.0. Use Symbol#desc or String#desc.")
ColumnExpr.new(self, DESC)
end
def asc #:nodoc:
Sequel::Deprecation.deprecate("Object#asc is deprecated and will be removed in Sequel 2.0. Use Symbol#asc or String#asc.")
ColumnExpr.new(self, ASC)
end
def ASC #:nodoc:
Sequel::Deprecation.deprecate("Object#ASC is deprecated and will be removed in Sequel 2.0. Use Symbol#asc or String#asc.")
ColumnExpr.new(self, ASC)
end
def all #:nodoc:
Sequel::Deprecation.deprecate("Object#all is deprecated and will be removed in Sequel 2.0. Use :#{self}.* or '#{self}.*'.lit.")
Sequel::SQL::ColumnAll.new(self)
end
def ALL #:nodoc:
Sequel::Deprecation.deprecate("Object#ALL is deprecated and will be removed in Sequel 2.0. Use :#{self}.* or '#{self}.*'.lit.")
Sequel::SQL::ColumnAll.new(self)
end
def cast_as(t) #:nodoc:
Sequel::Deprecation.deprecate("Object#cast_as is deprecated and will be removed in Sequel 2.0. Use Symbol#cast_as or String#cast_as.")
if t.is_a?(Symbol)
t = t.to_s.lit
end
Sequel::SQL::Function.new(:cast, self.as(t))
end
end
end
end
class Object
include Sequel::SQL::DeprecatedColumnMethods
def Sequel(*args) #:nodoc:
Sequel::Deprecation.deprecate("Object#Sequel is deprecated and will be removed in Sequel 2.0. Use Sequel.connect.")
Sequel.connect(*args)
end
def rollback! #:nodoc:
Sequel::Deprecation.deprecate("Object#rollback! is deprecated and will be removed in Sequel 2.0. Use raise Sequel::Error::Rollback.")
raise Sequel::Error::Rollback
end
end
class Symbol
# Converts missing method calls into functions on columns, if the
# method name is made of all upper case letters.
def method_missing(sym, *args) #:nodoc:
if ((s = sym.to_s) =~ /^([A-Z]+)$/)
Sequel::Deprecation.deprecate("Symbol#method_missing is deprecated and will be removed in Sequel 2.0. Use :#{sym}[:#{self}].")
Sequel::SQL::Function.new(s.downcase, self)
else
super
end
end
end
|
class UserGoal < ActiveRecord::Base
include ActivityLog
after_create :create_goal_log
belongs_to :user
has_many :activities, as: :targetable
def create_goal_log
create_log self, self.user_id, Settings.activity_type.create_goal
end
end
|
class MasterFaceSerializer < ActiveModel::Serializer
embed :ids
attributes :id, :name, :email
has_many :battle_faces
end
|
class PolyTreeNode
def initialize(value)
@value = value
@parent = nil
@children = []
end
def parent
@parent
end
def children
@children
end
def value
@value
end
def parent=(node)
if @parent != node
if node != nil
node.children << self
end
if @parent != nil
@parent.children.delete(self)
end
end
@parent = node
end
def add_child(child_node)
child_node.parent= self
end
def remove_child(child_node)
if !@children.include?(child_node)
raise "error"
end
child_node.parent= nil
end
def dfs(target_value)
return self if self.value == target_value
self.children.each do |child|
result = child.dfs(target_value)
return result unless result == nil
end
nil
end
def bfs(target_value)
queue = [self]
until queue.empty?
el = queue.shift
if el.value == target_value
return el
else
queue += el.children
end
end
end
end
if __FILE__ == $PROGRAM_NAME
parent = nil
child_1 = PolyTreeNode.new("child_1")
child_2 = PolyTreeNode.new("child_2")
child_2.parent = parent
child_2.parent = nil
puts child_2.parent == nil
end
|
class Site < ActiveRecord::Base
has_many :studysites
has_many :studies, through: :studysites
#validates_uniqueness_of :name, scope: :location, allow_nil: true
validates :name, uniqueness: {message: 'The site name and location already exists.', case_sensitive: false, scope: :location}
validates :name, :location, presence: true
end
|
=begin
#qTest Manager API Version 8.6 - 9.1
#qTest Manager API Version 8.6 - 9.1
OpenAPI spec version: 8.6 - 9.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
# Common files
require 'swagger_client/api_client'
require 'swagger_client/api_error'
require 'swagger_client/version'
require 'swagger_client/configuration'
# Models
require 'swagger_client/models/admin_profile'
require 'swagger_client/models/allowed_value_resource'
require 'swagger_client/models/app_detail'
require 'swagger_client/models/artifact_history_resource'
require 'swagger_client/models/artifact_search_params'
require 'swagger_client/models/assigned_project'
require 'swagger_client/models/assigned_users_project'
require 'swagger_client/models/attachment_author'
require 'swagger_client/models/attachment_resource'
require 'swagger_client/models/automation_request'
require 'swagger_client/models/automation_schedule_creation_api'
require 'swagger_client/models/automation_step_log'
require 'swagger_client/models/automation_test_log'
require 'swagger_client/models/automation_test_log_resource'
require 'swagger_client/models/automation_test_step_log'
require 'swagger_client/models/build_permission'
require 'swagger_client/models/build_resource'
require 'swagger_client/models/comment_query_params'
require 'swagger_client/models/comment_resource'
require 'swagger_client/models/defect_field_mapping'
require 'swagger_client/models/defect_mapping'
require 'swagger_client/models/defect_permission'
require 'swagger_client/models/defect_resource'
require 'swagger_client/models/defect_tracking_system'
require 'swagger_client/models/field_resource'
require 'swagger_client/models/history_change'
require 'swagger_client/models/history_query_params'
require 'swagger_client/models/history_resource'
require 'swagger_client/models/link'
require 'swagger_client/models/linked_artifact'
require 'swagger_client/models/linked_artifact_container'
require 'swagger_client/models/linked_defect_resource'
require 'swagger_client/models/linked_object'
require 'swagger_client/models/logged_user'
require 'swagger_client/models/manual_test_log_resource'
require 'swagger_client/models/message'
require 'swagger_client/models/module_permission'
require 'swagger_client/models/module_resource'
require 'swagger_client/models/o_auth_response'
require 'swagger_client/models/output_stream'
require 'swagger_client/models/paged_resource'
require 'swagger_client/models/paged_resource_attachment_resource'
require 'swagger_client/models/paged_resource_comment_resource'
require 'swagger_client/models/profile'
require 'swagger_client/models/project_admin_permission'
require 'swagger_client/models/project_resource'
require 'swagger_client/models/project_setting_permission'
require 'swagger_client/models/project_users_profile'
require 'swagger_client/models/property_resource'
require 'swagger_client/models/query_comment_resource'
require 'swagger_client/models/queue_processing_response'
require 'swagger_client/models/release_permission'
require 'swagger_client/models/release_with_custom_field_resource'
require 'swagger_client/models/report_permission'
require 'swagger_client/models/requirement_permission'
require 'swagger_client/models/requirement_resource'
require 'swagger_client/models/resource_support'
require 'swagger_client/models/schedule_permission'
require 'swagger_client/models/search_user_resource'
require 'swagger_client/models/search_user_resource_extension_response'
require 'swagger_client/models/search_user_response'
require 'swagger_client/models/session_manager_permission'
require 'swagger_client/models/site_users_profile'
require 'swagger_client/models/status_resource'
require 'swagger_client/models/test_case_permission'
require 'swagger_client/models/test_case_with_custom_field_resource'
require 'swagger_client/models/test_cycle_permission'
require 'swagger_client/models/test_cycle_resource'
require 'swagger_client/models/test_log_list_resource'
require 'swagger_client/models/test_log_resource'
require 'swagger_client/models/test_run_list_resource'
require 'swagger_client/models/test_run_permission'
require 'swagger_client/models/test_run_with_custom_field_resource'
require 'swagger_client/models/test_step_log_resource'
require 'swagger_client/models/test_step_resource'
require 'swagger_client/models/test_suite_permission'
require 'swagger_client/models/test_suite_with_custom_field_resource'
require 'swagger_client/models/traceability_requirement'
require 'swagger_client/models/user_profile'
require 'swagger_client/models/user_profile_response'
require 'swagger_client/models/user_resource'
require 'swagger_client/models/user_resource_extension'
# APIs
require 'swagger_client/api/attachment_api'
require 'swagger_client/api/automationjob_api'
require 'swagger_client/api/build_api'
require 'swagger_client/api/common_api'
require 'swagger_client/api/defect_api'
require 'swagger_client/api/field_api'
require 'swagger_client/api/login_api'
require 'swagger_client/api/module_api'
require 'swagger_client/api/objectlink_api'
require 'swagger_client/api/project_api'
require 'swagger_client/api/release_api'
require 'swagger_client/api/requirement_api'
require 'swagger_client/api/search_api'
require 'swagger_client/api/testcase_api'
require 'swagger_client/api/testcycle_api'
require 'swagger_client/api/testlog_api'
require 'swagger_client/api/testrun_api'
require 'swagger_client/api/testsuite_api'
require 'swagger_client/api/user_api'
require 'swagger_client/api/userprofile_api'
module SwaggerClient
class << self
# Customize default settings for the SDK using block.
# SwaggerClient.configure do |config|
# config.username = "xxx"
# config.password = "xxx"
# end
# If no block given, return the default Configuration object.
def configure
if block_given?
yield(Configuration.default)
else
Configuration.default
end
end
end
end
|
#!/usr/bin/env ruby
require File.expand_path('../../config/environment', __FILE__)
require "csv"
require "aws/s3"
raise "S3_KEY must be set in ENV" unless ENV['S3_KEY'].present?
raise "S3_SECRET must be set in ENV" unless ENV['S3_SECRET'].present?
AWS::S3::Base.establish_connection!(
:access_key_id => ENV['S3_KEY'],
:secret_access_key => ENV['S3_SECRET']
)
bucket = 'healer-production'
filename = 'procedures.txt'
if AWS::S3::S3Object.exists?("data/#{filename}", bucket)
file = AWS::S3::S3Object.find("data/#{filename}", bucket)
contents = file.value
i = 0
contents.each do |row|
i += 1
row_vals = row.split("|")
en = row_vals[0].strip.humanize
es = row_vals[1].strip.humanize
Procedure.create(:name_en => en, :name_es => es, :display_order => i)
end
else
raise "File does not exist at #{bucket}:data/#{filename}"
end |
class AddColumnToAttempt < ActiveRecord::Migration
def change
add_column :attempts, :enrollmentendsat, :datetime
end
end |
# frozen_string_literal: true
class BoardObject
attr_accessor :updated
HORIZONTAL_LIMIT = 512
VERTICAL_LIMIT = 256
def initialize
super
@updated = true
end
protected
def within_vertical_boundary?(pos)
pos.positive? && pos < VERTICAL_LIMIT
end
def within_horizontal_boundary?(pos)
pos.positive? && pos < HORIZONTAL_LIMIT
end
end
|
require 'rails_helper'
describe FetchFriendsForUser do
let(:request) { FetchFriendsForUserRequest.new(facebook_token: 'some token'.maybe)}
let(:listener_spy) { spy(ListenerSpy) }
subject { FetchFriendsForUser.new(request, listener_spy)}
describe '#perform' do
context 'without a facebook token' do
let(:request) { FetchFriendsForUserRequest.new(facebook_token: nil) }
it 'calls handle_failure with error message specifying lack of token' do
expect(listener_spy).to receive(:handle_failure).with('No facebook token for user present')
subject.perform
end
end
context 'with a facebook token' do
it 'calls find with facebook token on FriendRepository' do
expect(FriendRepository).to receive(:find).with(token: 'some token')
subject.perform
end
it 'calls handle_success with the resulting list of FriendEntities' do
friends = [
FriendEntity.new(name: 'bob', image_url: 'some url'),
FriendEntity.new(name: 'joe', image_url: 'some other url')
]
allow(FriendRepository).to receive(:find).and_return(friends)
expect(listener_spy).to receive(:handle_success).with(friends)
subject.perform
end
end
end
end |
class Romano
ValoresBasicos = {
1 => "I",
4 => "IV",
5 => "V",
9 => "IX",
10 => "X",
20 => "X",
30 => "X",
40 => "XL",
50 => "L",
90 => "XC",
100 => "C",
200 => "C",
300 => "C",
400 => "CD",
500 => "D",
900 => "CM",
1000 => "M"
}
def generar(nro)
if(nro>=1)
return "I"
end
end
def generarMenoresIgualesATres(nro)
resultado = ""
for valor in (1..nro) do
resultado = resultado + generar(nro)
end
return resultado
end
def generarValoresBasicos(nro)
return ValoresBasicos[nro]
end
def generarRomano(nro)
resultado = ""
if(nro >= 900)
resultado = resultado + generarValoresBasicos(900)
end
if(nro >= 500)
resultado = resultado + generarValoresBasicos(500)
end
if(nro >= 300)
resultado = resultado + generarValoresBasicos(300)
end
if(nro >= 200)
resultado = resultado + generarValoresBasicos(200)
end
if(nro >= 100)
resultado = resultado + generarValoresBasicos(100)
end
if(nro >= 90)
resultado = resultado + generarValoresBasicos(90)
end
if(nro >= 50)
resultado = resultado + generarValoresBasicos(50)
end
if(nro >= 40)
resultado = resultado + generarValoresBasicos(40)
end
if(nro >= 30)
resultado = resultado + generarValoresBasicos(30)
end
if(nro >= 20)
resultado = resultado + generarValoresBasicos(20)
end
if(nro >= 10)
resultado = resultado + generarValoresBasicos(10)
end
if(nro >= 9)
resultado = resultado + generarValoresBasicos(9)
end
if(nro >= 5)
resultado = resultado + generarValoresBasicos(5)
end
if(nro >= 4)
resultado = resultado + generarValoresBasicos(4)
nro = nro - 4;
end
resultado = resultado +generarMenoresIgualesATres(nro)
return resultado
end
end |
class PostitsController < ApplicationController
def index
@postits = Postit.all
end
def show
@postit = Postit.find(params[:id])
end
def new
@postit = Postit.new
end
def edit
@postit = Postit.find(params[:id])
end
def create
@postit = Postit.new(postit_params)
if @postit.save
redirect_to @postit
else
render 'new'
end
end
def update
@postit = Postit.find(params[:id])
if @postit.update(postit_params)
redirect_to @postit
else
render 'edit'
end
end
def destroy
@postit = Postit.find(params[:id])
@postit.destroy
redirect_to postits_path
end
def sortable
@postit = Postit.find(params[:id])
end
private
def postit_params
params.require(:postit).permit(:title, :text)
end
end
|
class CreateModels < ActiveRecord::Migration[5.2]
def change
create_table :models do |t|
t.string :name, null: false
t.datetime :release_date, null: false
t.references :brand, null: false
t.references :category, null: false
t.string :processor
t.string :ram
t.string :storage_capacity
t.string :storage_type
t.string :display
t.string :battery_capacity
t.string :wifi
t.string :bluetooth
t.string :gps
t.string :cellular
t.string :camera
t.string :size
t.string :weight
t.timestamps
end
add_index :models, :name, unique: true
add_index :models, :release_date
end
end
|
class CreateScreenings < ActiveRecord::Migration
def change
create_table :screenings do |t|
t.references :movie, index: true, foreign_key: true
t.references :user, index: true, foreign_key: true
t.references :theater, index: true, foreign_key: true
t.references :offer, index: true, foreign_key: true
t.datetime :start_time
t.date :date
t.boolean :approval_filmmaker
t.boolean :approval_theatre
t.integer :threshold
t.boolean :status
t.boolean :is_deleted
t.timestamps null: false
end
end
end
|
class Team < ActiveRecord::Base
before_create :inactive_season
has_many :match_results
validates :name, presence: true, length: { minimum: 3 }, uniqueness: true
def inactive_season
raise 'Sezon jest już rozpoczęty.' if Season.find(1).status == 'active'
end
# include Comparable
#
# def <=>(other)
# self.score <=> other.score
# end
end
|
require File.dirname(__FILE__) + '/spec_helper'
describe "the SJCL BitArray" do
it "work with extract" do
SJCL::BitArray.extract([1415934836, 543256164, 544042866], 0, 24).should eql(5530995)
SJCL::BitArray.extract([-123123, 2345], 8, 16).should eql(65055)
end
it "should handle partials" do
SJCL::BitArray.getPartial(26389912904448).should eql(24)
SJCL::BitArray.bitLength([26389912904448]).should eql(24)
SJCL::BitArray.getPartial(1352435907).should eql(32)
end
it "should make partials" do
SJCL::BitArray.partial(32, 27).should eql(27)
SJCL::BitArray.partial(24, 137).should eql(26388279101696)
SJCL::BitArray.partial(16, 204).should eql(17592199413760)
SJCL::BitArray.partial(8, 3271557120, 1).should eql(8795069612032)
end
it "should correclty shiftRight" do
conc = SJCL::BitArray.shiftRight([-1505830413, 1352435907], 8, 2130706432, [])
SJCL::BitArray.compare(conc, [2141601497, -212820856, 8795069612032]).should eql(true)
end
it "should clamp" do
clamped = SJCL::BitArray.clamp([2010473763, 1926277526, 2720643473, 3225629324], 128)
SJCL::BitArray.compare(clamped, [2010473763, 1926277526, 2720643473, 3225629324]).should eql(true)
clamped = SJCL::BitArray.clamp([1868310588, 3653507289, 867213828, 1392911557, 17593804424619, 3441232331, 3819666098, 3925464908], 144)
SJCL::BitArray.compare(clamped, [1868310588, 3653507289, 867213828, 1392911557, 17593804390400]).should eql(true)
end
it "should bitslice" do
sliced = SJCL::BitArray.bitSlice([2010473763, 1926277526, 2720643473, 3225629324], 0, 64)
SJCL::BitArray.compare(sliced, [2010473763, 1926277526]).should eql(true)
sliced = SJCL::BitArray.bitSlice([1830956770, 3659299964, 4136255234, 2601935920], 0, 64)
SJCL::BitArray.compare(sliced, [1830956770, 3659299964]).should eql(true)
end
it "should concat two bit arrays" do
conc = SJCL::BitArray.concat([8798223728640],[-1505830413, 1352435907])
SJCL::BitArray.compare(conc, [2141601497, -212820856, 8795069612032]).should eql(true)
expected = [2215220552, 2472502247, 2970193637, 3874452154, -1941053952, -922223310, 17590738944000]
conc = SJCL::BitArray.concat([2215220552, 2472502247, 2970193637, 3874452154, 17590244933632] ,[3724593415, 4247955903])
SJCL::BitArray.compare(conc, expected).should eql(true)
end
end
|
# Shorten this sentence:
advice = "Few things in life are as important as house training your pet dinosaur."
# ...remove everything starting from "house".
# Review the String#slice! documentation, and use that method to make the return value "Few things in life are as important as ". But leave the advice variable as "house training your pet dinosaur.".
p advice.slice!(0..advice.index('house') - 1)
p advice
# As a bonus, what happens if you use the String#slice method instead?
advice = "Few things in life are as important as house training your pet dinosaur."
p advice.slice(0..advice.index('house') - 1)
p advice
# Original advice variable will be left untouched.
# LS Solution
# Instead of using a range they use a length found by the starting index of 'house'.
advice = "Few things in life are as important as house training your pet dinosaur."
p advice.slice!(0, advice.index('house'))
p advice |
class ChangeColumnsInComments < ActiveRecord::Migration
def change
add_column :comments, :commentable_id, :integer
add_column :comments, :commentable_type, :string
remove_reference( :comments, :user, index: true, foreign_key: true)
remove_reference( :comments, :product, index: true, foreign_key: true)
remove_reference( :comments, :post, index: true, foreign_key: true)
add_index :comments, [:commentable_id, :commentable_type]
end
end
|
#coding:utf-8
# == Schema Information
#
# Table name: collaborators
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# password_digest :string(255)
# remember_token :string(255)
# admin :boolean default(FALSE)
# street :string(255)
# number :string(255)
# hood :string(255)
# cep :string(255)
# gender :string(255)
# brithdate :date
# fone1 :string(255)
# fone2 :string(255)
#
require 'spec_helper'
describe Collaborator do
before do
@collaborator = Collaborator.new(name: "Example collaborator",
email: "collaborator@example.com",
fone1: "11111111",
password: "foobar",
password_confirmation: "foobar")
end
subject { @collaborator }
it { should respond_to(:name) }
it { should respond_to(:email) }
it { should respond_to(:street) }
it { should respond_to(:number) }
it { should respond_to(:hood) }
it { should respond_to(:cep) }
it { should respond_to(:gender) }
it { should respond_to(:birth_date) }
it { should respond_to(:password_digest) }
it { should respond_to(:password) }
it { should respond_to(:password_confirmation) }
it { should respond_to(:remember_token) }
it { should respond_to(:admin) }
it { should respond_to(:partners) }
it { should respond_to(:feed) }
it { should respond_to(:authenticate) }
it { should be_valid }
it { should_not be_admin }
describe "with admin attribute set to 'true'" do
before { @collaborator.toggle!(:admin) }
it { should be_admin }
end
describe "when name is'nt present" do
before { @collaborator.name = "" }
it { should_not be_valid}
end
describe "when email is'nt present" do
before { @collaborator.email = "" }
it { should_not be_valid}
end
describe "when name is too long" do
before { @collaborator.name="e"*51 }
it { should_not be_valid }
end
describe "when email format is invalid" do
it "should be invalid" do
addresses = %w[collaborator@foo,com collaborator_at_foo.org example.collaborator@foo.
foo@bar_baz.com foo@bar+baz.com]
addresses.each do |invalid_address|
@collaborator.email = invalid_address
@collaborator.should_not be_valid
end
end
end
describe "email address with mixed case" do
let(:mixed_case_email) { "Foo@ExAMPle.CoM" }
it "should be saved as all lower-case" do
@collaborator.email = mixed_case_email
@collaborator.save
@collaborator.reload.email.should == mixed_case_email.downcase
end
end
describe "when email format is valid" do
it "should be valid" do
addresses = %w[collaborator@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn]
addresses.each do |valid_address|
@collaborator.email = valid_address
@collaborator.should be_valid
end
end
end
describe "when email address is already taken" do
before do
collaborator_with_same_email = @collaborator.dup
collaborator_with_same_email.email = @collaborator.email.upcase
collaborator_with_same_email.save
end
it { should_not be_valid }
end
describe "when password is not present" do
before { @collaborator.password = @collaborator.password_confirmation = " " }
it { should_not be_valid }
end
describe "when password doesn't match confirmation" do
before { @collaborator.password_confirmation = "mismatch" }
it { should_not be_valid }
end
describe "return value of authenticate method" do
before { @collaborator.save }
let(:found_collaborator) { Collaborator.find_by_email(@collaborator.email) }
describe "with valid password" do
it { should == found_collaborator.authenticate(@collaborator.password) }
end
describe "with invalid password" do
let(:collaborator_for_invalid_password) { found_collaborator.authenticate("invalid") }
it { should_not == collaborator_for_invalid_password }
specify { collaborator_for_invalid_password.should be_false }
end
end
describe "remember token" do
before { @collaborator.save }
its(:remember_token) { should_not be_blank }
end
describe "partner associations" do
before { @collaborator.save }
let!(:first_partner) do
FactoryGirl.create(:partner, collaborator: @collaborator, name: 'Alice')
end
let!(:last_partner) do
FactoryGirl.create(:partner, collaborator: @collaborator, name: 'Zélia')
end
it "should have the right partners in the right order" do
@collaborator.partners.should == [first_partner, last_partner]
end
it "should destroy associated partners" do
partners = @collaborator.partners
@collaborator.destroy
partners.each do |partner|
Partner.find_by_id(partner.id).should be_nil
end
end
describe "status" do
let(:someonelse_partner) do
FactoryGirl.create(:partner, collaborator: FactoryGirl.create(:collaborator))
end
its(:feed) { should include(first_partner) }
its(:feed) { should include(last_partner) }
its(:feed) { should_not include(someonelse_partner) }
end
end
end
|
class PricesController < ApplicationController
def index
@prices = Price.order('name')
end
def show
@price = Price.includes(:products).find(params[:id])
redirect_to @price, :status => :moved_permanently if request.path != price_path(@price)
end
end
|
class Post < ApplicationRecord
belongs_to :user
mount_uploader :post_image, PostImageUploader
validates :user_id, :description, presence: true
acts_as_likeable
end
|
require 'pg_search'
class Media < ApplicationRecord
belongs_to :artist
belongs_to :category
has_many :photos, dependent: :destroy
has_many :taggings, dependent: :destroy
has_many :rentals, dependent: :destroy
belongs_to :subscription_type
has_many :tags, through: :taggings
has_many :media_to_package_links
has_many :packages, through: :media_to_package_links
include PgSearch
pg_search_scope :search_by_title_artist_category_and_description,
against: [:title, :description],
associated_against: {
category: [:name],
artist: [:name]
},
using: {
tsearch: { prefix: true } # <-- now `superman batm` will return something!
}
mount_uploader :photo, PhotoUploader
end
|
require 'active_support'
module Easy
module ReferenceData
def self.refresh(clazz, unique_attribute_symbol, unique_attribute_value, attributes)
self.update_or_create(clazz, attributes.merge(unique_attribute_symbol => unique_attribute_value), keys: [unique_attribute_symbol])
end
def self.update_or_create(clazz, attributes, options)
unique_attribute_keys = options.fetch(:keys)
record = clazz.where(attributes.slice(*unique_attribute_keys)).first_or_initialize
if record.new_record?
$stderr.puts "..creating #{clazz}(#{attributes.slice(*unique_attribute_keys)})"
else
$stderr.puts "..updating #{clazz}(#{attributes.slice(*unique_attribute_keys)})"
end
begin
record.update!(attributes)
rescue
$stderr.puts "Save failed for #{record.class} with attributes #{attributes.inspect}"
raise
end
record
end
def self.load_files(wrap_in_transaction: false)
if wrap_in_transaction
ActiveRecord::Base.transaction do
load_the_files
end
else
load_the_files
end
end
private_class_method
def self.files
files = Dir[File.join(Rails.root, 'db', 'reference', '*.rb')].sort
files += Dir[File.join(Rails.root, 'db', 'reference', Rails.env, '*.rb')].sort
files
end
def self.load_the_files
files.each do |file|
puts "Populating reference #{file}"
load file
end
end
end
end
|
ActiveAdmin.register Post do
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
config.per_page = 10
permit_params do
permitted = [:text, :user_id]
permitted << :other if params[:action] == 'create' && current_user.admin?
permitted
end
end
|
# frozen_string_literal: true
class Product < ApplicationRecord
belongs_to :user
belongs_to :category
has_one_attached :image
has_many :order_products
validates :title, :price, :quantity, :description, :image, presence: true
end
|
Deface::Override.new(:virtual_path => "spree/admin/properties/_form",
:name => "properties_globalization_form",
:replace => "[data-hook='admin_property_form']",
:partial => "spree/admin/shared/properties_globalization_form") |
require 'test/unit'
class TestArticle < Test::Unit::TestCase
def setup
@tests = []
@test1 = Article.new("title","content bla bla bla","author")
@test2 = Article.new("title2","content2","author2")
@test3 = Article.new("title3","content3","author3")
@test4 = Article.new("title4","content4","author")
3.times{@test1.like!}
5.times{@test4.dislike!}
4.times{@test2.like!}
@test = ArticleManager.new([@test1,@test2,@test3,@test4])
end
def test_worst_articles
assert_equal([@test4,@test3,@test1,@test2], @test.worst_articles, "worst_articles doesn't work'")
end
def test_best_articles
assert_equal([@test2,@test1,@test3,@test4], @test.best_articles, "best_articles doesn't work'")
end
def test_worst_article
assert_equal(@test4,@test.worst_article,"worst_article doesn't work")
end
def test_best_article
assert_equal(@test2,@test.best_article,"best_article doesn't work")
end
def test_most_popular_article
assert_equal(@test4,@test.most_popular_article, "most_popular_article doesn't work")
end
def test_include?
assert(@test.include?("content"), "include? doesn't work")
end
def test_authors
assert_equal(["author", "author2", "author3"], @test.authors, "authors doesn't work")
end
def test_number_of_authors
assert_equal(@test.number_of_authors,3,"number_of_authors doesn't work")
end
def test_votes
assert_equal(@test.votes, 12, "votes doesn't work")
end
def test_to_s
assert_equal(@test.to_s,
"1. Title: title
Content: content bla bla bla
Author: author
2. Title: title2
Content: content2
Author: author2
3. Title: title3
Content: content3
Author: author3
4. Title: title4
Content: content4
Author: author
","to_s doesn't work")
end
end
|
require_relative 'test_helper'
require_relative '../lib/merchant'
class MerchantTest < Minitest::Test
def test_it_exists
merchant = Merchant.new({:id => 5,
:name => "Turing School",
:created_at => Time.now,
:updated_at => Time.now})
assert_instance_of Merchant, merchant
end
def test_it_has_attributes
merchant = Merchant.new({:id => 5,
:name => "Turing School",
:created_at => Time.now,
:updated_at => Time.now})
assert_equal 5, merchant.id
assert_equal "Turing School", merchant.name
end
end
|
module Crawler
class Fnv1
PRIME = 16777619
OFFSET_BASIS = 2166136261
MASK = 2 ** 32 - 1
def self.calc(str)
hash = OFFSET_BASIS
str.bytes.each do |octet|
hash = (hash * PRIME) & MASK
hash ^= octet
end
hash
end
end
end
|
class BonusDrink
BONUS_PER = 3
BONUS_GET = 1
class << self
def total_count_for(purchase)
purchase + calculate_bonus(purchase)
end
private
def calculate_bonus(empty_bottle)
# 空き瓶3本目まではおまけなし
return 0 if empty_bottle < BONUS_PER
# 最初のおまけ + (最初のおまけと交換した空き瓶を引いた残り本数) / (2本目のおまけ以降はおまけ一本を含めて3本)
BONUS_GET + (empty_bottle.to_i - BONUS_PER) / (BONUS_PER - BONUS_GET)
end
end
end
|
# Create a person class with at least 2 attributes and 2 behaviors. Call all
# person methods below the class so that they print their result to the
# terminal.
class Person
attr_reader :name, :height, :happiness, :working
def initialize(name, height, happiness)
@name = name
@height = height
@happiness = happiness
@working = false
end
def greet
p "Hi my name is #{name}!"
end
def work
@working = true
end
def relax
@working = false
@happiness += 2
end
end
max = Person.new("Max", "5 foot 8 inches", 5)
max.greet
p max.working
max.work
p max.working
p max.happiness
max.relax
p max.happiness
p max.working
|
=begin
Aeon Party
by Fomar0153
Version 1.1
----------------------
Notes
----------------------
This script allows you to summon actors in the style of FFX's aeons.
----------------------
Instructions
----------------------
See the thread or blog post for a change.
Also if using an actor battler script add:
SceneManager.scene.create_spriteset
below:
a = $game_actors[x]
$game_party.aeons.push(a)
in your common event.
----------------------
Change Log
----------------------
1.0 -> 1.1 Added a fix for some popup systems which showed death when
summoning aeons. Reason with the fix below.
Added support for actor battler scripts.
----------------------
Known bugs
----------------------
None
=end
$imported = {} if $imported.nil?
$imported["Fomar0153-Aeon Party"] = true
class Game_Party < Game_Unit
attr_accessor :aeons
alias aeon_initialize initialize
def initialize
aeon_initialize
@aeons = []
end
alias aeon_battle_members battle_members
def battle_members
return aeon_battle_members if @aeons == []
return @aeons
end
alias aeon_all_dead? all_dead?
def all_dead?
if aeon_all_dead?
if @aeons == []
return true
else
@aeons = []
clear_actions
return false
end
end
return false
end
def on_battle_end
@aeons = []
super
end
end
module BattleManager
class << self
alias aeon_process_victory process_victory
end
def self.process_victory
$game_party.aeons = []
SceneManager.scene.create_spriteset # added for actor sprites
aeon_process_victory
end
end
class Game_BattlerBase
#--------------------------------------------------------------------------
# * When a character is first created they have 0 HP and hence get death
# applied, if this happens in a battle and you are using popups
# you get a popup that death has been applied. This is the fix for that.
#--------------------------------------------------------------------------
alias no_death_on_initialize initialize
def initialize
no_death_on_initialize
@hp = 1
end
end |
# frozen_string_literal: true
require 'ipaddr'
module Keycard
# looks up institution ID(s) by IP address
class InstitutionFinder
INST_QUERY = <<~SQL
SELECT inst FROM aa_network WHERE
? >= dlpsAddressStart
AND ? <= dlpsAddressEnd
AND dlpsAccessSwitch = 'allow'
AND dlpsDeleted = 'f'
AND inst is not null
AND inst NOT IN
( SELECT inst FROM aa_network WHERE
? >= dlpsAddressStart
AND ? <= dlpsAddressEnd
AND dlpsAccessSwitch = 'deny'
AND dlpsDeleted = 'f' )
SQL
def initialize(db: Keycard::DB.db)
@db = db
@stmt = @db[INST_QUERY, *[:$client_ip] * 4].prepare(:select, :unused)
end
def attributes_for(request)
return {} unless (numeric_ip = numeric_ip(request.remote_ip))
insts = insts_for_ip(numeric_ip)
if !insts.empty?
{ 'dlpsInstitutionId' => insts }
else
{}
end
end
private
attr_reader :stmt
def insts_for_ip(numeric_ip)
stmt.call(client_ip: numeric_ip).map { |row| row[:inst] }
end
def numeric_ip(dotted_ip)
return unless dotted_ip
begin
IPAddr.new(dotted_ip).to_i
rescue IPAddr::InvalidAddressError
nil
end
end
end
end
|
class PhotosController < ApplicationController
layout 'admin'
before_action :user_check
before_action :parent
def index
@photos = @gallery.photos.order('position DESC')
end
def new
@photos = Photo.new({:name=>"Tytuł?", :gallery_id => @gallery.id, :position => (@gallery.photos.count + 1)})
@gall = Gallery.order('position ASC')
@counter = @gallery.photos.count + 1
end
def create
@photos = Photo.new(photo_params)
if @photos.save
flash[:notice] = "Zdjęcie pomyślnie dodane"
redirect_to(:action=>'index', :gallery_id => @gallery.id)
else
@counter = @gallery.photos.count + 1
@gall = Gallery.order('position ASC')
render('new')
end
end
def edit
@gall = Gallery.order('position ASC')
@counter = @gallery.photos.count
@photos = Photo.find(params[:id]) #parametr przekazany przez URL (przeglądarkę) -> w index, w guzikach jest wysyłany parametr
end
def update
@photos = Photo.find(params[:id])
if @photos.update_attributes(photo_params)
redirect_to(:action => "show", :id => @photos.id, :gallery_id => @gallery.id)
flash[:notice] = 'Pomyślnie zaktualizowano!'
else
@counter = @gallery.photos.count
@gall = Gallery.order('position ASC')
render('edit')
end
end
def delete
@photos = Photo.find(params[:id])
end
def destroy
photos = Photo.find(params[:id]).destroy
flash[:notice] = 'Pomyślnie usunięto!'
redirect_to(:action => "index", :gallery_id => @gallery.id)
end
def show
@photos = Photo.find(params[:id])
end
private
def photo_params
params.require(:photos).permit(:name, :position, :created_at, :gallery_id, :img)
end
def parent
if params[:gallery_id]
@gallery = Gallery.find(params[:gallery_id])
end
end
end |
# frozen_string_literal: true
RSpec.describe SparseInclude do
let(:klass) do
Class.new
end
let(:source_module) do
Module.new do
def foo
42
end
end
end
before do
klass.include SparseInclude[source_module, foo: :bar]
klass.extend SparseInclude[source_module, foo: :bazz]
end
it 'includes selected methods with alias to the class' do
expect(klass.new).to be_respond_to(:bar)
expect(klass.new.bar).to eql 42
expect(klass).to be_respond_to(:bazz)
expect(klass.bazz).to eql 42
end
end
|
# frozen_string_literal: true
module AsciiPngfy
module Settings
# Provides the interface for all the Setting implementations in a way that
# each inclusion of this module forces the including class to override
# the behaviour for #set and #get
#
# If the #get or #set method is called, but it is not overriden by the object
# mixing this module in, a NotImplementedError is raised
module SetableGetable
def get
self_class_name = self.class.to_s
expected_error_message = String.new
expected_error_message << "#{self_class_name}#get has not yet been implemented. "
expected_error_message << "Must override the #{self_class_name}#get method in order to "
expected_error_message << 'function as Setting.'
raise NotImplementedError, expected_error_message
end
def set
self_class_name = self.class.to_s
expected_error_message = String.new
expected_error_message << "#{self_class_name}#set has not yet been implemented. "
expected_error_message << "Must override the #{self_class_name}#set method in order to "
expected_error_message << 'function as Setting.'
raise NotImplementedError, expected_error_message
end
end
end
end
|
class RenameTablePicturesTagsToPictureTags < ActiveRecord::Migration[5.0]
def change
rename_table :pictures_tags, :picture_tags
end
end
|
class ByteSizeValidator < ActiveModel::EachValidator
include ActionView::Helpers::NumberHelper
def validate_each(record, attribute, value)
return if value.nil?
actual_size = value.bytesize
if options.key?(:minimum)
if actual_size < options[:minimum]
record.errors.add attribute, :too_small, count: format_bytes(options[:minimum]), actual: format_bytes(actual_size)
end
end
if options.key?(:maximum)
if actual_size > options[:maximum]
record.errors.add attribute, :too_large, count: format_bytes(options[:maximum]), actual: format_bytes(actual_size)
end
end
end
private
def format_bytes(bytes)
number_to_human_size(bytes, precision: 4)
end
end
|
module EasyCRUD
module Extensions
module CrudModel
extend ActiveSupport::Concern
included do
class_attribute :_crud_model
class << self
def crudify(model_name, opts = {})
self._crud_model = EasyCRUD.build_crud_model(model_name, opts)
end
end
end
end
end
end
|
module TestDB
def self.database
FileUtils.mkdir_p("#{File.dirname(__FILE__)}/../../tmp")
db = JSONDb.new("db-#{ENV['RACK_ENV']}.json")
db.delete!
db
end
end |
class AddVendorIdToProducts < ActiveRecord::Migration
def change
add_column :products, :vendorID, :int
end
end
|
class UserMailer < ActionMailer::Base
default from: ENV["EMAIL_FROM_ADDRESS"]
def violations_report(recipient:, violations:)
@recipient = recipient
@violations = violations
mail to: @recipient.email,
subject: "Heat Seek Daily Violations Report",
cc: ENV["VIOLATIONS_REPORT_CC_EMAIL"]
end
def welcome_email(recipient_id:, password_reset_token:)
@user = User.find(recipient_id)
@token = password_reset_token
attachments['Heat-Seek-Enrollment-Agreement.pdf'] = File.read(Rails.root.join('app', 'assets', 'documents', 'Heat-Seek-Enrollment-Agreement.pdf'))
attachments['how-it-works.pdf'] = File.read(Rails.root.join('app', 'assets', 'documents', 'how-it-works.pdf'))
mail to: @user.email, subject: "Welcome to your Heat Seek account!"
end
end
|
# frozen-string-literal: true
require 'auto_reloader/version'
require 'singleton'
require 'forwardable'
require 'monitor'
require 'thread' # for Mutex
require 'set'
require 'time' unless defined?(Process::CLOCK_MONOTONIC)
class AutoReloader
include Singleton
extend SingleForwardable
# default_await_before_unload will await for all calls to reload! to finish before calling
# unload!. This behavior is usually desired in web applications to avoid unloading anything
# while a request hasn't been finished, however it won't work fine if some requests are
# supposed to remain open, like websockets connections or something like that.
attr_reader :reloadable_paths, :default_onchange, :default_delay, :default_await_before_unload
def_delegators :instance, :activate, :reload!, :reloadable_paths, :reloadable_paths=,
:unload!, :force_next_reload, :sync_require!, :async_require!, :register_unload_hook
module RequireOverride
def require(path)
AutoReloader.instance.require(path) { super }
end
def require_relative(path)
from = caller.first.split(':', 2)[0]
fullpath = File.expand_path File.join File.dirname(caller.first), path
AutoReloader.instance.require_relative path, fullpath
end
end
def initialize
@activate_lock = Mutex.new
end
ActivatedMoreThanOnce = Class.new RuntimeError
def activate(reloadable_paths: [], onchange: true, delay: nil, watch_paths: nil,
watch_latency: 1, sync_require: false, await_before_unload: true)
@activate_lock.synchronize do
raise ActivatedMoreThanOnce, 'Can only activate Autoreloader once' if @reloadable_paths
@default_delay = delay
@default_onchange = onchange
@default_await_before_unload = await_before_unload
@watch_latency = watch_latency
sync_require! if sync_require
@reload_lock = Mutex.new
@zero_requests_condition = ConditionVariable.new
@requests_count = 0
@top_level_consts_stack = []
@unload_constants = Set.new
@unload_files = Set.new
@unload_hooks = []
@last_reloaded = clock_time
try_listen unless watch_paths == false
self.reloadable_paths = reloadable_paths
Object.include RequireOverride
end
end
# when concurrent threads require files race conditions may prevent the automatic detection
# of constants created by a given file. Calling sync_require! will ensure only a single file
# is required at a single time. However, if a required file blocks (think of a web server)
# then any requires by a separate thread would be blocked forever (or until the web server
# shutdowns). That's why require is async by default even though it would be vulnerable to
# race conditions.
def sync_require!
@require_lock ||= Monitor.new # monitor is like Mutex, but reentrant
end
# See the documentation for sync_require! to understand the reasoning. Async require is the
# default behavior but could lead to race conditions. If you know your requires will never
# block it may be a good idea to call sync_require!. If you know what require will block you
# can call async_require!, require it, and then call sync_require! which will generate a new
# monitor.
def async_require!
@require_lock = nil
end
def reloadable_paths=(paths)
@reloadable_paths = paths.map{|rp| File.expand_path(rp).freeze }.freeze
setup_listener if @watch_paths
end
def require(path, &block)
was_required = false
error = nil
maybe_synchronize do
@top_level_consts_stack << Set.new
old_consts = Object.constants
prev_consts = new_top_level_constants = nil
begin
was_required = yield
rescue Exception => e
error = e
ensure
prev_consts = @top_level_consts_stack.pop
return false if !error && !was_required # was required already, do nothing
new_top_level_constants = Object.constants - old_consts - prev_consts.to_a
(new_top_level_constants.each{|c| safe_remove_constant c }; raise error) if error
@top_level_consts_stack.each{|c| c.merge new_top_level_constants }
full_loaded_path = $LOADED_FEATURES.last
return was_required unless reloadable? full_loaded_path, path
@reload_lock.synchronize do
@unload_constants.merge new_top_level_constants
@unload_files << full_loaded_path
end
end
end
was_required
end
def maybe_synchronize(&block)
@require_lock ? @require_lock.synchronize(&block) : yield
end
def require_relative(path, fullpath)
require(fullpath){ Kernel.require fullpath }
end
InvalidUsage = Class.new RuntimeError
def reload!(delay: default_delay, onchange: default_onchange, watch_paths: @watch_paths,
await_before_unload: default_await_before_unload)
if onchange && !block_given?
raise InvalidUsage, 'A block must be provided to reload! when onchange is true (the default)'
end
unless reload_ignored = ignore_reload?(delay, onchange, watch_paths)
@reload_lock.synchronize do
@zero_requests_condition.wait(@reload_lock) unless @requests_count == 0
end if await_before_unload && block_given?
unload!
end
result = nil
if block_given?
@reload_lock.synchronize{ @requests_count += 1 }
begin
result = yield !reload_ignored
ensure
@reload_lock.synchronize{
@requests_count -= 1
@zero_requests_condition.signal if @requests_count == 0
}
end
find_mtime
end
@last_reloaded = clock_time if delay
result
end
def unload!
@force_reload = false
@reload_lock.synchronize do
@unload_hooks.reverse_each{|h| run_unload_hook h }
@unload_files.each{|f| $LOADED_FEATURES.delete f }
@unload_constants.each{|c| safe_remove_constant c }
@unload_hooks = []
@unload_files = Set.new
@unload_constants = Set.new
end
end
def register_unload_hook(&hook)
raise InvalidUsage, "A block is required for register_unload_hook" unless block_given?
@reload_lock.synchronize do
@unload_hooks << hook
end
end
def run_unload_hook(hook)
hook.call
rescue => e
puts "Failed to run unload hook in AutoReloader: #{e.message}.\n\n#{e.backtrace.join("\n")}"
end
def stop_listener
@reload_lock.synchronize do
@listener.stop if @listener
@listener = nil
end
end
def force_next_reload
@force_reload = true
end
private
def try_listen
Kernel.require 'listen'
@watch_paths = true
rescue LoadError # ignore
#puts 'listen is not available. Add it to Gemfile if you want to speed up change detection.'
end
def setup_listener
@reload_lock.synchronize do
@listener.stop if @listener
@listener = Listen.to(*@reloadable_paths, latency: @watch_latency) do |m, a, r|
@paths_changed = [m, a, r].any?{|o| o.any? {|f| reloadable?(f, nil) }}
end
@listener.start
end
end
if defined?(Process::CLOCK_MONOTONIC)
def clock_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
else
def clock_time
Time.now.to_f
end
end
def reloadable?(fullpath, path)
@reloadable_paths.any?{|rp| fullpath.start_with? rp}
end
def ignore_reload?(delay, onchange, watch_paths = @watch_paths)
return false if @force_reload
(delay && (clock_time - @last_reloaded < delay)) || (onchange && !changed?(watch_paths))
end
def changed?(watch_paths = @watch_paths)
return false if watch_paths && !@paths_changed
@paths_changed = false
return true unless @last_mtime_by_path
@reload_lock.synchronize do
return @unload_files.any?{|f| @last_mtime_by_path[f] != safe_mtime(f) }
end
end
def safe_mtime(path)
File.mtime(path) if File.exist?(path)
end
def find_mtime
@reload_lock.synchronize do
@last_mtime_by_path = {}
@unload_files.each{|f| @last_mtime_by_path[f] = safe_mtime f }
end
@last_mtime_by_path
end
def safe_remove_constant(constant)
Object.send :remove_const, constant
rescue NameError # ignore if it has been already removed
end
end
|
class SalesItems < ActiveRecord::Migration
def change
create_table :sales_items do |t|
t.integer :sale_id
t.integer :item_id
t.integer :quantity
end
end
end
|
# frozen_string_literal: true
class GuruLettersController < ApplicationController
skip_before_action :authenticate_user!, only: %i[new create]
def new
@guru_letter = GuruLetter.new
end
def create
@guru_letter = GuruLetter.new(letter_params)
if @guru_letter.valid?
GuruLettersMailer.contact_us(@guru_letter).deliver_now
redirect_to new_guru_letter_url, notice: t('.success')
else
render :new
end
end
private
def letter_params
params.require(:guru_letter).permit(:name, :email, :message)
end
end
|
class WelcomeController < ApplicationController
def home
if current_user.present?
redirect_to products_path
else
redirect_to new_user_session_path
end
end
end
|
class Api::Mobile::V1::ShopsController < Api::Mobile::V1::ApplicationController
helper_method :count_available_books_in_store
def index
@publisher_id = params[:id]
@shops = Shop.joins(shop_items: {book: :publisher}).where("publishers.id = ?", @publisher_id).distinct
end
def mark_as_sold
shop = Shop.find(shop_id)
if shop.present?
books = shop.shop_items.joins(:book).where('books.id = ?', book_id).with_state(:in_stock)
else
render json: { error: "No shop with id #{shop_id}" }
end
if books.present?
if books.count >= count
books = books.take(count)
books.each do |book|
book.mark_as_sold
end
render json: { state: true }
else
render json: {
error: 'There are not enough books'
}
end
else
render json: { error: "No books with id #{book_id}" }
end
end
private
def shop_id
params[:shop_id].to_i
end
def book_id
params[:book_id].to_i
end
def count
params[:books_count].to_i
end
def count_available_books_in_store(shop)
books = shop.shop_items.with_state(:in_stock).joins(:book, book: :publisher).where("publishers.id = ?", @publisher_id).group("books.id", "books.title").order("books.id").count
books = books.to_a.flatten.each_slice(3).to_a.map do |el|
{
"id": el[0],
"title": el[1],
"copies_in_stock": el[2]
}
end
books
end
end
|
class Post < ActiveRecord::Base
self.table_name = 'posts'
belongs_to :topic
def self.from_user(user_id)
where(user_id: user_id)
end
def self.posted_since(time = 1.minute.ago)
where(arel_table[:created_at].gt time)
end
def updatable_attributes
attributes.slice(*%w(id title text user_id topic_id))
end
end
|
#
# tkextlib/bwidget/scrolledwindow.rb
# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
#
require 'tk'
require 'tk/frame'
require 'tkextlib/bwidget.rb'
module Tk
module BWidget
class ScrolledWindow < TkWindow
end
end
end
class Tk::BWidget::ScrolledWindow
TkCommandNames = ['ScrolledWindow'.freeze].freeze
WidgetClassName = 'ScrolledWindow'.freeze
WidgetClassNames[WidgetClassName] = self
def get_frame(&b)
win = window(tk_send_without_enc('getframe'))
win.instance_eval(&b) if b
win
end
def set_widget(win)
tk_send_without_enc('setwidget', win)
self
end
end
|
#!/usr/bin/env ruby
# -------------------------------------------------------------------------- #
# Copyright 2002-2018, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
require "erb"
CMDS = {
:MISC => %w(mkfs sync mkswap),
:NET => %w(brctl ebtables iptables ip6tables ip ipset arping),
:LVM => %w(lvcreate lvremove lvs vgdisplay lvchange lvscan lvextend),
:ISCSI => %w(iscsiadm tgt-admin tgtadm),
:OVS => %w(ovs-ofctl ovs-vsctl),
:XEN => %w(xentop xl xm),
:CEPH => %w(rbd),
:HA => [
'systemctl start opennebula-flow',
'systemctl stop opennebula-flow',
'systemctl start opennebula-gate',
'systemctl stop opennebula-gate',
'service opennebula-flow start',
'service opennebula-flow stop',
'service opennebula-gate start',
'service opennebula-gate stop'
],
}
KEYS = CMDS.keys
abs_cmds = {}
not_found_cmds = []
KEYS.each do |label|
cmds = CMDS[label]
_abs_cmds = []
cmds.each do |cmd|
cmd_parts = cmd.split
abs_cmd = `which #{cmd_parts[0]} 2>/dev/null`
if !abs_cmd.empty?
cmd_parts[0] = abs_cmd.strip
_abs_cmds << cmd_parts.join(' ')
else
not_found_cmds << cmd
end
end
abs_cmds["ONE_#{label}"] = _abs_cmds
end
abs_cmds.reject!{|k,v| v.empty?}
puts ERB.new(DATA.read,nil, "<>").result(binding)
if !not_found_cmds.empty?
STDERR.puts "\n---\n\nNot found:"
not_found_cmds.each{|cmd| STDERR.puts("- #{cmd}")}
end
__END__
Defaults !requiretty
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
<% KEYS.each do |k|; l = "ONE_#{k}"; v = abs_cmds[l] %>
<% if !v.nil? %>
Cmnd_Alias <%= l %> = <%= v.join(", ") %>
<% end %>
<% end %>
oneadmin ALL=(ALL) NOPASSWD: <%= KEYS.select{|k| !abs_cmds["ONE_#{k}"].nil?}.collect{|k| "ONE_#{k}"}.join(", ") %>
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
if Rails.env.production?
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :timeoutable, :timeout_in =>20.minutes
else
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
has_many :orders
has_many :products
has_many :users
def to_s
first_name
end
def full_name
first_name + last_name
end
end
|
require 'test_helper'
class AchievementsControllerTest < ActionDispatch::IntegrationTest
setup do
@achievement = achievements(:one)
end
test "should get index" do
get achievements_url
assert_response :success
end
test "should get new" do
get new_achievement_url
assert_response :success
end
test "should create achievement" do
assert_difference('Achievement.count') do
post achievements_url, params: { achievement: { } }
end
assert_redirected_to achievement_url(Achievement.last)
end
test "should show achievement" do
get achievement_url(@achievement)
assert_response :success
end
test "should get edit" do
get edit_achievement_url(@achievement)
assert_response :success
end
test "should update achievement" do
patch achievement_url(@achievement), params: { achievement: { } }
assert_redirected_to achievement_url(@achievement)
end
test "should destroy achievement" do
assert_difference('Achievement.count', -1) do
delete achievement_url(@achievement)
end
assert_redirected_to achievements_url
end
end
|
require 'rails_helper'
RSpec.feature 'sign in' do
scenario 'with valid data' do
user = create(:user)
visit new_user_session_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_on 'Log in'
expect(current_path).to eq root_path
end
scenario 'with invalid data' do
user = create(:user)
visit new_user_session_path
fill_in 'Email', with: user.email
fill_in 'Password', with: "#{user.password}1"
click_on 'Log in'
expect(page).to have_text 'Invalid email or password.'
end
end
|
# typed: true
class CreateLocalLawPipelines < ActiveRecord::Migration[6.0]
def change
create_table :local_law_pipelines do |t|
t.text :title
t.text :paragraph
t.text :local_law_link
t.integer :paragraph_number
t.string :book
t.references :local_law_pipeline, null: false, foreign_key: true
t.timestamps
end
end
end
|
require 'elasticsearch/model'
class User < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
geocoded_by :full_street_address
after_validation :geocode unless Rails.env.test?
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable
has_many :owned_animals, class_name: 'Animal', foreign_key: 'owner_id'
has_many :bred_animals, class_name: 'Animal', foreign_key: 'owner_id'
validates :name,
:address1,
:city,
:state,
:zip,
:flock_name,
:email,
:phone,
presence: true
scope :locations, -> { where.not(latitude: nil, longitude: nil).select(:id, :flock_name, :name, :latitude, :longitude) }
def full_street_address
[address1, address2, city, state, zip, 'USA'].compact.join(', ')
end
def address
[address1, address2, [city, state].join(', '), zip].compact.join('\n')
end
end
|
class Projects < ActiveRecord::Migration
def change
create_table "projects", force: true do |t|
t.string "name"
t.string "category"
t.string "project_id"
t.string "acct_number"
t.boolean "active", default: true
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
end
end
|
class Survey < ActiveRecord::Base
belongs_to :creator, class_name: "User"
has_many :completed_surveys, class_name: "Completion"
has_many :survey_takers, class_name: "User", through: :completions
has_many :questions
end
|
require "test_helper"
class LoggingTest < Test::Unit::TestCase
def setup
@old_logger = Logging.logger
end
def teardown
Logging.logger = @old_logger
end
def test_log_message_with_default_level
logger = mock("logger")
logger.expects(:info).with("foo")
Logging.logger = logger
Logging.log.message("foo")
end
def test_log_message_custom_level
logger = mock("logger")
logger.expects(:error).with("foo")
Logging.logger = logger
Logging.log(:error).message("foo")
end
def test_log_error_with_default_level
error = mock(message: "foo", backtrace: ['one', 'two'])
logger = mock("logger")
logger.expects(:info).once.with("foo")
logger.expects(:info).once.with("one\ntwo")
Logging.logger = logger
Logging.log.error(error)
end
def test_log_error_with_custom_level
error = mock(message: "foo", backtrace: ['one', 'two'])
logger = mock("logger")
logger.expects(:error).once.with("foo")
logger.expects(:error).once.with("one\ntwo")
Logging.logger = logger
Logging.log(:error).error(error)
end
def test_no_logger
Logging.logger = nil
assert_nothing_raised do
Logging.log.message("foo")
end
end
end
|
require 'rgl/topsort' # acyclic
class AgentArc < ApplicationRecord
belongs_to :target, foreign_key: 'target_id', class_name: 'Agent', inverse_of: :in_arcs
belongs_to :source, foreign_key: 'source_id', class_name: 'Agent', inverse_of: :out_arcs
alias_attribute :agent, :source
alias_attribute :depends_on, :target
validates :source, presence: true
validates :target, uniqueness: { scope: [:source] }, presence: true
validate :check_acyclic
before_destroy { source.touch }
before_destroy :remove_target_related_formulation_aliases
after_create_commit { sync_nlp_source }
after_update_commit { sync_nlp_source }
def target_related_formulation_aliases
FormulationAlias.find_by_sql ["
SELECT
ia.id,
ia.aliasname,
ia.position_start,
ia.position_end,
ia.formulation_id,
ia.formulation_aliasable_id,
ia.formulation_aliasable_type,
ia.nature,
ia.is_list,
ia.any_enabled
FROM formulation_aliases AS ia
INNER JOIN interpretations ON ia.formulation_aliasable_id = interpretations.id
INNER JOIN formulations AS pr ON ia.formulation_id = pr.id
WHERE interpretations.agent_id = ?
AND ia.formulation_id IN (SELECT formulations.id
FROM formulations
INNER JOIN interpretations ON formulations.interpretation_id = interpretations.id
WHERE interpretations.agent_id = ?)", target_id, source_id]
end
private
def remove_target_related_formulation_aliases
related_aliases = target_related_formulation_aliases
if related_aliases.present?
related_aliases.each(&:destroy)
source.need_nlp_sync
end
end
def check_acyclic
return if source.nil? || target.nil?
src = AgentGraph.new(source).list_out_arcs
dst = AgentGraph.new(target).list_out_arcs
graph = RGL::DirectedAdjacencyGraph.new
(src + dst).each { |from, to| graph.add_edge(from, to) }
graph.add_edge(source, target)
return if graph.acyclic?
errors.add(:cycle, I18n.t('errors.agent_arc.cycle_detected'))
end
def sync_nlp_source
source.need_nlp_sync
source.touch
end
end
|
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
has_many :connections
has_many :categories, through: :connectinos
end |
Rails.application.routes.draw do
get 'exceptions/show'
root 'recipes#homepage'
resources :recipes, only: %w[show]
end
|
class AddBomIdentifierToParts < ActiveRecord::Migration
def change
add_column :parts, :bom_identifier, :string
end
end
|
#
# Library Preparation
#
begin
require 'spec'
rescue LoadError
require 'rubygems' unless ENV['NO_RUBYGEMS']
gem 'rspec'
require 'spec'
end
$:.unshift(File.dirname(__FILE__) + '/../lib')
require 'xpash'
#
# Constants
#
FIXTURE_DIR = "#{File.dirname(__FILE__)}/fixture"
FIXTURE_URL = "http://www.ruby-lang.org/"
Term::ANSIColor::coloring = false
#
# Helper methods
#
def get_fixture(filename = "default.html")
return XPash::Base.new(FIXTURE_DIR + "/" + filename)
end
def prepare_stdout
@stdout_io = StringIO.new
$stdout = @stdout_io
end
def read_stdout
@stdout_io.rewind
return @stdout_io.read
end
|
class LinkedList
attr_accessor :head
def initialize
@head = nil
end
def new_node(value)
Node.new(value)
end
def append(value)
empty? ? set_head(value) : set_tail(value)
end
def remove_at(index)
removed_node = at(index)
prev_node = at(index - 1)
next_node = at(index + 1)
prev_node.next_node = next_node
puts "#{removed_node.value} has left the group"
removed_node
end
def pop
new_tail = at(size - 2)
old_tail = new_tail.next_node
new_tail.next_node = nil
puts " #{old_tail.value} is now poofed! "
old_tail
end
def insert(value, index)
node = new_node(value)
prev_node = at(index - 1)
next_node = at(index)
prev_node.next_node = node
node.next_node = next_node
node
end
def find(value)
node = @head
index = 0
count = size - 1
count.times do
break if value == node.value
index += 1
node = node.next_node
end
value == node.value ? index : nil
end
def contains?(value)
node = @head
count = size - 1
count.times do
break if value == node.value
node = node.next_node
end
value == node.value ? true : false
end
def at(index)
node = @head
count = 0
size.times do
break if index == count
node = node.next_node
count += 1
end
return node
end
def prepend(value)
node = new_node(value)
node.next_node = head
@head = node
end
def last_node(node)
return node if node.tail?
last_node(node.next_node)
end
def size
return 0 if empty?
count_node(head, 1)
end
def empty?
head.nil?
end
def to_s
node = @head
display = "( #{node.value} ) -> "
until node.tail? do
display += " ( #{node.next_node.value} ) -> "
node = node.next_node
end
display += "nil"
end
def set_head(value)
@head = new_node(value)
end
def set_tail(value)
last_node(head).next_node = new_node(value)
end
def count_node(node, counter)
return counter if node.tail?
count_node(node.next_node, counter += 1)
end
def tail
last_node(head)
end
end
class Node
attr_accessor :value, :next_node
def initialize(value=nil)
@value = value
@next_node = nil
end
def tail?
@next_node.nil?
end
end
list_test = LinkedList.new
list_test.append('one')
list_test.append('two')
list_test.append('three')
list_test.append('four')
list_test.prepend('zero')
puts list_test
puts list_test.size
p list_test.contains?('three')
p list_test.at(1)
p list_test.find('nine')
list_test.insert("three_point_five", 4)
puts list_test
list_test.remove_at(4)
puts list_test
|
class Team
attr_reader :name, :motto, :members
def initialize(name,motto)
@name, @motto = name, motto
@members = []
end
def addMembers(*members)
members.each {|member| @members << member}
end
end
|
class QuestionFollower
attr_reader :id, :user_id, :question_id
def self.find_by_id(id)
query = <<-SQL
SELECT
*
FROM
question_followers
WHERE
id = ?
SQL
QuestionFollower.new(QuestionsDatabase.instance.execute(query, id)[0])
end
def self.followers_for_question_id(id)
followers = []
query = <<-SQL
SELECT
users.id, users.fname, users.lname
FROM
users JOIN question_followers
ON users.id = question_followers.user_id
WHERE
question_id = ?
SQL
raw_followers = QuestionsDatabase.instance.execute(query, id)
raw_followers.each do |entry|
followers << User.new(entry)
end
followers
end
def self.followed_questions_for_user_id(id)
questions = []
query = <<-SQL
SELECT
questions.id, questions.title, questions.body, questions.author_id
FROM
question_followers JOIN questions
ON questions.id = question_followers.question_id
WHERE
user_id = ?
SQL
raw_questions = QuestionsDatabase.instance.execute(query, id)
raw_questions.each do |entry|
questions << Question.new(entry)
end
questions
end
def initialize(options={})
@id, @user_id, @question_id =
options.values_at('id', 'user_id', 'question_id')
end
def self.most_followed_questions(n)
questions = []
query = <<-SQL
SELECT
questions.id, author_id, title, body
FROM
questions
JOIN
question_followers
ON
questions.id = question_followers.question_id
GROUP BY
question_id
ORDER BY
COUNT(user_id) DESC
LIMIT ?
SQL
raw_questions = QuestionsDatabase.instance.execute(query, n)
raw_questions.each do |entry|
questions << Question.new(entry)
end
questions
end
end |
FactoryBot.define do
factory :cond_like do
url 'https://instagram.com/someurl'
association :event
end
end
|
class RemoveFieldsFromCompletedTripTasks < ActiveRecord::Migration
def change
remove_column :completed_trip_tasks, :trip, :string
remove_column :completed_trip_tasks, :task, :string
end
end
|
require 'player'
describe Player do
subject(:player) {described_class.new "Tommy"}
describe '#initialize' do
it 'will return the requested player name' do
expect(player.name).to eq "Tommy"
end
it 'will return the requested player healthpoints' do
expect(player.healthpoints).to eq 100
end
end
end
|
RSpec.shared_context 'Github Client', shared_context: :metadata do
let(:endpoint) { 'https://api.github.com/graphql' }
let(:headers) do
{
'Authorization' => "Bearer #{ENV['GITHUB_ACCESS_TOKEN']}",
'Content-Type' => 'application/json'
}
end
let(:client) do
Graphlient::Client.new(
endpoint,
headers: headers,
schema_path: File.expand_path("#{__dir__}/../schema/github.json")
)
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
let(:user) { User.new(username: 'admin') }
describe 'associations' do
it { is_expected.to have_many(:events) }
end
describe 'validations' do
it 'is valid with valid attributes' do
expect(user).to be_valid
end
it 'is not valid without valid attributes' do
user.username = nil
expect(user).to_not be_valid
end
end
end
|
#!/usr/bin/env ruby
# :title: PlanR::Content::ResourceNode
=begin rdoc
(c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org>
=end
require 'plan-r/content_repo/content_node'
require 'find'
module PlanR
module ContentRepo
=begin rdoc
Document resource, e.g. an image, stylesheet, or template.
=end
class ResourceNode < ContentNode
KEY = :resource
PATHNAME = '.CONTENT.rsrc'
def self.valid?(actual_path)
node_path = File.join(actual_path, PATHNAME)
(File.exist? node_path) and (File.directory? node_path)
end
# NOTE: 'tree_path' is the path to the document. this makes
# :resource a directory of resource attachments.
def initialize(tree_path, res_path, fs_path)
@resource_dir = File.join(fs_path, PATHNAME)
actual_path = File.join(@resource_dir, res_path)
# FIXME: should tree_path encode resource location?
super tree_path, actual_path
end
def remove
super
doc_dir = @resource_dir
if (File.exist? doc_dir) and (File.directory? doc_dir) and
(Dir.entries(doc_dir).count <= 2)
if (File.basename(doc_dir) != PATHNAME)
raise NodeDeleteError,
"#{self.class.name} #{doc_dir} != #{PATHNAME}"
else
Dir.rmdir(doc_dir)
end
end
end
end
end
end
|
module CDI
module V1
class SimpleLearningTrackReviewSerializer < ActiveModel::Serializer
root false
attributes :id, :learning_track_id, :student_class_id, :comment,
:user_id, :review_type, :review_type_text, :score,
:review_types_texts, :created_at, :updated_at
end
end
end
|
class Image < ApplicationRecord
validates_presence_of :title
validates_presence_of :attachment_address
manage_with_tolaria using: {
icon: :image,
priority: 1,
category: "Media",
permit_params: [
:title,
:alternate_text,
:credit,
:keywords,
:attachment_address,
],
}
end
|
class GamesController < ApplicationController
def index
@games = Game.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @games }
end
end
def new
@game = Game.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @games }
end
end
def show
@game = Game.find(params[:id])
respond_to do |format|
format.html # index.html.erb
format.json { render json: @games }
end
end
# POST /games
# POST /games.json
def create
@game = Game.new(params[:games])
respond_to do |format|
if @game.save
redirect_to @game
end
end
end
def edit
@game = Game.find(params[:id])
end
def update
@game = Game.find(params[:id])
respond_to do |format|
if @game.update_attributes(params[:game])
format.html { redirect_to @game, notice: 'Game was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @game.errors, status: :unprocessable_entity }
end
end
end
def destroy
@game = Game.find(params[:id])
@game.destroy
respond_to do |format|
format.html {redirect_to games_url }
format.json { head :no_content }
end
end
end
|
json.books @books do |book|
json.extract! book, :isbn, :title, :des
json.comments book.comments do |comment|
json.extract! comment, :commenter, :body
end
json.authors book.authors do |author|
json.extract! author, :name
end
json.extract! book.category, :id, :category_name
end |
require 'xcode-installer/logout'
command :logout do |c|
c.syntax = 'xcode-installer logout'
c.summary = 'Remove account credentials'
c.description = ''
c.action XcodeInstaller::Logout, :action
end
|
class PersonFactory
def initialize max_id
@max_id = max_id
end
def build_person
new_person = Person.new(next_id)
end
def build_fake_person_list qty
persons = Array.new
qty.times do |i|
fake_person_id = next_id + i
persons << Person.new(
fake_person_id,
"fullname#{fake_person_id}",
"email#{fake_person_id}",
"contacts#{fake_person_id}"
)
end
persons
end
private
def next_id
@max_id + 1
end
end |
require 'stringio'
module RubyCraft
# Utils for manipulating bytes back and forth as strings, strings and numbers
module ByteConverter
def toByteString(array)
array.pack('C*')
end
def intBytes(i)
[i >> 24, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF]
end
def stringToByteArray(str)
str.bytes.to_a
end
def arrayToIO(arr)
io = StringIO.new
io.write toByteString arr
io.rewind
io
end
def stringToIo(str)
arrayToIO stringToByteArray(str)
end
def concat(array, enum)
for i in enum
array << i
end
end
def bytesToInt(array)
array.pack('C*').unpack("N").first
end
def pad(array, count, value = 0)
count.times do
array << value
end
array
end
extend self
end
end |
class SecretariatDecorator < Draper::Decorator
delegate_all
def image_url
h.image_tag model.image_url_url
end
end |
class UserSessionsController < ApplicationController
skip_before_filter :require_login, except: [:destroy]
def create
if @user = login(params[:name], params[:password])
redirect_to '/'
else
flash.now[:alert] = 'Login failed'
redirect_to :back
end
end
def destroy
logout
redirect_to '/'
end
end
|
# coding: utf-8
require 'spec_helper'
describe Cleanweb::Spam do
context "spam?" do
let(:params) { {subject: "subject", body: "body"} }
let(:cleanweb) { Cleanweb.new params }
let(:ok_response) { File.read(File.join("spec", "mocks", "ok.xml")) }
let(:links_response) { File.read(File.join("spec", "mocks", "links.xml")) }
let(:no_links_response) { File.read(File.join("spec", "mocks", "no_links.xml")) }
let(:no_links_body_response) { File.read(File.join("spec", "mocks", "no_links_body.xml")) }
let(:body_response) { File.read(File.join("spec", "mocks", "body.xml")) }
it "возвращает false если контент не спам" do
cleanweb.should_receive(:ask_yandex).and_return(ok_response)
expect(cleanweb.spam?).to eq false
end
it "возвращает true если контент спам, а ссылки ок" do
cleanweb.should_receive(:ask_yandex).and_return(body_response)
expect(cleanweb.spam?).to eq true
end
it "возвращает true если контент ок, а ссылки спам" do
cleanweb.should_receive(:ask_yandex).and_return(links_response)
expect(cleanweb.spam?).to eq true
end
it "возвращает false если контент ок, а ссылкок нет" do
cleanweb.should_receive(:ask_yandex).and_return(no_links_response)
expect(cleanweb.spam?).to eq false
end
it "возвращает true если контент спам, а ссылкок нет" do
cleanweb.should_receive(:ask_yandex).and_return(no_links_body_response)
expect(cleanweb.spam?).to eq true
end
end
end |
#encoding: utf-8
require 'rubygems'
require 'sqlite3'
require 'sinatra'
require 'sinatra/reloader'
def init_db
@db = SQLite3::Database.new 'blogsin.db'
@db.results_as_hash = true
end
before do
init_db
end
configure do
init_db
@db.execute 'CREATE TABLE IF NOT EXISTS
"Posts"
(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"created_date" DATE,
"content" TEXT
)'
end
get '/' do
@results = @db.execute 'SELECT * FROM Posts ORDER BY id DESC'
erb :index
end
get '/new' do
erb :new
end
post '/new' do
content = params[:content]
if content.length <= 0
@error = 'Type any text!'
return erb :new
end
@db.execute 'INSERT INTO Posts (content, created_date) VALUES (?, datetime())', [content]
redirect to '/'
erb "You typed #{content}"
end
get '/details/:post_id' do
post_id = params[:post_id]
results = @db.execute 'SELECT * FROM Posts WHERE id = ?', [post_id]
@row = results[0]
erb :details
end
post '/details/:post_id' do
post_id = params[:post_id]
content = params[:content]
erb "You comment: #{content} for post #{post_id}"
end
|
module Spree
class Calculator::PercentOffSalePriceCalculator < Spree::Calculator
# TODO validate that the sale price is between 0 and 1
def self.description
"Calculates the sale price for a Variant by taking off a percentage of the original price"
end
def compute(sale_price)
(1.0 - sale_price.value.to_f/100.0) * sale_price.price.variant.original_price.to_f
end
end
end |
class Game < ApplicationRecord
validates :name, presence: true, uniqueness: { message: 'not unique: This game is already in our database'}
validates :summary, presence: true
validates :cover_url, presence: true
has_many :reviews
end
|
module RequestHelper
def valid_signin(user)
visit new_user_session_path
fill_in 'Email', with: user.email.upcase
fill_in 'Password', with: user.password
click_button "Log in"
end
def update_author_with(name)
fill_in 'author_name', with: name
click_button "Update author"
end
def update_group_with(name)
fill_in 'group_name', with: name
click_button "Update group"
end
def update_book_with(title)
fill_in 'book_title', with: title
click_button "Update book"
end
def check_in(object)
check 'book_'+object.class.to_s.downcase+"_ids_#{object.id}"
end
def check_out(object)
uncheck 'book_'+object.class.to_s.downcase+"_ids_#{object.id}"
end
def check_permission_for_editing(object)
check object.to_s.downcase+"_editor"
end
end
RSpec::Matchers.define :have_error_message do |message|
match do |page|
expect(page).to have_selector('.alert.alert-danger', text: message)
end
end
|
name 'yum-repoforge'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache-2.0'
description 'Installs and onfigures yum-repoforge aka RPMforge'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '2.0.1'
depends 'compat_resource', '>= 12.16.3'
depends 'yum-epel'
%w(amazon centos oracle redhat scientific).each do |os|
supports os
end
source_url 'https://github.com/chef-cookbooks/yum-repoforge'
issues_url 'https://github.com/chef-cookbooks/yum-repoforge/issues'
chef_version '>= 12.1' if respond_to?(:chef_version)
|
require 'sinatra'
require 'net/http'
require 'json'
ROOT_DIR=File.dirname(__FILE__)
require "#{ROOT_DIR}/lib/google/resources_parser"
get '/' do
haml :index
end
get '/api/v1/google/resources' do
uri = URI('https://apps-apis.google.com/a/feeds/calendar/resource/2.0/taptera.com/')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = request.env['HTTP_AUTHORIZATION']
http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = true
res = http.request(req)
resources = Google::ResourcesParser.new.from_xml(res.body)
json = resources.map do |r|
{
name: r.name,
identifier: r.identifier
}
end
content_type :json
json.to_json
end |
require 'spec_helper'
require 'topicz/commands/stats_command'
describe Topicz::Commands::StatsCommand do
it 'generates no output if no changes were made' do
with_testdata do
expect {
Topicz::Commands::StatsCommand.new(nil, %w(-y 2000 -w 1)).execute
}.to output('').to_stdout
end
end
it 'generates statistics on Documents, Notes and Reference Material' do
expected =<<EOF
Special topic
* Documents/2001-01-05 Presentation.pptx
* Notes/2001-01-01 Note 1.md
* Reference Material/2001-01-03 Report.pdf
EOF
with_testdata do
expect {
Topicz::Commands::StatsCommand.new(nil, %w(-y 2001 -w 1)).execute
}.to output(expected).to_stdout
end
end
it 'generates statistics on across topics' do
expected =<<EOF
third
* Notes/2002-01-01 Note 1.md
fourth
* Notes/2002-01-01 Note 1.md
EOF
with_testdata do
expect {
Topicz::Commands::StatsCommand.new(nil, %w(-y 2002 -w 1)).execute
}.to output(expected).to_stdout
end
end
it 'supports help' do
expect(Topicz::Commands::StatsCommand.new.option_parser.to_s).to include 'Generates weekly statistics'
end
end
|
module Roglew
module GLX
WINDOW_BIT_SGIX ||= 0x00000001
RGBA_BIT_SGIX ||= 0x00000001
PIXMAP_BIT_SGIX ||= 0x00000002
COLOR_INDEX_BIT_SGIX ||= 0x00000002
SCREEN_EXT ||= 0x800C
DRAWABLE_TYPE_SGIX ||= 0x8010
RENDER_TYPE_SGIX ||= 0x8011
X_RENDERABLE_SGIX ||= 0x8012
FBCONFIG_ID_SGIX ||= 0x8013
RGBA_TYPE_SGIX ||= 0x8014
COLOR_INDEX_TYPE_SGIX ||= 0x8015
end
end
module GLX_SGIX_fbconfig
module RenderHandle
include Roglew::RenderHandleExtension
functions [
#GLXFBConfigSGIX* glXChooseFBConfigSGIX(Display *dpy, int screen, const int *attrib_list, int *nelements)
[:glXChooseFBConfigSGIX, [:pointer, :int, :pointer, :pointer], :pointer],
#GLXContext glXCreateContextWithConfigSGIX(
# Display* dpy,
# GLXFBConfig config,
# int render_type,
# GLXContext share_list,
# Bool direct)
[:glXCreateContextWithConfigSGIX, [:pointer, :pointer, :int, :pointer, :bool], :pointer],
#GLXPixmap glXCreateGLXPixmapWithConfigSGIX(Display* dpy, GLXFBConfig config, Pixmap pixmap)
[:glXCreateGLXPixmapWithConfigSGIX, [:pointer, :pointer, :int], :int],
#int glXGetFBConfigAttribSGIX(Display* dpy, GLXFBConfigSGIX config, int attribute, int *value)
[:glXGetFBConfigAttribSGIX, [:pointer, :pointer, :int, :pointer], :int],
#GLXFBConfigSGIX glXGetFBConfigFromVisualSGIX(Display* dpy, XVisualInfo *vis)
[:glXGetFBConfigFromVisualSGIX, [:pointer, Roglew::GLX::XVisualInfo.ptr], :pointer],
#XVisualInfo* glXGetVisualFromFBConfigSGIX(Display *dpy, GLXFBConfig config)
[:glXGetVisualFromFBConfigSGIX, [:pointer, :pointer], Roglew::GLX::XVisualInfo.ptr]
]
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.