text
stringlengths
10
2.61M
default_platform(:ios) platform :ios do desc "Push a new beta build to TestFlight" lane :beta do BUMP = latest_testflight_build_number + 1 sh("git add -A") sh("git commit -m \"Beta upload #{BUMP}\"") increment_build_number(build_number: BUMP) build_app( scheme: "VocabulAR", export_...
class StartDatabase < ActiveRecord::Migration def self.up create_table "answers", :force => true do |t| t.integer "question_id" t.integer "assessment_id" t.string "value" t.boolean "correct" t.datetime "created_at" t.datetime "updated_at" end create_table "assess...
class Tool < ActiveRecord::Base attr_accessible :name has_and_belongs_to_many :worker_profiles end
class FontNotoSansNko < Formula head "https://github.com/google/fonts/raw/main/ofl/notosansnko/NotoSansNKo-Regular.ttf", verified: "github.com/google/fonts/" desc "Noto Sans NKo" desc "Unmodulated design for texts in the African N’Ko script" homepage "https://fonts.google.com/specimen/Noto+Sans+NKo" def insta...
class NewslettersController < InheritedResources::Base def new @newsletter = Newsletter.new end def create @newsletter = Newsletter.new(newsletter_params) if @newsletter.save NewsletterMailer.newsletter_confirmation(@newsletter).deliver redirect_to root_path flash[:notice]...
# lib/version.rb # version info and histroy module ViralSeq VERSION = "1.0.5" end
require 'pg' require_relative 'seed_search_engine' #database name is search_engine #table name is reject_stats def main conn = PG.connect(dbname: 'search_engine') table_name = 'reject_stats' search_options = {} records = conn.exec("SELECT COUNT(*) FROM #{table_name};") row_count = records.getvalue 0, 0 if...
class AddConfirmedToSendee < ActiveRecord::Migration[5.1] def change add_column :sendees, :confirmed, :boolean end end
module Alipay module Service GATEWAY_URL = 'https://mapi.alipay.com/gateway.do' %w(app wap).each do |name| define_singleton_method "#{name}_pay_url" do |params, options = {}| params = { 'service' => services[name], '_input_charset' => 'utf-8', 'partner' ...
# -*- mode: ruby -*- # vi: ft=ruby : # # Borrowed the idea from http://bertvv.github.io/notes-to-self/2015/10/05/one-vagrantfile-to-rule-them-all/ # require 'rbconfig' require 'yaml' DEFAULT_BASE_BOX = "centos/7" cpuCap = 10 # Limit to 10% of the cpu inventory = YAML.load_file("inventory.yml") # G...
# frozen_string_literal: true require './models/cook_roulette/ip_address' RSpec.describe CookRoulette::IpAddress do describe ".forbidden?" do subject { described_class.forbidden?(given_ip_address) } context "if ALLOWED_IP_ADDRESSES env var includes given ip address" do let(:given_ip_address) { ENV.fe...
# # Cookbook Name:: cargo # Recipe:: default # # Copyright 2014 # # All rights reserved - Do Not Redistribute # Author: Pedro H. Spagiari (github/phspagiari) # Description: Installs and configure cargo and their dependencies apt_repository 'docker' do uri 'https://get.docker.io/ubuntu' distribution 'docker' comp...
describe User do let!(:user) do User.create(email: 'user@email.com', password: '1234', password_confirmation: '1234', full_name: 'bobby bobberson', user_name: 'bobMan') end describe '#creation' do it 'is a valid datamapper model' do ex...
Rails.application.routes.draw do resources :vehicles do match '/scrape', to: 'vehicles#scrape', via: :post, on: :collection end root to: 'vehicles#index' end
class ChangeConfigDefault < ActiveRecord::Migration[6.1] def change change_column_default :clients, :config, {} end end
# frozen_string_literal: true module Zafira module Operations module TestCase class Start include Concerns::Operationable def initialize(client) self.client = client end def call super do chain { init_start_time } chain { start_t...
require_relative '../../../spec_helper' describe 'resource_plex_home_theater_app::mac_os_x::10_10' do let(:source) { nil } let(:action) { nil } let(:runner) do ChefSpec::SoloRunner.new( step_into: 'plex_home_theater_app', platform: 'mac_os_x', version: '10.10' ) do |node| node.set...
class PolishCalculator attr_accessor :expressions def initialize @expressions = [] end def prompt_input print "input something>>\t" expressions << gets.chomp end def rpn loop do prompt_input check_expressions puts expressions.map(&:to_s).join(" ") end end def c...
class Order < ApplicationRecord belongs_to :user def items JSON.parse(products) end end
class Flight < ApplicationRecord belongs_to :origin, class_name: "Airport" belongs_to :destination, class_name: "Airport" has_many :bookings has_many :booking_passengers, through: :bookings has_many :passengers, through: :booking_passengers def start_date_formatted start.strftime("%d/%m...
class DeductionDetail < ApplicationRecord has_many :deduction end
class RequestsController < ApplicationController def new @house = House.find(params[:house_id]) @request = Request.new end def create @house = House.find(params[:house_id]) if @house != current_user.house @request = @house.requests.new(request_params) @request.user = current_user ...
# -*- encoding : utf-8 -*- class AddStartAndAlbumToListens < ActiveRecord::Migration def change add_column :listens, :album_id, :integer add_column :listens, :album_position, :integer add_column :listens, :started_at, :datetime end end
class AddHnCreatedAtToLinks < ActiveRecord::Migration def change add_column :links, :hn_created_at , :datetime end end
# encoding: UTF-8 module CDI module V1 module UserGalleries class AssetUploadCreateService < BaseCreateService include V1::ServiceConcerns::FileUploadParams record_type ::Photo, alias_name: :asset response_options success_code: 200 private def build_record ...
require 'active_support/core_ext/string/inflections' require 'battman/dsl/watch_block' module Battman module DSL Thread.abort_on_exception = true def initialize @blocks = Hash.new {|hash, key| hash[key] = []} @intervals_due = Hash.new {|hash, key| hash[key] = 0} yield self if block_given?...
class Api::V1::GoalsController < ApplicationController def index render json: Goal.all end def create # byebug goal = Goal.new(goal_params) if goal.save render json: goal else render json: { message: goal.errors }, status: 400 end end def destroy Goal.destroy(params[:...
require 'spec_helper' require 'helpers/sample_crawler' describe SampleCrawler do before(:each) do @sample_crawler = SampleCrawler.new end it 'should correctly assign event metadata' do @sample_crawler.should_receive(:parse) do |args| # args["event"]["description"].selector.should == "css=#main-nod...
require 'json' require 'rest-client' require 'health-data-standards' module PhEMA module Phenotype # Takes the output of the PhEMA authoring tool (a JSON-based phenotype definition), and identifies # all value sets. It the connects to a CTS2 repository and exports the value set definitions. # # CTS2...
module OrientdbBinary module BaseProtocol class DbList < BinData::Record include OrientdbBinary::BaseProtocol::Base endian :big int8 :operation, value: OrientdbBinary::OperationTypes::REQUEST_DB_LIST int32 :session end class DbListAnswer < BinData::Record endian :big ...
class Oid < ActiveRecord::Base has_many :oid_models has_many :device_models, :through => :oid_models has_many :events has_many :switch_ports, :through => :events validates :name, :message, :priorityLevel, :oid, :presence => true validates :name, :length => { :maximum => 15 } end
class Feedback < ApplicationRecord validates :name, :email, :description, presence: true def self.recent(number) Feedback.order("created_at desc").limit(number) end end
module PdfTempura class Document::Table::BoxedCharacterColumn < Document::Table::Column def initialize(name, height, options = {}, &block) @name = name @height = height @options = options @block = block if block_given? end def width field_at([0,0]).width end def fi...
class AddIncludeLinkToCollectionToHeroImages < ActiveRecord::Migration def change add_column :hero_images, :include_link_to_collection, :boolean change_column :hero_images, :caption, :string, limit: 25 end end
require_relative "../test_container" class Jaguar::HTTP1::SSLServerTest < ContainerTest include Requests::PlainGet include Requests::EncodingGet include Requests::ChunkedGet include Requests::KeepAliveGet include Requests::StreamGet include Requests::PlainPost include Requests::MultipartPost private ...
class ReviewsController < ApplicationController load_and_authorize_resource def index @reviews = Review.accessible_by(current_ability).all end def show end def edit end def create if @review.save(review_params) redirect_to book_path(Book.find(@review.book_id)), notice: t("success.notic...
class PostsController < ApplicationController def index @posts = BluethumbService.new.posts @posts = @posts.sort! { |a, b| b['created_at'] <=> a['created_at'] } unless @posts.blank? end def new; end def create response = BluethumbService.new(payload: post_params).create_post render :new and r...
class Song attr_reader :price attr_accessor :title, :duration def initialize(title, artist_name, duration, price) @title = title @artist = artist_name @duration = duration @price = price end end
class OrganizationsController < ApplicationController before_action :set_organization, only: [:organization_reporitng, :show, :edit, :update, :destroy] def organization_reporitng end def index @organizations = Organization.all respond_to do |format| format.html format.json do if p...
class AddPostStatus2ToBlogs < ActiveRecord::Migration[6.0] def change add_column :blogs, :status2, :integer, default:0 end end
require 'rails_helper' RSpec.describe Loan, type: :model do current_loan_spec = nil let(:loan) do current_loan_spec ||= create(:loan) end it { is_expected.to validate_presence_of(:rate) } it { is_expected.to validate_numericality_of(:rate).is_greater_than(0) } it { is_expected.to validate_presence_o...
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::BigInt do it "encodes big and small integers as strings" do big_integer_1 = 99**99 expected_str_1 = "36972963764972677265718790562880544059566876428174110243025997242355257045527752342141065001012823272794097888954832654011942999676...
=begin (Problem): Write a method that takes one argument, a string, and returns a new string with the words in reverse order. (Understand the Problem): • (Inputs): String of words • (Outputs): New string with words in reverse order • (Rules): o (Explicit): - Output should be a new string and not...
module Oss class Service attr_reader :access_key_id, :secret_access_key, :connection def initialize(options) @access_key_id = options.delete :access_key_id @secret_access_key = options.delete :secret_access_key @connection = Connection.new(:access_key_id => @access_key_id, :secret_ac...
# Code your prompts here! # First, puts out a string asking where the tourist would like to stay. puts "Let's plan your trip! Where would you like to go?" trip = gets.chomp.capitalize # Then, set a variable called stay to get the user's input. Make sure to capitilize that input. puts "What would you like to eat?" eat...
include ApplicationHelper class ApplicationController < ActionController::Base protect_from_forgery before_filter :logged_in_user def logged_in_user @current_user = User.find_by_id(session[:user_id]) end # so we don't get backtraces on production def local_request? false if RAILS_ENV == 'product...
# frozen_string_literal: true class ResetPasswordTokensController < ApplicationController before_action :authenticate_token!, only: [] def check_reset_token render_as_json do reset_password_token.user.as_json(user_as_json) end end def reset_password ResetPasswordToken.create!(user: user) ...
module Openweather2 class Weather attr_reader :city, :longitude, :latitude, :pressure, :humidity, :clouds, :temperature, :min_temperature, :max_temperature, :wind_speed, :wind_angle def initialize(json) @city = json['name'] @longitude = json['coord'] && json['coord']['lon'] @latitude...
# frozen_string_literal: true class CreateReviews < ActiveRecord::Migration[5.2] def change create_table :reviews do |t| t.string :title t.text :content t.integer :homework_id t.date :date t.decimal :rate t.integer :lesson_id t.timestamps end end end
class AnagramFinder def initialize @store = Hash.new { |h, k| h[k] = [] } end def add_word(word) @store[checksum(word)] << word end def anagrams @store.select {|checksum, words| words.length > 1 }.values end private def checksum(word) word.chars.sort.join.hash end end
class User < ActiveRecord::Base has_many :goals attr_accessible :email, :password, :password_confirmation, :avatar, :name, :username, :location, :about attr_accessor :password before_save :encrypt_password before_create :setup_activation validates_confirmation_of :password validates_presence_of :password, ...
class PubAccount < ActiveRecord::Base has_many :stats_entries, :dependent => :destroy def class_name self.class.to_s.demodulize.underscore end end
class Model::Section::TeachingCentreSelection < SitePrism::Section element :label, ".field-content" end
Rails.application.routes.draw do resources :enrollments resources :users resources :courses resources :subjects get 'static_pages/subjects' get 'static_pages/courses' get 'static_pages/instructors' resources :instructors root 'welcome#index' get '/signup', to: 'users#new' resources :users get ...
class AddPlaydayToReservations < ActiveRecord::Migration def change add_column :reservations, :playday_id, :integer add_index :reservations, :playday_id end end
FactoryGirl.define do factory :recipe do name {Faker::Food.ingredient} instructions {Faker::Lorem.paragraph} comment {Faker::Lorem.paragraph} status 1 end end
class Report < ActiveRecord::Base attr_accessible :name, :useragent, :description has_many :urls validates :name, presence: true validates :useragent, presence: true def queue_jobs self.urls.each do |url| url.delay.scrape_matches end end def percentage_complete percentage = self.urls.where...
class AddOrganizationToItem < ActiveRecord::Migration[6.0] def change add_reference :items, :organization, index: true end end
<?xml version="1.0" encoding="UTF-8"?> <interface> <!-- interface-requires gtk+ 2.12 --> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window"> <property name="can_focus">False</property> <property name="title" translatable="yes">Nastavení Fingerpaint</property> <child> ...
# frozen_string_literal: true FactoryBot.define do factory :client, class: MondialRelay::Client do wsdl_url { 'https://api.mondialrelay.com' } initialize_with { new(wsdl_url) } end factory :account, class: MondialRelay::Account do id { 'BDTEST13' } secret { 'PrivateK' } initialize_with { ne...
class Api::MessagesController < ApplicationController before_action :set_group def index @messages = @group.messages.includes(:user).where("id > ?", index_params[:last_message_id].to_i) end private def index_params params.permit(:last_message_id) end def set_group @group = Group.find(param...
require 'watir' require 'webdrivers' require 'minitest' Before do @site = Website.new(Watir::Browser.new) end After do @site.close end Given('Traveller is at the log-in page') do @login_page = @site.login_page.open end When('Traveller enters the correct username') do ### this step is now integrated elsew...
# frozen_string_literal: true module Vedeu module Repositories # Provides collection related query/command methods. # # @api private # module Assemblage include Enumerable # Return an individual element or collection of elements (if # the given index is a Range). # ...
require 'spec_helper' module Boilerpipe::SAX::TagActions describe InlineTagLabel do let(:subject) { InlineTagLabel.new(nil) } let(:handler) { ::Boilerpipe::SAX::HTMLContentHandler.new } describe '.new' do it 'takes a label action' end describe '#start' do it 'returns false' do ...
require 'test_helper' class PlayerSeasonsControllerTest < ActionDispatch::IntegrationTest setup do @player_season = player_seasons(:one) end test "should get index" do get player_seasons_url assert_response :success end test "should get new" do get new_player_season_url assert_response ...
module Topographer class Importer module Logger class Base attr_reader :fatal_errors def initialize @fatal_errors = [] end def successes raise NotImplementedError end def failures raise NotImplementedError end ...
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module TravelBehavior class Application < Rails::Application # Try loading a YAML file at `./config/env.[environment].yml`...
class PatientDecorator < Draper::Decorator delegate_all def full_name "#{object.first_name} #{object.last_name}" end # def age # # 60 * 60 * 24 * 365.25 is 31557600 # # 31557600 is one year in seconds # ((Time.now - date_of_birth) / 31557600).floor # end end
module Tablette class ActionViewRenderer < HTMLRenderer def initialize(template) super() @template = template end def wrap_content(proc) ->(*args) do @template.capture(*args, &proc) end end def to_html(node) super(node).html_safe end end module Act...
require 'htph'; # This is a very strict query interpreter for the hathi_* govdoc tables. It only does exact matches on single values. # A complex query is broken down into several smaller queries, where the results of the previous query is required to # be included in successful results of the next. db = HTPH...
# encoding: UTF-8 require_relative '../test_helper' describe "creq req" do let(:id) {'id'} let(:cmd) {'req'} let(:title) {'title'} let(:template) {'tt.id'} it 'must create file and notify about success' do inside_sandbox do file = "#{Settings.src}/id.md" success_msg = "File '#{...
# == Schema Information # # Table name: services # # id :integer not null, primary key # name :string(255) # showing_time :integer # cost :integer # organization_id :integer # created_at :datetime not null # updated_at :datetime not null # ...
# frozen_string_literal: true module MagickCanvas class Base include Magick extend ::Forwardable delegate %i[ app width height columns rows number_of_frames frame_steps iterations background_color ] => :options_with_defaults delegate %i[write] => :image_list class << self ...
#File actionpack/lib/action_dispatch/middleware/params_parser.rb, line 25 def parse_formatted_parameters(env) request = Request.new(env) return false if request.content_length.zero? mime_type = content_type_from_legacy_post_data_format_header(env) || request.content_mime_type strategy = @parsers[mime_...
# you can write to stdout for debugging purposes, e.g. # puts "this is a debug message" module Kata module Algorithms def self.find_gaps(n) binary_representation = n.to_s(2) in_gap = false length_of_gap = 0 maximum_length = 0 binary_representation.split('').each_with_index do |charac...
require 'rails_helper' RSpec.describe Archiver::TweetCreator do describe '#create' do let(:twitter_tweet) { double('TwitterTweet') } let(:tweet) { double('Tweet') } let(:parser) { double('Parser') } let(:feed_item_creator) { double('FeedItemCreator') } let(:tweet_user_creator) { double('TweetUser...
module CassandraObject module Core extend ActiveSupport::Concern def initialize(attributes=nil) @new_record = true @destroyed = false @model_attributes = {} self.attributes = attributes || {} attribute_definitions.each_value do |definition| unless definition.default.nil?...
module Nyaplot # The wrapper for pane of Nyaplotjs # (https://github.com/domitry/Nyaplotjs/blob/v2/src/parser/pane.js) # # @example # p1 = Pane.new.columns(s1, s2) # p2 = Pane.new.columns(s3, s4) # p3 = Pane.new.rows(p1, p2) # p3.to_iruby class Pane include Nyaplot::Base type :pane ...
class AddUsersInfo < ActiveRecord::Migration def change add_column :users, :name, :string add_column :users, :surname, :string add_column :users, :gender, :integer, :default => 0 add_column :users, :age, :integer add_column :users, :country, :string add_column :users, :city, :string add_colum...
# parser for FEC contributions data from: # https://www.fec.gov/data/receipts/individual-contributions class Parser::Fec < Parser::Csv def category "fec" end end
module QML module_function # @example # def set_app_name # QML.qt.application.name = 'appname' # end # @return [JSObject] QML Qt namespace object # @see http://doc.qt.io/qt-5/qml-qtqml-qt.html def qt @qt ||= begin component = QML::Component.new data: <<-QML import QtQuick 2.0...
require 'crawler/crawler.rb' namespace :crawler do desc "Start the crawler" task start: :environment do begin c = Crawler.new rescue puts 'crawler already running' end end desc "Stop the crawler" task stop: :environment do Crawler.stop end desc 'Check the status of the crawler' task status: ...
class StudentUsersController < ApplicationController before_action :set_student_user, only: [:show, :edit, :update, :destroy] # GET /student_users # GET /student_users.json def index @student_users = StudentUser.all respond_to do |format| format.html format.csv { send_data @student_users.to_csv...
require 'rake' namespace :heroku do namespace :deploy do desc "deploy to staging" task :production do puts "Starting pre-compile..." system "rake assets:precompile RAILS_ENV=production" puts "Finished pre-compile." puts "Committing changes..." system "git add ...
require 'dispatcher' # FedenaTask module FedenaTask def self.attach_overrides Dispatcher.to_prepare :fedena_task do ::User.instance_eval { include UserExtension } ::Student.instance_eval { include StudentExtension } end end def self.dependency_delete(student) student.user.tasks.destroy_a...
class MoveObservationsToRoles < ActiveRecord::Migration def change role = Role.find_or_create_by(name: 'observer') # We have to use raw sql because we've subclassed the observation class. Also, use `GROUP_BY` to find DISTINCT pairs. pgres = ProposalRole.connection.execute("SELECT proposal_id, user_id FRO...
require_relative 'db_connection' require 'active_support/inflector' # NB: the attr_accessor we wrote in phase 0 is NOT used in the rest # of this project. It was only a warm up. #table_name is instance variable class SQLObject def self.columns @columns ||= DBConnection.instance.execute2(<<-SQL) SELECT ...
require 'active_record' require 'bigdecimal' require 'cxbrank/const' require 'cxbrank/site_settings' require 'cxbrank/user' require 'cxbrank/master/music_set' require 'cxbrank/master/music' require 'cxbrank/master/course' require 'cxbrank/playdata/music_skill' require 'cxbrank/playdata/course_skill' require 'cxbrank/pl...
class ChangeTypeToFactType < ActiveRecord::Migration def change change_table :malariafacts do |t| t.remove :type t.integer :fact_type end end end
class CreateColorSetsAndPropertiesTables < ActiveRecord::Migration[5.1] def change create_table :color_sets do |t| t.string :color, null: false t.timestamps end create_table :properties do |t| t.integer :color_set_id, null: false t.string :name, null: false t.timestamps e...
require 'spec_helper' describe User, 'validations' do let!(:user) { create(:user, :paul) } context 'when valid data' do it 'accepts valid attribuites' do expect(user).to be_valid end end it 'requires name' do user = User.create(name: nil) expect(user.errors[:name].size).to eq(2) end ...
class Market attr_reader :name, :vendors def initialize(name) @name = name @vendors = [] end def add_vendor(vendor) @vendors << vendor end def vendor_names @vendors.map {|vendor| vendor.name} end def vendors_that_sell(item) @vendors.find_all do |vendor| vendor.inventory.has_...
require 'net/http' require 'tempfile' require 'fileutils' # This class is a wrapper for the Bing Maps API ({API Documentation}[http://msdn.microsoft.com/en-us/library/ff701724.aspx]) # that makes it easy to get more information about a location or create maps. # # Currently the class is built for dealing with one obj...
class Api::V1::BooksController < ApplicationController before_action :find_book, only: [:show, :update, :destroy] # GET /api/v1/books def index @books = Book.all end # GET /api/v1/books/:id def show unless @book.nil? @book end end # POST/api/v1/books def create @book = Book.cr...
ActiveAdmin.register Technician do config.sort_order = "first_name_asc" menu parent: I18n.t('admin.security') filter :first_name filter :last_name filter :email index do column :first_name column :last_name column :email default_actions end show do attributes_table_for technician...
require "spec_helper" describe Swow::Client do let(:bnet_eu) { Swow::Client.new(ENV["BNET_API_KEY"], "eu", logger: false) } it "doesn't raise en error with a valid region" do expect { bnet_eu }.not_to raise_error end let(:xx) { Swow::Client.new(ENV["BNET_API_KEY"], "xx", logger: false) } it "raiase an error it...
# -*- encoding : utf-8 -*- class View < ActiveRecord::Base belongs_to :church # serialize :filters, HashSerializer validates :name, presence: true, uniqueness: { scope: [ :church, :applies_to ] } validates :fields, presence: true validates :church, presence: true validates :applies_to, inclusion: { in: %w...
class UsersController < ApplicationController before_action :authenticate_user! before_action :require_account_owner, only: [:edit, :update] def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update(user_params) redirect_to dashboard_path els...
class Merchant < ActiveRecord::Base extend FriendlyId include AASM include GiveGoods::Geocodable friendly_id :name, use: :slugged paginates_per 4*15 mount_uploader :picture, ImageUploader attr_accessor :terms_of_service attr_accessible :name, :description, :website_url, :picture, :terms_of_service, ...
class Student < ActiveRecord::Base belongs_to :section has_many :marks end