text
stringlengths
10
2.61M
require 'spec_helper' RSpec.describe "brigade_projects/new", :type => :view do before(:each) do assign(:brigade_project, BrigadeProject.new( :title => "MyString", :description => "MyText", :brigade_id => 1 )) end it "renders new brigade_project form" do render assert_select "f...
require 'rails_helper' describe 'Student Edit' do describe 'user click edit' do it 'should edit student and redirect to show' do student_1 = Student.create(name: "Jesse James") student_2 = Student.create(name: "Jessica Jones") visit student_path(student_2) click_link "Edit Student" ...
class ProfilesController < ApplicationController def index policy_scope(Profile) @profiles = Profile.where.not(latitude: nil, longitude: nil) end def show @profile = Profile.find(params[:id]) skip_authorization @prestations = Prestation.where({user_id: @profile.user.id}) end # def new # ...
require 'spec_helper' module FidorApi module Model module Transfer RSpec.describe Generic do describe 'dynamic attributes based on routing_type' do let(:transfer) { described_class.new } let(:routing_type) { 'FOS_P2P_EMAIL' } let(:email) { 'some.one@example....
require_relative '../spec_helper' RSpec.configure do |c| c.path = '/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin' end describe command('php -v') do its(:stdout) { should match /PHP 5\.4\.13/ } end describe file('/var/lib/php/session') do it { should be_directory } it { should be_mode 1777 } en...
Rails.application.routes.draw do mount ZapiApp::Engine => "/zapi_app" end
BookmarkService::Application.routes.draw do resources :bookmarks root :to => "bookmarks#index" end
Then /^"([^\"]*)" access level should be "([^\"]*)"$/ do |user, access_level| # if user == "first user" and access_level == "0" # @first_user = User.find @first_user.id # @first_user.rec_access_level.should == AccessLevels::DISABLED # @first_user.access_disabled?.should be_true # els if user == "Barney Ru...
require 'singleton' module Rocketman module Adapter class Memory include Singleton def initialize @registry = {} end def register_event(event) if @registry[event] return @registry[event] else @registry[event] = {} end end ...
class Session < ApplicationRecord belongs_to :training has_many :session_progressions, dependent: :destroy has_many :progressions, -> { order(:order) }, through: :session_progressions def human_weekday %w[Sun Mon Tue Wed Thu Fri Sat][weekday] end def done_today executed_at && executed_at > 12.hour...
require 'rails_helper' RSpec.describe "LayoutLinks", :type => :request do it "should have a Home page at '/'" do get '/' response.should have_selector('title', :content => "Home") end it "should have a Contact page at '/contact'" do get '/contact' response.should have_selector('title', :content => "Contact") end it...
class NewsController < ApplicationController def index @title = text('news', 'news_all') @news = get_language.new.all end def new @new = New.find_by(id: params[:id]) if @new @title = @new.title else redirect_to news_path, notice: 'Новость не найдена' end end end
require 'faker' FactoryGirl.define do factory :production_record do dt_produced { Faker::Date.between(Date.today, 7.days.from_now) } qty_produced { Faker::Number.between(1, 100) } trait :invalid do dt_produced nil end end end
# frozen_string_literal: true class LineBotsController < ApplicationController protect_from_forgery except: [:callback] def callback events = ready(request) events.each do |event| case event when Line::Bot::Event::Message case event.type when Line::Bot::Event::MessageType::Text...
# # Cookbook Name:: frog # Recipe:: server # # Copyright (C) 2014 Nick Downs # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights t...
class Lesson < ApplicationRecord has_one_attached :image belongs_to :user has_many :comments has_many :likes, dependent: :destroy def like_user(user_id) likes.find_by(user_id: user_id) end end
class UserLocationsController < ApplicationController before_filter :authenticate_user! def create @user_location = current_user.user_locations.build(location_query: params[:user_location][:location_query]) respond_to do |format| if @user_location.save format.html { redirect_to current_u...
#Basic Mouse System v2.7h #----------# #Features: Provides a series of functions to find the current x, y position of # the mouse and whether it is being clicked or not (left or right click) # #Usage: Script calls: # Mouse.pos? - returns the x, y position as an array # Mouse.lclick?(re...
# frozen_string_literal: true module Zendesk class Request < Request def request_url "#{Zendesk::Client::HOST}api/v2/#{SOURCE}" end private def set_default_headers super @headers["Authorization"] = "#{$app_config.call(:zd_token_auth_type)} #{client.access_token.create.value if cli...
class UsersController < ApplicationController skip_authorization_check before_action :set_user, only: [:finish_signup] def finish_signup if request.patch? && params[:user] if @user.update(user_params) @user.delay.send_reconfirmation_instructions sign_out @user redirect_to root_pa...
require 'spec_helper' describe Subject do it 'has valid factory' do expect(build(:subject)).to be_valid end it { should belong_to(:writer) } it { should belong_to(:room) } it { should have_many(:posts).dependent(:destroy) } it { should validate_presence_of(:writer_id) } it { should validate_presence...
class AddColumnsToBooks < ActiveRecord::Migration def change add_column :books, :author_id, :string add_column :books, :category_id, :integer add_column :books, :book_id, :string end end
require 'gnuplot' class ClassifiedData attr_accessor :data, :classification def initialize(data = Array.new, classification = nil) @data = data @classification = classification self end end def load_data(filename, only_numbers = false) rows = [] IO.foreach(filename) do |line| rows << Clas...
module Utility def self.is_nil_or_not_present_or_not_number_or_zero(param) return (!param.is_a? Integer || param == 0 || param.nil? || !param.present?) end def self.split_base64(string_encode) if string_encode.match(%r{^data:(.*?);(.*?),(.*)$}) return { type: $1, # "image/png" name: ...
class AddColumnToStockMonitors < ActiveRecord::Migration[5.0] def change add_column :stock_monitors, :user_id, :string end end
class CMS::AreasController < CMS::ApplicationController include GoogleMapsAPI prepend_before_action { @model = Area } def new if @context.is_a?(Region) super country_code: @context.country_code else super end end def create super parameters end def update super paramete...
class PledgesController < ApplicationController def create @pledge = Pledge.new(pledge_params) @pledge.save redirect_to @pledge.project end private def pledge_params params.require(:pledge).permit(:amount, :user_id, :project_id) end end
class CreateMenuItemCategories < ActiveRecord::Migration def change create_table :menu_item_categories do |t| t.integer :menu_item_id t.integer :category_id end end end
require './rdparse.rb' require './nodes.rb' require './runtime.rb' @@global_frame = NAScopeFrame.new(:global) class PrometheusParser @@vars = {} def initialize @parser = Parser.new("prometheus") do # Comments token(/^(\/\/.*)/) # Separators token(/^\;/) { |s| s } # Parenthesis token(/^(\(|\)|\}...
class Api::SessionsController < ApplicationController def create if !params[:user] @errors = ["Username and password cannot be empty"] render "api/shared/error", status: 422 return elsif !params[:user][:username] || !params[:user][:password] @errors = ["Input fields cannot be empty"] ...
AttributeNormalizer.configure do |config| config.normalizers[:currency] = lambda do |value, _options| value.is_a?(String) ? value.gsub(/[^0-9\.]+/, '') : value end config.normalizers[:truncate] = lambda do |text, options| if text.is_a?(String) options.reverse_merge!(:length => 30, :omission => ".....
=begin Create a Dictionary Tree Create a dictionary class that has the following methods: add_word(word) does_word_exist?(word) =end class DictonaryTree attr_accessor :root def initialize() @root = Node.new("") end def add_word(word, root=@root) first_letter = word[0] first_letter_index = letter...
class Channel < Messageable has_many :messages, as: :messageable end
# frozen_string_literal: true # == Schema Information # # Table name: users # # id :bigint(8) not null, primary key # email :string(255) not null # email_publish :boolean default(FALSE), not null # family_name :string(255) not null # given_name ...
class FontGemunuLibre < Formula head "https://github.com/google/fonts/raw/main/ofl/gemunulibre/GemunuLibre%5Bwght%5D.ttf", verified: "github.com/google/fonts/" desc "Gemunu Libre" homepage "https://fonts.google.com/specimen/Gemunu+Libre" def install (share/"fonts").install "GemunuLibre[wght].ttf" end te...
class Admin::SlidesController < Admin::BaseController def index @slides = Slide.all end def show @slide = Slide.find(params[:id]) end def new @slide = Slide.new @dates = fourteen_days end def create @slide = Slide.new(slide_params) @slide.user = current_user if @slide.save ...
class PredictionsController < ApplicationController # GET /predictions # GET /predictions.json #def index #@predictions = Prediction.all #respond_to do |format| #format.html # index.html.erb #format.json { render json: @predictions } #end #end # GET /predictions/1 # GET /prediction...
#q6 Our code only works with the student name and cohort. Add more information: hobbies, country of birth, height, etc. #q7 Research how the method center() of the String class works. Use it in your code to make the output beautifully aligned. #q8 In the input_students method the cohort value is hard-coded. How can you...
require 'rails_helper' RSpec.feature "Fill in Your Representative Page", js: true do let(:your_representatives_details_page) { ET3::Test::YourRepresentativesDetailsPage.new } let(:employers_contract_claim_page) { ET3::Test::EmployersContractClaimPage.new } scenario "correctly will enable user to continue to repr...
class Comment < ApplicationRecord belongs_to :feedback belongs_to :user has_many :feedback has_many :user end
class AddTypeNumberToFurnitures < ActiveRecord::Migration[5.0] def change add_column :furnitures, :type_number, :string end end
class AddWithdrewToBirthdayParties < ActiveRecord::Migration def change add_column :birthday_parties, :withdrew, :decimal, precision: 10, scale: 2, default: 0 end end
class AddCredentialsToStockLocations < ActiveRecord::Migration[4.2] def change add_column :spree_stock_locations, :fedex_account, :string add_column :spree_stock_locations, :fedex_password, :string add_column :spree_stock_locations, :fedex_key, :string add_column :spree_stock_locations, :fedex_login, ...
class AddIndexOnAttendanceLabel < ActiveRecord::Migration def self.up add_index :attendance_labels, :attendance_type, :name => "index_by_attendance_type" end def self.down remove_index :attendance_labels, :name => "index_by_attendance_type" end end
# # Cookbook Name:: lighttpd # Recipe:: default # # Copyright 2014, 0xphk # # All rights reserved - Do Not Redistribute # # install package package 'lighttpd' do action :install end # use config from template lighttpd_conf = '/etc/lighttpd/lighttpd.conf' template lighttpd_conf do source 'lighttpd...
class ChangeWorkText < ActiveRecord::Migration def change change_column :works, :text, :text, :limit => 10000 end end
class Message def initialize(user, message) @user = user @message = message @timestamp = Time.now.to_i * 1000 # * 1000 because JavaScript needs milliseconds end def json { 'user' => @user, 'message' => @message, 'timestamp' => @timestamp }.to_json end end require '...
require "net/http" require "oj" Oj.default_options = { mode: :strict } module FluxHue # Helpers for Hue Bridge REST requests. Placeholder to accrue redundant code # in order to DRY things up, centralize response handling, and prepare for # a more streamlined approach to interacting with the bridge. class HTTP...
Pod::Spec.new do |spec| spec.name = "QRCodeLib" spec.version = "1.0.0" spec.summary = "快速生成二维码." spec.description = <<-DESC 基于C的快速生成二维码框架,一句话调用: UIImage *image = [QRCodeGenerator qrImageForString:codestr imageSize:300]; DESC spec.homepage = "https://github.com/jiuy...
require 'csv' require 'sunlight/congress' require 'erb' Sunlight::Congress.api_key = "e179a6973728c4dd3fb1204283aaccb5" def clean_zipcode(zipcode) zipcode.to_s.rjust(5,"0")[0..4] end # that line just cleaned up all of this code: =begin if zipcode.nil? zipcode == "00000" elsif zipcode...
# using subject.instance_variable_set is a code smell # use let when you need to instead # using .send method to access private methods is indicative of a design problem or could maybe the method should be public or don't test that because it is just a implementation detail describe 'BabySit' do let(:start) {17}; le...
class Teacher::ClusterSerializer < ActiveModel::Serializer root false attributes :id, :name end
require 'spec_helper' describe Leaguezone do let(:league) { FactoryGirl.create(:league) } before(:each) do @attr = { :name => "promotion", :description => "foo", :start_rank => 1, :end_rank => 3, :style => "foo", :created_by_id => 1, :updated_by_id => 1, :league_id => league.id } end it "sh...
require "jaguar/http1/parser" module Jaguar::HTTP1 # # the request MUST respond to: # * #verb (returns a String ("GET", "POST"...) # * #request_url (returns a URL) # * #headers (returns an headers hash) # * #body (returns an Enumerable) # class Request attr_reader :verb, :version, :headers, :body...
class CommentsController < ApplicationController before_action :authenticate before_filter :set_restaurant def create @comment = @restaurant.comments.new(comment_params) @comment.user_id = current_user.id if @comment.save redirect_to restaurant_path(@restaurant) else redirect_to resta...
class CashRegister attr_accessor :total, :items, :discount def initialize(employee_discount=0) @discount = employee_discount @items = [] @total = 0 end def add_item(item, price, number = 1) @last_number = number @last_price = price*number number.times {@items << item} @total += @last_price e...
json.array!(@activities) do |activity| json.id activity.id json.owner_id activity.owner_id json.username activity.user.username json.action activity.action json.picture activity.picture.title json.picture_id activity.picture.id json.viewed activity.viewed json.current_user current_user.username json.c...
FactoryBot.define do factory :review do course user rating { 5 } post { 'Great stuff' } end end
# League Point Calculator SI Homework # Julia Les 5/19/2016 # Prompt: Build a League Point Calculator. The LPC should be able to # let the user input teams and scores, and output the league ranking based on points # from highest to lowest. If there is a tie then they should be ordered # alphabetically. Each winning...
class User < ActiveRecord::Base has_secure_password has_one :business validates :first_name, presence: true validates :last_name, presence: true validates :email, presence: true end
# frozen_string_literal: true module Decidim module Opinions module Admin # This controller allows admins to answer opinions in a participatory process. class OpinionAnswersController < Admin::ApplicationController helper_method :opinion helper Opinions::ApplicationHelper hel...
require 'pry' require 'pry-byebug' #Reverse It # 1 - Create a method that reverses a string, without using the .reverse method # 2 - Create another method that tests whether that word is a palindrome def my_reverse(string) characters = string.downcase.chars reversed_string = "" until characters.empty? == true r...
class AddWeightAndListidToPoints < ActiveRecord::Migration def change add_column :points, :list_id, :integer add_column :points, :weight, :integer, :default => 1 end end
require 'observer' class Employee #this ruby module provides several methods which allow observers #to be added and notified include Observable attr_reader :name, :salary, :address def initialize( name, title, salary) @name = name @title = title @salary = salary end #again a custom writer is needed #...
class SerialisedTitlesController < ApplicationController # GET /serialised_titles # GET /serialised_titles.xml def index @serialised_titles = SerialisedTitle.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @serialised_titles } end end # GET /seria...
class RemoveColumnAuthUserOnFeeds < ActiveRecord::Migration[5.2] def change remove_column :feeds, :auth_user, :string end end
# prevents forms and pages from being processed more than once. # needs memcache for working. # check_request_fingerprint *actions - will keep a finger print check for the action, looks for a fingerprint in params, # if fingerprint already seen it will raise SessionFingerprint::DuplicateRequestFingerprint exception # a...
class KnowledgesController < ApplicationController before_action :set_knowledge, only: [:show, :edit, :update, :destroy] def index @knowledges = Knowledge.includes(:knowledge_level, :technology).all end def show end def new @knowledge = Knowledge.new @knowledge_levels = KnowledgeLevel.all @technologi...
require 'thor/group' module ChemistryKit module CLI class Generate < Thor include Thor::Actions attr_accessor :name def self.source_root File.join(File.dirname(__FILE__), '..') end desc "spec name [ARGS]", "Generate a Chemistry Kit spec" long_desc <<-LONGDESC ...
class RemoveCardidFromTypes < ActiveRecord::Migration[5.1] def change remove_column :types, :card_id end end
# frozen_string_literal: true class CreateBeerFlavorTable < ActiveRecord::Migration[5.2] def change create_table :beer_flavors do |t| t.integer :beer_id t.integer :flavor_id end end end
require 'date' require 'pathname' require 'rake' require 'rake/clean' require 'rake/testtask' require 'rake/extensiontask' $rootdir = Pathname.new(__FILE__).dirname $gemspec = Gem::Specification.new do |s| s.name = 'bloom-filter' s.version = '0' # modify ext/version.h s.date ...
class Section < ActiveRecord::Base has_and_belongs_to_many :students belongs_to :professor belongs_to :course #foreign keys for course, professor, student end
# web elements and functions for page class ProgressBarPage include Capybara::DSL include RSpec::Matchers include Capybara::RSpecMatchers def initialize @start_and_reset_button = Element.new(:css, '#startStopButton') @progress_bar = Element.new(:css, '#progressBar') @reset_button = Element.new(:css...
require 'test_helper' class PasswordResetRoutesTest < ActionController::TestCase context 'password reset routes' do should 'route to create a password reset' do assert_routing({method: 'post', path: URL_BASE + 'password_resets'}, {controller: URL_BASE + 'password_resets', action: 'create'}) end should ...
## # $Id: jboss_deploymentfilerepository.rb 9246 2010-05-07 22:28:37Z jduck $ ## ## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit....
# -*- encoding : utf-8 -*- require 'test_helper' class TheoreticalPartsControllerTest < ActionController::TestCase setup do @theoretical_part = theoretical_parts(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:theoretical_parts) end ...
FactoryBot.define do factory :facilities_management_supplier, class: FacilitiesManagement::Supplier do name { Faker::Name.unique.name } contact_name { Faker::Name.unique.name } contact_email { Faker::Internet.unique.email } telephone_number { Faker::PhoneNumber.unique.phone_number } end end
class FontIansui < Formula version "0.943" sha256 "d8157b39d10b3f4dbc8b09d240824f81ebb61d41e4bcbc283f249d9fdac5e4b3" url "https://github.com/ButTaiwan/iansui/releases/download/v#{version}/iansui.zip" desc "iansui" desc "Chinese font derived from Klee One" homepage "https://github.com/ButTaiwan/iansui" def...
module Api class ResumeEducationController < ApplicationController def index @resume_education_all = ResumeEducation.all respond_to do |format| format.json { render json: @resume_education_all } end end def show @resume_education = ResumeEducation.find(params[:id]) ...
require "test/unit" class Frog < Test::Unit::TestCase def frog_jump(init, target, jump) return 0 if init >= target mod = target % jump if mod == 0 jumps = (target / jump) - 1 else jumps = target / jump end jumps -= init / jump (jumps * jump) + init >= target ? jumps : jumps ...
class BankAccount attr_reader :balance def initialize(starting_balance=0) @balance = starting_balance end def check_balance "Your balance is $#{@balance}" end def deposit(amount) @balance += amount end def withdraw(amount) if (@balance - amount) >= 0 @balance -= amount end end def tr...
require 'spec_helper' require 'mist/git_model' describe Mist::GitModel do let(:model_class) { Class.new(Mist::GitModel) { def self.name; "TestModel"; end } } subject { model_class.new } describe "when no records ever existed" do it "last record should be nil" do model_class.last.should be_nil en...
class GlobalSceneAttribute < ActiveRecord::Base # Associations belongs_to :scene_attribute_type has_many :scene_global_scene_attributes, dependent: :destroy has_many :scenes, through: :scene_global_scene_attributes # Validations validates :name, :display_name, :scene_attribute_type_id, presence: true end
class CleanupIndexesToSpeedupExifAssetGeneration < ActiveRecord::Migration def change remove_index :photos, :name => :index_photos_on_cluster_id_and_is_visible add_index :exif_translations, [:name, :exif_name, :exif_value] add_index :photos, [:is_visible, :cluster_id] add_index :photos, [:is_visible,...
class Status < ActiveRecord::Base belongs_to :user has_and_belongs_to_many :tags has_and_belongs_to_many(:statuses, :join_table => "status_connections" :foreign_key => "status_a_id" :association_foreign_key => "status_b_id") attr_accessible :geocode, :image_url, :status validates :status, :presen...
module Objvent module Generators class InstallGenerator < ::Rails::Generators::Base source_root File.expand_path("../../templates", __FILE__) def copy_initializer template "objvent.rb", "config/initializers/objvent.rb" template "websocket_rails.rb", "config/initializers/events.rb" ...
class Post < ActiveRecord::Base self.per_page = 3 belongs_to :user validates :title, :body, presence: true # default_scope order(created_at: :desc) scope :published, -> { where(is_published: true) } end
Friendrank::Application.routes.draw do scope "/users", controller: :users do post "/create_and_or_sign_in", to: :create_and_or_sign_in get "/friends", to: :friends get "/friends_likes", to: :friends_likes get "/friends_likes_status", to: :friends_likes_status get "/top_friends", to: :top_friends ...
class ChangeStockInfos < ActiveRecord::Migration[5.0] def change add_column :stock_infos, :start_rate_mny, :integer add_column :stock_infos, :max_rate_mny, :integer add_column :stock_infos, :min_rate_mny, :integer add_column :stock_infos, :end_rate_mny, :integer add_column :stock_infos, :buy_sell_...
require 'pry' class LuckyRoulette attr_accessor :player def initialize(player) @player = player puts "\n--- Welcome to the Lucky Unlucky Bastard Roulette ---\n"#.colorize(:blue); sleep 1 puts "Annnnnnd...."; sleep 1 puts "There we gooooo..." roll_the_dice end # TRIPLE MIXED RANDOM NUMBER...
class PeriodicExpense < ActiveRecord::Base PERIODS = { 'weekly' => 1.week, 'monthly' => 1.month } belongs_to :user belongs_to :category has_many :expenses validates :description, :user, :amount, :period, :start_date, :category, presence: true validates :period, inclusion: { in: PERIODS.keys } validates ...
require 'rails_helper' feature "User visits profile page and sees their parking pass" do let!(:user) { FactoryGirl.create(:user) } let!(:parking_pass) { FactoryGirl.create(:parking_pass, user: user) } before { login_as(user, scope: :user) } context "As a user who owns a parking pass" do scenario "I can see...
class Compensation attr_accessor :criteria, :raw_data, :params def search(criteria) apply_default_criteria(criteria) self.criteria = criteria do_search get_results end def data_source_params params[:onetbreakdown] = criteria[:onetbreakdown] unless criteria[:onetbreakdown].nil? params[...
require 'cxbrank/const' require 'cxbrank/master/base' require 'cxbrank/master/music' module CxbRank module Master class LegacyChart < Base belongs_to :music def self.last_modified(music_id=nil) if music_id.present? legacy_charts = self.where(:music_id => music_id) else ...
# Problem 165: Intersections # http://projecteuler.net/problem=165 # A segment is uniquely defined by its two endpoints. By considering two line segments in plane geometry there are three possibilities: # the segments have zero points, one point, or infinitely many points in common. # Moreover when two segments have ...
module Roglew module WGL ERROR_INCOMPATIBLE_AFFINITY_MASKS_NV ||= 0x20D0 ERROR_MISSING_AFFINITY_MASK_NV ||= 0x20D1 class GPU_DEVICE < FFI::Struct layout :cb, :uint, :DeviceName, [:char, 32], :DeviceString, [:char, 128], :Flags, ...
RSpec.describe "`github_rb fetch_user` command", type: :cli do it "executes `github_rb help fetch_user` command successfully" do output = `github_rb help fetch_user` expected_output = <<-OUT Usage: github_rb fetch_user USERNAME Options: -h, [--help], [--no-help] # Display usage information Get user det...
class CalendarPresenter < SimpleDelegator def row_table_calendar(week_day, day, hour, current_user) room = room_reservation(day, hour) if room.present? helpers.content_tag :td, room_reservation_label(room, current_user) else helpers.content_tag :td, helpers.link_to("Disponível", '#'),...
require 'yaml' class Configuration attr_reader :federation, :redis, :clientserver, :clientclient def initialize config = YAML.load_file("../config.yml") @federation = config["federation"] @redis = config["redis"] @clientserver = config['clientserver'] @clientclient = config['clientclient'] ...