text
stringlengths
10
2.61M
## # *this class controls the cart actions # *created using scaffold # *the class methods are all common controller methods # [index] the index page for model is defined # [show] the page for each specific model instance eg. cart[6] is defined # [new] the page for creating new model instances is defined # [create] the stuff done after the new instance created # [edit] the edit page for model instances is defined # [update] the method called after edit # [destroy] mothod for destruction of model instances class CartsController < ApplicationController ##--:method: before_filter------------------------------------------- # using the following before_filter users cannot directly access: # * www.site.com/carts # * www.site.com/carts/new # * www.site.com/carts/[i] before_filter :access_denied , :except => [:create,:destroy,:update] def access_denied redirect_to root_url , :notice => 'You are not authorized to see this page!' end #----------------------------------------------------------------- # GET /carts # GET /carts.json def index @carts = Cart.all respond_to do |format| format.html # index.html.erb format.json { render json: @carts } end end # GET /carts/1 # GET /carts/1.json def show begin @cart = Cart.find(params[:id]) rescue ActiveRecord::RecordNotFound logger.error "Attempt to access invalid cart #{params[:id]}" redirect_to root_url, :notice => 'Invalid cart' else respond_to do |format| format.html # show.html.erb format.json { render json: @cart } end end end # GET /carts/new # GET /carts/new.json def new @cart = Cart.new respond_to do |format| format.html # new.html.erb format.json { render json: @cart } end end # GET /carts/1/edit def edit @cart = Cart.find(params[:id]) end # POST /carts # POST /carts.json def create @cart = Cart.new(params[:cart]) respond_to do |format| if @cart.save format.html { redirect_to @cart, notice: 'Cart was successfully created.' } format.json { render json: @cart, status: :created, location: @cart } else format.html { render action: "new" } format.json { render json: @cart.errors, status: :unprocessable_entity } end end end # PUT /carts/1 # PUT /carts/1.json def update @cart = Cart.find(params[:id]) respond_to do |format| if @cart.update_attributes(params[:cart]) format.html { redirect_to @cart, notice: 'Cart was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @cart.errors, status: :unprocessable_entity } end end end # DELETE /carts/1 # DELETE /carts/1.json def destroy @cart = current_cart @cart.destroy session[:cart_id] = nil respond_to do |format| format.html { redirect_to(root_url, :notice => 'Your cart is currently empty' ) } format.json { head :no_content } end end end
Gem::Specification.new do |s| s.name = 'balanced_vrp_clustering' s.version = '0.2.0' s.date = '2021-03-09' s.summary = 'Gem for clustering points of a given VRP.' s.authors = 'Mapotempo' s.files = %w[ lib/balanced_vrp_clustering.rb lib/helpers/helper.rb lib/helpers/hull.rb lib/concerns/overloadable_functions.rb ] s.require_paths = %w[lib] s.add_dependency "color-generator" # for geojson debug output s.add_dependency "geojson2image" # for geojson debug output s.add_dependency "awesome_print" # for geojson debug output end
class CreateGenders < ActiveRecord::Migration def self.up create_table :genders do |t| t.string :i18n_name t.timestamps end Gender.create(%w[male female transgender no_say].map { |i| {:i18n_name => i} }) add_index :genders, :i18n_name, :unique => true end def self.down drop_table :genders end end
Given /^"([^"]*)" belongs to "([^"]*)"$/ do | user_email, group_name | user = User.find_by_email( user_email ) group = Group.find_by_name(group_name) group.add_user( user ) end Given /^the group "([^"]*)" exists$/ do |group| group = Factory(:group, :name => group) group.save! end When /^I view the "([^"]*)" page$/ do |group_name| visit group_path(Group.find_by_name(group_name)) end Given /^"([^"]*)" built the "([^"]*)" Hub$/ do |user_email, group_name| user = User.find_by_email(user_email) group = Group.find_by_name(group_name) group.add_creator(user) end Given /^"([^"]*)" is a group admin for "([^"]*)"$/ do |user_email, group_name| user = User.find_by_email(user_email) group = Group.find_by_name(group_name) group.make_admin!(user) end When /^I visit the edit group page for "([^"]*)"$/ do |group_name| visit edit_group_path(Group.find_by_name(group_name)) end Given /^"([^"]*)" is the creator for the "([^"]*)" Hub$/ do |user_email, group_name| user = User.find_by_email(user_email) group = Group.find_by_name(group_name) group.make_creator!(user) end Then /^"([^"]*)" should be a group admin for "([^"]*)"$/ do |user_email, group_name| user = User.find_by_email(user_email) group = Group.find_by_name(group_name) member = group.get_membership(user) member.role.should == Membership::ROLES[1] end Then /^"([^"]*)" should be a regular member for "([^"]*)"$/ do |user_email, group_name| user = User.find_by_email(user_email) group = Group.find_by_name(group_name) member = group.get_membership(user) member.role.should == Membership::ROLES[0] end
module Mautic class Contact < Model alias_attribute :first_name, :firstname alias_attribute :last_name, :lastname def self.in(connection) Proxy.new(connection, endpoint, default_params: { search: '!is:anonymous' }) end def name "#{firstname} #{lastname}" end def assign_attributes(source = {}) super return unless source self.attributes = { tags: (source['tags'] || []).collect { |t| Mautic::Tag.new(@connection, t) }, doNotContact: source['doNotContact'] } end def add_dnc(comments: '') begin @connection.request(:post, "api/contacts/#{id}/dnc/email/add", body: { comments: comments }) clear_changes rescue ValidationError => e self.errors = e.errors end errors.blank? end def remove_dnc begin @connection.request(:post, "api/contacts/#{id}/dnc/email/remove", body: {}) clear_changes rescue ValidationError => e self.errors = e.errors end errors.blank? end def dnc? doNotContact.present? end def self.segment_memberships(connection: nil, contact: nil) contact_id = contact.is_a?(Mautic::Contact) ? contact.id : contact segments = connection.request(:get, %(api/contacts/#{contact_id}/segments))['lists'].values segments end def segment_memberships @connection.request(:get, %(api/contacts/#{id}/segments))['lists'].values end def add_to_company(company = nil) return if company.blank? company = company.is_a?(Mautic::Company) ? company : Mautic::Company.find(@connection, company) company.add_contact self end end end
class AddCarryingCapacityToItems < ActiveRecord::Migration[5.0] def change add_column :items, :carrying_capacity, :decimal, default: 0 end end
class ChangeCpfType < ActiveRecord::Migration[5.0] def change change_column :clientes, :cpf, :bigint, limit: 11 end end
class Account < ActiveRecord::Base USERS_COUNT_MIN = 1 has_many :users, :dependent => :destroy has_many :invoices, :dependent => :destroy has_many :expenses, :dependent => :destroy has_many :audits, :dependent => :destroy has_many :companies, :dependent => :destroy has_many :contacts, through: :companies has_many :attachments, :dependent => :destroy has_many :dtes, :dependent => :destroy has_many :money_accounts, dependent: :destroy accepts_nested_attributes_for :users, :allow_destroy => true validates_uniqueness_of :subdomain validates_presence_of :subdomain, :name validates_format_of :subdomain, :with => /^((?!^(www|folio|app|dev)).)*$/i, :message => "No puedes usar ese nombre", multiline: true validate :check_users_number # The account must have at least one user validates_presence_of :industry, :if => :e_invoice_enabled? validates_presence_of :industry_code, :if => :e_invoice_enabled? #validates_presence_of :e_invoice_resolution_date, :if => :e_invoice_enabled? after_save :initialize_account before_validation :clear_subdomain def self.per_page end def self.subdomain_available?(subdomain) return false if "/^((?!^(www|folio|app|dev)).)*$/i".match(subdomain) !exists?(:subdomain => subdomain.downcase) end def check_invoice_number_availability(number, taxed) value = number.to_i return !invoices.not_draft.taxed.where(number: value).any? if taxed.to_s == "true" return !invoices.not_draft.not_taxed.where(number: value).any? end def invoice_last_used_number(taxed = false) unless invoices.not_draft.any? return (dte_invoice_start_number - 1) if e_invoice_enabled? && taxed return (dte_invoice_untaxed_start_number - 1) if e_invoice_enabled? && !taxed return 0 end #invoices.not_draft.select(:number).order("number desc").limit(1).first.number result = 0 if taxed result = invoices.open.taxed.order("number desc").select(:number).limit(1).first else result = invoices.open.not_taxed.order("number desc").select(:number).limit(1).first end result.nil? ? 0 : result.number end def last_used_dte_nc_number return (dte_nc_start_number - 1) unless has_dte_nc? dtes.dte_ncs.last.folio end def has_dte_nc? dtes.dte_ncs.any? end def owner User.find(owner_id) end def contact_info_complete? attributes.detect {|k,v| v.blank? unless k == "e_invoice_enabled" }.nil? end def companies_in_alphabetycal_order(company_name_like) companies.in_alphabetycal_order(company_name_like) end def owner_name owner.full_name end def trial? plan_id == Plan.trial.id end def has_data? invoices.any? || expenses.any? end def has_invoices? invoices.any? end def invoices_search(params) invoices.search(params) end Invoice::STATUS_NAME.each do |status| define_method "#{status}_invoices" do self.invoices.send(status) end end def self.current_id=(id) Thread.current[:tenant_id] = id end def self.current_id Thread.current[:tenant_id] end # Invoice totals def total_due invoices.total_due end def total_active invoices.total_active end def total_closed invoices.total_closed end def total_draft invoices.total_draft end def users_emails_array users.map {|u| u.email} end private def users_count_valid? users.length >= USERS_COUNT_MIN end def check_users_number unless users_count_valid? errors.add(:base, :users_too_short, :count => USERS_COUNT_MIN) end end def initialize_account set_owner set_trial_plan end def set_owner update_column("owner_id", self.users.last.id) if owner_id.nil? end def set_trial_plan update_column("plan_id", Plan.trial.id) if plan_id.nil? end def clear_subdomain subdomain.split(/\./).join("") end end
FactoryGirl.define do factory :st_publisher_ownership_restaurant, class: OpenStruct do cuisine 'qwe' end end
require 'rails_helper' require 'shoulda/matchers' describe Bodega do it { should have_many(:vinos) } it { should belong_to(:denominacion) } it { should have_many(:comentarios) } context "comentarios and rating" do let(:finca_estacada) { Fabricate :bodega } before do estacada_crianza = Fabricate :vino, bodega_id: finca_estacada.id estacada_reserva = Fabricate :vino, bodega_id: finca_estacada.id estacada_gran_reserva = Fabricate :vino, bodega_id: finca_estacada.id ana = Fabricate :user jose = Fabricate :user marta = Fabricate :user anas_rating_estacada_reserva = Fabricate :rating, user_id: ana.id, vino_id: estacada_reserva.id, valoracion: 7 joses_rating_estacada_reserva = Fabricate :rating, user_id: jose.id, vino_id: estacada_reserva.id, valoracion: 10 martas_rating_estacada_reserva = Fabricate :rating, user_id: marta.id, vino_id: estacada_reserva.id, valoracion: 4 anas_rating_estacada_gran_reserva = Fabricate :rating, user_id: ana.id, vino_id: estacada_gran_reserva.id, valoracion: 9 joses_rating_estacada_gran_reserva = Fabricate :rating, user_id: jose.id, vino_id: estacada_gran_reserva.id, valoracion: 9 martas_rating_estacada_gran_reserva = Fabricate :rating, user_id: marta.id, vino_id: estacada_gran_reserva.id, valoracion: 3 end describe "number_of_rated_vinos" do it "returns the number of rated vinos belonged by the bodega" do expect(finca_estacada.number_of_rated_vinos).to eq(2) end end describe "average_rating" do it "returns the average rating of all the bodega's vinos" do expect(finca_estacada.average_rating).to eq(7) end end end end
require "spec_helper" describe Edge do let(:nodes) { [Node.new("Node 1"), Node.new("Node 2")] } subject { Edge.new(nodes, 10) } describe '#initialize' do its(:nodes) { should == nodes } its(:value) { should == 10 } end describe '#select_complement_node' do it 'returns the complement node of the edge' do subject.select_complement_node(nodes.first).should == nodes.last end end end
FactoryGirl.define do factory 'denormalization/queue', class: 'Treasury::Models::Queue' do sequence(:name) { |n| "name#{n}" } sequence(:table_name) { |n| "table_name#{n}" } sequence(:trigger_code) { |n| "trigger_code#{n}" } end end
class ApplicationController < ActionController::Base protect_from_forgery before_filter :need_login, :unless => lambda { |controller| controller_name == 'sessions' || controller_name == 'home' } protected def need_login unless already_logged_in? session[:url_desejada] = request.url redirect_to new_session_path end end def already_logged_in? !session[:usuario_id].nil? end end
class FixStateValueInPages < ActiveRecord::Migration def up Page.where(:state => nil).update_all(:state => "published") end end
class Racao < ActiveRecord::Base attr_accessible :ativa, :cod, :description validates_presence_of :cod, :description validates_uniqueness_of :cod #verifica codigo unico no banco validates_length_of :cod, minimum: 8, maximum: 8 # uma raรงรฃo pode ter varias receitas has_many :receitas, dependent: :destroy end
class BoxesController < ApplicationController before_filter :signed_in_user before_filter :correct_user, :only => [:show, :edit, :update, :destroy] before_filter :correct_user_new, :only => [:new] def new @box = Box.new end def create box = Box.new(params[:box]) if box.save flash[:success] = "Box successfully created!" redirect_to current_user else render 'new' end end def show @box = Box.find(params[:id]) end def edit @box = Box.find(params[:id]) end def update @box = Box.find(params[:id]) if @box.update_attributes(params[:box]) flash[:success] = "Box successfully updated!" redirect_to current_user else render 'edit' end end def destroy @box = Box.find(params[:id]) if @box.destroy flash[:success] = "Box successfully removed!" redirect_to current_user else flash[:error] = "An error occured while trying to delete your box!" redirect_to current_user end end private def signed_in_user unless signed_in? store_location redirect_to signin_url, :notice => "You must be logged in to view that!" end end def correct_user @box = Box.find(params[:id]) @user = @box.user redirect_to current_user, :notice => "You must be #{@user.name} to view that!" unless @user == current_user end def correct_user_new @user = User.find(params[:user_id]) redirect_to current_user, :notice => "You must be #{@user.name} to access that function!" unless @user == current_user end end
module Pacer module Routes::RouteOperations def fast_group_count(hash_map = nil) chain_route :side_effect => :group_count, :hash_map => hash_map end end module SideEffect module GroupCount def hash_map=(hash_map) @hash_map = hash_map end def at_least(n) @min = n self end def to_h h = {} min = @min || 0 cap.first.each do |k,v| h[k] = v if v >= min end h end protected def attach_pipe(end_pipe) if @hash_map @pipe = com.tinkerpop.pipes.sideeffect.GroupCountPipe.new @hash_map else @pipe = com.tinkerpop.pipes.sideeffect.GroupCountPipe.new end @pipe.set_starts(end_pipe) if end_pipe @pipe end end end end
# frozen_string_literal: true require 'feature_spec_helper' include Selectors::Dashboard describe Collection, type: :feature do let(:current_user) { create(:user, display_name: 'Jill User') } let(:title) { 'Test Collection Title' } let(:subtitle) { 'Machu Picchu' } before { sign_in_with_js(current_user) } describe 'creating a new collection from the dashboard' do it 'displays the new collection page' do go_to_dashboard db_create_empty_collection_button.click expect(page).to have_content('Create New Collection') within('div#descriptions_display') do expect(page).to have_selector('label', class: 'required', text: 'Title') expect(page).to have_selector('label', text: 'Subtitle') expect(page).to have_selector('label', class: 'required', text: 'Description') expect(page).to have_selector('label', class: 'required', text: 'Keyword') end within('div.collection_form_visibility') do expect(find('input#visibility_open')).to be_checked end end end describe 'creating new collections' do before do visit(new_collection_path) fill_in 'Title', with: title fill_in 'Subtitle', with: subtitle fill_in 'Description', with: 'description' fill_in 'Keyword', with: 'keyword' end context 'without any files' do it 'creates an empty collection' do click_button 'Create Empty Collection' expect(page).to have_content('Collection was successfully created.') expect(page).to have_content(title) expect(page).to have_content(subtitle) # The link to the creator search should look like this # with the correct solr key 'creator_name_sim': # catalog?f[creator_name_sim][]=Jill+User expect(find_link('Jill User')[:href]).to match /catalog\?f%5Bcreator_name_sim%5D%5B%5D=Jill\+User/ end end context 'when adding existing works' do let!(:file1) { create(:file, title: ['First file'], depositor: current_user.login) } let!(:file2) { create(:file, title: ['Second file'], depositor: current_user.login) } it 'adds existing works after the collection is created' do click_button 'Create Collection and Add Existing Works' expect(page).to have_content('Collection was successfully created.') check 'check_all' click_button "Add to #{title}" expect(page).to have_content(title) within('dl.metadata-collections') do expect(page).to have_content('Total Items') expect(page).to have_content('2') end within('table.table-striped') do expect(page).to have_content('First file') expect(page).to have_content('Second file') end end end context 'when adding new works' do it 'creates new works after the collection is created' do click_button 'Create Collection and Upload Works' expect(page).to have_content('Collection was successfully created.') expect(page).to have_content('Add Multiple New Works') within('ul.nav-tabs') { click_link('Collections') } expect(page).to have_select('batch_upload_item_collection_ids', selected: title) end end end describe 'selecting files from the dashboard' do let!(:file1) { create(:file, title: ['First file'], depositor: current_user.login) } let!(:file2) { create(:file, title: ['Second file'], depositor: current_user.login) } it 'creates a new collection using the selected files' do go_to_dashboard_works check 'check_all' click_button 'Add to Collection' db_create_populated_collection_button.click fill_in 'Title', with: title fill_in 'Subtitle', with: subtitle fill_in 'Description', with: 'description' fill_in 'Keyword', with: 'keyword' within('div.primary-actions') do expect(page).not_to have_button('Create Empty Collection') expect(page).not_to have_button('Create Collection and Upload Works') expect(page).not_to have_button('Create Collection and Add Existing Works') end within('table.table-striped') do expect(page).to have_content('First file') expect(page).to have_content('Second file') end click_button('Create New Collection') expect(page).to have_content 'Collection was successfully created.' expect(page).to have_content file1.title.first expect(page).to have_content file2.title.first end end end
require 'fileutils' class CreateFile < Command def initialize(path, contents) super "Create file: #{path}" @path = path @contents = contents end def execute f = File.open(@path, 'w') f.write @contents f.close end def unexecute File.delete(@path) end end
class CreateChats < ActiveRecord::Migration def change create_table :chats do |t| t.text :message t.belongs_to :user, index: true t.belongs_to :room, index: true t.datetime :deleted_at, index: true t.datetime :created_at, null: false, index: true end end end
# -*- encoding: utf-8 -*- # stub: react_webpack_rails 0.7.0 ruby lib Gem::Specification.new do |s| s.name = "react_webpack_rails".freeze s.version = "0.7.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Rafa\u{142} Gawlik".freeze, "Rados\u{142}aw Pi\u{105}tek".freeze] s.bindir = "exe".freeze s.date = "2017-03-30" s.description = "".freeze s.email = ["gawlikraf@gmail.com".freeze, "radek.nekath@gmail.com".freeze] s.homepage = "https://github.com/netguru/react_webpack_rails".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "2.5.2".freeze s.summary = "React and Rails integration done with webpack".freeze s.installed_by_version = "2.5.2" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<bundler>.freeze, ["~> 1.14.6"]) s.add_development_dependency(%q<rake>.freeze, ["~> 12.0"]) s.add_development_dependency(%q<rspec>.freeze, ["~> 3.5"]) s.add_runtime_dependency(%q<rails>.freeze, [">= 3.2"]) else s.add_dependency(%q<bundler>.freeze, ["~> 1.14.6"]) s.add_dependency(%q<rake>.freeze, ["~> 12.0"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.5"]) s.add_dependency(%q<rails>.freeze, [">= 3.2"]) end else s.add_dependency(%q<bundler>.freeze, ["~> 1.14.6"]) s.add_dependency(%q<rake>.freeze, ["~> 12.0"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.5"]) s.add_dependency(%q<rails>.freeze, [">= 3.2"]) end end
require 'base64' require 'json' module Gitlab class Workhorse SEND_DATA_HEADER = 'Gitlab-Workhorse-Send-Data' class << self def send_git_blob(repository, blob) params = { 'RepoPath' => repository.path_to_repo, 'BlobId' => blob.id, } [ SEND_DATA_HEADER, "git-blob:#{encode(params)}", ] end def send_git_archive(project, ref, format) format ||= 'tar.gz' format.downcase! params = project.repository.archive_metadata(ref, Gitlab.config.gitlab.repository_downloads_path, format) raise "Repository or ref not found" if params.empty? [ SEND_DATA_HEADER, "git-archive:#{encode(params)}", ] end protected def encode(hash) Base64.urlsafe_encode64(JSON.dump(hash)) end end end end
class Epic include Mongoid::Document include Mongoid::Timestamps # adds created_at and updated_at fields # field <name>, :type => <type>, :default => <value> # You can define indexes on documents using the index macro: # index :field <, :unique => true> # You can create a composite key in mongoid to replace the default id using the key macro: # key :field <, :another_field, :one_more ....> field :id field :phase field :storyName field :storyDesc field :assigned field :storyCount field :fname embeds_many :stories def getStoryById(id) return stories.find(id) end end
class TeamsController < ApplicationController def new @team = Team.new end def create @team = Team.new(team_params) if @team.save redirect_to @team else render 'new' end end def show @team = Team.find(params[:id]) end def index @teams = Team.all end def edit @team = Team.find(params[:id]) end def update @team = Team.find(params[:id]) if @team.update(params[:outcome].permit(:name)) redirect_to @team else render 'edit' end end def destroy @team = Team.find(params[:id]) @team.destroy redirect_to teams_path end private def team_params params.require(:team).permit(:name) end end
module Texto class Application < Gtk::Application def initialize super 'com.agent97.texto', Gio::ApplicationFlags::FLAGS_NONE signal_connect :activate do |application| window = Texto::ApplicationWindow.new(application) window.present end end end end
# encoding: utf-8 # === COPYRIGHT: # Copyright (c) Jason Adam Young # === LICENSE: # see LICENSE file module BoxscoresHelper def boxscore_title(boxscore) "#{boxscore.home_team.abbrev} vs. #{boxscore.away_team.abbrev} - #{boxscore.date.strftime("%b %d")}" end end
# frozen_string_literal: true class FinancialEntriesQuery < ApplicationQuery def initialize @relation = FinancialEntry.order(created_at: :desc) end def includes @relation = relation.includes(:user) self end end
module ApplicationHelper # Returns the full title on a per-page basis. def full_title(page_title = '') "#{(page_title + ' | ') unless page_title.empty?}Ruby on Rails Tutorial Sample App" end end
require 'test_helper' #require 'test_helper' #require 'webapp_exceptions' class SessionsControllerTest < WebappFunctionalTestCase # Replace this with your real tests. fixtures :users, :persistent_sessions test "should show login form" do get :new #Assert the instance variables assert_not_nil assigns["handle_or_email"] assert_not_nil assigns["password"] assert_not_nil assigns["keep_me_logged"] assert_response :success end ##Login negative tests test "should not login with inexisting handle or email" do #aoonis = users(:aoonis) post :create, :handle_or_email=>"unexistent", :password=>"somepassword", :keep_me_logged=>nil #Should render the login form again and with the with flash[:error]="Invalid username/login" #assert the the rendered action is "new" assert_redirected_to new_session_url #assert that an error occured and it's in the flas assert_error_flashed(:invalid_login_name_or_email) end test "should not login with empty handle or email" do #aoonis = users(:aoonis) post :create, :handle_or_email=>"", :password=>"somepassword", :keep_me_logged=>nil #Should render the login form again and with the with flash[:error]="Invalid username/login" #assert the the rendered action is "new" assert_redirected_to new_session_url #assert that an error occured and it's in the flas assert_error_flashed(:invalid_login_name_or_email) end test "should not login with empty password" do aoonis = users(:aoonis) post :create, :handle_or_email=>users(:aoonis).handle, :password=>"", :keep_me_logged=>nil #Should render the login form again and with the with flash[:error]="Invalid username/login" #assert the the rendered action is "new" #assert_redirected_to new_session_url assert_response :unauthorized #assert that an error occured and it's in the flas assert_error_flashed(:wrong_password) end test "should not login with wrong password" do #aoonis = users(:aoonis) post :create, :handle_or_email=>users(:aoonis).email, :password=>"some password", :keep_me_logged=>nil #Should render the login form again and with the with flash[:error]="Invalid username/login" #assert the the rendered action is "new" assert_response :unauthorized #assert_redirected_to new_session_url #assert that an error occured and it's in the flas assert_error_flashed(:wrong_password) end test "should not login inactive users" do #inactiveUser = users(:aoonis_inactive) post :create, :handle_or_email=>users(:aoonis_inactive).handle, :password=>"132435", :keep_me_logged=>"1" assert_nil session[:logged_user_id] assert_redirected_to root_url assert_error_flashed(:user_not_activated_yet) assert_nil PersistentSession.find_by_user_id(users(:aoonis_inactive).id) end test "should not authenticate facebook users" do post :create, :handle_or_email=>users(:aoonis_fb).handle, :password=>"132435", :keep_me_logged=>"0" assert_redirected_to new_session_url assert_error_flashed(:fb_user_not_authenticable_message,users(:aoonis_fb).handle) end #positive tests #Test for a valid email/password test "should login with valid email and password" do #aoonis = users(:aoonis) post :create, :handle_or_email=>users(:aoonis).email.upcase, :password=>"132435", :keep_me_logged=>"0" assert_redirected_to root_url assert_notice_flashed(:login_successfull) #check if the session has :user_id = users(:aoonis).id assert_not_nil session[:user_session] #assert_equal users(:aoonis).id, session[:logged_user_id] assert_equal users(:aoonis).id, session[:user_session].user_id assert_equal users(:aoonis).full_name, session[:user_session].name assert_nil PersistentSession.find_by_user_id(users(:aoonis).id) assert_nil cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] end test "should create an auto-login cookie in the client when keep me logged is selected" do post :create, :handle_or_email=>users(:aoonis).email, :password=>"132435", :keep_me_logged=>"1" assert_redirected_to root_url assert_notice_flashed(:login_successfull) assert_not_nil session[:user_session] #assert_equal users(:aoonis).id, session[:logged_user_id] assert_equal users(:aoonis).id, session[:user_session].user_id assert_equal users(:aoonis).full_name, session[:user_session].name #Should be created a persistent session assert_not_nil PersistentSession.find_by_user_id(users(:aoonis).id) #Get the key key = PersistentSession.find_by_user_id(users(:aoonis).id).key assert_equal "#{users(:aoonis).id}:#{key}", cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] end test "should send user to home page and show an error when trying to destroy inexistent session" do get :destroy #assert_nil session[:logged_user_id] assert_nil session[:user_session] assert_nil session[:facebook_session] assert_redirected_to root_url end test "should destroy session and return to home page with a success message" do get :destroy , {}, {:user_session=>UserSession.new(users(:aoonis)) } assert_notice_flashed(:session_destroyed) assert_nil session[:user_session] assert_redirected_to root_url end test "should destroy session, remove persistent session and remove cookie" do #Scenario: User have previouly create a persistent session. #Setup scenario persistent_session = PersistentSession.create_session(users(:aoonis).id) @request.cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] = "#{users(:aoonis).id}:#{persistent_session.key}" assert_not_nil PersistentSession.find_by_user_id(users(:aoonis).id) assert_not_nil @request.cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] #test get :destroy , {}, {:user_session=>UserSession.new(users(:aoonis)) } assert_notice_flashed(:session_destroyed) assert_nil session[:user_session] assert_redirected_to root_url assert_nil PersistentSession.find_by_user_id(users(:aoonis).id) end test "should do auto login with correct data" do #When a persistent session exists, with the correct cookie, it should be auto logged inf #Create a cookie persistent_session = PersistentSession.create_session(users(:aoonis).id) @request.cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] = "#{users(:aoonis).id}:#{persistent_session.key}" get :new, {}, {} assert_not_nil session[:user_session] #assert_equal users(:aoonis).id, session[:logged_user_id] assert_equal users(:aoonis).id, session[:user_session].user_id assert_equal users(:aoonis).full_name, session[:user_session].name #Should be created a persistent session assert_not_nil PersistentSession.find_by_user_id(users(:aoonis).id) assert_not_equal PersistentSession.find_by_user_id(users(:aoonis).id).key, persistent_session.key assert_not_nil @request.cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] assert_redirected_to new_session_url end test "should not do auto login with wrong data" do persistent_session = PersistentSession.create_session(users(:aoonis).id) @request.cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] = "#{users(:aoonis).id}:#{persistent_session.key}10" get :new, {}, {} assert_nil session[:user_session] #assert_equal users(:aoonis).id, session[:logged_user_id] #Should be created a persistent session assert_nil PersistentSession.find_by_user_id(users(:aoonis).id) assert_nil cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] assert_redirected_to root_url end test "should not do auto login with missing data" do #persistent_session = PersistentSession.create_session(users(:aoonis).id) @request.cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] = "#{users(:aoonis).id}:121212121210" get :new, {}, {} assert_nil session[:user_session] #assert_equal users(:aoonis).id, session[:logged_user_id] #Should be created a persistent session assert_nil PersistentSession.find_by_user_id(users(:aoonis).id) assert_nil cookies[WebappConstants::AUTO_LOGIN_COOKIE_NAME] assert_redirected_to root_url end end
class Blog::Post < ActiveRecord::Base include PgSearch multisearchable against: [:title, :body] self.table_name_prefix = "blog_" acts_as_commentable has_and_belongs_to_many :categories belongs_to :author, class_name: "User" include App::Permalink has_permalink :title validates :title, :body, :author_id, presence: true scope :visible, -> { where(visible: true) } scope :not_visible, -> { where.not(visible: true) } default_scope -> { order('published_at DESC') } before_save :generate_published_at_if_needed private def generate_published_at_if_needed time = published_at.present? ? published_at : Time.now self.published_at = time end end
Metube::Application.routes.draw do root "videos#show_all" #look at line 9. This refers to the Views/Folder not the as: # ACTUAL URL VIEWS FOLDER #Named Route (/pages/week-4/rails-intro-routes) get "/videos/gladiator" => "videos#show_gladiator", as: 'gladiator_video' get "/videos/air_force_one" => 'videos#show_air_force_one', as: 'air_force_one_sucks' get '/videos/fight_club' => 'videos#show_fight_club', as: 'fight_club_video' get '/videos/dumb_and_dumber' => 'videos#show_dumb_and_dumber', as: 'dumb_and_dumber_video' get '/videos/all' => 'videos#show_all', as: 'show_all_video' get 'posts/atlanta' => 'posts#atlanta' get 'posts/minneapolis' => 'posts#minneapolis' #get "<some_url>" => "<controller_name>#<method_name>" end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require "csv" CSV.foreach('db/user.csv') do |row| User.create(:name => row[0], :password => row[1], :usertag => row[2].to_i, :nickname => row[3]) end CSV.foreach('db/course.csv') do |row| Course.create(:course_name => row[0]) end CSV.foreach('db/registration.csv') do |row| Registration.create(:course_id => row[0],:user_id => row[1]) end CSV.foreach('db/lesson.csv') do |row| Lesson.create(:title => row[0],:body => row[1],:file_path => row[2],:course_id => row[3],:user_id => row[4]) end CSV.foreach('db/question.csv') do |row| Question.create(:title => row[0],:body => row[1],:metoo => row[2],:solved=> row[3],:lesson_id => row[4],:user_id => row[5]) end CSV.foreach('db/answer.csv') do |row| Answer.create(:body => row[0],:score => row[1],:authorized => row[2], :question_id => row[3],:user_id => row[4]) end CSV.foreach('db/comment.csv') do |row| Comment.create(:body => row[0],:score => row[1], :answer_id => row[2],:user_id => row[3]) end CSV.foreach('db/bar.csv') do |row| Bar.create(:page => row[0],:score => row[1], :lesson_id => row[2]) end
module LittleMapper module MapperInstanceMethods def to_persistent(entity) pe = persisted?(entity) ? find_persistent_by_id(entity.id) : self.class.persistent_entity.new self.class.mappings.each do |m| m.from(entity).to_persistent(pe) end pe end def to_entity(persistent) e = self.class.entity.new e.id = persistent.id # probably set this only if configured & see duplication below self.class.mappings.each do |m| m.from(persistent).to_entity(e) end e end def persisted?(entity) !entity.id.nil? # should maybe check for empty strings too? end def <<(entity) pe = to_persistent(entity) if pe.save entity.id = pe.id unless entity.id # set this only if configured LittleMapper::Result::RepoSuccess.new(pe) else LittleMapper::Result::RepoFailure.new(pe) end end def find_persistent_by_id(id) self.class.persistent_entity.find_by_id(id) end def find_by_id(id) pe = find_persistent_by_id(id) return nil unless pe to_entity(pe) end def find_all self.class.persistent_entity.all.collect { |e| to_entity(e) } end def last to_entity(self.class.persistent_entity.last) end end end
class AddLogoToAdvertisers < ActiveRecord::Migration def change add_column :advertisers, :logo, :string rename_table :campagnes, :campaigns remove_column :campaigns, :file_url, :string remove_column :campaigns, :meta_data, :string end end
class MathDojo attr_accessor :result def initialize @result = 0 end # splat operator for unknow number of parameters def add(*args) # flatten returns a new one-dimensional array, flattens self recursively newarr = args.flatten #puts newarr newarr.each do |el| @result += el end self end def subtract(*args) subtotal = 0 newarr = args.flatten #puts newarr newarr.each do |num| subtotal += num end @result -= subtotal self end def multiply(*args) subtotal = 0 newarr = args.flatten newarr.each do |num| subtotal += num end @result *= subtotal self end def reset() @result = 1 self end end #puts MathDojo.new.add(2).add(2, 5).subtract(3, 2).result #puts MathDojo.new.add(1).add([3, 5, 7, 8], [2, 4.3, 1.25]).subtract([2,3], [1.1, 2.3]).result
class AlterTableMovementsSaldoClear < ActiveRecord::Migration def change change_column :movements, :saldo, :decimal, default: 0, precision: 8, scale: 2 end end
class Scrabble SCORE = { 1 => %w(A E I O U L N R S T), 2 => %w(D G), 3 => %w(B C M P), 4 => %w(F H V W Y), 5 => %w(K), 8 => %w(J X), 10 => %w(Q Z) } def initialize(word) @word = word end def score return 0 if @word.nil? @word.gsub(/[^a-z]/i, '').chars.inject(0) do |sum, char| SCORE.select { |_, v| v.include? char.upcase }.keys.first + sum end end def self.score(word) new(word).score end end # Done in 16 min
# frozen_string_literal: true class NewsletterService attr_reader :ambassador MAILCHIMP_API_KEY = Rails.application.credentials[:production][:mailchimp][:api_key].freeze AMBASSADOR_LIST_ID = '8ae9ed9f0d'.freeze def initialize(ambassador) @ambassador = ambassador end def subscribe ambassador_list .members(lower_case_md5_hashed_email_address) .upsert(body: { email_address: ambassador.email, status: "subscribed", merge_fields: { FNAME: ambassador.first_name, LNAME: ambassador.last_name } }) end private def ambassador_list gibbon.lists(AMBASSADOR_LIST_ID) end def gibbon Gibbon::Request.new(api_key: MAILCHIMP_API_KEY) end def lower_case_md5_hashed_email_address return unless ambassador.email Digest::MD5.hexdigest ambassador.email.downcase end end
FactoryBot.define do factory :product do title { Faker::Commerce.product_name } price { Faker::Commerce.price } image { Faker::Internet.url(host: 'railsfragrances.com') + ['.jpg, .png'].sample } end end
require_relative 'basics' #Interesting Ruby features #========================= #Everything is an object #----------------------- puts "Are these all Objects?" puts "something".is_a? Object puts 1.is_a? Object puts true.is_a? Object puts nil.is_a? Object #Modules #------- module Titles REGULAR = ['Mr.', 'Mrs.', 'Miss','Dr.'].freeze HONORIFIC = ['Sir', 'Your Highness'].freeze def inquire_after puts "How are you doing, #{@person}?" end end class Baz < Bar include Titles def use_title puts "Hey, #{REGULAR[0]}#{@person}" end end baz = Baz.new baz.inquire_after baz.use_title #Metaprogramming #--------------- class Talker def self.say(message, person) puts "#{message.capitalize}, #{person}!" end def self.method_missing(method_name, *arguments, &block) if method_name.to_s =~ /^say_(.*)$/ say($1, arguments.first) else super end end end Talker.say_hello 'Fullstacker' Talker.say_bye 'Fullstacker' #Duck typing #----------- class KnownTalker < Talker def self.respond_to?(method_sym, include_private = false) if method_sym.to_s =~ /^say_(.*)$/ true else super end end end puts "Does KnownTalker know how to say something?" puts KnownTalker.respond_to?(:say_something) puts "Does KnownTalker know how to sing something?" puts KnownTalker.respond_to?(:sing_something) #Blocks #------ def manipulate(message) puts "Message before manipulation is #{message}" message = yield(message) puts "Message after manipulation is #{message}" end manipulate("Forwards") { |str| str.reverse } #Enumerable #---------- squares_array = [1,2,3,4,5,6].map do |number| number * number end puts squares_array.inspect
require 'test_helper' class SubscriptionsControllerTest < ActionController::TestCase def setup @controller = SubscriptionsController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_should_get_index login_as :trevor get :index assert_response :success end def test_should_toggle_subscription login_as :trevor topic, user = topics(:Testing), users(:trevor) get :toggle, :id => topic.to_param assert_response :success assert user.subscriptions.include?(topic) get :toggle, :id => topic.to_param assert_response :success assert !user.subscriptions.include?(topic) end def test_should_destroy_subscription end end
class RLanguagesController < ApplicationController before_action :set_r_language, only: [:show, :edit, :update, :destroy] # GET /r_languages # GET /r_languages.json def index @r_languages = RLanguage.all end # GET /r_languages/1 # GET /r_languages/1.json def show end # GET /r_languages/new def new @r_language = RLanguage.new end # GET /r_languages/1/edit def edit end # POST /r_languages # POST /r_languages.json def create @r_language = RLanguage.new(r_language_params) respond_to do |format| if @r_language.save format.html { redirect_to @r_language, notice: 'R language was successfully created.' } format.json { render action: 'show', status: :created, location: @r_language } else format.html { render action: 'new' } format.json { render json: @r_language.errors, status: :unprocessable_entity } end end end # PATCH/PUT /r_languages/1 # PATCH/PUT /r_languages/1.json def update respond_to do |format| if @r_language.update(r_language_params) format.html { redirect_to @r_language, notice: 'R language was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @r_language.errors, status: :unprocessable_entity } end end end # DELETE /r_languages/1 # DELETE /r_languages/1.json def destroy @r_language.destroy respond_to do |format| format.html { redirect_to r_languages_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_r_language @r_language = RLanguage.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def r_language_params params.require(:r_language).permit(:language, :properties) end end
class AddDoneToTask < ActiveRecord::Migration def change add_column :tasks, :is_done, :bool, default: false add_column :tasks, :done_date, :date end end
class CreateEvents < ActiveRecord::Migration def change create_table :events do |t| t.integer :source_id t.string :source_type t.references :user, index: true t.string :action t.references :project, index: true t.string :extra_1 t.string :extra_2 t.timestamps null: false end add_index :events, [:source_id, :source_type], name: "index_events_on_source_id_and_source_type" end end
class Tagged < ActiveRecord::Base belongs_to :micropost belongs_to :synonymous_club validates :micropost, presence: true validates :synonymous_club, presence: true end
#!/usr/bin/env ruby require 'nokogiri' class Nokogiri::XML::Element def get_field name f = css("fields > field[name='#{name}'] values value") if f.children.length > 1 f.children.map { |x| x.content } else f.inner_html end end end
class Stack attr_reader :lifo def initialize @lifo = [] end def push(el) lifo << el end def pop lifo.pop end def peek lift[-1] end end class Queue attr_reader :fifo def initialize @fifo = [] end def push(el) fifo << el end def pop fifo.shift end def peek fifo[0] end end class Map attr_reader :nested def initialize nested = [] end def set(key, value) index = 0 nested.each_with_index do |ele, i| if ele == key index += i end end if index != 0 nested[index][1] = value else nested.push([key, value]) end value end def get(key) nested.each do |i| if pair[0] == key return pair[1] end end nil end def delete(key) value = get(key) nested.reject! { |pair| pair[0] == key } value end def show nested.each do |el| el end end end
class ImagesController < ApplicationController before_action :authenticate_user! before_action :correct_user, only: [:destroy] def new @image = current_user.images.build end def create @image = current_user.images.build(image_params) if @image.save flash[:success] = '็”ปๅƒใ‚’ๆŠ•็จฟใ—ใพใ—ใŸ' redirect_to root_path else @images = current_user.feed_images.order('created_at DESC').page(params[:page]) flash.now[:danger] = '็”ปๅƒใฎๆŠ•็จฟใซๅคฑๆ•—ใ—ใพใ—ใŸ' render 'new' end end def destroy @image = Image.find(params[:id]) @image.destroy if @image flash[:success] = '็”ปๅƒใ‚’ๅ‰Š้™คใ—ใพใ—ใŸ' redirect_to root_path end private def image_params params.require(:image).permit(:image, :content) end def correct_user @image = current_user.images.find_by(id: params[:id]) unless @image redirect_to root_path end end end
class Cell attr_accessor :alive, :neighbours def self.dead Cell.new(false) end def self.alive Cell.new(true) end def initialize(alive) @alive = alive end alias_method :alive?, :alive def next_state alive_count = neighbours.count { |n| n.alive? } if alive case alive_count when 0..1 false when 2..3 true else false end else if alive_count == 3 return true end end end def print_cell if alive? print "X" else print " " end end end
class KeywordAssociationsController < ApplicationController def create @verse = Verse.find(params[:verse_id]) @keyword = Keyword.where('value = ?', params[:keyword][:value]).take(1).first unless @keyword.present? @keyword = Keyword.new @keyword.value = params[:keyword][:value] @keyword.save end @association = KeywordAssociation.new @association.verse_id = @verse.id @association.keyword_id = @keyword.id @association.count = 1 @association.ip_address = request.remote_ip @verse.keyword_associations << @association @verse.save render json: @association.as_json( include: { keyword: { only: :value } } ) end def update @association = KeywordAssociation.find(params[:id]) @association.count = @association.count + 1 @association.save render json: @association.as_json( include: { keyword: { only: :value } } ) end def delete @association = KeywordAssociation.find(params[:id]) keyword_id = @association.keyword_id @association.destroy @associations = KeywordAssociation.where('keyword_id = ?', keyword_id) unless @associations.present? Keyword.find(keyword_id).destroy end render nothing: true end def filter @keyword = Keyword.where('value = ?', params[:keyword]).first @verses = Array.new if @keyword.present? @keyword.keyword_associations.each do |association| @verses << association.verse end end render json: { "verses" => @verses.map do |verse| verse.as_json( include: { keyword_associations: { include: { keyword: { only: :value } }, only: :count } } ) end } end end
class CreatePages < ActiveRecord::Migration def self.up say "PAGES" say "-------------" create_table :pages do |page| page.string :title, :slug, :description, :keywords, :language page.text :body page.string :class_name, {:default => 'Page'} page.integer :lft, :rgt, :parent_id page.integer :status_id, { :default => 1 } page.integer :layout_id, { :default => 1 } page.integer :template_id, { :default => 1 } page.integer :author_id, { :default => 1 } page.timestamps page.datetime :deleted_at end # INDEXES say "adding indexes ..." add_index :pages, :title add_index :pages, :slug add_index :pages, :class_name end def self.down drop_table :pages end end
require 'open-uri' require 'nokogiri' require 'yaml' def read_html(url) charset = nil html = open(url) do |f| charset = f.charset f.read end return Nokogiri::HTML.parse(html, nil, charset) end def parse_day(doc) daysets = doc.xpath("//html/body/div/div[4]/table/tr/td/div/table/tr/td[2]/h3") dayarray = [] daysets.each{|dayset| text = dayset.text if date = text.match(/([0-9]+) ([0-9]+), ([0-9]+)/) then dayarray.push(Date.strptime(date[3].to_s + "-" + date[2].to_s + "-" + date[1].to_s, '%Y-%m-%d')) end } return dayarray end def parse_title(doc) titlesets = doc.xpath("//html/body/div/div[4]/table/tr/td/div/table/tr/td[2]/div") titlearray = [] titlesets.each{|titleset| lilist = titleset.xpath("ul/li") linearray = [] lilist.each{|line| time = nil end_time = nil title = nil uri = nil a_tag = line.at("a") unless a_tag.nil? then link = a_tag["href"] if url = link.match(/http:\/\/re.wikiwiki.jp\/\?(.*)/) then uri = url[1] end end if time_title = line.text.match(/([0-9]+)ๆ™‚([0-9]+)ๅˆ†[๏ฝž~]([0-9]+)ๆ™‚([0-9]+)ๅˆ†[[:blank:]]?+(.*)/) then time = {'hour' => time_title[1].to_i, 'min' => time_title[2].to_i} end_time = {'hour' => time_title[3].to_i, 'min' => time_title[4].to_i} title = time_title[5] elsif time_title = line.text.match(/([0-9]+)ๆ™‚([0-9]+)ๅˆ†(ไปฅ้™|้ ƒ|ใใ‚‰ใ„)?+(๏ฝž|~)?+[[:blank:]]?+(.*)/) then time = {'hour' => time_title[1].to_i, 'min' => time_title[2].to_i} title = time_title[5] elsif time_title = line.text.match(/ๆœชๅฎš[[:blank:]](.*)/) then title = time_title[1] elsif time_title = line.text.match(/(.*)/) then title = time_title[1] end title.gsub!(/โ– /,'') if title.include?('โ– ') linearray.push({'time' => time, 'end_time' => end_time, 'title' => title, 'uri' => uri}) unless title.nil? } titlearray.push(linearray) } return titlearray end def make_event(dayarray, titlearray) eventarray = [] dayarray.zip(titlearray){|day,titles| titles.each{|title| event = {'date' => day, 'time' => title['time'], 'title' => title['title'], 'end_time' => title['end_time'], 'uri' => title['uri']} eventarray.push(event) } } return eventarray end pages = ['201803', '201804', '201805', '201806', '201807', '201808', '201809', '201810', '201811', '201812', '201901', '201902', '201903', '201904', '201905', '201906', '201907'] base_url = 'https://wikiwiki.jp/nijisanji/?plugin=minicalendar&file=%E9%85%8D%E4%BF%A1%E4%BA%88%E5%AE%9A&date=' pages.each{|month| puts month url = base_url + month doc = read_html(url) day_a = parse_day(doc) title_a = parse_title(doc) event_a = make_event(day_a, title_a) YAML.dump(event_a, File.open('resource/' + month + 'wiki.yaml', 'w')) }
class ParkingStallsController < ApplicationController load_resource :tenant load_resource :user load_and_authorize_resource :parking_stall, :through => [:user, :tenant ] before_filter :set_and_authorize_parent before_filter :spread_breadcrumbs def index end def show end def new @parking_stall.lot = 'default' @parking_stall.name = ParkingStall.order(:name).last.try(:name).to_i + 1 end def create @parking_stall = @parent.parking_stalls.build(params[:parking_stall]) if @parking_stall.save redirect_to [@parent, @parking_stall], :notice => t('parking_stalls.controller.successfuly_created') else render :new end end def edit end def update if @parking_stall.update_attributes(params[:parking_stall]) redirect_to [@parent, @parking_stall], :notice => t('parking_stalls.controller.successfuly_updated') else render :edit end end def destroy @parking_stall.destroy m = method( :"#{@parent.class.name.underscore}_parking_stalls_url" ) redirect_to m.(@parent), :notice => t('parking_stalls.controller.successfuly_destroyed') end private def set_and_authorize_parent @parent = @user || @tenant authorize! :read, @parent end def spread_breadcrumbs if @user add_breadcrumb t("users.index.page_title"), tenant_users_path(@user.current_tenant) add_breadcrumb @user, tenant_user_path(@user.current_tenant, @user) add_breadcrumb t("parking_stalls.index.page_title"), user_parking_stalls_path(@user) if @parking_stall && !@parking_stall.new_record? add_breadcrumb @parking_stall, user_parking_stall_path(@user, @parking_stall) end end if @tenant add_breadcrumb t("parking_stalls.index.page_title"), tenant_parking_stalls_path(@tenant) if @parking_stall && !@parking_stall.new_record? add_breadcrumb @parking_stall, tenant_parking_stall_path(@tenant, @parking_stall) end end end end
class ContentsController < ApplicationController before_action :set_content, only: [:show, :edit, :update, :destroy] def index @contents = Content.all end def show @content = Content.find(params[:id]) @opinions = @content.opinions.paginate(page: params[:page]) @content_attachments = @content.content_attachments end def new @content = Content.new @content_attachment = @content.content_attachments.build end def create @content = Content.new(content_params) if @content.save params[:content_attachments]['photo'].each do |a| @content_attachment = @content.content_attachments.create!(:photo => a, :content_id => @content.id) end flash[:success] = "ะ”ะพะฑะฐะฒะปะตะฝะพ" redirect_to @content else render 'new' end end def edit @content = Content.find(params[:id]) end def update @content = Content.find(params[:id]) if @content.update_attributes(content_params) flash[:success] = "ะžะฑะฝะพะฒะปะตะฝะพ!" redirect_to @content else render 'edit' end end private def set_content @content = Content.find(params[:id]) end def content_params params.require(:content).permit(:title, :kind, :description, :access) end end
class BookUser < ApplicationRecord belongs_to :user belongs_to :book belongs_to :status after_save :update_book_availability_count validates_presence_of :book_id ,:user_id ,:from, :to,:status_id validate :check_date validate :multiple_borrows, on: :create def multiple_borrows status_returned_id = Status.where('name=?',"Returned").first.id books_borrowed = BookUser.where('user_id=? and book_id=? and status_id !=?', user_id, book_id,status_returned_id) if !books_borrowed.empty? errors.add(:book_id,"already borrowed and not returned yet!") end end def check_date if self.from > self.to errors.add(:to, "date should be greater than from date") end if self.to < Date.today errors.add(:to , "date should be greater than today") end end def self.create_book_user(id,current_user,book_user) book = Book.where('id=?',id).first book.with_lock do if book.borrowed_count.to_i < book.availability book_user.book_id = book.id book_user.user_id = current_user.id book_user.from = Date.today book_user.to = Date.today + 15.days book_user.status_id = Status.where('name=?',"Borrowed").first.id end end end def self.set_current_user_records(current_user) if current_user.role == "admin" @book_users = BookUser.all else @book_users = current_user.book_users end end def update_book_availability_count book = Book.where('id=?',book_id).first if status_id == Status.where('name=?',"Borrowed").first.id book.borrowed_count = book.borrowed_count.to_i + 1 elsif status_id == Status.where('name=?',"Returned").first.id book.borrowed_count = book.borrowed_count.to_i - 1 end book.save end end
# Implementar en este fichero la clase para crear objetos racionales require "./gcd.rb" class Fraccion attr_reader :x, :y # x es el numerador # y es el denominador def initialize(x,y) @x,@y = x, y mcm = gcd(x, y) @x = x/mcm @y = y/mcm end def to_s "#{@x}/#{@y}" end def suma(other) # SUMA x = (@x * other.y) + (@y * other.x) y = @y * other.y Fraccion.new(x, y) end def resta(other) # RESTA x = (@x * other.y) - (@y * other.x) y = @y * other.y Fraccion.new(x, y) end def multipl(other) #MULTIPLICACION x = @x * other.x y = @y * other.y Fraccion.new(x, y) end def div(other) #DIVISION x = @x * other.y y = @y * other.x Fraccion.new(x, y) end end #Mostramos los Resultados #x = Fraccion.new(2, 5) #y = Fraccion.new(3, 6) #puts "RESULTADOS"; #puts "Valor de x:"; puts x #puts "Valor de y:"; puts y #puts "El valor de la suma es:"; puts x.suma(y) #puts "El valor de la resta es:"; puts x.resta(y) #puts "El valor de la multiplicacion es:"; puts x.multipl(y) #puts "El valor de la division es:"; puts x.div(y)
# frozen_string_literal: true # user controller class UsersController < ResourceController exception = %i[create email_confirmation forgot_password set_new_password] before_action :authenticate_user, except: exception before_action :validate_user, only: %i[update destroy] def index status, result = Contacts::Index.new( current_user, limit: params[:limit], offset: params[:offset] ).perform render json: result, status: status rescue StandardError => e render json: { error: e.message }, status: 500 end def email_confirmation status, result = Account::EmailConfirmation.new( params[:token] ).perform render json: result, status: status rescue StandardError => e render json: { error: e.message }, status: 500 end def forgot_password status, result = Account::ForgotPassword.new( params[:email] ).perform render json: result, status: status rescue StandardError => e render json: { error: e.message }, status: 500 end def set_new_password status, result = Account::ResetPassword.new( params[:email], params[:token], params[:password] ).perform render json: result, status: status rescue StandardError => e render json: { error: e.message }, status: 500 end private def validate_user return if @object.id == current_user.id route_not_found end end
class Experience < ActiveRecord::Base belongs_to :user validates :company, length: { maximum: 60 }, presence: true validates :location, length: { maximum: 60 }, presence: true validates :duration, numericality: {less_than_or_equal_to: 600}, presence: true validates :role, length: { maximum: 20 }, presence: true validates :description, length: { maximum: 200 } 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) admin = {:email => 'admin@kb.com'} admin_user = Admin.where(:email => admin[:email]).first if admin_user.blank? admin_user = Admin.create(:email => admin[:email], :password => 'ginger79', :password_confirmation => 'ginger79') admin_user.save! end
# frozen_string_literal: true class Balance def add_and_verify(amount) current_credit = credit add_credit(amount) compare_credit = credit - amount compare_credit.round(2) == current_credit ? true : deduct_credit(amount) end def deduct_and_verify(amount) current_credit = credit if deduct_credit(amount) compare_credit = credit + amount compare_credit.round(2) == current_credit ? true : add_credit(amount) else false end end def show_balance credit end private def add_credit(amount) if amount < 1_000_000_000_000 @credit += amount @credit = @credit.round(2) else false end end def deduct_credit(amount) if amount <= @credit @credit -= amount @credit = @credit.round(2) else false end end protected attr_reader :credit def initialize @credit = 0 end end
require 'yaks' require 'yaks-html' require 'rubygems/package_task' require 'rspec/core/rake_task' require 'yard' def mutant_task(_gem) require 'mutant' task :mutant do pattern = ENV.fetch('PATTERN', 'Yaks*') opts = ENV.fetch('MUTANT_OPTS', '').split(' ') requires = %w[-ryaks -ryaks/behaviour/optional_includes] args = %w[-Ilib --use rspec --score 100] + requires + opts + [pattern] result = Mutant::CLI.run(args) raise unless result == Mutant::CLI::EXIT_SUCCESS end end def gem_tasks(gem) Gem::PackageTask.new(Gem::Specification.load("#{gem}.gemspec")) do |task| task.package_dir = '../pkg' end mutant_task(gem) if RUBY_ENGINE == 'ruby' && RUBY_VERSION >= "2.1.0" RSpec::Core::RakeTask.new(:rspec) do |t, _task_args| t.rspec_opts = "-Ispec" t.pattern = "spec" end YARD::Rake::YardocTask.new do |t| t.files = ["lib/**/*.rb" "**/*.md"] t.options = %w[--output-dir ../doc] end end
class DesktopPage < Page include Watirsome # page title h1 :title, title: 'ะะฐัั‚ะพะปัŒะฝั‹ะต ะบะพะผะฟัŒัŽั‚ะตั€ั‹', visible: true # main part of page div :items, class: 'col-middle' a :item_title do |title| items_div.a(text: title) end # filters section a :filter, css: '#filters .f-check .f-item a' div :processors, class: 'group-gr-4554' a :processors do |model| processors_div.a(text: /#{model}/) end def choose_processor(model) scroll_and_click processors_a(model) DesktopPage.new(@browser) end def open_item(title) scroll_and_click item_title_a(title) ProductPage.new(@browser) end def go_back @brower.back DesktopPage.new(@browser) end end
require_relative '../spec_helper' module PacketGen module Plugin class IKE describe TrafficSelector do let(:ts) { TrafficSelector.new } describe '#initialize' do it 'creates a TrafficSelector with default values' do ts = TrafficSelector.new expect(ts.type).to eq(7) expect(ts.human_type).to eq('IPv4') expect(ts.protocol).to eq(0) expect(ts.length).to eq(16) expect(ts.start_port).to eq(0) expect(ts.end_port).to eq(65535) expect(ts.start_addr).to eq('0.0.0.0') expect(ts.end_addr).to eq('0.0.0.0') end it 'accepts options' do options = { type: TrafficSelector::TS_IPV6_ADDR_RANGE, protocol: 58, length: 0x100, start_port: 0x8000, end_port: 0x8100, start_addr: '10::1', end_addr: '31::' } ts = TrafficSelector.new(options) options.each do |k,v| expect(ts.send(k)).to eq(v) end end it 'accepts ports option' do ts = TrafficSelector.new(ports: 1025..3000) expect(ts.start_port).to eq(1025) expect(ts.end_port).to eq(3000) end it 'guesses type from addresses' do ts = TrafficSelector.new(start_addr: '10.0.0.1', end_addr: '31.255.255.255') expect(ts.human_type).to eq('IPv4') expect(ts[:start_addr]).to be_a(PacketGen::Header::IP::Addr) expect(ts[:end_addr]).to be_a(PacketGen::Header::IP::Addr) ts = TrafficSelector.new(start_addr: '10::1', end_addr: '11::0') expect(ts.human_type).to eq('IPv6') expect(ts[:start_addr]).to be_a(PacketGen::Header::IPv6::Addr) expect(ts[:end_addr]).to be_a(PacketGen::Header::IPv6::Addr) end end describe '#read' do it 'sets TrafficSelector from a binary string (IPv4)' do str = [7, 6, 16, 0, 65535, 10, 0, 0, 1, 10, 0, 0, 255].pack('CCnnnC8') ts.read(str) expect(ts.human_type).to eq('IPv4') expect(ts.human_protocol).to eq('tcp') expect(ts.length).to eq(16) expect(ts.start_port).to eq(0) expect(ts.end_port).to eq(65535) expect(ts.start_addr).to eq('10.0.0.1') expect(ts.end_addr).to eq('10.0.0.255') end it 'sets TrafficSelector from a binary string (IPv6)' do str = [8, 17, 40, 443, 443].pack('CCn3') str << ([0] * 15 + [1] + [0] * 14 + [65535]).pack('C30n') ts.read(str) expect(ts.human_type).to eq('IPv6') expect(ts.human_protocol).to eq('udp') expect(ts.length).to eq(40) expect(ts.start_port).to eq(443) expect(ts.end_port).to eq(443) expect(ts.start_addr).to eq('::1') expect(ts.end_addr).to eq('::ffff') end end describe '#type=' do it 'accepts Integer' do ts.type = 8 expect(ts.type).to eq(8) ts.type = 7 expect(ts.type).to eq(7) end it 'accepts String' do ts.type = 'IPV4' expect(ts.type).to eq(7) ts.type = 'IPv4' expect(ts.type).to eq(7) ts.type = 'ipv4' expect(ts.type).to eq(7) ts.type = 'IPV6' expect(ts.type).to eq(8) ts.type = 'IPv6' expect(ts.type).to eq(8) ts.type = 'ipv6' expect(ts.type).to eq(8) end it 'raises on unknown type' do expect { ts.type = 48 }.to raise_error(ArgumentError, /unknown type/) expect { ts.type = 'blah!' }.to raise_error(ArgumentError, /unknown type/) end end describe '#protocol=' do it 'accepts Integer' do ts.protocol = 250 expect(ts.protocol).to eq(250) expect(ts.human_protocol).to eq('250') end it 'accepts String' do ts.protocol = 'tcp' expect(ts.protocol).to eq(6) expect(ts.human_protocol).to eq('tcp') end it 'raises on unknown protocol (String only)' do expect { ts.protocol = 'blah!' }.to raise_error(ArgumentError, /unknown protocol/) end end describe '#to_s' do it 'returns a binary string' do ts = TrafficSelector.new(protocol: 'igmp', start_addr: '42.23.5.89', end_addr: '42.23.5.89') expected = "\x07\x02\x00\x10\x00\x00\xff\xff\x2a\x17\x05\x59\x2a\x17\x05\x59" expect(ts.to_s).to eq(force_binary expected) ts = TrafficSelector.new(protocol: 'udp', ports: 64..65, start_addr: '2a00::1', end_addr: '2a00::2') expected = "\x08\x11\x00\x28\x00\x40\x00\x41" expected << IPAddr.new('2a00::1').hton << IPAddr.new('2a00::2').hton expect(ts.to_s).to eq(force_binary expected) end end describe '#to_human' do it 'returns a human readable string' do ts = TrafficSelector.new(protocol: 'igmp', start_addr: '42.23.5.89', end_addr: '42.23.5.89') expect(ts.to_human).to eq('42.23.5.89-42.23.5.89/igmp') ts = TrafficSelector.new(protocol: 'udp', ports: 64..65, start_addr: '2a00::1', end_addr: '2a00::2') expect(ts.to_human).to eq('2a00::1-2a00::2/udp[64-65]') end end end describe TSi do describe '#initialize' do it 'creates a TSi payload with default values' do tsi = TSi.new expect(tsi.next).to eq(0) expect(tsi.flags).to eq(0) expect(tsi.length).to eq(8) expect(tsi.num_ts).to eq(0) expect(tsi.traffic_selectors).to be_empty end it 'accepts options' do opts = { next: 59, flags: 0x65, length: 128, num_ts: 0xf0, } tsi = TSi.new(opts) opts.each do |k,v| expect(tsi.send(k)).to eq(v) end end end describe '#read' do it 'sets TSi from a binary string' do sk_ei = ['B37E73D129FFE681D2E3AA3728C2401E' \ 'D50160E39FD55EF1A1EAE0D3F4AA6126D8B8A626'].pack('H*') cipher = get_cipher('gcm', :decrypt, sk_ei[0..31]) pkt = PacketGen.read(File.join(__dir__, '..', 'ikev2.pcapng'))[2] pkt.ike_sk.decrypt! cipher, salt: sk_ei[32..35], icv_length: 16, parse: false str = pkt.ike_sk.body idx = str.index(force_binary "\x2d\x00\x00\x18") tsi = TSi.new.read(str[idx, 0x18]) expect(tsi.next).to eq(45) expect(tsi.flags).to eq(0) expect(tsi.length).to eq(24) expect(tsi.num_ts).to eq(1) expect(tsi.rsv).to eq(0) expect(tsi.selectors.to_human).to eq('10.1.0.0-10.1.0.255') expect(tsi.selectors.first.human_protocol).to eq('') end end describe '#to_s' do it 'returns a binary string' do tsi = TSi.new(next: 2, num_ts: 22) tsi.calc_length expected = "\x02\x00\x00\x08\x16\x00\x00\x00" expect(tsi.to_s).to eq(force_binary expected) end end describe '#inspect' do it 'returns a string with all attributes' do tsi = TSi.new str = tsi.inspect expect(str).to be_a(String) (tsi.fields - %i(body rsv1 rsv2)).each do |attr| expect(str).to include(attr.to_s) end end end describe '#traffic_selectors' do let(:tsi) { TSi.new } it 'accepts pushing a TrafficSelector object' do ts = TrafficSelector.new(type: 7, start_addr: '10.0.0.1', end_addr: '10.0.0.255') expect { tsi.selectors << ts }.to change { tsi.num_ts }.by(1) end it 'accepts pushing a Hash describing a traffic selector' do expect { tsi.selectors << { type: 'IPv4', start_addr: '10.0.0.1', end_addr: '10.0.0.255', protocol: 'tcp', ports: 1..1024 } }. to change { tsi.num_ts }.by(1) end it 'accepts pushing a Hash describing a traffic selector, guessing type' do expect { tsi.selectors << { start_addr: '10.0.0.1', end_addr: '10.0.0.255', protocol: 'tcp', ports: 1..1024 } }. to change { tsi.num_ts }.by(1) expect(tsi.selectors.last.human_type).to eq('IPv4') expect(tsi.selectors.last.start_port).to eq(1) expect(tsi.selectors.last.end_port).to eq(1024) expect { tsi.selectors << { start_addr: '2001::1', end_addr: '2002::' } }. to change { tsi.num_ts }.by(1) expect(tsi.selectors.last.type).to eq(TrafficSelector::TS_IPV6_ADDR_RANGE) expect(tsi.selectors.last.start_addr).to eq('2001::1') expect(tsi.selectors.last.end_addr).to eq('2002::') end end end end end end
class TweetsController < ApplicationController get '/tweet' do erb :'tweets/tweet' end get '/users/:id' do if logged_in? @tweets = current_user.tweets erb :'user/show' else redirect to '/sign_in' end end def tweet_params params.require(:tweet).permit(:body, :user_id) end post '/tweet' do tweet = Tweet.new(params[:tweet]) tweet.user_id = current_user.id if tweet.save redirect to "/" else @error = @tweet.errors.full_messages.first end end get '/tweets/:id' do @tweet = Tweet.find(params[:id]) erb :"tweets/tweet" end delete '/tweets/:id' do @tweet = Tweet.delete(params[:id]) redirect "/" end get '/tweets/:id/edit' do @tweet = Tweet.find(params[:id]) erb :"tweets/edit" end patch '/tweets/:id' do @tweet = Tweet.find(params[:id]) @tweet.body = params[:boyd] @tweet.save redirect "/tweets/#{@tweet.id}" end end
# a module that can be extended into a Hash object to provide some convenience methods # There may be simple, idiomatic ways to perform these functions with Hash or the rails Hash extensions. # If there are, I am unaware of them. In any case, it should be easy enough to search for usage of this # module and remove it if there is a cleaner way to implement a nil_safe_get module HashExtension def nil_safe_get(path) return nil if path.blank? [path].flatten.inject(self) do |ret,k| v = k.nil? ? nil : ret[k.to_sym] || ret[k.to_s] break if v.nil? v end end end
class User < ApplicationRecord has_many :microposts validates :name, presence: true validates :email, presence: true def first_post microposts.first end def to_s name end end
#!/usr/bin/env ruby require 'csv' require 'awesome_print' require 'json' FILES = ['table_people-object.json', 'table_correspondents-object.json'] SOURCE = 'target' TARGET = 'target' def getJSON(id) path = "#{SOURCE}/#{FILES[id]}" file = open(path) json = file.read JSON.parse(json) end def writeJSON (file, hash) File.open("#{TARGET}/#{file}.json", "w") do |file| file.write(JSON.pretty_generate(hash)) end end people = getJSON(0) correspondents = getJSON(1) writeJSON('data', people.merge(correspondents))
class Relationship < ActiveRecord::Base # only the followed_id is accessible attr_accessible :followed_id # Rails infers the names of the foreign keys from the corresponding symbols # (i.e., follower_id from :follower, and followed_id from :followed) # but since there is neither a Followed nor a Follower model we need to supply the class name User belongs_to :follower, class_name: "User" belongs_to :followed, class_name: "User" # must not be empty validates :follower_id, presence: true validates :followed_id, presence: true end
require 'rails_helper' describe WeatherService do context "class methods" do context ".weather_forecast" do it "returns results" do query = WeatherService.weather_forecast(35.6762, 139.6503) expect(query).to be_a Hash location_data = query[:current] expect(location_data).to have_key :dt expect(location_data[:dt]).to be_a(Numeric) expect(location_data).to have_key :sunrise expect(location_data[:sunrise]).to be_a(Numeric) expect(location_data).to have_key :sunset expect(location_data[:sunset]).to be_a(Numeric) expect(location_data).to have_key :temp expect(location_data[:temp]).to be_a(Numeric) expect(location_data).to have_key :weather expect(location_data[:weather]).to be_a(Array) expect(location_data[:weather][0]).to be_a(Hash) weather_data = location_data[:weather][0] expect(weather_data).to have_key :description expect(weather_data[:description]).to be_a(String) expect(weather_data).to have_key :icon expect(weather_data[:icon]).to be_a(String) end end end end
class CreateOrderAddOns < ActiveRecord::Migration def change create_table :order_add_ons do |t| t.integer :item_add_on_id t.integer :order_line_item_id t.integer :quantity t.timestamps end end end
require 'minitest/autorun' require_relative '../lib/nmatrix/rowcol' class TestNMatrixRowcol < MiniTest::Test def test_dense d = NMatrix.indgen [3,3] # [ # [0, 1, 2] # [3, 4, 5] # [6, 7, 8] # ] assert_equal N[ [0, 1, 2] ], d.row(0) assert_equal N[ [0, 1, 2], [6, 7, 8] ], d.row([0,2]) assert_equal N[ [3, 4, 5], [6, 7, 8] ], d.row(d.sum(1) > 6) assert_equal N[ [0], [3], [6] ], d.col(0) assert_equal N[ [0, 2], [3, 5], [6, 8] ], d.col([0,2]) assert_equal N[ [2], [5], [8] ], d.col(d.sum(0) > 12) assert_equal N[ [0, 2], [6, 8] ], d.row([0,2]).col([0,2]) assert_equal d.stype, d.row([0,2]).stype assert_equal d.dtype, d.row([0,2]).dtype end def test_sparse y = NMatrix.diagonal([1,2,3], stype: :yale) # [ # [1, 0, 0] # [0, 2, 0] # [0, 0, 3] # ] assert_equal N[ [1, 0, 0] ], y.row(0) assert_equal N[ [1, 0, 0], [0, 0, 3] ], y.row([0,2]) assert_equal N[ [0, 0, 3] ], y.row(y.sum(1) > 2) assert_equal N[ [1], [0], [0] ], y.col(0) assert_equal N[ [1, 0], [0, 0], [0, 3] ], y.col([0,2]) assert_equal N[ [0], [0], [3] ], y.col(y.sum(0) > 2 ) assert_equal N[ [1, 0], [0, 3] ], y.row([0,2]).col([0,2]) assert_equal y.stype, y.row([0,2]).stype assert_equal y.dtype, y.row([0,2]).dtype end def test_1d_row d = N[1,2,3,4,5] assert_equal N[1,3], d.row([0,2]) assert_equal N[4,5], d.row(d > 3) end def test_1d_col d = N[1,2,3,4,5] assert_raises RangeError do d.col [0,2] end end end
require "metacrunch/hash" require "metacrunch/transformator/transformation/step" require_relative "../aleph_mab_normalization" require_relative "./add_creationdate" class Metacrunch::ULBD::Transformations::AlephMabNormalization::AddCreationdateSearch < Metacrunch::Transformator::Transformation::Step def call target ? Metacrunch::Hash.add(target, "creationdate_search", creationdate_search) : creationdate_search end private def creationdate_search if date = creationdate date.gsub(/[^0-9]/i, '') # Entferne alle nicht numerischen Zeichen end end private def creationdate target.try(:[], "creationdate") || self.class.parent::AddCreationdate.new(source: source).call end end
# -*- coding: utf-8 -*- class PowersController < ApplicationController def index respond_to do |format| format.html format.json { render json: Power.all } end end def update update_power(params[:iidxid]) render text: "update succeeded" end def update_power(iidxid) hash = Hash.new hash[:iidxid] = iidxid ["SP", "DP"].each do |playtype| [8, 9, 10].each do |level| score_sym = "score#{level}".to_sym title_sym = "title#{level}".to_sym hash[score_sym], hash[title_sym] = single_score_power(iidxid, playtype, level) end [11, 12].each do |level| score_sym = "score#{level}".to_sym clear_sym = "clear#{level}".to_sym hash[clear_sym] = clear_power(iidxid, playtype, level) hash[score_sym] = total_score_power(iidxid, playtype, level) end score_total = 0 (8..12).each do |level| score_sym = "score#{level}".to_sym score_total += hash[score_sym].to_f end hash[:score_total] = score_total.to_s clear_total = 0 (11..12).each do |level| clear_sym = "clear#{level}".to_sym clear_total += hash[clear_sym].to_f end hash[:clear_total] = clear_total.to_s @power = Power.where(iidxid: iidxid, playtype: playtype).first @power ||= Power.create( iidxid: iidxid, playtype: playtype, score8: "0.00", score9: "0.00", score10: "0.00", score11: "0.00", score12: "0.00", title8: "-", title9: "-", title10: "-", clear11: "0.00", clear12: "0.00", date: Date.today, score_total: "0.00", clear_total: "0.00" ) @power.update_attributes(hash) end end def update_all @users = User.all @users.each do |user| update_power(user[:iidxid]) puts "Completed: #{user[:iidxid]}" end render text: "update succeeded" end def clear_power(iidxid, playtype, level) # ๅŸบ็คŽ็‚น:30 * (FC+EXH+H)^2 * 5^((FC+EXH)^2) * 5^(FC^2) # ็‚นๆ•ฐ:ๅŸบ็คŽ็‚น ^ ( (1.1 + 1/6) - (5^(BP/100))/6 ) - lv12 base = case level when 11 then 40 when 12 then 250 end fc_num = 0 fc_rate = 0 exh_num = 0 exh_rate = 0 h_num = 0 h_rate = 0 bp_sum = 0 score_num = 0 lamp_num = 0 bp_ave = 0 scores = Score.where(iidxid: iidxid) Music.where(playtype: playtype, level: level.to_s).each do |music| score = scores.select{|x| x.title == music[:title] && x.playtype == playtype && x.difficulty == music[:difficulty] }.first next unless score fc_num += 1 if score[:clear] == "FC" exh_num += 1 if score[:clear] == "EXH" h_num += 1 if score[:clear] == "H" lamp_num += 1 if score[:clear] != "-" if score[:bp] != "-" bp_sum += score[:bp].to_i score_num += 1 end end bp_ave = bp_sum.to_f / score_num if score_num > 0 if lamp_num > 0 fc_rate = fc_num.to_f / lamp_num exh_rate = exh_num.to_f / lamp_num h_rate = h_num.to_f / lamp_num end k = case level when 11 then (1.1 + 1.0/6) - ((1.14**(bp_ave / 2)) / 6) when 12 then (1.1 + 1.0/6) - ((5**(bp_ave / 100)) / 6) end base_point = base * (fc_rate + exh_rate + h_rate)**2 * 5**((fc_rate + exh_rate)**2) * 5**(fc_rate**2) # catch underflow if (base_point * 100).to_i > 100 clear_power = base_point**k else clear_power = 0 end # catch overflow begin if clear_power.to_i > 100000 clear_power = 0 end rescue clear_power = 0 end # For debug # if level == 11 # raise "LEVEL:"+level.to_s+"\n,IIDXID:"+iidxid+",\nSCORE_NUM:"+score_num.to_s+",\nLAMP_NUM:"+lamp_num.to_s+",\nFC_NUM:"+fc_num.to_s+ # "\n,EXH_NUM:"+exh_num.to_s+"\n,H_NUM:"+h_num.to_s+"\n,FC_RATE:"+fc_rate.to_s+"\n,EXH_RATE:"+exh_rate.to_s+"\n,H_RATE:"+h_rate.to_s+ # "\n,BP_AVE:"+bp_ave.to_s+"\n,BASE_POINT:"+base_point.to_s+"\n,K:"+k.to_s+"\n,CLEAR_POWER:"+("%.2f" % clear_power) # end "%.2f" % clear_power end def single_score_power(iidxid, playtype, level) title = "-" max_rate = 0 scores = Score.where(iidxid: iidxid) Music.where(playtype: playtype, level: level.to_s).each do |music| #score = Score.where(iidxid: iidxid, title: music[:title], playtype: playtype, difficulty: music[:difficulty]).first score = scores.select{|x| x.title == music[:title] && x.playtype == playtype && x.difficulty == music[:difficulty] }.first next unless score if max_rate < score[:rate].to_f title = music[:title] max_rate = score[:rate].to_f end end base = case level when 8 then 280 when 9 then 330 when 10 then 390 end mas_rate = 99.9 if max_rate == 100 score_power = base * (0.6 ** (100 - max_rate)) score_power_string = "%.2f" % score_power [score_power_string, title] end def total_score_power(iidxid, playtype, level) base = case level when 11 then 50 when 12 then 200 end score_rate = 0 score_num = 0 aaa_num = 0 aa_num = 0 rate_sum = 0 scores = Score.where(iidxid: iidxid) Music.where(playtype: playtype, level: level.to_s).each do |music| score = scores.select{|x| x.title == music[:title] && x.playtype == playtype && x.difficulty == music[:difficulty] }.first next unless score if score[:rate].to_f > 0 score_num += 1 rate_sum += score[:rate].to_f if score[:rate].to_f > 88.8 aaa_num += 1 elsif score[:rate].to_f > 77.7 aa_num += 1 end end end score_rate = rate_sum / score_num if score_num > 0 score_rate /= 100 if 1 > score_rate && score_rate > 0 pika_great = (score_rate - 0.5) / (1 - score_rate) score_power = base * (aaa_num.to_f / score_num + 1) * ((aaa_num + aa_num).to_f / score_num) * pika_great; else score_power = 0 end "%.2f" % score_power end end
class RenamesClassOnPlayer < ActiveRecord::Migration[5.0] def change rename_column :players, :class, :course end end
class Grid attr_accessor :cells, :width, :height def initialize(width, height) @width = width @height = height @cells = [] height.times do cells << ([Cell.dead] * width) end height.times do |y| width.times do |x| cells[y][x].neighbours = neighbours_for(y, x) end end end def neighbours_for(y, x) [ [-1, -1], [-1, 0], [-1, 1], # under [0, -1], [0, 1], # sides [1, -1], [1, 0], [1, 1] # over ].map do |(y_delta, x_delta)| cells[(y + y_delta) % height][(x + x_delta) % width] end end def print_grid height.times do |y| width.times do |x| cell = cells[y][x] cell.print_cell end print "\n" end end def tick print_grid new_grid = dup_grid changes = [] height.times do |y| width.times do |x| cell = cells[y][x] changes << cell.next_state end end height.times do |y| width.times do |x| cell = cells[y][x] cell.alive = changes[y * x] end end tick end end
require_relative '../../lib/desuraify' RSpec.describe Desuraify::Member do before do @member = Desuraify::Member.new('animdude') @member.update end describe 'member data' do it 'should have an activity_points attribute' do expect(@member.activity_points.class).to eq(Fixnum) end it 'should have a country attribute' do expect(@member.country.class).to eq(String) end it 'should have a gender attribute' do expect(@member.gender.class).to eq(String) end it 'should have the html page available' do expect(@member.html).not_to eq(nil) expect(@member.html.class).to eq(String) end it 'should have an array of images' do expect(@member.images.class).to eq(Array) expect(@member.images).to eq([]) end it 'should have an image_count' do expect(@member.images_count.class).to eq(Fixnum) end it 'should have a level attribute' do expect(@member.level.class).to eq(Float) end it 'should have an offline attribute' do expect(@member.offline.class).to eq(String) end it 'should have a rank attribute' do expect(@member.rank.class).to eq(String) end it 'should have a site_visits attribute' do expect(@member.site_visits.class).to eq(String) end it 'should have a time_online attribute' do expect(@member.time_online.class).to eq(String) end it 'should have an array of videos' do expect(@member.videos.class).to eq(Array) expect(@member.videos).to eq([]) end it 'should have a videos_count' do expect(@member.videos_count.class).to eq(Fixnum) end it 'should have a visits attribute' do expect(@member.visits.class).to eq(String) end it 'should have a watchers attribute' do expect(@member.watchers.class).to eq(String) end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :set_timezone, :set_cookie # before_action :check_user_paid_type helper_method :user_is_president helper_method :current_tenant layout :layout_by_resource def after_sign_in_path_for(resource) domain = resource.tenant_domain if domain == 'me' # sign_out resource new_user_registration_url(subdomain: domain) elsif request.subdomain.blank? || request.subdomain == domain root_url(subdomain: domain) else raise "User doen't not belong to this socity. Please contect society president for this" end end def user_is_president @user_is_president ||= current_user.has_role? :president end def current_tenant @current_tenant = Tenant.find_by(domain: request.subdomain) unless main_domain? end def main_domain? request.subdomain.blank? || FORBIDDEN_SUBDOMAINS.include?(request.subdomain) end def largest_hash_key(hash) unless hash.blank? max = hash.values.max Hash[hash.select { |_k, v| v == max }] end end protected def layout_by_resource if devise_controller? # and !user_signed_in? 'login' else 'application' end end private def set_timezone Time.zone = cookies['time_zone'] end def set_cookie cookies.permanent.signed[:user_id] = current_user.id if current_user end def check_user_paid_type if current_user valid_user = User.check_user_paid_type(current_user) unless valid_user flash[:error] = 'Please upgrade your membership. Otherwise you will not able to access the application.' sign_out current_user end end end end
class Admin::BroApprovalsController < Admin::AdminController before_action :set_bro_order def create @approved_line_items = BroLineItem.where(id: params[:bro_line_item_ids]) @approved_line_items.update_all(approved: true) @bro_order.approve! if @bro_order.submitted? end private def set_bro_order @bro_order = BroOrder.find_by(guid: params[:bro_order_guid]) end end
require 'terraform_tool/modules/manager' module TerraformTool module Commands module Render def self.included(thor_class) thor_class.class_eval do desc "render", "Renders the module templates" long_desc <<-LONGDESC Renders the module templates without running Terraform LONGDESC def render module_manager = TerraformTool::Modules::Manager.new(context: context, environment: environment) module_manager.render_modules end end end end end end
# frozen_string_literal: true require "bindata" require "tpm/constants" require "tpm/sized_buffer" require "tpm/t_public/s_ecc_parms" require "tpm/t_public/s_rsa_parms" module TPM # Section 12.2.4 in https://trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-2-Structures-01.38.pdf class TPublic < BinData::Record endian :big uint16 :alg_type uint16 :name_alg # :object_attributes skip length: 4 sized_buffer :auth_policy choice :parameters, selection: :alg_type do s_ecc_parms TPM::ALG_ECC s_rsa_parms TPM::ALG_RSA end choice :unique, selection: :alg_type do sized_buffer TPM::ALG_ECC sized_buffer TPM::ALG_RSA 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) require 'faker' Artist.destroy_all Genre.destroy_all Song.destroy_all 20.times do Artist.create(name: Faker::Music.band, bio: Faker::Lorem.paragraph) end 20.times do Genre.create(name: Faker::Music.genre) end 20.times do Song.create(name: Faker::Music::Prince.song, artist_id: Artist.all.sample.id, genre_id: Genre.all.sample.id) end
require File.expand_path('../helper', __FILE__) class NotPredicateTest < Test::Unit::TestCase def test_terminal? rule = NotPredicate.new assert_equal(false, rule.terminal?) end def test_match rule = NotPredicate.new('a') match = rule.match(input('a')) assert_equal(nil, match) match = rule.match(input('b')) assert(match) assert_equal('', match) assert_equal(0, match.length) end def test_to_s rule = NotPredicate.new('a') assert_equal('!"a"', rule.to_s) end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) articles=[ ["title1","content1"], ["title2","content2"], ["title3","content3"], ["title4","content4"], ["title5","content5"], ["title6","content6"], ["title7","content7"], ["title8","content8"], ["title9","content9"], ["title10","content11"], ["title12","content12"], ["title13","content13"], ["title14","content14"], ["title15","content15"], ["title16","content16"], ["title17","content17"], ["title18","content18"], ["title19","content19"], ["title20","content20"], ["title21","content21"], ["title22","content22"], ["title23","content23"], ["title24","content24"], ["title25","content25"], ["title26","content26"], ["title27","content27"], ["title28","content28"], ["title29","content29"], ["title30","content30"], ] articles.each do |title,content| Article.create(title:title,content:content) end
class TweetsController < ApplicationController before_action :authenticate_user! def index following_ids = current_user.following.pluck(:user_id) following_ids << current_user.id @tweets = Tweet.where(user_id: following_ids).order(created_at: :desc) end def new @tweet = current_user.tweets.new end def create @tweet = current_user.tweets.new(tweet_params) if @tweet.save redirect_to tweets_path, notice: 'Tweet created' else flash[:error] = 'Error' render :new end end def destroy @tweet = current_user.tweets.find(params[:id]) @tweet.destroy redirect_to tweets_path, notice: 'Tweet deleted' end private def tweet_params params.require(:tweet).permit(:body) end end
require "./src/const/total-syouhai.rb" require "./src/util/log-msg.rb" # # 1 vs 1 ๅฏพๆˆฆใฎ็ตๆžœใ‚’ไฟๆŒ. # class FightResult attr_accessor :challenger1_name # ๆŒ‘ๆˆฆ่€… 1 ใฎๅๅ‰ attr_accessor :challenger2_name # ๆŒ‘ๆˆฆ่€… 2 ใฎๅๅ‰ attr_accessor :challenger1_win_num # ๆŒ‘ๆˆฆ่€… 1 ใฎๅ‹ใกๆ•ฐ attr_accessor :challenger2_win_num # ๆŒ‘ๆˆฆ่€… 2 ใฎๅ‹ใกๆ•ฐ attr_accessor :draw_num # ใ‚ใ„ใ“ใฎๆ•ฐ # ใ‚ณใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ def initialize(challenger1_name, challenger2_name, challenger1_win_num, challenger2_win_num, draw_num) @challenger1_name = challenger1_name @challenger2_name = challenger2_name @challenger1_win_num = challenger1_win_num @challenger2_win_num = challenger2_win_num @draw_num = draw_num @log = LogMsg.new end # ๅผ•ๆ•ฐใงๆŒ‡ๅฎšใ•ใ‚ŒใŸๆŒ‘ๆˆฆ่€…ใฎๅ‹ๆ•—ใ‚’่ชฟในใ‚‹. # ๆŒ‡ๅฎšใ—ใŸๆŒ‘ๆˆฆ่€…ใŒใ“ใฎๅฏพๆˆฆ็ตๆžœใซๅซใพใ‚Œใชใ„ # ๅ ดๅˆใฏ nil ใ‚’่ฟ”ใ™. def result_judgement(challenger) @log.msg("START") if (challenger != @challenger1_name) && (challenger != @challenger2_name) then # ๆŒ‡ๅฎšใ•ใ‚ŒใŸๆŒ‘ๆˆฆ่€…ๅใŒๆŒ‘ๆˆฆ่€… 1 ใจ 2 ใฎใ„ใšใ‚Œใงใ‚‚ใชใ„ๅ ดๅˆ @log.msg("END") return nil end # ๆŒ‡ๅฎšใ•ใ‚ŒใŸๆŒ‘ๆˆฆ่€…ใŒ 1 ใ‹ 2 ใฎใ„ใšใ‚Œใ‹ใชใฎใง๏ผŒๅ‹ๆ•—ใ‚’ๅˆคๅฎšใ™ใ‚‹ if @challenger1_win_num > @challenger2_win_num then # ๆŒ‘ๆˆฆ่€… 1 ใŒๅ‹ๅˆฉใ—ใŸๅ ดๅˆ # ๆŒ‡ๅฎšใ•ใ‚ŒใŸๆŒ‘ๆˆฆ่€…ใซใ‚ˆใ‚Šๅ‹ๆ•—ใ‚’่ฟ”ๅดใ™ใ‚‹ if challenger == @challenger1_name then @log.msg("END") return TotalSyouhai::WIN elsif challenger == @challenger2_name then @log.msg("END") return TotalSyouhai::LOSE else @log.msg("END") return nil end elsif @challenger1_win_num < @challenger2_win_num then # ๆŒ‘ๆˆฆ่€… 2 ใŒๅ‹ๅˆฉใ—ใŸๅ ดๅˆ # ๆŒ‡ๅฎšใ•ใ‚ŒใŸๆŒ‘ๆˆฆ่€…ใซใ‚ˆใ‚Šๅ‹ๆ•—ใ‚’่ฟ”ๅดใ™ใ‚‹ if challenger == @challenger1_name then @log.msg("END") return TotalSyouhai::LOSE elsif challenger == @challenger2_name then @log.msg("END") return TotalSyouhai::WIN else @log.msg("END") return nil end elsif @challenger1_win_num == @challenger2_win_num then # ๅ‹ๅˆฉๆ•ฐใŒๅŒใ˜ใงใ‚ใ‚Œใฐใฉใกใ‚‰ใŒๆŒ‡ๅฎšใ•ใ‚Œใฆใ„ใฆใ‚‚ๅผ•ใๅˆ†ใ‘ @log.msg("END") return TotalSyouhai::DRAW else # ใใ‚Œไปฅๅค–ใฎๅ ดๅˆใฏ nil ใ‚’่ฟ”ๅด @log.msg("END") return nil end @log.msg("END") end end
Rails.application.routes.draw do # Github Callback get '/auth/github/callback', to: 'sessions#create' # Logout get '/logout', to: 'sessions#destroy', as: :logout end
# frozen_string_literal: true RSpec.describe "dry types errors" do describe Dry::Types::CoercionError do it "requires a string message" do expect { described_class.new(:invalid) }.to raise_error(ArgumentError, /message must be a string/) end end end
class CreateRsvps < ActiveRecord::Migration def self.up create_table :rsvps do |t| t.timestamps t.references :rsvpable, :polymorphic => true end end def self.down drop_table :rsvps end end
class User < ApplicationRecord has_many :positions has_many :contacts has_many :conections, through: :contacts validates :name, presence: true validates :email, presence: true end
class Node < ApplicationRecord belongs_to :place validates :node_name, presence: true, length: { minimum: 3 } validates :node_name, uniqueness: true end
require 'sweetcron' class CrawlerStartTask @@logger = Logger.new(File.join(RAILS_ROOT, "log", "crawler.log")) def self.logger @@logger ||= Logger.new STDOUT end def self.execute crawler = SweetCron::Crawler.new logger crawler.start end end
Types::QueryType = GraphQL::ObjectType.define do name "Query" description "Avaiable Queries" fields Util::FieldComposer.compose([ Queries::UserQueryType, Queries::PostQueryType, Queries::PaginationQueryType, Queries::CommentQueryType]) end
class ErrorSerializer include FastJsonapi::ObjectSerializer attributes :message end
class Guide::ScenariosController < Guide::BaseController layout 'guide/scenario' def show expose_layout expose_scenario end private def expose_layout @layout_view = Guide::ScenarioLayoutView.new( node: active_node, node_title: nobilizer.bestow_title(node_path), scenario: scenario, format: scenario_format, injected_html: injected_html, ) end def expose_scenario @scenario_view = Guide::ScenarioView.new( node: active_node, scenario: scenario, format: scenario_format, ) end def scenario @scenario ||= simulator.fetch_scenario(scenario_id) end def simulator @simulator ||= Guide::Simulator.new(active_node, bouncer) end def scenario_id params[:scenario_id].to_sym end def scenario_format params[:scenario_format].to_sym end end
require File.expand_path '../../test_helper', __dir__ # Test class for VirtualNetwork Collection class TestVirtualNetworks < Minitest::Test def setup @service = Fog::Network::AzureRM.new(credentials) @virtual_networks = Fog::Network::AzureRM::VirtualNetworks.new(resource_group: 'fog-test-rg', service: @service) @network_client = @service.instance_variable_get(:@network_client) end def test_collection_methods methods = [ :all, :get, :check_if_exists ] methods.each do |method| assert_respond_to @virtual_networks, method end end def test_collection_attributes assert_respond_to @virtual_networks, :resource_group end def test_all_method_response response = [ApiStub::Models::Network::VirtualNetwork.create_virtual_network_response(@network_client)] @service.stub :list_virtual_networks, response do assert_instance_of Fog::Network::AzureRM::VirtualNetworks, @virtual_networks.all assert @virtual_networks.all.size >= 1 @virtual_networks.all.each do |nic| assert_instance_of Fog::Network::AzureRM::VirtualNetwork, nic end end end def test_get_method_response response = ApiStub::Models::Network::VirtualNetwork.create_virtual_network_response(@network_client) @service.stub :get_virtual_network, response do assert_instance_of Fog::Network::AzureRM::VirtualNetwork, @virtual_networks.get('fog-rg', 'fog-test-virtual-network') end end def test_check_if_exists_method_success @service.stub :check_for_virtual_network, true do assert @virtual_networks.check_if_exists('fog-test-rg', 'fog-test-virtual-network') end end def test_check_if_exists_method_failure @service.stub :check_for_virtual_network, false do assert !@virtual_networks.check_if_exists('fog-test-rg', 'fog-test-virtual-network') end end end
module GithubManager class Organization attr_accessor :login_name, :repositories, :avatar_url, :repos_url, :collaborators def initialize(login_name, avatar_url, repos_url) @login_name = login_name @repos_url = repos_url @avatar_url = avatar_url @collaborators = [] @repositories = fetch_repos end def top_five_collaborators(days_ago) @collaborators.each { |collaborator| collaborator.contributions_number = 0 } @repositories.each { |repo| repo.fetch_commits_from days_ago } top_five_collaborators = @collaborators.sort_by { |col| col.contributions_number }.reverse![0..4].select { |col| col.contributions_number > 0 } top_five_collaborators.each { |col| col.avg_contributions = '%.2f' % (col.contributions_number / days_ago.to_f) } end def fetch_repos fetched_repos = [] response = RESTClient.make_request('GET', "/orgs/#{@login_name}/repos", { :page => 1, :per_page => 100 }) if response loop do parsed_response = JSON.parse response.body parsed_response.each do |repo| fetched_repos << Repository.new(repo['name']) end if response.next_page_url response = RESTClient.make_request('GET', response.next_page_url) else break end end else raise "There was a problem fetching the organization repos" end fetched_repos end end end
require 'rails_helper' RSpec.describe Tag, type: :model do subject { build(:tag) } describe 'validations' do it { should validate_presence_of(:name) } it { should validate_length_of(:name).is_at_most(50) } end describe 'associations' do it { should belong_to(:project) } it { should have_many(:feedbacks) } end end
# frozen_string_literal: true class RenameRegistrationQuota < ActiveRecord::Migration[4.2] def up rename_table :registration_quota, :registration_quotas change_column :attendances, :registration_value, :decimal, precision: 10, decimal: 2 end def down rename_table :registration_quotas, :registration_quota change_column :attendances, :registration_value, :integer end end
json.array!(@computers) do |computer| json.extract! computer, :id, :user_id, :name, :avatar, :cpu, :model, :ram, :brand, :hd, :video_card, :operation_system json.url computer_url(computer, format: :json) end
class Admissions::OrganizationsController < Admissions::AdmissionsController before_filter :set_organization, except: [:index, :new, :create] load_resource find_by: :permalink authorize_resource def index @organizations = Organization.ordered.paginate page: params[:page], per_page: @per_page end def show end def new @organization = Organization.new end def create @organization = Organization.new(params[:organization]) if @organization.save redirect_to admin_organizations_path, notice: organization_flash(@organization).html_safe else render :new end end def edit end def update if @organization.update_attributes(params[:organization]) redirect_to admin_organizations_path, notice: organization_flash(@organization).html_safe else render :edit end end def confirm_destroy end def destroy @organization.destroy redirect_to admin_organizations_path, notice: "Successfully destroyed #{@organization.name}." end private def set_organization @organization = Organization.find_by_permalink!(params[:id]) end def organization_flash(organization) render_to_string partial: "flash", locals: { organization: organization } end end