text stringlengths 10 2.61M |
|---|
$input = 1350
start_x, start_y = 1, 1
$max_steps = 50
def draw_maze(w, h, visited_set)
puts " "+(0..w-1).to_a.join
(0..h-1).each do |y|
line = "#{y} "+(y<=9?" ":"")
(0..w-1).each do |x|
line += is_wall(x,y) ? "# " : visited_set[coord(x,y)] ? "O " : ". "
end
puts line
end
end
def is_wall(x, y)
return ... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :email, :first_name, :last_name, :organization_id,... |
class Photo
include Mongoid::Document
include Mongoid::Orderable
mount_uploader :image, PhotoUploader
orderable
field :note, type: String
def as_json(options = {})
json = super
json['id'] = json['_id'].to_s
json
end
def previous(limit = 1)
self.class.where(:position.lt => self.pos... |
require 'selenium-webdriver'
require 'yaml'
require 'appium_lib'
@config = YAML.load_file('.config/cucumber.yaml')
#browser can be set at command line, default is Chrome
case ENV['BROWSER']
when 'iphone_simulator'
caps = {
'platformName' => 'iOS',
'platformVersion' => "#{@config['iphone_sim']['ve... |
module Bsale
class DteCode < Base
def all
Bsale.response('dte_codes', self)
end
def find(id:)
id = id.to_i
raise 'You must need to pass an ID' if id.zero?
Bsale.response("dte_codes/#{id}", self)
end
def attributes
%i(
href
id
name
cod... |
# frozen_string_literal: true
module Api::V1::User
class UpdateAction < ::Api::V1::BaseAction
try :deserialize, with: 'params.deserialize', catch: JSONAPI::Parser::InvalidDocument
step :validate, with: 'params.validate'
try :update, catch: Sequel::InvalidOperation
def update(input)
::UpdateEnt... |
class State < ApplicationRecord
belongs_to :country
has_many :user
has_many :vacancies
end
|
class ResetPasswordPageController < CmsController
def index
@presenter = ResetPasswordPresenter.new(params[:reset_password_presenter])
if request.post? && @presenter.valid?
handle_redirect(@presenter.password_request, @obj)
end
end
private
def handle_redirect(status, target)
options = {... |
#
# Cookbook Name: ubercloud
# Recipe:: consul.rb
#
# Search for master IP address
node.override['ubercloud']['is_master'] = true
cluster.store_discoverable()
ubercloud_master = cluster.search(:clusterUID => node['cyclecloud']['cluster']['id']).select { |n|
not n['ubercloud'].nil? and n['ubercloud']['is_master'] =... |
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))
describe "TokyoCabinetRepository with default setup" do
before(:all) do
@r = ClassFactory.new(Repositories::AbstractHelpers,
Repositories::DefaultUuidHelpers,
Repositories::HashHelper, ... |
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.integer :shopsense_id
t.string :brand_name
t.string :product_name
t.integer :price
t.string :sale_price
t.string :retailer
t.string :img_url
t.string :clickUrl
... |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# ... |
class AddArrivalCountToArrival < ActiveRecord::Migration[5.2]
def change
add_column :arrivals, :arrival_count, :integer, default: 0, null: false
add_column :arrivals, :item_id, :integer
add_column :arrivals, :arrival_date, :date
end
end
|
require 'spec_helper'
describe Shoulda::Matchers::Independent::DelegateMethodMatcher do
describe '#description' do
context 'against an instance' do
subject { Object.new }
context 'by default' do
it 'states that it should delegate method to the right object' do
matcher = delegate_me... |
require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your applica... |
Sequel.migration do
up do
create_table(:registers) do
primary_key :id
String :name, index: true, unique: true
end
create_table(:series) do
foreign_key :register_id, :registers, null: false, index: true
primary_key :id
DateTime :time, index: true
BigDecimal :watt_hours,... |
class CreateProductRecommendations < ActiveRecord::Migration
def change
create_table :product_recommendations do |t|
t.string :product_name
t.string :recommended_to
t.string :recommended_product_url
t.string :recommended_product_image_url
t.string :recommended_by
t.text :messag... |
require 'rails_helper'
describe User do
before(:all) do
# In case tests failed in previous pass, remove db account in public database
begin
Util::UserManager.remove_user(User.new(:username=>'spec_test'))
rescue
end
end
it "isn't added if invalid name" do
allow_any_instance_of(described... |
class FontLinuxBiolinum < Formula
version "5.3.0_2012_07_02"
sha256 "24a593a949808d976850131a953c0c0d7a72299531dfbb348191964cc038d75d"
url "https://downloads.sourceforge.net/linuxlibertine/LinLibertineTTF_#{version}.tgz", verified: "downloads.sourceforge.net/linuxlibertine/"
desc "Linux Biolinum"
homepage "ht... |
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} head
# @return {ListNode}
def insertion_sort_list(head)
return [] if head == [] || head == nil
cur = head
dummy = ListNode... |
json.array!(@searches) do |search|
json.extract! search, :id, :food_type_id, :service_type_id, :establishment_type_id, :location_id
json.url search_url(search, format: :json)
end
|
module Admin::PathHistory
# To ensure correct path history working we need to be 100% sure that browser's back button will not use cache
def no_cache!
response.headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires']... |
ActionController::Routing::Routes.draw do |map|
map.resources :forms do |forms|
forms.resources :fields
end
map.resources :testing_queues
# The priority is based upon order of creation: first created -> highest priority.
map.home '', :controller => 'contests', :action => 'index'
map.connect... |
require "vagrant"
require Vagrant.source_root.join("test/unit/base")
require Vagrant.source_root.join("plugins/providers/virtualbox/config")
require Vagrant.source_root.join("plugins/providers/virtualbox/synced_folder")
describe VagrantPlugins::ProviderVirtualBox::SyncedFolder do
let(:machine) do
double("machin... |
require 'rails_helper'
RSpec.describe "teams_integrations/index", type: :view do
# before(:each) do
# assign(:teams_integrations, [
# TeamsIntegration.create!(
# :channel => "Channel",
# :webhook_url => "MyText"
# ),
# TeamsIntegration.create!(
# :channel => "Channel",
... |
# frozen_string_literal: true
module HumanSize
VERSION = '1.1.2'
end
|
require 'amazon/ecs'
module AmazonTags
include Radiant::Taggable
class TagError < StandardError; end;
tag "amazon" do |tag|
if tag.double? then
if tag.attr['asin'] then
aws_response = find_amazon_items(tag)
tag.locals.items = aws_response.items
tag.locals.item = aws_response.i... |
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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
#... |
require 'spec_helper'
describe 'Saving Projects', reset: false do
context 'when adding a name to a project' do
let(:path) { '/search/collections?p=!C179002914-ORNL_DAAC!C179003030-ORNL_DAAC' }
let(:query_re) { /^projectId=(\d+)$/ }
before :all do
Capybara.reset_sessions!
load_page :search
... |
class User < ActiveRecord::Base
#a user should have many microposts
has_many :micropost
end
|
class SectionsController < ApplicationController
layout "admin" # Oznamujem kontroleru, ze ma pouzivat layout "admin"
before_filter :confirm_logged_in
before_filter :find_page, :request_separator
def index
list
render("list")
end
def list
@sections = Section.sorted.where(:page_id => @page.... |
class AddContestAndSexToItriRecords < ActiveRecord::Migration
def change
add_column :itri_records, :contest_id, :integer
add_column :itri_records, :sex, :boolean
end
end
|
module Api
class CategoriesController < ApplicationController
before_action :check_categories
def index
params[:per_page] ||= 100
params[:page] ||= 1
@category = Category
@category = @category.get_parents if params[:only_head_categories]
@category = @category.get_children(params[:get_children]) if p... |
# require_relative 'spec_helper'
# module Ripley
# describe Inquisitor do
# # context "on a blank class" do
# # class MyClass; end
# # context "on an instance" do
# # let(:object){ MyClass.new }
# # it "should return the associated inquisitor" do
# # inquisitor = object... |
require 'test_helper'
require File.expand_path("../../../app/validators/date_format_validator", __FILE__)
class TestModel
include ActiveModel::Validations
attr_accessor :date
validates :date, date_format: true
end
class DateFormatValidatorTest < ActiveSupport::TestCase
def assert_valid_date(date)
t = Te... |
class TheresNoMethod
end
t = TheresNoMethod.new
# below we will check if the Class TheresNoMethod resonds to the first_method
puts ">>>>>>>>>>>>>>>>> " && TheresNoMethod.respond_to?(:first_method)
#false
# The result is false, cause the class TheresNoMethod is empty, and dont have any method until now.
# Now, we'll ... |
# frozen_string_literal: true
windows_provision = <<SCRIPT
# add the bolt user account
($user = New-LocalUser -Name bolt -Password (ConvertTo-SecureString -String bolt -Force -AsPlainText)) | Format-List
# add the bolt user to the 'Remote Management Users' group
Add-LocalGroupMember -Group 'Remote Management Users' -M... |
# frozen_string_literal: true
module Dry
module Logic
module Operations
class Implication < Binary
def type
:implication
end
def operator
:then
end
def call(input)
left_result = left.(input)
if left_result.success?
... |
require_relative "recipe_base"
class Recipe < RecipeBase
PROMPT_KEY = "recipe"
def generate
@_generate ||= openai.completion(
prompt: prompt,
max_tokens: 512,
temperature: 0.4,
stop: "Name:"
).dig("choices").first.dig("text")
end
end
|
class AddIntentIdToInterpretationAliases < ActiveRecord::Migration[5.1]
def change
add_reference :interpretation_aliases, :intent, foreign_key: { on_delete: :cascade }, type: :uuid
end
end
|
#!/usr/bin/env ruby
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of... |
module Envirotech
module Mappable
def self.included(klass)
klass.settings = {
index: {
analysis: {
analyzer:
{ english_analyzer: {
tokenizer: 'standard',
filter: %w(standard asciifolding lowercase snowb... |
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
validates :title, :description, :image_url, presence: true
validates :image_url, format: {with: /\.(png|jpg)\Z/i}
validates :title, :length => {in: 3..350}
end
|
class EvenOdd
def initialize(n)
@n = n.to_s
end
def runlengths
@runlengths ||= @n.scan(/([02468]+|[13579]+)/).flatten.map(&:length)
end
def bad?
return true if runlengths.max > 2
return true if runlengths.length > 2 && runlengths[1...-1].min < 2
false
end
def pattern
return if b... |
#
# Be sure to run `pod lib lint DesignableButton.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "Des... |
# frozen_string_literal: true
require 'spec_helper'
describe 'main_app_integration' do
it 'should use main_app layout' do
# TODO: make a working test with that.
# Changing layout on the fly does not seem to work.
# Monologue.layout = "layouts/application"
# visit root_path
# page.should hav... |
require "rspec/helper"
describe "sprockets helpers" do
let(:env) { Jekyll::Assets::Env.new(stub_jekyll_site) }
it "initializes the helpers" do
Sprockets::Helpers.instance_methods.each do |method|
expect(env.context_class.method_defined?(method)).to be_truthy
end
end
it "uses our digest" do
ex... |
require 'rom/relation/loaded'
require 'rom/commands/graph'
require 'rom/support/deprecations'
module ROM
# Exposes defined gateways, relations and mappers
#
# @api public
class Container
extend Deprecations
include Equalizer.new(:gateways, :relations, :mappers, :commands)
# @return [Hash] configur... |
# encoding: utf-8
require 'logger'
module DCC
module Logger
@@log = ::Logger.new(STDOUT)
@@log.level = ::Logger::FATAL
def self.setLog(log)
class <<log
def context(tag)
tags.push(tag)
yield
ensure
tags.pop
end
def tags
@tags... |
class TeamsController < ApplicationController
before_action :get_team, only: [:select, :show, :edit, :update, :destroy]
before_action :authenticate_user!, only: [:index, :select, :new, :edit, :create, :update, :destroy]
def index
@teams = current_user.groups
end
def select
authorize @team
curre... |
class Publisher < ActiveRecord::Base
has_many :books, dependent: :destroy
after_destroy :log_destroy_action
after_update :log_update_action
after_create :log_create_action
scope :order_by_id, -> {order(id: :asc)}
scope :likes, -> {find_by_sql("SELECT publishers.id, name, user_id AS 'like_from_... |
module Fog
class Bluebox
class Real
# Reboot block
#
# ==== Parameters
# * block_id<~String> - Id of block to reboot
# * type<~String> - Type of reboot, must be in ['HARD', 'SOFT']
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# TO... |
# frozen_string_literal: true
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.[](code)
@cached ||= {}
@cached[code] ||= readonly.find_by(code: code)
end
def self.clear_cache
@cached = {}
true
end
def as_typical_json
as_json(only: self.class.rw_attribu... |
# coding: utf-8
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
def now (year = nil, month = nil, day = nil, hour = nil, minute = nil, second = nil)
@now ||= Horai::now
DateTime.new(year || @now.year,
month || @now.month,
day || @now.day,
hour ... |
require 'spec_helper'
describe Stormpath::Resource::Group, :vcr do
describe "instances should respond to attribute property methods" do
let(:directory) { test_directory }
let(:group) { directory.groups.create name: 'someTestGroup', description: 'someTestDescription' }
after do
group.delete if gr... |
# frozen_string_literal: true
# Item
class Item < ApplicationRecord
has_one_attached :image
end
|
class Album < ActiveRecord::Base
belongs_to :user
has_many :photos
end
|
class EstimatesController < ApplicationController
UBER_BASE_URL = 'https://api.uber.com'
LYFT_BASE_URL = 'https://api.lyft.com'
@lyft_access_token = nil
def show
end
def get
if(params[:brand] == 'uber')
render :json => uber(params[:start_lat], params[:start_lng], params[:end_lat], params[:e... |
class ChangeOrderEvaluatedDefault < ActiveRecord::Migration
def change
change_column :orders, :evaluated, :boolean, default: false
end
end
|
require "spec_helper"
describe "Comments" do
describe "for posts" do
before { @user = login }
let(:post) { create :post }
it "adds comment to post" do
visit post_path(post)
within "#new_comment" do
fill_in "Content", :with => "Wow, you guys rock!"
click_on "Respond"
e... |
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def add_two_numbers(l1, l2)
node = l1
node2 = l2
arr1 = []
arr2 ... |
require 'rails_helper'
describe AuthorizeRequest do
let!(:user) { create :user }
let(:valid_token) { { 'uid' => user.email, 'token' => user.token } }
let(:invalid_token) { { 'uid' => 'invalid', 'token' => 'invalid' } }
context '#call' do
context 'with valid credentials' do
it "should success" do
... |
class CreateEnvironments < ActiveRecord::Migration[5.2]
def change
create_table :environments do |t|
t.boolean :is_student_register_active, null: false, default: false
t.boolean :is_advisors_register_active, null: false, default: false
t.boolean :is_schedules_register_active, null: false, defaul... |
# encoding: utf-8
require "logstash/inputs/base"
require "logstash/namespace"
require "logstash/util/relp"
require "logstash/util/socket_peer"
require "openssl"
# Read RELP events over a TCP socket.
#
# For more information about RELP, see
# <http://www.rsyslog.com/doc/imrelp.html>
#
# This protocol implements applica... |
class CampusSchoolTypeTotalsController < ApplicationController
before_action :set_campus_school_type_total, only: [:show, :edit, :update, :destroy]
# GET /campus_school_type_totals
# GET /campus_school_type_totals.json
def index
@campus_school_type_totals = CampusSchoolTypeTotal.all
end
# GET /campus_... |
module ReversePolishCalculator
# Calculator parses expressions from input and calculates the result using MathEngine
class Calculator
def initialize
@math_engine = MathEngine.new
end
def calculate(input, options = {}, &block)
input = StringIO.new(input) unless input.respond_to? :readline
... |
# frozen_string_literal: true
require "graphql/persisted_queries/hash_generator_builder"
require "graphql/persisted_queries/resolver"
module GraphQL
module PersistedQueries
# Patches GraphQL::Schema to support persisted queries
module SchemaPatch
attr_reader :persisted_query_store, :hash_generator_pro... |
class Lesson < ActiveRecord::Base
attr_accessible :course_id, :description, :is_project, :position, :section_id, :title, :url, :title_url
belongs_to :section
has_one :course, :through => :section
validates_uniqueness_of :position, :message => "Lesson position has already been taken"
def next_lesson
le... |
class AddColumnsToSize < ActiveRecord::Migration[5.2]
def change
add_column :sizes, :size, :integer, null: false, default: 0
end
end
|
# frozen_string_literal: true
require_relative '../../lib/vmfloaty/service'
describe Service do
describe '#initialize' do
it 'store configuration options' do
options = MockOptions.new({})
config = { 'url' => 'http://example.url' }
service = Service.new(options, config)
expect(service.con... |
# frozen_string_literal: true
RSpec.describe Sandbox::Calculators::Divider do
describe '#call' do
it 'works' do
expect(subject.call(4, 2)).to eq(2)
end
it 'returns info when dividing by 0' do
expect(subject.call(4, 0)).to eq("Can't divide by 0")
end
end
end
|
class User < ApplicationRecord
has_secure_password
validates :username, presence: true, length: { minimum: 1 }, uniqueness: true
validates :password, presence: true, length: { minimum: 1 }
def full_name
return "#{ first_name } #{ last_name }"
end
end
|
class AddPaymentStatusToPaypalTransaction < ActiveRecord::Migration
def change
add_column :paypal_transactions, :payment_status, :string
end
end
|
require 'spec_helper'
describe CatalogController do
before do
session[:user]='bob'
end
it "should use CatalogController" do
expect(controller).to be_an_instance_of CatalogController
end
describe "configuration" do
let(:config) { CatalogController.blacklight_config }
describe "search_builde... |
module Antlr4::Runtime
class Utils
def self.num_non_nil(data)
n = 0
return n if data.nil?
i = 0
while i < data.length
o = datap[i]
n += 1 unless o.nil?
i += 1
end
n
end
def self.remove_all_elements(data, value)
return if data.nil?
... |
require 'rails_helper'
RSpec.describe "donors/donations/new", type: :view do
before(:each) do
assign(:donors_donation, Donors::Donation.new())
end
it "renders new donors_donation form" do
render
assert_select "form[action=?][method=?]", donors_donations_path, "post" do
end
end
end
|
class LocalizedGenerator < Rails::Generators::Base
desc "This generator copies a sample localized.yml and creates a concerns for
scopes and site flags on active record models."
argument :sites, :type => :array, :default => ['us:en-US', 'uk:en-UK', 'it:it-IT'], :banner => "site:locale us:en-US"
def create_loc... |
# 1000 Lights
=begin
(Understand the Problem)
Problem: Write a method that takes one argument, the total number of switches, and returns an Array that identifies which lights are on after n repetitions.
Inputs: Integer
Outputs: Array (which switches are still left on)
Questions:
1.
2.
Exp... |
# describe 'comments' do
# describe 'build_with_user' do
#
# let(:user) { User.create email: 'test@test.com' }
# let(:post) { Post.create title: 'Hey' }
# let(:comment_params) { {comment: 'fine'} }
#
# subject(:comment) { post.comments.build_with_user(comment_params, user) }
#
# it 'builds a revie... |
class FontAlegreyaSc < Formula
head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/alegreyasc"
desc "Alegreya SC"
homepage "https://fonts.google.com/specimen/Alegreya+SC"
def install
(share/"fonts").install "AlegreyaSC-Black.ttf"
(share/"fonts... |
class InstitutionsController < ApplicationController
def index
if params[:name]
@institutions = Institution.find(:all, conditions: ['name LIKE ?',"#{params[:name]}"])
else
@institutions = Institution.all
end
respond_to do |format|
format.json { ren... |
class Meeting < ApplicationRecord
extend Enumerize
belongs_to :user
enumerize :commune, in: [:corral, :futrono, :la_union, :lago_ranco, :lanco, :mariquina, :paillaco, :panguipulli, :rio_bueno, :valdivia]
end
|
json.array!(@document_exports) do |document_export|
json.extract! document_export, :id, :export_jid, :exported_at, :repository_id, :file, :export_type, :filtered_ids
json.url document_export_url(document_export, format: :json)
end
|
# frozen_string_literal: true
require 'jiji/configurations/mongoid_configuration'
require 'jiji/utils/value_object'
module Jiji::Model::Agents
class AgentSourceRepository
def all
AgentSource.all.order_by(:name.asc).map { |a| a }
end
def get_by_type(type)
AgentSource.where(type: type).order... |
module Restfulie::Client
module Formatter
module Json
# Receives Json representations and turn them into hashes. Turn
# hashes into json objects.
class Driver
def marshal(obj, rel)
if obj.kind_of? String
obj
else
MultiJson.dump(obj)
e... |
class User < ApplicationRecord
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
extend Enumerize
enumerize :role, in: [:user, :admin, :dev], default: :user, predicates: true
# As admin
has_many :created_teams, foreign_key: :creator_id, class_name: 'Team'
# ... |
require 'nokogiri'
require 'pry'
# gem install nokogiri and pry
# pry allows REPL
# nokogiri turns html into an object
# when this file is run using ruby in terminal (e.g. 'ruby yelp_parser.rb'),
# the binding.pry (at bottom of script) will open a pry shell
# and allow us to have access the script data (i.e. variables... |
require 'spec_helper'
OmniAuth.config.test_mode = true
describe AuthenticationsController do
describe "#create" do
before(:each) do
@user = User.create(:username => "A user", :email => "a_user@example.com", :password => "hungry")
login_user
end
it "creates a new tripit authentication" do
... |
class Translator
attr_reader :encoding, :upper_case, :upper_case_letters, :contraction
def initialize
@encoding = {}
@upper_case = ('A'..'Z').to_a
@upper_case_letters = {}
@contraction = {}
end
def dictionary
@encoding['a'] = ["0.", "..", ".."]
@encoding['b'] = ["0.", "0.", ".."]
@... |
class PessoaFisica < Pessoa
## RELACIONAMENTOS
has_many :dependentes
accepts_nested_attributes_for :dependentes, allow_destroy: true
## VALIDAÇÕES
validates :cpf, :nome, presence: true
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
require 'jwt'
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: generate.rb -k path/to/file -i your_issuer_id [-u a_usernamee]"
opts.on("-h", "--help", "show help") do |h|
options[:help] = opts.banner
end
opts.on("-k KEY", "--key KEY", "path to private key") do |key|
opt... |
# frozen_string_literal: true
class Profile::ItemsController < ApplicationController
before_action :set_profile_item, only: %i[show edit update destroy]
# GET /profile/items
# GET /profile/items.json
def index
# @profile_items = Profile::Item.all
@profile_items = Item.all
end
# GET /profile/items... |
FactoryBot.define do
factory :product do
name {"シャツ"}
description {"良い商品です"}
condition {"1"}
delivery_cost {"1"}
delivery_way {"未定"}
delivery_origin {"1"}
preparatory_days {"1"}
price {"30000"}
user
association :category, factory: :cat... |
class AddVideoUrlToServiceCategory < ActiveRecord::Migration
def change
add_column :service_categories, :video_url, :string
end
end
|
class DashboardController < ApplicationController
def show
@projects = current_user.projects
end
end
|
require 'securerandom'
require 'bcrypt'
class Client < Sequel::Model
one_to_many :shards
#Class methods
def self.validate(client_id_, plaintext_secret)
maybe_client = self.where(:client_id => client_id_).first
if maybe_client && maybe_client.authenticate(plaintext_secret)
return maybe_client
el... |
require 'dm-core'
class CasinoPlayer
include DataMapper::Resource
property :id, Serial
property :name, String
property :money, Integer
# BOMB - Track how well things are going with the Bomb game
property :bombs_solution, String
property :bombs_diffused, Integer
property :bombs_failed, Integer
end |
require 'rails_helper'
RSpec.feature 'Loggin in as employee' do
before do
initialize_app_settings
@employee = create(:employee)
visit '/employees/sign_in'
expect(page).to have_button('Log in')
end
scenario 'with valid credential' do
fill_in 'Email', with: @employee.email
fill_in 'Passwo... |
class Favorite < ActiveRecord::Base
def self.total_pages(condition = nil)
total_count = (condition.present?) ? where(condition).count : all.count
return 0 if total_count <= 10
return total_count / 10 if (total_count % 10) == 0
(total_count / 10 ) + 1
end
def self.page_data(user_id, page_num)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.