text
stringlengths
10
2.61M
class StorySerializer < MessageSerializer attributes :snapchat_media_id, :latitude, :longitude, :source, :permission, :has_face, :status, :blurred, :shareable_to, :youtube_id def latitude latitude = object.latitude return if latitude.blank? if owner? latitude.to_f else latitude.to_f.round(2) end end def longitude longitude = object.longitude return if longitude.blank? if owner? longitude.to_f else longitude.to_f.round(2) end end def include_permission? owner? end def include_status? owner? end def include_blurred? owner? end def youtube_id object.youtube_id if object.shareable_to_youtube? end end
class ClassMappingsController < ApplicationController before_action :set_class_mapping, only: [:show, :edit, :update, :destroy] # GET /class_mappings # GET /class_mappings.json def index s_id = Allotment.where(user_id: current_user.id).pluck(:school_id) @class_mappings = ClassMapping.includes(:standard, :section).where(school_id: s_id) standards = Standard.all sections = Section.all class_mappings = @class_mappings.map do |c| { id:c.id, standard: c.standard.name, section: c.section.name, school: s_id} end render component: 'ClassMappings', props: { class_mappings: class_mappings, standards: standards, sections: sections} end # GET /class_mappings/1 # GET /class_mappings/1.json def show end # GET /class_mappings/new def new @class_mapping = ClassMapping.new end # GET /class_mappings/1/edit def edit end # POST /class_mappings # POST /class_mappings.json def create s_id = Allotment.where(user_id: current_user.id).pluck(:school_id).first standard_id = Standard.where(name: params[:class_mapping][:standard]).pluck(:id).first section_id = Section.where(name: params[:class_mapping][:section]).pluck(:id).first @classes = ClassMapping.new({:section_id => section_id, :standard_id => standard_id, :school_id => s_id}) @saved_class = { id:@classes.id, standard: params[:class_mapping][:standard], section: params[:class_mapping][:section], school: s_id} if @classes.save render :json => @saved_class end end # PATCH/PUT /class_mappings/1 # PATCH/PUT /class_mappings/1.json def update respond_to do |format| if @class_mapping.update(class_mapping_params) format.html { redirect_to @class_mapping, notice: 'Class mapping was successfully updated.' } format.json { render :show, status: :ok, location: @class_mapping } else format.html { render :edit } format.json { render json: @class_mapping.errors, status: :unprocessable_entity } end end end # DELETE /class_mappings/1 # DELETE /class_mappings/1.json def destroy @class_mapping.destroy respond_to do |format| format.html { redirect_to class_mappings_url, notice: 'Class mapping was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_class_mapping @class_mapping = ClassMapping.find(params[:id]) end def find_mapping_id std = params["standard"] sec = params["section"] @mapping_id = 0 std_id = Standard.find_by_standard_name(std) sec_id = Section.find_by_section_name(sec) c_map = ClassMapping.all c_map.each do |c_map| if (c_map.standard_id == std_id.id && c_map.section_id == sec_id.id) @mapping_id = c_map.id end end end # Never trust parameters from the scary internet, only allow the white list through. def class_mapping_params params.require(:class_mapping).permit(:standard_id, :section_id, :school_id) end end
ActionController::Base.class_eval do def self.require_user(options = {}) raise Exception, "require_user cannot be called on ActionController::Base. Only it's subclasses" if self == ActionController::Base prepend_before_filter :require_user, options end helper_method :current_user, :current_user? def current_user @current_user ||= if session[:account_id] and defined?(current_site) (account = BigAuth::Account.find(session[:account_id])) && current_site && account.users.find_by_site_id(current_site.id) elsif session[:account_id] (account = BigAuth::Account.find(session[:account_id])) && account.users.first elsif cookies[:remember_token] and defined?(current_site) (account = BigAuth::Account.find_by_remember_token(cookies[:remember_token])) && current_site && account.users.find_by_site_id(current_site.id) elsif cookies[:remember_token] and defined?(current_site) (account = BigAuth::Account.find_by_remember_token(cookies[:remember_token])) && account.users.first else false end end def current_user? !!current_user end protected # Filters def require_user current_user.present? || deny_access end def require_no_user !current_user.present? || deny_access end def require_super_user (current_user.present? and current_user == User.first) || deny_access end # Utils def store_location session[:return_to] = request.fullpath end def deny_access store_location redirect_to login_path end def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end def current_user=(user) user.tap do |user| user.account.remember session[:account_id] = user.account.id cookies[:remember_token] = user.account.remember_token end end def logout! session[:account_id] = nil @current_user = nil cookies.delete(:remember_token) session[:return_to] = nil end end
# frozen_string_literal: true SATISFACTION_FORM_DATA = { satisfaction: 'PART', person_delivering: { name: 'Mr A Person', address: { premise: '1', street: 'Some Street', thourough_fare: 'Some Village', post_town: 'Some Town', county: 'Some County', country: 'GBR', post_code: 'AB12 3CD', care_of_name: 'Blah', po_box: '1234' }, interest_in_charge: 'Chargee' } }.freeze PART_CEASE_RELEASE_FORM_DATA = { part_cease_release: 'RELEASE', assets_description: '1 EXAMPLE STREET CARDIFF', person_delivering: { name: 'Mr A Person', address: { premise: '1', street: 'Some Street', thourough_fare: 'Some Village', post_town: 'Some Town', county: 'Some County', country: 'GBR', post_code: 'AB12 3CD', care_of_name: 'Blah', po_box: '1234' }, interest_in_charge: 'Chargee' } }.freeze FULL_CEASE_RELEASE_FORM_DATA = { all_cease_release: 'CEASE', person_delivering: { name: 'Mr A Person', address: { premise: '1', street: 'Some Street', thourough_fare: 'Some Village', post_town: 'Some Town', county: 'Some County', country: 'GBR', post_code: 'AB12 3CD', care_of_name: 'Blah', po_box: '1234' }, interest_in_charge: 'Chargee' } }.freeze # rubocop:disable Metrics/BlockLength, Layout/LineLength RSpec.describe CompaniesHouseXmlgateway::Service::ChargeUpdate do subject(:response) { CompaniesHouseXmlgateway.client.perform_charge_update(CH_HEADERS, form_data) } context 'creating a charge update on or after 06/04/2013' do context 'MR04 --> satisfaction' do context 'successful response' do let!(:form_data) { SATISFACTION_FORM_DATA.merge(charge_code: '055334530001') } it 'checks response from CH' do expect(response.success).to eql true end end context 'unsuccessful response' do let!(:form_data) { SATISFACTION_FORM_DATA } it 'checks response from CH' do expect(response.success).to eql false end end end context 'MR05 --> part cease release' do context 'successful response' do let!(:form_data) { PART_CEASE_RELEASE_FORM_DATA.merge(charge_code: '055334530001') } it 'checks response from CH' do expect(response.success).to eql true end end context 'unsuccessful response' do let!(:form_data) { PART_CEASE_RELEASE_FORM_DATA } it 'checks response from CH' do expect(response.success).to eql false end end end context 'MR05 --> FULL cease release' do context 'successful response' do let!(:form_data) { FULL_CEASE_RELEASE_FORM_DATA.merge(charge_code: '055334530001') } it 'checks response from CH' do expect(response.success).to eql true end end context 'unsuccessful response' do let!(:form_data) { FULL_CEASE_RELEASE_FORM_DATA } it 'checks response from CH' do expect(response.success).to eql false end end end end # Cant really test this until we find out where exisiting charge key comes from # stubbing out the success response for the CompaniesHouseXmlgateway::Response # below just to get teh spec to pass. See the below link for more info # https://kudocs.monday.com/boards/1635340513/pulses/1889511000 context 'creating a charge update before 06/04/2013' do context 'satisfaction' do let!(:form_data) do SATISFACTION_FORM_DATA.merge( existing_charge_key: '25cdd00c92fd275031911824f0616dee8dc5c7f27', creation_date: '1995-09-29', instrument_description: 'LEGAL CHARGE', short_particulars: '48 EXAMPLE ROAD CARDIFF TOGETHER WITH BY WAY OF FLOATING SECURITY ALL MOVEABLE PLANT MACHINERY IMPLEMENTS FURNITURE AND EQUIPMENT NOW OR FROM TIME TO TIME PLACED ON OR USED IN OR ABOUT THE PROPERTY' ) end before { expect_any_instance_of(CompaniesHouseXmlgateway::Response).to receive(:success).and_return(true) } it 'receives a successful response from CH' do # need an exisiting charge key from the sandbox to successfully test??? expect(response.success).to eql true end end end end # rubocop:enable Metrics/BlockLength, Layout/LineLength
require 'test_helper' class LeadsSignupTest < ActionDispatch::IntegrationTest test "invalid signup information (does not create lead)" do get '/sign_up' assert_no_difference 'Lead.count' do post '/', params: {lead: { first_name: "", last_name: "", phone_number: "", birthday: "", email: "user@invalid", password: "foo", }}, headers: {'HTTP_REFERER' => '/signup'} end end test "valid signup information (creates lead)" do get '/sign_up' assert_difference 'Lead.count', 1 do post '/', params: { lead: { first_name: "Hugh", last_name: "Kolias", phone_number: "1234567890", birthday: "1990-04-14", email: "hughkolias2@gmail.com", password: "foobar66", } } end end test "on invalid signup information flash is displayed" do get '/sign_up' post '/', params: { lead: { first_name: "", last_name: "", phone_number: "", birthday: "", email: "", password: "", }}, headers: {'referer' => '/'} follow_redirect! assert_select "div.alert.alert-notice", 'First name cannot be blank, Last name cannot be blank, Birthday cannot be blank, Email cannot be blank, Phone number cannot be blank, and Password cannot be blank' end test "on valid signup information flash is displayed and user is redirected" do get '/sign_up' post '/', params: {lead: { first_name: "Hugh", last_name: "Kolias", phone_number: "1234567890", birthday: "1990-04-14", email: "hughkolias2@gmail.com", password: "foobar66", }} follow_redirect! assert_template 'leads/leads/bookings' assert_template partial: "_navbar_logged_in" end end
class SearchService def initialize(zip) @zip = zip @conn = Faraday.new(url: "https://developer.nrel.gov") do |faraday| faraday.adapter Faraday.default_adapter end end def make_stations parse_results.map do |result| Station.new(result) end end def parse_results JSON.parse(raw_results, symbolize_names: true)[:fuel_stations] end def raw_results conn.get("/api/alt-fuel-stations/v1/nearest.json?api_key=#{ENV["nrel_api_key"]}&location=#{zip}&radius=6&fuel_type=LPG,ELEC&limit=10").body end private attr_reader :zip, :conn end
class Admin::VetContactsController < Admin::ApplicationController load_and_authorize_resource respond_to :html, :xml, :json, :xls # GET /vet_contacts # GET /vet_contacts.xml def index @search = VetContact.organization(current_user).search(params[:q]) @vet_contacts = @search.result.paginate(:page => params[:page], :per_page => 10).order("updated_at DESC") respond_with(@vet_contacts) do |format| format.html # index.html.erb format.xls { send_data VetContact.organization(current_user).to_xls, content_type: 'application/vnd.ms-excel', filename: 'vet_contacts.xls' } end end # GET /vet_contacts/1 # GET /vet_contacts/1.xml def show @vet_contact = VetContact.find(params[:id]) respond_with(@vet_contact) end # GET /vet_contacts/new # GET /vet_contacts/new.xml def new @vet_contact = VetContact.new respond_with(@vet_contact) end # GET /vet_contacts/1/edit def edit @vet_contact = VetContact.find(params[:id]) end # POST /vet_contacts # POST /vet_contacts.xml def create @vet_contact = current_user.organization.vet_contacts.new(params[:vet_contact]) if @vet_contact.save flash[:notice] = 'Vet contact was successfully created.' else flash[:error] = 'Vet contact was not successfully created.' end respond_with(@vet_contact, :location => admin_vet_contact_path(@vet_contact)) end # PUT /vet_contacts/1 # PUT /vet_contacts/1.xml def update @vet_contact = VetContact.find(params[:id]) @vet_contact.update_attributes(params[:vet_contact]) respond_with(@vet_contact, :location => admin_vet_contact_path(@vet_contact)) end # DELETE /vet_contacts/1 # DELETE /vet_contacts/1.xml def destroy @vet_contact = VetContact.find(params[:id]) @vet_contact.destroy flash[:notice] = 'Successfully destroyed vet contact.' respond_with(@vet_contact, :location => admin_vet_contacts_path) end end
class CreateUsedUrls < ActiveRecord::Migration[6.1] def change create_table :used_urls, id: false do |t| t.string :short_name t.string :long_name t.datetime :last_used t.timestamps end add_index :used_urls, :short_name, unique: true add_index :used_urls, :last_used end end
# frozen_string_literal: true class ApplicationController def initialize(routes) @routes = routes @params = parse_params @permitted_params = {} @missing_fields = [] end def set_params yield end def present(options = {}) @routes.status(options[:status] || 200) options[:payload] end def param(options = {}) return (@permitted_params = options) if @permitted_params.nil? @permitted_params.merge!(options) @permitted_params end def params return @params if @permitted_params.empty? extract_parameters raise BadRequestException.new(@missing_fields) if @missing_fields.any? @returned_params end private def parse_params JSON.parse(@routes.request.body.read) .merge(@routes.params).with_indifferent_access rescue JSON::ParserError, TypeError @routes.params.with_indifferent_access end def extract_parameters @returned_params = @permitted_params.reduce({}) do |aux, key| if @params[key.first.to_s].nil? @missing_fields << key.first.to_s next aux end aux.merge(:"#{key.first}" => @params[key.first.to_s]) end end end
require "spec_helper" describe RuntimeValidationsController do describe "routing" do it "routes to #index" do get("/runtime_validations").should route_to("runtime_validations#index") end it "routes to #new" do get("/runtime_validations/new").should route_to("runtime_validations#new") end it "routes to #show" do get("/runtime_validations/1").should route_to("runtime_validations#show", :id => "1") end it "routes to #edit" do get("/runtime_validations/1/edit").should route_to("runtime_validations#edit", :id => "1") end it "routes to #create" do post("/runtime_validations").should route_to("runtime_validations#create") end it "routes to #update" do put("/runtime_validations/1").should route_to("runtime_validations#update", :id => "1") end it "routes to #destroy" do delete("/runtime_validations/1").should route_to("runtime_validations#destroy", :id => "1") end end end
require 'rails_helper' describe Item do before do @item = FactoryBot.build(:item) end describe '商品の新規登録' do context '新規登録がうまくいくとき' do it "title,concept,category_id,status_id,delivery_id,area_id,days_id,price,が存在すれば登録できる" do expect(@item).to be_valid end end context '新規登録がうまくいかないとき' do it "titleが空だと登録できない" do @item.title = nil @item.valid? expect(@item.errors.full_messages).to include("Title can't be blank") end it "conceptが空だと登録できない" do @item.concept = nil @item.valid? expect(@item.errors.full_messages).to include("Concept can't be blank") end it "category_idが空だと登録できない" do @item.category_id = nil @item.valid? expect(@item.errors.full_messages).to include("Category can't be blank", "Category is not a number") end it "category_idのidが1の場合登録できない" do @item.category_id = 1 @item.valid? expect(@item.errors.full_messages).to include("Category must be other than 1") end it "status_idが空だと登録できない" do @item.status_id = nil @item.valid? expect(@item.errors.full_messages).to include("Status can't be blank", "Status is not a number") end it "status_idのidが1の場合登録できない" do @item.status_id = 1 @item.valid? expect(@item.errors.full_messages).to include("Status must be other than 1") end it "delivery_idが空だと登録できない" do @item.delivery_id = nil @item.valid? expect(@item.errors.full_messages).to include("Delivery can't be blank", "Delivery is not a number") end it "delivery_idのidが1の場合登録できない" do @item.delivery_id = 1 @item.valid? expect(@item.errors.full_messages).to include("Delivery must be other than 1") end it "area_idが空だと登録できない" do @item.area_id = nil @item.valid? expect(@item.errors.full_messages).to include("Area can't be blank", "Area is not a number") end it "area_idのidが1の場合登録できない" do @item.area_id = 1 @item.valid? expect(@item.errors.full_messages).to include("Area must be other than 1") end it "days_idが空だと登録できない" do @item.days_id = nil @item.valid? expect(@item.errors.full_messages).to include("Days can't be blank", "Days is not a number") end it "days_idのidが1の場合登録できない" do @item.days_id = 1 @item.valid? expect(@item.errors.full_messages).to include("Days must be other than 1") end it "priceが空だと登録できない" do @item.price = nil @item.valid? expect(@item.errors.full_messages).to include("Price can't be blank") end it "priceが半角数字以外の場合登録できない" do @item.price = "ABあ亜ア0" @item.valid? expect(@item.errors.full_messages).to include("Price is not a number") end it "priceが300未満だと登録できない" do @item.price = 290 @item.valid? expect(@item.errors.full_messages).to include("Price must be greater than or equal to 300") end it "priceが10000000以上だと登録できない" do @item.price = 10000000 @item.valid? expect(@item.errors.full_messages).to include("Price must be less than or equal to 9999999") end end end end
require 'rails_helper' RSpec.describe "record_types/new", type: :view do before(:each) do assign(:record_type, create(:record_type)) end it "renders new record_type form" do render assert_select "form[action=?][method=?]", record_types_path, "post" do assert_select "input#record_type_name[name=?]", "record_type[name]" end end end
# frozen_string_literal: true module RbLint module Rules # Detects assigning values inside of conditions. For example: # # bar if foo = 1 # module AssignmentInCondition %i[case elsif if unless until while].each do |event| define_method(:"on_#{event}") do |predicate, *others| if %i[assign massign].include?(predicate[0]) violation('Assignment found inside a condition.') end super(predicate, *others) end end end # Detects case clauses that are duplicated. For example: # # case foo # when :one, :one # 1 # end # module DuplicateCaseCondition def on_case(predicate, following) clauses = clauses_from(following) if clauses.uniq.length != clauses.length violation('Duplicate case clauses found.') end super end private def clauses_from(clause) case clause in [:when, args, _, following] args + clauses_from(following) in [:in, args, _, following] clauses_from(following) else [] end end end # Detects literal values used inside conditions. For example: # # foo if 1 # module LiteralAsCondition %i[case elsif if unless until while].each do |event| define_method(:"on_#{event}") do |predicate, *others| if literal?(predicate) violation('Literal found inside a condition.') end super(predicate, *others) end end private def literal?(node) case node in [:@int, *] | [:var_ref, [:@kw, 'true' | 'false']] true in [:binary, left, :"||", right] literal?(left) || literal?(right) else false end end end # Return a module containing all of the configured rules def self.from(config) config.default = { 'Enabled' => true } Module.new do Rules.constants.each do |constant| include(Rules.const_get(constant)) if config[constant.to_s]['Enabled'] end end end end end
class SessionController < ApplicationController def new; end def create user = User.find_by(email: params[:email]) if user.nil? flash[:error] = 'The provided email is not associated with an account. Please register or try again.' redirect_to login_path elsif user.authenticate(params[:password]) session[:user_id] = user.id redirect_to dashboard_index_path if current_user.user? redirect_to admin_dashboard_path if current_user.admin? else flash[:error] = 'The password provided is incorrect. Please try again.' redirect_to login_path end end def destroy session[:user_id] = nil redirect_to root_path end end
require "test_helper" describe "Markov::DB" do before do @dbname = "markov_test" @source = "test/fixtures/text_sample.txt" @parser = Markov::Parser.new(@source) @db = Markov::DB.new(dbname: @dbname) end it "connects to the db" do assert @db.send(:connection, "") end it "makes the word groups from a parser" do assert_equal @db.word_groups(@source), @parser.groups(4) end describe "adding a csv source" do before do @csv = @db.tmp_csv("testing", @source) end it "makes a temporary csv" do assert File.exists?(@csv) end it "imports the temp csv" do @db.import("testing", @source) @query = "SELECT * FROM word_groups WHERE source = 'testing'" assert_equal @db.send(:connection, @query).values.length, @db.word_groups(@source, { tagged: true }).length end it "gets a list of available csv sources" do @db.import("testing", @source) assert_includes @db.csv_sources, "testing" end after do FileUtils.remove_entry(File.dirname(@csv)) end end after do @db.send(:connection, "DELETE FROM word_groups WHERE source = 'testing';") @db.send(:connection, "TRUNCATE word_groups_jsonb") end end
# coding: utf-8 class Admin::TicketsController < Admin::ApplicationController before_filter :setup_default_filter, only: :index def index @search = Ticket.search(params[:q]) search_result = @search.result(distinct: true).order("id DESC, updated_at DESC") @tickets = show_all? ? search_result : search_result.page(params[:page]) # записываем отрисованные тикеты в куки, для перехода к следующему тикету после ответа cookies[:tickets_list] = @tickets.map(&:id).join(',') end def show @ticket = Ticket.find(params[:id]) @next_ticket = @ticket.find_next_ticket_from(cookies[:tickets_list]) @replies = @ticket.replies.dup @reply = @ticket.replies.build do |reply| reply.user = current_user end @ticket_tag = TicketTag.new end def close @ticket = Ticket.find(params[:ticket_id]) if @ticket.close @ticket.user.track! :close_ticket, @ticket, current_user redirect_to [:admin, @ticket] else redirect_to [:admin, @ticket], alert: @ticket.errors.full_messages.join(', ') end end def reactivate @ticket = Ticket.find(params[:ticket_id]) if @ticket.reactivate @ticket.user.track! :reactivate_ticket, @ticket, current_user redirect_to [:admin, @ticket] else redirect_to [:admin, @ticket], alert: @ticket.errors.full_messages.join(', ') end end def edit @ticket = Ticket.find(params[:id]) end def update @ticket = Ticket.find(params[:id]) if @ticket.update_attributes(params[:ticket], as: :admin) @ticket.user.track! :update_ticket, @ticket, current_user redirect_to [:admin, @ticket] else render :edit end end def tag_relations_form @ticket = Ticket.find(params[:ticket_id]) render partial: 'tag_relations_form', locals: { ticket: @ticket } end def update_subscribers @ticket = Ticket.find(params[:ticket_id]) @ticket.update_attributes(params[:ticket], as: :admin) @ticket.user.track! :update_ticket_subscribers, @ticket, current_user render partial: 'ticket_subscribers', locals: { ticket: @ticket } end def accept @ticket = Ticket.find(params[:ticket_id]) @ticket.accept(current_user) redirect_to [:admin, @ticket] end private def default_breadcrumb false end def setup_default_filter params[:q] ||= { state_in: ['active', 'answered'] } end end
require "spec_helper" module GotFixed describe IssuesController do routes { GotFixed::Engine.routes } describe "routing" do it "routes to #index" do get("/issues").should route_to("got_fixed/issues#index") end end end end
# Included in +ApplicationHelper+, this sets up the override logic for # cobrand-specific assets. Assuming the <tt>@cobrand</tt> instance variable is # set and the asset exists in the current cobrand's (or cobrand's parent's or # grandparent's) public directory, it will render. Under <tt>Rails.root</tt>: # # cobrands/#{short_name}/public/(images|javascripts|stylesheets)/#{asset} module CobrandAssetOverrides #:nodoc: include ActionView::Helpers::AssetTagHelper def image_path(source) super detect_cobrand_asset(source, "images") end alias path_to_image image_path # Re-alias. private # See <tt>ActionView::Helpers::AssetTagHelper#compute_public_path</tt>. def detect_cobrand_asset(source, dir, ext = nil) return source if @cobrand.nil? || source[%r{^(?:[-a-z]+://|/)}i] full_source = ext.blank? ? source : "#{source}.#{ext}" @cobrand.ancestors.each do |cobrand| cobrand_source = File.join cobrand.public_path, dir, full_source if File.exist? cobrand_source full_source += "?#{cobrand_asset_id cobrand_source}" return "/#{cobrand.short_name}/#{dir}/#{full_source}" end end source end # See <tt>ActionView::Helpers::AssetTagHelper#rails_asset_id</tt>. def cobrand_asset_id(source) ENV["RAILS_ASSET_ID"] || File.mtime(source).to_i end end
class CreateReservations < ActiveRecord::Migration[6.1] def change create_table :reservations do |t| t.references :user t.references :screening t.references :cinema t.references :movie t.boolean :confirmed, default: false t.timestamps end end end
require 'spec_helper' feature 'visit password edit screen' do scenario 'with valid token in url, redirects to the edit page with the token removed from the url' do user = create(:user, :with_password_reset_token_and_timestamp) visit_password_reset_page_for(user) expect(current_path).to eq edit_users_password_path(user) expect(current_path).to_not have_content('token') end scenario 'with an invalid token in url, failure and prompt to request a password reset' do user = create(:user, :with_password_reset_token_and_timestamp) visit_password_reset_page_for(user, 'this is an invalid token') expect_forbidden_failure end scenario 'with a valid token, but an expired timestamp' do user = create(:user, :with_password_reset_token_and_timestamp, password_reset_sent_at: 20.years.ago) visit_password_reset_page_for(user) expect_token_expired_failure end scenario 'with a nil token' do user = create(:user) visit_password_reset_page_for(user, token: nil) expect_forbidden_failure end end feature 'visitor updates password' do before(:each) do @user = create(:user, :with_password_reset_token_and_timestamp) end scenario 'with valid password, signs in user' do update_password @user, 'newpassword' expect_user_to_be_signed_in end scenario 'with a valid password, password is updated' do old_pw = @user.encrypted_password update_password @user, 'newpassword' expect_password_was_updated(old_pw) end scenario 'password change signs in user' do update_password @user, 'newpassword' sign_out sign_in_with @user.email, 'newpassword' expect_user_to_be_signed_in end scenario 'signs in, redirects user' do update_password @user, 'newpassword' expect_path_is_redirect_url end end feature 'visitor updates password with invalid password' do before(:each) do @user = create(:user, :with_password_reset_token_and_timestamp) end scenario 'with a blank password, signs out user' do update_password @user, '' expect_invalid_password expect_user_to_be_signed_out end scenario 'with a short password, flashes invalid password' do update_password @user, 'short' expect_invalid_password expect_user_to_be_signed_out end end def update_password(user, password) visit_password_reset_page_for user fill_in 'password_reset_password', with: password click_button 'Save this password' end def visit_password_reset_page_for(user, token = user.password_reset_token) visit edit_users_password_path(id: user, token: token) end def expect_invalid_password expect(page).to have_content I18n.t('flashes.failure_after_update') end def expect_forbidden_failure expect(page).to have_content I18n.t('passwords.new.description') expect(page).to have_content I18n.t('flashes.failure_when_forbidden') end def expect_token_expired_failure expect(page).to have_content 'Sign in' expect(page).to have_content I18n.t('flashes.failure_token_expired') end # def expect_path_is_redirect_url # expect(current_path).to eq(Authenticate.configuration.redirect_url) # end def expect_password_was_updated(old_password) expect(@user.reload.encrypted_password).not_to eq old_password end
# frozen_string_literal: true module Api module V1 # API for authorization class AuthController < BaseController # POST /api/v1/sign_in def sign_in user = users_collection.authenticate(params[:email], params[:password]) render_response("Invalid email or password", 401) && return unless user render json: { token: JsonWebToken.encode({ user_id: user.id }, jwt_lifetime) }, status: :ok rescue StandardError => e log_error(e, "[Api::V1::AuthorizationController] Authorization failed with params: #{params.inspect}") render_error(e) end private def jwt_lifetime Rails.application.config.jwt_default_lifetime unless params[:unlimited_expiry_time].eql?("true") end def users_collection User end end end end
class Port < BaseResource schema do string :host_interface integer :host_port integer :container_port string :proto end end
# == Schema Information # # Table name: tenants # # id :integer not null, primary key # nome :string(255) # created_at :datetime not null # updated_at :datetime not null # subdomain :string(255) # require 'spec_helper' describe Tenant do let (:tenant) { FactoryGirl.create(:tenant) } subject { tenant } it { should respond_to(:nome) } it { should respond_to(:subdomain) } it { should be_valid } describe "Should have many users" do it { should have_many(:users) } end end
# coding: UTF-8 require 'sinatra' require 'sinatra/streaming' require 'zip/filesystem' require 'aws-sdk' require 'securerandom' require './group' DEFAULT_BUCKET = ENV['DEFAULT_BUCKET'] DEFAULT_ACCOUNT = ENV['DEFAULT_ACCOUNT'] DEFAULT_MONTH = Date.today.strftime('%Y-%m') get '/' do '<html><body><form action="download.csv" method="get">' + 'Bucket: <input name="bucket" value="'+DEFAULT_BUCKET+'"/><br/>' + 'Account: <input name="account" value="'+DEFAULT_ACCOUNT+'"/><br/>' + 'Month: <input type="month" name="month" value="'+DEFAULT_MONTH+'"/><br/>' + 'Skip resources with Customer tag: <input type="checkbox" name="skip_customer" value="true"/><br/>' + ' <button>Download</button>' + '</form></body></html>' end get '/download.csv' do bucket = params[:bucket] || DEFAULT_BUCKET account = params[:account] || DEFAULT_ACCOUNT file = "#{account}-aws-billing-detailed-line-items-with-resources-and-tags-#{params[:month]}.csv" temp = "tmp/#{SecureRandom.uuid}-#{params[:month]}" client = Aws::S3::Client.new(region: 'us-east-1') client.get_object({ response_target: "#{temp}.zip", bucket: bucket, key: "#{file}.zip" }) Zip::File.open("#{temp}.zip") do |zipfile| zipfile.extract(file, "#{temp}.csv") end File.delete("#{temp}.zip") content_type :csv headers 'Content-disposition' => "attachment; filename=grouped-#{params[:month]}.csv" stream do |out| process_csv(File.new("#{temp}.csv", 'r:UTF-8'), out, params[:skip_customer] == 'true') out.flush File.delete("#{temp}.csv") end end
class Brain WINNING_COMBOS = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7] ].freeze def initialize end private def invert(list) (1..9).to_a.select { |num| !list.include?(num) } end def filter_wins(num) WINNING_COMBOS.select do |combo| combo.include?(num) end end public def find_wins(list) wins = Array.new(WINNING_COMBOS) not_marked = invert(list) temp = [] loop do break if not_marked.empty? || wins.empty? temp = filter_wins(not_marked.pop) if !temp.empty? temp.each { |combo| wins.delete(combo) } end end wins end def complete_two_in_row(moves) WINNING_COMBOS.each do |combo| combo_compare = moves.select do |mark| combo.include?(mark) end next unless combo_compare.count == 2 combo.each do |mark| return mark unless moves.include?(mark) end end nil end end
class CreateMedias < ActiveRecord::Migration def change create_table :medias do |t| t.belongs_to :user t.belongs_to :account, index: true t.string :url if ActiveRecord::Base.connection.class.name === 'ActiveRecord::ConnectionAdapters::PostgreSQLAdapter' t.json :data else t.text :data end t.timestamps null: false end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # module ActionView module Helpers # Provides a set of methods for making it easier to debug Rails objects. module DebugHelper # Returns a YAML representation of +object+ wrapped with <pre> and </pre>. # If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead. # Useful for inspecting an object at the time of rendering. # # ==== Example # # @user = User.new({ :username => 'testing', :password => 'xyz', :age => 42}) %> # debug(@user) # # => # <pre class='debug_dump'>--- !ruby/object:User # attributes: # &nbsp; updated_at: # &nbsp; username: testing # # &nbsp; age: 42 # &nbsp; password: xyz # &nbsp; created_at: # attributes_cache: {} # # new_record: true # </pre> def debug(object) begin Marshal::dump(object) "<pre class='debug_dump'>#{h(object.to_yaml).gsub(" ", "&nbsp; ")}</pre>" rescue Exception => e # errors from Marshal or YAML # Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback "<code class='debug_dump'>#{h(object.inspect)}</code>" end end end end end
class AcceptedOffersController < ApplicationController def create @offer = Offer.find(params[:offer_id]) @accepted_offer = AcceptedOffer.new @accepted_offer.offer = @offer @accepted_offer.user = current_user authorize @accepted_offer if @accepted_offer.save redirect_to offer_path(@offer), notice: 'You have committed to pick up.' else render :show end end def destroy @accepted_offer = AcceptedOffer.find(params[:id]) authorize @accepted_offer @accepted_offer.destroy redirect_to @accepted_offer.offer, notice: 'Your commitment to pick up was successfully cancelled.' end end
class GeoRoundRobin #for further purposes @@current_cycle = nil def self.companies_for_slots(companies, slots=nil) # Podria validar que los datos dentro de companies sea de la clase correspondiente pero seria limitar la funcionalidad. raise "companies should be an Array of Companies" unless companies.class.eql?(Array) && companies.any? raise "Slots has to be a number or nil" unless slots.class.eql?(Integer) || slots.nil? # returns 2 by default slots = slots || 2 # current cycle or a new one based on how many companies there are company_cycle = @@current_cycle || companies.cycle current_companies = [] slots.times do current_companies << company_cycle.next end @@current_cycle = company_cycle return current_companies end end
require 'board' describe 'Board' do let(:b){Board.new} describe '#initialize' do it 'should create a bomb grid' do expect(b.bomb_grid).to be_a(Array) end it 'should create flag-activate grid' do expect(b.bomb_grid).to be_a(Array) end end describe '#populate' do it 'populates bomb grid with bombs' end describe '#number' do it 'fills out bomb grid with proximity numbers' end describe '#receive_flag' do let(:coordinate){[2,2]} it 'adds flag to flag_grid' do b.receive_flag(coordinate) expect(b.flag_grid[coordinate[0]][coordinate[1]]).not_to be_nil end it 'removes flag from flag_grid if flag was already there' do b.receive_flag(coordinate) b.receive_flag(coordinate) expect(b.flag_grid[coordinate[0]][coordinate[1]]).to be_nil end end describe '#activate_cell' do it 'adds activation mark to flag-activate grid' do b.activate_cell([1,2]) expect(b.flag_grid[1][2]).not_to be_nil end end end
module NavigationHelpers def path_for(page_description) case page_description when "home" then root_path else raise "unrecognized page description \"#{page_description}\"." end end def locator_for(location_description) case location_description when "menu" then "#menu" when "navigation" then "#menu" when "secondary menu" then ".secondary-nav" when "notification area" then "#notifications" when "page title" then "#page-title" when "main content" then "#main-content" when /(\d(?:st|nd|rd|th)) (.+) row/ then "##{hyphenize($2)}-table tr:nth-child(#{$1.to_i + 1})" else raise "unrecognized location description \"#{location_description}\"." end end private def hyphenize(words) words.gsub(/\s/, "-") end end World(NavigationHelpers)
class Carriage include Manufacturer include Validation attr_reader :capacity, :occupied validate :manufacturer, :presence def initialize(manufacturer, capacity) @manufacturer = manufacturer @capacity = capacity validate! @occupied = 0 end def free_capacity capacity - occupied end end
class Admin::UsersController < ApplicationController layout 'admin' before_action :authenticate_user! before_action :set_users, only: [:edit, :update, :destroy] load_and_authorize_resource def index @users = User.all end def new @user = User.new @user.build_agent_detail end def create @user = User.create(user_params) @user.skip_password_validation = true respond_to do |format| if @user.save format.html { custom_path(@user) } else format.html { render :action => "new" } end end end def edit end def agent_list @users = User.agents end def customer_list @users = User.customers end def update if user_params[:password].blank? user_params.delete(:password) user_params.delete(:password_confirmation) end # https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-edit-their-account-without-providing-a-password successfully_updated = if needs_password?(@user, user_params) @user.update(user_params) else @user.update_without_password(user_params) end respond_to do |format| if successfully_updated format.html { custom_path(@user) } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @user.errors, status: :unprocessable_entity } end end end def destroy @user.destroy respond_to do |format| format.html { custom_path(@user) } format.xml { head :ok } end end private def set_users @user = User.find(params[:id]) end def user_params params.required(:user).permit(:username, :email,:password, :password_confirmation, :first_name, :last_name, :user_type, agent_detail_attributes: [:id, :code_number, :address, :contact_number, :designation]) end # https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-edit-their-account-without-providing-a-password def needs_password?(user, params) params[:password].present? end def custom_path(user) if user.user_type.eql?('agent') redirect_to agent_list_admin_users_path, notice: 'Agent was successfully created.' else redirect_to customer_list_admin_users_path, notice: 'Customer was successfully created.' end end end
class AriaquenuploadsController < ApplicationController # GET /ariaquenuploads # GET /ariaquenuploads.json def index @ariaquenuploads = Ariaquenupload.all respond_to do |format| format.html # index.html.erb format.json { render json: @ariaquenuploads } end end # GET /ariaquenuploads/1 # GET /ariaquenuploads/1.json def show @ariaquenupload = Ariaquenupload.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @ariaquenupload } end end # GET /ariaquenuploads/new # GET /ariaquenuploads/new.json def new @ariaquenupload = Ariaquenupload.new respond_to do |format| format.html # new.html.erb format.json { render json: @ariaquenupload } end end # GET /ariaquenuploads/1/edit def edit @ariaquenupload = Ariaquenupload.find(params[:id]) end # POST /ariaquenuploads # POST /ariaquenuploads.json def create @ariaquenupload = Ariaquenupload.new(params[:ariaquenupload]) respond_to do |format| if @ariaquenupload.save format.html { redirect_to @ariaquenupload, notice: 'Ariaquenupload was successfully created.' } format.json { render json: @ariaquenupload, status: :created, location: @ariaquenupload } else format.html { render action: "new" } format.json { render json: @ariaquenupload.errors, status: :unprocessable_entity } end end end # PUT /ariaquenuploads/1 # PUT /ariaquenuploads/1.json def update @ariaquenupload = Ariaquenupload.find(params[:id]) respond_to do |format| if @ariaquenupload.update_attributes(params[:ariaquenupload]) format.html { redirect_to @ariaquenupload, notice: 'Ariaquenupload was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @ariaquenupload.errors, status: :unprocessable_entity } end end end # DELETE /ariaquenuploads/1 # DELETE /ariaquenuploads/1.json def destroy @ariaquenupload = Ariaquenupload.find(params[:id]) @ariaquenupload.destroy respond_to do |format| format.html { redirect_to ariaquenuploads_url } format.json { head :no_content } end end end
class Profile < ActiveRecord::Base enum gender: { male: 'M', female: 'F'} has_one :casa belongs_to :screen_writer mount_uploader :profile_pic, ProfilePicUploader # Tells rails to use this uploader for this model. validates :fname,:dob,:gender, :presence => true has_one :address, -> { where entity_type: :screen_writer }, foreign_key: :entity_id end
class Attribute < ActiveRecord::Base has_many :children, :foreign_key => :parent_id, :class_name => 'Attribute', :order => '`attributes`.`order`, `attributes`.`value` ' belongs_to :parent, :foreign_key => :parent_id, :class_name => 'Attribute' has_and_belongs_to_many :events, :class_name => "Event" , :join_table=> "events_attributes" has_and_belongs_to_many :occurrences, :class_name => "Occurrence" , :join_table=> "occurrences_attributes" scope :top_categories, :conditions => ['parent_id IS NULL'] scope :with_occurrences, :conditions => ['occurrences_count > ?', 0] def to_param "#{id}-#{value.to_url}" end def leafs @leafs ||= []# self.children end def leafs=(attrs) @leafs = attrs end def self.find_with_counts(conditions) find(:all, :select => 'attributes.*, count(occurrences.id) as occurrences_count', :joins => :occurrences, :conditions => conditions, :group => 'attributes.id') end def on_home_page=(value) write_attribute(:on_home_page, value) # We need to update all children and their childrent with the value self.children.each do |child| child.on_home_page = value child.save! end end def to_s_long if ( self.parent == nil) return "Rubro >> " + self.value else return parent.to_s_long + " >> " + self.value end end def update_events_count children.each { |child| child.update_events_count } self.events_count = events.count + children.inject(0) { |sum, child| sum + child.events_count } save! end def update_occurrences_count(conditions) children.each { |child| child.update_occurrences_count(conditions) } self.occurrences_count = occurrences.count(conditions) + children.inject(0) { |sum, child| sum + child.occurrences_count } save! end def update_count(conditions) children.each { |child| child.update_count(conditions) } update_events_count update_occurrences_count(conditions) self.count = occurrences_count + events_count save! end # Updates occurrences and events count for each category on database for current date def self.recount categories = Attribute.find(:all, :conditions => ['parent_id is null']) categories.each { |category| category.update_count(:conditions => ['date >= ?', Date.current])} end def parent_chain self.parent_id.blank? ? [self] : [self, self.parent.parent_chain].flatten end end # == Schema Info # Schema version: 20110328181217 # # Table name: attributes # # id :integer(4) not null, primary key # name :string(50) not null # parent_id :integer(4) # value :string(50) not null # icon :string(50) # order :integer(4) # count :integer(4) # events_count :integer(4) # occurrences_count :integer(4) # on_home_page :boolean(1) not null, default(TRUE) # top_parent_id :integer(4)
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" RELEASE="3.6.3" BUILD="1" # Synced folders, if any, are stored here synced_folders=Hash.new # Extract SYNCED_FOLDERS into a hash for use below if ENV['SYNCED_FOLDERS'] ENV['SYNCED_FOLDERS'].split(/[,\s]+/).each do |pair| (src,dest) = pair.split(/:/) synced_folders[src] = dest end end Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # Dynamic Node Configuration # The number of client hosts to provision and bootstrap to the hub. Adjust this as desired. hosts = 4 ##### No edits below this point are necessary ##### # Every Vagrant virtual environment requires a box to build off of. config.vm.box = "centos-6.5-x86_64-cfengine_enterprise-#{RELEASE}-#{BUILD}" config.vm.box_url = "http://cfengine.vagrant-baseboxes.s3.amazonaws.com/#{config.vm.box}.box" # Specify the first three octects of the private host_only network for inter # vm communication first_three_network_octets = "192.168.33" # We reserve the hub ip for .2 cfengine_hub_ip = "#{first_three_network_octets}.2" # All the hosts get port 80 forwarded to this port + host_number # (just like the IP) prefix_80_fwd = 900 # Begin Hub Configuration # hub_80_fwd = Integer("#{prefix_80_fwd}#{0+2}") config.vm.define :hub do |hub| hub.vm.hostname = "hub" hub.vm.network :private_network, ip: "#{cfengine_hub_ip}" hub.vm.network :forwarded_port, guest: 80, host: hub_80_fwd # Mount synced foleders (these are also mounted on clients below) synced_folders.each { |k, v| hub.vm.synced_folder k, v } if ENV['MASTERFILES'] hub.vm.synced_folder ENV['MASTERFILES'], "/var/cfengine/masterfiles" else hub.vm.synced_folder "./masterfiles", "/var/cfengine/masterfiles" end hub.vm.provider "virtualbox" do |v| # v.gui = true v.customize ["modifyvm", :id, "--memory", "512", "--cpus", "2"] #v.name = "hub_#{package_version}_#{RELEASE}" v.name = "CFEngine Enterprise #{RELEASE}-#{BUILD} hub" end # Use a synced folder so that we can edit from outside of the environment # A typical workflow has masterfiles pulled from version control hub.vm.provision :shell, :path => "scripts/install_cfengine_enterprise.sh", :args => "hub" hub.vm.provision :shell, :path => "scripts/bootstrap_cfengine.sh", :args => "#{cfengine_hub_ip}" hub.vm.provision :shell, :path => "scripts/instructions.sh", :args => "localhost #{hub_80_fwd}" end # # Begin Dynamic Node Specification # # Calculate Node IP # .1 is reserved for internal router # .2 is reserved for the hub # .3 begins host ips host_ip_offset = 2 #maxhosts = 252 # Without a license there is no sense in going beyond 25 hosts. maxhosts = 25 (1..hosts).each do |host_number| # Set padding for host name to make it look pretty host_name = "host" + host_number.to_s.rjust(3, '0') # Calculate ip address for host host_ip = "#{first_three_network_octets}.#{host_number+host_ip_offset}" # Calculate host port to forward to port 80 host_80_fwd = Integer("#{prefix_80_fwd}#{host_number+host_ip_offset}") config.vm.define host_name.to_sym do |host| host.vm.hostname = "#{host_name}" host.vm.network :private_network, ip: "#{host_ip}" host.vm.network :forwarded_port, guest: 80, host: host_80_fwd # Mount synced foleders (these are also mounted on by the hub above) synced_folders.each { |k, v| config.vm.synced_folder k, v } host.vm.provision :shell, :path => "scripts/install_cfengine_enterprise.sh", :args => "agent" host.vm.provision :shell, :path => "scripts/bootstrap_cfengine.sh", :args => "#{cfengine_hub_ip}" host.vm.provision :shell, :path => "scripts/instructions.sh", :args => "localhost #{hub_80_fwd}" host.vm.provider "virtualbox" do |v| v.customize ["modifyvm", :id, "--memory", "128", "--cpus", "2"] #v.gui=true #v.name = "agent_#{host_name}_#{package_version}_#{RELEASE}" #v.name = "agent_#{host_name}" v.name = "CFEngine Enterprise #{RELEASE}-#{BUILD} agent #{host_name}" end end end end
# == Schema Information # # Table name: visits # # id :integer not null, primary key # visit_nr :integer # visit_date :datetime # league :string(255) # home_club :string(255) # away_club :string(255) # ground :string(255) # street :string(255) # city :string(255) # country :string(255) # longitude :float # latitude :float # gmaps :boolean # result :string(255) # season :string(255) # kickoff :string(255) # gate :integer # user_id :integer # created_at :datetime not null # updated_at :datetime not null # class Visit < ActiveRecord::Base belongs_to :user acts_as_gmappable attr_accessible :away_club, :city, :gate, :ground, :home_club, :kickoff, :latitude, :longitude, :gmaps, :league, :result, :season, :street, :country, :user_id, :visit_date, :visit_nr validates :city, :street, :country, :ground, :result, :visit_nr, :visit_date, presence: true def gmaps4rails_address "#{self.street}, #{self.city}, #{self.country}" end def gmaps4rails_infowindow "<p>#{self.home_club}</p> <p>#{self.ground}</p> <p><a href='/visits/#{self.id}'>view details</a></p>" end end
class PostEvent < ApplicationRecord validates :title, presence: true validates :title, length: { maximum: 40 } validates :description, length: { maximum: 300 } validates :category, inclusion: { in: %w[defect supply others], message: 'Category need to be choosen' } validates :importance, inclusion: { in: %w[important trivial], message: 'Importance need to be choosen' } validate :file_size_have_to_be_less_than_5mb, on: :create validate :file_format_jpg_jpeg_png, on: :create belongs_to :user has_many :likes, dependent: :destroy has_many :messages, dependent: :destroy has_many :notifications, dependent: :nullify has_many_attached :images scope :find_by_title, ->(query) do where('title ILIKE ?', "%#{sanitize_sql_like(query)}%") end def file_size_have_to_be_less_than_5mb return false unless images.attached? images.attachments.each { |photo| errors.add(:images, 'can\'t be greater than 5MB') if photo.byte_size > 5_000_000 } end def file_format_jpg_jpeg_png return false unless images.attached? images.attachments.each do |photo| if photo.content_type != 'image/png' && photo.content_type != 'image/jpg' && photo.content_type != 'image/jpeg' errors.add(:images, 'image needs to be png / jpeg / jpg') end end end end
class ChangeFundAmountDefault < ActiveRecord::Migration def change change_column :campaigns, :fund_goal, :integer, :default => 0 change_column :campaigns, :fund_amount, :integer, :default => 0 end end
#!/usr/bin/env ruby require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment')) # 1. Выбираем проекты из списка. project_ids = File.readlines('tmp/del.txt').map(&:to_i) # 2. Выбираем проекты для работы. projects = Project.includes(:card, :user, :research_areas, :direction_of_sciences, :critical_technologies).where(id: project_ids) # 3. a. Все поля карточек проектов = "none"; # b. "Направления исследований"="Информационно-телекоммуникационные системы"; # c. "Критические технологии"="Компьютерное моделирование наноматериалов, наноустройств и нанотехнологий"; # d. "Области науки"="Информатика". project = projects.first card_attrs = project.card .attributes .except("id", "project_id") .each_with_object({}) { |(k, v), h| h[k] = "none" } research_area = ResearchArea.find_by_name("Информатика") direction_of_science = DirectionOfScience.find_by_name("Информационно-телекоммуникационные системы") critical_technology = CriticalTechnology.find_by_name("Компьютерное моделирование наноматериалов, наноустройств и нанотехнологий") Project.transaction do projects.each do |project| project.card.update_attributes(card_attrs) project.research_areas = [research_area] project.direction_of_sciences = [direction_of_science] project.critical_technologies = [critical_technology] # 4. Рассылаем пользователям извещение об удалении проекта. Mailer.delay.junk_project_clearence(project.user.full_name, project.id, project.title, project.user.emails) end end
class AddUserToLegacyUsers < ActiveRecord::Migration def change add_reference :legacy_users, :user, index: {unique: true}, foreign_key: true end end
class Account attr_reader :id attr_reader :balance PENALTY = 5.00 def initialize _id, _balance @id = _id.to_i @balance = _balance.to_f.round 2 end def transaction amount amount.to_f.round 2 @balance += amount penalize if @balance < 0.0 and amount < 0.0 @balance = @balance.round 2 end private def penalize @balance -= PENALTY end end
class FightersGuild::FightersGuildController < ApplicationController check_authorization rescue_from CanCan::AccessDenied do |exception| redirect_to new_user_registration_path, :alert => exception.message end before_filter :set_lists private def set_lists @questpages = Questpage.all end def churn_badge args={} badge = args[:badge] videos = args[:videos] user = args[:user] videos.each do |video| player_video = PlayerVideo.where( :user_id => user.id, :video_id => video.id ).first if player_video video.tasks.each do |task| if player_video.tasks.include? task.id badge[:player][:n_done] += 1 else badge[:player][:n_not_done] += 1 badge[:player][:is_accomplished] = false end end badge[:player][:percent_done] = 100 * badge[:player][:n_done].to_f / ( 0.0001 + badge[:player][:n_done] + badge[:player][:n_not_done] ) else badge[:player][:percent_done] = 0 badge[:player][:is_accomplished] = false end end if 0 == videos.length badge[:player][:percent_done] = 0 badge[:player][:is_accomplished] = false end badge[:order_value] = badge[:player][:is_accomplished] ? badge[:accomplished_order_value] : badge[:unaccomplished_order_value] # byebug end def churn_questsets qs @questsets.each_with_index do |q, idx| if 0 == idx q[:is_available] = true elsif user_signed_in? if qs[idx-1][:player][:is_accomplished] q[:is_available] = true else q[:is_available] = false end else q[:is_available] = false end end end end
require_relative '../../test_helper' require 'sidekiq/testing' class Bot::Smooch3Test < ActiveSupport::TestCase def setup super setup_smooch_bot end def teardown super CONFIG.unstub(:[]) Bot::Smooch.unstub(:get_language) end test "should create media" do Sidekiq::Testing.inline! do json_message = { type: 'image', text: random_string, mediaUrl: @media_url_2, mediaType: 'image/jpeg', role: 'appUser', received: 1573082583.219, name: random_string, authorId: random_string, mediaSize: random_number, '_id': random_string, source: { originalMessageId: random_string, originalMessageTimestamp: 1573082582, type: 'whatsapp', integrationId: random_string }, language: 'en' }.to_json assert_difference 'ProjectMedia.count' do SmoochWorker.perform_async(json_message, 'image', @app_id, 'default_requests', YAML.dump({})) end end end test "should create media with unstarted status" do messages = [ { '_id': random_string, authorId: random_string, type: 'text', text: random_string } ] payload = { trigger: 'message:appUser', app: { '_id': @app_id }, version: 'v1.1', messages: messages, appUser: { '_id': random_string, 'conversationStarted': true } }.to_json Bot::Smooch.run(payload) pm = ProjectMedia.last assert_equal 'undetermined', pm.last_verification_status # Get requests data sm = pm.get_annotations('smooch').last requests = DynamicAnnotation::Field.where(annotation_id: sm.id, field_name: 'smooch_data') assert_equal 1, requests.count end test "should bundle messages" do Sidekiq::Testing.fake! do uid = random_string messages = [ { '_id': random_string, authorId: uid, type: 'text', text: 'foo', }, { '_id': random_string, authorId: uid, type: 'image', text: 'first image', mediaUrl: @media_url }, { '_id': random_string, authorId: uid, type: 'image', text: 'second image', mediaUrl: @media_url_2 }, { '_id': random_string, authorId: uid, type: 'text', text: 'bar' } ] messages.each do |message| payload = { trigger: 'message:appUser', app: { '_id': @app_id }, version: 'v1.1', messages: [message], appUser: { '_id': random_string, 'conversationStarted': true } }.to_json Bot::Smooch.run(payload) sleep 1 end assert_difference 'ProjectMedia.count' do Sidekiq::Worker.drain_all end pm = ProjectMedia.last assert_no_match /#{@media_url}/, pm.text assert_equal 'UploadedImage', pm.media.type end end test "should delete cache entries when user annotation is deleted" do create_annotation_type_and_fields('Smooch User', { 'Id' => ['Text', false], 'App Id' => ['Text', false], 'Data' => ['JSON', false] }) Bot::Smooch.unstub(:save_user_information) SmoochApi::AppApi.any_instance.stubs(:get_app).returns(OpenStruct.new(app: OpenStruct.new(name: random_string))) { 'whatsapp' => '', 'messenger' => 'http://facebook.com/psid=1234', 'twitter' => 'http://twitter.com/profile_images/1234/image.jpg', 'other' => '' }.each do |platform, url| SmoochApi::AppUserApi.any_instance.stubs(:get_app_user).returns(OpenStruct.new(appUser: { clients: [{ displayName: random_string, platform: platform, info: { avatarUrl: url } }] })) uid = random_string messages = [ { '_id': random_string, authorId: uid, type: 'text', text: random_string } ] payload = { trigger: 'message:appUser', app: { '_id': @app_id }, version: 'v1.1', messages: messages, appUser: { '_id': random_string, 'conversationStarted': true } }.to_json redis = Redis.new(REDIS_CONFIG) assert_equal 0, redis.llen("smooch:bundle:#{uid}") assert_nil Rails.cache.read("smooch:banned:#{uid}") assert_difference "Dynamic.where(annotation_type: 'smooch_user').count" do assert Bot::Smooch.run(payload) end pm = ProjectMedia.last sm = CheckStateMachine.new(uid) sm.enter_human_mode sm = CheckStateMachine.new(uid) assert_equal 'human_mode', sm.state.value Bot::Smooch.ban_user({ 'authorId' => uid }) assert_not_nil Rails.cache.read("smooch:banned:#{uid}") a = Dynamic.where(annotation_type: 'smooch_user').last assert_not_nil a a.destroy! assert_nil Rails.cache.read("smooch:banned:#{uid}") sm = CheckStateMachine.new(uid) assert_equal 'waiting_for_message', sm.state.value assert_equal 0, redis.llen("smooch:bundle:#{uid}") end Bot::Smooch.stubs(:save_user_information).returns(nil) end test "should detect media type" do Sidekiq::Testing.inline! do # video message = { type: 'file', text: random_string, mediaUrl: @video_url, mediaType: 'image/jpeg', role: 'appUser', received: 1573082583.219, name: random_string, authorId: random_string, '_id': random_string } assert_difference 'ProjectMedia.count' do Bot::Smooch.save_message(message.to_json, @app_id) end message['mediaUrl'] = @video_url_2 assert_raises 'ActiveRecord::RecordInvalid' do Bot::Smooch.save_message(message.to_json, @app_id) end # audio message = { type: 'file', text: random_string, mediaUrl: @audio_url, mediaType: 'image/jpeg', role: 'appUser', received: 1573082583.219, name: random_string, authorId: random_string, '_id': random_string } assert_difference 'ProjectMedia.count' do Bot::Smooch.save_message(message.to_json, @app_id) end message['mediaUrl'] = @audio_url_2 assert_raises 'ActiveRecord::RecordInvalid' do Bot::Smooch.save_message(message.to_json, @app_id) end end end test "should not save larger files" do messages = [ { '_id': random_string, authorId: random_string, type: 'image', text: random_string, mediaUrl: @media_url_3, mediaSize: UploadedImage.max_size + random_number }, { '_id': random_string, authorId: random_string, type: 'file', mediaType: 'image/jpeg', text: random_string, mediaUrl: @media_url_2, mediaSize: UploadedImage.max_size + random_number }, { '_id': random_string, authorId: random_string, type: 'video', mediaType: 'video/mp4', text: random_string, mediaUrl: @video_url, mediaSize: UploadedVideo.max_size + random_number }, { '_id': random_string, authorId: random_string, type: 'audio', mediaType: 'audio/mpeg', text: random_string, mediaUrl: @audio_url, mediaSize: UploadedAudio.max_size + random_number } ] assert_no_difference 'ProjectMedia.count', 0 do assert_no_difference 'Annotation.where(annotation_type: "smooch").count', 0 do messages.each do |message| uid = message[:authorId] message = { trigger: 'message:appUser', app: { '_id': @app_id }, version: 'v1.1', messages: [message], appUser: { '_id': uid, 'conversationStarted': true } }.to_json ignore = { trigger: 'message:appUser', app: { '_id': @app_id }, version: 'v1.1', messages: [ { '_id': random_string, authorId: uid, type: 'text', text: '2' } ], appUser: { '_id': uid, 'conversationStarted': true } }.to_json assert Bot::Smooch.run(message) end end end end test "should not crash if message in payload contains nil name" do messages = [ { '_id': random_string, authorId: random_string, type: 'text', text: random_string, name: nil } ] payload = { trigger: 'message:appUser', app: { '_id': @app_id }, version: 'v1.1', messages: messages, appUser: { '_id': random_string, 'conversationStarted': true } }.to_json assert Bot::Smooch.run(payload) end test "should support message without mediaType" do # video message = { '_id': random_string, authorId: random_string, type: 'file', text: random_string, mediaUrl: @video_url, mediaType: 'video/mp4' }.with_indifferent_access is_supported = Bot::Smooch.supported_message?(message) assert is_supported.slice(:type, :size).all?{ |_k, v| v } message = { '_id': random_string, authorId: random_string, type: 'file', text: random_string, mediaUrl: @video_url, mediaType: 'newtype/ogg' }.with_indifferent_access is_supported = Bot::Smooch.supported_message?(message) assert !is_supported.slice(:type, :size).all?{ |_k, v| v } message = { '_id': random_string, authorId: random_string, type: 'file', text: random_string, mediaUrl: @video_url }.with_indifferent_access is_supported = Bot::Smooch.supported_message?(message) assert is_supported.slice(:type, :size).all?{ |_k, v| v } # audio message = { '_id': random_string, authorId: random_string, type: 'file', text: random_string, mediaUrl: @audio_url, mediaType: 'audio/mpeg' }.with_indifferent_access is_supported = Bot::Smooch.supported_message?(message) assert is_supported.slice(:type, :size).all?{ |_k, v| v } message = { '_id': random_string, authorId: random_string, type: 'file', text: random_string, mediaUrl: @audio_url, mediaType: 'newtype/mp4' }.with_indifferent_access is_supported = Bot::Smooch.supported_message?(message) assert !is_supported.slice(:type, :size).all?{ |_k, v| v } message = { '_id': random_string, authorId: random_string, type: 'file', text: random_string, mediaUrl: @audio_url }.with_indifferent_access is_supported = Bot::Smooch.supported_message?(message) assert is_supported.slice(:type, :size).all?{ |_k, v| v } end test "should perform fuzzy matching on keyword search" do RequestStore.store[:skip_cached_field_update] = false setup_elasticsearch t = create_team pm1 = create_project_media quote: 'A segurança das urnas está provada.', team: t pm2 = create_project_media quote: 'Segurança pública é tema de debate.', team: t [pm1, pm2].each { |pm| publish_report(pm) } sleep 3 # Wait for ElasticSearch to index content [ 'Segurança das urnas', 'Segurança dad urnas', 'Segurança das urna', 'Seguranca das urnas' ].each do |query| assert_equal [pm1.id], Bot::Smooch.search_for_similar_published_fact_checks('text', query, [t.id]).to_a.map(&:id) end assert_equal [], Bot::Smooch.search_for_similar_published_fact_checks('text', 'Segurando', [t.id]).to_a.map(&:id) end test "should get turn.io installation" do @installation.set_turnio_secret = 'secret' @installation.set_turnio_token = 'token' @installation.save! assert_equal @installation, Bot::Smooch.get_turnio_installation('PzqzmGtlarsXrz6xRD7WwI74//n+qDkVkJ0bQhrsib4=', '{"foo":"bar"}') end test "should send message to turn.io user" do @installation.set_turnio_secret = 'test' @installation.set_turnio_phone = 'test' @installation.set_turnio_token = 'token' @installation.save! Bot::Smooch.get_installation('turnio_secret', 'test') WebMock.stub_request(:post, 'https://whatsapp.turn.io/v1/messages').to_return(status: 200, body: '{}') assert_equal 200, Bot::Smooch.turnio_send_message_to_user('test:123456', 'Test').code.to_i WebMock.stub_request(:post, 'https://whatsapp.turn.io/v1/messages').to_return(status: 404, body: '{}') assert_equal 404, Bot::Smooch.turnio_send_message_to_user('test:123456', 'Test 2').code.to_i end test "should resend turn.io message" do WebMock.stub_request(:post, 'https://whatsapp.turn.io/v1/messages').to_return(status: 200, body: '{}') @installation.set_turnio_secret = 'test' @installation.set_turnio_phone = 'test' @installation.set_turnio_token = 'test' @installation.save! Bot::Smooch.get_installation('turnio_secret', 'test') pm = create_project_media team: @team publish_report(pm) Rails.cache.write('smooch:original:987654', { project_media_id: pm.id, fallback_template: 'fact_check_report_text_only', language: 'en', query_date: Time.now.to_i }.to_json) payload = { statuses: [{ id: '987654', recipient_id: '123456', status: 'failed', timestamp: Time.now.to_i.to_s }]} assert Bot::Smooch.run(payload.to_json) end test "should send media message to turn.io user" do @installation.set_turnio_secret = 'test' @installation.set_turnio_phone = 'test' @installation.set_turnio_token = 'token' @installation.save! Bot::Smooch.get_installation('turnio_secret', 'test') WebMock.stub_request(:post, 'https://whatsapp.turn.io/v1/messages').to_return(status: 200, body: '{}') WebMock.stub_request(:post, 'https://whatsapp.turn.io/v1/media').to_return(status: 200, body: { media: [{ id: random_string }] }.to_json) url = random_url WebMock.stub_request(:get, url).to_return(status: 200, body: File.read(File.join(Rails.root, 'test', 'data', 'rails.png'))) assert_not_nil Bot::Smooch.turnio_send_message_to_user('test:123456', 'Test', { 'type' => 'image', 'mediaUrl' => url }) end end
# Curve25519+ECDH implementation in Ruby # Disclaimer: This code is for learning purposes ONLY. It is NOT secure. # Tanner Prynn require 'SecureRandom' require 'digest' # Fast Modular Exponentiation (base**exp % mod) def modexp(base, exp, mod) prod = 1 base = base % mod until exp.zero? exp.odd? and prod = (prod * base) % mod exp >>= 1 base = (base * base) % mod end prod end # Extended Euclidean Algorithm def egcd(a, b) if a == 0 return b, 0, 1 else g, y, x = egcd(b % a, a) return g, (x - (b / a) * y), y end end # Modular Inverse (a**-1 mod m) def modinv(a, m) if a < 0 return modinv(a % m, m) end g, x, y = egcd(a, m) if g != 1 fail 'modular inverse does not exist' else return x % m end end module Curve25519 # Spec: http://cr.yp.to/ecdh/curve25519-20060209.pdf # Group Operations: https://hyperelliptic.org/EFD/g1p/auto-montgom.html # Curve25519 is an EC curve in Montgomery form: # b*y^2 = x^3 + a*x^2 + x P = 2**255 - 19 A = 486662 B = 1 class Point attr_reader :x attr_reader :y def initialize(x, y) if !(x == 0 && y == 1) raise "Invalid Point" unless (Curve25519::B * y**2) % Curve25519::P == (x**3 + Curve25519::A * x**2 + x) % Curve25519::P end @x = x % Curve25519::P @y = y % Curve25519::P end def ==(o) return o.class == self.class && o.x == @x && o.y == @y end def -@ if self.infty? return self else return Curve25519::Point.new(@x, -@y) end end def infty? return self == Curve25519::Inf end def add(o) return Curve25519.add(self, o) end def double return Curve25519.double(self) end def mult(n) return Curve25519.mult(n, self) end end # homogenous form b*y^2*z = x^3 + a*x^2*z + x*z^2 # z = 0 -> x^3 = 0 -> x = 0 # => point at infinity is (0,1,0) # we can use (0,1) in affine coords, because it is not on the curve Inf = Point.new(0, 1) # Base point specified by Bernstein Base = Point.new(9, 14781619447589544791020593568409986887264606134616475288964881837755586237401) def Curve25519.add(p1, p2) if p1.infty? return p2 elsif p2.infty? return p1 elsif p1 == p2 return Curve25519.double(p1) elsif p1.x == p2.x && p1.y != p2.y return Curve25519::Inf end x1 = p1.x y1 = p1.y x2 = p2.x y2 = p2.y # x3 = b*(y2-y1)^2/(x2-x1)^2-a-x1-x2 n = (B*modexp(y2-y1, 2, P)) % P d = modinv(modexp(x2-x1, 2, P), P) x3 = ((n * d) - A - x1 - x2) % P # y3 = (2*x1+x2+a)*(y2-y1)/(x2-x1)-b*(y2-y1)^3/(x2-x1)^3-y1 t1 = (((2*x1) + x2 + A) * (y2 - y1) * modinv(x2-x1, P)) % P t2 = (B * modexp(y2 - y1, 3, P) * modexp(modinv(x2-x1, P), 3, P)) % P y3 = (t1 - t2 - y1) % P return Point.new(x3, y3) end def Curve25519.double(p1) if p1.infty? return Curve25519::Inf end x1 = p1.x y1 = p1.y # x3 = b*(3*x1^2+2*a*x1+1)^2/(2*b*y1)^2-a-x1-x1 n = (B * modexp(3*modexp(x1, 2, P) + 2*A*x1 + 1, 2, P)) % P d = modinv(modexp(2 * B * y1, 2, P), P) x3 = n*d - A - x1 - x1 % P # y3 = (2*x1+x1+a)*(3*x1^2+2*a*x1+1)/(2*b*y1)-b*(3*x1^2+2*a*x1+1)^3/(2*b*y1)^3-y1 n1 = ((2*x1 + x1 + A)*(3*modexp(x1, 2, P) + 2*A*x1 + 1)) % P d1 = modinv(2*B*y1, P) n2 = (B*modexp(3*modexp(x1, 2, P) + 2*A*x1 + 1, 3, P)) % P d2 = modinv(modexp(2*B*y1, 3, P), P) y3 = n1*d1 - n2*d2 - y1 return Point.new(x3, y3) end def Curve25519.mult(n, p1) # See http://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Point_multiplication # This multiplication is vulnerable to timing/power analysis! # Secure ec multiplication uses the Montgomery ladder which works in fixed-time p3 = Curve25519::Inf n.to_s(2).split("").each do |bit| p3 = p3.double if bit == "1" p3 = p3.add(p1) end end return p3 end end module ECDH class User attr_reader :name attr_reader :public_key attr_reader :keys def initialize(name = nil, secret = nil) @name = name @keys = Hash.new if secret @secret = secret % Curve25519::P else secret = SecureRandom.random_bytes(32) # Curve 25519 secret clamping function secret[0] = (secret[0].ord & 0b01111111).chr secret[0] = (secret[0].ord | 0b01000000).chr secret[31] = (secret[31].ord & 0b11111000).chr @secret = secret.unpack("H*")[0].to_i(16) end @public_key = Curve25519::Base.mult(@secret) end def negotiate(other, initial_negotiation = true) if initial_negotiation other.negotiate(self, false) end shared = other.public_key.mult(@secret) # Bernstein uses Salsa20 as his hash # We'll just stick with sha256 since it's built in hash = Digest::SHA256.new hash << shared.x.to_s(16) @keys[other.name] = hash.digest return nil end end end if __FILE__ == $PROGRAM_NAME # Create ECDH users alice and bob a = ECDH::User.new('alice') b = ECDH::User.new('bob') # alice initiates DH exchange with bob a.negotiate(b) # alice and bob now have a shared secret key fail "keys don't match" unless a.keys['bob'] == b.keys['alice'] p "Success!" end
# -*- encoding: utf-8 -*- require 'yaml' module TTYCoke class Config include TTYCoke::Log def initialize(config_file=ENV['HOME'] + "/.ttycokerc") log_rescue(self, __method__, caller, TTYCoke::Errors::YamlSyntaxError) { @files = { init: config_file, tty_coke: File.dirname(__FILE__) + '/../../config/config.yaml' } raw_yaml = YAML::load(File.open(File.expand_path(file))) paths = raw_yaml.fetch('import') importer = File.dirname(file) @config = TTYCoke::Import.import(raw_yaml, paths, {}, importer) } end def find_program prgm if @config.keys.include?(prgm) @config.fetch(prgm) else false end end def file log_rescue(self, __method__, caller) { if FileTest.exist?(@files.fetch(:init)) @files.fetch(:init) else @files.fetch(:tty_coke) end } end end end
class Socat < Formula homepage "http://www.dest-unreach.org/socat/" url "http://www.dest-unreach.org/socat/download/socat-1.7.3.0.tar.gz" sha1 "c09ec6539647cebe8fccdfcf0f1ace1243231ec3" bottle do cellar :any sha1 "1dbd28a373b01b68aa18882f27a4ad82a75cdcd6" => :yosemite sha1 "af4f37fa4ac0083200f6ede2e740a35b69decc0e" => :mavericks sha1 "1e756f77d2956ceea9ea454d62ef1ae58e90d1ad" => :mountain_lion end depends_on 'readline' depends_on 'openssl' def install ENV.enable_warnings # -w causes build to fail system "./configure", "--prefix=#{prefix}", "--mandir=#{man}" system "make install" end end
require_relative '../test_helper' class ClientTest < Minitest::Test include TestHelpers def test_it_creates_client_with_correct_attributes create_payloads(1) client = Client.find(1) assert_equal "jumpstartlab0", client.identifier assert_equal "http://jumpstartlab.com0", client.root_url end def test_all_through_client_relationships create_payloads(1) client = Client.find(1) assert_equal 1, client.urls.count assert_equal 1, client.referrers.count assert_equal 1, client.request_types.count assert_equal 1, client.requested_ats.count assert_equal 1, client.user_agents.count assert_equal 1, client.responded_ins.count assert_equal 1, client.parameters.count assert_equal 1, client.ips.count assert_equal 1, client.resolutions.count assert_equal 1, client.event_names.count end def test_it_finds_most_frequent_request_type create_payloads(1) PayloadRequest.find_or_create_by({ :url => Url.create(name: "http://test.com"), :referrer => Referrer.create(name: "http://test.com"), :request_type => RequestType.find(1), :requested_at => RequestedAt.create(time: "test"), :event_name => EventName.create(name: "test"), :user_agent => PayloadUserAgent.create(browser: "test", platform: "test"), :responded_in => RespondedIn.create(time: 27), :parameter => Parameter.create(list: "[]"), :ip => Ip.create(value: "127.0.0.1"), :resolution => Resolution.create(width: "1920", height: "1280"), :client => Client.find(1) }) client = Client.find(1) assert_equal 2, client.counts_request_type_max assert_equal ["GET 0"], client.most_frequent_request_type end def test_it_handles_most_frequent_request_type_when_there_is_a_tie create_payloads(1) PayloadRequest.find_or_create_by({ :url => Url.create(name: "http://test.com"), :referrer => Referrer.create(name: "http://test.com"), :request_type => RequestType.create(verb: "POST 0"), :requested_at => RequestedAt.create(time: "test"), :event_name => EventName.create(name: "test"), :user_agent => PayloadUserAgent.create(browser: "test", platform: "test"), :responded_in => RespondedIn.create(time: 27), :parameter => Parameter.create(list: "[]"), :ip => Ip.create(value: "127.0.0.1"), :resolution => Resolution.create(width: "1920", height: "1280"), :client => Client.find(1) }) client = Client.find(1) assert client.most_frequent_request_type.include?("POST 0") assert client.most_frequent_request_type.include?("GET 0") end def test_urls_get_returned_in_order_by_count_for_one create_payloads(1) client = Client.find(1) assert_equal "http://jumpstartlab.com/blog0", client.order_urls_by_count[0].name end def test_urls_get_returned_in_order_by_count_for_multiple create_payloads(1) PayloadRequest.find_or_create_by({ :url => Url.create(name: "http://test.com"), :referrer => Referrer.create(name: "http://test.com"), :request_type => RequestType.find(1), :requested_at => RequestedAt.create(time: "test"), :event_name => EventName.create(name: "test"), :user_agent => PayloadUserAgent.create(browser: "test", platform: "test"), :responded_in => RespondedIn.create(time: 27), :parameter => Parameter.create(list: "[]"), :ip => Ip.create(value: "127.0.0.1"), :resolution => Resolution.create(width: "1920", height: "1280"), :client => Client.find(1) }) client = Client.find(1) assert client.order_urls_by_count[1].name.include?("http://test.com") assert client.order_urls_by_count[0].name.include?("http://jumpstartlab.com/blog0") end def test_it_calculates_response_analytics create_payloads(1) PayloadRequest.find_or_create_by({ :url => Url.create(name: "http://test.com"), :referrer => Referrer.create(name: "http://test.com"), :request_type => RequestType.find(1), :requested_at => RequestedAt.create(time: "test"), :event_name => EventName.create(name: "test"), :user_agent => PayloadUserAgent.create(browser: "test", platform: "test"), :responded_in => RespondedIn.create(time: 28), :parameter => Parameter.create(list: "[]"), :ip => Ip.create(value: "127.0.0.1"), :resolution => Resolution.create(width: "1920", height: "1280"), :client => Client.find(1) }) client = Client.find(1) assert_equal 14, client.responded_ins.average_response_time assert_equal 28, client.responded_ins.max_response_time assert_equal 0, client.responded_ins.min_response_time end def test_it_finds_matching_payloads create_payloads(1) PayloadRequest.find_or_create_by({ :url => Url.find(1), :referrer => Referrer.find(1), :request_type => RequestType.find(1), :requested_at => RequestedAt.find(1), :event_name => EventName.find(1), :user_agent => PayloadUserAgent.find(1), :responded_in => RespondedIn.find(1), :parameter => Parameter.find(1), :ip => Ip.create(value: "127.0.0.1"), :resolution => Resolution.find(1), :client => Client.find(1) }) client = Client.find(1) assert_equal 2, client.find_matching_payloads("socialLogin0").count assert_equal 0, client.find_matching_payloads("test").count end def test_it_can_breakdown_by_hour create_payloads(1) client = Client.find(1) assert_equal 24, client.breakdown_by_hour("socialLogin 0").count end def test_it_can_breakdown_by_hour_with_two_payloads create_payloads(1) PayloadRequest.find_or_create_by({ :url => Url.find(1), :referrer => Referrer.find(1), :request_type => RequestType.find(1), :requested_at => RequestedAt.create(time: "2013-02-16 22:38:28 -0700"), :event_name => EventName.find(1), :user_agent => PayloadUserAgent.find(1), :responded_in => RespondedIn.find(1), :parameter => Parameter.find(1), :ip => Ip.create(value: "127.0.0.1"), :resolution => Resolution.find(1), :client => Client.find(1) }) client = Client.find(1) assert_equal Array, client.breakdown_by_hour("socialLogin 0")[0][1].class assert_equal 24, client.breakdown_by_hour("socialLogin 6").count end end
require 'spec_helper' describe "Prism Type requests" do describe "GET unpublished /prism_type" do it "should return a 404" do p = PrismType.make!(:published => false) get prism_type_path(p) assert_response :missing end end describe "GET published /prism_type" do it "should return a valid page" do p = PrismType.make! get prism_type_path(p) assert_response :success end end end
# encoding: UTF-8 # Copyright 2011-2013 innoQ Deutschland GmbH # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require File.join(File.expand_path(File.dirname(__FILE__)), '../test_helper') class RdfSyncTest < ActiveSupport::TestCase setup do @rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' @skos = 'http://www.w3.org/2004/02/skos/core#' @base_url = 'http://example.com/' @target_host = 'http://example.org/sesame/repositories/test' @username = 'johndoe' class FakeViewContext # XXX: does not belong here def iqvoc_default_rdf_namespaces return Iqvoc.rdf_namespaces end end @view_context = FakeViewContext.new @sync = RdfSyncService.new(@base_url, @target_host, username: @username, view_context: @view_context) @concepts = 1.upto(15).map do |i| Concept::SKOS::Base.new.publish.tap { |c| c.save } end # HTTP request mocking @observers = [] # one per request WebMock.disable_net_connect! WebMock.stub_request(:any, /.*example.org.*/).with do |req| # not using WebMock's custom assertions as those didn't seem to provide # sufficient flexibility fn = @observers.shift raise(TypeError, "missing request observer: #{req.inspect}") unless fn fn.call(req) true end.to_return do |req| { status: 204 } end end teardown do WebMock.reset! WebMock.allow_net_connect! raise(TypeError, 'unhandled request observer') unless @observers.length == 0 end test 'serialization' do concept = @concepts[0] assert @sync.serialize(concept).include?(<<-EOS.strip) <#{@base_url}#{concept.origin}> <#{@rdf}type> <#{@skos}Concept> . EOS end test 'single-batch synchronization' do concepts = @concepts[0..4] @observers << lambda do |req| concepts.each do |concept| assert_equal :delete, req.method end end @observers << lambda do |req| concepts.each do |concept| assert_equal :post, req.method graph_uri = @base_url + concept.origin assert req.body.include?("<#{graph_uri}> {") end end res = @sync.sync(concepts) end test 'full synchronization' do concepts = Iqvoc::Concept.base_class.published.unsynced assert_not_equal 0, concepts.count assert_not_equal 0, concepts.where(rdf_updated_at: nil).count 2.times do # 2 requests (reset + insert) per batch @observers << lambda { |req| } # no need to check details here end assert @sync.all assert_equal 0, concepts.where(rdf_updated_at: nil).count end test 'request batches' do concepts = Iqvoc::Concept.base_class.published.unsynced concept_count = concepts.count batch_count = 3 sync = RdfSyncService.new(@base_url, @target_host, username: @username, batch_size: (concept_count / batch_count).ceil, view_context: @view_context) (2 * batch_count).times do # 2 requests (reset + insert) per batch @observers << lambda { |req| } # no need to check details here end assert sync.all end end
require 'test_helper' class DecimalConverterTest < ActiveSupport::TestCase test 'decimal_to_sexagesimal should return sexagesimal with reverse' do res = DecimalConverter.decimal_to_sexagesimal(666) assert_equal '6b', res end test 'sexagesimal_to_decimal should return decimal' do res = DecimalConverter.sexagesimal_to_decimal('6b') assert_equal 666, res end test 'sexagesimal_to_decimal with wrong params' do res = DecimalConverter.sexagesimal_to_decimal('aOc') assert_nil res end end
class ProjectsController < ApplicationController before_action :find_project, only: [:show, :edit, :update, :destroy, :complete, :started, :stopped] def index @projects= Project.all.order("created_at DESC") end def new @project = Project.new end def create @project=Project.new(project_params) @project.update_attribute(:w0_started_at, Time.now) @project.update_attribute(:w0_stopped_at, Time.now) if @project.save redirect_to root_path else puts(@project.errors.full_messages) render 'new' end end def show @project = Project.find(params[:id]) @kunde = Kunden.find(@project.kunden_id) #@kunden = Kunden.all.collect{|d| [d.firma, d.id ]} #@kunden = Kunden.find(params[:kunden_id]) end def edit end def update if @project.update(project_params) redirect_to project_path(@project) else #puts(@project.errors.full_messages) render'edit' end end def destroy @project.destroy puts(@project.errors.full_messages) redirect_to root_path end def complete @project.update_attribute(:completed_at, Time.now) redirect_to root_path end def started @project.update_attribute(:w0_started_at, Time.now) redirect_to project_path end def stopped @project.update_attribute(:w0_stopped_at, Time.now) redirect_to project_path end private def project_params params.require(:project).permit(:title,:description,:noInt,:noExt,:workTodo, :created_at, :updated_at, :completed_at, :workTodo1,:workTodo2, :workTodo3, :workTodo4, :w0_started_at, :w0_stopped_at, :work, :work1, :work2, :work3, :work4, :bearbeiter, :liefTermn, :warEing, :ext, :ext1, :ext2, :ext3, :ansprech, :kunde, :befund, :zukauf, :kunden_id) end def find_project @project = Project.find(params[:id]) end end
module DeployIt module Configurators class Rails attr_reader :project def initialize(project) @project = project end def to_hash { postgresql: { password: { postgres: project.db_admin_password } }, "deploy-it" => { database: { database: project.database_name, username: project.database_username, password: project.database_password, adapter: project.database_adapter, host: project.machine_with_role(RailsRole::DATABASE).ip }, rails: { host: project.machine_with_role(RailsRole::APPLICATION).ip, secret: project.secret }, path: "/srv/app-#{project.id}", repo_url: project.repo_url, port: project.port, }, } end end end end
class Session < ApplicationRecord validates :username, :password, presence: true end
require 'rails_helper' RSpec.describe 'Book Index Page', type: :feature do describe 'as a visitor visiting the books index page' do before :each do @book_1 = Book.create!(title: "The Hobbit") @book_2 = Book.create!(title: "Fun & Games") end it 'shows all book titles in the database, and each title is a link to a show page' do visit books_path expect(page).to have_link(@book_1.title) expect(page).to have_link(@book_2.title) end end end
module AccountsHelper def admin_link_to_account(account) link_to(admin_account_path(account.id)) { account_with_avatar(account) } end def account_with_avatar(account) safe_join([ avatar_for(account), content_tag(:span, account, class: 'text-bold') ], ' ') end def hero_tldr_roles(heroes) roles = heroes.map(&:role) role_counts = {} roles.each do |role| role_counts[role] ||= 0 role_counts[role] += 1 end role_counts = role_counts.sort_by { |role, count| -count }.to_h role_counts.keys.map(&:to_s) end def heroes_tldr(heroes) roles = hero_tldr_roles(heroes).map { |role| Hero.pretty_role(role) } roles.take(3).join(' / ') end def avatar_for(account, classes: '') return unless account.avatar_url classes += ' avatar' image_tag(account.avatar_url, class: classes, width: 20) end def platform_options Account::VALID_PLATFORMS.map { |key, label| [label, key] } end def account_switcher(selected_account, classes: '') render partial: 'accounts/account_switcher', locals: { selected_account: selected_account, classes: classes } end def account_switcher_url(account) if params[:controller] == 'trends' if params[:season] trends_path(params[:season], account) else all_seasons_trends_path(account) end else url_with(battletag: account.to_param) end end def accounts @accounts ||= if signed_in? current_user.accounts.order_by_battletag else [] end end def default_account_account_options accounts.map do |account| [account.battletag, account.to_param] end end end
class CheetahFactorRankingsController < ApplicationController include Navigation::PathGeneration helper FactorRating layout "quiz" def first_custom program = Program.find_by(slug: params[:program_id]) section = Section.find_by(slug: params[:section_id]) factors = current_user.rateable_custom_cheetah_factors if factors.empty? redirect_to full_step_path(section.section_steps.last) else redirect_to program_phase_section_cheetah_factor_ranking_path(program, section.phase, section, factors.first, :custom_factors => true) end end def show @program = Program.find_by(slug: params[:program_id]) @section = Section.find_by(slug: params[:section_id]) @cheetah_factor = CheetahFactor.find(params[:id]) @response_option = @cheetah_factor.response_option @cheetah_factor_ranking = current_user.cheetah_factor_rankings.find_or_create_by(cheetah_factor_id: @cheetah_factor.id) if params[:custom_factors] == "true" user_factors = current_user.rateable_custom_cheetah_factors else user_factors = current_user.rateable_non_custom_cheetah_factors end current_index = user_factors.index(@cheetah_factor) @next_selection = user_factors[current_index+1] if current_index < user_factors.length-1 @previous_selection = user_factors[current_index-1] if current_index > 0 @percent_complete = (( current_index+1).to_f / user_factors.count) * 100 -1 end def create @cheetah_factor = CheetahFactor.find(params[:id]) @cheetah_factor_ranking = current_user.cheetah_factor_rankings.find_by(cheetah_factor_id: @cheetah_factor.id) if params[:repeat] == "true" @cheetah_factor_ranking.final_rating = params[:rating] else @cheetah_factor_ranking.original_rating = params[:rating] end if @cheetah_factor_ranking.save render json: @cheetah_factor_ranking else render json: {message: "Unable to save rating"} end end end
require 'digest/md5' class Profile < ActiveRecord::Base has_many :measurements, :order => 'created_at ASC' before_validation :generate_md5 before_save :generate_statistics validates_uniqueness_of :md5 default_scope where(:included => true) scope :average_accuracy_top, lambda{|qty| where('average_accuracy > 0').order('average_accuracy ASC').limit(qty) } scope :best_accuracy_top, lambda{|qty| where('best_accuracy > 0').order('best_accuracy ASC').limit(qty) } scope :popular_top, lambda{|qty| order("measurements_count DESC").limit(qty) } def self.generate_md5(model, operating_system, version, carrier) Digest::MD5.hexdigest("#{model}#{operating_system}#{version}#{carrier}") end def generate_md5 self.md5 = Profile.generate_md5(attributes['model'], attributes['operating_system'], attributes['version'], attributes['carrier']) end def generate_statistics self.average_accuracy = (measurements.average(:accuracy) || 0) self.best_accuracy = (measurements.minimum(:accuracy) || 0) end def to_s "#{model} on #{operating_system} #{version}#{carrier ? 'on ' + carrier : nil}" end def carrier attributes['carrier'] == 'unknown' ? nil : attributes['carrier'] end def devices_count measurements.count('uid', :distinct => true) end def exclude! self.update_attribute(:included, false) end def average_accuracy_as_integer average_accuracy.to_i end def unitize(attribute) unit_of_measure = case attribute.to_sym when :average_accuracy, :average_accuracy_as_integer, :best_accuracy "m" when :measurements_count " measurements" else '' end "#{self.send(attribute)}#{unit_of_measure}" end end
require 'json' require_relative '../logging' class Xamarin extend Logging @XAMARIN_ANDROID_GUID = "{EFBA0AD7-5A72-4C68-AF49-83D382785DCF}"; @XAMARIN_IOS_GUID = "{FEACFBD2-3405-455C-9665-78FE426C6842}"; def self.scan(path) results = [] # Must have csproj containing Xamarin Android or iOS project guid android_projects = find(@XAMARIN_ANDROID_GUID, path) results.push(*self.analyze(android_projects, "android")) ios_projects = find(@XAMARIN_IOS_GUID, path) results.push(*self.analyze(ios_projects, "ios")) return results end def self.find(needle, path) projects = `find #{path} -name "*.csproj" -o -name '*.fsproj' -o -name '*.sln' | xargs grep -il "#{needle}"`.split(/\n/) return projects end def self.analyze(project_files, target_os) projects = [] project_files.each do |project_file| configuration = XamarinConfiguration.new("Xamarin", project_file, target_os) projects << configuration end return projects end end class XamarinConfiguration def initialize(type, project_file, target_os) @type = type @project_file = project_file @target_os = target_os end end
class Api::V1::CharactersController < ApplicationController film = Film.new def index characters = Character.all render json: characters, status: 200 end def create character = Character.new( name: character_params[:name], actor: character_params[:actor], film: character_params[:film], ) if character.save render json: film, status: 200 else render json: {error: "Error creating character."} end end def show character = Character.find_by(id: params[:id]) if character render json: character, status: 200 else render json: {error: "Character not found."} end private def character_params params.require(:character).permit([ :name, :actor, :film ]) end end end #irb(main):001:0> c = Character.new(name: "Gandalf", actor: "Ian McKellen", film: "The Lord of the Rings Trilogy")
require "setup" require "cubic/workers/base" class TestBaseWorker < Minitest::Test def setup @worker = Cubic::Workers::Base.new end def test_rehearal result = nil @worker.rehearsal do result = 1 end assert_equal 1, result end def test_log_error out, _ = capture_subprocess_io do @worker.log_error "logmsg_err" end assert_match "logmsg_err", out end def test_log_info out, _ = capture_subprocess_io do @worker.log_info "logmsg_info" end assert_match "logmsg_info", out end def test_shutdown assert_equal nil, @worker.shutdown? end def test_shutdown_after_call_shutdown @worker.shutdown! assert_equal true, @worker.shutdown? end end
require 'rails_helper' RSpec.describe PollsHelper, type: :helper do describe '#poll_date' do let!(:nimp) { 'test' } let!(:time) { Time.zone.now } it 'shall give unchanged expr' do expect(helper.poll_date(nimp)).to eq(nimp) end it 'shall transate a date' do expect(helper.poll_date(time)).to eq(I18n.l(time, format: '%a %d %b')) end end describe '#poll_datetime' do let!(:nimp) { 'test' } let!(:time) { Time.zone.now } it 'shall give unchanged expr' do expect(helper.poll_datetime(nimp)).to eq(nimp) end it 'shall transate a date' do expect(helper.poll_datetime(time)).to eq( I18n.l(time, format: '%a %d %b | %H:%M') ) end end describe '#answers_list' do let!(:poll_date) { create(:poll_date_with_answers) } let!(:poll_opinion) { create(:poll_opinion_with_answers) } it 'shall give a PollOpinion tag' do expect(helper.answers_list(poll_opinion)).to include( poll_opinion.answers.first.answer_label ) end it 'shall give a PollDate tag' do expect(helper.answers_list(poll_date).to_s).to include( helper.poll_datetime(poll_date.answers.first.date_answer) ) end end describe '#panel_question' do let!(:poll_date) { create(:poll_date_with_answers) } let!(:poll_opinion) { create(:poll_opinion_with_answers) } it 'shall give a panel question to poll date' do expect(helper.panel_question(poll_date)).to include( poll_date.question ) expect(helper.panel_question(poll_date)).to include('info') end it 'shall give a panel question to poll opinion' do expect(helper.panel_question(poll_opinion)).to include( poll_opinion.question ) expect(helper.panel_question(poll_opinion)).to include('warning') end end end
require_relative 'compare-sort' require 'rspec' describe "ValidateData" do it "raises no error if data is array" do expect { ValidateData.run([]) }.not_to raise_error end it "raises an error if data is not an array" do expect { ValidateData.run({}) }.to raise_error end it "raises an error if data is not ALL numbers or strings" do expect { ValidateData.run(["a", 1]) }.to raise_error end it "does not raise an error if data IS all numbers" do expect { ValidateData.run([1, 2, 3]) }.not_to raise_error end it "does not raise an error if data is all strings" do expect { ValidateData.run(["a", "b", "c"]) }.not_to raise_error end end describe "BubbleSort"do it "sorts numbers correctly" do data = (1..10).to_a expect(BubbleSort.run(data.shuffle)).to eq(data) end it "sorts strings correctly" do data = ("a".."z").to_a expect(BubbleSort.run(data.shuffle)).to eq(data) end it "when passed an empty array, it returns an empty array" do expect(BubbleSort.run([])).to eq([]) end it "when passed an array with one element, it returns it" do expect(BubbleSort.run([1])).to eq([1]) end end describe "ModifiedBubbleSort"do it "sorts correctly" do data = (1..10).to_a expect(ModifiedBubbleSort.run(data.shuffle)).to eq(data) end it "sorts strings correctly" do data = ("a".."z").to_a expect(ModifiedBubbleSort.run(data.shuffle)).to eq(data) end it "when passed an empty array, it returns an empty array" do expect(ModifiedBubbleSort.run([])).to eq([]) end it "when passed an array with one element, it returns it" do expect(ModifiedBubbleSort.run([1])).to eq([1]) end end describe "SelectionSort"do it "sorts correctly" do data = (1..10).to_a expect(SelectionSort.run(data.shuffle)).to eq(data) end it "sorts strings correctly" do data = ("a".."z").to_a expect(SelectionSort.run(data.shuffle)).to eq(data) end it "when passed an empty array, it returns an empty array" do expect(SelectionSort.run([])).to eq([]) end it "when passed an array with one element, it returns it" do expect(SelectionSort.run([1])).to eq([1]) end end describe "InsertionSort"do it "sorts correctly" do data = (1..10).to_a expect(InsertionSort.run(data.shuffle)).to eq(data) end it "sorts strings correctly" do data = ("a".."z").to_a expect(InsertionSort.run(data.shuffle)).to eq(data) end it "when passed an empty array, it returns an empty array" do expect(InsertionSort.run([])).to eq([]) end it "when passed an array with one element, it returns it" do expect(InsertionSort.run([1])).to eq([1]) end end describe "MergeSort"do it "sorts correctly" do data = (1..10).to_a expect(MergeSort.run(data.shuffle)).to eq(data) end it "sorts strings correctly" do data = ("a".."z").to_a expect(MergeSort.run(data.shuffle)).to eq(data) end it "when passed an empty array, it returns an empty array" do expect(MergeSort.run([])).to eq([]) end it "when passed an array with one element, it returns it" do expect(MergeSort.run([1])).to eq([1]) end end describe "QuickSort"do it "sorts correctly" do data = (1..10).to_a expect(QuickSort.run(data.shuffle)).to eq(data) end it "sorts strings correctly" do data = ("a".."z").to_a expect(QuickSort.run(data.shuffle)).to eq(data) end it "when passed an empty array, it returns an empty array" do expect(QuickSort.run([])).to eq([]) end it "when passed an array with one element, it returns it" do expect(QuickSort.run([1])).to eq([1]) end end describe "HeapSort" do it "sorts correctly" do data = (1..10).to_a expect(HeapSort.run(data.shuffle)).to eq(data) end it "sorts strings correctly" do data = ("a".."z").to_a expect(HeapSort.run(data.shuffle)).to eq(data) end it "when passed an empty array, it returns an empty array" do expect(HeapSort.run([])).to eq([]) end it "when passed an array with one element, it returns it" do expect(HeapSort.run([1])).to eq([1]) end end describe "CompareSort"do it "bubble sorts correctly" do data = (1..10).to_a info = { data: data.shuffle, sorting_method: "BubbleSort" } expect(CompareSort.run(info)).to eq(data) end it "modified bubble sorts correctly" do data = (1..10).to_a info = { data: data.shuffle, sorting_method: "ModifiedBubbleSort" } expect(CompareSort.run(info)).to eq(data) end it "merge sorts correctly" do data = (1..10).to_a info = { data: data.shuffle, sorting_method: "MergeSort" } expect(CompareSort.run(info)).to eq(data) end it "insertion sorts correctly" do data = (1..10).to_a info = { data: data.shuffle, sorting_method: "InsertionSort" } expect(CompareSort.run(info)).to eq(data) end it "selection sorts correctly" do data = (1..10).to_a info = { data: data.shuffle, sorting_method: "SelectionSort" } expect(CompareSort.run(info)).to eq(data) end it "heap sorts correctly" do data = (1..10).to_a info = { data: data.shuffle, sorting_method: "HeapSort" } expect(CompareSort.run(info)).to eq(data) end end
class AddProfileRefToMatches < ActiveRecord::Migration def change add_reference :matches, :profile, index: true end end
module Calypso module GithubClient module ProjectsAPI def projects fetch(projects_url) end def project(name) projects.select { |p| p['name'] == name }.first end def project_issues(project_name:, column_name: nil, state: 'closed') project = project(project_name) column = column_name ? column(project, column_name) : nil issues_ids = project_carts_issue_ids(project: project, column: column) issues(state: state).select do |issue| issues_ids.include?(issue['number']) end end def no_project_issues(state: 'open') issues_ids = [] projects.each do |project| issues_ids << project_carts_issue_ids(project: project) end issues_ids.flatten! issues(state: state).select do |issue| !issues_ids.include?(issue['number']) end end def project_carts_issue_ids(project:, column: nil) cards(project: project, column: column).map do |card| issue_url = card['content_url'] next if issue_url.nil? issue_url[/http.*[^0-9]([0-9]+)$/, 1].to_i end.compact end def column_cards(project_name:, column_name:) project = project(project_name) column = column(project, column_name) fetch(cards_url(column)) end def drop_cards(cards) cards.each do |card| delete(delete_card_url(card)) end end private def column(project, name) columns(project).select { |c| c['name'] == name }.first end def columns(project) fetch(columns_url(project['id'])) end def cards(project:, column: nil) if column.nil? cards = [] columns(project).each do |col| print "#{col['name']} > " column_cards = cards(project: project, column: col) cards += column_cards end cards else fetch(cards_url(column)) end end def projects_url repos_url('projects') end def columns_url(project_id) api_url(path: "projects/#{project_id}/columns") end def cards_url(column) api_url(path: "projects/columns/#{column['id']}/cards") end def delete_card_url(card) api_url(path: "projects/columns/cards/#{card['id']}") end end end end
class UserTestObserver < ActiveRecord::Observer def after_create(user_test) UserTestMailer.deliver_signup_notification(user_test) end def after_save(user_test) UserTestMailer.deliver_activation(user_test) if user_test.recently_activated? end end
class PhotosController < ApplicationController protect_from_forgery prepend: true before_action :authenticate_admin! before_action :fill_attr, only: [:new, :create] #def index # @photos = Photo.all #end def new end def create if @photo.valid? @photo.save redirect_to collections_path(@collection) else render action: 'new' end end private def fill_attr if params.key?(:photo) @photo = Photo.new(params[:photo].permit(:title, :description, :url)) else @photo = Photo.new end @photo.collection = @collection = Collection.find(Integer(params[:collection_id])) end end
# Definition for a binary tree node. class TreeNode attr_accessor :val, :left, :right def initialize(val = 0, left = nil, right = nil) @val = val @left = left @right = right end end # @param {TreeNode} s # @param {TreeNode} t # @return {Boolean} def is_subtree(s, t) traverse(s,t) end # @param {TreeNode} s # @param {TreeNode} t # @return {Boolean} def equals(s,t) return true if s.nil? && t.nil? return false if t.nil? || s.nil? equals(s.left,t.left) && equals(s.right,t.right) && s.val == t.val end # @param {TreeNode} s # @param {TreeNode} t # @return {Boolean} def traverse(s,t) return false if s.nil? equals(s,t) || is_subtree(s.left,t) || is_subtree(s.right,t) end
# frozen_string_literal: true module Admin class ProductsController < Admin::BaseController # GET /products def index @products = Product.all end # GET /products/1 def show @product = product end # GET /products/new def new render :form, locals: { product: Product.new, method: :post, url: admin_products_path } end # GET /products/1/edit def edit render :form, locals: { product: product, method: :put, url: admin_product_path(product) } end # POST /products def create @product = Product.new(product_params) respond_to do |format| if @product.save format.html { redirect_to admin_product_path(@product), notice: 'Product was successfully created.' } else format.html { render :form, locals: { product: @product, url: admin_products_path, method: :post } } end end end # PATCH/PUT /products/1 def update @product = product respond_to do |format| if @product.update(product_params) format.html { redirect_to admin_product_path(@product), notice: 'Product was successfully updated.' } else format.html { render :form, locals: { product: product, method: :put, url: admin_product_path(product) } } end end end # DELETE /products/1 def destroy product.destroy respond_to do |format| format.html { redirect_to admin_products_url, notice: 'Product was successfully destroyed.' } end end private # Use callbacks to share common setup or constraints between actions. def product @product ||= Product.find(params[:id]) end # Only allow a list of trusted parameters through. def product_params params.require(:product).permit(:name, :quantity, :price) end end end
module Retrocalc class StructureTypeJsonPresenter attr_reader :audit_strc_type def initialize(audit_strc_type) @audit_strc_type = audit_strc_type end def as_json { name: audit_strc_type.name, api_name: audit_strc_type.api_name, genus_api_name: audit_strc_type.genus_structure_type.api_name, parent_api_name: audit_strc_type.parent_structure_type.api_name } end end end
# frozen_string_literal: true class NonOccupantsController < ApplicationController def index @q = non_occup_query @pagy, @non_occupants = pagy(@q.result) @house_id = params.dig(:q,:house_id) || params.dig(:house_id) end def update redirect_to houses_path and return unless house_id non_occupant = Person.find(params[:id]) if non_occupant.update(house_id: house_id) redirect_to house_detail_path(id: house_id), notice: 'An occupant was added.' else render :index end end private def non_occup_query Person .where(house_id: nil) .order(last: :asc, first: :asc, middle: :asc) .ransack(params[:q]) end def house_id @house_id ||= existing_house_id end def existing_house_id House.find(house_id_as_UUID_from_params).id rescue ActiveRecord::RecordNotFound nil end def house_id_as_UUID_from_params params[:house_id].match(SharedRegexp::UUID_FORMAT)[0] end end
# What is your name? Some known vampires are in the area, and we can check against the Werewolf Intelligence Bureau database for their aliases. # How old are you? What year were you born? This is to try to trick the vampire, who is likely several hundreds of years old. If an employee gives an age and a year of birth that don’t line up mathematically, that employee might be a vampire. # Our company cafeteria serves garlic bread. Should we order some for you? Vampires hate garlic. Do not even get a vampire started on garlic. Invite a vampire to an Italian restaurant even one time, and you’ll never hear the end of it. # Would you like to enroll in the company’s health insurance? Vampires are immortal, so they certainly don’t need health insurance. applicants = 1 until applicants == 0 puts "How many applicants do we have today?" applicants = gets.chomp.to_i if applicants == 0 puts "Ok! All done!" break elsif applicants != 0 puts "What is your name?" name = gets.chomp.to_s name.downcase if name == "drake cula" && "tu fang" puts "Warning! Definitely a vampire!" else puts "Lovely name! Moving on!" end puts "How old are you and what year were you born?" age = gets.chomp.to_i year = gets.chomp.to_i if age >= 100 || year <= 1916 puts "Woh oh! Seems like a vampire's age to me." elsif age <= 100 && year >= 1916 puts "Sounds good!" else puts "Make sure you are typing your age, hit enter, and then your birth year and hit enter." end puts "Our company cafeteria serves garlic bread. Should we order some for you?" order = gets.chomp if order == "yes" puts "Good...good...yes." else puts "Possible Vampire!" end puts "Would you like to enroll in the company’s health insurance?" insurance = gets.chomp if insurance == "no" puts "A little suspicious as to why you would deny health coverage for a mortal life..." else puts "Cool, I will sign you up!" end puts "What are you allergic to?" allergies = gets.chomp if allergies == "sunshine" && "garlic" puts "Probably a vampire" else puts "If you are finished with our application please type 'complete'." answer = gets.chomp if answer == "complete" puts "Applicant Name: #{name}/Age: #{age} This applicant had said #{order} to edible garlic base substance and #{insurance} to the company's health insurance for mortals. This applicant is allergic to #{allergies}. If you have gotten 2 or more warnings during this applicantion, please consider contacting your local vampire slayer." else puts "Okay restart if you would like!" end end end end print "Actually, never mind! What do these questions have to do with anything? Let's all be friends."
# frozen_string_literal: true Sequel.migration do transaction up do create_table(:foos) do String :name, size: 255 end end end
class CustomSessionsController < Devise::SessionsController def create super flash[:success] = t('.welcome', name: current_user.name) end end
require "rails_helper" RSpec.describe CreditCompaniesController, :type => :routing do describe "routing" do it "routes to #index" do expect(:get => "/credit_companies").to route_to("credit_companies#index") end it "routes to #new" do expect(:get => "/credit_companies/new").to route_to("credit_companies#new") end it "routes to #show" do expect(:get => "/credit_companies/1").to route_to("credit_companies#show", :id => "1") end it "routes to #edit" do expect(:get => "/credit_companies/1/edit").to route_to("credit_companies#edit", :id => "1") end it "routes to #create" do expect(:post => "/credit_companies").to route_to("credit_companies#create") end it "routes to #update" do expect(:put => "/credit_companies/1").to route_to("credit_companies#update", :id => "1") end it "routes to #destroy" do expect(:delete => "/credit_companies/1").to route_to("credit_companies#destroy", :id => "1") end end end
class BookingsController < ApplicationController before_action :set_skill, only: [ :create] def create @booking = Booking.new(booking_params) @booking.skill = @skill @booking.user = current_user if @booking.save redirect_to user_path(current_user) else @user = @skill.user render 'skills/show', skill: @skill, user: @user end end def update @booking = Booking.find(params[:id]) answer = params[:booking][:accepted] if answer == "Accept this booking" @booking.accepted = "Accepted" elsif answer == "Refuse this booking" @booking.accepted = "Refused" else @booking.accepted = "Pending" end @booking.save redirect_to user_path(current_user) end private def booking_params params.require(:booking).permit(:starts_at, :duration, :user_id, :skill_id) end def set_skill @skill = Skill.find(params[:skill_id]) end end
class DNA def initialize(strand) @strand = strand end def hamming_distance(other_strand) effective_length = [@strand.size, other_strand.size].min effective_length.times.count do |idx| @strand[idx] != other_strand[idx] end end end # def hamming_distance(other_strand) # pairs = @strand.chars.zip(other_strand.chars).delete_if { |pair| pair.include?(nil) } # pairs.count { |pair| pair.uniq.size == 2 } # end # def hamming_distance(other_strand) # shorter_strand, longer_strand = [@strand, other_strand].sort_by(&:size) # count = 0 # shorter_strand.chars.each_with_index do |elem, idx| # count += 1 if elem != longer_strand[idx] # end # count # end # def hamming_distance(other_strand) # shorter_strand, longer_strand = [@strand, other_strand].sort_by(&:size) # idx = 0 # shorter_strand.chars.reduce(0) do |count, elem| # count += 1 unless longer_strand[idx] == elem # idx += 1 # count # end # end
require 'hmac-sha2' require 'base64' module Cybersourcery class CybersourceSigner attr_accessor :profile, :signer attr_writer :time attr_writer :form_fields attr_reader :signable_fields IGNORE_FIELDS = %i[ commit utf8 authenticity_token action controller ] def initialize(profile, signer = Signer) @profile = profile @signer = signer @signable_fields = { access_key: @profile.access_key, profile_id: @profile.profile_id, payment_method: @profile.payment_method, locale: @profile.locale, transaction_type: @profile.transaction_type, currency: @profile.currency } end def add_and_sign_fields(params) add_signable_fields(params) signed_fields end def add_signable_fields(params) @signable_fields.merge! params.symbolize_keys.delete_if { |k,v| @profile.unsigned_field_names.include?(k) || IGNORE_FIELDS.include?(k) } end def signed_fields form_fields.tap do |data| signature_keys = data[:signed_field_names].split(',').map(&:to_sym) signature_message = self.class.signature_message(data, signature_keys) data[:signature] = signer.signature(signature_message, profile.secret_key) end end def form_fields @form_fields ||= signable_fields.dup.merge( unsigned_field_names: @profile.unsigned_field_names.join(','), transaction_uuid: SecureRandom.hex(16), reference_number: SecureRandom.hex(16), signed_date_time: time, signed_field_names: nil # make sure it's in data.keys ).tap do |data| data[:signed_field_names] = data.keys.join(',') end end def time @time ||= Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ") end def self.signature_message(hash, keys) keys.map {|key| "#{key}=#{hash.fetch(key)}" }.join(',') end class Signer def self.signature(message, secret_key) mac = HMAC::SHA256.new(secret_key) mac.update message Base64.strict_encode64(mac.digest) end end end end
Grauer::Application.routes.draw do devise_for :users, controllers: { registrations: 'users/registrations' } root 'schools#index' resources :schools, only: [:index, :new, :create] do resources :families, only: [:index, :new, :create, :show, :edit, :update] do resources :children, only: [:new, :create, :edit, :update, :destroy] resources :comments, only: [:create] resources :movements, only: [:new, :create, :destroy] member do get 'enable' get 'disable' end end resources :notifications, only: [:index] resources :lists, only: [:show] resources :evolutions, only: [:index, :create] resources :bills, only: [:index, :new, :create, :destroy, :edit, :update] resources :menus, only: [:index, :create, :update, :destroy] do get :get_menus, on: :collection end end resources :foods, only: [:index, :new, :create, :destroy, :edit, :update] # resources :menus, only: [:index, :create, :update, :destroy] do # get :get_menus, on: :collection # end resources :users, only: [:index] end
# Virus Predictor # I worked on this challenge [by myself, with: Catherine V. ]. # We spent [1.5] hours on this challenge. # EXPLANATION OF require_relative # require_relative allows us to access a file in the same # directory without having to copy the direct code # require looks through ruby gems to see if a certain library is present require_relative 'state_data' class VirusPredictor # assigns attributes of state, population, and population density to an instance of VirusPredictor def initialize(state_of_origin, population_density, population) @state = state_of_origin @population = population @population_density = population_density end # private # calls predicted_deaths and speed_of_spread methods below def virus_effects predicted_deaths speed_of_spread end private #You will not be able to call the predicted_deaths of speed_of)spread methods on an instane of VirusPredictor because they are under the private method and considered private methods. # takes pop., pop. density, and state as arguments and compares them against certain thresholds and generates a number of deaths def predicted_deaths if @population_density >= 200 x = 0.4 elsif @population_density >= 150 x = 0.3 elsif @population_density >= 100 x = 0.2 elsif @population_density >= 50 x = 0.1 else x = 0.05 end number_of_deaths = (@population_density * x).floor print "#{@state} will lose #{number_of_deaths} people in this outbreak" end #a hash adds to the complexity #ORIGINAL POPULATION DENISTY METHOD NOT DRY # predicted deaths is solely based on population density # if @population_density >= 200 # number_of_deaths = (@population * 0.4).floor # elsif @population_density >= 150 # number_of_deaths = (@population * 0.3).floor # elsif @population_density >= 100 # number_of_deaths = (@population * 0.2).floor # elsif @population_density >= 50 # number_of_deaths = (@population * 0.1).floor # else # number_of_deaths = (@population * 0.05).floor # end # generates speed of spread of disease based on certain population densities def speed_of_spread #in months # We are still perfecting our formula here. The speed is also affected # by additional factors we haven't added into this functionality. speed = if @population_density >= 200 0.5 elsif @population_density >= 150 1 elsif @population_density >= 100 1.5 elsif @population_density >= 50 2 else 2.5 end puts " and will spread across the state in #{speed} months.\n\n" end end #======================================================================= # DRIVER CODE # initialize VirusPredictor for each state alabama = VirusPredictor.new("Alabama", STATE_DATA["Alabama"][:population_density], STATE_DATA["Alabama"][:population]) alabama.virus_effects #alabama.predicted_deaths jersey = VirusPredictor.new("New Jersey", STATE_DATA["New Jersey"][:population_density], STATE_DATA["New Jersey"][:population]) jersey.virus_effects california = VirusPredictor.new("California", STATE_DATA["California"][:population_density], STATE_DATA["California"][:population]) california.virus_effects alaska = VirusPredictor.new("Alaska", STATE_DATA["Alaska"][:population_density], STATE_DATA["Alaska"][:population]) alaska.virus_effects STATE_DATA.each do |state, data| current_state = VirusPredictor.new(state, data[:population_density], data[:population]) current_state.virus_effects end #======================================================================= # Reflection Section
class CreateStatisticDailies < ActiveRecord::Migration def change create_table :statistic_dailies do |t| t.float :mu t.integer :tier_id t.integer :division t.integer :matches_played t.integer :mmr t.integer :playlist_id t.string :player_id t.date :stat_date end end end
require 'spec_helper' include OwnTestHelper describe "Beer page" do it "has a link to creating a new beer if user is signed in" do user = FactoryGirl.create :user sign_in username:user.username, password:"Foobar1" visit beers_path expect(page).to have_content "New Beer" end it "no link for creating if not signed in" do visit beers_path expect(page).not_to have_content "New Beer" end describe "creating a new beer" do before :each do user = FactoryGirl.create :user sign_in username:user.username, password:"Foobar1" FactoryGirl.create :brewery, name: "Koff" visit new_beer_path select 'Koff', from:'beer[brewery_id]' end it "creating a new beer with a valid name works" do fill_in 'beer_name', with: 'Olunen' expect{ click_button 'Save' } .to change{ Beer.count }.by 1 expect(current_path).to eq beers_path end it "creating a new beer with invalid name doesn't work" do fill_in 'beer_name', with: '' expect{ click_button 'Save' } .not_to change{ Beer.count } expect(page).to have_content "Name can't be blank" end end end
class Vaccination < ApplicationRecord has_many :baby_vaccinations, dependent: :destroy has_many :babies, through: :baby_vaccinations validates :age, presence: true validates :title, presence: true end
# class Player class Player attr_accessor :name, :token, :won, :moves def initialize(name, token, won) @name = name @token = token @won = won @moves = [] end end
# -*- coding : utf-8 -*- require 'spec_helper' describe Mushikago::Hanamgri::UpdateDomainRequest do shared_examples_for ' a valid request instance for update_domain' do |n, d, o| subject{ Mushikago::Hanamgri::UpdateDomainRequest.new(n, d, o) } it{ should be_kind_of(Mushikago::Http::PostRequest) } its(:path){ should == "/1/hanamgri/domains/#{n}" } its(:domain_name){ should == n } its(:description){ should == d } end test_parameters = [ ['domain_name', 'description', {}], ['name', 'description', {}], ].each do |n, d, o| context ".new(#{n}, #{d}, #{o})" do it_should_behave_like ' a valid request instance for update_domain', n, d, o 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: :reset_session before_action :configure_permitted_parameters, if: :devise_controller? def configure_permitted_parameters devise_parameter_sanitizer.permit(:accept_invitation, keys: [:name]) devise_parameter_sanitizer.permit(:sign_up,keys: [:name]) end def authenticate_inviter! current_user || authenticate_user! end def after_sign_in_path_for(resource) if resource.sign_in_count == 1 and resource.organization == nil new_account_path else root_path end end def after_invite_path_for(*) users_path end private def authorizated_roles (*roles) roles.any? { |role_name| User.roles[role_name] == User.roles[current_user.role] } end end
class Ability include CanCan::Ability def initialize(thisuser) thisuser ||= User.new #guest account if thisuser.has_role? :manager can :manage, :all elsif thisuser.has_role? :participant can :manage, [ Home, Activity, Registration, Agency, Event, Sponsor, Team ] can :manage, thisuser else can :create, User can :read, [ Home, Event] end end end
ENV["RAILS_ENV"] ||= "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' #Getting capybara ready for use #require "capybara/rails" # require "capybara/rails" # require "minitest/rails/capybara" class ActiveSupport::TestCase ActiveRecord::Migration.check_pending! # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests # -- they do not yet inherit this setting fixtures :all # Add more helper methods to be used by all tests here... private def login_as(user) if user.type == "Doctor" session[:doctor_id] = user.id elsif user.type == "Patient" session[:patient_id] = user.id end end end
require 'spec_helper' feature "goal tracking" do #Log in, get to user's show page before(:each) do visit new_user_url sign_up("foo") end feature "creating goals" do let(:current_user) { User.find_by_username("foo") } it "doesn't create goals without a title" do click_button "Add Goal" expect(page).to have_content("Title can't be blank") end it "shows new goals upon creation" do add_goal("Be Awesome") expect(current_user.goals.first.title).to eq("Be Awesome") end it "starts goals as uncompleted" do add_goal("Be Awesome") expect(page).to have_content("In Progress") expect(page).to have_button("Complete") expect(page).not_to have_content("Completed") end it "starts goals as private" do add_goal("Be Awesome") expect(page).to have_content("Private") expect(page).to have_button("Make Public") end it "can complete goals" do add_goal("Be Awesome") click_button("Complete") expect(page).to have_content("Completed") expect(page).not_to have_content("In Progress") expect(page).to have_button("Uncomplete") end it "can make goals public" do add_goal("Be Awesome") click_button("Make Public") expect(page).to have_content("Public") expect(page).to have_button("Make Private") end it "can uncomplete goals" do add_goal("Be Awesome") click_button("Complete") click_button("Uncomplete") expect(page).to have_content("In Progress") expect(page).to have_button("Complete") expect(page).not_to have_content("Completed") end it "can make goals public" do add_goal("Be Awesome") click_button("Make Public") click_button("Make Private") expect(page).to have_content("Private") expect(page).to have_button("Make Public") end it "can have multiple goals" do add_goal("Be Awesome") add_goal("Have Multiple Goals") expect(page).to have_content("Be Awesome") expect(page).to have_content("Have Multiple Goals") end end feature "viewing others' goals" do before(:each) do add_goal("Be Awesome") click_button("Make Public") add_goal("Be Private") switch_user("bar") visit user_url(User.find_by_username("foo")) end let(:current_user) { User.find_by_username("bar") } it "can view others' public goals" do expect(page).to have_content("Be Awesome") end it "can't view others' private goals" do expect(page).not_to have_content("Be Private") end it "can't create goals on others' pages" do expect(page).not_to have_button("Add Goal") end it "can't affect status of goals on others' pages" do expect(page).not_to have_button("Make Private") expect(page).not_to have_button("Make Public") expect(page).not_to have_button("Complete") expect(page).not_to have_button("Uncomplete") end it "can't see own goals on others' pages" do visit user_url(current_user) add_goal("Be Yourself") visit user_url(User.find_by_username("foo")) expect(page).not_to have_content("Be Yourself") end end end
FactoryBot.define do factory :sistema_usuario, class: 'Sistema::Usuario' do nombre { Faker::Name.name } email 'foo@bar.com' password 'foobar' password_confirmation 'foobar' end end # ## Schema Information # # Table name: `sistema_usuarios` # # ### Columns # # Name | Type | Attributes # ---------------------- | ------------------ | --------------------------- # **`id`** | `bigint(8)` | `not null, primary key` # **`nombre`** | `string` | # **`email`** | `string` | # **`numero_cuenta`** | `string` | # **`balance`** | `string` | # **`password_digest`** | `string` | # **`created_at`** | `datetime` | `not null` # **`updated_at`** | `datetime` | `not null` #
# http://www.mudynamics.com # http://labs.mudynamics.com # http://www.pcapr.net require 'mu/scenario/pcap' module Mu class Scenario module Pcap class Fields FIELDS = [ :rtp, :"rtp.setup-frame" ].freeze FIELD_COUNT = FIELDS.length SEPARATOR = "\xff".freeze TSHARK_OPTS = "-Eseparator='#{SEPARATOR}'" FIELDS.each do |field| TSHARK_OPTS << " -e #{field}" end TSHARK_OPTS.freeze def self.readline io if ::IO.select [ io ], nil, nil, Pcap::TSHARK_READ_TIMEOUT return io.readline.chomp end raise Errno::ETIMEDOUT, "read timed out" end def self.next_from_io io if line = readline(io) fields = line.split SEPARATOR, FIELD_COUNT hash = {} FIELDS.each do |key| val = fields.shift hash[key] = val.empty? ? nil : val end return hash end rescue Exception => e Pcap.warning e.message return nil end end end end end
class Article < ActiveRecord::Base has_many :events has_many :users, through: :events default_scope {order ('created_at DESC')} end
# frozen_string_literal: true # rubocop:todo all require_relative './performs_modern_retries' require_relative './performs_no_retries' module SupportsModernRetries shared_examples 'it supports modern retries' do let(:retry_writes) { true } context 'against a standalone server' do require_topology :single before(:all) do skip 'RUBY-2171: standalone topology currently uses legacy write retries ' \ 'by default. Standalone should NOT retry when modern retries are enabled.' end it_behaves_like 'it performs no retries' end context 'against a replica set or sharded cluster' do require_topology :replica_set, :sharded it_behaves_like 'it performs modern retries' end end end
# frozen_string_literal: true module Mutations module Games class UpdateGame < ::Mutations::BaseMutation argument :game_id, Integer, required: true argument :player, String, required: true argument :board, Types::Input::BoardInputType, required: true type Types::GameType def resolve(game_id:, player:, board:) board_params = Hash board Game.find(game_id).tap do |game| game.update!(player: player) game.board.update(**board_params) rescue ActiveRecord::RecordInvalid => e GraphQL::ExecutionError.new('Invalid attributes for game') end end end end end
require 'rails_helper' RSpec.describe MainController, :type => :controller do describe "Won card" do before do @joe = FactoryGirl.create(:facebook_user) @john = FactoryGirl.create(:twitter_user) @techniques_card = FactoryGirl.build(:techniques_card) @tools_card = FactoryGirl.build(:tools_card) @joe.cards << @techniques_card @joe.save! @john.cards << @tools_card @john.save! end it "should redirect to login page if the user is not logged in" do get :won_card, uuid: @tools_card.uuid expect(response).to redirect_to "/login" expect(flash[:notice]).to match(/^Por favor ingresa tus credenciales para continuar./) end it "should redirect to root if I am the owner of the card" do session[:user_id] = @joe.id get :won_card, uuid: @joe.cards.first.uuid expect(@joe.cards.count).to eq(1) expect(@joe.history.count).to eq(0) expect(response).to redirect_to "/" expect(flash[:notice]).to match("El token ya te pertenece.") end it "should change the owner of the card" do session[:user_id] = @joe.id get :won_card, uuid: @tools_card.uuid expect(@joe.cards.count).to eq(2) expect(@joe.history.count).to eq(1) expect(response).to redirect_to "/" expect(flash[:notice]).to match("Acabas de ganar una partida a <a href=\"/profile/#{@john.id}\">John Q Public</a>!") end end describe "Login" do it "should render login page" do get :login expect(response).to render_template(:login) end end describe "Profile" do it "should render profile page for an user" do user = FactoryGirl.create(:facebook_user) get :profile, id: user.id expect(assigns(:user)).to eq(user) end end describe "Status board" do before do 30.times do |count| user = FactoryGirl.create(:facebook_user, uid: SecureRandom.uuid) user.update cards_count: count end end it "should render the status board with the top 20 users" do get :status_board ranks = assigns(:users).collect(&:rank) expect(ranks).to eq((1..20).to_a) end end describe "Timeline" do before do @joe = FactoryGirl.create(:facebook_user) @john = FactoryGirl.create(:twitter_user) @techniques_card = FactoryGirl.build(:techniques_card) @tools_card = FactoryGirl.build(:tools_card) @joe.cards << @techniques_card @joe.save! @john.cards << @tools_card @john.save! @joe.won(@techniques_card) end it "should render the timeline page" do get :timeline expect(assigns(:history).count).to eq(1) end it "should render template with the history after given time" do History.first.update created_at: 2.days.ago @john.won(@techniques_card) get :timeline_updates, after: 1.day.ago expect(assigns(:history)).to eq([History.first]) expect(response).to render_template("main/_history") end end end
module Front::BaseHelper include ApplicationHelper def front_menu_class(actual_menu_name) menus = { appreciations: ["/front/appreciations.*"] } menu_class(menus, actual_menu_name) end def appreciation_custom_style(appreciation) return "style_no_saved" if appreciation.uuid.nil? styles = ["style_fish", "style_snell", "style_waterfly"] index = appreciation.uuid.each_byte.inject(&:+) styles[index % styles.length] end def render_markdown(text) options = { filter_html: true, no_images: true, no_links: true, no_styles: true, hard_wrap: true } renderer = Redcarpet::Render::HTML.new(options) Redcarpet::Markdown.new(renderer).render(text).html_safe end end
require 'spec_helper' describe Schema do context "The Schema class" do it "should parse a schema" do schema = Schema.build('config/schemas/stix/stix_core.xsd') schema.should_not be_nil schema.namespace.should == "http://stix.mitre.org/stix-1" schema.prefix.should == "stix" Schema.find('stix').should == schema schema.types.length.should == 11 schema.elements.length.should == 1 schema.attributes.length.should == 0 end it "should default the blacklist to true" do Schema.blacklist_enabled?.should == true end it "should be able to enable and disable the blacklist (schemas to ignore)" do Schema.blacklist_enabled = false Schema.blacklist_enabled?.should == false end it "should indicate whether a schema is blacklisted" do Schema.blacklist_enabled = false Schema.blacklisted?("http://stix.mitre.org").should == false Schema.blacklisted?("http://iodef.ietf.org").should == false Schema.blacklist_enabled = true Schema.blacklisted?("http://stix.mitre.org").should == false Schema.blacklisted?("http://cybox.ietf.org").should == false Schema.blacklisted?("http://data-marking.mitre.org").should == false Schema.blacklisted?("http://iodef.ietf.org").should == true end it "should return namespace mappings" do Schema.build('config/schemas/stix/stix_common.xsd') Schema.namespaces['xs'].should == 'http://www.w3.org/2001/XMLSchema' Schema.namespaces['stixCommon'].should == 'http://stix.mitre.org/common-1' end end context "A schema instance" do before do @schema = Schema.build('config/schemas/stix/stix_core.xsd') end it "should be able to find an element" do @schema.find_element('STIX_Package').should_not be_nil end it "should be able to list global elements" do @schema.elements.should == [@schema.find_element('STIX_Package')] end it "should be able to find the schema location" do @schema.schema_location.should == 'http://stix.mitre.org/XMLSchema/core/1.1/stix_core.xsd' end end end
class Painel::UsersController < Painel::BaseController before_action :set_users, :only => [ :update, :show, :updatepassword ] # before_filter :validate_user, :only => :show def index @users = User.where(:level => 0) end def new @user = User.new end def create @user = User.new(user_params_create) respond_to do |format| if @user.save format.json { render json: @user } format.html { redirect_to painel_users_path } end end end def show end def updatepassword respond_to do |f| if @user.update_attributes(user_params_update_password) f.html { redirect_to painel_user_path } end end end def update respond_to do |format| if @user.update_attributes(user_params_update) format.html { redirect_to painel_user_path } end end end private def validate_user redirect_to :controller => 'users', :action => 'show', :id => current_user unless current_user.id.to_s == params[:id] end def user_params_update params.require(:user).permit(:name, :birthday, :telephone, :cellphone, :email, :CEP, :address_line, :number, :district, :city, :state, :status) end def user_params_update_password params.require(:user).permit(:password, :password_confirmation, :current_password) end def user_params_create params.require(:user).permit(:name, :cpf, :birthday, :telephone, :cellphone, :email, :password, :password_confirmation, :CEP, :address_line, :number, :district, :city, :state, :status) end def set_users @user = User.find(params[:id]) end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'perf_framework/version' Gem::Specification.new do |spec| spec.name = "perf_framework" spec.version = PerfFramework::VERSION spec.authors = ["Abin Shahab"] spec.email = ["ashahab@altiscale.com"] spec.description = %q{Gem to run a performance benchmark} spec.summary = IO.read(File.join(File.dirname(__FILE__), 'README.md')) spec.homepage = "https://github.com/AltiPub/perf-framework" spec.license = "Proprietary" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rspec" spec.add_development_dependency "rake" spec.add_development_dependency "rubocop" spec.add_development_dependency('geminabox', '~> 0.11') spec.add_runtime_dependency "net-ssh" spec.add_runtime_dependency "net-scp" spec.add_runtime_dependency "aws-sdk" end