text stringlengths 10 2.61M |
|---|
class ReportMailMailer < ApplicationMailer
def notify_user(report)
@report = report
mail(to: @report.email, subject: "VRS: Report sent")
end
def notify_admin(admin)
@admin = admin
mail(to: @admin.email, subject: "VRS: New Report")
end
end
|
class AddSideDealTitle < ActiveRecord::Migration
def self.up
add_column :products, :side_deal_title, :string
end
def self.down
remove_column :products, :side_deal_title
end
end |
require_relative '../test_helper'
class RelationshipTest < ActiveSupport::TestCase
def setup
super
Sidekiq::Testing.inline!
@team = create_team
@project = create_project team: @team
end
test "should move secondary item to same folder as main" do
RequestStore.store[:skip_cached_field_update] = false
t = create_team
p1 = create_project team: t
p2 = create_project team: t
pm1 = create_project_media team: t, project: p1
pm2 = create_project_media team: t, project: p2
assert_equal p1, pm1.reload.project
assert_equal p2, pm2.reload.project
assert_equal 1, p1.reload.medias_count
assert_equal 1, p2.reload.medias_count
r = create_relationship relationship_type: Relationship.confirmed_type, source_id: pm1.id, target_id: pm2.id
assert_equal p1, pm1.reload.project
assert_equal p1, pm2.reload.project
assert_equal 1, p1.reload.medias_count
assert_equal 0, p2.reload.medias_count
end
test "should create relationship between items with same media" do
t = create_team
m = create_valid_media
pm1 = create_project_media media: m, team: t
pm2 = ProjectMedia.new
pm2.media = m
pm2.team = t
pm2.save(validate: false)
create_relationship source_id: pm1.id, target_id: pm2.id, relationship_type: Relationship.confirmed_type
end
test "should update sources_count and parent_id for confirmed item" do
setup_elasticsearch
t = create_team
pm_s = create_project_media team: t
pm_t = create_project_media team: t
r = create_relationship source_id: pm_s.id, target_id: pm_t.id, relationship_type: Relationship.suggested_type
sleep 2
es_t = $repository.find(get_es_id(pm_t))
assert_equal pm_t.id, es_t['parent_id']
assert_equal pm_t.reload.sources_count, es_t['sources_count']
assert_equal 0, pm_t.reload.sources_count
# Confirm item
r.relationship_type = Relationship.confirmed_type
r.save!
sleep 2
es_t = $repository.find(get_es_id(pm_t))
assert_equal r.source_id, es_t['parent_id']
assert_equal pm_t.reload.sources_count, es_t['sources_count']
assert_equal 1, pm_t.reload.sources_count
r.destroy!
es_t = $repository.find(get_es_id(pm_t))
assert_equal pm_t.id, es_t['parent_id']
end
test "should set cluster" do
t = create_team
u = create_user
create_team_user team: t, user: u, role: 'admin'
s = create_project_media team: t
t = create_project_media team: t
s_c = create_cluster project_media: s
s_c.project_medias << s
t_c = create_cluster project_media: t
t_c.project_medias << t
User.stubs(:current).returns(u)
create_relationship source_id: s.id, target_id: t.id, relationship_type: Relationship.confirmed_type
assert_nil Cluster.where(id: t_c.id).last
assert_equal [s.id, t.id].sort, s_c.reload.project_media_ids.sort
User.unstub(:current)
end
test "should remove suggested relation when same items added as similar" do
team = create_team
s = create_project_media team: team
t = create_project_media team: team
r = create_relationship source_id: s.id, target_id: t.id, relationship_type: Relationship.suggested_type
r2 = create_relationship source_id: s.id, target_id: t.id, relationship_type: Relationship.confirmed_type
assert_nil Relationship.where(id: r.id).last
assert_not_nil Relationship.where(id: r2.id).last
assert_raises ActiveRecord::RecordInvalid do
create_relationship source_id: s.id, target_id: t.id, relationship_type: Relationship.suggested_type
end
end
test "should verify versions and ES for bulk-update" do
with_versioning do
setup_elasticsearch
RequestStore.store[:skip_cached_field_update] = false
t = create_team
u = create_user
create_team_user team: t, user: u, role: 'admin'
with_current_user_and_team(u, t) do
# Try to create an item with title that trigger a version metadata error(CV2-2910)
pm_s = create_project_media team: t, quote: "Rahul Gandhi's interaction with Indian?param:test&Journalists Association in London"
pm_t1 = create_project_media team: t
pm_t2 = create_project_media team: t
pm_t3 = create_project_media team: t
r1 = create_relationship source_id: pm_s.id, target_id: pm_t1.id, relationship_type: Relationship.suggested_type
r2 = create_relationship source_id: pm_s.id, target_id: pm_t2.id, relationship_type: Relationship.suggested_type
r3 = create_relationship source_id: pm_s.id, target_id: pm_t3.id, relationship_type: Relationship.suggested_type
# Verify unmatched
assert_equal 0, pm_s.reload.unmatched
assert_equal 0, pm_t1.reload.unmatched
assert_equal 0, pm_t2.reload.unmatched
assert_equal 0, pm_t3.reload.unmatched
# Verify cached fields
sleep 2
es_s = $repository.find(get_es_id(pm_s))
assert_equal 3, pm_s.suggestions_count
assert_equal pm_s.suggestions_count, es_s['suggestions_count']
relations = [r1, r2]
ids = relations.map(&:id)
updates = { action: "accept", source_id: pm_s.id }
assert_difference 'Version.count', 2 do
Relationship.bulk_update(ids, updates, t)
end
assert_equal Relationship.suggested_type, r3.reload.relationship_type
assert_equal Relationship.confirmed_type, r1.reload.relationship_type
assert_equal Relationship.confirmed_type, r2.reload.relationship_type
# Verify confirmed_by
assert_equal [u.id], Relationship.where(id: ids).map(&:confirmed_by).uniq
# Verify cached fields
assert_equal 1, pm_s.suggestions_count
assert_equal 1, pm_s.suggestions_count(true)
sleep 2
# Verify ES
es_s = $repository.find(get_es_id(pm_s))
es_t = $repository.find(get_es_id(pm_t1))
assert_equal r1.source_id, es_t['parent_id']
assert_equal pm_t1.reload.sources_count, es_t['sources_count']
assert_equal 1, pm_t1.reload.sources_count
assert_equal pm_s.suggestions_count, es_s['suggestions_count']
# Verify unmatched
assert_equal 0, pm_s.reload.unmatched
assert_equal 0, pm_t1.reload.unmatched
assert_equal 0, pm_t2.reload.unmatched
assert_equal 0, pm_t3.reload.unmatched
end
end
end
test "should bulk-reject similar items" do
RequestStore.store[:skip_cached_field_update] = false
with_versioning do
setup_elasticsearch
t = create_team
u = create_user
p = create_project team: t
p2 = create_project team: t
create_team_user team: t, user: u, role: 'admin'
with_current_user_and_team(u, t) do
pm_s = create_project_media team: t, project: p
pm_t1 = create_project_media team: t, project: p
pm_t2 = create_project_media team: t, project: p
pm_t3 = create_project_media team: t, project: p
r1 = create_relationship source_id: pm_s.id, target_id: pm_t1.id, relationship_type: Relationship.suggested_type
r2 = create_relationship source_id: pm_s.id, target_id: pm_t2.id, relationship_type: Relationship.suggested_type
r3 = create_relationship source_id: pm_s.id, target_id: pm_t3.id, relationship_type: Relationship.suggested_type
relations = [r1, r2]
ids = relations.map(&:id)
updates = { source_id: pm_s.id }
assert_difference 'Version.count', 2 do
Relationship.bulk_destroy(ids, updates, t)
end
assert_equal 1, pm_t1.reload.unmatched
assert_equal 1, pm_t2.reload.unmatched
assert_equal 0, pm_t3.reload.unmatched
assert_equal 0, pm_s.reload.unmatched
# Verify cached fields
assert_not pm_t1.is_suggested
assert_not pm_t1.is_suggested(true)
r3.destroy!
assert_equal 1, pm_t3.reload.unmatched
assert_equal 1, pm_s.reload.unmatched
end
end
end
test "should inherit report when pinning new main item" do
t = create_team
pm1 = create_project_media team: t
create_claim_description project_media: pm1
pm2 = create_project_media team: t
r = create_relationship source_id: pm1.id, target_id: pm2.id, relationship_type: Relationship.confirmed_type
publish_report(pm1)
assert_not_nil pm1.get_dynamic_annotation('report_design')
assert_nil pm2.get_dynamic_annotation('report_design')
r = Relationship.find(r.id)
r.source_id = pm2.id
r.target_id = pm1.id
r.save!
assert_nil pm1.get_dynamic_annotation('report_design')
assert_not_nil pm2.get_dynamic_annotation('report_design')
end
test "should pin item when both have claims" do
t = create_team
pm1 = create_project_media team: t
create_claim_description project_media: pm1
pm2 = create_project_media team: t
create_claim_description project_media: pm2
r = create_relationship source_id: pm1.id, target_id: pm2.id, relationship_type: Relationship.confirmed_type
assert_nothing_raised do
r = Relationship.find(r.id)
r.source_id = pm2.id
r.target_id = pm1.id
r.save!
end
end
test "should not attempt to update source count if source does not exist" do
r = create_relationship relationship_type: Relationship.confirmed_type
r.source.delete
assert_nothing_raised do
r.reload.send :update_counters
end
end
test "should cache the name of who created a similar item" do
RequestStore.store[:skip_cached_field_update] = false
t = create_team
u = create_user is_admin: true
pm1 = create_project_media team: t
pm2 = create_project_media team: t
r = nil
with_current_user_and_team(u, t) do
r = create_relationship source_id: pm1.id, target_id: pm2.id, relationship_type: Relationship.confirmed_type, user: nil
end
assert_queries(0, '=') { assert_equal u.name, pm2.added_as_similar_by_name }
Rails.cache.delete("check_cached_field:ProjectMedia:#{pm2.id}:added_as_similar_by_name")
assert_queries(0, '>') { assert_equal u.name, pm2.added_as_similar_by_name }
r.destroy!
assert_queries(0, '=') { assert_nil pm2.added_as_similar_by_name }
end
test "should avoid circular relationship" do
t = create_team
pm1 = create_project_media team: t
pm2 = create_project_media team: t
assert_nothing_raised do
create_relationship source_id: pm1.id, target_id: pm2.id
end
assert_raises 'ActiveRecord::RecordNotUnique' do
create_relationship source_id: pm2.id, target_id: pm1.id
end
pm3 = create_project_media
assert_raises 'ActiveRecord::RecordInvalid' do
create_relationship source_id: pm3.id, target_id: pm3.id
end
end
end
|
class CreateSubscriptions < ActiveRecord::Migration[5.2]
def change
create_table :subscriptions do |t|
t.string :plan, default: "FREE"
t.integer :amount, default: 0
t.datetime :expiring_date
t.datetime :start_date
t.integer :boost, default: 0
t.integer :priorities, default: 0
t.integer :user_id
t.timestamps
end
add_index :subscriptions, :user_id
end
end
|
class Accessory < ApplicationRecord
belongs_to :cospul_detail
validates :cospul_detail , presence: true
validates :name , presence: true, length: { maximum: 200 }
end
|
module Reports
class PatientState < Reports::View
self.table_name = "reporting_patient_states"
belongs_to :patient
enum htn_care_state: {
dead: "dead",
under_care: "under_care",
lost_to_follow_up: "lost_to_follow_up"
}, _prefix: :htn_care_state
def self.materialized?
true
end
def self.by_assigned_region(region_or_source)
region = region_or_source.region
where("assigned_#{region.region_type}_region_id" => region.id)
end
def self.by_month_date(month_date)
where(month_date: month_date)
end
end
end
|
class RemoveIsSuspensionFromEuDecisionTypes < ActiveRecord::Migration
def up
remove_column :eu_decision_types, :is_suspension
end
def down
add_column :eu_decision_types, :is_suspension, :boolean
end
end
|
class CreateCustomerItems < ActiveRecord::Migration
def change
create_table :customer_items do |t|
t.integer :customer_id
t.integer :customer_field_id
t.string :value_name
t.timestamps
end
add_index :customer_items, :customer_id
add_index :customer_items, :customer_field_id
end
end
|
class Task < ApplicationRecord
belongs_to :commitment
belongs_to :user
has_one :tasks_abstract
attr_accessor :user_name, :commitment_name, :user_id, :commitment_date # Agregar cualquier otro al metodo as_json de abajo
# Sobreescribir la funcion as_json
def as_json options=nil
options ||= {}
options[:methods] = ((options[:methods] || []) + [:user_name, :commitment_name, :user_id, :commitment_date])
super options
end
end
|
class AbstractDirectory
include Mongoid::Document
belongs_to :site
belongs_to :directory, class_name: "AbstractDirectory"
has_many :files, class_name: "AbstractFile"
has_many :directories, class_name: "AbstractDirectory"
field :path
def name
File.basename(path)
end
def extension
File.extname(path)
end
end
|
class User < ApplicationRecord
validates :firstname, :lastname, :email, presence: true
has_many :tasks
def due_today
self.tasks.select do |t|
t.due_date.to_date == DateTime.now.to_date
end
end
end
|
class TeamMemberPolicy < ApplicationPolicy
delegate :event, :user_con_profile, to: :record
delegate :convention, to: :event
def read?
return true if oauth_scoped_disjunction do |d|
d.add(:read_events) do
EventPolicy.new(authorization_info, event).read?
end
d.add(:read_conventions) do
has_convention_permission?(convention, 'update_event_team_members')
end
end
super
end
def manage?
return true if oauth_scoped_disjunction do |d|
d.add(:read_events) { team_member_for_event?(event) }
d.add(:read_conventions) do
has_convention_permission?(convention, 'update_event_team_members')
end
end
super
end
class Scope < Scope
def resolve
return scope.all if oauth_scope?(:read_conventions) && site_admin?
return scope.none unless oauth_scope?(:read_events)
disjunctive_where do |dw|
dw.add(event: events_where_team_member)
dw.add(event: EventPolicy::Scope.new(authorization_info, Event.all).resolve)
dw.add(event: Event.where(
convention: conventions_with_permission('update_event_team_members')
))
end
end
end
end
|
class RenameListaLivroToBookList < ActiveRecord::Migration[6.0]
def up
rename_column :lista_livros, :lista_id, :list_id
rename_column :lista_livros, :livro_id, :book_id
rename_table :lista_livros, :book_lists
end
def down
rename_column :lista_livros, :list_id, :lista_id
rename_column :lista_livros, :book_id, :livro_id
rename_table :book_lists, :lista_livros
end
end
|
json.array!(@qualifications) do |qualification|
json.extract! qualification, :id, :doctor_id, :title
json.url qualification_url(qualification, format: :json)
end
|
class DispenserComplementaryDrink < ActiveRecord::Migration
def change
add_column :dispensers, :complementary_drink, :boolean, default: false
end
end
|
class Item < ActiveRecord::Base
belongs_to :inventory
delegate :owner, to: :inventory
end |
class StorageType < ActiveRecord::Base
has_many :storages
validates :length, presence: true, numericality: true
validates :width, presence: true, numericality: true
validates :price, presence: true, numericality: true
validates :late_fee, presence: true, numericality: true
def area
self.length * self.width
end
def title
self.length.to_s() + " X " + self.width.to_s()
end
end
|
class ChangeDescriptionAndAvailabilityToCampingCars < ActiveRecord::Migration[6.0]
def change
change_column :camping_cars, :availability, 'boolean USING CAST(availability AS boolean)'
change_column :camping_cars, :description, :text
end
end
|
class PreparationsController < ApplicationController
before_action :set_preparation, only: [:show, :edit, :update, :destroy]
def index
@preparations = Preparation.paginate(page: params[:page])
end
def show
end
def new
@preparation = Preparation.new
end
def edit
end
def create
@preparation = Preparation.new(preparation_params)
respond_to do |format|
if @preparation.save
format.html { redirect_to @preparation, notice: 'Preparation was successfully created.' }
format.json { render action: 'show', status: :created, location: @preparation }
else
format.html { render action: 'new' }
format.json { render json: @preparation.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @preparation.update(preparation_params)
format.html { redirect_to @preparation, notice: 'Preparation was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @preparation.errors, status: :unprocessable_entity }
end
end
end
def destroy
@preparation.destroy
respond_to do |format|
format.html { redirect_to preparations_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_preparation
@preparation = Preparation.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def preparation_params
params.require(:preparation).permit(:recipe_id, :step, :instruction)
end
end
|
#!/usr/bin/env ruby
def shared_examples_for(*args)
end
require "bundler/setup"
require "irb"
require "syntax_highlighting"
SyntaxHighlighting.configure do |config|
config.language_files = Dir.glob(
Bundler.root.join(
"resources",
"syntax_highlighting",
"**",
"*.tmLanguage.json"
)
)
config.theme_file = Bundler.root.join(
"resources",
"syntax_highlighting",
"themes",
"ayu-light",
"ayu-light.sublime-color-scheme"
)
end
def highlighter
@highlighter ||= SyntaxHighlighting::Highlighter.new
end
puts "Example usage:"
puts "```"
puts "highlighter.parse(\"# hello world\", :ruby)"
puts "```"
puts ""
IRB.start
|
require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
# 各テストが実行される直前で実行されるメソッド
def setup
@base_title = "Ruby on Rails Tutorial Sample App"
end
test "should get root" do
get root_path
assert_response :success
end
test "should get help" do
get helpp_path
assert_response :success
# タイトルのテスト
assert_select "title", "Help | #{@base_title}"
end
# 新規テスト
test "should get about" do
get about_path
assert_response :success
# タイトルのテスト
assert_select "title", "About | #{@base_title}"
end
# 問合せページ
test "should get contract" do
get contract_path
assert_response :success
# タイトルのテスト
assert_select "title", "Contract | #{@base_title}"
end
# コンタクト
test "should get contact" do
get contact_path
assert_response :success
assert_select "title", "Contact | Ruby on Rails Tutorial Sample App"
end
end
|
class CampaignChannelsController < ApplicationController
def index
# this route receives AJAX $.get requests to update
# the New Report form fields on home#index
@campaign_channels = CampaignChannel.where(campaign_id: params[:campaign_id])
respond_to do |format|
format.js
end
end
end
|
class WorkCenter < ApplicationRecord
has_many :doctors
has_many :receptionists
has_many :managers
has_many :events, through: :doctors
def status_text
self.status? ? "Activo" : "Inactivo"
end
end
|
# frozen_string_literal: true
class AddTypeToTeacherSetsTable < ActiveRecord::Migration[4.2]
def change
add_column :teacher_sets, :set_type, :string, :limit => 20 # Subject Set / Single-Item Set
add_index :teacher_sets, ["set_type"], :name => "index_teacher_set_type"
end
end
|
json.questions do
json.array!(@all_questions) do |question|
json.extract! question, :id, :title, :body, :topic, :user, :answers
json.url question_url(question, format: :json)
end
end
|
class CreateAnnotationOnPostgres < ActiveRecord::Migration[4.2]
def change
create_table :annotations, force: true do |t|
t.string :annotation_type, null: false
t.integer :version_index
t.string :annotated_type
t.integer :annotated_id
t.string :annotator_type
t.integer :annotator_id
t.text :entities
t.text :data
t.string :file
t.integer :lock_version, default: 0, null: false
t.boolean :locked, default: false
t.text :attribution
t.text :fragment
t.timestamps
end
add_index :annotations, :annotation_type
add_index :annotations, [:annotated_type, :annotated_id]
add_index :annotations, :annotation_type, name: 'index_annotation_type_order', order: { name: :varchar_pattern_ops }
end
end
|
require 'spec_helper'
describe Converters::ServiceConverter do
fixtures :services
fixtures :app_categories
let(:service1) { services(:service1) }
let(:service2) { services(:service2) }
subject { described_class.new(service1) }
describe '#to_compose_hash' do
it 'creates a hash from the given Service' do
expect(subject.to_compose_hash).to be_a Hash
end
it 'copies the service name' do
expect(subject.to_compose_hash.keys.first).to eq service1.name
end
it 'copies the exposed ports' do
expect(subject.to_compose_hash.values.first['expose']).to eq service1.expose
end
it 'converts the service ports' do
service1.ports << {
'host_interface' => '127.0.0.1',
'host_port' => 8080,
'container_port' => 8081,
'proto' => 'UDP'
}
expect(subject.to_compose_hash.values.first['ports']).to eq(['3306:3306', '127.0.0.1:8080:8081/udp'])
end
it 'converts the service links when present'do
service1.links << ServiceLink.new(linked_to_service: service2, alias: 'other')
expect(subject.to_compose_hash.values.first['links']).to eq(['my-other-service:other'])
end
it 'does not include the service links when not present'do
expect(subject.to_compose_hash.values.first['links']).to be_nil
end
it 'converts the service environment variables'do
expect(subject.to_compose_hash.values.first['environment']).to eq(['MYSQL_ROOT_PASSWORD=pass@word01'])
end
it 'converts the service volumes'do
expect(subject.to_compose_hash.values.first['volumes']).to eq(['/var/panamax:/var/app/panamax'])
end
it 'converts the service volumes_from'do
service1.volumes_from << SharedVolume.new(exported_from_service: service2)
expect(subject.to_compose_hash.values.first['volumes_from']).to eq(['my-other-service'])
end
it 'copies the service command' do
expect(subject.to_compose_hash.values.first['command']).to eq(service1.command)
end
end
describe '#to_image' do
it 'creates an Image from the given Service' do
expect(subject.to_image).to be_a Image
end
it 'copies the service name' do
expect(subject.to_image.name).to eq service1.name
end
it 'copies the service description' do
expect(subject.to_image.description).to eq service1.description
end
it 'copies the category names' do
expect(subject.to_image.categories).to eq service1.categories.map(&:name)
end
it 'copies the service from string' do
expect(subject.to_image.source).to eq service1.from
end
it 'copies the service ports' do
expect(subject.to_image.ports).to eq service1.ports
end
it 'copies the service expose ports' do
expect(subject.to_image.expose).to eq service1.expose
end
it 'copies the service environment' do
expect(subject.to_image.environment).to eq service1.environment
end
it 'copies the service volumes' do
expect(subject.to_image.volumes).to eq service1.volumes
end
it 'copies the service command' do
expect(subject.to_image.command).to eq service1.command
end
it 'copies the service type' do
expect(subject.to_image.type).to eq service1.type
end
context 'when handling linked services' do
before do
service1.links.create(linked_to_service: services(:service2), alias: 'DB')
end
it 'populates the image links' do
expect(subject.to_image.links).to eql [{ 'service' => 'my-other-service', 'alias' => 'DB' }]
end
end
context 'when handling service categories' do
before do
service1.categories.create(app_category: app_categories(:category1))
end
it 'populates the image categories' do
expect(subject.to_image.categories).to eq [app_categories(:category1).name]
end
end
context 'when handling services with volumes_from' do
before do
service1.volumes_from.create(exported_from_service: services(:service2))
end
it 'populates the image with volumes_from' do
expect(subject.to_image.volumes_from).to eql [{ 'service' => 'my-other-service' }]
end
end
end
end
|
class PendingMembershipsController < ApplicationController
def create
params[:user_id] ||= current_user.id
@pending_membership = PendingMembership.new(organization_id: params[:organization_id], user_id: params[:user_id])
#authorize @pending_membership
respond_to do |format|
@pending_membership.save
format.html do
if params[:user_id] == current_user.id
redirect_to :back, notice: 'Requested to join the organization.'
else
redirect_to :back, notice: 'User invited to join the organization'
end
end
format.json do
render :show, status: :created, location: @pending_membership
end
end
end
def accept
@pending_membership = PendingMembership.find(params[:id])
#authorize @pending_membership
@membership = Membership.create(organization_id: @pending_membership.organization_id, user_id: @pending_membership.user_id, permission: @pending_membership.permission)
@pending_membership.destroy
redirect_to @membership.organization, notice: 'Member was added to organization'
end
def destroy
@pending_membership = PendingMembership.find(params[:id])
organization_id = @pending_membership.organization_id
#authorize @pending_membership
@pending_membership.destroy
redirect_to Organization.friendly.find(organization_id)
end
end
|
class ChangeColumn < ActiveRecord::Migration
def change
change_column :products, :inventory, :integer, :default => 1
end
end
|
class Admin::SellsController < ApplicationController
before_action :authenticate_admin!
def index
@sells = Sell.with_deleted.page(params[:page]).per(5)
end
def show
@sell = Sell.with_deleted.find(params[:id])
@sell_detail = SellDetail.with_deleted.find(params[:id])
@sell_details = SellDetail.with_deleted.where(sell_id: @sell.id)
end
def create
end
def update
@sell = Sell.find(params[:id])
@sell.update(sell_params)
redirect_to admin_sells_path(@sell)
end
private
def sell_params
params.require(:sell).permit(:ship_l_name, :ship_f_name, :ship_code, :ship_address, :ship_tel, :pay, :ship_status)
end
end
|
def numbers()
a = 123
a= 0123 # octal
a = 0x123 # hex
a,b,c = 1,2,3
a = 0b111
a = a ** a #^2
-1/3 # is -1
-1 % 3 # is 2
3.to_s
3.odd?
3.lcm
3.+
3.class
3.methods #=>
end
def symbols()
a = :symbols
a.to_s
s = "s"
s.intern # to symbol
end
def strings()
puts "The sum 6+3 is #{6+3}"
puts %Q/The sum 6+3 is #{6+3}/
a = "Hello"
a.empty?
a.starts_with? "H"
a.include?
a.length
a.to_f
a.to_i
a.split # [H, e, ...]
a.upcase # HELLO
a.downcase # hello
a.capitalize # Hello
a.clear # ""
a.replace "hi" # hi
a.chomp "l" # helo, removes last l
a.chop # hell
a.slice start=2, length=2 # returns ll
a.sub "l", "k" # hekko
a.gsub "l", "l" # heklo
end
def array()
a = Array.new
a = [6, 1, 5, 4]
a[-1] # 4
a.length
a[2,3] # start num
# add remove from end
a.push
a.pop
# add remove from beginning
a.unshift(10, 40)
a.shift
a = [1]
b = [2]
a = a+b
a.reverse
a.sort().shuffle
index = 0
names = Array.new
while name = gets
name.chomp!.upcase!
names[index] = name
index += 1
end
puts "The sorted array:"puts names.sort
a = ["hi", "a"]
a = a.map {|name| name.capitalize} # ["Hi", "A"]
[1, 2, 3].reduce {|sum, i| sum + i}
[1, 2, 3].reduce 0 do |sum, i|
sum + i
end
end
# blocks
def fibUpTo(max)
i1, i2 = 1, 1
while i1 <= max
yield i1 if block_given?
i1, i2 = i2, i1+i2
end
end
fibUpTo(1000) { |f| print f, " " }
def range()
a = 0..4
a.to_a
a.last # is 4
a.last 2 # is [3, 4]
a === 3 # true
3 === a # false
a === 8 #false
b = "car"..."cat"
b.include? "cas" # true
b.cover? "casando" # true
end
def booleans()
fa = false || nil
fa = true and false # fa is false, and then true
end
def branch()
if true
elsif true
else
end
puts "true" if true
end
def loop()
while true
end
until false
end
end
def hash()
h = Hash.new(0)
h = {'k=>' 2,
'l' => 3 }
list = ["cake", "bake", "cookie", "car", "apple"]
# Group by string length:
groups = Hash.new {|h,k| h[k] = []}
list.each {
|v| groups[v.length] << v
}
groups
# filter methods
a.delete_if { |k, v| v =~ /[aeiou]/ }
a.keep_if { |k, v| v =~ /[aeiou]/ }
end
def compar()
3 <=> 2 # returns 1
s1, s2 = "h", "h"
s1==s2 # true # call this on primitive types
s1.equal? s2 # false # call this on object types
s1.object_id is the addr # addr is 2n+1 for numbers
end
# LHS Gather, RHS SPLIT
def splat(*names) # var arg
a, b, *c = [1, 9, 2, 3, 4]
a, b, c = [1, 9, 2, 3, 4] # 3 and 4 lost
end
a = [1, 2, 3]
splat(*a)
=begin
multiline comment
"Hi #{name}" + "!" #=> "Hi Liam!"
=end
__FILE__ # filename
__LINE__ # line number
def lists()
list = [1, 2, 3]
list.size #=> 3
end
|
class Candidatura < ApplicationRecord
default_scope -> { order(created_at: :desc) }
mount_uploader :foto, PictureUploader
validates :foto, presence: true
validates :name, presence: true
validates :user_id, presence: true
end
|
class Industry < ActiveRecord::Base
has_many :clients
def name
"#{code}||#{title}"
end
end
|
def input_students
students = {}
student_count = []
cohorts = ["january", "february", "march", "april", "may", "june", "july",
"august", "september", "october", "november", "december"]
puts "Please enter the names of the student & cohort"
puts "To finish, just hit return twice"
user_input = gets.strip
user = user_input.split()
while !user_input.empty?
name = user[0]
student_count << name
if user.count < 2
cohort = "september"
else
cohort = user[1]
end
if cohorts.include? cohort
if students[cohort.to_sym].nil?
students[cohort.to_sym] = [name]
else
students[cohort.to_sym] << name
end
if students.count == 1
puts "Now we have #{student_count.count} student"
else
puts "Now we have #{student_count.count} students"
end
elsif !cohorts.include? user[1]
puts "You entered a month that is not recognised, add name & cohort again"
end
user_input = gets.strip
user = user_input.split()
end
students
end
=begin
def student_initial
puts "Please enter the intial of the students you want to print"
initial = gets.chomp
return initial
end
=end
def print_header
puts "The students of Villains Academy"
puts "------------------"
end
def student_list(students)
students.each { |cohort, students|
puts cohort.capitalize
puts students
}
end
def print_footer(names)
student_number = 0
names.each { |cohort, names|
names.each { |name|
student_number += 1
}
}
if student_number == 0
return
elsif student_number == 1
print "Overall, we have #{student_number} great student"
else
print "Overall, we have #{student_number} great students"
end
end
students = input_students
#si = student_initial
print_header
student_list(students)
print_footer(students)
|
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post, optional: true
belongs_to :message, optional: true
belongs_to :parent, class_name: 'Comment', optional: true
has_many :likes, dependent: :destroy
has_many :replies,
class_name: 'Comment', foreign_key: :parent_id, dependent: :destroy
has_one :notification, dependent: :destroy
validates :content, presence: true
validates :user, presence: true
end
|
require 'spec_helper'
describe HomeController do
describe "GET 'index'" do
context 'user not signed in' do
before { get :index }
subject { response }
it do
should render_template('index')
should be_success
end
end
context 'user signed in' do
login_user
before { get :index }
subject { response }
it do
should render_template('index_signed_in')
should be_success
end
end
end
end
|
class AddIdToAlumnos < ActiveRecord::Migration
def change
add_column :alumnos, :id, :primary_key
end
end
|
class AddPlannedDisbursements < ActiveRecord::Migration[6.0]
def change
create_table :planned_disbursements, id: :uuid do |t|
t.string :planned_disbursement_type
t.date :period_start_date
t.date :period_end_date
t.decimal :value, precision: 13, scale: 2
t.string :currency
t.string :providing_organisation_name
t.string :providing_organisation_type
t.string :providing_organisation_reference
t.string :receiving_organisation_name
t.string :receiving_organisation_type
t.string :receiving_organisation_reference
t.boolean :ingested, default: false
t.references :parent_activity, type: :uuid
t.timestamps
end
end
end
|
require 'aethyr/core/objects/exit'
#Like an Exit, but different.
#
#Portals can be entered, do not show up on the list of exits,
class Portal < Exit
#Creates a new portal. args same as Exit.
def initialize(exit_room = nil, *args)
super
@generic = 'portal'
@article = 'a'
@visible = false
@show_in_look = "A portal to the unknown stands here."
end
#Message when a player enters through the portal.
#If info.entrance_message has not been set, provides a generic message.
#
#Otherwise, info.entrance_message can be used to create custom messages.
#Use !name in place of the player's name.
#
#If something more complicated is required, override this method in a subclass.
def entrance_message player, action = nil
if info.entrance_message
info.entrance_message.gsub(/(!name|!pronoun\(:(\w+)\)|!pronoun)/) do
case $1
when "!name"
player.name
when "!pronoun"
player.pronoun
else
if $2
player.pronoun($2.to_sym)
end
end
end
else
case action
when "jump"
"#{player.name} jumps in over #{self.name}."
when "climb"
"#{player.name} comes in, climbing #{self.name}."
when "crawl"
"#{player.name} crawls in through #{self.name}."
else
"#{player.name} steps through #{self.name}."
end
end
end
#Message when leaving in the given direction. Works the same way as #entrance_message
def exit_message player, action = nil
if info.exit_message
info.exit_message.gsub(/(!name|!pronoun\(:(\w+)\)|!pronoun)/) do
case $1
when "!name"
player.name
when "!pronoun"
player.pronoun
else
if $2
player.pronoun($2.to_sym)
end
end
end
else
case action
when "jump"
"#{player.name} jumps over #{self.name}."
when "climb"
"#{player.name} climbs #{self.name}."
when "crawl"
"#{player.name} crawls out through #{self.name}."
else
"#{player.name} steps through #{self.name} and vanishes."
end
end
end
#The message sent to the player as they pass through the portal.
def portal_message player, action = nil
if info.portal_message
info.portal_message.gsub(/(!name|!pronoun\(:(\w+)\)|!pronoun)/) do
case $1
when "!name"
player.name
when "!pronoun"
player.pronoun
else
if $2
player.pronoun($2.to_sym)
end
end
end
else
case action
when "jump"
"Gathering your strength, you jump over #{self.name}."
when "climb"
"You reach up and climb #{self.name}."
when "crawl"
"You stretch out on your stomach and crawl through #{self.name}."
else
"You boldly step through #{self.name}."
end
end
end
def peer
self.long_desc
end
end
|
require 'rails_helper'
describe "tickets" do
it "belongs to a board" do
board = Board.create(title: "my project")
ticket = board.tickets.create(title: "todo", description:"soon", status:0)
expect(ticket.board).to eq(board)
end
end
|
class Tag < ActiveRecord::Base
has_and_belongs_to_many :articles
validates_presence_of :name
before_save :touch_articles
def touch_articles
self.articles.touch
end
end
|
node['fileserver']['ingredients'].each do |data_bag,attrs|
# getting all the the artifacts may be expensive
# only retrieve if it hasn't been set in a role
Chef::Log.fatal node['fileserver']['ingredients'][data_bag]
if not node['fileserver']['ingredients'][data_bag]['version']
all_artifacts = search(data_bag,"*:*")
node.default['fileserver']['ingredients'][data_bag]['version']=all_artifacts.map{|v|
v['version']}.flatten.uniq.sort.last
end
search(data_bag,"version:#{node['fileserver']['ingredients'][data_bag]['version']}").each do |ing|
cache_file = File.join(Chef::Config[:file_cache_path], ing['filename'])
# Populate the cache and checksums
chksumf="#{cache_file}.checksum"
rf = remote_file cache_file do
source ing['source']
checksum ing['checksum']
not_if do
(::File.exists? chksumf) && (open(chksumf).read == ing['checksum'])
end
end
rf.run_action :create
cs=file "#{cache_file}.checksum" do
content ing['checksum']
end
cs.run_action :create
end
end
|
class Review < ApplicationRecord
after_commit on: [:create] do
NotifiyUsersJob.perform_later(self)
end
has_many :notifications, as: :notifiable, dependent: :destroy
belongs_to :recipe
belongs_to :user
default_scope { order(created_at: :desc) }
validates :body, presence: true
end
|
module EmbeddableContent
module Images
class AttributionsProcessor
attr_reader :image_processor
delegate :embedder, :target, :document, :image_catalog, to: :image_processor
delegate :locale, to: :embedder
TARGETS_NEEDING_ATTRIBUTIONS = %i[print].freeze
ATTRIBUTIONS_PARTIAL = 'export/shared/attributions_images'.freeze
ATTRIBUTIONS_NODE_ID = 'image-attributions-node'.freeze
ATTRIBUTIONS_NODE_SELECTOR = "div##{ATTRIBUTIONS_NODE_ID}".freeze
def initialize(image_processor)
@image_processor = image_processor
end
def process!
render_attributions if attributions_required?
end
private
def attributions_required?
TARGETS_NEEDING_ATTRIBUTIONS.include?(target) &&
attributions_node.present? &&
image_catalog.present? &&
attributions.present?
end
def attributions
@attributions =
image_catalog.select(&:attribution).compact
end
def attributions_node
@attributions_node ||= document.css(ATTRIBUTIONS_NODE_SELECTOR).first
end
def render_attributions
attributions_node.replace(attributions_fragment)
end
def attributions_html
I18n.with_locale(locale) { render_html }
end
def render_html
ApplicationController.renderer.render(
partial: ATTRIBUTIONS_PARTIAL,
locals: { image_files: image_catalog }
)
end
def attributions_fragment
@attributions_fragment ||= Nokogiri::HTML.fragment(attributions_html)
end
end
end
end
|
class PaymentMethod < ApplicationRecord
serialize :descriptions, Array
enum payment_type: [:debit, :credit, :bank]
enum card_type: [:visa, :mastercard, :amex, :other]
# Relationships
belongs_to :country
belongs_to :user
# Autocode: Validations
validates :country_id, presence: true
validates :user_id, presence: true
end
|
require 'test_helper'
class UserTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
test "should be invalid" do
user = User.new
assert !user.valid?, "User shoudn't be created"
end
test "should not accept equal user" do
user1 = new(email:'hboaventura@gmail.com', password:'donald')
user1.save
user2 = new(email:'hboaventura@gmail.com', password:'donald')
assert !user2.valid?, "User with same e-mail shound't be created"
end
test "should not accept invalid email" do
user = new(:email => 'teste')
user.valid?
assert user.errors[:email].any?, "invalid :email shouldn't be accepted"
end
test "should not accept empty password" do
user = new(:password => nil)
user.valid?
assert user.errors[:password].any?, "nil :password shouldn't be accepted"
end
test "should not accept short password" do
user = new(:password => "abcde")
user.valid?
assert user.errors[:password].any?, "short :password shouldn't be accepted"
end
private
def new(options={})
User.new({
:email => "email@test.com",
:password => "password",
}.merge(options))
end
end
|
# ===============================================
#
# Compass Configuration File
#
# Creates archived versions of compiled CSS based
# on their MD5 file hash
#
# ===============================================
require 'yaml'
require 'logger'
# Constants
BASE = File.absolute_path(".")
OUTPUT = "_combinedfiles"
MANIFEST = "#{BASE}/sass.yml"
# Compass Config
environment = :production
output_style = :compressed
relative_assets = true
project_path = BASE
sass_dir = "sass"
css_dir = OUTPUT
images_dir = "images"
generated_images_dir = "#{OUTPUT}/img/"
javascripts_dir = "js"
# Return the locations of the CSS file archive
# archivePath, archiveURL
def get_archive_locations(fullPath)
fileHash = get_file_hash(fullPath)
extension = File.extname(fullPath)
archiveURL = "#{OUTPUT}/#{fileHash}#{extension}"
archivePath = "#{BASE}/#{archiveURL}"
return archivePath, archiveURL
end
# Return the MD5 hash of the given file
def get_file_hash(fullPath)
contents = File.read(fullPath)
fileHash = Digest::MD5.hexdigest(contents)
return fileHash
end
# Get an instance of Logger
def get_logger()
# Set up logging
log = ::Logger.new(STDOUT)
log.level = ::Logger::INFO
return log
end
# Read and return the CSS file manifest
def read_manifest()
if not File.exists?(MANIFEST)
return {}
end
f = File.new(MANIFEST, "r")
f.rewind()
yml = f.read()
f.close()
return YAML.load(yml)
end
# Update the CSS file manifest
def write_manifest(fullPath, archiveURL)
manifest = read_manifest()
name = File.basename(fullPath)
manifest[name] = archiveURL
f = File.new(MANIFEST, "w")
yml = manifest.to_yaml()
f.write(yml)
f.close()
end
# Create CSS version archives upon compile
# Sass calls this whenever a CSS compilation occurs
on_stylesheet_saved do |fullPath|
# Calculate archive locations
archivePath, archiveURL = get_archive_locations(fullPath)
# Move File into archive path
File.rename(fullPath, archivePath)
# Write yml file documenting which css file to use
write_manifest(fullPath, archiveURL)
# Log success message
log = get_logger()
log.info("Compiled to #{archivePath}")
end
# Log Sass Syntax Errors
# Sass call this when a compilation error is encountered
on_stylesheet_error do |fullPath, message|
log = get_logger()
log.error("Error compiling #{fullPath}. Message: #{message}")
end
|
class Admin < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable,
:registerable,
:recoverable,
:rememberable,
:validatable
has_many :shops, dependent: :destroy
has_many :favorites, dependent: :destroy
has_many :favorite_shops, through: :favorites, source: :shop
has_many :messages
with_options presence: true, on: :create do
validates :name
with_options format: { with: /\A[a-z0-9]+\z/i } do
validates :password
end
end
with_options presence: true, on: :update do
validates :name
end
def self.guest
find_or_create_by!(name: 'ゲスト', email: 'guest@example.com') do |admin|
admin.password = SecureRandom.hex(10)
end
end
end
|
class AddHistoryToErrors < ActiveRecord::Migration
def change
add_column :errors, :history, :json
end
end
|
require 'spec_helper'
describe 'wlp::deploy_app', :type => :define do
let(:pre_condition){
'
class {"wlp": install_src => "https://public.dhe.ibm.com/downloads/wlp/16.0.0.2/wlp-javaee7-16.0.0.2.zip" }
wlp::server{"testserver": ensure => "present" };
'
}
context 'supported operating systems' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts
end
let :title do
'hello_world.war'
end
context "wlp::deploy_app as dropin" do
let(:params) { { :type => 'dropin', :server => 'testserver', :install_src => '/vagrant/hello_world.war' } }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_archive('hello_world.war').with({
:path => '/opt/ibm/wlp/usr/servers/testserver/dropins/hello_world.war',
:source => '/vagrant/hello_world.war',
:user => 'wlp',
:group => 'wlp'
}) }
end
context "wlp::deploy_app deleting dropin" do
let(:params) { { :type => 'dropin', :server => 'testserver', :install_src => '/vagrant/hello_world.war', :ensure => 'absent' } }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_file('/opt/ibm/wlp/usr/servers/testserver/dropins/hello_world.war').with({
:ensure => 'absent'
}) }
end
context "wlp::deploy_app as static" do
let(:params) { { :type => 'static', :server => 'testserver', :install_src => '/vagrant/hello_world.war' } }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_archive('hello_world.war').with({
:path => '/opt/ibm/wlp/usr/servers/testserver/apps/hello_world.war',
:source => '/vagrant/hello_world.war',
:user => 'wlp',
:group => 'wlp',
:notify => 'Wlp_server_control[testserver]',
}) }
end
context "wlp::deploy_app deleting static" do
let(:params) { { :type => 'static', :server => 'testserver', :install_src => '/vagrant/hello_world.war', :ensure => 'absent' } }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_file('/opt/ibm/wlp/usr/servers/testserver/apps/hello_world.war').with({
:ensure => 'absent',
:notify => 'Wlp_server_control[testserver]',
}) }
end
context "wlp::deploy_app invalid args dropin" do
let(:params) { { :type => 'special', :server => 'testserver', :install_src => '/vagrant/hello_world.war' } }
it { should compile.with_all_deps.and_raise_error(/No matching entry for selector parameter with value 'special'/) }
end
end
end
end
end
|
module VW
class Request < Com::Android::Volley::Toolbox::StringRequest
# part of this class had to be implemented as a Java extension to work around
# what appears to be a RM bug. See request.java
VOLLEY_GET = 0
VOLLEY_POST = 1
VOLLEY_PUT = 2
VOLLEY_DELETE = 3
def self.get_request(url, params, listener)
url = add_params_to_url(url, params)
request_with_params(VOLLEY_GET, url, params, listener).tap do |req|
req.listener = listener
end
end
def self.post_request(url, params, listener)
request_with_params(VOLLEY_POST, url, params, listener).tap do |req|
req.listener = listener
end
end
def self.put_request(url, params, listener)
request_with_params(VOLLEY_PUT, url, params, listener).tap do |req|
req.listener = listener
end
end
def self.delete_request(url, params, listener)
request_with_params(VOLLEY_DELETE, url, params, listener).tap do |req|
req.listener = listener
end
end
def listener=(value)
@listener = value
end
def self.retry_policy
Com::Android::Volley::DefaultRetryPolicy.new(10000, 3, 1)
end
def headers=(headers)
# call into the method defined in the .java file
setHeaders(headers)
end
def parseNetworkResponse(network_response)
@listener.network_response = network_response if @listener
super
end
def self.add_params_to_url(url, params)
if params.blank?
url
else
params_array = params.map do |k, v|
v = Java::Net::URLEncoder.encode(v, "utf-8")
"#{k}=#{v}"
end
"#{url}?#{params_array.join("&")}"
end
end
def self.set_request_for_listener(method, url, params, listener)
# There probably is a much better way then passing all these around like this
listener.request_url = url
listener.request_params = params
listener.request_method = method
end
private
# this is to maintain compatibility with AFMotion - somewhere (possibly in AFNetworking?) the
# keys get flattened out like so:
#
# { user: { email: "x@x.com", password: "pass" } }
# becomes
# { "user[email]" => "x@x.com", "user[password]" => "pass" }
#
# This is not a robust implementation of this, but will serve our needs for now
def self.prepare_params(params)
new_params = {}
params.keys.each do |key|
if params[key].is_a?(Hash)
params[key].keys.each do |inner_key|
new_params["#{key}[#{inner_key}]"] = params[key][inner_key].to_s
end
else
new_params[key.to_s] = params[key].to_s
end
end
new_params
end
def self.request_with_params(method, url, params, listener)
set_request_for_listener method, url, params, listener
Request.new(method, url, listener, listener).tap do |req|
req.setRetryPolicy(retry_policy)
unless method == VOLLEY_GET
params = prepare_params(params)
req.setParams(params)
end
end
end
end
end
|
Gem::Specification.new do |s|
s.name = 'timesheet_rules_engine'
s.version = '0.0.4'
s.date = '2019-04-28'
s.summary = "Timesheet Rules Engine"
s.description = "Timesheet Rules Engine"
s.authors = ["Shawn Lee-Kwong"]
s.email = 'slk@edatanow.com'
s.files = Dir["{lib}/**/*"]
s.homepage =
'http://rubygems.org/gems/timesheet_rules_engine'
s.license = 'MIT'
s.test_files = Dir["spec/**/*"]
s.add_dependency "holidays"
s.add_dependency "activesupport"
end |
class LawAndRegulation < ActiveRecord::Base
has_and_belongs_to_many :type_of_law_and_regulations
has_attached_file :document
validates_attachment_content_type :document, :content_type => ['application/pdf', 'application/msword', 'text/plain', 'application/msexcel', /\Aimage\/.*\Z/, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
end
|
class MonthlyDistrictReport::Hypertension::DistrictData
include MonthlyDistrictReport::Utils
attr_reader :repo, :district, :report_month, :last_6_months
def initialize(district, period_month)
@district = district
@report_month = period_month
@last_6_months = Range.new(@report_month.advance(months: -5), @report_month)
@repo = Reports::Repository.new(district, periods: @last_6_months)
end
def content_rows
[row_data]
end
def header_rows
[[ # row 1
"District",
"Facilities implementing IHCI",
"Total DHs/SDHs",
"Total CHCs",
"Total PHCs",
"Total HWCs/SCs",
"Total hypertension registrations",
"Total assigned hypertension patients",
"Total hypertension patients under care",
"Treatment outcome for hypertension patients under care", *Array.new(3, nil),
"Total registered hypertension patients", *Array.new(5, nil),
"Hypertension patients under care", *Array.new(5, nil),
"New registrations (DH/SDH/CHC)", *Array.new(5, nil),
"New registrations (PHC)", *Array.new(5, nil),
"New registrations (HWC/SC)", *Array.new(5, nil),
"Patient follow-ups", *Array.new(5, nil),
"BP controlled rate", *Array.new(5, nil),
"BP controlled count", *Array.new(5, nil),
"Cumulative registrations at HWCs", *Array.new(2, nil),
"Cumulative patients under care at HWCs", *Array.new(2, nil),
"% of assigned patients at HWCs / SCs (as against district)", *Array.new(2, nil),
"% of patients followed up at HWCs / SCs", *Array.new(2, nil),
"Cumulative assigned patients to HWCs", * Array.new(2, nil)
],
[ # row 2
nil, # "District",
nil, # "Facilities implementing IHCI",
nil, # "Total DHs/SDHs",
nil, # "Total CHCs",
nil, # "Total PHCs",
nil, # "Total HWCs/SCs",
nil, # "Total registrations",
nil, # "Total assigned patients",
nil, # "Total patients under care",
"% BP controlled",
"% BP uncontrolled",
"% Missed Visits",
"% Visits, no BP taken",
*last_6_months.map { |period| format_period(period) }, # "Total registered patients",
*last_6_months.map { |period| format_period(period) }, # "Patients under care",
*last_6_months.map { |period| format_period(period) }, # "New registrations (DH/SDH/CHC)",
*last_6_months.map { |period| format_period(period) }, # "New registrations (PHC)",
*last_6_months.map { |period| format_period(period) }, # "New registrations (HWC/SC)",
*last_6_months.map { |period| format_period(period) }, # "Patient follow-ups",
*last_6_months.map { |period| format_period(period) }, # "BP controlled rate"
*last_6_months.map { |period| format_period(period) }, # "BP controlled count"
*last_6_months.drop(3).map { |period| format_period(period) }, # "Cumulative registrations at HWCs"
*last_6_months.drop(3).map { |period| format_period(period) }, # "Cumulative patients under care at HWCs"
*last_6_months.drop(3).map { |period| format_period(period) }, # "% of assigned patients at HWCs / SCs (as against district)"
*last_6_months.drop(3).map { |period| format_period(period) }, # "% of patients followed up at HWCs / SCs"
*last_6_months.drop(3).map { |period| format_period(period) } # "Cumulative assigned patients to HWCs"
]]
end
private
def row_data
active_facilities = district.facilities.active(month_date: @report_month.to_date)
facility_counts_by_size = active_facilities.group(:facility_size).count
{
"District" => district.name, # "District"
"Facilities implementing IHCI" => active_facilities.count, # "Facilities implementing IHCI"
"Total DHs/SDHs" => facility_counts_by_size.fetch("large", 0), # "Total DHs/SDHs"
"Total CHCs" => facility_counts_by_size.fetch("medium", 0), # "Total CHCs"
"Total PHCs" => facility_counts_by_size.fetch("small", 0), # "Total PHCs"
"Total HWCs/SCs" => facility_counts_by_size.fetch("community", 0), # "Total HWCs/SCs"
"Total hypertension registrations" => repo.cumulative_registrations[district.slug][report_month], # "Total registrations"
"Total assigned hypertension patients" => repo.cumulative_assigned_patients[district.slug][report_month], # "Total assigned patients"
"Total hypertension patients under care" => repo.under_care[district.slug][report_month], # "Total patients under care"
"% BP controlled" => percentage_string(repo.controlled_rates[district.slug][report_month]), # "% BP controlled",
"% BP uncontrolled" => percentage_string(repo.uncontrolled_rates[district.slug][report_month]), # "% BP uncontrolled",
"% Missed Visits" => percentage_string(repo.missed_visits_rate[district.slug][report_month]), # "% Missed Visits",
"% Visits, no BP taken" => percentage_string(repo.visited_without_bp_taken_rates[district.slug][report_month]), # "% Visits, no BP taken",
**last_6_months_data(repo.cumulative_registrations, :cumulative_registrations), # "Total registered patients",
**last_6_months_data(repo.under_care, :under_care), # "Patients under care",
**last_6_months_data(indicator_by_facility_size([:large, :medium], :monthly_registrations), :monthly_registrations_large_medium), # "New registrations (DH/SDH/CHC)"
**last_6_months_data(indicator_by_facility_size([:small], :monthly_registrations), :monthly_registrations_small), # "New registrations (PHC)"
**last_6_months_data(indicator_by_facility_size([:community], :monthly_registrations), :monthly_registrations_community), # "New registrations (HWC/SC)"
**last_6_months_data(repo.hypertension_follow_ups, :hypertension_follow_ups), # "Patient follow-ups",
**last_6_months_data(repo.controlled_rates, :controlled_rates, true), # "BP controlled rate"
**last_6_months_data(repo.controlled, :controlled), # "BP controlled count"
# last 3 months of data, at community facilities
**last_6_months_data(indicator_by_facility_size([:community], :cumulative_registrations, last_6_months),
:cumulative_registrations_community).drop(3).to_h, # "Cumulative registrations at HWCs"
**last_6_months_data(indicator_by_facility_size([:community], :under_care, last_6_months),
:cumulative_under_care_community).drop(3).to_h, # "Cumulative patients under care at HWCs"
**last_6_months_percentage(indicator_by_facility_size([:community], :cumulative_assigned_patients, last_6_months.drop(3)),
repo.cumulative_assigned_patients,
:cumulative_assigned_patients_community_percentage)
.drop(3).to_h, # "% of assigned patients at HWCs / SCs (as against district)"
**last_6_months_percentage(indicator_by_facility_size([:community], :monthly_follow_ups, last_6_months.drop(3)),
indicator_by_facility_size([:community, :small, :medium, :large], :monthly_follow_ups, last_6_months.drop(3)),
:monthly_follow_ups_community_percentage)
.drop(3).to_h, # "% of patients followed up at HWCs / SCs"
**last_6_months_data(indicator_by_facility_size([:community], :cumulative_assigned_patients, last_6_months.drop(3)),
:cumulative_assigned_patients_community).drop(3).to_h # "Cumulative assigned patients to HWCs"
}
end
def indicator_by_facility_size(facility_sizes, indicator, periods = last_6_months)
{
district.slug => Reports::FacilityState
.where(district_region_id: district.id, month_date: periods, facility_size: facility_sizes)
.group(:month_date)
.sum(indicator)
.map { |k, v| [Period.month(k), v.to_i] }
.to_h
}
end
def last_6_months_data(data, indicator, show_as_rate = false)
last_6_months.each_with_object({}) do |month, hsh|
value = data.dig(district.slug, month) || 0
hsh["#{indicator} - #{month}"] = indicator_string(value, show_as_rate)
end
end
def last_6_months_percentage(numerators, denominators, indicator)
last_6_months.each_with_object({}) do |month, hsh|
value = percentage(numerators.dig(district.slug, month), denominators.dig(district.slug, month))
hsh["#{indicator} - #{month}"] = indicator_string(value, true)
end
end
end
|
# Write your code here!
require 'yaml'
def game_hash
YAML.load_file("./game__details.yaml")
# p game_stats[:home][:players]
# p game_stats[:away][:players]
end
def num_points_scored(name)
hash = game_hash
hash.each_pair do |key, team_stats|
points = find_stat_in_team_stats_for_player(name, team_stats, :points)
return points if points
end
end
def shoe_size(name)
hash = game_hash
hash.each_pair do |key, team_stats|
size = find_stat_in_team_stats_for_player(name, team_stats, :shoe)
return size if size
end
end
def find_stat_in_team_stats_for_player(name, team_stats, stat_name)
team_stats[:players].each do |player|
if player.keys[0] == name
return player[name][stat_name]
end
end
return nil
end
def team_colors(team)
hash = game_hash
hash.each_pair do |key, team_stats|
if team == team_stats[:team_name]
return team_stats[:colors]
end
end
end
def team_names
hash = game_hash
[ hash[:home][:team_name], hash[:away][:team_name] ]
end
def player_numbers(team_name)
hash = game_hash
hash.each_pair do |key, team_stats|
if team_stats[:team_name] == team_name
return team_stats[:players].map {|player| player.values[0][:number] }
end
end
end
def player_stats(name)
hash = game_hash
hash.each_pair do |key, team_stats|
team_stats[:players].each do |player|
if player.keys[0] == name
return player[name]
end
end
end
end
def get_players_for_team(team_name)
hash = game_hash
hash.each_pair do |key, team_stats|
if team_stats[:team_name] == team_name
return team_stats[:players].map {|player| player.keys[0] }
end
end
end
def find_player_with_max(players, stat)
max = 0
players.reduce("") do |memo, player|
size = player_stats(player)[stat]
if size > max
memo = player
max = size
end
memo
end
end
def get_all_players
teams = team_names
get_players_for_team(teams[0]) + get_players_for_team(teams[1])
end
def big_shoe_rebounds
player_with_biggest_shoe = find_player_with_max(get_all_players, :shoe)
player_stats(player_with_biggest_shoe)[:rebounds]
end
def most_points_scored
p find_player_with_max(get_all_players, :points)
end
def winning_team
teams = team_names
didHomeWin(teams[0], teams[1]) ? team_names[0] : team_names[1]
end
def didHomeWin(home_team, away_team)
home_score = calculate_score_for_team(home_team)
away_score = calculate_score_for_team(away_team)
home_score > away_score ? true : false
end
def calculate_score_for_team(team)
players = get_players_for_team(team)
players.reduce(0) do |memo, player|
memo += num_points_scored(player)
end
end
def player_with_longest_name
get_all_players.max { |a, b| a.length <=> b.length }
end
def long_name_steals_a_ton?
return !!(find_player_with_max(get_all_players, :steals) == player_with_longest_name)
end |
module SocialStream
module Places
module Models
module Document
extend ActiveSupport::Concern
included do
attr_accessor :place_property_object_id
before_validation(:on => :create) do
set_place
end
end
protected
def set_place
return if place_property_object_id.blank?
activity_object_holders <<
ActivityObjectProperty::Photo.new(:activity_object_id => place_property_object_id)
end
end
end
end
end
|
require "test_helper"
class ApplicationTest < MiniTest::Unit::TestCase
def test_instantianes_with_api_key
stubs = Faraday::Adapter::Test::Stubs.new
pinged = false
stubs.head('/v0') do |env|
pinged = true
[200, response_headers, '']
end
app = Orchestrate::Application.new("api_key") do |conn|
conn.adapter :test, stubs
end
assert_equal "api_key", app.api_key
assert_kind_of Orchestrate::Client, app.client
assert pinged, "API wasn't pinged"
end
def test_instantiates_with_client
client, stubs = make_client_and_artifacts
pinged = false
stubs.head('/v0') do |env|
pinged = true
[ 200, response_headers, '' ]
end
app = Orchestrate::Application.new(client)
assert_equal client.api_key, app.api_key
assert_equal client, app.client
assert pinged, "API wasn't pinged"
end
def test_collection_accessor
app, stubs = make_application
users = app[:users]
assert_kind_of Orchestrate::Collection, users
assert_equal app, users.app
assert_equal 'users', users.name
end
def dup_generates_new_client
client, stubs = make_client_and_artifacts
app = Orchestrate::Application.new(client)
duped_app = app.dup
assert_equal app.api_key, duped_app.api_key
assert_equal client.faraday_configuration, duped_app.client.faraday_configuration
refute_equal client.object_id, duped_app.client.object_id
refute_equal client.http.object_id, duped_app.client.http.object_id
end
end
|
# frozen_string_literal: true
class Litter < ApplicationRecord
has_one_attached :profile_image
belongs_to :mother, class_name: 'Cat'
belongs_to :father, class_name: 'Cat'
has_many :kittens, class_name: 'Cat', dependent: :nullify
has_many :images, class_name: 'LitterAttachedImage', dependent: :destroy
validates :name, :mother_id, :father_id, :date_of_creation, presence: true
validates :profile_image, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg']
end
|
class CreateGeinins < ActiveRecord::Migration[5.1]
def change
create_table :geinins do |t|
t.string :name
t.string :yomi
t.string :agency
t.integer :start_year
t.string :twitter_id
t.string :instagram_id
t.string :youtube_url
t.string :blog_url
t.string :official_profile_url
t.date :end_date
t.references :user, foreign_key: true
t.timestamps
end
end
end
|
# loyaltylabs specific API calls here
class SYWR::LoyaltyLabs
LL_ENDPOINT = 'https://apis3.loyaltylab.com/loyaltyapi/loyaltyapi.asmx'
LL_NAMESPACE = 'http://www.loyaltylab.com/loyaltyapi'
LL_USER = 'viewpoints@shopyourwayrewards.com'
LL_PASS = 'Sh0pyourway!'
attr_reader :client
attr_accessor :authentication_token, :user, :errors
def initialize url=LL_ENDPOINT
@client = Savon::Client.new url
@user = {}
@errors = []
end
# returns user hash if found, else nil
def find_user_by_email email
response = make_request 'GetShopperByEmail', { :email => email }
return unless valid?
response = response.to_hash[:GetShopperByEmailResponse].try(:[], :GetShopperByEmailResult)
{ :first_name => response[:FirstName], :last_name => response[:LastName], :rewards_id => response[:ShopperId] } if response
end
# return user hash if found, else nil
def find_user_by_shopper_id id
response = make_request 'GetShopperByID', { :shopperId => id }
return unless valid?
response = response.to_hash[:GetShopperByIDResponse].try(:[], :GetShopperByIDResult) if response
{ :first_name => response[:FirstName], :last_name => response[:LastName], :rewards_id => response[:ShopperId] } if response
end
def find_user_by_rewards_id id, last_name
response = make_request 'GetShopperByRegisteredCard', { :lastName => last_name, :loyaltyCardNum => id }
return unless valid?
response = response.to_hash[:GetShopperByRegisteredCardResponse].try(:[], :GetShopperByRegisteredCardResult)
{ :first_name => response[:FirstName], :last_name => response[:LastName], :rewards_id => response[:ShopperId] } if response
end
def verify_sywr_number number, last_name, first_name
# first_name is ignored, but having it makes the switch to the SHC api easier in the calling controller
response = make_request 'GetShopperByRegisteredCard', { :lastName => last_name, :loyaltyCardNum => number }
return unless valid?
response = response.to_hash[:GetShopperByRegisteredCardResponse].try(:[], :GetShopperByRegisteredCardResult)
response ? true : false
end
# returns the current reward balance for a given user account
def current_point_balance rewards_id
response = make_request 'GetShopperPointBalance', { :shopperId => rewards_id }
return unless valid?
response.to_hash[:GetShopperPointBalanceResponse].try(:[], :GetShopperPointBalanceResult) if response
end
# returns true if the client is valid or not
def valid?
errors.empty?
end
protected
# makes the SOAP authentication request, stores the hash in @authentication_token
def authentication_token force=false
auth = lambda { make_request 'AuthenticateUser', { :username => LL_USER, :password => LL_PASS }}
@authentication_token = auth.call if force
@authentication_token ||= auth.call
end
# returns the authenticated XML required for each subsequent request
def authentication_header
hash = authentication_token.to_hash
to_wsdl 'AuthenticationResult' => hash[:AuthenticateUserResponse][:AuthenticateUserResult]
end
# wraps SOAP requests with the proper namespaces, headers, and body
def make_request action, params
hash = to_wsdl(params)
tries = 0
begin
tries += 1
header = authentication_header unless action == 'AuthenticateUser'
response = client.send("#{action}!") do |soap|
soap.namespace = LL_NAMESPACE + '/'
soap.action = LL_NAMESPACE + '/' + action
soap.input = action
soap.header = header
soap.body = hash
end
if response.http.code != '200'
raise "SYWR: SOAP #{action} failed"
else
response
end
rescue => e
if tries < 3
reset_token if e == '(detail) Authenticated token has expired or is invalid'
logger.debug "SYWR: SOAP #{action} failed - #{e}"
retry
else
logger.warn "SYWR: SOAP #{action} completely failed - #{e}"
@errors << 'failed'
nil
end
end
end
# reset token if necessary
def reset_token
authentication_token true
end
# prepend attributes with 'wsdl:' string
# ex. to_wsdl { :username => 'viewpoints' } # => { 'wsdl:username' => 'viewpoints' }
def to_wsdl params
hash = {}
params.each_pair do |k,v|
if v.kind_of? Hash
hash["wsdl:#{k.to_s}"] = to_wsdl(v)
else
hash["wsdl:#{k.to_s}"] = v
end
end
hash
end
def logger
RAILS_DEFAULT_LOGGER
end
end
|
# encoding: utf-8
require 'redis'
require 'webmock/rspec'
ENV["REDISTOGO_URL"] = 'redis://username:password@localhost:6379'
def stub_get(user)
stub_request(:get, "http://www.memrise.com/user/#{user}/").
with(:headers => {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => fixture("#{user}.html"), :headers => {})
end
def fixture_path
File.expand_path("../fixtures", __FILE__)
end
def fixture(file)
File.new(fixture_path + '/' + file)
end
def fixture_stats
{
'osahyoun' => {
:username => 'osahyoun',
:rank => 6329,
:word_count => 315,
:points => 112726,
:thumbs_up => 0,
:high_fives => 2,
:courses_total => 5,
:courses => [
["French - The 1170 most common verbs", "http://www.memrise.com/set/10004259/french-the-1170-most-common-verbs/"],
["Introductory Spanish", "http://www.memrise.com/set/10007193/introductory-spanish/"]
]
},
'MonkeyKing' => {
:username => 'MonkeyKing',
:rank => 44,
:word_count => 2961,
:points => 2197050,
:thumbs_up => 0,
:high_fives => 68,
:courses_total => 9,
:courses => [
["Characters 501 - 1000 in Mandarin", "http://www.memrise.com/set/10011007/characters-501-1000-in-mandarin/"],
["高级汉语口语 上册", "http://www.memrise.com/set/10019695/-305/"]
]
}
}
end
|
# user: id (creator)
# name: string
# type: string (anon/common)
# encrypted_password: for private rooms
# last_activity: datetime (after 5 hours, delete it if anon)
class Chat < ActiveRecord::Base
belongs_to :user
has_many :messages, :dependent => :destroy
has_many :members, :dependent => :destroy
has_and_belongs_to_many :users, -> { uniq }, :join_table => :members
scope :anons, -> { where(:chat_type => :anon) }
scope :expired, -> { where('last_activity <= ?', EXPIRATION_TIME.ago) }
attr_accessor :password
EXPIRATION_TIME = 5.hours # delete anonymous chats after this
TYPES = {
:anon => :anon,
:common => :common
}
def password=(psw)
self.encrypted_password = BCrypt::Engine.hash_secret(psw, PASSWORD_SALT)
end
def anon?
self.chat_type == :anon
end
def expired?
self.last_activity <= EXPIRATION_TIME.ago
end
end
|
require 'kilomeasure'
describe 'duct air sealing (input-only)' do
include_examples 'measure', 'duct_air_sealing'
let!(:before_inputs) do
{
}
end
let!(:after_inputs) do
{
duct_cost: 4_000,
leakage: 'No observable leaks',
annual_heating_savings: 1_500,
annual_cooling_savings: 500
}
end
let!(:shared_inputs) do
{
gas_cost_per_therm: 1,
electric_cost_per_kwh: 1
}
end
it { should_get_gas_savings(1_500) }
it { should_get_electric_savings(500) }
it { should_get_cost_savings(2_000) }
it { should_get_cost_of_measure(4_000) }
it { should_get_years_to_payback(2) }
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
#Route per Localtower
if Rails.env.development? and defined?(Localtower)
mount Localtower::Engine, at: "localtower"
end
#interfacce dei modelli per query su /db_admin con gemma rails_admin
mount RailsAdmin::Engine => '/db_admin', as: 'rails_admin'
end
|
require_relative 'lib/game'
def loadDeck(name)
deck = []
xs = IO.readlines(name)
xs.each {|x| y = x.chomp.split(/,/); deck << Card.new(y[0], y[1], y[2])}
return deck
end
def ordinal(num)
case num.to_s
when /1$/
return "#{num}st"
when /2$/
return "#{num}nd"
when /3$/
return "#{num}rd"
else
return "#{num}th"
end
end
def stats(round)
puts "#{round.correct} correct guesses out of #{round.turns.count} for a total score of #{round.percentCorrect}%"
round.categories.each {|x| puts "In #{x}: #{round.percentInCategory(x)}%"}
puts "------------------------------------------------------"
end
deck = Deck.new(loadDeck("cards.txt"))
done = false
puts "------------------------------------------------------"
puts "Welcome to flash cards! Type \'!\' at any time to exit."
puts " Type \'?\' to see your stats, and \'...\' to restart."
puts "------------------------------------------------------"
if deck.cards.empty?
puts "Deck is empty! Something is wrong with your input file."; done = true
else
round = Round.new(deck)
puts "You're playing with #{deck.count} cards...\n\n"
end
i = 1
while !done #Is there a more idiomatic way of doing this? I'm sure there must be.
puts "#{ordinal(i)} question!"
puts round.current.question
print ">> "
inp = gets.chomp
if inp == '!'
done = true
elsif inp == '?'
puts "Your stats:"
stats(round)
elsif inp == '...'
puts "Restarting!\n\n"
round = Round.new(deck)
else
if round.turn(inp) #We're actually taking the turn here, mind.
puts "Correct!\n\n"
else
puts "Incorrect.\n\n"
end
i += 1
end
end
puts "Thanks for playing!\nYour final stats:"
stats(round) |
# Inspired by http://railscasts.com/episodes/340-datatables
#
# This implementation expands on that basic idea by injecting a dependency on
# Sunspot for full text search and ordering, rather than using database level
# solutions such as "LIKE '%..%'" clauses.
class Datatable
attr_reader :total_record_count
def initialize(params, input)
@params = params
@total_record_count = input.search.execute.total
@search = input.search
@columns = input.columns
end
def s_echo
params[:sEcho].to_i
end
def filtered_record_count
filtered_search.total
end
def data
filtered_search.results
end
private
attr_reader :params, :columns
def filtered_search
@filtered_search ||= @search.build do
fulltext params[:sSearch]
order_by(sort_column, sort_direction)
paginate page: page, per_page: per
end.execute
end
def page
(params[:iDisplayStart].to_i / per) + 1
end
def per
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end
def sort_direction
params[:sSortDir_0] == "desc" ? :desc : :asc
end
def sort_column
columns[params[:iSortCol_0].to_i]
end
end
|
class AddColumnYearToStockInputs < ActiveRecord::Migration
def change
add_column :stock_inputs, :year, :integer, index: true
end
end
|
class Subscription < ApplicationRecord
belongs_to :user
belongs_to :book_assignment
enum delivery_method: { "Eメール" => "email", "プッシュ通知" => "webpush" }
scope :deliver_by_email, -> { where(delivery_method: :email) }
scope :deliver_by_webpush, -> { where(delivery_method: :webpush) }
end
|
a = 10
b = 20
unless a > b
puts "a不比b大"
end
# 这个程序执行后输出“a 不比 b 大”。unless 语句的条件 a > b 为假,所以程序执行了 puts 方法。
|
require "spec_helper"
describe Liftoff::DependencyManager do
describe "#setup" do
it "raises an error when not implemented" do
manager = InvalidDependencyManager.new(:config)
expect { manager.setup }.to raise_error(NotImplementedError)
end
it "doesn't raise an error when implemented" do
manager = ValidDependencyManager.new(:config)
expect { manager.setup }.not_to raise_error
end
end
describe "#install" do
it "raises an error when not implemented" do
manager = InvalidDependencyManager.new(:config)
expect { manager.install }.to raise_error(NotImplementedError)
end
it "doesn't raise an error when implemented" do
manager = ValidDependencyManager.new(:config)
expect { manager.install }.not_to raise_error
end
end
describe "#run_script_phases" do
it "provides an empty array as a default" do
manager = Liftoff::DependencyManager.new(:config)
expect(manager.run_script_phases).to eq([])
end
end
class InvalidDependencyManager < Liftoff::DependencyManager; end
class ValidDependencyManager < Liftoff::DependencyManager;
def install; end
def setup; end
end
end
|
class AddRememberTokenToUsers < ActiveRecord::Migration
def change
add_column :users, :remember_token, :string
add_index :users, :remember_token
end
end
|
class CreatePhotoComments < ActiveRecord::Migration
def self.up
create_table :photo_comments do |t|
t.string :commentText
t.string :username
t.integer :rsvp_invite_id
t.integer :photo_id
t.timestamps
end
end
def self.down
drop_table :photo_comments
end
end
|
# Question 1
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" }
}
sum = 0
munsters.each do |name, details|
if details["gender"] == "male"
sum += details["age"]
end
end
p sum
# Question 2
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" },
"Marilyn" => { "age" => 23, "gender" => "female"}
}
munsters.each do |name, details|
puts "#{name} is a #{details["age"]} year old #{details["gender"]}."
end
# Question 3
def tricky_method(a_string_param, an_array_param)
a_string_param += "rutabaga"
an_array_param << "rutabaga"
end
my_string = "pumpkins"
my_array = ["pumpkins"]
tricky_method(my_string, my_array)
puts "My string looks like this now: #{my_string}"
puts "My array looks like this now: #{my_array}"
def not_so_tricky_method(a_string_param, an_array_param)
a_string_param += "rutabaga"
an_array_param += ["rutabaga"]
return a_string_param, an_array_param
end
my_string = "pumpkins"
my_array = ["pumpkins"]
my_string, my_array = not_so_tricky_method(my_string, my_array)
puts "My string looks like this now: #{my_string}"
puts "My array looks like this now: #{my_array}"
# Question 4
sentence = "Humpty Dumpty sat on a wall"
p sentence.split.reverse!.join(" ") + "."
# Question 5
answer = 42
def mess_with_it(some_number)
some_number += 8
end
new_answer = mess_with_it(answer)
p answer - 8 # should be 34 since method not invoked
p new_answer # should be 50 since method is invoked -
# Question 6
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => {"age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" },
"Marilyn" => { "age" => 23, "gender" => "female" }
}
def mess_with_demographoics(demo_hash)
demo_hash.values.each do |family_member|
family_member["age"] += 42
family_member["gender"] = "other"
end
end
mess_with_demographoics(munsters)
p munsters # permanently alters the hash because demo_hash points to munsters
# Question 7
def rps(fist1,fist2)
if fist1 == "rock"
(fist2 == "paper") ? "paper" : "rock"
elsif fist1 == "paper"
(fist2 == "scissors") ? "scissors" : "paper"
else
(fist2 == "rock") ? "rock" : "scissors"
end
end
puts rps(rps(rps("rock", "paper"), rps("rock", "scissors")), "rock")
# result is paper following order of operations
# Question 8
def foo(param = "no")
"yes"
end
def bar(param = "no")
param == "no" ? "yes" : "no"
end
p bar(foo) # is "no" because foo will always be "yes"
|
class Character < MarvelApi
def initialize(name)
super("characters")
self.query = "name=#{name}"
request
end
def character
@character ||= OpenStruct.new results[0]
end
def id
character.id
end
def comics
character.comics["items"].map do |cc|
cc["resourceURI"]
end.map do |uri|
uri[/\d*$/]
end.map do |id|
Comic.new id
end if character.comics.present?
end
end |
name 'notifying-action'
maintainer 'ClearStory Data, Inc.'
maintainer_email 'mbautin@clearstorydata.com'
license 'Apache License 2.0'
description 'An easier way to send notifications from resources'
version '1.0.3'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :guitars
def set_role
if self.role == 1
self.role = 2
else
self.role = 1
end
end
def self.get_users collection, type_user
collection = collection.where("role = :type_user ", type_user: type_user )
end
end
|
require 'attr_typecastable/types/exception'
require 'attr_typecastable/types/base'
require "active_support/core_ext/class"
module AttrTypecastable
module Types
class ArrayBase < Base
class_attribute :inner_typecaster
private
def do_typecast(value)
wrapped = Array(value)
wrapped.map { |v| inner_typecaster.typecast(v) }
end
end
class ArrayFactory
def self.build(typecaster_name, **options)
typecaster = Types.typecaster_for(typecaster_name).new(options)
klass = Class.new(ArrayBase)
klass.inner_typecaster = typecaster
klass
end
end
end
end
|
module States
class Crash < Base
def init
super
ex = cvar['exc']
tex = game.texture_cache['backgrounds/crash']
@background = Moon::Sprite.new(tex).to_sprite_context
@text = Moon::Label.new(format_exception(ex), backtrace_font)
@gui.add @background
@gui.add @text
end
def format_exception(ex)
ex.inspect +
"\n" +
ex.backtrace.join("\n")
end
def backtrace_font
game.font_cache['vera.10']
end
def crash_handling(exc)
raise exc
end
def start
super
end
end
end
|
require 'test_helper'
class CreateStockchecksheetsTest < ActionDispatch::IntegrationTest
# test message
test " get new sheet form and create new sheet" do
# gets new sheet path -> emulating user behaviour were user selet the option to create a new record
get new_stockchecksheet_path
# assert whether we have the new path reached for the template
assert_template 'stockchecksheets/new'
# assert wether we have created a new sheet
# by checking the difference in count
assert_difference 'Stockchecksheet.count', 1 do
# submission of a new form handled by the create action which is a
# HTTP POST request to create a new sheet with the below attirbutes
post_via_redirect stockchecksheets_path, stockchecksheet: {item1: "drill1",
item2: "drill2",item3: "drill3",item4: "drill4",item5: "drill5",
item11: "1",
item12: "1",item21: "5",item22: "5",item31: "18",item32: "18",
item41: "25",item42: "25",item51: "30",item52: "29"}
end
# asserting the the show view whether it contains
# one of the strings passed in at creation ->
# "phy" should be visible in the reponse body
assert_template 'stockchecksheets/show'
assert_match "Physical", response.body
end
end |
require 'spec_helper'
describe 'useradd::login_defs' do
context 'supported operating systems' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts
end
context 'with default parameters' do
let(:expected) { File.read('spec/expected/default_login_defs') }
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('useradd::login_defs') }
it { is_expected.to create_file('/etc/login.defs').with_content(expected) }
end
context 'with everything defined or true' do
let(:expected) { File.read('spec/expected/default_login_defs_all_true') }
let(:params) {{
:chfn_auth => true,
:chsh_auth => true,
:default_home => true,
:su_wheel_only => true,
:erasechar => 100,
:killchar => 100,
:max_members_per_group => 100,
:pass_min_len => 100,
:sys_gid_max => 100,
:sys_gid_min => 100,
:sys_uid_max => 100,
:sys_uid_min => 100,
:uid_min => 100,
:ulimit => 100,
:env_hz => 'HZ=100',
:env_tz => 'TZ=CST6CDT',
:fake_shell => '/usr/sbin/nologin',
:ftmp_file => '/tmp/ftmp',
:hushlogin_file => '/tmp/hushlogin',
:login_string => 'Password: ',
:mail_file => '/tmp/mailfile',
:nologins_file => '/tmp/nologins',
:sulog_file => '/tmp/sulog',
:ttygroup => 'puppet',
:ttyperm => '0600',
:ttytype_file => '/tmp/ttytype',
:userdel_cmd => '/usr/sbin/userdel',
:console => ['/dev/tty1'],
:env_path => ['/usr/bin','/usr/local/bin'],
:env_supath => ['/usr/bin','/usr/sbin/','/usr/local/bin'],
:motd_file => ['/etc/motd','/etc/issue']
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('useradd::login_defs') }
it { is_expected.to create_file('/etc/login.defs').with_content(expected) }
end
end
end
end
end
|
# All examples presume that you have a ~/.fog credentials file set up.
# More info on it can be found here: http://fog.io/about/getting_started.html
require "bundler"
Bundler.require(:default, :development)
# Uncomment this if you want to make real requests to GCE (you _will_ be billed!)
# WebMock.disable!
def test
# Config
name = "fog-lb-test-#{Time.now.to_i}"
zone = "europe-west1-d"
region = "europe-west1"
# Setup
gce = Fog::Compute.new :provider => "Google"
servers = []
puts "Creating instances..."
puts "--------------------------------"
(1..3).each do |i|
begin
disk = gce.disks.create(
:name => "#{name}-#{i}",
:size_gb => 10,
:zone_name => zone,
:source_image => "debian-11-bullseye-v20220920"
)
disk.wait_for { disk.ready? }
rescue
puts "Failed to create disk #{name}-#{i}"
end
begin
server = gce.servers.create(
:name => "#{name}-#{i}",
:disks => [disk.get_as_boot_disk(true, true)],
:machine_type => "f1-micro",
:zone_name => zone
)
servers << server
rescue
puts "Failed to create instance #{name}-#{i}"
end
end
puts "Creating health checks..."
puts "--------------------------------"
begin
health = gce.http_health_checks.new(:name => name)
health.save
rescue
puts "Failed to create health check #{name}"
end
puts "Creating a target pool..."
puts "--------------------------------"
begin
pool = gce.target_pools.new(
:name => name,
:region => region,
:health_checks => [health.self_link],
:instances => servers.map(&:self_link)
)
pool.save
rescue
puts "Failed to create target pool #{name}"
end
puts "Creating forwarding rules..."
puts "--------------------------------"
begin
rule = gce.forwarding_rules.new(
:name => name,
:region => region,
:port_range => "1-65535",
:ip_protocol => "TCP",
:target => pool.self_link
)
rule.save
rescue
puts "Failed to create forwarding rule #{name}"
end
# TODO(bensonk): Install apache, create individualized htdocs, and run some
# actual requests through the load balancer.
# Cleanup
puts "Cleaning up..."
puts "--------------------------------"
begin
rule.destroy
rescue
puts "Failed to clean up forwarding rule."
end
begin
pool.destroy
rescue
puts "Failed to clean up target pool."
end
begin
health.destroy
rescue
puts "Failed to clean up health check."
end
begin
servers.each(&:destroy)
rescue
puts "Failed to clean up instances."
end
end
test
|
class CreateOrderProductions < ActiveRecord::Migration[5.0]
def change
create_table :order_productions do |t|
t.string :solicitante
t.string :ficha_proc
t.string :codigo
t.string :descricao
t.integer :quant
t.string :injetora
t.string :modelo
t.string :acessorios
t.timestamps
end
end
end
|
class UsersController < Devise::RegistrationsController
before_action :authenticate_user!
before_action :admin_only, :except => [:show, :my_data]
def new
foo
@user = User.find(params[:id])
end
def index
if current_user.admin?
@users = User.no_agents
elsif current_user.org_admin?
@users = User.where(org_id: current_user.org_id).no_agents
else
@users = Array(current_user)
end
end
def show
@user = User.find(params[:id])
unless current_user.admin?
unless @user == current_user
redirect_to :back, :alert => "Access denied."
end
end
end
def update
@user = User.find(params[:id])
if @user.update_attributes(secure_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
def destroy
user = User.find(params[:id])
user.destroy
redirect_to users_path, :notice => "User deleted."
end
def my_data
respond_to do |format|
format.json do
if user_signed_in?
user_data = { user:
{ email: current_user.email,
auth_token: current_user.authentication_token,
org_id: current_user.org_id,
org_slug: current_user.org.slug
}
}
render json: user_data
else
render json: [], status: :unauthorized
end
end
end
end
def after_update_path_for(resource)
signed_in_root_path(resource)
end
private
def admin_only
# unless current_user.admin?
# redirect_to :back, :alert => "Access denied."
# end
end
def secure_params
params.require(:user).permit(:role)
end
end
|
class AddFetchColumnToFeeds < ActiveRecord::Migration
def change
add_column :feeds, :fetch, :boolean, :default => true
end
end
|
include AutobotsTransform
#
# Requires a table object with random
# access, we should probably write one
# that can stream off of disk at some point
#
# This doesn't generate quite the right id's
# unless you use an ordered hash to store the
# inverted indexes in.
#
# It's important to note that we're using dimension
# names in indexes everywhere to make sure that we
# can do cubes only for the dimensions we're interested
# in and not every dimension in the table
#
module QuotientCube
class Base < AutobotsTransform::Table
attr_accessor :table
attr_accessor :dimensions
attr_accessor :measures
attr_accessor :values
def initialize(table, dimensions, measures)
@table = table
@dimensions = dimensions
@measures = measures
super(:column_names => ['id', 'upper', 'lower', 'child_id', *measures])
end
def build(&block)
cell = Array.new(dimensions.length).fill('*')
dfs(cell, (0..table.data.length - 1).to_a, 0, -1, &block)
self.sort(['upper', 'id'])
end
def update(tree, &block)
cell = Array.new(dimensions.length).fill('*')
ddfs(tree, cell, (0..table.data.length - 1).to_a, 0, -1, &block)
self.sort(['upper', 'id'])
end
#
# Returns a list of each dimension
# with an array of values that appear
# in that dimension
#
# {'product' => ['P1', 'P2'], 'season' => ['s', 'f]}
#
def values
if @values
return @values
else
values = {}
table.each do |row|
dimensions.each do |dimension|
values[dimension] ||= []
values[dimension] << row[dimension]
end
end
values.keys.each do |dimension|
values[dimension].uniq!
values[dimension].sort!
end
@values = values
end
end
#
# Collects statistics about the rows
# in the current partition we're searching
#
# [
# {"S1"=>[0, 1], "S2"=>[2]},
# {"P1"=>[0, 2], "P2"=>[1]},
# {"f"=>[2], "s"=>[0, 1]}
# ]
#
def indexes(pointers)
indexes = {}
dimensions.each do |dimension|
index = {}
columni = table.column_names.index(dimension)
pointers.each do |rowi|
value = table.data[rowi][columni]
index[value] ||= []
index[value] << rowi
end
# puts "Setting indexes[#{dimension}] to #{index.inspect}"
indexes[dimension] = index
end
indexes
end
#
# the upper bound is the same as the lower bound for every
# value of the lower bound that isn't '*'
#
# for any value of the lower bound that is '*' if there
# is a single value that appears in every tuple of the
# partition that we're looking over, then the value
# of the upper bound for that dimension is the value
# that appears in every tuple
#
# This is the 'jumping' described in the literature
#
# Example: if our partition is:
# (2, 1, 1), (2, 1, 2)
#
# and our lower bound is
# (2, *, *)
#
# our upper bound is
# (2, 1, *)
#
def upper_bound(indexed, lower)
upper = lower.dup
lower.each_with_index do |value, index|
dimension = dimensions[index]
if value == '*'
if indexed[dimension].keys.length == 1
upper[index] = indexed[dimension].keys.first
end
else
upper[index] = value
end
end
upper
end
def dfs(cell, pointers, position, child, &block)
# puts table.to_s
# Computer aggregate of cell
aggregate = block.call(table, pointers) if block_given?
# Collect information about the partition
indexed = indexes(pointers)
# Compute the upper bound of the class containing cell
# by 'jumping' to the appropriate upper bound
upper = upper_bound(indexed, cell)
class_id = self.length
# puts "Recording class [#{class_id}, #{upper.inspect}, #{cell.inspect}, #{child}]"
self << [class_id, upper.dup, cell.dup, child, *aggregate]
# puts "Found class #{class_id} (#{child}) => #{upper}"
# puts cell.inspect
# puts upper.inspect
# return if we've examined this upper bound before
# I don't think this is working
for j in (0..position - 1) do
return if cell[j] == '*' and upper[j] != '*'
end
d = upper.dup
n = dimensions.length - 1
for j in (position..n) do
next unless d[j] == '*'
dimension = dimensions[j]
indexed[dimension].keys.sort.each do |x|
pointers = indexed[dimension][x]
if(pointers.length > 0)
d[j] = x
dfs(d, pointers, j, class_id, &block)
d[j] = '*'
end
end
end
end
#
# Delta DFS for updating a qc-tree in batch
#
def ddfs(tree, cell, pointers, position, child, &block)
# Computer aggregate of cell
# this might be different here if we're updating
aggregate = block.call(table, pointers) if block_given?
# Collect information about the partition
indexed = indexes(pointers)
# Compute the upper bound of the class containing cell
# by 'jumping' to the appropriate upper bound
upper = upper_bound(indexed, cell)
#
# Look in the tree for the upper bound (ub) of the class containing c
#
# If we can't find it record a new class like we normally would
#
# If we do find ub then we compare it to c' (upper), we have 3 cases
#
# 1) ub ^ c' = ub
# We found the exact upper bound in the tree
# Record a measure update on the class
# 2) ub ^ c' = c'
# c' is an upper bound bound. Record a split class
# with upper bound c' containing all cells of C that
# are below c'. The remainder of C forms another class
# with ub as its upper bound. (????)
# 3) Neither of the above.
# ub and c' are not comparable. Record a new class with
# upper bound c'' = ub ^ c'
#
class_id = self.length
self << [class_id, upper.dup, cell.dup, child, *aggregate]
# puts "Found class #{class_id} (#{child}) => #{upper}"
# puts cell.inspect
# puts upper.inspect
# return if we've examined this upper bound before
for j in (0..position - 1) do
return if cell[j] == '*' and upper[j] != '*'
end
d = upper.dup
n = dimensions.length - 1
for j in (position..n) do
next unless d[j] == '*'
dimension = dimensions[j]
indexed[dimension].each do |x, pointers|
if(pointers.length > 0)
d[j] = x
dfs(tree, d, pointers, j, class_id, &block)
d[j] = '*'
end
end
end
end
class << self
def build(table, dimensions, measures, &block)
new(table, dimensions, measures).build(&block)
end
end
end
end |
require 'feature_helper'
feature 'Create trade request', js: true do
given(:user) { create :user }
given(:trade_request) { user.trade_requests.last }
given!(:geocode) { GeoHelper.define_stub 'New York City, New York', :geolocate_newyork }
context 'authenticated' do
background do
login_as user
end
Steps 'I create my first trade request' do
Given 'I am on the trade requests page' do
should_be_located '/u/trade_requests'
end
When 'I click the create button' do
click_link '+ Create New'
end
Then 'I should see the trade request form' do
should_see 'New Trade Request'
should_see 'Name'
should_see 'Location'
should_see 'Trade Type'
should_see 'Percentage Profit'
should_see 'Accepted Currency'
should_be_located '/u/trade_requests/new'
end
When 'I click save' do
click_button 'Save'
end
Then 'I should see validation errors' do
should_see 'New Trade Request'
should_see "Name can't be blank"
should_see "Location can't be blank"
should_see "Profit can't be blank"
end
When 'I fill out the form' do
fill_in :trade_request_name, with: 'Best Trade Ever'
fill_in :trade_request_location, with: 'New York City, New York'
fill_in :trade_request_description, with: 'I only accept trading on Sundays.'
select "I am Buying Dash", from: "trade_request_kind"
select "EUR", from: "trade_request_currency"
fill_in :trade_request_profit, with: 'foo'
end
And 'I click save' do
click_button 'Save'
end
Then 'I should see validation errors' do
should_see "Profit must be a number"
end
When 'I fill out the form' do
fill_in :trade_request_profit, with: '2.5'
end
And 'I click save' do
click_button 'Save'
end
Then 'I should be on the list view' do
should_see '+ Create New'
end
And 'the record should be created with correct data' do
expect(trade_request.name).to eq 'Best Trade Ever'
expect(trade_request.description).to eq 'I only accept trading on Sundays.'
expect(trade_request.kind).to eq 'buy'
expect(trade_request.profit).to eq '2.5'
expect(trade_request.location).to eq 'New York City, New York'
expect(trade_request.longitude).to eq -74.0059413
expect(trade_request.latitude).to eq 40.7127837
expect(trade_request.slug).to eq 'best_trade_ever'
expect(trade_request.active).to eq true
expect(trade_request.currency).to eq 'eur'
end
end
describe 'correctly setting default active states based on limit of 2 active trade requests' do
context 'I already have one active trade requests' do
let!(:trade_request_1) { create :trade_request, user: user }
Steps 'I create a trade request' do
When 'I click the create button' do
click_link '+ Create New'
end
When 'I fill out the form' do
fill_in :trade_request_name, with: 'Best Trade Ever'
fill_in :trade_request_location, with: 'New York City, New York'
select "I am Buying Dash", from: "trade_request_kind"
fill_in :trade_request_profit, with: '2.5'
end
And 'I click save' do
click_button 'Save'
end
Then 'I should be on the list view' do
should_see '+ Create New'
end
And 'the record should be created with correct data' do
expect(trade_request.name).to eq 'Best Trade Ever'
expect(trade_request.active).to eq true
end
end
end
context 'I already have two active trade requests' do
let!(:trade_request_1) { create :trade_request, user: user }
let!(:trade_request_2) { create :trade_request, user: user }
Steps 'I create a trade request' do
When 'I click the create button' do
click_link '+ Create New'
end
When 'I fill out the form' do
fill_in :trade_request_name, with: 'Best Trade Ever'
fill_in :trade_request_location, with: 'New York City, New York'
select "I am Buying Dash", from: "trade_request_kind"
fill_in :trade_request_profit, with: '2.5'
end
And 'I click save' do
click_button 'Save'
end
Then 'I should be on the list view' do
should_see '+ Create New'
end
And 'the record should be created with correct data' do
expect(trade_request.name).to eq 'Best Trade Ever'
expect(trade_request.active).to eq false
end
end
end
context 'I already have two active trade requests and two inactive' do
let!(:trade_request_1) { create :trade_request, user: user }
let!(:trade_request_2) { create :trade_request, user: user }
let!(:trade_request_3) { create :trade_request, user: user, active: false }
let!(:trade_request_4) { create :trade_request, user: user, active: false }
Steps 'I create a trade request' do
When 'I click the create button' do
click_link '+ Create New'
end
When 'I fill out the form' do
fill_in :trade_request_name, with: 'Best Trade Ever'
fill_in :trade_request_location, with: 'New York City, New York'
select "I am Buying Dash", from: "trade_request_kind"
fill_in :trade_request_profit, with: '2.5'
end
And 'I click save' do
click_button 'Save'
end
Then 'I should be on the list view' do
should_see '+ Create New'
end
And 'the record should be created with correct data' do
expect(trade_request.name).to eq 'Best Trade Ever'
expect(trade_request.active).to eq false
end
end
end
end
end
end
|
module TheCityAdmin
FactoryGirl.define do
factory :user_invitation_list, :class => TheCityAdmin::UserInvitationList do
total_entries 0
total_pages 0
per_page 15
current_page 1
#invitations {}
end
end
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
stations = [
{
title: "The Lot Radio @ Basilica Soundscape",
description: "The Lot Radio comes to the 6th annual Basilica Soundscape in Hudson, NY.",
url: "https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/355616768&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"
},
{
title: "Dazed Digital Mixes",
description: "All the Dazed Mixes, all in one place.",
url: "https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/296562077&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"
},
{
title: "FADER Mixtape: April 2015",
description: "Bringing you the best of April 2015",
url: "https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/103211648&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"
},
{
title: "NAAFI 2.0",
description: "The raw sounds of Mexico City's nightlife",
url: "https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/327036999&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"
}
]
stations.each do |station|
Station.create(station)
end
|
# frozen_string_literal: true
class ApplicationController < ActionController::API
def render_object(object)
if object.respond_to?(:errors) && object.errors.any?
render(jsonapi_errors: object.errors)
else
renderization =
{ jsonapi: object, include: includes_params }
render renderization
end
end
def includes_params
params.fetch(:includes, {})
end
end
|
class AuthController < ApplicationController
def login
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
token = encode_token({user_id: user.id})
render :json => {token: token}
else
render :json => {error: "Invalid username or password"}, :status => 401
end
end
private
def encode_token(payload)
payload['exp'] = 1.hour.from_now.to_i
JWT.encode(payload, "secret key")
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :star do
actor_id 1
movie_id 1
character "MyString"
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "precise64"
config.vm.box_url = "http://files.vagrantup.com/precise64.box"
# Assign this VM to a host-only network IP, allowing you to access it
# via the IP. Host-only networks can talk to the host machine as well as
# any other machines on the same network, but cannot be accessed (through this
# network interface) by any external networks.
config.vm.network :private_network, ip: "192.168.33.10"
config.vm.hostname = "simple-mongo"
config.vm.synced_folder "apt-cache", "/var/cache/apt/archives", create: true
# config.vm.boot_mode = :gui
config.vm.provision :shell do |shell|
shell.inline = "if [ ! -d /etc/puppet/modules ] ; then mkdir -p /etc/puppet/modules;
puppet module install puppetlabs/mongodb;
fi"
end
config.vm.provision :puppet do |puppet|
puppet.manifests_path = "manifests"
puppet.manifest_file = "simple-mongo.pp"
end
end
|
class AddIndexesToEventAttendances < ActiveRecord::Migration[5.2]
def change
add_index :event_attendances, :attended_event_id
add_index :event_attendances, :attendee_id
end
end
|
# frozen_string_literal: true
require 'spec_helper'
shared_examples_for 'a connection based apartment adapter' do
include Apartment::Spec::AdapterRequirements
let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } }
describe '#init' do
after do
# Apartment::Tenant.init creates per model connection.
# Remove the connection after testing not to unintentionally keep the connection across tests.
Apartment.excluded_models.each do |excluded_model|
excluded_model.constantize.remove_connection
end
end
it 'should process model exclusions' do
Apartment.configure do |config|
config.excluded_models = ['Company']
end
Apartment::Tenant.init
expect(Company.connection.object_id).not_to eq(ActiveRecord::Base.connection.object_id)
end
end
describe '#drop' do
it 'should raise an error for unknown database' do
expect do
subject.drop 'unknown_database'
end.to raise_error(Apartment::TenantNotFound)
end
end
describe '#switch!' do
it 'should raise an error if database is invalid' do
expect do
subject.switch! 'unknown_database'
end.to raise_error(Apartment::TenantNotFound)
end
end
end
|
# take a length and width in meters and return the area in both
# meters and feet
SQMETERS_TO_SQFEET = 10.7639
# using the constant is good practice when using a number whose
# meaning is not immediately obvious when seeing it
def area
puts "Enter the length of the room in meters:"
length = gets.chomp.to_f
puts "Enter the width of the room in meters:"
width = gets.chomp.to_f
area_meters = (length * width).round(2)
area_feet = (area_meters * SQMETERS_TO_SQFEET).round(2)
puts "The area of the room is #{area_meters} square meters " + \
"(#{area_feet})"
end
area
|
require 'rails_helper'
feature 'User does login or logout' do
describe 'login' do
scenario 'successfully' do
user = create(:user, email: 'user@example.com')
visit root_path
click_on 'Entrar'
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_on 'Log in'
expect(page).to have_content(user.email)
expect(page).to have_link('Sair')
expect(page).to have_css('i.fas.fa-plus-circle')#new task icon
expect(page).not_to have_link('Entrar')
expect(page).not_to have_content('Bem vindo ao TODOlist')
end
scenario 'and fill with wrong email and password', js: true do
visit root_path
click_on 'Entrar'
fill_in 'Email', with: 'customer@example.com'
fill_in 'Password', with: '654321'
click_on 'Log in'
expect(page).to have_content('Incorrect email or password.')
end
scenario 'and not fill in fields', js: true do
visit root_path
click_on 'Entrar'
click_on 'Log in'
expect(page).to have_content('Incorrect email or password.')
end
end
describe 'logout' do
scenario 'successfully' do
user = create(:user, email: 'user@example.com')
login_as(user, scope: :user)
visit root_path
click_on 'Sair'
expect(page).not_to have_content(user.email)
expect(page).not_to have_link('Sair')
expect(page).to have_link('Entrar')
expect(page).to have_content('Bem vindo ao TODOlist')
end
end
end
|
class Admin::UserPhotosController < Admin::BaseController
permit "superuser"
layout 'admin/base'
helper_method :user, :photos, :photo
# render index
# === Custom REST methods
def destroy_checked
count = params[:photo_ids].size
params[:photo_ids].each do |p|
LocalPhoto.find(p).destroy
end
flash[:notice] = "Deleted #{count} photo#{"s" unless count == 1}."
redirect_to admin_user_user_photos_path(user, params.slice(:page))
rescue ActiveRecord::RecordNotFound
flash[:notice] = "At least one checked photo was not found."
render :action => "index"
end
private
def user
@user ||= User.find_by_auth_screen_name! params[:user_id]
end
def photos
@photos ||= user.photos.paginate :page => params[:page]
end
def photo
@photo ||= user.photos.find params[:id]
end
# ===
def page
params[:page].blank? ? nil : params[:page]
end
end
|
class Comment < ActiveRecord::Base
belongs_to :ticket
belongs_to :user
has_attached_file :attachment,
:path => ":rails_root/public/uploads/:class/:attachment/:id/:style/:basename.:extension",
:url => "#{SITE_URL}uploads/:class/:attachment/:id/:style/:basename.:extension",
:styles => { :thumb => "90x90>", :preview => "650x650>" },
:whiny => false
before_validation :clear_attachment
validates_attachment_size :attachment, :less_than => 10.megabytes
validates_presence_of :body
validates_presence_of :ticket_id
def delete_attachment=(value)
@delete_attachment = !value.to_i.zero?
end
def delete_attachment
!!@delete_attachment
end
alias_method :delete_attachment?, :delete_attachment
def attachment_image?
!!/image\/.*/.match(self.attachment_content_type)
end
protected
def clear_attachment
self.attachment = nil if delete_attachment? and not attachment.dirty?
end
end
|
class CreateDeliveries < ActiveRecord::Migration
def change
create_table :deliveries do |t|
t.string :courier
t.string :dispatch
t.integer :guide
t.integer :guide2
t.integer :guide3
t.decimal :cargo_cost, :precision => 8, :scale => 2
t.decimal :cargo_cost2, :precision => 8, :scale => 2
t.decimal :cargo_cost3, :precision => 8, :scale => 2
t.decimal :dispatch_cost, :precision => 8, :scale => 2
t.decimal :dua_cost, :precision => 8, :scale => 2
t.string :supplier
t.string :origin
t.date :origin_date
t.date :arrival_date
t.date :delivery_date
t.text :status
t.date :invoice_delivery_date
t.date :doc_courier_date
t.integer :invoice_number
t.decimal :fob_total_cost, :precision => 8, :scale => 2
t.decimal :total_units_cost, :precision => 8, :scale => 2
t.timestamps
end
end
end
|
class UserDecorator < ApplicationDecorator
delegate_all
def name
h.link_to object.name, h.edit_user_path(object)
end
def admin
h.check_box_tag 'users[]', object.admin , object.admin,{ :disabled => "disabled"}
end
# Define presentation-specific methods here. Helpers are accessed through
# `helpers` (aka `h`). You can override attributes, for example:
#
# def created_at
# helpers.content_tag :span, class: 'time' do
# object.created_at.strftime("%a %m/%d/%y")
# end
# end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.