text stringlengths 10 2.61M |
|---|
class CreateMonsterRewards < ActiveRecord::Migration
def change
create_table :monster_rewards do |t|
t.integer :monster_id
t.integer :item_id
t.string :rank
t.string :action
t.integer :drop_rate
t.timestamps
end
end
end
|
# == Schema Information
#
# Table name: resources
#
# id :integer not null, primary key
# subject_id :integer
# title :string(100)
# description :string
# row :integer
# url :string
# time_estimate :string(50)
# created_at :datetime not null
# updated_at :datetime not null
# content :text
# slug :string
# published :boolean
# video_url :string
# category :integer
# own :boolean
# type :string(100)
#
# Indexes
#
# index_resources_on_subject_id (subject_id)
#
class Resource < ApplicationRecord
include RankedModel
ranks :row, with_same: :subject_id, class_name: 'Resource'
extend FriendlyId
friendly_id :title
enum category: [:blog_post, :video_tutorial, :reading, :game, :tutorial, :documentation]
belongs_to :subject
has_many :comments, as: :commentable # TODO: change to reviews
has_many :resource_completions, dependent: :delete_all
validates :subject, :title, :description, presence: :true
scope :for, -> user { published unless user.is_admin? }
scope :published, -> { where(published: true) }
default_scope { rank(:row) }
after_initialize :default_values
def next
self.subject.resources.published.where('row > ?', self.row).first
end
def last?
self.next.nil?
end
def self_completable?
url? || markdown?
end
def type_name
return "url" if url?
return "markdown" if markdown?
return "course" if course?
return "quiz" if quiz?
end
def url?
self.type == "ExternalUrl"
end
def markdown?
self.type == "MarkdownDocument"
end
def course?
self.type == "Course"
end
def quiz?
self.type == "Quizer::Quiz"
end
def to_s
title
end
def to_path
"#{subject.to_path}/resources/#{slug}"
end
def to_html_link
"<a href='#{to_path}'>#{title}</a>"
end
def to_html_description
"#{to_html_link} del tema #{subject.to_html_link}"
end
private
def default_values
self.published ||= false
self.type ||= "ExternalUrl"
rescue ActiveModel::MissingAttributeError => e
# ranked_model makes partial selects and this error is thrown
end
end
|
class AddIndexActionsToPermissions < ActiveRecord::Migration
def change
add_index :permissions, :action
end
end
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2019-2020 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Mongo
module Crypt
# A class that implements I/O methods between the driver and
# the MongoDB server or mongocryptd.
#
# @api private
class EncryptionIO
# Timeout used for TLS socket connection, reading, and writing.
# There is no specific timeout written in the spec. See SPEC-1394
# for a discussion and updates on what this timeout should be.
SOCKET_TIMEOUT = 10
# Creates a new EncryptionIO object with information about how to connect
# to the key vault.
#
# @param [ Mongo::Client ] client The client used to connect to the collection
# that stores the encrypted documents, defaults to nil.
# @param [ Mongo::Client ] mongocryptd_client The client connected to mongocryptd,
# defaults to nil.
# @param [ Mongo::Client ] key_vault_client The client connected to the
# key vault collection.
# @param [ Mongo::Client | nil ] metadata_client The client to be used to
# obtain collection metadata.
# @param [ String ] key_vault_namespace The key vault namespace in the format
# db_name.collection_name.
# @param [ Hash ] mongocryptd_options Options related to mongocryptd.
#
# @option mongocryptd_options [ Boolean ] :mongocryptd_bypass_spawn
# @option mongocryptd_options [ String ] :mongocryptd_spawn_path
# @option mongocryptd_options [ Array<String> ] :mongocryptd_spawn_args
#
# @note When being used for auto encryption, all arguments are required.
# When being used for explicit encryption, only the key_vault_namespace
# and key_vault_client arguments are required.
#
# @note This class expects that the key_vault_client and key_vault_namespace
# options are not nil and are in the correct format.
def initialize(
client: nil, mongocryptd_client: nil, key_vault_namespace:,
key_vault_client:, metadata_client:, mongocryptd_options: {}
)
validate_key_vault_client!(key_vault_client)
validate_key_vault_namespace!(key_vault_namespace)
@client = client
@mongocryptd_client = mongocryptd_client
@key_vault_db_name, @key_vault_collection_name = key_vault_namespace.split('.')
@key_vault_client = key_vault_client
@metadata_client = metadata_client
@options = mongocryptd_options
end
# Query for keys in the key vault collection using the provided
# filter
#
# @param [ Hash ] filter
#
# @return [ Array<BSON::Document> ] The query results
def find_keys(filter)
key_vault_collection.find(filter).to_a
end
# Insert a document into the key vault collection
#
# @param [ Hash ] document
#
# @return [ Mongo::Operation::Insert::Result ] The insertion result
def insert_data_key(document)
key_vault_collection.insert_one(document)
end
# Get collection info for a collection matching the provided filter
#
# @param [ Hash ] filter
#
# @return [ Hash ] The collection information
def collection_info(db_name, filter)
unless @metadata_client
raise ArgumentError, 'collection_info requires metadata_client to have been passed to the constructor, but it was not'
end
@metadata_client.use(db_name).database.list_collections(filter: filter, deserialize_as_bson: true).first
end
# Send the command to mongocryptd to be marked with intent-to-encrypt markings
#
# @param [ Hash ] cmd
#
# @return [ Hash ] The marked command
def mark_command(cmd)
unless @mongocryptd_client
raise ArgumentError, 'mark_command requires mongocryptd_client to have been passed to the constructor, but it was not'
end
# Ensure the response from mongocryptd is deserialized with { mode: :bson }
# to prevent losing type information in commands
options = { execution_options: { deserialize_as_bson: true } }
begin
response = @mongocryptd_client.database.command(cmd, options)
rescue Error::NoServerAvailable => e
raise e if @options[:mongocryptd_bypass_spawn]
spawn_mongocryptd
response = @mongocryptd_client.database.command(cmd, options)
end
return response.first
end
# Get information about the remote KMS encryption key and feed it to the the
# KmsContext object
#
# @param [ Mongo::Crypt::KmsContext ] kms_context A KmsContext object
# corresponding to one remote KMS data key. Contains information about
# the endpoint at which to establish a TLS connection and the message
# to send on that connection.
# @param [ Hash ] tls_options. TLS options to connect to KMS provider.
# The options are same as for Mongo::Client.
def feed_kms(kms_context, tls_options)
with_ssl_socket(kms_context.endpoint, tls_options) do |ssl_socket|
Timeout.timeout(SOCKET_TIMEOUT, Error::SocketTimeoutError,
'Socket write operation timed out'
) do
ssl_socket.syswrite(kms_context.message)
end
bytes_needed = kms_context.bytes_needed
while bytes_needed > 0 do
bytes = Timeout.timeout(SOCKET_TIMEOUT, Error::SocketTimeoutError,
'Socket read operation timed out'
) do
ssl_socket.sysread(bytes_needed)
end
kms_context.feed(bytes)
bytes_needed = kms_context.bytes_needed
end
end
end
# Adds a key_alt_name to the key_alt_names array of the key document
# in the key vault collection with the given id.
def add_key_alt_name(id, key_alt_name)
key_vault_collection.find_one_and_update(
{ _id: id },
{ '$addToSet' => { keyAltNames: key_alt_name } },
)
end
# Removes the key document with the given id
# from the key vault collection.
def delete_key(id)
key_vault_collection.delete_one(_id: id)
end
# Finds a single key document with the given id.
def get_key(id)
key_vault_collection.find(_id: id).first
end
# Returns a key document in the key vault collection with
# the given key_alt_name.
def get_key_by_alt_name(key_alt_name)
key_vault_collection.find(keyAltNames: key_alt_name).first
end
# Finds all documents in the key vault collection.
def get_keys
key_vault_collection.find
end
# Removes a key_alt_name from the key_alt_names array of the key document
# in the key vault collection with the given id.
def remove_key_alt_name(id, key_alt_name)
key_vault_collection.find_one_and_update(
{ _id: id },
[
{
'$set' => {
keyAltNames: {
'$cond' => [
{ '$eq' => [ '$keyAltNames', [ key_alt_name ] ] },
'$$REMOVE',
{
'$filter' => {
input: '$keyAltNames',
cond: { '$ne' => [ '$$this', key_alt_name ] }
}
}
]
}
}
}
]
)
end
# Apply given requests to the key vault collection using bulk write.
#
# @param [ Array<Hash> ] requests The bulk write requests.
#
# @return [ BulkWrite::Result ] The result of the operation.
def update_data_keys(updates)
key_vault_collection.bulk_write(updates)
end
private
def validate_key_vault_client!(key_vault_client)
unless key_vault_client
raise ArgumentError.new('The :key_vault_client option cannot be nil')
end
unless key_vault_client.is_a?(Client)
raise ArgumentError.new(
'The :key_vault_client option must be an instance of Mongo::Client'
)
end
end
def validate_key_vault_namespace!(key_vault_namespace)
unless key_vault_namespace
raise ArgumentError.new('The :key_vault_namespace option cannot be nil')
end
unless key_vault_namespace.split('.').length == 2
raise ArgumentError.new(
"#{key_vault_namespace} is an invalid key vault namespace." +
"The :key_vault_namespace option must be in the format database.collection"
)
end
end
# Use the provided key vault client and namespace to construct a
# Mongo::Collection object representing the key vault collection.
def key_vault_collection
@key_vault_collection ||= @key_vault_client.with(
database: @key_vault_db_name,
read_concern: { level: :majority },
write_concern: { w: :majority }
)[@key_vault_collection_name]
end
# Spawn a new mongocryptd process using the mongocryptd_spawn_path
# and mongocryptd_spawn_args passed in through the extra auto
# encrypt options. Stdout and Stderr of this new process are written
# to /dev/null.
#
# @note To capture the mongocryptd logs, add "--logpath=/path/to/logs"
# to auto_encryption_options -> extra_options -> mongocrpytd_spawn_args
#
# @return [ Integer ] The process id of the spawned process
#
# @raise [ ArgumentError ] Raises an exception if no encryption options
# have been provided
def spawn_mongocryptd
mongocryptd_spawn_args = @options[:mongocryptd_spawn_args]
mongocryptd_spawn_path = @options[:mongocryptd_spawn_path]
unless mongocryptd_spawn_path
raise ArgumentError.new(
'Cannot spawn mongocryptd process when no ' +
':mongocryptd_spawn_path option is provided'
)
end
if mongocryptd_spawn_path.nil? ||
mongocryptd_spawn_args.nil? || mongocryptd_spawn_args.empty?
then
raise ArgumentError.new(
'Cannot spawn mongocryptd process when no :mongocryptd_spawn_args ' +
'option is provided. To start mongocryptd without arguments, pass ' +
'"--" for :mongocryptd_spawn_args'
)
end
begin
Process.spawn(
mongocryptd_spawn_path,
*mongocryptd_spawn_args,
[:out, :err]=>'/dev/null'
)
rescue Errno::ENOENT => e
raise Error::MongocryptdSpawnError.new(
"Failed to spawn mongocryptd at the path \"#{mongocryptd_spawn_path}\" " +
"with arguments #{mongocryptd_spawn_args}. Received error " +
"#{e.class}: \"#{e.message}\""
)
end
end
# Provide a TLS socket to be used for KMS calls in a block API
#
# @param [ String ] endpoint The URI at which to connect the TLS socket.
# @param [ Hash ] tls_options. TLS options to connect to KMS provider.
# The options are same as for Mongo::Client.
# @yieldparam [ OpenSSL::SSL::SSLSocket ] ssl_socket Yields a TLS socket
# connected to the specified endpoint.
#
# @raise [ Mongo::Error::KmsError ] If the socket times out or raises
# an exception
#
# @note The socket is always closed when the provided block has finished
# executing
def with_ssl_socket(endpoint, tls_options)
address = begin
host, port = endpoint.split(':')
port ||= 443 # All supported KMS APIs use this port by default.
Address.new([host, port].join(':'))
end
mongo_socket = address.socket(
SOCKET_TIMEOUT,
tls_options.merge(ssl: true)
)
yield(mongo_socket.socket)
rescue => e
raise Error::KmsError, "Error when connecting to KMS provider: #{e.class}: #{e.message}"
ensure
mongo_socket&.close
end
end
end
end
|
require 'test_helper'
class CassandraObject::Types::ArrayTypeTest < CassandraObject::Types::TestCase
test 'encode' do
assert_equal ['1', '2'].to_json, coder.encode(['1', '2'])
assert_raise ArgumentError do
coder.encode('wtf')
end
end
test 'decode' do
assert_equal ['1', '2'], coder.decode(['1', '2'].to_json)
assert_equal [], coder.decode(nil)
assert_equal [], coder.decode('')
end
class TestIssue < CassandraObject::Base
self.column_family = 'Issues'
array :favorite_colors, unique: true
end
test 'default' do
assert_equal [], TestIssue.new.favorite_colors
end
test 'append marks dirty' do
issue = TestIssue.create favorite_colors: []
assert !issue.changed?
issue.favorite_colors << 'red'
assert issue.changed?
assert_equal({'favorite_colors' => [[], ['red']]}, issue.changes)
end
test 'delete marks dirty' do
issue = TestIssue.create favorite_colors: ['red']
assert !issue.changed?
issue.favorite_colors.delete('red')
assert issue.changed?
assert_equal({'favorite_colors' => [['red'], []]}, issue.changes)
end
test 'unique array removes blank' do
issue = TestIssue.create favorite_colors: ['blue', 'red', '', nil]
assert_equal ['blue', 'red'], issue.favorite_colors
end
test 'unique array uniquifies' do
issue = TestIssue.create favorite_colors: ['blue', 'red']
issue.favorite_colors = ['red', 'red', 'blue']
assert !issue.changed?
issue.favorite_colors = ['red', 'green']
assert issue.changed?
end
test 'unique array rescues argument error' do
issue = TestIssue.create favorite_colors: [1, 'red']
assert_equal [1, 'red'], issue.favorite_colors
end
test 'write non array' do
issue = TestIssue.create favorite_colors: true
assert_equal [true], issue.favorite_colors
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources 'users' do
resources 'recipes'
end
get '/search' => 'pages#search'
get '/instructions' => 'pages#instructions'
get '/ingredients' => 'pages#ingredients'
get '/login' => 'sessions#new'
post '/login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
get '/' => 'pages#index'
root 'pages#index'
end
|
# Modelo TextoFavorito
# Tabla textos_favorito
# Campos id:integer
# medico_id:integer
# texto_id:integer
# created_at:datetime
# updated_at:datetime
class TextoFavorito < ActiveRecord::Base
belongs_to :medico, inverse_of: :textos_favoritos
belongs_to :texto, inverse_of: :textos_favoritos
validates :medico, presence: true
validates :texto, presence: true
end
|
# == Schema Information
# Schema version: 20100705154452
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# crypted_password :string(255)
# password_salt :string(255)
# persistence_token :string(255)
# login_count :integer default(0), not null
# failed_login_count :integer default(0), not null
# last_request_at :datetime
# current_login_at :datetime
# last_login_at :datetime
# current_login_ip :string(255)
# last_login_ip :string(255)
# first_name :string(255)
# last_name :string(255)
# country :string(255)
# birthday :date
# created_at :datetime
# updated_at :datetime
#
class User < ActiveRecord::Base
acts_as_authentic
has_and_belongs_to_many :roles
validates_presence_of :password, :password_confirmation, :on => :create
validates_presence_of :email
#attr_accessor :first_name, :last_name
def has_role?(rolename)
self.roles.find_by_name(rolename) ? true : false
end
def full_name
#return "Full name here"
[first_name, last_name].join(" ")
end
# Alternatively we may want to set dependent to nullify if we are
# going to allow anonymous voting in the future
has_many :ratings, :dependent => :destroy
has_many :entities, :through => :ratings
has_many :opinions, :through => :ratings
has_many :beliefs, :dependent => :destroy
has_many :opinions, :through => :beliefs
before_destroy :fix_global_ideals
def fix_global_ideals
beliefs = Belief.find_by_user_id id
beliefs.each do |b|
#TODO delete global ideal information if the user is deleted
end
end
def get_ideal_and_weight_for(opinion)
belief = Belief.find_by_opinion_id_and_user_id opinion, self
unless belief and belief.ideal
return nil, nil
end
ideal = belief.ideal
# If weight not given, set to full... why am I doing this?
weight = (belief.weight and belief.weight > 0) ? belief.weight : 5
if opinion.dimension.bool?
# Transform boolean 0|1 values into either 1|5
ideal = ideal * 4 + 1
end
return ideal, weight
end
def cos_similarity(other)
similarity(other, true)
end
def calude_similarity(other)
similarity(other, false, true)
end
def similarity(other, use_cos = false, use_calude = false)
return 1 if self.id == other.id
beliefs = Belief.find :all, :conditions => "user_id = #{self.id}"
num = 0
unless use_cos
sims = 0
else
sum_mine_his = 0
sum_his_sq = 0
sum_mine_sq = 0
end
beliefs.each do |mine|
next unless mine.opinion.dimension.enabled?
his = Belief.find_by_user_id_and_opinion_id other, mine.opinion_id
#If this user doesn't have a belief set then go to next one
next unless his
unless use_cos
sims += mine.similarity_to his, use_calude
# this is the +2 part
num += 1 if use_calude
else
if mine.opinion.dimension.bool?
mine_i = mine.ideal * 4 + 1
his_i = his.ideal * 4 + 1
else
mine_i = mine.ideal
his_i = his.ideal
end
# Set weight to I don't care if not available
mine_w = (mine.weight ? mine.weight : 1)
his_w = (his.weight ? his.weight : 1)
sum_mine_his += mine_i * his_i + mine_w * his_w
sum_mine_sq += mine_i * mine_i + mine_w * mine_w
sum_his_sq += his_i * his_i + his_w * his_w
end
num += 1
end
if use_cos
return (sum_mine_his / (Math.sqrt(sum_mine_sq) * Math.sqrt(sum_his_sq))) if num > 0
elsif num > 0
ret = sims / num
return ret
end
return nil
end
# Returns rating out of 10
def rating_for(entity, wf = 5)
ratings = Rating.all :conditions => "entity_id=#{entity.id} and user_id=#{self.id}"
return nil unless ratings and ratings.length > 0
dist = 0
num = 0
ratings.each do |rating|
weight = rating.opinion.weight
next if weight < 1.1
dist += Dimension.distance(rating.value, rating.opinion.ideal, weight / wf)
num += 1
end
((1 - dist / num) * 10.0)
end
def has_rated?(entity)
ratings = Rating.all :conditions => "entity_id=#{entity.id} and user_id=#{self.id}"
return false unless ratings and ratings.length > 0
true
end
def get_rated_entities
ratings = Rating.all :conditions => {:user_id => self.id}, :select => "DISTINCT(entity_id)", :include => :entity
ratings.collect {|x| x.entity }
end
def get_avg_rating( wf = 5)
num_ratings = 0
total_rating = 0
entities = get_rated_entities
entities.each do |e|
total_rating += self.rating_for e, wf
num_ratings += 1
end
return total_rating / num_ratings if num_ratings > 0
return nil
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe 'SDAM prose tests' do
# The "streaming protocol tests" are covered by the tests in
# sdam_events_spec.rb.
describe 'RTT tests' do
min_server_fcv '4.4'
require_topology :single
let(:subscriber) { Mrss::EventSubscriber.new }
let(:client) do
new_local_client(SpecConfig.instance.addresses,
# Heartbeat interval is bound by 500 ms
SpecConfig.instance.test_options.merge(
heartbeat_frequency: 0.5,
app_name: 'streamingRttTest',
),
).tap do |client|
client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
end
end
it 'updates RTT' do
server = client.cluster.next_primary
sleep 2
events = subscriber.select_succeeded_events(Mongo::Monitoring::Event::ServerHeartbeatSucceeded)
events.each do |event|
event.round_trip_time.should be_a(Numeric)
event.round_trip_time.should > 0
end
root_authorized_client.use('admin').database.command(
configureFailPoint: 'failCommand',
mode: {times: 1000},
data: {
failCommands: %w(isMaster hello),
blockConnection: true,
blockTimeMS: 500,
appName: "streamingRttTest",
},
)
deadline = Mongo::Utils.monotonic_time + 10
loop do
if server.average_round_trip_time > 0.25
break
end
if Mongo::Utils.monotonic_time >= deadline
raise "Failed to witness RTT growing to >= 250 ms in 10 seconds"
end
sleep 0.2
end
end
after do
root_authorized_client.use('admin').database.command(
configureFailPoint: 'failCommand', mode: 'off')
end
end
end
|
require 'rails_helper'
describe HomeController do
describe 'GET search' do
let(:collective) { create(:collective, name: 'Werner') }
let!(:unwanted_collective) { create(:collective, name: 'Lambda') }
let!(:desired_intervention) { create(:intervention, name: 'Praça Werner & Gauss', collective: collective) }
let!(:undesired_intervention) { create(:intervention, name: 'Johnson & Johnson', collective: collective) }
before do
get :search, query: 'Werrner', tag: 'any'
end
it 'returns only desired interventions' do
expect(assigns(:interventions)).to include(desired_intervention)
expect(assigns(:interventions)).not_to include(undesired_intervention)
end
it 'returns desired collectives' do
expect(assigns(:collectives)).to include(collective)
expect(assigns(:collectives)).not_to include(unwanted_collective)
end
end
end
|
require "net/http"
require "uri"
require "json"
module Code2Gist
extend self
CODE_REGEX = /```((?:\s*)\w+\.\w+)?[^\n]*\n(.*?)```/m
module Config
def self.github_login
@@github_login ||= nil
end
def self.github_login=(github_login)
@@github_login = github_login
end
def self.github_token
@@github_token ||= nil
end
def self.github_token=(github_token)
@@github_token = github_token
end
end
def upload(text, description = nil, anonymous = false)
new_text = name_nameless_code_blocks(text)
code_blocks = Hash[*new_text.scan(CODE_REGEX).flatten]
if code_blocks.empty?
return nil
end
get_gist(code_blocks, description, anonymous)
end
def replace(text, description = nil, opts = {})
options = {:html => false, :anonymous => false}.merge(opts)
new_text = name_nameless_code_blocks(text)
gist_url = upload(new_text, description, options[:anonymous])
if options[:html]
new_text.gsub(CODE_REGEX, "<script src=\"#{gist_url}.js?file=\\1\"></script>")
else
new_text.gsub(CODE_REGEX, "#{gist_url}?file=\\1")
end
end
private
def name_nameless_code_blocks(text)
nameless_blocks = 0
new_text = text.gsub(/```((?:\s*)\w+\.\w+)?/).with_index do |match, index|
if index%2 == 0 && match.size == 3
nameless_blocks += 1;
"```untitled_#{nameless_blocks}.txt"
else
match
end
end
new_text
end
def get_gist(data, description, anonymous)
post_data = {}
data.each_with_index do |(filename, content), index|
post_data.merge!("files[#{filename}]" => content)
end
post_data.merge!(
"login" => Code2Gist::Config.github_login,
"token" => Code2Gist::Config.github_token
) unless anonymous || Code2Gist::Config.github_login.nil? || Code2Gist::Config.github_token.nil?
post_data.merge!("description" => description)
result = Net::HTTP.post_form(URI.parse("http://gist.github.com/api/v1/json/new"), post_data)
if result.code == "401"
$stderr.puts "Your GitHub login/token credentials are incorrect"
elsif result.code != "200"
$stderr.puts "There was a problem communicating with http://gist.github.com (#{result.code} error)"
end
parsed_json = JSON(result.body)
repo = nil
parsed_json['gists'].each do |key, val|
key.each do |k, v|
if "#{k}" == 'repo'
repo = "#{v}"
end
end
end
return "https://gist.github.com/#{repo}"
end
end
|
class RemoveUniquenessFromUniqueHash < ActiveRecord::Migration
def change
remove_index :answers, :unique_hash
end
end
|
require 'rails_helper'
RSpec.describe Authenticator, type: :model do
describe ".access_token" do
subject { described_class.access_token(authorization) }
context "when authorization header contains a bearer token" do
let(:authorization) { "Bearer foo" }
it { is_expected.to eq("foo") }
end
context "when authorization header doesn't contain a bearer prefix" do
let(:authorization) { "foo" }
it "raises an error" do
expect { subject }.to raise_error(Authenticator::Error,
"Bearer token is invalid")
end
end
context "when authorization header doesn't contain a token" do
let(:authorization) { "Bearer " }
it "raises an error" do
expect { subject }.to raise_error(Authenticator::Error,
"Bearer token is invalid")
end
end
end
describe ".validate_token" do
let(:validator) { instance_double("GoogleIDToken::Validator") }
before do
allow(validator).to receive(:check).with("foo", "www.example.com")
.and_return({ foo: "bar" })
allow(validator).to receive(:check).with("invalid", "www.example.com")
.and_raise(GoogleIDToken::ValidationError)
end
subject { described_class.validate_token(access_token, validator) }
context "when token is valid" do
let(:access_token) { "foo" }
it { is_expected.to be true }
end
context "when token is invalid" do
let(:access_token) { "invalid" }
it { is_expected.to be false }
end
end
end
|
require 'logger'
module Logging
def self.make_logger(root_dir, log_file_name, log_dir_name='logs', log_level=Logger::INFO, rotation_count=10, size_in_bytes=10240000)
# pass in root_dir = ::File.dirname(__FILE__)
logs_dir = ::File.join(root_dir, log_dir_name)
::Dir.mkdir(logs_dir) unless File.exists? logs_dir
::Logger.class_eval do
alias_method :write, :<<
end
logger = Logger.new(::File.join(logs_dir, log_file_name), rotation_count, size_in_bytes)
logger.level = log_level
logger
end
end
|
class AddAttachmentHeadBackgroundToHomeResources < ActiveRecord::Migration
def self.up
add_column :home_resources, :head_background_file_name, :string
add_column :home_resources, :head_background_content_type, :string
add_column :home_resources, :head_background_file_size, :integer
add_column :home_resources, :head_background_updated_at, :datetime
end
def self.down
remove_column :home_resources, :head_background_file_name
remove_column :home_resources, :head_background_content_type
remove_column :home_resources, :head_background_file_size
remove_column :home_resources, :head_background_updated_at
end
end
|
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/shared/windows'
require 'etc'
platform_is :windows do
describe "Etc.passwd" do
it_behaves_like(:etc_on_windows, :passwd)
end
end
platform_is_not :windows do
describe "Etc.passwd" do
before(:all) do
@etc_passwd = `cat /etc/passwd`.chomp.split("\n").
map { |s| s.split(':') }.
map { |e| Struct::Passwd.new(e[0],e[1],e[2].to_i,e[3].to_i,e[4],e[5],e[6]) }
end
before(:each) do
Etc.setpwent
end
it "should return an instance of Struct::Passwd" do
pw = Etc.passwd
pw.is_a?(Struct::Passwd).should == true
end
it "should return the first entry from /etc/passwd on the first call without a passed block" do
expected = @etc_passwd.first
pw = Etc.passwd
pw.uid.should == expected.uid
end
it "should return the second entry from /etc/passwd on the second call without a passed block" do
expected = @etc_passwd.at(1)
Etc.passwd
pw = Etc.passwd
pw.uid.should == expected.uid
end
it "should return nil once all entries are retrieved without a passed block" do
(1..@etc_passwd.length).each { Etc.passwd }
pw = Etc.passwd
pw.should be_nil
end
it "should loop through all the entries when a block is passed" do
expected = @etc_passwd.length
actual = 0
Etc.passwd { |pw| actual += 1 }
actual.should == expected
end
it "should reset the file for reading when a block is passed" do
expected = @etc_passwd.first
Etc.passwd
actual = nil
Etc.passwd { |pw| actual = pw if actual.nil? }
actual.uid.should == expected.uid
end
it "should reset the file for reading again after a block is passed" do
expected = @etc_passwd.at(1)
last = nil
Etc.passwd { |pw| last = pw unless pw.nil? }
actual = Etc.passwd
actual.uid.should == expected.uid
last.uid.should == @etc_passwd.last.uid
end
end
end
|
module ModelStack
module DSLMethod
class DefaultPrimaryKey
attr_accessor :generator
def self.handle(generator, default_primary_key)
dpk = default_primary_key.is_a?(Array) ? default_primary_key : [default_primary_key]
generator.default_primary_key = dpk
end
end
end
end |
# coding: utf-8
require 'homebus'
require 'homebus_app'
require 'mqtt'
require 'dotenv'
require 'net/http'
require 'json'
class AQIHomeBusApp < HomeBusApp
def initialize(options)
@options = options
super
end
def update_delay
15*60
end
def url
# https://docs.airnowapi.org/CurrentObservationsByZip/query
"http://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=#{options[:zipcode]}&distance=25&API_KEY=#{ENV['AIRNOW_API_KEY']}"
end
def setup!
Dotenv.load('.env')
end
def work!
uri = URI(url)
results = Net::HTTP.get(uri)
aqi = JSON.parse results, symbolize_names: true
pp aqi
answer = {
id: @uuid,
timestamp: Time.now.to_i,
observations: aqi.map { |o| { name: o[:ParameterName], aqi: o[:AQI], condition: o[:Category][:Name], condition_index: o[:Category][:Number] }}
}
pp answer
@mqtt.publish '/aqi',
JSON.generate(answer),
true
sleep update_delay
end
def manufacturer
'HomeBus'
end
def model
'Air Quality Index'
end
def friendly_name
'Air Quality Index'
end
def friendly_location
'Portland, OR'
end
def serial_number
''
end
def pin
''
end
def devices
[
{ friendly_name: 'Air Quality Index',
friendly_location: 'Portland, OR',
update_frequency: update_delay,
index: 0,
accuracy: 0,
precision: 0,
wo_topics: [ '/aqi' ],
ro_topics: [],
rw_topics: []
}
]
end
end
|
class AddUsernameLevelTotalPointToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :username, :string
add_column :users, :level, :integer, default: 0
add_column :users, :total_point, :integer, default: 0
end
end
|
class CreatePedidolineas < ActiveRecord::Migration
def change
create_table :pedidolineas do |t|
t.string :pedido_id
t.string :producto
t.string :product_value
t.string :product_id
t.float :precio
t.float :cantidad
t.float :total
t.string :imagen
t.timestamps null: false
end
end
end
|
require 'active_support/core_ext/array/wrap'
module Hydramata
module Works
# Responsible for validating an array of items using the underlying
# presence validator.
class PresenceOfEachValidator < SimpleDelegator
def initialize(options, collaborators = {})
@base_validator_builder = collaborators.fetch(:base_validator_builder) { default_base_validator_builder }
__setobj__(base_validator_builder.call(options))
end
attr_reader :base_validator_builder
private :base_validator_builder
def validate(record)
attributes.each do |attribute|
value = record.read_attribute_for_validation(attribute)
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
validate_each(record, attribute, value)
end
end
def validate_each(record, attribute, values)
wrapped_values = Array.wrap(values)
if wrapped_values.present?
wrapped_values.each do |value|
previous_error_count = (record.errors[attribute] || []).size
__getobj__.validate_each(record, attribute, value)
messages = record.errors[attribute]
if messages && messages.size > previous_error_count
record.errors.add(attribute, fixed_message(value, messages.pop))
end
end
else
__getobj__.validate_each(record, attribute, nil)
end
record.errors[attribute]
end
private
def fixed_message(value, message)
"value #{value.inspect} #{message}"
end
def default_base_validator_builder
require 'active_model/validations/presence'
ActiveModel::Validations::PresenceValidator.method(:new)
end
end
end
end
|
# -*- coding: utf-8 -*-
require 'ipscan'
require 'thor'
module IPScan
class CLI < Thor
desc "range [SCAN_RANGE]", "scan 192.168.1.0-254"
def range(range)
IPScan.scan(range)
end
end
end
|
class AdminsController < ApplicationController
def index
end
def create
admin = Admin.new(admin_params)
if admin.save
session[:admin_id] = admin.id
redirect_to '/dashboard'
else
flash[:register_errors] = admin.errors.full_messages
redirect_to '/'
end
end
private
def admin_params
params.require(:admin).permit(:username, :password, :password_confirmation)
end
end
|
# == Schema Information
#
# Table name: tag_topics
#
# id :integer not null, primary key
# topic :string not null
# created_at :datetime
# updated_at :datetime
#
class TagTopic < ActiveRecord::Base
validates_length_of :topic, :minimum => 2, :maximum => 1024, :allow_blank => false
has_many :taggings,
foreign_key: :tag_id,
primary_key: :id,
class_name: 'Tagging'
has_many :shortened_urls,
through: :taggings,
source: :shortened_url
end
|
class ChangeEstimateToNullTrueInTasks < ActiveRecord::Migration
def change
change_column :tasks, :estimate, :integer, :null => true, :default => 0
end
end
|
class ReportingCycle
attr_reader :report
def initialize(activity, financial_quarter, financial_year)
@activity = activity
@financial_quarter = financial_quarter
@financial_year = financial_year
@report = nil
end
def tick
approve_report
create_report
increment_quarter
end
private
def approve_report
@report&.update!(state: :approved)
end
def create_report
@report = Report.new(fund: @activity.associated_fund, organisation: @activity.organisation)
@report.created_at = FinancialQuarter.new(@financial_year.to_i, @financial_quarter.to_i).start_date
@report.financial_quarter = @financial_quarter
@report.financial_year = @financial_year
@report.state = :active
@report.save!
end
def increment_quarter
@financial_quarter += 1
if @financial_quarter > 4
@financial_year += 1
@financial_quarter = 1
end
end
end
|
class Attachment < ActiveRecord::Base
mount_uploader :file, AttachmentsUploader
belongs_to :origin, polymorphic: true
validates_presence_of :name, :file
validate :attachment_size_validation
scope :situation_true, -> { where(situation: true) }
private
def attachment_size_validation
errors[:file] << "should be less than 3MB" if file.size > 3.megabytes
end
end
|
class User < ApplicationRecord
def generate_token
self.update_attributes(token: Time.now.to_i)
end
def generate_reset_password_token
self.update_attributes(reset_password_token: self.email)
end
end
|
# encoding: UTF-8
class Submission < ApplicationRecord
include WithScoring
SUBMISSION_VARCHAR_COLUMNS = ['submission_status',
'irb_study_num',
'nucats_cru_contact_name',
'iacuc_study_num',
'effort_approver_username',
'department_administrator_username',
'submission_category',
'core_manager_username',
'notification_sent_to',
'type_of_equipment'].freeze
belongs_to :project
belongs_to :applicant, :class_name => 'User', :foreign_key => 'applicant_id'
belongs_to :submitter, :class_name => 'User', :foreign_key => 'created_id'
belongs_to :effort_approver, :class_name => 'User', :primary_key => 'username', :foreign_key => 'effort_approver_username'
belongs_to :core_manager, :class_name => 'User', :primary_key => 'username', :foreign_key => 'core_manager_username'
belongs_to :department_administrator, :class_name => 'User', :primary_key => 'username', :foreign_key => 'department_administrator_username'
belongs_to :applicant_biosketch_document, :class_name => 'FileDocument', :foreign_key => 'applicant_biosketch_document_id'
belongs_to :application_document, :class_name => 'FileDocument', :foreign_key => 'application_document_id'
belongs_to :budget_document, :class_name => 'FileDocument', :foreign_key => 'budget_document_id'
belongs_to :other_support_document, :class_name => 'FileDocument', :foreign_key => 'other_support_document_id'
belongs_to :document1, :class_name => 'FileDocument', :foreign_key => 'document1_id'
belongs_to :document2, :class_name => 'FileDocument', :foreign_key => 'document2_id'
belongs_to :document3, :class_name => 'FileDocument', :foreign_key => 'document3_id'
belongs_to :document4, :class_name => 'FileDocument', :foreign_key => 'document4_id'
belongs_to :supplemental_document, :class_name => 'FileDocument', :foreign_key => 'supplemental_document_id'
# TODO : determine how many supplemental documents are needed or add a join model to associate many documents
# (probably will continue to simply add belongs_to relationships to this model)
has_many :submission_reviews, :dependent => :destroy
has_many :reviewers, :through => :submission_reviews, :source => :user
has_many :key_personnel, :class_name => 'KeyPerson'
has_many :key_people, :through => :key_personnel, :source => :user
after_save :save_documents
accepts_nested_attributes_for :applicant
accepts_nested_attributes_for :key_personnel
attr_accessor :max_budget_request
attr_accessor :min_budget_request
# TODO: determine where submissions need to be ordered and add this at that point
# the ordering has been commented out because the joins method is not working
# which means that the order on 'users' is causing sql problems
# TODO: determine if the joins is necessary - this causes the record to be 'readonly' and
# will throw an ActiveRecord::ReadOnlyRecord error upon save
# default_scope joins([:applicant]) #.order('lower(users.last_name), submissions.project_id, lower(submissions.submission_title)')
scope :assigned_submissions, lambda { where('submission_reviews_count >= 2') }
scope :unassigned_submissions, lambda { where(:submission_reviews_count => 0) }
scope :recent, lambda { where('submissions.created_at > ?', 3.weeks.ago) }
scope :filled_submissions, lambda { |*args| where('submission_reviews_count >= :max_reviewers', { :max_reviewers => args.first || 2 }) }
scope :unfilled_submissions, lambda { |*args| where('submission_reviews_count < :max_reviewers', { :max_reviewers => args.first || 2 }) }
scope :associated, lambda { |*args|
includes('submission_reviews')
.where('(submissions.applicant_id = :id OR submissions.created_id = :id) AND
submissions.project_id IN (:projects)',
{ :projects => args[0], :id => args[1] })
}
scope :associated_with_user, lambda { |*args|
includes('submission_reviews')
.where('submissions.applicant_id = :id or submissions.created_id = :id',
{ :id => args.first })
.order('id asc')
}
before_validation :clean_params, :set_defaults
SUBMISSION_VARCHAR_COLUMNS.each do |column|
validates_length_of column.to_sym, :allow_blank => true, :maximum => 255, :too_long => 'is too long (maximum is 255 characters)'
end
validates_length_of :submission_title, :within => 6..200, :too_long => '--- pick a shorter title', :too_short => '--- pick a longer title'
validates_numericality_of :direct_project_cost, :greater_than => 1_000_000, :if => proc { |sub| (sub.direct_project_cost || 0) < sub.min_project_cost && ! sub.direct_project_cost.blank? }, :message => 'is too low'
validates_numericality_of :direct_project_cost, :less_than => 1000, :if => proc { |sub| (sub.direct_project_cost || 0) > sub.max_project_cost }, :message => 'is too high'
# Various values to be set for the `submission_status` attributes
# presumably depends on the state of the whole of the associated submission_reviews
PENDING = 'Pending'
REVIEWED = 'Reviewed'
DENIED = 'Denied'
AWARDED = 'Awarded'
COMPLETED = 'Completed'
STATUSES = [PENDING, REVIEWED, DENIED, AWARDED, COMPLETED]
EQUIPMENT_TYPES = ['New', 'ReLODE']
validates :submission_status, inclusion: { in: STATUSES }
validates :type_of_equipment, inclusion: { in: EQUIPMENT_TYPES }, allow_blank: true
def overall_score_average
calculate_average submission_reviews.map(&:overall_score).reject{ |score| score.to_i.zero? }
end
def overall_score_string
return '-' if unreviewed?
("%.2f" % overall_score_average) + " (#{submission_reviews.map(&:overall_score).join(',')})"
end
def composite_score
calculate_average submission_reviews.flat_map(&:scores).reject(&:zero?)
end
def composite_score_string
composite = composite_score
return '-' if composite.zero?
"%.2f" % composite
end
def max_project_cost
max_budget_request || self.project.max_budget_request || 50_000
end
def min_project_cost
min_budget_request || self.project.min_budget_request || 1000
end
def status
return 'Incomplete' if project.blank? || applicant.blank?
return 'Incomplete' if project.show_project_cost && direct_project_cost.blank?
return 'Incomplete' if project.show_effort_approver && project.require_effort_approver && effort_approver_username.blank?
return 'Incomplete' if project.show_department_administrator && department_administrator_username.blank?
return 'Incomplete' if project.show_core_manager && core_manager_username.blank?
return 'Incomplete' if project.show_abstract_field && abstract.blank?
return 'Incomplete' if project.show_manage_other_support && other_support_document_id.blank?
return 'Incomplete' if project.show_document1 && project.document1_required && document1_id.blank?
return 'Incomplete' if project.show_document2 && project.document2_required && document2_id.blank?
return 'Incomplete' if project.show_document3 && project.document3_required && document3_id.blank?
return 'Incomplete' if project.show_document4 && project.document4_required && document4_id.blank?
return 'Incomplete' if project.show_budget_form && budget_document_id.blank?
return 'Incomplete' if project.show_manage_biosketches && applicant_biosketch_document_id.blank?
return 'Incomplete' if project.show_application_doc && application_document_id.blank?
'Complete'
end
def is_complete?
status == 'Complete'
end
alias :complete? :is_complete?
def is_open?
project.is_open?
end
alias :is_open_submission? :is_open?
alias :open? :is_open?
def is_modifiable?
project.is_modifiable?
end
alias :modifiable? :is_modifiable?
def is_reviewable?
project.is_reviewable?
end
alias :reviewable? :is_reviewable?
def key_personnel_names
key_personnel.map { |k| k.name || k.user.name }
end
def key_personnel_emails
key_personnel.map { |k| k.email || k.user.email }
end
def status_reason
out = []
return ['Project undefined'] if project.blank? || applicant.blank?
out << 'Project cost is undefined. Please enter a project cost. ' if project.show_project_cost && direct_project_cost.blank?
out << "#{project.effort_approver_title} unset. Complete in title page. " if project.show_effort_approver && project.require_effort_approver && effort_approver_username.blank?
out << "#{project.department_administrator_title} unset. Complete in title page. " if project.show_department_administrator && department_administrator_username.blank?
out << 'Core Manager unset. Complete in title page. ' if project.show_core_manager && core_manager_username.blank?
out << 'Abstract needs to be completed. Complete in title page. ' if project.show_abstract_field && abstract.blank?
out << 'Manage Other Support document needs to be uploaded. ' if project.show_manage_other_support && other_support_document_id.blank?
out << "#{project.document1_name} document needs to be uploaded. " if project.show_document1 && project.document1_required && document1_id.blank?
out << "#{project.document1_name} document is absent but not required. " if project.show_document1 && document1_id.blank?
out << "#{project.document2_name} document needs to be uploaded. " if project.show_document2 && project.document2_required && document2_id.blank?
out << "#{project.document2_name} document is absent but not required. " if project.show_document2 && document2_id.blank?
out << "#{project.document3_name} document needs to be uploaded. " if project.show_document3 && project.document3_required && document3_id.blank?
out << "#{project.document3_name} document is absent but not required. " if project.show_document3 && document3_id.blank?
out << "#{project.document4_name} document needs to be uploaded. " if project.show_document4 && project.document4_required && document4_id.blank?
out << "#{project.document4_name} document is absent but not required. " if project.show_document4 && document4_id.blank?
out << 'Budget document needs to be uploaded. ' if project.show_budget_form && budget_document_id.blank?
out << 'PI biosketch needs to be uploaded. ' if project.show_manage_biosketches && applicant_biosketch_document_id.blank?
out << 'Application document needs to be uploaded. ' if project.show_application_doc && application_document_id.blank?
out << 'Application has been fully completed!' if out.blank?
out.compact
end
def self.approved_submissions(username)
self.where('effort_approver_username = :username', { username: username }).all
end
def program_name
project.try(:program).try(:program_name)
end
# this will update the applicant's personal biosketch and then add to the submission
def uploaded_biosketch=(data_field)
unless data_field.blank?
self.applicant_biosketch_document = FileDocument.new if applicant_biosketch_document.nil?
self.applicant_biosketch_document.uploaded_file = data_field
# do not update the applicant's biosketch
# self.applicant.uploaded_biosketch = data_field
end
end
# this defines the connection between the model attribute exposed to the form (uploaded_budget)
# and the file_document model
def uploaded_budget=(data_field)
self.budget_document = FileDocument.new if self.budget_document.nil?
self.budget_document.uploaded_file = data_field unless data_field.blank?
end
def uploaded_other_support=(data_field)
self.other_support_document = FileDocument.new if self.other_support_document.nil?
self.other_support_document.uploaded_file = data_field unless data_field.blank?
end
def uploaded_document1=(data_field)
self.document1 = FileDocument.new if self.document1.nil?
self.document1.uploaded_file = data_field unless data_field.blank?
end
def uploaded_document2=(data_field)
self.document2 = FileDocument.new if self.document2.nil?
self.document2.uploaded_file = data_field unless data_field.blank?
end
def uploaded_document3=(data_field)
self.document3 = FileDocument.new if self.document3.nil?
self.document3.uploaded_file = data_field unless data_field.blank?
end
def uploaded_document4=(data_field)
self.document4 = FileDocument.new if self.document4.nil?
self.document4.uploaded_file = data_field unless data_field.blank?
end
def uploaded_supplemental_document=(data_field)
self.supplemental_document = FileDocument.new if self.supplemental_document.nil?
self.supplemental_document.uploaded_file = data_field unless data_field.blank?
end
# this defines the connection between the model attribute exposed to the form (uploaded_application)
# and the storage fields for the file
def uploaded_application=(data_field)
self.application_document = FileDocument.new if self.application_document.nil?
self.application_document.uploaded_file = data_field unless data_field.blank?
end
def clean_params
# need the before_type_cast or else Rails 2.3 truncates after any comma. strange
txt = self.direct_project_cost_before_type_cast
return if txt.blank?
txt = txt.to_s
txt = txt.split('.')[0]
txt = txt.split(',').join
txt = txt.sub(/\D+(\d*)/, '\1')
self.direct_project_cost = txt
end
def set_defaults
self.submission_status = PENDING if self.submission_status.blank?
end
def save_documents
do_save(self.budget_document, :budget_document)
do_save(self.other_support_document, :other_support_document)
do_save(self.document1, :document1)
do_save(self.document2, :document2)
do_save(self.document3, :document3)
do_save(self.document4, :document4)
do_save(self.application_document, :application_document)
set_applicant_biosketch
do_save(self.applicant_biosketch_document, :applicant_biosketch_document)
do_save(self.supplemental_document, :supplemental_document)
end
def set_applicant_biosketch
unless self.applicant.blank? || self.applicant.biosketch.blank? # self.applicant.biosketch_document_id.blank?
if self.applicant_biosketch_document_id.blank?
# create a new copy of the file associated only with the submission
unless self.applicant.biosketch.file.blank?
self.applicant_biosketch_document = FileDocument.new(file: self.applicant.biosketch.file)
self.applicant_biosketch_document.file_content_type = self.applicant.biosketch.file_content_type
self.applicant_biosketch_document.file_file_name = self.applicant.biosketch.file_file_name
self.applicant_biosketch_document.last_updated_at = self.applicant.biosketch.updated_at
self.applicant_biosketch_document.save
end
begin
logger.error "saving biosketch: updated_at: #{self.applicant_biosketch_document.last_updated_at} was #{self.applicant.biosketch.updated_at}"
rescue
puts 'error logging error when saving biosketch'
end
self.save
end
end
end
def do_save(model, name)
if !model.nil? && model.changed?
if model.errors.blank?
model.save
else
msg = "unable to save #{name.to_s.titleize}: #{model.errors.full_messages.join('; ')}"
self.errors.add(name.to_sym, msg)
end
end
end
def unreviewed?
submission_reviews.blank?
end
end
|
# Helper Method
def display_board(board)
square_size = Math.sqrt(board.size)
if !(square_size % 1 > 0)
n_lines = board.size / square_size
row_n = 0
rows = board.each_slice(square_size).to_a
while row_n < square_size
space = 0
row = rows[row_n]
write_line(row)
if row_n < (square_size - 1)
write_hrule(square_size)
end
row_n += 1
end
else
puts '!! the board given is not squared !!'
end
end
def write_line(array)
place_i = 0
while place_i < array.size
symbol = array[place_i]
if !(symbol == 'X' || symbol == 'O' || symbol == ' ')
symbol = ' '
end
print " #{symbol} "
if place_i < (array.size - 1)
print '|'
end
place_i += 1
end
puts ''
end
def write_hrule(spaces)
n = (spaces * 4) - 1
i = 0
while i < n
print '-'
i += 1
end
puts ''
end
def valid_move?(board, index)
(!position_taken?(board, index)) && index.between?(0, board.size - 1)
end
def input_to_index(user_input)
user_input.to_i - 1
end
def move(board, index, current_player)
board[index] = current_player
end
def position_taken?(board, location)
board[location] != " "
end
def turn(board)
puts 'Please enter 1-9:'
index = input_to_index(gets.strip)
if valid_move?(board, index)
move(board, index, current_player(board))
display_board(board)
else
turn(board)
end
end
def turn_count(board)
counter = 0
board.each do |place|
if place == 'X' || place == 'O'
counter += 1
end
end
counter
end
def current_player(board)
turn_count(board).even? ? 'X' : 'O'
end
def position_taken?(board, index)
!(board[index].nil? || board[index] == " ")
end
def won?(board)
WIN_COMBINATIONS.find do |win|
win.all? {|position| board[position] == 'X'} || win.all? {|position| board[position] == 'O'}
end
end
def full?(board)
board.none? {|place| place == ' ' || place == '' || place == nil}
end
def draw?(board)
won?(board) || !full?(board) ? false : true
end
def over?(board)
won?(board) || full?(board) ? true : false
end
def winner(board)
won?(board) ? board[won?(board)[0]] : nil
end
def play(board)
while !over?(board) && !draw?(board)
turn(board)
end
if winner(board)
puts "Congratulations #{winner(board)}!"
else
puts "Cat's Game!"
end
end
# Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [
[0,1,2], # Top row
[3,4,5], # Middle row
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
] |
class User < ActiveRecord::Base
has_many :reviews, -> { order 'created_at DESC' }
has_many :queue_items, -> { order('position') }
has_many :relationships
has_many :followings, through: :relationships
has_many :follower_relationships, class_name: "Relationship", foreign_key: "following_id"
has_many :followers, through: :follower_relationships, source: :user
has_many :invitations
has_secure_password validations: false
validates_presence_of :email, :password, :full_name
validates_uniqueness_of :email
def has_queue_item(queue_item)
queue_items.include?(queue_item)
end
def next_position_available
queue_items.count + 1
end
def already_queued?(video)
queue_items.map(&:video).include?(video)
end
def normalize_queue_item_positions
queue_items.each_with_index do |queue_item, index|
queue_item.update_attributes(position: index + 1)
end
end
end |
def report(grades)
raise 'Please provide valid grades' if grades == ''
g_count = 0
r_count = 0
a_count = 0
uncounted = 0
result = []
grades_arr = grades.split(',')
grades_arr.each do |grade|
if grade == 'Green'
g_count += 1
elsif grade == 'Red'
r_count += 1
elsif grade == 'Amber'
a_count += 1
else
uncounted += 1
end
end
result << "Green: #{g_count}" if g_count != 0
result << "Amber: #{a_count}" if a_count != 0
result << "Red: #{r_count}" if r_count != 0
result << "Uncounted: #{uncounted}" if uncounted != 0
result.join("\n")
end
|
class DeviseCreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
t.string :email, null: false, default: ""
t.string :username, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
t.string :reset_password_token
t.datetime :reset_password_sent_at
t.datetime :remember_created_at
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :name, null: false
t.string :country, null: false
t.string :company_name, null: false
t.decimal :profit_share, null: false, precision: 4, scale: 1
t.string :currency, null: false, default: "USD"
t.string :language, null: false, default: "en"
t.integer :zip
t.decimal :net_income, precision: 10, scale: 2
t.string :street_name
t.boolean :admin, null: false, default: false
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :username, unique: true
add_index :users, :reset_password_token, unique: true
add_index :users, :confirmation_token, unique: true
end
end
|
class Pet < ApplicationRecord
belongs_to :user
after_destroy :remove_id_directory
mount_uploader :image, PetUploader
private
def remove_id_directory
# clean up image directory after a destroy
FileUtils.remove_dir("uploads/pets/#{self.id}", :force => true)
end
end |
class MessageMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.message_mailer.contact.subject
#
def contact(message)
@greeting = "Hi"
#defines all the mail for the message to be sent to the email address through contact.html.erb
@name = message.name
@email = message.email
@description = message.description
@duedate = message.duedate
@budget = message.budget
mail to: "ontrackprogramming@gmail.com", from: message.email
end
end
|
require 'rubygems'
require 'gosu'
require 'socket'
require_relative 'position'
require_relative 'player'
require_relative 'passive_objects'
$winW, $winH = 600, 400
$rop = 20
class TankDuel < Gosu::Window
attr_accessor :listenThread, :serverSocket, :id , :player, :enemy, :blocks, :running, :font
def initialize(width, height)
super(width,height,false)
self.caption = "TankDuel"
@player=Player.new()
@enemy=Enemy.new()
@blocks=[]
@mousep=mousepos
@running=true
@font=Gosu::Font.new(self, "Arial", 24)
end
def self.create(width,height,serverSocket, player_data)
game = TankDuel.new($winW, $winH);
game.listenThread = Thread.fork {game.listen()}
game.serverSocket = serverSocket
game.id,x,y=player_data.split(',').map{|e| e.to_f}
game.id=game.id.to_i
game.player.setP Position.new(x,y)
game.player.setV Position.new(0.0,0.0)
game.enemy.setP Position.new(-1000,-1000)
return game
end
def listen
while info = @serverSocket.gets.chomp.split(",")
obj_type=info[0].to_i
if obj_type==1
x,y,life=info[1..3].map(&:to_f)
@enemy.setP Position.new(x,y)
@enemy.life=life
elsif obj_type==2
x,y,vx,vy=info[1..4].map(&:to_f)
block=Block.new Position.new(x,y), Position.new(vx,vy), true # <<<< from_enemy
@blocks<<block
end
end
end
def draw
@player.draw(self)
@enemy.draw(self)
draw_line(@player.pos.x,@player.pos.y,0xffffffff,@mousep.x,@mousep.y,0xffffffff,3)
if(!@blocks.nil?)
@blocks.each{|b| b.draw(self)}
end
draw_rect(0,$winH*0.96,$winW*0.5*@player.life/100.0,$winH,0xff_3344CC,5)
draw_rect($winW*(1.0-0.5*@enemy.life/100.0),$winH*0.96,$winW,$winH,0xff_7711CC,5)
if !running
if(@player.life<=0 and @enemy.life<=0)
text="Empate"
elsif @player.life<=0
text="Derrota"
else
text="Vitoria"
end
@font.draw(text, $winW*0.5, $winH*0.90, 6, scale_x = 1, scale_y = 1, color = 0xff_ffffff)
end
end
def draw_rect(xo,yo,xf,yf,c=0xffffffff,z=0)
draw_quad(xo,yo,c,xf,yo,c,xf,yf,c,xo,yf,c,z)
end
def update
if (@player.life <=0 or @enemy.life <=0) and @running
@running = false
@serverSocket.puts "0"
end
@player.update if running
if(!@blocks.nil?)
@blocks.each{|b| b.update; }
@blocks.each do |b|
check_X = b.pos.x.between?(@player.pos.x-@player.l,@player.pos.x+@player.l)
check_Y = b.pos.y.between?(@player.pos.y-@player.l,@player.pos.y+@player.l)
check_eX = b.pos.x.between?(@enemy.pos.x-@enemy.l,@enemy.pos.x+@enemy.l)
check_eY = b.pos.y.between?(@enemy.pos.y-@enemy.l,@enemy.pos.y+@enemy.l)
if (check_eX and check_eY and not b.from_enemy)
b.for_delete=true
end
if (check_X and check_Y and b.from_enemy)
b.for_delete=true
@player.life=[@player.life-@player.dmg,0].max
end
end
@blocks.select!{|b| !b.for_delete}
end
sendMe
@mousep=mousepos
end
def sendMe
@serverSocket.puts "1,#{@player.pos.x},#{@player.pos.y},#{@player.life}"
end
def sendBlock(block)
@serverSocket.puts "2,#{block.pos.x},#{block.pos.y},#{block.vel.x},#{block.vel.y}"
end
def shoot
shoot_vel=Block::CONST_VEL
dif = Position.sub(mousepos,@player.pos)
dif = Position.mult(dif,shoot_vel/Position.modulo(dif))
block=Block.new(@player.pos,dif)
sendBlock(block)
@blocks<<block
end
def button_down(id)
if(id == Gosu::MsLeft and @running)
shoot
end
if(id == Gosu::KbQ)
@player.life=0
@running=false
@serverSocket.puts "0"
close!
end
@player.button_down(id)
end
def mousepos
return Position.new(mouse_x.to_f,mouse_y.to_f)
end
def button_up(id)
@player.button_up(id)
end
def close
!@running
end
end
print "Endereco Ip = "
ip=gets.chomp
serverSocket = TCPSocket.new (ip.length<7) ? ('127.0.0.1'):(ip), 2000
info=serverSocket.gets
flag, player_data=info.split(" ")
if(!flag.eql?("error"))
game = TankDuel.create($winW, $winH, serverSocket, player_data);
game.show()
end
serverSocket.close |
require 'pry'
class ApiController < ActionController::Base
def getPart
part = Part.where(:name => params[:part_name]).first
if part.nil?
render :text => "Part: #{params[:part_name]} does not exist.", status: 400
return
end
render :json => part, status: 200
end
def getPartDependencies
version = params[:version] || part.version
queue = [[params[:part_name], version]]
visited = Hash.new
allDep = Hash.new
visited[params[:part_name]] = Array.new
visited[params[:part_name]].push(version)
loop do
curDep = queue.pop
break if curDep == nil
partObj = Hash.new
partObj['name'] = curDep[0]
partObj['version'] = curDep[1]
dependencies = Dependency.where(:part_name => curDep[0], :part_version => curDep[1])
depList = Hash.new
dependencies.each do |addDep|
depName, depVersion = addDep.dependency_name, addDep.dependency_version.split[1]
if !visited.has_key?(depName) || !visited[depName].include?(depVersion)
queue.push([depName, depVersion])
visited[depName] = Array.new if !visited.has_key?(depName)
visited[depName].push(depVersion)
end
depList[depName] = addDep.dependency_version
end
partObj['dependencies'] = depList
allDep[curDep[0]] = [] if !allDep.has_key?(curDep[0])
allDep[curDep[0]].push(partObj)
end
render :json => allDep, status: 200
end
def upload
part = Part.where(:name => params[:name]).first
if part.nil?
Part.create(:name => params[:name], :description => params[:description], :version => params[:version],
:authors => params[:authors], :email => params[:email], :homepage => params[:homepage])
Version.create(:part_name => params[:name], :version => params[:version])
if !params[:dependencies].nil? && !params[:dependencies].empty?
params[:dependencies].each do |dependency_name, dependency_version|
Dependency.create(:part_name => params[:name], :part_version => params[:version],
:dependency_name => dependency_name, :dependency_version => dependency_version)
end
end
render :text => "Successfully created css part: #{params[:name]}", status: 200
else
if Gem::Version.new(params[:version]) > Gem::Version.new(part.version)
Version.create(:part_name => params[:name], :version => params[:version])
part.update_attributes(:version => params[:version])
if !params[:dependencies].nil? && !params[:dependencies].empty?
params[:dependencies].each do |dependency_name, dependency_version|
Dependency.create(:part_name => params[:name], :part_version => params[:version],
:dependency_name => dependency_name, :dependency_version => dependency_version)
end
end
render :text => "Successfully updated css part: #{part.name} to version: #{params[:version]}", status: 200
else
render :text => "Specified version #{params[:version]} not greater than latest version: #{part.version}", status: 400
end
end
end
# TODO: check that dependency follows format (i.e. >= 1.0.0)
def validateDependencies
params[:dependencies].split("&").each do |dependency|
dependency_values = dependency.split("=")
versions = Version.where(:part_name => dependency_values[0])
if versions.empty?
render :text => "Part: #{dependency_values[0]} does not exist.", status: 400
return
else
part = versions.where(:version => dependency_values[1]).first
if part.nil?
render :text => "Part: #{dependency_values[0]} with version: #{dependency_values[1]} does not exist", status: 400
return
end
end
end
render :nothing => true, status: 200
end
end
|
module StarWars
class ImportStarships < Base
def call
(1..).each do |page|
response = get_starships(page)
break unless response.found?
import_starships(response)
end
end
private
def get_starships(page)
api.get_starships(page: page)
end
def import_starships(response)
starships_attributes = []
response.data.results.each do |result|
starships_attributes << slice_attributes(result)
end
Starship.create!(starships_attributes)
end
def slice_attributes(result)
result.to_h.slice(
:name,
:model,
:manufacturer,
:cost_in_credits,
:length,
:max_atmosphering_speed,
:crew,
:passengers,
:cargo_capacity,
:consumables,
:hyperdrive_rating,
:mglt,
:starship_class,
:url
)
end
end
end
|
class ApplicationController < ActionController::Base
before_action :basic_auth if Rails.env.production?
before_action :configure_permitted_parameters, if: :devise_controller?
# ページネーションの個数
SHOP_PER = 6
ITME_PER = 5
private
def configure_permitted_parameters
# 新規登録時にnameの取得を許可
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
# 編集時にnameの取得を許可
devise_parameter_sanitizer.permit(:account_update, keys: [:name])
end
def basic_auth
authenticate_or_request_with_http_basic do |username, password|
username == ENV['BASIC_AUTH_USER'] &&
password == ENV['BASIC_AUTH_PASSWORD'] # 環境変数を読み込む記述に変更
end
end
def authenticate_user_admin!
redirect_to root_path unless user_signed_in? || admin_signed_in?
end
end
|
class AddFulltextIndicesToPlaces < ActiveRecord::Migration
def change
add_index :places, :name
add_index :places, :description
add_index :places, :street
add_index :places, :city
add_index :places, :zip_code
add_index :places, :url
add_index :places, :twitter_name
end
end
|
require 'digest/sha2'
class User < ActiveRecord::Base
after_create :create_a_default_phone_book, :if => :'is_native != false'
# Sync other nodes when this is a cluster.
#
after_create :create_on_other_gs_nodes
after_create :create_default_group_memberships
after_destroy :destroy_on_other_gs_nodes
after_update :update_on_other_gs_nodes
attr_accessible :user_name, :email, :password, :password_confirmation,
:first_name, :middle_name, :last_name, :male,
:image, :current_tenant_id, :language_id,
:new_pin, :new_pin_confirmation, :send_voicemail_as_email_attachment,
:importer_checksum, :gs_node_id
attr_accessor :new_pin, :new_pin_confirmation
before_validation {
# If the PIN and PIN confirmation are left blank in the GUI
# then the user/admin does not want to change the PIN.
if self.new_pin.blank? && self.new_pin_confirmation.blank?
self.new_pin = nil
self.new_pin_confirmation = nil
end
}
validates_length_of [:new_pin, :new_pin_confirmation],
:minimum => (GsParameter.get('MINIMUM_PIN_LENGTH').nil? ? 4 : GsParameter.get('MINIMUM_PIN_LENGTH')),
:maximum => (GsParameter.get('MAXIMUM_PIN_LENGTH').nil? ? 10 : GsParameter.get('MAXIMUM_PIN_LENGTH')),
:allow_blank => true, :allow_nil => true
validates_format_of [:new_pin, :new_pin_confirmation],
:with => /^[0-9]+$/,
:allow_blank => true, :allow_nil => true,
:message => "must be numeric."
validates_confirmation_of :new_pin, :if => :'pin_changed?'
before_save :hash_new_pin, :if => :'pin_changed?'
has_secure_password
validates_presence_of :password, :password_confirmation, :on => :create, :if => :'password_digest.blank?'
validates_presence_of :email
validates_presence_of :last_name
validates_presence_of :first_name
validates_presence_of :user_name
validates_uniqueness_of :user_name, :case_sensitive => false
validates_uniqueness_of :email, :allow_nil => true, :case_sensitive => false
validates_length_of :user_name, :within => 0..50
validates_presence_of :uuid
validates_uniqueness_of :uuid
# Associations:
#
has_many :tenant_memberships, :dependent => :destroy
has_many :tenants, :through => :tenant_memberships
has_many :user_group_memberships, :dependent => :destroy, :uniq => true
has_many :user_groups, :through => :user_group_memberships
has_many :phone_books, :as => :phone_bookable, :dependent => :destroy
has_many :phone_book_entries, :through => :phone_books
has_many :phones, :as => :phoneable
has_many :sip_accounts, :as => :sip_accountable, :dependent => :destroy
has_many :phone_numbers, :through => :sip_accounts
has_many :conferences, :as => :conferenceable, :dependent => :destroy
has_many :fax_accounts, :as => :fax_accountable, :dependent => :destroy
has_many :auto_destroy_access_authorization_phone_numbers, :class_name => 'PhoneNumber', :foreign_key => 'access_authorization_user_id', :dependent => :destroy
belongs_to :current_tenant, :class_name => 'Tenant'
validates_presence_of :current_tenant, :if => Proc.new{ |user| user.current_tenant_id }
belongs_to :language
validates_presence_of :language_id
validates_presence_of :language
validate :current_tenant_is_included_in_tenants, :if => Proc.new{ |user| user.current_tenant_id }
belongs_to :gs_node
has_many :parking_stalls, :as => :parking_stallable, :dependent => :destroy
has_many :group_memberships, :as => :item, :dependent => :destroy, :uniq => true
has_many :groups, :through => :group_memberships
has_many :switchboards, :dependent => :destroy
has_many :voicemail_accounts, :as => :voicemail_accountable, :dependent => :destroy
has_many :generic_files, :as => :owner, :dependent => :destroy
# Avatar like photo
mount_uploader :image, ImageUploader
before_save :format_email_and_user_name
before_destroy :destroy_or_logout_phones
after_save :become_a_member_of_default_user_groups
after_save :change_language_of_child_objects
def destroy
clean_whitelist_entries
super
end
def pin_changed?
! @new_pin.blank?
end
def sip_domain
if self.current_tenant
return self.current_tenant.sip_domain
end
return nil
end
def to_s
max_first_name_length = 10
max_last_name_length = 20
if self.first_name.blank?
self.last_name.strip
else
"#{self.first_name.strip} #{self.last_name.strip}"
end
end
def self.find_user_by_phone_number( number, tenant )
tenant = Tenant.where( :id => tenant.id ).first
if tenant
if tenant.sip_domain
user = tenant.sip_domain.sip_accounts.
joins(:phone_numbers).
where(:phone_numbers => { :number => number }).
first.
try(:sip_accountable)
if user.class.name == 'User'
return user
end
end
end
return nil
end
def authenticate_by_pin?( entered_pin )
self.pin_hash == Digest::SHA2.hexdigest( "#{self.pin_salt}#{entered_pin}" )
end
def admin?
self.user_groups.include?(UserGroup.find(2))
end
def sim_cards
SimCard.where(:sip_account_id => self.sip_account_ids)
end
private
def hash_new_pin
if @new_pin \
&& @new_pin_confirmation \
&& @new_pin_confirmation == @new_pin
self.pin_salt = SecureRandom.base64(8)
self.pin_hash = Digest::SHA2.hexdigest(self.pin_salt + @new_pin)
end
end
def format_email_and_user_name
self.email = self.email.downcase.strip if !self.email.blank?
self.user_name = self.user_name.downcase.strip if !self.user_name.blank?
end
# Create a personal phone book for this user:
def create_a_default_phone_book
private_phone_book = self.phone_books.find_or_create_by_name_and_description(
I18n.t('phone_books.private_phone_book.name', :resource => self.to_s),
I18n.t('phone_books.private_phone_book.description')
)
end
# Check if a current_tenant_id is possible tenant_membership wise.
def current_tenant_is_included_in_tenants
if !self.tenants.include?(Tenant.find(self.current_tenant_id))
errors.add(:current_tenant_id, "is not possible (no TenantMembership)")
end
end
# Make sure that there are no whitelist entries with phone_numbers of
# a just destroyed user.
#
def clean_whitelist_entries
phone_numbers = PhoneNumber.where( :phone_numberable_type => 'Whitelist').
where( :number => self.phone_numbers.map{ |x| x.number } )
phone_numbers.each do |phone_number|
if phone_number.phone_numberable.whitelistable.class == Callthrough
whitelist = Whitelist.find(phone_number.phone_numberable)
phone_number.destroy
if whitelist.phone_numbers.count == 0
# Very lickly that this Whitelist doesn't make sense any more.
#
whitelist.destroy
end
end
end
end
# Make sure that a tenant phone goes back to the tenant and doesn't
# get deleted with this user.
#
def destroy_or_logout_phones
self.phones.each do |phone|
if phone.sip_accounts.where(:sip_accountable_type => 'Tenant').count > 0
phone.user_logout
else
phone.destroy
end
phone.resync
end
end
# Normaly a new user should become a member of default user groups.
#
def become_a_member_of_default_user_groups
UserGroup.where(:id => GsParameter.get('DEFAULT_USER_GROUPS_IDS')).each do |user_group|
user_group.user_group_memberships.create(:user_id => self.id)
end
end
def create_default_group_memberships
templates = GsParameter.get('User', 'group', 'default')
if templates.class == Array
templates.each do |group_name|
group = Group.where(:name => group_name).first
if group
self.group_memberships.create(:group_id => group.id)
end
end
end
end
def change_language_of_child_objects
if !self.language_id_changed?
return nil
end
code = self.language.code
self.sip_accounts.each do |sip_account|
sip_account.update_attributes(:language_code => code)
end
end
end
|
class CircularBuffer
class BufferEmptyException < StandardError; end
class BufferFullException < StandardError; end
def initialize(size)
@buffer = Array.new(size, nil)
end
def read
if buffer_empty?
raise BufferEmptyException
else
result = @buffer[0]
move_buffer_over
@buffer[-1] = nil
result
end
end
def write(input)
if buffer_has_empty_slot?
if !input.nil?
@buffer.each_with_index do |slot, index|
if slot.nil?
@buffer[index] = input
break
end
end
end
else
raise BufferFullException
end
end
def write!(input)
if buffer_has_empty_slot?
write(input)
else
if !input.nil?
move_buffer_over
@buffer[-1] = input
end
end
end
def clear
@buffer.each_with_index do |_, index|
@buffer[index] = nil
end
end
private
def buffer_empty?
@buffer.all? { |slot| slot.nil? }
end
def buffer_has_empty_slot?
@buffer.any? { |slot| slot.nil? }
end
def move_buffer_over
@buffer.each_with_index do |slot, index|
@buffer[index] = @buffer[index + 1] unless index == @buffer.size - 1
end
end
end
|
class InterestListWorksController < ApplicationController
load_and_authorize_resource
# GET /interest_list_works
def index
render json: @interest_list_works
end
# GET /interest_list_works/1
def show
render json: @interest_list_work
end
# POST /interest_list_works
def create
if @interest_list_work.save
render json: @interest_list_work, status: :created, location: @interest_list_work
else
render json: @interest_list_work.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /interest_list_works/1
def update
if @interest_list_work.update(interest_list_work_params)
render json: @interest_list_work
else
render json: @interest_list_work.errors, status: :unprocessable_entity
end
end
# DELETE /interest_list_works/1
def destroy
@interest_list_work.destroy
end
private
def interest_list_work_params
params.require(:interest_list_work).permit(:interest_list_id, :work_id)
end
end
|
# frozen_string_literal: true
module PgTagsOn
class PredicateHandler
# Base predicate handler
class BaseHandler
include PgTagsOn::ActiveRecord::Arel
OPERATORS = {
eq: :eq,
all: '@>',
any: '&&',
in: '<@',
one: '@>'
}.freeze
def initialize(attribute, query, predicate_builder)
@attribute = attribute
@query = query
@predicate_builder = predicate_builder
end
def call
raise 'Invalid predicate' unless OPERATORS.keys.include?(predicate)
if operator.is_a?(Symbol)
send("#{operator}_node")
else
::Arel::Nodes::InfixOperation.new(operator, left, right)
end
end
def predicate
@predicate ||= query.predicate.to_sym
end
def operator
@operator ||= self.class.const_get('OPERATORS').fetch(predicate)
end
def eq_node
node = ::Arel::Nodes::InfixOperation.new(self.class::OPERATORS[:all], left, right)
node.and(arel_function('array_length', attribute, 1).eq(value.size))
end
def left
attribute
end
def right
bind_node
end
def bind_node
query_attr = ::ActiveRecord::Relation::QueryAttribute.new(attribute_name, value, cast_type)
Arel::Nodes::BindParam.new(query_attr)
end
def value
@value ||= Array.wrap(query.value)
end
def klass
@klass ||= predicate_builder.send(:table).send(:klass)
end
def table_name
@table_name ||= attribute.relation.name
end
def attribute_name
attribute.name.to_s
end
# Returns Type object
def cast_type
@cast_type ||= klass.type_for_attribute(attribute_name)
end
def settings
@settings ||= (klass.pg_tags_on_options_for(attribute_name) || {}).symbolize_keys
end
private
attr_reader :attribute, :query, :predicate_builder
end
end
end
|
class ControlsController < ApplicationController
before_action :logged_in_user, only: [:create,:update,:destroy]
before_action :correct_user, only: [:create,:update,:destroy]
def create
@controller = Control.create(controller_params)
@controller.app_id = @app.id
@controller.name = @controller.name.gsub(" ", "_").gsub("-","_").camelize
@model = Model.find(1) # replace this line
# add controller boolean for user auth and special controllers
# oh god this controller is going to be very fat...
# this kinda works
if @controller.name.downcase == 'user'
# create models and controller
@controller.program = """class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.create(user_params)
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
else
redirect_to #{@controller.redirect}
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to #{@controller.redirect}
end
private
def correct_user
unless current_user == @user
redirect_to @controller.redirect
end
end
"""
elsif @controller.name.downcase == 'product'
# create models and controller
elsif @controller.name.downcase == 'marketplace'
# create models and controller
elsif @controller.name.downcase == 'post'
# create models and controller
elsif @controller.name.downcase == 'post picture'
# create models and controller
elsif @controller.name.downcase == 'product picture'
# create models and controller
else
@controller.program = """class #{@controller.name.pluralize.camelize}Controller < ApplicationController
#{"""def new
#{@controller.name.singularize} = #{@controller.name.singularize.titleize}.new
end""" if @controller.new_action}
#{"""def create
#{@controller.name.singularize} = #{@controller.name.singularize.titleize}.create(controller_params)
if @controller.save
redirect_to #{@controller.redirect}
else
render 'new'
end
end""" if @controller.create_action}
#{"""def edit
#{@controller.name.singularize} = #{@controller.name.singularize.titleize}.find(params[:id])
end""" if @controller.edit_action}
#{"""def show
#{@controller.name.singularize} = #{@controller.name.singularize.titleize}.find(params[:id])
end""" if @controller.show_action}
#{"""def update
#{@controller.name.singularize} = #{@controller.name.singularize.titleize}.find(params[:id])
if #{@controller.name.singularize}.update_attributes(controller_params)
redirect_to #{@controller.redirect}
else
render 'edit'
end
end""" if @controller.update_action}
#{"""def destroy
#{@controller.name.singularize} = #{@controller.name.singularize.titleize}.find(params[:id])
#{@controller.name.singularize}.destroy
redirect_to #{@controller.redirect}
end""" if @controller.destroy_action}
# code from the drag and drop editor passed to the back end
###
private
def controller_params
params.require(:#{@model.name.underscore}.permit(
#{@model.migrations.each do |migration|
if migration == @model.migrations.last
":#{migration.name.underscore},"
else
":#{migration.name.underscore}"
end
end
})
end
end
"""
# parameters part needs fixing
if @controller.save
Thread.start do
system "cd ./#{@app.directory} && rails g controller #{@controller.name.pluralize.underscore}"
# write code to file
File.open("./#{@app.directory}/app/controllers/#{@controller.name.pluralize.underscore}_controller.rb",'w') do |file|
file.puts("#{@controller.program}") # overwrites previous code and saves
end
end
redirect_to edit_app_path(@app) # for further editing and such
end
end
def update
@controller = Controller.find(params[:app_id])
if @controller.update_attributes(controller_params)
Thread.start do
# explain beforehand what view type is what
# write to here
File.open("#{@app.directory}/app/controllers/#{@controller.name.pluralize.underscore}_controller.rb",'w') do |file|
file.puts("#{@controller.program}") # overwrites previous code and saves
end
# write code to file
end
redirect_to edit_app_path(@app) # for further editing and such
else
flash[:danger] = "Cannot update"
end
end
def destroy
end
private
def controller_params
params.require(:control).permit(:name,:new_action,:create_action,:show_action,:edit_action,:update_action,:destroy_action)
end
end
|
class Funcionalidade < ActiveRecord::Base
belongs_to :tipo_funcionalidade
belongs_to :funcionalidade_pai, :class_name => "Funcionalidade"
end
|
require 'fileutils'
require 'rubygems'
require 'rubygems/remote_fetcher'
require 'rubygems/source_info_cache_entry'
require 'sources'
# SourceInfoCache stores a copy of the gem index for each gem source.
#
# There are two possible cache locations, the system cache and the user cache:
# * The system cache is prefered if it is writable or can be created.
# * The user cache is used otherwise
#
# Once a cache is selected, it will be used for all operations.
# SourceInfoCache will not switch between cache files dynamically.
#
# Cache data is a Hash mapping a source URI to a SourceInfoCacheEntry.
#
#--
# To keep things straight, this is how the cache objects all fit together:
#
# Gem::SourceInfoCache
# @cache_data = {
# source_uri => Gem::SourceInfoCacheEntry
# @size => source index size
# @source_index => Gem::SourceIndex
# ...
# }
#
class Gem::SourceInfoCache
include Gem::UserInteraction
@cache = nil
def self.cache
return @cache if @cache
@cache = new
@cache.refresh
@cache
end
def self.cache_data
cache.cache_data
end
# Search all source indexes for +pattern+.
def self.search(pattern)
cache.search(pattern)
end
def initialize # :nodoc:
@cache_data = nil
@cache_file = nil
@dirty = false
@system_cache_file = nil
@user_cache_file = nil
end
# The most recent cache data.
def cache_data
return @cache_data if @cache_data
@dirty = false
cache_file # HACK writable check
# Marshal loads 30-40% faster from a String, and 2MB on 20061116 is small
begin
data = File.open cache_file, 'rb' do |fp|
fp.read
end
@cache_data = Marshal.load data
rescue
{}
end
end
# The name of the cache file to be read
def cache_file
return @cache_file if @cache_file
@cache_file = (try_file(system_cache_file) or
try_file(user_cache_file) or
raise "unable to locate a writable cache file")
end
# Write the cache to a local file (if it is dirty).
def flush
write_cache if @dirty
@dirty = false
end
# Refreshes each source in the cache from its repository.
def refresh
Gem.sources.each do |source_uri|
cache_entry = cache_data[source_uri]
if cache_entry.nil? then
cache_entry = Gem::SourceInfoCacheEntry.new nil, 0
cache_data[source_uri] = cache_entry
end
cache_entry.refresh source_uri
end
update
flush
end
# Searches all source indexes for +pattern+.
def search(pattern)
cache_data.map do |source, sic_entry|
sic_entry.source_index.search pattern
end.flatten
end
# The name of the system cache file.
def system_cache_file
@system_cache_file ||= File.join(Gem.dir, "source_cache")
end
# Mark the cache as updated (i.e. dirty).
def update
@dirty = true
end
# The name of the user cache file.
def user_cache_file
@user_cache_file ||=
ENV['GEMCACHE'] || File.join(Gem.user_home, ".gem", "source_cache")
end
# Write data to the proper cache.
def write_cache
open cache_file, "wb" do |f|
f.write Marshal.dump(cache_data)
end
end
# Set the source info cache data directly. This is mainly used for unit
# testing when we don't want to read a file system for to grab the cached
# source index information. The +hash+ should map a source URL into a
# SourceIndexCacheEntry.
def set_cache_data(hash)
@cache_data = hash
@dirty = false
end
private
# Determine if +fn+ is a candidate for a cache file. Return fn if
# it is. Return nil if it is not.
def try_file(fn)
return fn if File.writable?(fn)
return nil if File.exist?(fn)
dir = File.dirname(fn)
if ! File.exist? dir
begin
FileUtils.mkdir_p(dir)
rescue RuntimeError
return nil
end
end
if File.writable?(dir)
FileUtils.touch fn
return fn
end
nil
end
end
|
require 'puppet/type'
Puppet::Type.newtype(:rz_policy) do
@doc = <<-EOT
Manages razor policy.
EOT
ensurable
newparam(:name) do
desc 'unique name of policy'
end
newparam(:enabled) do
desc 'enabled state for policy'
newvalues(true, false, 'true', 'false')
defaultto(true)
end
newparam(:repo) do
desc 'name of repo to use'
end
newparam(:installer) do
desc 'installer to use'
end
newparam(:broker) do
desc 'name of broker'
end
newparam(:hostname) do
end
newparam(:root_password) do
desc 'root password'
end
newparam(:max_count) do
desc 'max count for policy'
munge do |x|
Integer(x)
end
end
newparam(:rule_number) do
munge do |x|
Integer(x)
end
end
newproperty(:tags, :array_matching => :all) do
end
autorequire(:rz_repo) do
self[:repo]
end
autorequire(:rz_broker) do
self[:broker]
end
end
|
class MembershipsController < ApplicationController
def create
@membership = Membership.new(user_id: params[:user], petition_id: params[:petition_id])
if @membership.save!
redirect_to state_path(id: params[:id]), notice: "You've signed this petition!"
end
end
def destroy
@membership = Membership.find(params[:id])
@membership.destroy
redirect_to user_path
end
end
|
class CreateCompanies < ActiveRecord::Migration
def change
create_table :companies do |t|
t.integer :rank
t.boolean :is_new
t.boolean :is_featured
t.boolean :is_member
t.string :logo_src
t.string :url
t.string :category_name
t.string :name_text
t.string :name_url
t.string :country
t.string :tags
t.text :des_short
t.text :des_long
t.string :crunchbase_url
t.string :angellist_url
t.timestamps null: false
end
end
end
|
require 'rails_helper'
RSpec.describe "admin/external_links/new", type: :view do
before(:each) do
assign(:admin_external_link, ExternalLink.new(
:link_type => "MyString",
:title => "MyString",
:url => "MyString"
))
end
it "renders new admin_external_link form" do
render
assert_select "form[action=?][method=?]", external_links_path, "post" do
assert_select "input#admin_external_link_link_type[name=?]", "admin_external_link[link_type]"
assert_select "input#admin_external_link_title[name=?]", "admin_external_link[title]"
assert_select "input#admin_external_link_url[name=?]", "admin_external_link[url]"
end
end
end
|
class Message < ApplicationRecord
NUM_OF_MESSAGES = 36
def self.get_new_massages(count)
ids = []
iteration = (count && count > 0) ? count : NUM_OF_MESSAGES
iteration.times do
ids << SecureRandom.random_number(5000)
end
messages = []
Message.where("id IN (?)", ids).map{|message|
messages << {
author: message.author,
created_at: (message.created_at + 3.hours).strftime("%e %B, %T"),
body: message.body
}
}
messages
end
end
|
class Api::V1::CurrentHotreadsController < ActionController::API
def index
render json: Read.hot_reads
end
end
|
require 'rails_helper'
RSpec.describe Item, type: :model do
before do
@item = FactoryBot.build(:item)
end
describe '商品出品' do
context '商品を出品できる時' do
it '全ての空欄を条件通りに埋めている時' do
expect(@item).to be_valid
end
end
context '商品を出品できない時' do
it 'nameが空では出品できない' do
@item.name = ''
@item.valid?
expect(@item.errors.full_messages).to include("Name can't be blank")
end
it 'imageが空では登録できない' do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include("Image can't be blank")
end
it 'infoが空では登録できない' do
@item.info = ''
@item.valid?
expect(@item.errors.full_messages).to include("Info can't be blank")
end
it 'categroy_idが0では登録できない' do
@item.category_id = 0
@item.valid?
expect(@item.errors.full_messages).to include("Category must be other than 0")
end
it 'item_status_idが0では登録できない' do
@item.item_status_id = 0
@item.valid?
expect(@item.errors.full_messages).to include("Item status must be other than 0")
end
it 'delivary_price_idが0では登録できない' do
@item.delivary_price_id = 0
@item.valid?
expect(@item.errors.full_messages).to include("Delivary price must be other than 0")
end
it 'prefecture_idが0では登録できない' do
@item.prefecture_id = 0
@item.valid?
expect(@item.errors.full_messages).to include("Prefecture must be other than 0")
end
it 'delivary_date_idが0では登録できない' do
@item.delivary_date_id = 0
@item.valid?
expect(@item.errors.full_messages).to include("Day time must be other than 0")
end
it 'priceが空では登録できない' do
@item.price = 0
@item.valid?
expect(@item.errors.full_messages).to include("Price must be greater than 300")
end
it 'priceが全角だと登録できない' do
@item.price = '111'
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it '数字以外で混じっていると登録できない' do
@item.price = 'てさ4'
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it '300円未満では登録できない' do
@item.price = 11
@item.valid?
expect(@item.errors.full_messages).to include("Price must be greater than 300")
end
it '9999999円以上だと登録できない' do
@item.price = 9999999999999
@item.valid?
expect(@item.errors.full_messages).to include("Price must be less than 9999999")
end
end
end
end
|
RSpec.describe Diamond do
let(:instance) { described_class.new }
describe '#build' do
subject { instance.build(input) }
context 'when given an invalid params' do
context 'when given a special character' do
let(:input) { '@' }
it { is_expected.to eq('') }
end
context 'when given an empty input' do
let(:input) { '' }
it { is_expected.to eq('') }
end
context 'when given a number' do
let(:input) { '1' }
it { is_expected.to eq('') }
end
context 'when given a mix of character' do
let(:input) { 'a1@' }
it { is_expected.to eq('') }
end
context 'when given a word' do
let(:input) { 'word' }
it { is_expected.to eq('') }
end
end
context 'when given a valid parms' do
context 'when given a downcase character' do
let(:input) { 'a' }
it { is_expected.to eq("A\n") }
end
context 'when given an A character' do
let(:input) { 'A' }
it { is_expected.to eq("A\n") }
end
context 'when given a B character' do
let(:input) { 'B' }
it { is_expected.to eq("_A_\nB_B\n_A_\n") }
end
context 'when given a C character' do
let(:input) { 'C' }
it { is_expected.to eq("__A__\n_B_B_\nC___C\n_B_B_\n__A__\n") }
end
context 'when given a J character' do
let(:input) { 'J' }
it { is_expected.to eq(<<~EXAMPLE) }
_________A_________
________B_B________
_______C___C_______
______D_____D______
_____E_______E_____
____F_________F____
___G___________G___
__H_____________H__
_I_______________I_
J_________________J
_I_______________I_
__H_____________H__
___G___________G___
____F_________F____
_____E_______E_____
______D_____D______
_______C___C_______
________B_B________
_________A_________
EXAMPLE
end
end
end
end
|
Vagrant.configure("2") do |config|
config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
config.vm.box = 'ubuntu/trusty64'
config.vm.host_name = 'l52.root-servers.net'
config.vm.network "forwarded_port", guest: 53, host: 5353, protocol: "tcp"
config.vm.network "forwarded_port", guest: 53, host: 5353, protocol: "udp"
config.vm.provision "shell", inline: "wget https://apt.puppetlabs.com/puppet5-release-trusty.deb"
config.vm.provision "shell", inline: "dpkg -i puppet5-release-trusty.deb"
config.vm.provision "shell", inline: "apt-get update"
config.vm.provision "shell", inline: "apt-get -y upgrade"
config.vm.provision "shell", inline: "apt-get install -y puppet-agent python-dnspython"
config.vm.provision "shell", inline: "/vagrant/fetch_zone.sh"
config.vm.provision :puppet do |puppet|
puppet.environment = 'production'
puppet.environment_path = 'puppet/environments'
puppet.hiera_config_path = "puppet/hiera.yaml"
puppet.module_path = "../modules"
end
end
|
require "rails_helper"
feature "User creates a shortened url" do
scenario "successfully" do
visit root_path
original_url = "https://www.example.com/really/long/path?with=query_params"
create_shortened_url original_url
expect(page).to display_shortened_url original_url
# expect(page).to display_original_url original_url
end
end
|
require 'test_helper'
class PatriasControllerTest < ActionController::TestCase
setup do
@patria = patrias(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:patrias)
end
test "should get new" do
get :new
assert_response :success
end
test "should create patria" do
assert_difference('Patria.count') do
post :create, patria: { flag: @patria.flag, nome: @patria.nome, sigla: @patria.sigla }
end
assert_redirected_to patria_path(assigns(:patria))
end
test "should show patria" do
get :show, id: @patria
assert_response :success
end
test "should get edit" do
get :edit, id: @patria
assert_response :success
end
test "should update patria" do
patch :update, id: @patria, patria: { flag: @patria.flag, nome: @patria.nome, sigla: @patria.sigla }
assert_redirected_to patria_path(assigns(:patria))
end
test "should destroy patria" do
assert_difference('Patria.count', -1) do
delete :destroy, id: @patria
end
assert_redirected_to patrias_path
end
end
|
FactoryGirl.define do
factory :finance, :class => Refinery::Finances::Finance do
sequence(:Main_headline) { |n| "refinery#{n}" }
end
end
|
module ThreeScale
module Backend
class Usage
class << self
def user_usage(user, timestamp)
usage user do |metric_id, period|
Stats::Keys.user_usage_value_key(
user.service_id, user.username, metric_id, period.new(timestamp))
end
end
def application_usage(application, timestamp)
usage application do |metric_id, period|
Stats::Keys.usage_value_key(
application.service_id, application.id, metric_id, period.new(timestamp))
end
end
def is_set?(usage_str)
usage_str && usage_str[0] == '#'.freeze
end
def get_from(usage_str, current_value = 0)
if is_set? usage_str
usage_str[1..-1].to_i
else
# Note: this relies on the fact that NilClass#to_i returns 0
# and String#to_i returns 0 on non-numeric contents.
current_value + usage_str.to_i
end
end
private
def usage(obj)
pairs = metric_period_pairs obj.usage_limits
return {} if pairs.empty?
keys = pairs.map(&Proc.new)
values = {}
pairs.zip(storage.mget(keys)) do |(metric_id, period), value|
values[period] ||= {}
values[period][metric_id] = value.to_i
end
values
end
def metric_period_pairs(usage_limits)
usage_limits.map do |usage_limit|
[usage_limit.metric_id, usage_limit.period]
end
end
def storage
Storage.instance
end
end
end
end
end
|
require_relative 'game_vector'
class Obstacle
attr_accessor :pos
attr_accessor :crossed
DEFAULT_VALUES = { pos: GameVector.new(0, 0), crossed: false }
WIDTH = 106
HEIGHT = 600
GAP = 200
def initialize(args)
args = DEFAULT_VALUES.merge(args)
self.pos = args[:pos]
self.crossed = args[:crossed]
end
def rectangle(top)
if top
Rectangle.new(pos: GameVector.new(pos.x, pos.y - Obstacle.height), size: Obstacle.size_vector)
else
Rectangle.new(pos: GameVector.new(pos.x, pos.y + GAP), size: Obstacle.size_vector)
end
end
def self.width; WIDTH; end
def self.height; HEIGHT; end
def self.gap; GAP; end
def self.size_vector
GameVector.new(width, height)
end
end |
path = File.expand_path '../', __FILE__
require "#{path}/config/env.rb"
class Upandcoming < Sinatra::Base
include Voidtools::Sinatra::ViewHelpers
# partial :comment, { comment: "blah" }
# partial :comment, comment
def partial(name, value={})
locals = if value.is_a? Hash
value
else
hash = {}; hash[name] = value
hash
end
haml "_#{name}".to_sym, locals: locals
end
@@path = PATH
@@issues_dir = "issues"
@@issues_dir = "issues_linux" if File.exist?("/home/makevoid")
# confs
ISSUE_NUM = 1 # defines the directory whre the issue images are
FORMAT = "svg" #jpg
#
def issues_dir
@@issues_dir
end
helpers do
def photos
all = Dir.glob("#{@@path}/public/#{@@issues_dir}/#{ISSUE_NUM}/*.#{FORMAT}")
all.sort_by do |img|
File.basename(img).to_i
end
end
def issues_json
{ path: "#{@@issues_dir}/#{ISSUE_NUM}", size: photos.size }.to_json
end
end
get "/" do
# haml :index
File.read "public/app.html"
end
# get "/slides.json" do
# # TODO: staticize this
# photos.map do |photo|
# File.basename photo, ".jpg"
# end.to_json
# end
end
# require_all "#{path}/routes" |
require 'nokogiri'
module XmlOption
module_function
def from_file_path path
XmlOption.from_string(File.read(path))
end
def from_io io
XmlOption.from_string(io.read)
end
def from_string string
XmlOption.parse(Nokogiri::XML.parse(string).root)
end
def parse elem, parent = nil
if elem.children.empty? && parent
(parent[elem.name] ||= []) <<
Hash[elem.attributes.values.map{ |attr| [attr.name, attr.value] }]
else
result = {elem.name => hash = {}}
elem.children.map{ |child|
XmlOption.parse(child, hash) if child.kind_of?(Nokogiri::XML::Element)
}.compact
result
end
end
end # of XmlOption
|
require "spec_helper"
describe RemessasController do
describe "routing" do
it "routes to #index" do
get("/remessas").should route_to("remessas#index")
end
it "routes to #new" do
get("/remessas/new").should route_to("remessas#new")
end
it "routes to #show" do
get("/remessas/1").should route_to("remessas#show", :id => "1")
end
it "routes to #edit" do
get("/remessas/1/edit").should route_to("remessas#edit", :id => "1")
end
it "routes to #create" do
post("/remessas").should route_to("remessas#create")
end
it "routes to #update" do
put("/remessas/1").should route_to("remessas#update", :id => "1")
end
it "routes to #destroy" do
delete("/remessas/1").should route_to("remessas#destroy", :id => "1")
end
end
end
|
require 'test_helper'
class UserSignupTest < ActionDispatch::IntegrationTest
test "invalid signup info" do
get signup_path
before_count = User.count
post users_path, params: {user:{ name: "",
email: "dingdong@ding.com",
password: "foo",
password_confirmation: "doo"}}
post_count = User.count
assert_template 'users/new'
assert_equal before_count, post_count
end
test "invalid signup info2" do
get signup_path
assert_no_difference 'User.count' do
post users_path, params: {user:{ name: "",
email: "dingdong@ding.com",
password: "foo",
password_confirmation: "doo"}}
end
assert_template 'users/new'
assert_select 'li', text: "Name can't be blank"
assert_select 'div#error_header', "The Form contains 2 errors"
end
test "valid signup info" do
get signup_path
assert_difference 'User.count', 1 do
post users_path, params: {user:{ name: "ding",
email: "dingdong@ding.com",
password: "foo",
password_confirmation: "foo"}}
end
follow_redirect!
assert_template 'users/show'
end
end
|
=begin
Write a method that computes the difference between the square of the sum of the first n positive integers and the sum of the squares of the first n positive integers.
Examples:
=end
def sum_square_difference(int)
square_of_sum = (1..int).inject(&:+) ** 2
sum_of_square = (1..int).map do |num|
num ** 2
end
square_of_sum - sum_of_square.sum
end
puts sum_square_difference(3) == 22
# -> (1 + 2 + 3)**2 - (1**2 + 2**2 + 3**2)
puts sum_square_difference(10) == 2640
puts sum_square_difference(1) == 0
puts sum_square_difference(100) == 25164150 |
class Class
def dependencies
dependencies_accumulator = super
dependencies_accumulator.push(*@__dependencies__)
if respond_to?(:superclass) && !superclass.nil?
dependencies_accumulator.push(*superclass.dependencies)
end
dependencies_accumulator.uniq
end
def resolve(opts={})
instance = allocate
dependencies.each do |name|
dependency = opts.has_key?(name) ? opts[name] : Resolve.resolve(name, opts)
instance.send("#{name}=", dependency)
end
if instance.private_methods.include? :initialize
initialize_method = instance.method(:initialize)
if initialize_method.arity.zero?
instance.send(:initialize)
else
instance.send(:initialize, opts)
end
end
return instance
end
end
|
class AddArchivedFlag < ActiveRecord::Migration
def change
add_column :project_medias, :archived, :boolean, default: false
add_index :project_medias, :archived
add_column :sources, :archived, :boolean, default: false
add_index :sources, :archived
add_index :projects, :archived
add_index :teams, :archived
end
end
|
require 'time'
require_relative 'reservation'
require_relative 'front_desk'
require_relative 'room'
class Block
attr_reader :block_start, :block_end, :rate, :block_rooms, :block_ID
attr_writer :block_ID
def initialize(block_start, block_end, rate, converted_rooms)
@block_start = Date.parse(block_start)
@block_end = Date.parse(block_end)
@block_rate = rate
@block_ID = block_id_generator
@block_rooms = converted_rooms
#when i actually reserve a room, it goes into reserved_in_block array? this is an option for
# refactor.
@reserved_in_block = []
if block_rooms.length > 5
raise StandardError.new "Block is limited to 5 rooms"
end
end
def block_id_generator
letters = ('A'..'Z').to_a.shuffle[0..1].join
id = letters + (0..9).to_a.shuffle[0..2].join
return id
end
def is_available_block?(room)
return false if @reserved_in_block.include?(room)
end
end
|
class CreateCopropietarios < ActiveRecord::Migration[6.0]
def change
create_table :copropietarios do |t|
t.string :id_copropietario
t.string :nombres
t.string :cedula
t.date :fecha_nacimiento
t.string :actividad
t.string :direccion
t.string :telefono
t.string :celular
t.string :mail
t.string :id_edificio
t.string :id_departamento
t.timestamps
end
end
end
|
class Table < ApplicationRecord
DEFAULT_TABLE_NAME = "Stembolt Courtney".freeze
class << self
def default
Table.find_by(name: DEFAULT_TABLE_NAME)
end
end
has_many :matches
validates :name, presence: true
# NOTE: The active flag on players (at the time of this writing) means
# "active on the default table." It is not possible to be active on other
# tables.
def active_players
name == DEFAULT_TABLE_NAME ? Player.active : Player.none
end
def ongoing_match
matches.ongoing.order(:created_at).first
end
def upcoming_matches
matches.ongoing.order(:created_at).offset(1)
end
end
|
class User < ActiveRecord::Base
after_create :create_keywords
attr_accessible :first_name, :last_name, :image, :location, :occupation, :abstracts_attributes, :emails_attributes, :show_email, :is_admin, :bio
has_many :abstracts
has_many :attendances
has_many :authentications
has_many :emails
has_many :user_interests
has_many :interests, :through => :user_interests
has_many :coordinates
has_many :likes
has_many :requests
accepts_nested_attributes_for :abstracts
accepts_nested_attributes_for :emails, :allow_destroy => true
validates_presence_of :first_name
validates_presence_of :last_name
def coordinate (conference)
self.coordinates.each do |c|
if c.conference_id == conference.id
return true
end
end
return false
end
def name
return self.first_name.to_s + " " + self.last_name.to_s
end
def get_conferences
conferences = []
self.attendances.each do |attendance|
conferences << attendance.conference
end
return conferences
end
def self.create_with_omniauth(auth)
user = User.new
authentication = Authentication.where(:uid => auth["uid"], :provider => auth["provider"])
if authentication.size > 0
return User.find(authentication.last.user_id)
else
email = auth["info"]["email"]
eModel = Email.find_by_mail_address(email)
if eModel
aModel = Authentication.new
aModel.uid = auth["uid"]
aModel.provider = auth["provider"]
aModel.user_id = eModel.user_id
aModel.save
return User.find(aModel.user_id)
end
user.first_name = auth["info"]["first_name"]
user.last_name = auth["info"]["last_name"]
user.image = auth["info"]["image"] if auth["info"]["image"]
extra = auth["extra"] if auth["extra"]
raw_info = extra["raw_info"] if extra["raw_info"]
if auth["provider"] == "facebook"
work = raw_info["work"].first if raw_info["work"] && raw_info["work"].first
if work
employer = work["employer"]["name"] if work["employer"]
position = work["position"]["name"] if work["position"]
user.occupation = position + " at " + employer
end
user.location = auth["info"]["location"] if auth["info"]["location"]
elsif auth["provider"] == "linkedin"
location = raw_info["location"] if raw_info["location"]
user.occupation = auth["info"]["headline"] if auth["info"]["headline"]
user.location = location["name"]
user.location = user.location + ", " + location["country"]["code"] if location["country"]["code"]
end
user.save
unless eModel
eModel = Email.new
eModel.mail_address = email
eModel.user_id = user.id
eModel.save
aModel = Authentication.new
aModel.uid = auth["uid"]
aModel.provider = auth["provider"]
aModel.user_id = eModel.user_id
aModel.save
end
return user
end
end
# Bio no longer being used
# def create_bio
# @bio = Abstract.create(:user_id => self.id)
# @bio.is_bio = true
# @bio.keywords = false
# @bio.save
# end
def create_keywords
@keys = Abstract.create(:user_id => self.id)
@keys.keywords = true
@keys.is_bio = false
@keys.save
end
def get_notifications
notifications = Request.where('inviter = ? AND (reply IS NOT NULL OR accepted = ?)', self.id, true)
end
def get_accepted
Request.where('inviter = ? AND user_id IS NOT NULL AND accepted = ?', self.id, true)
end
def get_invites
Request.where('user_id = ? AND accepted IS NULL', self.id)
end
def get_requests
Request.where('inviter = ? AND accepted IS NULL', self.id)
end
def attach_att(email_address)
atts = Attendance.all
atts.each do |a|
if a.registered_email == email_address
if a.user_id.nil?
a.user_id = self.id
a.save
end
end
end
end
def attach_request(email_address)
requests = Request.where("email = ? AND invitee_registered = ? AND user_id is null", email_address, false).all
requests.each do |r|
r.user_id = self.id
r.invitee_registered = true
r.save
end
end
end
|
class User < BaseResource
include ActiveResource::Singleton
schema do
string :email
boolean :github_access_token_present
string :github_access_token
boolean :subscribe
end
def repositories
self.respond_to?(:repos) ? repos : []
end
end
|
module KrakenClient
module Requests
module Content
class Header
attr_accessor :config, :endpoint_name, :options, :url
def initialize(config, endpoint_name, options, url)
@config = config
@endpoint_name = endpoint_name
@url = url
@options = options
@options[:nonce] = nonce
end
def call
{
'API-Key' => config.api_key,
'API-Sign' => generate_signature,
}
end
private
## Security
# Using nanosecond timestamp keeps nonce within the 64-bit range
# and allows for stable parallel requests using the same API key
# without getting nonce errors
def nonce
(Time.now.to_f * 10e8).to_i.to_s
end
def encoded_options
uri = Addressable::URI.new
uri.query_hash = options
uri.query
end
def generate_signature
key = Base64.decode64(config.api_secret)
message = generate_message
generate_hmac(key, message)
end
def generate_message
digest = OpenSSL::Digest.new('sha256', options[:nonce] + encoded_options).digest
url.split('.com').last + digest
end
def generate_hmac(key, message)
Base64.strict_encode64(OpenSSL::HMAC.digest('sha512', key, message))
end
end
end
end
end
|
class View
def ask_for_ingredient
puts "What ingredient would you like a recipe for?"
ingredient = gets.chomp
puts "Looking for \"#{ingredient}\" recipes on the Internet..."
ingredient
end
def display_imported_recipes(recipes_array)
recipes_array.each_with_index do |recipe_hash, index|
puts "#{index + 1}. #{recipe_hash[:name]}"
end
puts "Which recipe would you like to import? (enter index)"
index = gets.chomp.to_i - 1
puts "Importing \"#{recipes_array[index][:name]}\"..."
index
end
def ask_for_recipe_info
puts "What recipe would you like to add?"
print "> "
recipe = gets.chomp
puts "What is it's description?"
print "> "
description = gets.chomp
puts "What is it's rating?"
print "> "
rating = gets.chomp.to_i
puts "What is it's preparation time?"
print "> "
prep_time = gets.chomp
return [recipe, description, rating, prep_time]
end
def display(recipes)
recipes.each_with_index do |recipe, index|
done = recipe.done? ? "X" : " "
puts "#{index + 1}. [#{done}] #{recipe.name} (rating #{recipe.rating} | prep time: #{recipe.prep_time})"
end
end
def ask_for_input
puts "What index would you like to delete?"
print "> "
gets.chomp.to_i - 1
end
def ask_which_recipe_to_mark_as_done
puts "What's the recipe you want to mark as done? Provide the index"
print "> "
gets.chomp.to_i - 1
end
end
|
class CreateFinalPolicyExperienceCalculations < ActiveRecord::Migration
def change
create_table :final_policy_experience_calculations do |t|
t.integer :representative_number
t.string :policy_type
t.integer :policy_number
t.string :valid_policy_number
t.index [:policy_number, :representative_number], name: 'index_pol_exp_pol_num_and_man_num_rep'
t.string :policy_group_number
t.string :policy_status
t.float :policy_total_four_year_payroll
t.integer :policy_credibility_group
t.integer :policy_maximum_claim_value
t.float :policy_credibility_percent
t.float :policy_total_expected_losses
t.float :policy_total_limited_losses
t.integer :policy_total_claims_count
t.float :policy_total_modified_losses_group_reduced
t.float :policy_total_modified_losses_individual_reduced
t.float :policy_group_ratio
t.float :policy_individual_total_modifier
t.float :policy_individual_experience_modified_rate
t.string :data_source
t.timestamps null: false
end
end
end
|
#
require 'tarantool16'
require 'wallarm/common/processor'
class UpdateSpotsQueueProcessor < Processor
def initialize( queue, config)
super
@min_delay = 60
@queue = queue
@tdb = Tarantool16.new( config.tarantool)
@iteration_time = config.iteration_time
@max_iterations = config.max_iterations
end
def process
Log.info("Processed %.3f%% spots" % @queue.processed)
@tdb.call( 'wallarm.mark_processed_spots', [@queue.last_processed_id]) unless @queue.last_processed_id.nil?
firstid, lastid = unprocessed_requests
@queue.set_range( firstid, lastid)
end
def unprocessed_requests
first, last = @tdb.call( "wallarm.unprocessed_spots", [])
return if first.nil? or last.nil?
firstid = first[0]
firsttime = first[1]
lastid = last[0]
lasttime = last[1]
total = lastid+1-firstid
time = lasttime+1-firsttime
if time > @iteration_time * @max_iterations
k = 1.0 / @max_iterations
lastid = firstid + (k*total).to_i
elsif time > @iteration_time
k = 1.0 * @iteration_time / time
lastid = firstid + (k*total).to_i
end
Log.info "#{lastid+1-firstid}/#{total} requests for process"
[firstid, lastid]
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
layout 'application'
def handle_ajax_validation_errors(object)
if !object.errors.empty? && request.xhr?
response.headers['X-JSON'] = object.errors.to_json
render :nothing => true, :status=>444
return true
end
return false
end
def authorize
redirect_to :controller => :home, :action => :index unless Security.authorized?
end
def logged_in_user
return session[:user]
end
def authorized?
return !logged_in_user.nil?
end
def render_404
render :file => "#{Rails.root}/public/404.html", :status => 404
end
end
|
class Route
attr_reader :pattern, :http_method, :controller_class, :action_name
def initialize(pattern, http_method, controller_class, action_name)
@pattern = pattern
@http_method = http_method
@controller_class = controller_class
@action_name = action_name
end
def matches?(req)
(self.pattern =~ req.path) && (self.http_method.to_s == req.request_method.downcase)
end
def run(req, res)
match_data = @pattern.match(req.path)
names = match_data.names
captures = match_data.captures
route_params = Hash[names.zip(captures)]
@controller_class.new(req, res, route_params).invoke_action(action_name)
end
end
class Router
attr_reader :routes
def initialize
@routes = []
end
def add_route(pattern, method, controller_class, action_name)
@routes << Route.new(pattern, method, controller_class, action_name)
end
# evaluate the proc in the context of the instance
def draw(&proc)
instance_eval(&proc)
end
[:get, :post, :put, :delete].each do |http_method|
define_method(http_method) do |pattern, controller_class, action_name|
add_route(pattern, http_method, controller_class, action_name)
end
end
# return the route that matches this request
def match(req)
@routes.find { |route| route.matches?(req) }
end
def run(req, res)
matching_route = match(req)
if matching_route.nil?
res.status = 404
res.write "Route not found"
res.finish
else
matching_route.run(req, res)
end
end
end
|
require "pry"
class Instructor
@@all = [ ]
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def pass_student (student, test_name)#student == instance
result = Boatingtest.all.find{|test|
test.student == student.first_name && test.b_test == test_name} #a Boatingtest instance
if result !=nil
result.test_status = "passed"
else
Boatingtest.new(student.first_name, test_name, "passed", self)
end
end
def fail_student(student, test_name)#student == instance
result = Boatingtest.all.find{|test|
test.student == student.first_name && test.b_test == test_name} #a Boatingtest instance
if result !=nil
result.test_status = "failed"
else
Boatingtest.new(student.first_name, test_name, "failed", self)
end
end
end
|
require 'active_support'
require 'active_support/all'
require 'fnv'
require 'byebug'
require 'bcrypt'
require 'jwt'
require "date"
module WebToken
class MakeToken
def initialize( user_id )
data = {
userid: user_id,
date: Date.today.to_s,
time: Time.now
}
payload = {:data => data}
@token = JWT.encode payload, nil, 'none'
end
def web_token
@token
end
end
end
|
class NotificationMailer < ApplicationMailer
def notification(user)
mail to: user.email
end
end
|
class DistributionsController < ApplicationController
include DistributionActions
before_action :authenticate_user!
private
def update_customization
if @distribution.valid?
redirect_to edit_dataset_path(@distribution.dataset)
return
end
render :edit
return
end
def distribution_params
params.require(:distribution).permit(
:title,
:description,
:publish_date,
:download_url,
:modified,
:temporal_init_date,
:temporal_term_date,
:media_type,
:format,
:spatial,
:tools,
:codelist,
:codelist_link,
:copyright
)
end
end
|
require 'spec_helper'
describe APICoder::Type do
describe 'default types' do
%w(integer string float).each do |name|
subject { described_class.fetch(name) }
let(:klass) { "APICoder::Type::#{name.camelize}".constantize }
it "#{name} is registered" do
is_expected.to eq klass
end
end
end
end
shared_examples_for 'type match' do
context 'when match value given' do
subject { described_class.new.valid?(valid_value) }
it { is_expected.to be_truthy }
end
context 'when not match value given' do
subject { described_class.new.valid?(invalid_value) }
it { is_expected.to be_falsey }
end
end
describe APICoder::Type::Value do
describe '#valid?' do
subject { described_class.new.valid?(value) }
let(:value) { nil }
it { is_expected.to be_truthy }
end
end
describe APICoder::Type::String do
describe '#valid?' do
let(:valid_value) { '0' }
let(:invalid_value) { 0 }
it_behaves_like 'type match'
end
end
describe APICoder::Type::Integer do
describe '#valid?' do
let(:valid_value) { 0 }
let(:invalid_value) { '0' }
it_behaves_like 'type match'
end
end
describe APICoder::Type::Float do
describe '#valid?' do
let(:valid_value) { 0.1 }
let(:invalid_value) { '0.1' }
it_behaves_like 'type match'
end
end
|
require 'rails_helper'
RSpec.describe 'roles#index', type: :request do
subject(:make_request) do
jsonapi_get '/api/v1/roles', headers: auth_headers(user)
end
describe 'basic fetch' do
let!(:role1) { create(:role) }
let!(:role2) { create(:role) }
let!(:user) { create(:user, role: role1) }
it 'works' do
expect(V1::RoleResource).to receive(:all).and_call_original
make_request
expect(response.status).to eq(200), response.body
expect(d.map(&:jsonapi_type).uniq).to match_array(['roles'])
expect(d.map(&:id)).to match_array([role1.id, role2.id])
end
end
end
|
#1. Come up with requirements/specifications, which will determine the scope of your application. (usually the manager/client does this who are usually
# not technical)
#2. As programmers, we next need to think about application logic. Not code, but just the logical sequence of steps that need to be taken in order to complete the job
#3. Translation of these steps into code
#4. Run to test the code
# draw a board
# assign player1 to "X"
# assign computer to "O"
# loop until a winner or all squares are taken
# player picks an empty square
# checkwin
# computer picks an empty square
# checkwin
# if there is a winner
# show the winner
# else
# it's a tie
# end
def check_winner b, player
winning_lines = [ [1,2,3],
[4,5,6],
[7,8,9],
[1,4,7],
[2,5,8],
[3,6,9],
[1,5,9],
[3,5,7] ]
winning_lines.each do |line|
return "#{player}" if (b[line[0]] == "X" && b[line[1]] == "X" && b[line[2]] == "X")
return "Computer" if (b[line[0]] == "O" && b[line[1]] == "O" && b[line[2]] == "O")
end
nil
end
def initialize_board
b = {}
(1..9).each {|x| b[x] = '_'}
b
end
def draw_board(b)
system 'cls'
puts "_#{b[1]}_|_#{b[2]}_|_#{b[3]}_"
puts "_#{b[4]}_|_#{b[5]}_|_#{b[6]}_"
puts " #{b[7]} | #{b[8]} | #{b[9]} "
end
def player_picks_square b
empty_square = false
while empty_square == false
puts "Pick a square (1-9)"
position = gets.chomp.to_i
if b[position] == '_'
b[position] = 'X'
empty_square = true
else
puts "Sorry, square is not available. Please try again"
end
end
end
def empty_positions b
#returns an array of keys which represent the available positions on the game board
b.select {|k,v| v == '_'}.keys
end
def computer_picks_square b
position = empty_positions(b).sample
b[position] = 'O'
end
#main program
puts "Hello, welcome to Larry's Tic Tac Toe game!".center(80)
puts "Press [Enter]..."
gets
puts "What is your name?"
name = gets.chomp
keep_playing = true
while keep_playing == true
board = initialize_board
draw_board board
begin
player_picks_square board
winner = check_winner board, name
if winner
draw_board board
break
end
computer_picks_square board
draw_board board
winner = check_winner board, name
end until winner || empty_positions(board).empty?
#binding.pry
if winner
puts "#{winner} won!"
else
puts "It's a tie"
end
gets
puts "Would you like to play again? (y/n)"
answer = gets.chomp
if answer != 'y'
keep_playing = false
else
puts "Thank you for playing!"
end
end |
class Message < ActiveRecord::Base
belongs_to :sender, :foreign_key => :sender_id, class_name: 'User'
belongs_to :recipients, :foreign_key => :recipient_id, class_name: 'User'
validates :title, presence: true
validates :body, presence: true
def read?
!!read_at # reat_at = nil will return false. it equal !read_at.nil?
end
end
|
module Remote
class Translation < DigitalBiblePlatform::Base
attr_accessor :description, :abbreviation, :language
def initialize(description, abbreviation, language)
self.description = description
self.abbreviation = abbreviation
self.language = language
end
def self.all
client.translations.collect do |translation|
self.new(translation.version_name, translation.version_code, translation.language_english)
end
end
end
end
|
class Pair < ApplicationRecord
validates :date, presence: true
validates :student1_id, presence: true
validates :student2_id, presence: true
belongs_to :student1, class_name: 'User', foreign_key: 'student1_id'
belongs_to :student2, class_name: 'User', foreign_key: 'student2_id'
def self.removeTeams(day)
existing_teams = Pair.where(date: day)
if existing_teams.size > 0
existing_teams.each do |team|
team.destroy
end
end
end
def self.teamsForCourseday(day)
teams = makeTeams()
teams.each do |student|
new_match = Pair.create(student1: student[0], student2: student[1], date: day)
end
end
def self.makeTeams()
teams = []
picked_students = []
students = User.all.select { |u| u.admin == false }
students.push(User.find{ |u| u.no_teammate == true}) if students.length.odd?
teams_per_day = students.size / 2
teams_per_day.times do
randomizer_first = rand(students.size)
first_pick = students[randomizer_first]
picked_students << students.delete_at(randomizer_first)
randomizer_second = rand(students.size)
second_pick = students[randomizer_second]
picked_students << students.delete_at(randomizer_second)
teams << [first_pick, second_pick]
end
return teams
end
end
|
module ApplicationHelper
def bootstrap_class_for flash_type
case flash_type
when :success
"alert-success"
when :error
"alert-error"
when :alert
"alert-block"
when :notice
"alert-info"
else
flash_type.to_s
end
end
def raw_price(field)
number_to_currency(field, precision: 0)
end
def validate_field(field)
field.to_i > 0 ? true : false
end
def validate_price_field(field)
field.to_i > 0 ? raw_price(field) : 'N/A'
end
def validate_listing_field(field)
field.to_i > 0 ? field.to_i : 'N/A'
end
def javascript_void
'javascript:;'
end
def canonical_url
request.url
end
end |
class Admin::AdvisersController < Admin::AdminController
before_action :set_adviser, only: [:edit, :update, :destroy]
# GET /advisers
# GET /advisers.json
def index
@advisers = Adviser.all
respond_with @advisers
end
# GET /advisers/new
def new
@adviser = Adviser.new
respond_with @adviser
end
# GET /advisers/1/edit
def edit
end
# POST /advisers
# POST /advisers.json
def create
@adviser = Adviser.new(adviser_params)
flash[:notice] = 'Adviser was successfully created.' if @adviser.save
respond_with @adviser, :location => admin_advisers_path
end
# PATCH/PUT /advisers/1
# PATCH/PUT /advisers/1.json
def update
flash[:notice] = 'Adiser was successfully updated.' if @adviser.update(adviser_params)
respond_with @adviser, :location => admin_advisers_path
end
# DELETE /advisers/1
# DELETE /advisers/1.json
def destroy
@adviser.destroy
respond_with @adviser, :location => admin_advisers_path
end
private
# Use callbacks to share common setup or constraints between actions.
def set_adviser
@adviser = Adviser.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def adviser_params
params.require(:adviser).permit(:name, :lattes, :avatar)
end
end
|
json.array! "users", @users do |json, user|
json.code user.code # Code
json.name user.name # Name
end
|
require 'test_helper'
class MainHotCatchLogsControllerTest < ActionDispatch::IntegrationTest
setup do
@main_hot_catch_log = main_hot_catch_logs(:one)
end
test "should get index" do
get main_hot_catch_logs_url
assert_response :success
end
test "should get new" do
get new_main_hot_catch_log_url
assert_response :success
end
test "should create main_hot_catch_log" do
assert_difference('MainHotCatchLog.count') do
post main_hot_catch_logs_url, params: { main_hot_catch_log: { count_log: @main_hot_catch_log.count_log, from_log: @main_hot_catch_log.from_log, id_log_origin_app: @main_hot_catch_log.id_log_origin_app, log_data: @main_hot_catch_log.log_data, name_app: @main_hot_catch_log.name_app } }
end
assert_redirected_to main_hot_catch_log_url(MainHotCatchLog.last)
end
test "should show main_hot_catch_log" do
get main_hot_catch_log_url(@main_hot_catch_log)
assert_response :success
end
test "should get edit" do
get edit_main_hot_catch_log_url(@main_hot_catch_log)
assert_response :success
end
test "should update main_hot_catch_log" do
patch main_hot_catch_log_url(@main_hot_catch_log), params: { main_hot_catch_log: { count_log: @main_hot_catch_log.count_log, from_log: @main_hot_catch_log.from_log, id_log_origin_app: @main_hot_catch_log.id_log_origin_app, log_data: @main_hot_catch_log.log_data, name_app: @main_hot_catch_log.name_app } }
assert_redirected_to main_hot_catch_log_url(@main_hot_catch_log)
end
test "should destroy main_hot_catch_log" do
assert_difference('MainHotCatchLog.count', -1) do
delete main_hot_catch_log_url(@main_hot_catch_log)
end
assert_redirected_to main_hot_catch_logs_url
end
end
|
require_relative 'db_connection'
require 'active_support/inflector'
require 'byebug'
# NB: the attr_accessor we wrote in phase 0 is NOT used in the rest
# of this project. It was only a warm up.
class SQLObject
def self.columns
return @columns if @columns
characteristics = DBConnection.execute2("SELECT * FROM #{self.table_name}")
@columns = characteristics.first.map(&:to_sym)
end
def self.finalize!
self.columns.each do |column|
define_method(column) do
self.attributes[column]
end
define_method("#{column.to_s}=") do |val|
self.attributes[column] = val
end
end
end
def self.table_name=(table_name)
@table_name = table_name
end
def self.table_name
@table_name ||= self.to_s.tableize
end
def self.all
all_obj = DBConnection.execute("SELECT * FROM #{self.table_name}")
self.parse_all(all_obj)
end
def self.parse_all(results)
parsed = results.map do |params|
parsed_params = params.to_a
parsed_params.map { |pair| [pair[0].to_sym, pair[-1]] }
end
final_results = parsed.map(&:to_h)
final_results.map do |params|
self.new(params)
end
end
def self.find(id)
results = DBConnection.execute(<<-SQL)
SELECT
#{self.table_name}.*
FROM
#{self.table_name}
WHERE
#{self.table_name}.id = #{id}
SQL
self.parse_all(results).first
end
def initialize(params = {})
your_class = self.class
unless params.keys.all? { |param| your_class.columns.include?(param) }
bad_param = params.keys.find { |param| !your_class.columns.include?(param) }
raise "unknown attribute '#{bad_param.to_s}'"
else
characteristics = params.keys
your_class.columns.each do |column|
if characteristics.include?(column)
self.send("#{column}=", params[column])
end
end
end
end
def attributes
@attributes ||= {}
end
def attribute_values
attributes.values
end
def insert
question_marks = (["?"] * @attributes.length).join(", ")
col_names = self.class.columns.select { |symbol| attributes.keys.include?(symbol) }
col_names = col_names.map(&:to_s).join(", ")
DBConnection.execute(<<-SQL, *attribute_values)
INSERT INTO
#{self.class.table_name} (#{col_names})
VALUES
(#{question_marks})
SQL
self.id = DBConnection.last_insert_row_id
end
def update
# ...
end
def save
# ...
end
end
|
require 'rails_helper'
RSpec.describe ShopsController, type: :controller do
describe 'Get #map' do
context 'リクエストに引数がない場合' do
before do
get :map
end
it 'ステータスコードが200であること' do
expect(response).to be_success
end
it 'homeテンプレートを表示すること' do
expect(response).to render_template 'static_pages/home'
end
end
context 'リクエストに引数がある場合' do
before do
create_list(:shop, 20)
create_list(:prefecture, 20)
create_list(:branch, 20)
@s_ids = Shop.pluck(:id).sample(10)
@p_ids = Prefecture.pluck(:id).sample(10)
get :map, "s_ids": @s_ids.map(&:to_i),
"p_ids": @p_ids.map(&:to_i)
end
it 'ステータスコードが200であること' do
expect(response).to be_success
end
it 'mapテンプレートを表示すること' do
expect(response).to render_template 'shops/map'
end
it 'ショップidのパラメータがセットされる' do
expect(assigns(:selected_shop_ids)).to eq(@s_ids)
end
it '都道府県idのパラメータがセットされる' do
p_ids = [2, 1, 5, 3]
expect(assigns(:selected_prefecture_ids)).to eq(@p_ids)
end
it '検索条件にヒットした店舗がセットされる' do
@branches = Branch.of_shops(@s_ids)
.in_prefecutres(@p_ids)
expect(assigns(:branches)).to eq(@branches)
end
end
end
end
|
# frozen_string_literal: true
# time service
module TimeService
class TimeCalculator
DAY_IN_MINUTES = 1440
def convert_to_minutes(time_input)
# time_arr = time_input.split(':')
# hours = time_arr[0]
# min = time_arr[1]
# @minutes += hours.to_i * 60
# @minutes += min.to_i
@minutes = time_input[:hours] * 60
@minutes += time_input[:minutes]
end
def convert_from_minutes
hours = @minutes / 60
minutes = @minutes % 60
{ hours: hours, minutes: minutes }
end
def minutes_add(minute)
@minutes += minute
@minutes %= DAY_IN_MINUTES if @minutes > DAY_IN_MINUTES
end
end
class TimeParser < TimeCalculator
attr_accessor :time_input, :minutes_to_add
def check_args
return if ARGV.length == 3
puts 'Wrong arguments number (expected 2)'
exit
end
def initialize(&block)
return unless block_given?
instance_eval(&block)
add_minutes
end
def add_minutes(time_input = nil, minutes_to_add = nil)
@time_input = time_input if time_input
@minutes_to_add = minutes_to_add if minutes_to_add
time = parse_input
convert_to_minutes(time)
minutes_add(@minutes_to_add)
print
end
private
def main
check_args
# time = parse_time
convert_to_minutes(time)
print
end
def parse_input
parse_format
parse_time
end
def parse_format
@time_format = @time_input.split(' ')[1]
end
def parse_time
time_input = @time_input.split(':')
hours = @time_format == 'AM' ? time_input[0].to_i : time_input[1].to_i + 12
minutes = time_input[1].to_i
{ hours: hours, minutes: minutes }
end
def print
time = convert_from_minutes
time_hours = @time_format == 'AM' ? time[:hours] : time[:hours] % 12
time_minutes = time[:minutes] < 10 ? "0#{time[:minutes]}" : time[:minutes]
puts "#{time_hours}:#{time_minutes} #{@time_format}"
end
end
end
TimeService::TimeParser.new.add_minutes('11:12 PM', 3700)
# TimeService::TimeParser.new do
# @time_input = '12:58 AM'
# @minutes_to_add = 3700
# end
|
class Api::V1::FeesAndCommissionsController < Api::V1::BaseController
before_action :set_fees_and_commission, only: [:show, :update, :destroy]
def_param_group :fees_and_commission do
param :fees_and_commission, Hash, required: true, action_aware: true do
param :amount_from, /\A(\d+[\.,]?\d*|\d*[\.,]?\d+)\Z/, required: true, allow_nil: false
param :amount_to, /\A(\d+[\.,]?\d*|\d*[\.,]?\d+)\Z/, required: true, allow_nil: false
param :amount, /\A(\d+[\.,]?\d*|\d*[\.,]?\d+)\Z/, required: true, allow_nil: false
param :percentage, /\A(\d+[\.,]?\d*|\d*[\.,]?\d+)\Z/, required: true, allow_nil: false
param :percent_base, [true, false], required: true, allow_nil: false
param :active, [true, false], required: true, allow_nil: false
param :fc_type, Integer, required: true, allow_nil: false
param :rank, Integer, required: true, allow_nil: false
param :money_type, Integer, required: true, allow_nil: false
param :tansaction_type, Integer, required: true, allow_nil: false
param :sending_country_id, Integer, required: true, allow_nil: false
param :receiving_country_id, Integer, required: true, allow_nil: false
end
end
#api :GET, '/fees_and_commissions', 'List fees_and_commissions'
def index
@fees_and_commissions = FeesAndCommission.page(params[:page]).per(params[:per])
render json: @fees_and_commissions
end
#api :GET, '/fees_and_commissions/:id', 'Show fees_and_commission'
def show
render json: @fees_and_commission
end
#api :POST, '/fees_and_commissions', 'Create fees_and_commission'
param_group :fees_and_commission
def create
@fees_and_commission = FeesAndCommission.new(fees_and_commission_params)
if @fees_and_commission.save
render json: @fees_and_commission, status: :created, location: @fees_and_commission
else
render json: @fees_and_commission.errors, status: :unprocessable_entity
end
end
#api :PUT, '/fees_and_commissions/:id', 'Update fees_and_commission'
param_group :fees_and_commission
def update
if @fees_and_commission.update(fees_and_commission_params)
render json: @fees_and_commission
else
render json: @fees_and_commission.errors, status: :unprocessable_entity
end
end
#api :DELETE, '/fees_and_commissions/:id', 'Destroy fees_and_commission'
def destroy
@fees_and_commission.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_fees_and_commission
@fees_and_commission = FeesAndCommission.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def fees_and_commission_params
params.require(:fees_and_commission).permit(:amount_from, :amount_to, :amount, :percentage, :percent_based, :active, :fc_type, :rank, :money_type, :tansaction_type, :sending_country_id, :receiving_country_id)
end
end
|
class RemoveSizeFromAnimal < ActiveRecord::Migration
def change
remove_column :animals, :size, :integer
end
end
|
class InvestorNomenclature < ApplicationRecord
validates :name, presence: true, format: { without: /(;|,|\/)/, message: "les caractères ; et , ne sont pas autorisés" }
def self.sectors
InvestorNomenclature.where(type_nomenclature: "sector").order(:name)
end
def self.zones
InvestorNomenclature.where(type_nomenclature: "zone").order(:name)
end
def self.nature_operations
InvestorNomenclature.where(type_nomenclature: "nature_operation").order(:name).pluck(:name)
end
def self.type_operations
InvestorNomenclature.where(type_nomenclature: "type_operation").order(:name).pluck(:name)
end
end
|
# frozen_string_literal: true
# This file is part of IPsec packetgen plugin.
# See https://github.com/sdaubert/packetgen-plugin-ipsec for more informations
# Copyright (c) 2018 Sylvain Daubert <sylvain.daubert@laposte.net>
# This program is published under MIT license.
module PacketGen
module Plugin
# Version of ipsec plugin
IPSEC_VERSION = '1.0.3'
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.