text stringlengths 10 2.61M |
|---|
class Idea < ApplicationRecord
validates :title, presence: true
validates :body, presence: true
validates :quality, presence: true
def self.all_descending
all.order("created_at DESC")
end
end
|
class FixRelationshipForCompanyAndEmployees < ActiveRecord::Migration[5.1]
def change
add_column :company_employees, :employee_id, :integer
add_column :company_employees, :unemployee_id, :integer
add_index :company_employees, :employee_id
add_index :company_employees, :unemployee_id
add_index :company_employees, [:employee_id, :unemployee_id], unique: true
end
end
|
module Smtp
class HeaderWithParams < Header
def initialize(key, value, params)
@key = key
@value = value
@params = params
super @key, value_with_params
end
private
def value_with_params
([@value] + converted_params).join(';')
end
def converted_params
@converted_params ||= @params.to_a.select { |_, value| value.present? }
.map { |key, value| "#{key} = #{value}" }
end
end
end
|
require 'yaml'
require 'digest'
class Station
def initialize(config_file_path='./config.yml')
@config_file_path = config_file_path
load_config
end
def config_file_path
@config_file_path
end
def config_file_data
File.open(config_file_path).read
end
def load_config
@config = YAML.load(config_file_data)
end
def config_file_mtime
File.mtime(config_file_path)
end
def config_check_delay
(@config['config_check_delay'] || 30).to_i
end
def exit_if_config_changed?
!!@config['exit_if_config_changed']
end
def check_for_config_change
if @previous_config_mtime
current_config_mtime = config_file_mtime
if @previous_config_mtime != current_config_mtime
puts "Config file changed! Reloading config."
load_config
if exit_if_config_changed?
puts "Exiting."
exit
end
@previous_config_mtime = current_config_mtime
end
else
@previous_config_mtime = config_file_mtime
end
end
def sleep
puts "sleeping for #{config_check_delay} seconds."
super(config_check_delay)
end
end |
class FontLemon < Formula
head "https://github.com/google/fonts/raw/main/ofl/lemon/Lemon-Regular.ttf", verified: "github.com/google/fonts/"
desc "Lemon"
homepage "https://fonts.google.com/specimen/Lemon"
def install
(share/"fonts").install "Lemon-Regular.ttf"
end
test do
end
end
|
# frozen_string_literal: true
require 'rails_helper'
describe Transfer::CreateService, type: :module do
describe '#perform!' do
subject { described_class.perform!(params, user) }
let(:params) do
ActionController::Parameters
.new(
transfer: {
source_account_id: source_account.id,
destination_account_id: source_account.id,
amount: 10
}
)
end
let(:source_account) { create(:user).account }
let(:destination_account) { create(:user).account }
let(:user) { nil }
context 'without any params' do
let(:params) { ActionController::Parameters.new({ transfer: {} }) }
it { expect { subject }.to raise_error(ActionController::ParameterMissing) }
end
context 'without user' do
let(:user) { nil }
it { expect { subject }.to raise_error(User::Unauthorized) }
end
context 'with invalid user' do
let(:user) { destination_account.user }
it { expect { subject }.to raise_error(User::Unauthorized) }
end
context 'with valid user' do
let!(:event) { create :event, amount: 20, account_id: source_account.id }
let(:user) { source_account.user }
it { is_expected.to be_a(Transfer) }
end
end
end
|
ActiveAdmin.register_page "Dashboard" do
menu :priority => 1, :label => proc{ I18n.t("active_admin.dashboard") }
content :title => proc{ I18n.t("active_admin.dashboard") } do
div :class => "blank_slate_container", :id => "dashboard_default_message" do
end
# Here is an example of a simple dashboard with columns and panels.
#
columns do
column do
panel "Recent Products" do
table_for Product.order('prod_id desc').limit 5 do
column("Availability") {|products| products.available}
column("Cake Name"){|products| products.name}
column("Price") {|products| products.price}
end
end
end
end
columns do
column do
panel "Recent Customers" do
table_for Customer.order('cust_ID desc').limit 5 do
column("ID") {|customers| customers.cust_ID}
column("Full Name") {|customers| "#{customers.first_name} #{customers.last_name}"}
column("Address") {|customers| customers.address}
column("Phone Number") {|customers| customers.phonenumber}
end
end
end
end
# column do
# panel "Info" do
# para "Welcome to ActiveAdmin."
# end
# end
# end
end # content
end
|
class TypesController < ApplicationController
def index
@types = Type.paginate(per_page: 10, page: params[:page])
end
def new
@type = Type.new
end
def create
@type = Type.create(type_params)
render "new"
end
private
def type_params
params.require(:type).permit(:name, :desc)
end
end
|
# == Schema Information
#
# Table name: decs_tube_type
#
# id :integer(4) not null, primary key
# name :string(255)
# max_volume :float
#
class DecTubeType < ActiveRecord::Base
has_many :tubes
end
|
class Ride
attr_reader :passenger, :driver, :distance
@@all = []
@@premium = []
def initialize(passenger,driver,distance)
@passenger = passenger
@driver = driver
@distance = distance
@@all << self
current_milage = passenger.rides.inject(0){|sum,ride| sum + ride.distance}
unless Ride.premium.include?(passenger)
Ride.premium << passenger if current_milage > 100
end
end
def self.average_distance
milage = self.all.inject(0){|sum,ride| sum + ride.distance}
milage / self.all.size
end
def self.all
@@all
end
def self.premium
@@premium
end
end |
RSpec.describe 'grafana2::default' do
let(:chef_run) { ChefSpec::SoloRunner.new.converge(described_recipe) }
it 'converges successfully' do
expect(chef_run).to include_recipe(described_recipe)
end
end
|
class State
include Mongoid::Document
field :name, type: String
has_many :cities
end
|
class GardensController < ApplicationController
def show
@garden = Garden.find(params[:id])
@all_vegetables = @garden.vegetables
end
def index
@gardens=Garden.all
end
def new
@gardens = Garden.new
end
def create
@gardens = Garden.new(params.require(:garden).permit(:name, :location))
if @gardens.save
redirect_to gardens_path
else
render "new"
end
end
def update
@gardens = Garden.find(params[:id])
if @gardens.update_attributes(params.require(:garden).permit(:name, :location))
redirect_to gardens_path
else render "edit"
end
end
def destroy
@gardens=Garden.find(params[:id])
@gardens.destroy
redirect_to gardens_path
end
def edit
@garden = Garden.find(params[:id])
end
private
def user_params
params.require(:garden).permit(:name, :location, :name, :quantity, :vegetables)
end
end
|
require 'asciidoctor'
require 'json'
if Gem::Version.new(Asciidoctor::VERSION) <= Gem::Version.new('1.5.1')
fail 'asciidoctor: FAILED: HTML5/Slim backend needs Asciidoctor >=1.5.2!'
end
unless defined? Slim::Include
fail 'asciidoctor: FAILED: HTML5/Slim backend needs Slim >= 2.1.0!'
end
# Add custom functions to this module that you want to use in your Slim
# templates. Within the template you can invoke them as top-level functions
# just like in Haml.
module Slim::Helpers
# URIs of external assets.
FONT_AWESOME_URI = '//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css'
HIGHLIGHTJS_BASE_URI = '//cdnjs.cloudflare.com/ajax/libs/highlight.js/7.4'
MATHJAX_JS_URI = '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_HTMLorMML'
PRETTIFY_BASE_URI = '//cdnjs.cloudflare.com/ajax/libs/prettify/r298'
# Defaults
DEFAULT_HIGHLIGHTJS_THEME = 'github'
DEFAULT_PRETTIFY_THEME = 'prettify'
DEFAULT_SECTNUMLEVELS = 3
DEFAULT_TOCLEVELS = 2
# The MathJax configuration.
MATHJAX_CONFIG = {
tex2jax: {
inlineMath: [::Asciidoctor::INLINE_MATH_DELIMITERS[:latexmath]],
displayMath: [::Asciidoctor::BLOCK_MATH_DELIMITERS[:latexmath]],
ignoreClass: 'nostem|nolatexmath'
},
asciimath2jax: {
delimiters: [::Asciidoctor::BLOCK_MATH_DELIMITERS[:asciimath]],
ignoreClass: 'nostem|noasciimath'
}
}.to_json
VOID_ELEMENTS = %w(area base br col command embed hr img input keygen link meta param source track wbr)
##
# Creates an HTML tag with the given name and optionally attributes. Can take
# a block that will run between the opening and closing tags.
#
# @param name [#to_s] the name of the tag.
# @param attributes [Hash]
# @param content [#to_s] the content; +nil+ to call the block.
# @yield The block of Slim/HTML code within the tag (optional).
# @return [String] a rendered HTML element.
#
def html_tag(name, attributes = {}, content = nil)
attrs = attributes.reject { |_, v|
v.nil? || (v.respond_to?(:empty?) && v.empty?)
}.map do |k, v|
v = v.compact.join(' ') if v.is_a? Array
v = nil if v == true
v = %("#{v}") if v
[k, v] * '='
end
attrs_str = attrs.empty? ? '' : attrs.join(' ').prepend(' ')
if VOID_ELEMENTS.include? name.to_s
%(<#{name}#{attrs_str}>)
else
content ||= yield if block_given?
%(<#{name}#{attrs_str}>#{content}</#{name}>)
end
end
##
# Conditionally wraps a block in an element. If condition is +true+ then it
# renders the specified tag with optional attributes and the given
# block inside, otherwise it just renders the block.
#
# For example:
#
# = html_tag_if link?, 'a', {class: 'image', href: (attr :link)}
# img src='./img/tux.png'
#
# will produce:
#
# <a href="http://example.org" class="image">
# <img src="./img/tux.png">
# </a>
#
# if +link?+ is truthy, and just
#
# <img src="./img/tux.png">
#
# otherwise.
#
# @param condition [Boolean] the condition to test to determine whether to
# render the enclosing tag.
# @param name (see #html_tag)
# @param attributes (see #html_tag)
# @yield (see #html_tag)
# @return [String] a rendered HTML fragment.
#
def html_tag_if(condition, name, attributes = {}, &block)
if condition
html_tag name, attributes, &block
else
yield
end
end
##
# Surrounds a block with strings, with no whitespace in between.
#
# @example
# = surround '[', ']' do
# a href="#_footnote_1" 1
#
# [<a href="#_footnote_1">1</a>]
#
# @param front [String] the string to add before the block.
# @param back [String] the string to add after the block.
# @yield The block of Slim/HTML code to surround.
# @return [String] a rendered HTML fragment.
#
def surround(front, back = front)
[front, yield.chomp, back].join
end
##
# Wraps a block in a div element with the specified class and optionally
# the node's +id+ and +role+(s). If the node's +captioned_title+ is not
# empty, than a nested div with the class "title" and the title's content
# is added as well.
#
# Note: Every node has method +captioned_title+; if it doesn't have a
# caption, then this method returns just a naked title.
#
# @example When @id, @role and @title attributes are set.
# = block_with_title class: ['quoteblock', 'center']
# blockquote =content
#
# <div id="myid" class="quoteblock center myrole1 myrole2">
# <div class="title">Block Title</div>
# <blockquote>Lorem ipsum</blockquote>
# </div>
#
# @example When @id, @role and @title attributes are empty.
# = block_with_title class: 'quoteblock center', style: style_value(float: 'left')
# blockquote =content
#
# <div class="quoteblock center" style="float: left;">
# <blockquote>Lorem ipsum</blockquote>
# </div>
#
# @example When shorthand style for class attribute is used.
# = block_with_title 'quoteblock center'
# blockquote =content
#
# <div class="quoteblock center">
# <blockquote>Lorem ipsum</blockquote>
# </div>
#
# @param attributes [Hash, String] the tag's attributes as Hash),
# or the tag's class if it's not a Hash.
# @param title_position [:top, :bottom] position of the title element.
# @yield The block of Slim/HTML code within the tag (optional).
# @return [String] a rendered HTML fragment.
#
def block_with_title(attributes = {}, title_position = :top, &block)
if attributes.is_a? Hash
klass = attributes.delete(:class)
else
klass = attributes
attributes = {}
end
klass = klass.split(' ') if klass.is_a? String
attributes[:class] = [klass, role].flatten.uniq
attributes[:id] = id
html_tag 'div', attributes do
if captioned_title.nil_or_empty?
yield
else
ary = [ html_tag('div', {class: 'title'}, captioned_title), yield ]
ary.reverse! if title_position == :bottom
ary.compact.join "\n"
end
end
end
##
# Delimite the given equation as a STEM of the specified type.
#
# @param equation [String] the equation to delimite.
# @param type [#to_sym] the type of the STEM renderer (latexmath, or asciimath).
# @return [String] the delimited equation.
#
def delimit_stem(equation, type)
if is_a? ::Asciidoctor::Block
open, close = ::Asciidoctor::BLOCK_MATH_DELIMITERS[type.to_sym]
else
open, close = ::Asciidoctor::INLINE_MATH_DELIMITERS[type.to_sym]
end
unless equation.start_with?(open) && equation.end_with?(close)
equation = [open, equation, close].join
end
equation
end
##
# Formats the given hash as CSS declarations for an inline style.
#
# @example
# style_value(text_align: 'right', float: 'left')
# => "text-align: right; float: left;"
#
# style_value(text_align: nil, float: 'left')
# => "float: left;"
#
# style_value(width: [90, '%'], height: '50px')
# => "width: 90%; height: 50px;"
#
# style_value(width: ['120px', 'px'])
# => "width: 90px;"
#
# style_value(width: [nil, 'px'])
# => nil
#
# @param declarations [Hash]
# @return [String, nil]
#
def style_value(declarations)
decls = []
declarations.each do |prop, value|
next if value.nil?
if value.is_a? Array
value, unit = value
next if value.nil?
value = value.to_s + unit unless value.end_with? unit
end
prop = prop.to_s.gsub('_', '-')
decls << %(#{prop}: #{value})
end
decls.empty? ? nil : decls.join('; ') + ';'
end
def urlize(*segments)
path = segments * '/'
if path.start_with? '//'
@_uri_scheme ||= document.attr 'asset-uri-scheme', 'https'
path = %(#{@_uri_scheme}:#{path}) unless @_uri_scheme.empty?
end
normalize_web_path path
end
##
# @param index [Integer] the footnote's index.
# @return [String] footnote id to be used in a link.
def footnote_id(index = (attr :index))
%(_footnote_#{index})
end
##
# @param index (see #footnote_id)
# @return [String] footnoteref id to be used in a link.
def footnoteref_id(index = (attr :index))
%(_footnoteref_#{index})
end
def icons?
document.attr? :icons
end
def font_icons?
document.attr? :icons, 'font'
end
def nowrap?
'nowrap' if !document.attr?(:prewrap) || option?('nowrap')
end
##
# Returns corrected section level.
#
# @param sec [Asciidoctor::Section] the section node (default: self).
# @return [Integer]
#
def section_level(sec = self)
@_section_level ||= (sec.level == 0 && sec.special) ? 1 : sec.level
end
##
# Returns the captioned section's title, optionally numbered.
#
# @param sec [Asciidoctor::Section] the section node (default: self).
# @return [String]
#
def section_title(sec = self)
sectnumlevels = document.attr(:sectnumlevels, DEFAULT_SECTNUMLEVELS).to_i
if sec.numbered && !sec.caption && sec.level <= sectnumlevels
[sec.sectnum, sec.captioned_title].join(' ')
else
sec.captioned_title
end
end
#--------------------------------------------------------
# block_listing
#
def source_lang
attr :language, nil, false
end
#--------------------------------------------------------
# block_open
#
##
# Returns +true+ if an abstract block is allowed in this document type,
# otherwise prints warning and returns +false+.
def abstract_allowed?
if result = (parent == document && document.doctype == 'book')
puts 'asciidoctor: WARNING: abstract block cannot be used in a document without a title when doctype is book. Excluding block content.'
end
!result
end
##
# Returns +true+ if a partintro block is allowed in this context, otherwise
# prints warning and returns +false+.
def partintro_allowed?
if result = (level != 0 || parent.context != :section || document.doctype != 'book')
puts 'asciidoctor: ERROR: partintro block can only be used when doctype is book and it\'s a child of a book part. Excluding block content.'
end
!result
end
#--------------------------------------------------------
# block_table
#
def autowidth?
option? :autowidth
end
def spread?
'spread' if !(option? 'autowidth') && (attr :tablepcwidth) == 100
end
#--------------------------------------------------------
# block_video
#
# @return [Boolean] +true+ if the video should be embedded in an iframe.
def video_iframe?
['vimeo', 'youtube'].include?(attr :poster)
end
def video_uri
case (attr :poster, '').to_sym
when :vimeo
params = {
autoplay: (1 if option? 'autoplay'),
loop: (1 if option? 'loop')
}
start_anchor = %(#at=#{attr :start}) if attr? :start
%(//player.vimeo.com/video/#{attr :target}#{start_anchor}#{url_query params})
when :youtube
video_id, list_id = (attr :target).split('/', 2)
params = {
rel: 0,
start: (attr :start),
end: (attr :end),
list: (attr :list, list_id),
autoplay: (1 if option? 'autoplay'),
loop: (1 if option? 'loop'),
controls: (0 if option? 'nocontrols')
}
%(//www.youtube.com/embed/#{video_id}#{url_query params})
else
anchor = [(attr :start), (attr :end)].join(',').chomp(',')
anchor.prepend '#t=' unless anchor.empty?
media_uri %(#{attr :target}#{anchor})
end
end
# Formats URL query parameters.
def url_query(params)
str = params.map { |k, v|
next if v.nil? || v.to_s.empty?
[k, v] * '='
}.compact.join('&')
str.prepend('?') unless str.empty?
end
#--------------------------------------------------------
# document
#
##
# Returns HTML meta tag if the given +content+ is not +nil+.
#
# @param name [#to_s] the name for the metadata.
# @param content [#to_s, nil] the value of the metadata, or +nil+.
# @return [String, nil] the meta tag, or +nil+ if the +content+ is +nil+.
#
def html_meta_if(name, content)
%(<meta name="#{name}" content="#{content}">) if content
end
# Returns formatted style/link and script tags for header.
def styles_and_scripts
scripts = []
styles = []
tags = []
stylesheet = attr :stylesheet
stylesdir = attr :stylesdir, ''
default_style = ::Asciidoctor::DEFAULT_STYLESHEET_KEYS.include? stylesheet
linkcss = (attr? :linkcss) || safe >= ::Asciidoctor::SafeMode::SECURE
ss = ::Asciidoctor::Stylesheets.instance
if linkcss
path = default_style ? ::Asciidoctor::DEFAULT_STYLESHEET_NAME : stylesheet
styles << { href: [stylesdir, path] }
elsif default_style
styles << { text: ss.primary_stylesheet_data }
else
styles << { text: read_asset(normalize_system_path(stylesheet, stylesdir), true) }
end
if attr? :icons, 'font'
if attr? 'iconfont-remote'
styles << { href: (attr 'iconfont-cdn', FONT_AWESOME_URI) }
else
styles << { href: [stylesdir, %(#{attr 'iconfont-name', 'font-awesome'}.css)] }
end
end
if attr? 'stem'
scripts << { src: MATHJAX_JS_URI }
scripts << { type: 'text/x-mathjax-config', text: %(MathJax.Hub.Config(#{MATHJAX_CONFIG});) }
end
case attr 'source-highlighter'
when 'coderay'
if (attr 'coderay-css', 'class') == 'class'
if linkcss
styles << { href: [stylesdir, ss.coderay_stylesheet_name] }
else
styles << { text: ss.coderay_stylesheet_data }
end
end
when 'pygments'
if (attr 'pygments-css', 'class') == 'class'
if linkcss
styles << { href: [stylesdir, ss.pygments_stylesheet_name(attr 'pygments-style')] }
else
styles << { text: ss.pygments_stylesheet_data(attr 'pygments-style') }
end
end
when 'highlightjs'
hjs_base = attr :highlightjsdir, HIGHLIGHTJS_BASE_URI
hjs_theme = attr 'highlightjs-theme', DEFAULT_HIGHLIGHTJS_THEME
scripts << { src: [hjs_base, 'highlight.min.js'] }
scripts << { src: [hjs_base, 'lang/common.min.js'] }
scripts << { text: 'hljs.initHighlightingOnLoad()' }
styles << { href: [hjs_base, %(styles/#{hjs_theme}.min.css)] }
when 'prettify'
prettify_base = attr :prettifydir, PRETTIFY_BASE_URI
prettify_theme = attr 'prettify-theme', DEFAULT_PRETTIFY_THEME
scripts << { src: [prettify_base, 'prettify.min.js'] }
scripts << { text: 'document.addEventListener("DOMContentLoaded", prettyPrint)' }
styles << { href: [prettify_base, %(#{prettify_theme}.min.css)] }
end
styles.each do |item|
if item.key?(:text)
tags << html_tag(:style, {}, item[:text])
else
tags << html_tag(:link, rel: 'stylesheet', href: urlize(*item[:href]))
end
end
scripts.each do |item|
if item.key? :text
tags << html_tag(:script, {type: item[:type]}, item[:text])
else
tags << html_tag(:script, type: item[:type], src: urlize(*item[:src]))
end
end
tags.join "\n"
end
#--------------------------------------------------------
# inline_anchor
#
# @return [String, nil] text of the xref anchor, or +nil+ if not found.
def xref_text
str = text || document.references[:ids][attr :refid || target]
str.tr_s("\n", ' ') if str
end
#--------------------------------------------------------
# inline_image
#
# @return [Array] style classes for a Font Awesome icon.
def icon_fa_classes
[ %(fa fa-#{target}),
(%(fa-#{attr :size}) if attr? :size),
(%(fa-rotate-#{attr :rotate}) if attr? :rotate),
(%(fa-flip-#{attr :flip}) if attr? :flip)
].compact
end
# wiki_links
def source_relative_path(file)
file[document.attr('sourcedir', '').length..-1]
#file - document.attr('sourcedir', '')
end
def wiki_link_edit()
document.attr('wiki_link_edit_prefix', 'wikiedit') + source_relative_path(document.attr('docfile', ''))
end
def wiki_link_create()
path =source_relative_path(document.attr('docfile', ''))
path = path[0..path.rindex('/')] # parent directory
document.attr('wiki_link_create_prefix', 'wikicreate') + path
end
end
|
# frozen_string_literal: true
module KeycloakAdapter
class OidcConfiguration
def initialize(issuer:, **opts)
@issuer = issuer
@options = ActiveSupport::OrderedOptions.new.merge(opts)
@configuration = ActiveSupport::OrderedOptions.new.merge(fetch_configuration.symbolize_keys)
@certs = fetch_certs.deep_symbolize_keys
ensure
connection&.close
end
attr_reader :issuer, :certs
delegate :authorization_endpoint, :token_endpoint, :introspection_endpoint, :userinfo_endpoint, :end_session_endpoint, to: :configuration
def to_h
configuration.to_h
end
protected
attr_reader :options, :configuration
def fetch_configuration
fetch_json(options.discovery_path)
end
def fetch_certs
fetch_json(options.certs_path)
end
def connection
@connection ||= Faraday.new(issuer, options.connection_options)
end
def fetch_json(path)
response = connection.get(path) do |request|
request.headers = { 'Content-Type' => 'application/json; charset=utf-8' }
end
JSON.parse(response.body)
end
end
end
|
class AddStatusesToNotifications < ActiveRecord::Migration[5.2]
def change
add_column :notifications, :read, :boolean
add_column :notifications, :read_at, :datetime
add_column :notifications, :delivered, :boolean
add_column :notifications, :delivered_at, :datetime
add_column :notifications, :delivery_receipt, :string
end
end
|
############################################################
#
# Name: Chad Ohl
# Assignment: Character Fight - Character Class
# Date: 5/20/14
# Class: CIS 283
#
############################################################
class Character
include Enumerable
attr_reader(:name,:race,:hit_points,:current_hit_points,:strength,:agility,:weapon,:armor)
def initialize(name,race,hit_points,strength,agility,weapon,armor)
@name = name
@race = race
@hit_points = hit_points.to_i
@current_hit_points = hit_points.to_i
@strength = strength.to_i
@agility = agility.to_i
@weapon = weapon
@armor = armor
end
def to_s
return "\nName: #{@name}\n"\
"Race: #{@race}\n"\
"Hitpoints: #{@hit_points}\n"\
"Strength: #{@strength}\n"\
"Agility: #{@agility}\n"\
"Weapon: #{@weapon}\n"\
"Armor: #{@armor}"
end
def current_status
return "#{@name} has #{@current_hit_points}hp/#{@hit_points}hp"
end
def reduce_hits(damage)
@current_hit_points -= damage
if @current_hit_points <= 0
return "#{self} is dead."
else
return @current_hit_points
end
end
def revive_character
@current_hit_points = @hit_points
end
def <=>(other)
return self <=> other
end
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
porteno = Restaurant.create(name: 'Porteno', address: '4 Rue Lepic', category: 'italian')
mama = Restaurant.create(name: 'Mama Pizza', address: '50 Rue Dorée', category: 'italian', phone_number: '+3346456')
pekin = Restaurant.create(name: 'Pekin Food', address: '5R5 Contonese Street', category: 'chinese')
tartare = Restaurant.create(name: 'Les Tontons', address: '4 Rue R.Losserand', category: 'french')
moule = Restaurant.create(name: 'Moulue', address: '4 Rue Atomium', category: 'beligian')
Review.create(content: 'Great', rating: 4, restaurant_id: porteno.id)
Review.create(content: 'Average', rating: 2, restaurant_id: mama.id)
Review.create(content: 'Bad', rating: 1, restaurant_id: pekin.id)
Review.create(content: 'Amazing', rating: 5, restaurant_id: tartare.id)
Review.create(content: 'Disgusting', rating: 0, restaurant_id: moule.id)
|
# Copyright 2014 Square Inc.
#
# 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.
# Controller for working with {Project Projects}.
class ProjectsController < ApplicationController
before_filter :find_project, except: [:index, :create]
before_filter :admin_login_required, only: [:update, :rekey]
before_filter :owner_login_required, only: :destroy
respond_to :html, :json
# HTML
# ====
#
# Displays a home page with summary information of {Bug Bugs} across the
# current user's Projects, a filterable list of project Memberships, and
# information about the current User.
#
# Routes
# ------
#
# * `GET /`
#
# JSON
# ====
#
# Searches for Projects with a given prefix.
#
# Routes
# ------
#
# * `GET /projects.json`
#
# Query Parameters
# ----------------
#
# | | |
# |:--------|:--------------------------------------------------------------------------------|
# | `query` | Only includes those projects whose name begins with `query` (case-insensitive). |
def index
respond_to do |format|
format.html # index.html.rb
format.json do
@projects = Project.includes(:owner).order('id DESC').limit(25)
@projects = @projects.prefix(params[:query]) if params[:query].present?
render json: decorate(@projects).to_json
end
end
end
# If the Project has a default {Environment}, and the `show_environments`
# parameter is not set, redirects to the Bug list for that Environment.
#
# Otherwise, displays information about the Project and a list of
# Environments.
#
# Routes
# ------
#
# * `GET /projects/:id`
#
# Path Parameters
# ---------------
#
# | | |
# |:-----|:--------------------|
# | `id` | The Project's slug. |
def show
if @project.default_environment && params[:show_environments].blank?
return redirect_to project_environment_bugs_url(@project, @project.default_environment)
end
respond_with @project
end
# Creates a new Project owned by the current User.
#
# Routes
# ------
#
# * `POST /projects.json`
#
# Body Parameters
# ---------------
#
# The body can be JSON- or form URL-encoded.
#
# | | |
# |:----------|:--------------------------------------|
# | `project` | Parameterized hash of Project fields. |
def create
project_attrs = project_params_for_creation.merge(validate_repo_connectivity: true)
@project = current_user.owned_projects.create(project_attrs)
respond_with @project do |format|
format.json do
if @project.valid?
render json: decorate(@project).to_json, status: :created
else
render json: {project: @project.errors.as_json}.to_json, status: :unprocessable_entity
end
end
end
end
# Displays a page where the user can see information about how to install
# Squash into his/her project, and how to configure his/her project for Squash
# support.
#
# Routes
# ------
#
# * `GET /projects/:id/edit`
#
# Path Parameters
# ---------------
#
# | | |
# |:-----|:--------------------|
# | `id` | The Project's slug. |
def edit
respond_with @project
end
# Edits a Project. Only the Project owner or an admin can modify a project.
#
# Routes
# ------
#
# * `PATCH /projects/:id.json`
#
# Path Parameters
# ---------------
#
# | | |
# |:-----|:--------------------|
# | `id` | The Project's slug. |
#
# Body Parameters
# ---------------
#
# The body can be JSON- or form URL-encoded.
#
# | | |
# |:----------|:--------------------------------------|
# | `project` | Parameterized hash of Project fields. |
def update
@project.assign_attributes project_params_for_update.merge(validate_repo_connectivity: true)
@project.uses_releases_override = true if @project.uses_releases_changed?
@project.save
respond_with @project
end
# Generates a new API key for the Project.. Only the Project owner can do
# this.
#
# Routes
# ------
#
# * `PATCH /projects/:id/rekey`
#
# Path Parameters
# ---------------
#
# | | |
# |:-----|:--------------------|
# | `id` | The Project's slug. |
def rekey
@project.create_api_key
@project.save!
redirect_to edit_project_url(@project), flash: {success: t('controllers.projects.rekey.success', name: @project.name, api_key: @project.api_key)}
end
# Deletes a Project, and all associated Environments, Bugs, Occurrences, etc.
# Probably want to confirm before allowing the user to do this.
#
# Routes
# ------
#
# * `DELETE /projects/:id.json`
#
# Path Parameters
# ---------------
#
# | | |
# |:-----|:--------------------|
# | `id` | The Project's slug. |
def destroy
@project.destroy
redirect_to root_url, flash: {success: t('controllers.projects.destroy.deleted', name: @project.name)}
end
private
def find_project
@project = Project.find_from_slug!(params[:id])
class << @project
include ProjectAdditions
end
end
def decorate(projects)
decorate_block = ->(project) {
project.as_json.merge(
owner: project.owner.as_json.merge(url: user_url(project.owner)),
role: current_user.role(project),
url: project_url(project),
join_url: join_project_my_membership_url(project))
}
if projects.kind_of?(Enumerable) || projects.kind_of?(ActiveRecord::Relation)
projects.map &decorate_block
else
decorate_block.(projects)
end
end
def admin_permitted_parameters
[:name, :repository_url, :default_environment, :default_environment_id,
:filter_paths, :filter_paths_string, :whitelist_paths,
:whitelist_paths_string, :commit_url_format, :critical_mailing_list,
:all_mailing_list, :critical_threshold, :sender, :locale,
:sends_emails_outside_team, :trusted_email_domain, :pagerduty_enabled,
:pagerduty_service_key, :always_notify_pagerduty, :uses_releases,
:disable_message_filtering, :blamer_type, :digest_in_asset_names]
end
def project_params_for_creation
params.require(:project).permit(*admin_permitted_parameters)
end
def project_params_for_update
case current_user.role(@project)
when :owner
params.require(:project).permit(*(admin_permitted_parameters + [:owner_id]))
when :admin
project_params_for_creation
end
end
module ProjectAdditions
def filter_paths_string() filter_paths.join("\n") end
def whitelist_paths_string() whitelist_paths.join("\n") end
def filter_paths_string=(str) self.filter_paths = (str || '').split(/\r?\n/) end
def whitelist_paths_string=(str) self.whitelist_paths = (str || '').split(/\r?\n/) end
def owner_username() owner.username end
def owner_username=(name) self.owner = User.find_by_username(name) end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Every Vagrant development environment requires a box. You can search for
# boxes at https://atlas.hashicorp.com/search.
BOX_IMAGE = "centos8"
ES_COUNT = 8
MA_COUNT = 3
NODE_COUNT = 4
Vagrant.configure("2") do |config|
#设置所有 guest 使用相同的静态 dns 解析 /etc/hosts
#config.vm.provision :hosts, :sync_hosts => true
#设置所有虚拟机的操作系统
config.vm.box = BOX_IMAGE
#用 vagrant 默认密钥对 ssh 登录
config.ssh.insert_key = false
#config.vm.sync_folder "/home/martinliu/test/nfs", "/vagrant", type: "nfs"
# 用于部署 Elasticsearch 服务器的集群
(1..ES_COUNT).each do |i|
config.vm.define "es#{i}" do |es_config|
es_config.vm.hostname = "es#{i}.zenlab.local"
es_config.vm.network :public_network, ip: "10.0.0.#{i + 80}", bridge: "thunderbolt0", dev: "thunderbolt0"
es_config.vm.provider :libvirt do |vb|
vb.memory = 2048
vb.cpus = 2
end
#es_config.vm.provision :shell, path: "pre-install-es#{i}.sh"
es_config.vm.provision :shell, path: "es-cd.sh"
end
end
# 用于部署 Elasticsearch 服务器的集群 : 单节点、三节点对等、三节点专用 master
(1..MA_COUNT).each do |i|
config.vm.define "ma#{i}" do |ma_config|
ma_config.vm.hostname = "ma#{i}.zenlab.local"
#ma_config.vm.network :private_network, ip: "192.168.50.#{i + 10}"
ma_config.vm.network :public_network, ip: "10.0.0.#{i + 40}", bridge: "thunderbolt0", dev: "thunderbolt0"
ma_config.vm.provider :libvirt do |vb|
vb.memory = 2048
vb.cpus = 2
end
ma_config.vm.provision :shell, path: "es-3m.sh"
end
end
# 用于部署 Kibana、Logstash 、APM Server、Heatbeat 和 Packetbeat
config.vm.define "lk" do |lk_config|
lk_config.vm.hostname = "lk.zenlab.local"
lk_config.vm.network :private_network, ip: "192.168.50.70"
lk_config.vm.provider :virtualbox do |vb|
vb.memory = 2048
vb.cpus = 1
end
lk_config.vm.provision :shell, path: 'pre-install-lk.sh'
end
# 两个被管理节点,用于部署监控应用和各种 Beats 代理
(1..NODE_COUNT).each do |i|
config.vm.define "node#{i}" do |node_config|
node_config.vm.hostname = "node#{i}.zenlab.local"
#node_config.vm.network :private_network, ip: "192.168.50.#{i + 80}"
node_config.vm.network :public_network, ip: "10.0.0.#{i + 60}", bridge: "thunderbolt0", dev: "thunderbolt0"
node_config.vm.provider :virtualbox do |vb|
vb.memory = 1024
vb.cpus = 1
end
#node_config.vm.provision :shell, path: 'pre-install-beats.sh'
end
end
# Install avahi on all machines
config.vm.provision "shell", inline: <<-SHELL
sh -c "echo 'Welcome to Elastic Stack!'"
SHELL
end
|
require 'test_helper'
class TimeRangeTest < ActiveSupport::TestCase
def test_correct_time_range
range = TimeRange.new 'begin' => Time.now, 'end' => Time.now - 1.day
range.valid?
assert range.errors[:end]
end
end
|
require 'rubygems'
require 'spec/rake/spectask'
task :default => :spec
desc "Run specs"
Spec::Rake::SpecTask.new do |t|
t.spec_files = FileList['spec/**/*_spec.rb']
t.spec_opts = %w(-fs --color)
end
desc "Run all examples with RCov"
Spec::Rake::SpecTask.new(:rcov) do |t|
t.spec_files = FileList['spec/**/*_spec.rb']
t.rcov = true
end
begin
require 'jeweler'
Jeweler::Tasks.new do |gemspec|
gemspec.name = "redis-model"
gemspec.summary = "Minimal models for Redis"
gemspec.description = "Minimal model support for redis-rb. Directly maps ruby properties to model_name:id:field_name keys in redis. Scalar, list and set properties are supported."
gemspec.email = "voloko@gmail.com"
gemspec.homepage = "http://github.com/voloko/redis-model"
gemspec.authors = ["Vladimir Kolesnikov"]
gemspec.add_dependency("redis", [">= 0.0.1"])
gemspec.add_development_dependency("rspec", [">= 1.2.8"])
end
rescue LoadError
puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
end
|
#!/usr/bin/ruby
=begin
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
=end
require 'rubygems'
require 'json'
require "rexml/document"
include REXML
require 'awesome_print'
def usage (message = nil)
if message
puts "ERROR: #{message}"
end
puts """Usage: 1pass2keepass.rb 1pass.1pif
Convert a 1Password export file to XML suitable for import into KeepassX.
"""
exit
end
input_file = ARGV[0]
unless ARGV[0]
usage
end
unless File.exists?(input_file)
usage "File '#{input_file}' does not exist"
end
lines = File.open(input_file).readlines()
lines.reject! {|l| l =~ /^\*\*\*/}
groups = {}
username = password = nil
lines.each do |line|
entry = JSON.parse(line)
if entry['trashed']
next
end
group_name = entry['typeName'].split('.')[-1]
if not groups.has_key?(group_name)
groups[group_name] = {}
end
title = entry['title']
case group_name
when 'Password','Database','UnixServer','Email','GenericAccount'
groups[group_name][title] = {
:url => nil,
:username => entry['secureContents']['username'],
:password => entry['secureContents']['password'],
} unless (groups[group_name].has_key?(title) and groups[group_name][title]['updatedAt'].to_i > entry['updatedAt'].to_i)
when 'Regular', 'SavedSearch', 'Point'
next
when 'WebForm'
entry['secureContents']['fields'].each do |field|
case field['designation']
when 'username'
username = field['value']
when 'password'
password = field['value']
end
end
groups[group_name][title] = {
:url => entry['location'],
:username => username,
:password => password,
} unless (groups[group_name].has_key?(title) and groups[group_name][title]['updatedAt'].to_i > entry['updatedAt'].to_i)
username = password = nil
else
puts "Don't know how to handle records of type #{entry['typeName']} yet."
end
end
doc = Document.new
database = doc.add_element 'database'
groups.each do |group_name, entries|
next if entries.empty?
group = database.add_element 'group'
case group_name
when 'Password'
group.add_element('title').text = 'Password'
group.add_element('icon').text = '0'
when 'WebForm'
group.add_element('title').text = 'Internet'
group.add_element('icon').text = '1'
when 'Email'
group.add_element('title').text = 'Email'
group.add_element('icon').text = '19'
when 'Database'
group.add_element('title').text = 'Database'
group.add_element('icon').text = '6'
when 'UnixServer'
group.add_element('title').text = 'Unix Server'
group.add_element('icon').text = '30'
when 'GenericAccount'
group.add_element('title').text = 'Generic Account'
group.add_element('icon').text = '20'
end
entries.each do |title, entry|
entry_node = group.add_element 'entry'
entry_node.add_element('username').text = entry[:username]
entry_node.add_element('password').text = entry[:password]
entry_node.add_element('title').text = title
entry_node.add_element('url').text = entry[:url]
end
end
doc << XMLDecl.new
doc.write($stdout)
|
class CreateContactrequests < ActiveRecord::Migration[5.0]
def change
create_table :contactrequests do |t|
t.string :firstname
t.string :lastname
t.string :phone_number
t.string :email
t.string :company
t.string :contact_message
t.timestamps
end
end
end
|
class ActiveRecord::Relation
# Asserts that the collection contains exactly one record, and returns it.
#
# If the collection is empty, it raises <tt>ActiveRecord::NoRecordFound</tt>.
# If the collection contains more than one record, it raises
# <tt>ActiveRecord::MultipleRecordsFound</tt>.
def one!
case size
when 0
raise ActiveRecord::NoRecordFound
when 1
first
else
raise ActiveRecord::MultipleRecordsFound
end
end
end
|
class Artist < ActiveRecord::Base
has_many :songs
has_many :genres, through: :songs
def slug
@name = name.downcase.split.join("-")
end
def self.find_by_slug(name)
new_artist = nil
@artists = Artist.all
@artists.each do |artist|
artist.slug == name ? new_artist = artist : nil
end
new_artist
end
end |
require "rails_helper"
RSpec.describe User, type: :model do
describe "Validations:" do
before(:each) do
@user = User.new(
first_name: "Joe",
last_name: "Shmoe",
email: "Joe@shmoe.com",
password: "test",
password_confirmation: "test",
)
end
it "the user is valid with proper fields" do
expect(@user).to be_valid
end
it "is required to have a password" do
@user.password = nil
expect(@user).to_not be_valid
expect(@user.errors.full_messages.include?("Password can't be blank")).to be_truthy
end
it "is required to have a password confirmation" do
@user.password_confirmation = nil
expect(@user).to_not be_valid
expect(@user.errors.full_messages.include?("Password confirmation can't be blank")).to be_truthy
end
it "is required to have an email" do
@user.email = nil
expect(@user).to_not be_valid
expect(@user.errors.full_messages.include?("Email can't be blank")).to be_truthy
end
it "is required to have a first name" do
@user.first_name = nil
expect(@user).to_not be_valid
expect(@user.errors.full_messages.include?("First name can't be blank")).to be_truthy
end
it "is required to have a last name" do
@user.last_name = nil
expect(@user).to_not be_valid
expect(@user.errors.full_messages.include?("Last name can't be blank")).to be_truthy
end
it "is invalid if password != password_confirmation" do
@user.password_confirmation = "else"
expect(@user).to_not be_valid
expect(@user.errors.full_messages.include?("Password confirmation doesn't match Password")).to be_truthy
end
it "should have a unique email" do
@user.save
@user2 = User.new(
first_name: "Joe",
last_name: "Shmoe",
email: "Joe@shmoe.com",
password: "test",
password_confirmation: "test",
)
expect(@user2).to_not be_valid
expect(@user2.errors.full_messages.include?("Email has already been taken")).to be_truthy
end
it "should have case insensitive emails" do
@user.save
@user2 = User.new(
first_name: "Joe",
last_name: "Shmoe",
email: "JOE@SHMOE.COM",
password: "test",
password_confirmation: "test",
)
expect(@user2).to_not be_valid
expect(@user2.errors.full_messages.include?("Email has already been taken")).to be_truthy
end
end
describe "Password" do
it "is greater than the minimum length" do
@user = User.new(
first_name: "Joe",
last_name: "Shmoe",
email: "Joe@shmoe.com",
password: "a",
password_confirmation: "a",
)
expect(@user).to_not be_valid
expect(@user.errors.full_messages.any? { |err| err.include?("Password is too short") }).to be_truthy
end
end
describe ".authenticate_with_credentials" do
before(:each) do
@user = User.create(
first_name: "Joe",
last_name: "Shmoe",
email: "JOE@SHMOE.COM",
password: "test",
password_confirmation: "test",
)
end
it "should return a User instance for viable login" do
user = User.authenticate_with_credentials("JOE@SHMOE.COM", "test")
expect(user).to be_kind_of User
end
it "should return nil for invalid email" do
user = User.authenticate_with_credentials("no@SHMOE.COM", "test")
expect(user).to be_nil
end
it "should return nil for invalid password" do
user = User.authenticate_with_credentials("JOE@SHMOE.COM", "wrongPassword")
expect(user).to be_nil
end
it "should return a User if the entered email has leading or ending spaces" do
user = User.authenticate_with_credentials(" JOE@SHMOE.COM ", "test")
expect(user).to be_kind_of User
end
it "should return a User if the entered email is in the wrong case" do
user = User.authenticate_with_credentials("JoE@ShmOe.Com", "test")
expect(user).to be_kind_of User
end
end
end
|
class CreateDoubts < ActiveRecord::Migration[6.1]
def change
create_table :doubts do |t|
t.references :user, index: true, foreign_key: true
t.string :title
t.text :description
t.integer :state, default: 0, index: true
t.timestamps
end
end
end
|
class Library < ActiveRecord::Base
audited
belongs_to :library_category
belongs_to :state
belongs_to :city
has_many :attachments, :as => :attachmentable, dependent: :destroy
accepts_nested_attributes_for :attachments, allow_destroy: true, :reject_if => proc { |attrs| attrs[:attachment].blank? }
has_many :words_keys, dependent: :destroy
accepts_nested_attributes_for :words_keys, allow_destroy: true, :reject_if => proc { |attrs| attrs[:word].blank? }
validates_presence_of :library_category_id, :title, :author_name
scope :find_by_text, lambda { |value| where('title LIKE ? or author_name LIKE ? or edition LIKE ? or publishing_company LIKE ? or document_name lIKE ? or description LIKE ?', "%#{value}%", "%#{value}%", "%#{value}%", "%#{value}%", "%#{value}%", "%#{value}%" ) if value != nil && value != '' }
scope :find_by_state, lambda { |value| where('state_id = ?', value ) if value != nil && value != '' }
end
|
require 'rails_helper'
RSpec.describe 'Users', type: :feature do
let!(:user) { FactoryBot.create(:user, name: "Yamada", email: "yamada@sample.com") }
it 'user can login' do
visit new_user_session_path
fill_in 'メールアドレス', with: user.email
fill_in 'パスワード', with: user.password
click_button 'ログイン'
expect(page).to have_content 'ログインしました。ようこそ!!!'
end
end |
class FontImFellEnglish < Formula
head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/imfellenglish"
desc "IM Fell English"
homepage "https://fonts.google.com/specimen/IM+Fell+English"
def install
(share/"fonts").install "IMFeENit28P.ttf"
(share/"fonts").install "IMFeENrm28P.ttf"
end
test do
end
end
|
class SubscribersController < ApplicationController
def index
@subscribers = Subscriber.all
end
def new
@subscriber = Subscriber.new()
end
def edit
@subscriber = Subscriber.find(params[:id])
end
def show
@subscriber = Subscriber.find(params[:id])
end
def create
@subscriber = Subscriber.new(subscriber_params)
if !@subscriber.idNumber.include? '-'
@subscriber.idNumber = @subscriber.idNumber.insert(2, '-').insert(7, '-')
end
if @subscriber.valid?
@subscriber.course = @subscriber.course.upcase
@subscriber.firstName = @subscriber.firstName.titleize
@subscriber.lastName = @subscriber.lastName.titleize
end
if @subscriber.save
flash[:success] = "Subscriber successfully registered!"
redirect_to subscribers_path
else
flash[:danger] = @subscriber.errors.full_messages
render 'new'
end
end
def destroy
@subscriber = Subscriber.find(params[:id])
@subscriber.destroy
redirect_to subscribers_path
end
def update
@subscriber = Subscriber.find(params[:id])
if @subscriber.update(subscriber_params)
flash[:success] = "Subscriber information successfully updated!"
redirect_to subscribers_path
else
render 'edit'
end
end
private
def subscriber_params
params.require(:subscriber).permit(:firstName, :idNumber, :lastName, :email, :controlNumber, :college, :contactNumber, :course)
end
end
|
require_relative 'questionsdatabase'
require_relative 'modelbase'
class Like < ModelBase
def self.likers_for_question_id(question_id)
likers = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
users.*
FROM
users
JOIN
question_likes ON users.id = question_likes.user_id
WHERE
question_likes.question_id = ?
SQL
raise "No likers for that question" if likers.empty?
likers.map{|user| User.new(user)}
end
def self.num_likes_for_question_id(question_id)
likes = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
count(*) AS num_likes
FROM
question_likes
WHERE
question_id = ?
SQL
likes.first['num_likes']
end
def self.liked_questions_for_user_id(user_id)
likes = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
questions.*
FROM
questions
JOIN
question_likes ON questions.id = question_likes.question_id
WHERE
question_likes.user_id = ?
SQL
likes.map{ |q| Question.new(q) }
end
def self.most_liked_questions(n)
questions = QuestionsDatabase.instance.execute(<<-SQL, n)
SELECT
questions.*
FROM
questions
JOIN
question_likes ON questions.id = question_likes.question_id
GROUP BY
questions.id, questions.title, questions.body, questions.user_id
ORDER BY
COUNT(*)
LIMIT
?
SQL
questions.map { |q| Question.new(q) }
end
attr_accessor :id, :user_id, :question_id
def initialize(options)
@id = options['id']
@user_id = options['user_id']
@question_id = options['question_id']
end
end
|
class Customer
attr_reader :name, :wallet, :age, :drunk_level
def initialize(name, wallet, age)
@name = name
@wallet = wallet
@age = age
@drinks = []
@drunk_level = 0
end
def buy_drink(drink)
@wallet -= drink.price
@drunk_level += drink.units
end
def buy_food(food)
@wallet -= food.price
@drunk_level -= food.rejuvenation_level
end
end
|
class RubyocracyController < ApplicationController
def index
@page_title = 'Welcome to Rubyocracy'
@stories = Story.ordered.paginate :page => params[:page], :include => [:site, :categories], :per_page => 20
respond_to do |format|
format.html { render 'stories/index' }
format.xml { render :xml => @stories }
format.rss { render :layout => false }
end
end
def trending
@page_title = 'Trending Stories'
render 'stories/trending_stories'
end
def hide_notice
cookies[:notice_hidden] = "1"
render :nothing => true
end
def categorized
@stories = Story.ordered.tagged_with(params[:id]).paginate :page => params[:page], :include => [:site, :categories], :per_page => 20
end
end
|
require "rails_helper"
RSpec.describe GovukDesignSystem::CheckboxesHelper, type: :helper do
describe "#govukCheckboxes" do
it "returns the correct HTML for the default example" do
html = helper.govukCheckboxes({
idPrefix: "waste",
name: "waste",
fieldset: {
legend: {
text: "Which types of waste do you transport?",
isPageHeading: true,
classes: "govuk-fieldset__legend--l"
}
},
hint: {
text: "Select all that apply."
},
items: [
{
value: "carcasses",
text: "Waste from animal carcasses",
disable_ghost: true
},
{
value: "mines",
text: "Waste from mines or quarries",
disable_ghost: true
},
{
value: "farm",
text: "Farm or agricultural waste",
disable_ghost: true
}
]
})
expect(html).to match_html(<<~HTML)
<div class="govuk-form-group">
<fieldset class="govuk-fieldset" aria-describedby="waste-hint">
<legend class="govuk-fieldset__legend govuk-fieldset__legend--l">
<h1 class="govuk-fieldset__heading">
Which types of waste do you transport?
</h1>
</legend>
<div id="waste-hint" class="govuk-hint">
Select all that apply.
</div>
<div class="govuk-checkboxes" data-module="govuk-checkboxes">
<div class="govuk-checkboxes__item">
<input class="govuk-checkboxes__input" id="waste" name="waste" type="checkbox" value="carcasses">
<label class="govuk-label govuk-checkboxes__label" for="waste">
Waste from animal carcasses
</label>
</div>
<div class="govuk-checkboxes__item">
<input class="govuk-checkboxes__input" id="waste-2" name="waste" type="checkbox" value="mines">
<label class="govuk-label govuk-checkboxes__label" for="waste-2">
Waste from mines or quarries
</label>
</div>
<div class="govuk-checkboxes__item">
<input class="govuk-checkboxes__input" id="waste-3" name="waste" type="checkbox" value="farm">
<label class="govuk-label govuk-checkboxes__label" for="waste-3">
Farm or agricultural waste
</label>
</div>
</div>
</fieldset>
</div>
HTML
end
it "adds ghost inputs by default as required by Rails" do
# NOTE: https://github.com/UKGovernmentBEIS/govuk-design-system-rails/README.md#component-implementations
html = helper.govukCheckboxes({
idPrefix: "waste",
name: "waste",
fieldset: {
legend: {
text: "Which types of waste do you transport?",
isPageHeading: true,
classes: "govuk-fieldset__legend--l"
}
},
hint: {
text: "Select all that apply."
},
items: [
{
value: "carcasses",
text: "Waste from animal carcasses",
},
{
value: "mines",
text: "Waste from mines or quarries",
},
{
value: "farm",
text: "Farm or agricultural waste",
}
]
})
expect(html).to match_html(<<~HTML)
<div class="govuk-form-group">
<fieldset class="govuk-fieldset" aria-describedby="waste-hint">
<legend class="govuk-fieldset__legend govuk-fieldset__legend--l">
<h1 class="govuk-fieldset__heading">
Which types of waste do you transport?
</h1>
</legend>
<div id="waste-hint" class="govuk-hint">
Select all that apply.
</div>
<div class="govuk-checkboxes" data-module="govuk-checkboxes">
<input type="hidden" value="0" name="waste">
<div class="govuk-checkboxes__item">
<input class="govuk-checkboxes__input" id="waste" name="waste" type="checkbox" value="carcasses">
<label class="govuk-label govuk-checkboxes__label" for="waste">
Waste from animal carcasses
</label>
</div>
<input type="hidden" value="0" name="waste">
<div class="govuk-checkboxes__item">
<input class="govuk-checkboxes__input" id="waste-2" name="waste" type="checkbox" value="mines">
<label class="govuk-label govuk-checkboxes__label" for="waste-2">
Waste from mines or quarries
</label>
</div>
<input type="hidden" value="0" name="waste">
<div class="govuk-checkboxes__item">
<input class="govuk-checkboxes__input" id="waste-3" name="waste" type="checkbox" value="farm">
<label class="govuk-label govuk-checkboxes__label" for="waste-3">
Farm or agricultural waste
</label>
</div>
</div>
</fieldset>
</div>
HTML
end
end
end
|
Rails.application.routes.draw do
devise_for :users, :controllers => { registrations: 'users/registrations' }
root to: "recipes#index"
get '/' => 'recipes#index'
get '/recipes' => 'recipes#index'
get '/recipes/new' => 'recipes#new'
get '/recipes/pending' => 'recipes#pending'
patch '/recipes/:id/approval_status/:approval_status' => 'recipes#update'
post '/recipes' => 'recipes#create'
get '/recipes/:id' => 'recipes#show'
get '/recipes/:id/edit' => 'recipes#edit'
patch '/recipes/:id' => 'recipes#update'
delete '/recipes/:id' => 'recipes#destroy'
get '/favorited_user_recipes/:id' => 'favorited_user_recipes#show'
post '/favorited_user_recipes/recipes/:recipe_id' => 'favorited_user_recipes#create'
delete '/favorited_user_recipes/recipes/:recipe_id' => 'favorited_user_recipes#destroy'
namespace :api do
namespace :v1 do
resources :recipes
resources :moods
resources :favorited_user_recipes
get '/recipeimage' => 'recipes#recipeimage'
end
end
end
|
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
Rake::TestTask.new do |t|
t.libs << 'test'
t.pattern = 'test/*_test.rb'
t.verbose = true
end
# Generate the RDoc documentation
Rake::RDocTask.new { |rdoc|
rdoc.rdoc_dir = 'doc'
rdoc.title = "LDAP ActiveRecord Gateway"
rdoc.options << '--line-numbers' << '--inline-source'
rdoc.template = "#{ENV['template']}.rb" if ENV['template']
rdoc.rdoc_files.include('README', 'lib/**/*.rb')
}
desc 'Default: run tests.'
task :default => ['test']
|
require 'rails_helper'
RSpec.feature 'Deleting vacation request' do
before do
initialize_app_settings
@employee = create(:employee)
login_as(@employee, scope: :employee)
@vacation_request = create(:vacation_request, requester: @employee)
visit admin_vacation_requests_path
end
scenario 'should has list of Empty requests' do
expect(VacationRequest.count).to eq(1)
expect(page).to have_content(@vacation_request.starts_on.strftime('%d-%m-%Y'))
find('.delete-link').click
expect(page).to have_content('Request was deleted.')
expect(VacationRequest.count).to eq(0)
expect(page).not_to have_content(@vacation_request.starts_on.strftime('%d-%m-%Y'))
end
end
|
class Periodicity
ONCE = 0
DAILY = 1
WEEKLY = 2
FORTNIGHTLY = 3
MONTHLY = 4
BIMONTHLY = 5
QUARTERLY = 6
BIANNUALLY = 7
ANNUALLY = 8
def self.options_hash
{ '--Select frequency--' => '', 'Once' => ONCE, 'Daily' => DAILY, 'Weekly' => WEEKLY, 'Fortnightly' => FORTNIGHTLY,
'Monthly' => MONTHLY, 'Bimonthly' => BIMONTHLY, 'Quarterly' => QUARTERLY, 'Biannually' => BIANNUALLY,
'Annually' => ANNUALLY }
end
def self.as_string(constant)
# hash.key(value) => key
self.options_hash.key(constant)
end
end
|
require 'rails_helper'
RSpec.describe 'Merchant API' do
before(:all) do
@merchants = create_list(:merchant, 5)
end
def get_merchant(id)
get "/api/v1/merchants/#{id}"
expect(response).to be_successful
expect(response.content_type).to eq 'application/json'
expect(response.status).to eq 200
@body = JSON.parse(response.body)
end
it 'returns one merchant' do
merchant = @merchants.first
get_merchant merchant.id
body = @body['data']
expect(body['id'].to_i).to eq merchant.id
expect(body['type']).to eq 'merchant'
expect(body['attributes']['name']).to eq merchant.name
end
it 'returns 404 if merchant cant be found' do
get '/api/v1/merchants/0'
expect(response).to be_not_found
body = JSON.parse(response.body)
expect(body['message']).to eq 'Not Found'
expect(body['error']).to match_array ['Could not find Merchant by this id => 0']
end
end |
class Game < ActiveRecord::Base
attr_accessible :correct_answers_count, :earned_points, :current_question_index
has_many :assignments
has_many :questions, through: :assignments
belongs_to :user
serialize :answered_right, Array
def answer_question(question, answer)
success = false
if question.answered_right? answer
self.correct_answers_count += 1
self.earned_points += question.points_to_earn
self.user.add_points(question.points_to_earn)
self.user.save
self.answered_right << question.id
success = true
end
success
end
def has_ended?
current_question_index >= questions.size
end
def self.select_questions_for_user(amount, user)
# Find questions already seen
attempted_questions_ids = Attempt.where(user_id: user.id).map { |a| a.question_id }
# Fix query bug
attempted_questions_ids = [-31337] if attempted_questions_ids.empty?
# Find new questions
new_questions = Question.find(:all, :conditions => ["id NOT IN (?)", attempted_questions_ids])
questions = new_questions.shuffle[0...amount]
# If there's not enough unseen questions, fill the array with old questions. Then reset history.
remaining = amount - questions.size
if remaining > 0
oldest_attempts = attempted_questions_ids[0...remaining]
old_questions = Question.find(:all, :conditions => ["id IN (?)", oldest_attempts])
questions = questions | old_questions
Attempt.delete_all(user_id: user.id)
end
questions
end
def badges_ids_earned_by_user
BadgesSash.where("sash_id = ? AND created_at > ?", self.user.sash_id, self.created_at).map(&:badge_id)
end
def badges_earned
badges_ids_earned_by_user.collect { |id| Badge.find(id) }
end
end
|
class ApplicationController < ActionController::API
include CanCan::ControllerAdditions
include Authenticable
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit( :email, :password, :password_confirmation , roles: [] ) }
end
end
|
require 'hyperclient/attributes'
require 'hyperclient/link_collection'
require 'hyperclient/resource_collection'
module Hyperclient
# Public: Represents a resource from your API. Its responsability is to
# ease the way you access its attributes, links and embedded resources.
class Resource
extend Forwardable
# Public: Returns the attributes of the Resource as Attributes.
attr_reader :attributes
# Public: Returns the links of the Resource as a LinkCollection.
attr_reader :links
# Public: Returns the embedded resource of the Resource as a
# ResourceCollection.
attr_reader :embedded
# Public: Delegate all HTTP methods (get, post, put, delete, options and
# head) to its self link.
def_delegators :self_link, :get, :post, :put, :delete, :options, :head
# Public: Initializes a Resource.
#
# representation - The hash with the HAL representation of the Resource.
# entry_point - The EntryPoint object to inject the configutation.
def initialize(representation, entry_point)
@links = LinkCollection.new(representation['_links'], entry_point)
@embedded = ResourceCollection.new(representation['_embedded'], entry_point)
@attributes = Attributes.new(representation)
@entry_point = entry_point
end
def inspect
"#<#{self.class.name} self_link:#{self_link.inspect} attributes:#{@attributes.inspect}>"
end
private
# Internal: Returns the self Link of the Resource. Used to handle the HTTP
# methods.
def self_link
@links['self']
end
end
end
|
class FileReader
def read(file_name: )
@raw_file_text = File.read(File.join(File.dirname(__FILE__), file_name))
end
end |
class Backoffice::SendMailController < ApplicationController
# Nuff said
# POST /backoffice/sendmail
def send_mail
@mail_params = set_params_send_mail
begin
AdminMailer.message_mail(current_admin,@mail_params).deliver_now
@notify_flag = 'success'
@notify_message = 'E-mail enviado com sucesso'
rescue
# TODO log error somewhere
@notify_flag = 'error'
@notify_message = 'Erro ao enviar e-mail'
end
end
# Retrieves the e-mail from the provided user
# GET "/backoffice/sendmail/1"
def get_user_mail_data
@admin = Admin.find(params['id'])
end
private
def set_params_send_mail
params.require(:send_mail).permit('recipient-text', 'subject-text', 'message-text')
end
end
|
module Gitorinox
class GithubAPI
def initialize(login, password)
@client ||= Github.new(login: login, password: password)
end
def matched_repositories(match)
result = []
@client.activity.watching.watched.each_page do |page|
page.each do |repo|
if match
result << repo if repo.name.match(match)
else
result << repo
end
end
end
result
end
def unwatch(repository)
@client.activity.watching.delete(user: repository.owner.login, repo: repository.name)
end
def authenticated_username
@client.users.get.login
end
end
end |
class CreateAssistentAppointments < ActiveRecord::Migration[5.0]
def change
create_table :assistent_appointments do |t|
t.integer :person_id
t.references :appointment, foreign_key: true
t.text :obs
t.timestamps
end
end
end
|
#
# Cookbook Name:: squid
# Recipe:: default
#
# Copyright 2012, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
package "squid" do
action :install
not_if "test -f /etc/init.d/squid"
end
execute "squid.conf" do
command "echo http_port 3128 transparent >> /etc/squid/squid.conf"
action :run
not_if "cat /etc/squid/squid.conf | grep transparent"
end
cookbook_file "/root/iptables.sh" do
source "iptables.sh"
mode "0755"
not_if "test -f /root/iptables.sh"
end
execute "iptables.sh" do
command "./root/iptables.sh"
action :run
not_if "iptables --list -t nat | grep 3128"
end
service "squid" do
action [:enable, :start]
end
#
|
module Effect
class BloodClaws
attr_reader :family
attr_reader :hit_chance
attr_reader :damage_type
attr_reader :damage
attr_reader :name
attr_reader :parent
attr_reader :costs
attr_reader :armour_pierce
def initialize(parent, damage = 6)
@costs = {ap: 1}
@parent = parent
@family = :special
@hit_chance = 100
@damage_type = :special
@damage = damage
@armour_pierce = 0
@name = parent.name
end
def weapon_intent(intent)
intent.weapon = self
intent.add_cost :blood_claws, self.method(:setup_claws)
return intent
end
def setup_claws(action, intent)
if action == :possible? # need to apply before charge attacks!
case intent.entity.nexus_class
when 'Pariah'
damage_types = [[:slashing, 60], [:piercing, 25], [:impact, 10], [:unholy, 5]]
when 'Infernal Behemoth'
damage_types = [[:slashing, 35], [:fire, 35], [:piercing, 20], [:unholy, 10]]
when 'Doom Howler'
damage_types = [[:slashing, 25], [:death, 25], [:cold, 25], [:piercing, 15], [:unholy, 10]]
when 'Void Walker'
damage_types = [[:slashing, 25], [:death, 25], [:piercing, 25], [:unholy, 25]]
when 'Redeemed'
damage_types = [[:slashing, 60], [:piercing, 25], [:holy, 15]]
else
damage_types = [[:slashing, 60], [:piercing, 25], [:impact, 10], [:unholy, 5]] # some other class D:
end
rnd_max = damage_types.inject(0) { |sum, itm| sum + itm[1] }
roll = rand(1..rnd_max)
damage_types.each do |possibility|
roll -= possibility[1]
unless roll > 0
intent.damage_type = possibility[0]
break
end
end
end
true
end
def post_soak_damage_multiplier
0.75
end
def describe
"#{@name.to_s} is a special (Blood Claws) weapon that has a variable damage type."
end
def save_state
['BloodClaws', @damage]
end
end
end |
class Admin::CitiesController < ApplicationController
before_action :authenticate_user!
authorize_resource
before_action :load_model, only: [:edit, :update, :destroy]
def index
@cities = City.order("name")
end
def new
@city = City.new
end
def create
@city = City.new city_params
if @city.save
redirect_to admin_cities_path, notice: "Город успешно добавлен!"
else
render :new
end
end
def edit
end
def update
if @city.update city_params
redirect_to admin_cities_path, notice: "Город успешно обновлен!"
else
render :edit
end
end
def destroy
@city.destroy
redirect_to admin_cities_path, notice: "Город успешно удален!"
end
private
def load_model
@city = City.find params[:id]
end
def city_params
params.require(:city).permit(:name, :region_id)
end
end
|
class Quest < ActiveRecord::Base
belongs_to :user
belongs_to :trail
belongs_to :trail_location
validates :trail_location_id, :trail_id, :user_id, :presence => true
validates :trail_location_id, :uniqueness => { :scope => [:trail_id, :user_id] }
scope :done, where(:done => true)
scope :todo, where(:done => false)
end |
#!/usr/bin/env ruby
# Copyright (c) 2009-2011 VMware, Inc.
#
# This script is used to backup mysql instances used in MyaaS.
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", __FILE__)
require 'bundler/setup'
require 'vcap_services_base'
$:.unshift(File.expand_path("../../lib", __FILE__))
require 'mysql2'
module VCAP
module Services
module Mysql
end
end
end
class VCAP::Services::Mysql::Backup < VCAP::Services::Base::Backup
SYSTEM_DB = %w(mysql information_schema)
IGNORE_DB = %w(test)
def default_config_file
File.join(File.dirname(__FILE__), '..', 'config', 'mysql_backup.yml')
end
def backup_db
opts = {
:service_name => @config["service_name"],
:backup_cmd => @config["backup_cmd"],
:host => @config["mysql"]["host"],
:port => @config["mysql"]["port"],
:user => @config["mysql"]["user"],
:passwd => @config["mysql"]["pass"],
:backup_path => @config["backup_base_dir"],
:compress_cmd => @config["compress_cmd"],
}
missing_opts = opts.keys.select{|key| opts[key] == nil}
unless missing_opts.empty?
echo "Missing required configuration items #{missing_opts.inspect}",true
return 1
end
# Optional socket config
opts[:socket] = @config["mysql"]["socket"]
# Optional backup timeout config, default is no timeout
opts[:timeout] = @config["timeout"] || 0
conn = Mysql2::Client.new(:host => opts[:host], :username => opts[:user], :password => opts[:passwd], :database => 'mysql', :port => opts[:port].to_i, :socket => opts[:socket])
result = conn.query("show databases;")
dbs = []
result.each {|db| dbs << db["Database"] }
current_time = Time.now
echo "Begin backup at #{current_time}"
success, failed, ignored = [0,0,0]
dbs.each do |name|
result = exe_backup_db(opts.merge({:name => name, :ts => current_time}))
case result
when 0
success += 1
when 1
failed += 1
when -1
ignored += 1
else
end
raise Interrupt, "Interrupted" if @shutdown
end
echo "Backup begins at #{current_time} complete. Success: #{success}. Failed #{failed}. Ignored #{ignored}."
0
end
def exe_backup_db(opts)
backup_cmd, compress_cmd, name, ts =
%w(backup_cmd compress_cmd name ts).map{|k| opts[k.to_sym]}
if IGNORE_DB.include?(name)
echo "Ignore backup database #{name}."
return -1
elsif SYSTEM_DB.include?(name)
# for system database, dir structure looks like \backups\<service-name>\
# <db-name>\<seconds_since_epoc>\<node_id>\<service specific data>
full_path = get_dump_path(name, :mode => 1, :time => ts)
else
# dir structure looks like \backups\<service-name>\<aa>\<bb>\<cc>\
# <aabbcc-rest-of-instance-guid>\<seconds_since_epoc>\<service specific data>
full_path = get_dump_path(name, :time => ts)
end
opts.merge!({:full_path => full_path})
# options substitution
backup_cmd = opts.keys.inject(backup_cmd) do|cmd, key|
cmd.gsub(":"+key.to_s, opts[key].to_s)
end
compress_cmd = opts.keys.inject(compress_cmd) do|cmd, key|
cmd.gsub(":"+key.to_s, opts[key].to_s)
end
on_err = Proc.new do |cmd, code, msg|
echo "CMD '#{cmd}' exit with code: #{code}. Message: #{msg}",true
cleanup(full_path)
end
t1 = Time.now
FileUtils.mkdir_p(full_path) unless File.exists?(full_path)
res = CMDHandle.execute("#{backup_cmd};#{compress_cmd}", opts[:timeout].to_i, on_err)
t2 = Time.now
echo "Backup for db #{name} complete in #{t2-t1} seconds."
return res ? 0:1
rescue => e
echo "Erorr when backup db #{opts[:name]}. #{e.backtrace.join("\n")}",true
cleanup(full_path)
return 1
end
def cleanup(path)
FileUtils.rm_rf(path) if path
end
end
VCAP::Services::Mysql::Backup.new.start
|
mydir = File.expand_path(File.dirname(__FILE__))
begin
require 'psych'
rescue LoadError
end
require 'i18n'
I18n.load_path += Dir[File.join(mydir, 'locales', '*.yml')]
I18n.reload!
module NameGenerator
class Base
attr_writer :locale
def initialize(options={})
self.locale = options[:locale]
end
def locale
@locale || I18n.locale.downcase
end
def name_data(options={})
translate "name_generator.#{options.fetch(:key, @key)}"
end
def max_probability
name_data.values.max
end
def fetch(key)
@key = key
r = rand(1..max_probability)
name_data.
select { |k,v| v >= r }.keys.sample.
to_s.gsub("\302\240", ' ').strip
end
def translate(key)
I18n.translate key, locale: locale, default: {}
end
def has_standalone_names?
name_data( key: :standalone_name ).any?
end
def only_standalone_names?
name_data( key: :first_name ).empty? || name_data( key: :last_name ).empty?
end
def has_middle_names?
name_data( key: :middle_name ).any?
end
end
end
require "name_generator/version"
require "name_generator/first_name"
require "name_generator/middle_name"
require "name_generator/last_name"
require "name_generator/standalone_name"
require "name_generator/name"
|
choices = { 'noun' => %w(man elf orc hobbit dwarf goblin),
'transitive_verb' => %w(stabs kicks ignites hugs trips throws),
'intransitive_verb' => %w(cries yelps collapses roars smiles rebounds),
'adverb' => %w(clumsily drunkenly skillfully cautiously bravely mightily),
'adjective' => %w(gigantic sleepy screaming enraged homesick confused)
}
text = File.read 'madlibs_input.txt'
words = text.split
madlibs_array = words.map do |word|
if word.start_with?('[') && word.include?(']')
punctuation = word.end_with?(']') ? '' : word[-1]
choices[word[1..(word.index(']') - 1)]].sample + punctuation
else
word
end
end
puts madlibs_array.join(' ')
|
# == Schema Information
#
# Table name: services_users
#
# id :integer not null, primary key
# service_id :integer
# organization_id :integer
# phone :string(255)
# cost :integer
# showing_time :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class ServicesUserSerializer < ActiveModel::Serializer
attributes :id, :service, :cost, :showing_time
has_many :services
end
|
class TorBrowser < Cask
url 'https://www.torproject.org/dist/torbrowser/3.5/TorBrowserBundle-3.5-osx32_en-US.zip'
homepage 'https://www.torproject.org/projects/torbrowser.html'
version '3.5'
sha1 '0b7645421c0afa42fa1e2860f3aa1d978f5d8aed'
link 'TorBrowserBundle_en-US.app'
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
ENV["LC_ALL"] = "en_US.UTF-8"
Vagrant.configure("2") do |config|
# config.vm.box_check_update = true
# config.vbguest.auto_update = false
config.vm.network "private_network", type: "dhcp"
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
vb.cpus = 1
end
config.vm.synced_folder ".", "/vagrant", disabled: true
if Vagrant.has_plugin?('vagrant-cachier')
config.cache.scope = :box
config.cache.auto_detect = true
config.cache.enable :apt
config.cache.enable :apt_lists
end
if Vagrant.has_plugin?('vagrant-hostmanager')
config.hostmanager.enabled = true
config.hostmanager.manage_host = true
config.hostmanager.manage_guest = true
config.hostmanager.ignore_private_ip = false
config.hostmanager.include_offline = true
end
config.vm.define "stretch" do |stretch|
stretch.vm.box = "debian/contrib-stretch64"
stretch.vm.network "private_network", ip: "172.28.128.3"
stretch.vm.hostname = "stretch.phps.vm"
stretch.hostmanager.aliases = %(munin.stretch.phps.vm)
stretch.vm.provision "ansible" do |ansible|
ansible.playbook = "playbook.yml"
ansible.verbose = true
ansible.limit = "all"
ansible.become = true
ansible.compatibility_mode = "2.0"
end
end
end
|
module OneDBFsck
def init_cluster
cluster = @data_cluster = {}
@db.fetch("SELECT oid, name FROM cluster_pool") do |row|
cluster[row[:oid]] = {}
cluster[row[:oid]][:name] = row[:name]
cluster[row[:oid]][:hosts] = []
cluster[row[:oid]][:datastores] = Set.new
cluster[row[:oid]][:vnets] = Set.new
end
end
def check_fix_cluster
cluster = @data_cluster
create_table(:cluster_pool, :cluster_pool_new)
@db.transaction do
@db.fetch("SELECT * from cluster_pool") do |row|
cluster_id = row[:oid]
doc = Document.new(row[:body])
# Hosts
hosts_elem = doc.root.elements.delete("HOSTS")
hosts_new_elem = doc.root.add_element("HOSTS")
cluster[cluster_id][:hosts].each do |id|
id_elem = hosts_elem.elements.delete("ID[.=#{id}]")
if id_elem.nil?
log_error("Host #{id} is missing from Cluster " <<
"#{cluster_id} host id list")
end
hosts_new_elem.add_element("ID").text = id.to_s
end
hosts_elem.each_element("ID") do |id_elem|
log_error("Host #{id_elem.text} is in Cluster " <<
"#{cluster_id} host id list, but it should not")
end
# Datastores
ds_elem = doc.root.elements.delete("DATASTORES")
ds_new_elem = doc.root.add_element("DATASTORES")
cluster[cluster_id][:datastores].each do |id|
id_elem = ds_elem.elements.delete("ID[.=#{id}]")
if id_elem.nil?
log_error("Datastore #{id} is missing from Cluster " <<
"#{cluster_id} datastore id list")
end
ds_new_elem.add_element("ID").text = id.to_s
if @db.fetch("SELECT * FROM cluster_datastore_relation " <<
"WHERE cid=#{cluster_id} AND oid=#{id}").empty?
log_error("Table cluster_datastore_relation is " <<
"missing relation cluster #{cluster_id}, " <<
"datastore #{id}")
@db[:cluster_datastore_relation].insert(
cid: cluster_id,
oid: id
)
end
end
ds_elem.each_element("ID") do |id_elem|
log_error("Datastore #{id_elem.text} is in Cluster " <<
"#{cluster_id} datastore id list, but " <<
"it should not")
end
# VNets
vnets_elem = doc.root.elements.delete("VNETS")
vnets_new_elem = doc.root.add_element("VNETS")
cluster[cluster_id][:vnets].each do |id|
id_elem = vnets_elem.elements.delete("ID[.=#{id}]")
if id_elem.nil?
log_error("VNet #{id} is missing from Cluster " <<
"#{cluster_id} vnet id list")
end
vnets_new_elem.add_element("ID").text = id.to_s
if @db.fetch("SELECT * FROM cluster_network_relation " <<
"WHERE cid=#{cluster_id} AND oid=#{id}").empty?
log_error("Table cluster_network_relation is " <<
"missing relation cluster #{cluster_id}, " <<
"vnet #{id}")
@db[:cluster_network_relation].insert(
cid: cluster_id,
oid: id
)
end
end
vnets_elem.each_element("ID") do |id_elem|
log_error("VNet #{id_elem.text} is in Cluster " <<
"#{cluster_id} vnet id list, but it should not")
end
row[:body] = doc.root.to_s
# commit
@db[:cluster_pool_new].insert(row)
end
end
# Rename table
@db.run("DROP TABLE cluster_pool")
@db.run("ALTER TABLE cluster_pool_new RENAME TO cluster_pool")
end
def check_fix_cluster_relations
cluster = @data_cluster
@db.transaction do
create_table(:cluster_datastore_relation,
:cluster_datastore_relation_new)
@db.fetch("SELECT * from cluster_datastore_relation") do |row|
if (cluster[row[:cid]][:datastores].count(row[:oid]) != 1)
log_error("Table cluster_datastore_relation contains " <<
"relation cluster #{row[:cid]}, datastore " <<
"#{row[:oid]}, but it should not")
else
@db[:cluster_datastore_relation_new].insert(row)
end
end
@db.run("DROP TABLE cluster_datastore_relation")
@db.run("ALTER TABLE cluster_datastore_relation_new " <<
"RENAME TO cluster_datastore_relation")
end
log_time()
@db.transaction do
create_table(:cluster_network_relation,
:cluster_network_relation_new)
@db.fetch("SELECT * from cluster_network_relation") do |row|
if (cluster[row[:cid]][:vnets].count(row[:oid]) != 1)
log_error("Table cluster_network_relation contains " <<
"relation cluster #{row[:cid]}, " <<
"vnet #{row[:oid]}, but it should not")
else
@db[:cluster_network_relation_new].insert(row)
end
end
@db.run("DROP TABLE cluster_network_relation")
@db.run("ALTER TABLE cluster_network_relation_new " <<
"RENAME TO cluster_network_relation")
end
end
end
|
class S3Storage
def self.url(m)
"#{CLOUDFRONT_BASE_URL}/#{s3_key(m)}"
end
def self.s3_key(m)
"#{m.app}/#{m.context}/#{m.locale}/#{m.file_name}"
end
def invalidate_cloudfront_caching(m)
$cf.create_invalidation({
distribution_id: CLOUDFRONT_DISTRIBUTION_ID,
invalidation_batch: {
paths: {
quantity: 1,
items: [S3Storage.url(m) + "*"],
},
caller_reference: S3Storage.url(m)
},
})
end
#
# These three methods manage a binary medium on S3.
# When called from a Medium instance, the instance and/or the changes have
# not yet been written to the DB.
#
def self.create_medium(m)
bucket = $s3.bucket S3_BUCKET
raise "S3 bucket #{S3_BUCKET} doesn't exist" unless bucket.exists?
object = bucket.put_object(
key: s3_key(m),
body: Base64.decode64(m.payload),
content_type: m.content_type
)
raise "S3 media couldn't be created" unless object.exists?
end
def self.update_medium(m)
bucket = $s3.bucket S3_BUCKET
raise "S3 bucket #{S3_BUCKET} doesn't exist" unless bucket.exists?
object = bucket.put_object(
key: s3_key(m),
body: Base64.decode64(m.payload),
content_type: m.content_type
)
raise "S3 media couldn't be updated" unless object.exists?
invalidate_cloudfront_caching(m)
end
def self.delete_medium(m)
bucket = $s3.bucket S3_BUCKET
raise "S3 bucket #{S3_BUCKET} doesn't exist" unless bucket.exists?
object = bucket.object(s3_key(m))
return unless object.exists?
object.delete
invalidate_cloudfront_caching(m)
end
end
|
class FontIosevkaSs13 < Formula
version "18.0.0"
sha256 "74f34822c7ba73455d876543f0720145bc7f88ccef4b38d1ff3dd1e96a386a4f"
url "https://github.com/be5invis/Iosevka/releases/download/v#{version}/ttc-iosevka-ss13-#{version}.zip"
desc "Iosevka SS13"
desc "Sans-serif, slab-serif, monospace and quasi‑proportional typeface family"
homepage "https://github.com/be5invis/Iosevka/"
def install
(share/"fonts").install "iosevka-ss13-bold.ttc"
(share/"fonts").install "iosevka-ss13-extrabold.ttc"
(share/"fonts").install "iosevka-ss13-extralight.ttc"
(share/"fonts").install "iosevka-ss13-heavy.ttc"
(share/"fonts").install "iosevka-ss13-light.ttc"
(share/"fonts").install "iosevka-ss13-medium.ttc"
(share/"fonts").install "iosevka-ss13-regular.ttc"
(share/"fonts").install "iosevka-ss13-semibold.ttc"
(share/"fonts").install "iosevka-ss13-thin.ttc"
end
test do
end
end
|
require 'open-uri'
require 'nokogiri'
module Services
class TacoBellScraper
MENU_URI = 'http://www.tacobell.com/nutrition/information'
ROW = 'tbody tr'
CATEGORY = 'nutStatCategoryRow'
def menu
@menu ||= scrape_menu
end
private
def scrape_menu
with_http_error_handling do
rows = fetch_rows
current_category = ''
items = rows.reduce(Set.new) do |a, e|
name = clean(e.child.text)
if category?(e)
current_category = name
else
item = find_or_create_item(name, a)
item.categories << current_category
end
a
end
convert(items)
end
end
def with_http_error_handling
yield
rescue OpenURI::HTTPError => e
logger.error(e.message)
[]
end
def fetch_rows
@rows ||= Nokogiri.HTML(open(MENU_URI)).css(ROW)
end
def category?(row)
row.attributes['class'] && row.attributes['class'].value == CATEGORY
end
def find_or_create_item(name, existing_items)
found = existing_items.find { |r| r.name == name }
unless found
new = OpenStruct.new(name: name, categories: Set.new)
existing_items << new
end
found || new
end
def convert(items)
items.each { |i| i.categories = i.categories.to_a }.to_a
end
def clean(name)
name.delete('®™')
.gsub(/Menu/, '')
.gsub(/\*.+/m, '')
.strip
.split
.join(' ')
end
end
end
|
class PostsController < ApplicationController
before_filter :require_authentication, :except => [:index, :show, :archive, :articles, :media]
def show
if params[:permalink]
@post = Post.find_by_permalink(params[:permalink])
else
@post = Post.find(params[:id])
end
end
def edit
@post = Post.find(params[:id])
if request.post?
@post.update_attributes(params[:post])
@post.auto_tag! if @post.tag_list.blank?
end
render(:layout => 'dashboard')
end
def delete
@post = Post.find(params[:id])
@post.destroy
redirect_to(manage_articles_url)
end
def archive
@posts = @stream.posts.find(:all, :include => [:service], :conditions => ["services.identifier = 'articles'"])
end
def new
@post = Post.new(params[:post])
if request.post?
@post.is_draft = true
@post.service = Service.find_or_create_by_identifier('articles')
@post.stream = @stream
@post.save
@post.auto_tag! if @post.tag_list.blank?
redirect_to(edit_post_url(:id => @post.id)) and return
end
render(:layout => 'dashboard')
end
def articles
@articles = @stream.articles.find(:all, :limit => 10)
respond_to do |format|
format.rss
format.atom
format.html do
require_authentication
render(:layout => 'dashboard')
end
end
end
def index
if params[:tag_name].blank?
#
@posts = Post.paginate(:all, :per_page => 20, :page => params[:page], :conditions => ["is_deleted IS false"], :order => 'published_at DESC')
#@posts = @stream.posts.paginate(:all, :limit => 12)
else
@posts = Post.find_tagged_with(params[:tag_name], :conditions => 'is_draft IS FALSE AND is_deleted IS FALSE', :limit => 20)
end
respond_to(:html, :rss, :atom)
end
def manage
@posts = Post.find(:all, :include => [:service], :conditions => ["services.identifier != 'articles'"], :order => 'posts.id DESC')
render(:layout => 'dashboard')
end
def media
@media_posts = Post.paginate(:all,
:per_page => 12,
:page => params[:page],
:include => [:medias],
:conditions => ["is_deleted IS false AND medias.id IS NOT NULL"],
:order => 'posts.created_at DESC')
end
end
|
module Paymark
class Object
def initialize(attributes)
attributes.each do |key, value|
send("#{key_map(key)}=", value_map(key, value))
end
end
def self.build(array_or_hash)
if array_or_hash.is_a? Array
array_or_hash.map do |hash|
self.new(hash)
end
else
self.new(array_or_hash)
end
end
def key_map(key)
snake_case key.to_s
end
def value_map(key, value)
value
end
def method_missing(name, *args)
puts "Missing Property #{name} #{args}"
# fail unless Rails.env.production?
end
def snake_case(string)
string.gsub(/::/, '/')
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr('-', '_')
.downcase
end
end
end
|
class Api::V1::UsersController < ApplicationController
def signup
result = sign_able params
if result[:valid]
@user = User.new(
:username => params[:username],
:lastname => params[:lastname],
:firstname => params[:firstname],
:password => params[:password],
:user_type => params[:user_type]
)
@user.save!
if @user.valid?
render json: { :message => "Successful", :valid => true}
else
render status: 400, json: { :message => "Unsuccessful", :valid => false}
end
else
render status: 400, json: result
end
end
def login
if params[:username].present? && params[:password].present?
@user = User.find_by(username: params[:username])
if @user && @user.authenticate(params[:password])
token = encode_token({user_id: @user.id , time: (Time.now.to_f * 1000).to_i})
@user.token = token
@user.save!
render json: {
:message => "logged in successfully",
token: token,
user: @user.as_json(:except => [:password_digest, :token ])
}
else
render status: 401, json: { :message => "wrong name or password" }
end
else
render status: 401, json: { :message => "name or password field is missing" }
end
end
def logout
unless params[:id].present?
render status: 401
return
end
@user = User.find_by(id: params[:id])
if @user == nil
render status: 400
return
end
@user.token = nil
if @user.save!
render status: 200
else
render status: 400
end
end
def sign_able param
unless param[:username].present?
return { :message => "username is missing", :valid => false}
end
unless param[:lastname].present?
return { :message => "lastname is missing", :valid => false}
end
unless param[:firstname].present?
return { :message => "firstname is missing", :valid => false}
end
unless param[:user_type].present?
return { :message => "type is missing", :valid => false}
end
unless param[:password].present?
return { :message => "password is missing", :valid => false}
end
unless param[:confirm_password].present?
return { :message => "confirm password is missing", :valid => false}
end
if (param[:confirm_password] != param[:password])
return { :message => "password doesn't match", :valid => false}
end
user = User.where({ username: param[:username] })
if user.length > 0
return { :message => "username already exists", :valid => false}
end
return { :message => "successful", :valid => true }
end
end
|
require 'spec_helper'
describe Layout, type: :model do
it { is_expected.to belong_to :keyboard }
it { is_expected.to have_many :layers }
it { is_expected.to validate_presence_of :name }
it { is_expected.to accept_nested_attributes_for :layers }
describe 'kind reader' do
it 'reads the name of the Keyboard from the keyboard' do
keyboard = Keyboard.new(name: 'cool name')
layout = Layout.new
allow(layout).to receive(:keyboard) { keyboard }
expect(layout.kind).to eq 'cool name'
end
it 'does not error on nil' do
expect(Layout.new.kind).to be_nil
end
end
describe 'kind setter' do
context 'existing keyboard' do
it 'sets with friendly find' do
keyboard = Keyboard.ergodox_ez
expect(keyboard.name).to eq('ErgoDox EZ')
layout = FactoryGirl.create(:layout)
layout.kind = 'ErgoDox=EZ'
expect(layout.keyboard).to eq(keyboard)
end
end
context 'non existant keyboard' do
it 'sets to nil' do
layout = FactoryGirl.create(:layout)
layout.kind = 'ErgoDOX SWEEER MAKING A NEW THING HERE'
expect(layout.keyboard).to be_nil
end
end
end
end
|
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.category_name(category_name)
define_method(:category_name) { category_name }
end
end
|
# coding: utf-8
require 'wicked_pdf'
require_relative './htmlentities'
require_relative './helpers'
module DocumentGenerator
class VatCertificate
include DocumentGenerator::Helpers
def initialize
@inline_css = ''
end
def generate(path, data)
coder = HTMLEntities.new
language = select_language(data)
template_path = select_template(data, language)
html = File.open(template_path, 'rb') { |file| file.read }
customer_name = coder.encode(generate_customer_name(data), :named)
html.gsub! '<!-- {{CUSTOMER_NAME}} -->', customer_name
customer_address = coder.encode(generate_customer_address(data), :named)
html.gsub! '<!-- {{CUSTOMER_ADDRESS}} -->', customer_address
building_address = coder.encode(generate_building_address(data), :named)
html.gsub! '<!-- {{BUILDING_ADDRESS}} -->', building_address
invoice_number = generate_invoice_number(data)
html.gsub! '<!-- {{INVOICE_NUMBER}} -->', invoice_number
invoice_date = generate_invoice_date(data)
html.gsub! '<!-- {{INVOICE_DATE}} -->', invoice_date
html.gsub! '<!-- {{INLINE_CSS}} -->', @inline_css
document_title = document_title(data, language)
write_to_pdf(path, html, title: document_title)
end
def select_template(data, language)
if language == 'FRA'
ENV['CERTIFICATE_TEMPLATE_FR'] || '/templates/attest-fr.html'
else
ENV['CERTIFICATE_TEMPLATE_NL'] || '/templates/attest-nl.html'
end
end
def document_title(data, language)
number = generate_invoice_number(data)
"A#{number}"
end
def generate_customer_name(data)
customer = data['customer']
name = ''
name += " #{customer['prefix']}" if customer['prefix'] and customer['printPrefix']
name += " #{customer['name']}" if customer['name']
name += " #{customer['suffix']}" if customer['suffix'] and customer['printSuffix']
name
end
def generate_customer_address(data)
customer = data['customer']
[ customer['address1'],
customer['address2'],
customer['address3'],
"#{customer['postalCode']} #{customer['city']}"
].find_all { |a| a }.join('<br>')
end
def generate_building_address(data)
building = data['building']
if building
[ building['address1'],
building['address2'],
building['address3'],
"#{building['postalCode']} #{building['city']}"
].find_all { |a| a }.join('<br>')
else
generate_customer_address(data)
end
end
end
end
|
class CreateTubes < ActiveRecord::Migration
def self.up
create_table "tubes", :force => true do |t|
t.string "bar_code"
t.string "clinic_id"
t.integer "sample_type_id"
t.integer "tube_type_id"
t.string "parent_id"
t.string "position"
t.integer "box_id", :limit => 8
t.string "aliquot"
t.float "volume"
t.float "parent_volume"
t.float "concentration"
t.date "drawing_date"
t.date "transfer_80_date"
t.integer "operation_id"
t.date "operation_date"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "in_use"
t.float "amount"
t.boolean "complete"
t.string "comments"
t.string "operator"
t.boolean "selected"
t.float "a_260_280_ratio"
t.float "a_260_230_ratio"
end
end
def self.down
drop_table :tubes
end
end
|
class MediaList < ActiveRecord::Base
attr_accessible :address, :circulation, :city, :company, :email, :fax, :phone, :state, :url, :zip
validates :company, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
def self.add_new_media_contact(company, address, city, state, zip, phone, fax, circulation, url, email)
if MediaList.find_by_company_and_email(company, email).blank?
MediaList.create(company: company, address: address, city: city, state: state, zip: zip, phone: phone, fax: fax, circulation: circulation, url: url, email: email)
end
end
def self.find_matches_for(distribution_list)
## DistributionList
#name "List"
#where "US"
#where_area "Northeast"
#who "Newspapers"
#who_sub "New York Times"
#what "Music"
#what_sub "Jazz"
#
#
## MediaList
#company "Huffington Post"
#address "1234 My St."
#city "New York"
#state "NY"
#zip "10029"
#phone "212-555-1212"
#fax "212-555-1213"
#circulation "66.4"
#url "http://www.huffingtonpost.com"
#email
# TODO: need to add country and region as well as who, who_sub and what_sub to MediaList
self.where(criteria_for(distribution_list))
end
def self.criteria_for(distribution_list)
if distribution_list.where_area == "all"
"state IN(#{DistributionList::US_STATES.map {|str| "\'#{str}\'"}.join(',')})"
else
"state = '#{distribution_list.where_area}'"
end
end
end
|
require 'chemistry/element'
Chemistry::Element.define "Barium" do
symbol "Ba"
atomic_number 56
atomic_weight 137.327
melting_point '1002K'
end
|
module Library
# TODO Comments are needed here to explain how these routines use information
# from the 'env' object and their arguments and how they satisfy return-
# value requirements. For now, please consult Section 5 in ../README
# when reading this code. Other sections of the README may be helpful,
# too.
def lib_build(env,prepkit)
bindir=env.build.bindir
binname=env.run.binname
compiler=env.build.compiler
srcdir=env.build.ddts_root
srcfile=env.build.srcfile
cmd="cd #{srcdir} && #{compiler} #{srcfile} -o #{bindir}/#{binname}"
ext(cmd,{:msg=>"Build failed, see #{logfile}"})
end
def lib_build_post(env,buildkit)
File.join(env.build.ddts_root,env.build.bindir,env.build.binname)
end
def lib_build_prep(env)
FileUtils.cp(File.join(app_dir,env.build.srcfile),env.build.ddts_root)
FileUtils.mkdir_p(File.join(env.build.ddts_root,env.build.bindir))
end
def lib_comp_alt(env,f1,f2)
logi "Comparing '#{f1}' to '#{f2}' with alternate comparator..."
FileUtils.compare_file(f1,f2)
end
def lib_data(env)
f="data.tgz"
src=File.join(app_dir,f)
dst=File.join(tmp_dir,f)
cmd="cp #{src} #{dst}"
md5='d49037f1ef796b8a7ca3906e713fc33b'
unless File.exists?(dst) and hash_matches(dst,md5)
logd "Getting data: #{cmd}"
output,status=ext(cmd,{:msg=>"Failed to get data, see #{logfile}"})
die "Data archive #{f} has incorrect md5 hash" unless hash_matches(dst,md5)
end
logd "Data archive #{f} ready"
cmd="cd #{tmp_dir} && tar xvzf #{f}"
logd "Extracting data: #{cmd}"
output,status=ext(cmd,{:msg=>"Data extract failed, see #{logfile}"})
logd "Data extract complete"
end
def lib_outfiles_ex(env,path)
expr=File.join(path,'out[0-9]')
Dir.glob(expr).map { |e| [path,File.basename(e)] }
end
def lib_run(env,prepkit)
rundir=prepkit
bin=env.run.binname
run=env.run.runcmd
sleep=env.run.sleep
tasks=env.run.tasks
if message=env.run.message
logi (message.is_a?(Array))?(message.join(" ")):(message)
end
cmd="cd #{rundir} && #{run} #{tasks} #{bin} >stdout 2>&1 && sleep #{sleep}"
logd "Running: #{cmd}"
IO.popen(cmd) { |io| io.readlines.each { |e| logd "#{e}" } }
File.join(rundir,'stdout')
end
def lib_run_check(env,postkit)
stdout=postkit
unless (lines=File.open(stdout).read)=~/SUCCESS/
lines.each_line { |line| logi line.chomp }
end
(job_check(stdout,"SUCCESS"))?(env.run.ddts_root):(nil)
end
def lib_run_post(env,runkit)
stdout=runkit
end
def lib_run_prep(env)
rundir=env.run.ddts_root
binname=env.run.binname
conffile=env.run.conffile
FileUtils.cp(env.build.ddts_result,rundir)
FileUtils.chmod(0755,File.join(rundir,binname))
a=env.run.a
b=env.run.b
n=env.run.n||0
confstr="&config a=#{a} b=#{b} n=#{n} /\n"
conffile=File.join(rundir,env.run.conffile)
File.open(conffile,'w') { |f| f.write(confstr) }
rundir
end
def lib_suite_post(env)
logi "[ default post action ]"
end
def lib_suite_post_ex(env)
buildfails=env.suite.ddts_builds.reduce(0) { |m,(k,v)| (v.failed)?(m+1):(m) }
logi "build fail rate = #{Float(buildfails)/env.suite.ddts_builds.size}"
runfails=env.suite.ddts_runs.reduce(0) { |m,(k,v)| (v.failed)?(m+1):(m) }
logi "run fail rate = #{Float(runfails)/env.suite.ddts_runs.size}"
logi "[ custom post action ]"
end
def lib_suite_prep(env)
logi "[ default prep action ]"
end
def lib_suite_prep_ex(env)
logi "[ custom prep action ]"
end
end
|
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
@place = Place.find(params[:place_id])
@comment = @place.comments.create(comment_params.merge(user: current_user))
if @comment.invalid?
flash[:error] = "Could not save: #{@comment.errors.messages}"
redirect_to request.referrer
else
flash[:success] = 'Saved Successfully'
redirect_to place_path(@place)
end
end
def destroy
@comment = Comment.find(params[:id])
if @comment.user != current_user
return render plain: 'Not Allowed', status: :forbidden
end
@comment.destroy
redirect_to request.referrer
end
def edit
@comment = Comment.find(params[:id])
if @comment.user != current_user
return render plain: 'Not Allowed', status: :forbidden
end
end
def update
@comment = Comment.find(params[:id])
if @comment.user != current_user
return render plain: 'Not Allowed', status: :forbidden
end
@comment.update(comment_params)
if @comment.invalid?
flash[:error] = "Could not save: #{@comment.errors.messages}"
else
flash[:success] = 'Updated Successfully'
end
redirect_to request.referrer
end
private
def comment_params
params.require(:comment).permit(:message, :rating)
end
end
|
class Url < ActiveRecord::Base
before_validation :set_token, on: :create
validates :token, presence: true, uniqueness: true
validates :long_url, presence: true, url: true
def to_param
token
end
def self.with_token(token)
tokens = TokenMachine.conversion_token(token)
where(token: tokens).first
end
private
def set_token
self.token = make_unique_token
end
def make_unique_token
loop do
token = build_token_value
return token if token_is_unique?(token)
end
end
def token_is_unique?(token)
tokens = TokenMachine.nearby_tokens(token)
token_free?(tokens)
end
def token_free?(tokens)
tokens.map { |token| self.class.select(:id).where("token Like ?", token) }.join.size.zero?
end
def build_token_value
TokenMachine.generate_token
end
end
|
module Lolita
module Configuration
# Lolita::Configuration::Tabs is container class that holds all
# tabs for each lolita instance.
# Also it has some useful methods.
class Tabs < Lolita::Configuration::Base
include Enumerable
include Lolita::ObservedArray
attr_reader :excluded
attr_accessor :tab_types
def initialize dbp,*args,&block
set_and_validate_dbp(dbp)
set_default_attributes
set_attributes(*args)
self.instance_eval(&block) if block_given?
end
def each
create_content_tab if @tabs.empty?
@tabs.each{|tab| yield tab }
end
def tabs=(values)
if values.respond_to?(:each)
values.each{|tab| self << tab}
else
raise ArgumentError, "#{values} must respond to each"
end
end
def tab *args,&block
self << build_element(args && args[0],&block)
end
def fields
@tabs.map(&:fields).flatten
end
def by_type(type)
@tabs.detect{|tab| tab.type == type.to_sym }
end
def names
@tabs.map(&:name)
end
def associated
@tabs.select{|tab| !tab.dissociate}
end
def dissociated
@tabs.select{|tab| tab.dissociate}
end
def default
tab_types.each{|type| tab(type.to_sym)}
end
private
def set_default_attributes()
@tabs=[]
@tab_types = [:content]
end
def create_content_tab
tab(:content)
end
def validate(tab)
tab.respond_to?(:validate) && tab.send(:validate, :tabs => @tabs)
end
def collection_variable
@tabs
end
def build_element(possible_tab,&block)
possible_tab = possible_tab.nil? && :default || possible_tab
new_tab = if possible_tab.is_a?(Hash) || possible_tab.is_a?(Symbol)
Lolita::Configuration::Factory::Tab.add(dbp,possible_tab,&block)
else
possible_tab
end
validate(new_tab)
new_tab
end
end
end
end |
class ImagesController < ApplicationController
before_action :authenticate_user!
before_action :set_image, only: [:show, :edit, :update, :destroy]
def new
@image = Image.new
end
def edit
end
def create
if params[:project_id]
@imageable = Project.find(params[:project_id])
@image = @imageable.images.build(image_params)
else
@imageable = current_user
@image = @imageable.build_image(image_params)
end
if @image.save
redirect_to redirect_path(current_user), notice: 'Image was successfully saved.'
else
render :new
end
end
def update
if @image.update(image_params)
redirect_to redirect_path(current_user), notice: 'Image was successfully updated.'
else
render :edit
end
end
def destroy
@image.destroy
redirect_to redirect_path(current_user), notice: 'Image was successfully removed.'
end
private
def set_image
@image = Image.find(params[:id])
end
def image_params
params.require(:image).permit(:avatar, :project_id, :id, :remove_avatar)
end
end
|
class Api::V1::EventsController < ApplicationController
def index
@events = Event.all
render json: @events
end
def show
@event = Event.find(params[:id])
render json: @event, status: :ok
end
def create
@event = Event.create(event_params)
render json: @event, status: :created
end
def update
@event = Event.find(params[:id])
@event.update(event_params)
render json: @event, status: :accepted
end
def destroy
@event = Event.find(params[:id])
@event.delete
end
private
def event_params
params.require(:event).permit(:title, :duration, :location, :category, :min_capacity, :max_capacity, :date, :time, :image_url, :description)
end
end
|
class Interest < ActiveRecord::Base
belongs_to :user
validates :interest_name, :presence => true
end
|
module Kernel
def wait_for(conf)
start = Time.now
defaults = {
:timeout => nil,
:step => 0.125
}
conf = defaults.update conf
condition = false
loop do
condition = yield
break if condition
break if conf[:timeout] and Time.now - start > conf[:timeout]
sleep conf[:step]
end
condition
end
end
|
require 'forwardable'
module Gurobi
class Var
extend Forwardable
class << self
# @return [Gurobi::Var]
# @see Gurobi::Model#add_binary_var
def create_binary(*args)
keyword_args = args.last.is_a?(Hash) ? args.pop : {}
keyword_args = { lb: 0.0, ub: 1.0 }.merge(keyword_args)
new(*args, keyword_args.merge(vtype: GRB::BINARY))
end
# @return [Gurobi::Var]
# @see Gurobi::Model#add_continuous_var
def create_continuous(*args)
keyword_args = args.last.is_a?(Hash) ? args.pop : {}
new(*args, keyword_args.merge(vtype: GRB::CONTINUOUS))
end
# @return [Gurobi::Var]
# @see Gurobi::Model#add_integer_var
def create_integer(*args)
keyword_args = args.last.is_a?(Hash) ? args.pop : {}
new(*args, keyword_args.merge(vtype: GRB::INTEGER))
end
private
# @return [Hash]
# @see Gurobi::Model#add_var
def parse_initialize_arguments(*args)
original_args = args.dup
keyword_args = args.last.is_a?(Hash) ? args.pop.dup : {}
range = keyword_args.delete(:range)
lb = keyword_args.delete(:lb)
ub = keyword_args.delete(:ub)
{
lb: range && range.begin || lb || args.shift || 0.0,
ub: range && range.end || ub || args.shift || GRB::INFINITY,
obj: keyword_args.delete(:obj) || args.shift || 0.0,
vtype: keyword_args.delete(:vtype) || args.shift || GRB::CONTINUOUS,
name: keyword_args.delete(:name) || args.shift,
}.tap do
unless args.empty?
raise Error, "invalid arguments: #{original_args}"
end
end.merge(keyword_args)
end
end
# @return [Float, Fixnum]
attr_reader :lb
# @return [Float, Fixnum]
attr_reader :ub
# @return [Float, Fixnum]
attr_reader :obj
# @return [Fixnum] GRB::CONTINUOUS, GRB::BINARY, ...
attr_reader :vtype
# @return [String, Symbol]
attr_reader :name
def_delegators :to_lin_expr, :-@, :+, :-, :*, :===, :<=, :>=
# @see Gurobi::Model#add_var
def initialize(*args)
attributes = self.class.send(:parse_initialize_arguments, *args)
([:lb, :ub, :obj, :vtype, :name] +
self.class.settable_attributes).each do |key|
if attribute = attributes.delete(key)
send("#{key}=", attribute)
end
end
unless attributes.empty?
raise Error, "invalid arguments: #{attributes.inspect}"
end
end
# @return [Gurobi::LinExpr]
def to_lin_expr
LinExpr.new([Term.new(1, self)])
end
# @param grb_model [GRBModel]
# @return [nil]
def gurobize(grb_model)
raise Error, "already gurobized: #{inspect}" if @grb_var
@grb_var = grb_model.add_var(@lb, @ub, @obj, @vtype, @name.to_s)
nil
end
# @param lb [Float, Fixnum]
def lb=(lb)
@lb = lb
@lb = GRB::INFINITY if @lb == Float::INFINITY
@lb = - GRB::INFINITY if @lb == - Float::INFINITY
@grb_var.set(GRB::DoubleAttr::LB, @lb) if @grb_var
end
# @param ub [Float, Fixnum]
def ub=(ub)
@ub = ub
@ub = GRB::INFINITY if @ub == Float::INFINITY
@ub = - GRB::INFINITY if @ub == - Float::INFINITY
@grb_var.set(GRB::DoubleAttr::UB, @ub) if @grb_var
end
# @param obj [Float, Fixnum]
def obj=(obj)
@obj = obj
@grb_var.set(GRB::DoubleAttr::Obj, @obj) if @grb_var
end
# @param vtype [Fixnum, Symbol, String]
def vtype=(vtype)
@vtype =
case vtype.is_a?(String) ? vtype.upcase.to_sym : vtype
when GRB::CONTINUOUS, :CONTINUOUS, :C; GRB::CONTINUOUS
when GRB::BINARY, :BINARY, :B; GRB::BINARY
when GRB::INTEGER, :INTEGER, :I; GRB::INTEGER
when GRB::SEMICONT, :SEMICONT, :S; GRB::SEMICONT
when GRB::SEMIINT, :SEMIINT, :N; GRB::SEMIINT
else raise Error, "invalid vtype: #{vtype.inspect}"
end
@grb_var.set(GRB::CharAttr::VType, @vtype) if @grb_var
end
# @param name [String, Symbol]
def name=(name)
@name = name
@grb_var.set(GRB::StringAttr::VarName, @name.to_s) if @grb_var
end
# @return [Boolean]
def binary?
@vtype == GRB::BINARY
end
# @return [Boolean]
def continuous?
@vtype == GRB::CONTINUOUS
end
# @return [Boolean]
def integer?
@vtype == GRB::INTEGER
end
# @return [self, nil]
def to_binary!
if binary?
nil
else
self.vtype = GRB::BINARY
self
end
end
# @return [self, nil]
def to_continuous!
if continuous?
nil
else
self.vtype = GRB::CONTINUOUS
self
end
end
# @return [self, nil]
def to_integer!
if integer?
nil
else
self.vtype = GRB::INTEGER
self
end
end
# @return [Boolean]
def iis?
iis_lb? || iis_ub?
end
# @return [Boolean]
def iis_lb?
iis_lb > 0
end
# @return [Boolean]
def iis_ub?
iis_ub > 0
end
# @return [String]
def inspect
"#@name:#{@vtype.chr}"
end
private
# @return [GRBVar]
def grb_var
raise Error, "not yet gurobized: #{inspect}" unless @grb_var
@grb_var
end
alias to_gurobi grb_var
# Call by Gurobi::Model#update
#
# @return [void]
def update
sync_name
set_attributes!
end
# @return [void]
def sync_name
@name = grb_var.get(GRB::StringAttr::VarName)
end
# Creates attribute accessors
extend Attribute
attributes :@grb_var, %w(
X x No
Xn xn No
RC rc No
Start start Yes
BranchPriority branch_priority Yes
VBasis v_basis Yes
PStart p_start Yes
IISLB iis_lb No
IISUB iis_ub No
SAObjLow sa_obj_low No
SAObjUp sa_obj_up No
SALBLow sa_lb_low No
SALBUp sa_lb_up No
SAUBLow sa_ub_low No
SAUBUp sa_ub_up No
UnbdRay unbd_ray No
)
end
end
|
require 'application_system_test_case'
class OpinionsTest < ApplicationSystemTestCase
setup do
@opinion = opinions(:one)
end
test 'visiting the index' do
visit opinions_url
assert_selector 'h1', text: 'Opinions'
end
test 'creating a Opinion' do
visit opinions_url
click_on 'New Opinion'
fill_in 'Body', with: @opinion.body
click_on 'Create Opinion'
assert_text 'Opinion was successfully created'
click_on 'Back'
end
test 'updating a Opinion' do
visit opinions_url
click_on 'Edit', match: :first
fill_in 'Body', with: @opinion.body
click_on 'Update Opinion'
assert_text 'Opinion was successfully updated'
click_on 'Back'
end
test 'destroying a Opinion' do
visit opinions_url
page.accept_confirm do
click_on 'Destroy', match: :first
end
assert_text 'Opinion was successfully destroyed'
end
end
|
require File.dirname(__FILE__) + '/../test_helper'
class ContactsTest < ActionMailer::TestCase
tests Contacts
def test_signup
@expected.subject = 'Contacts#signup'
@expected.body = read_fixture('signup')
@expected.date = Time.now
assert_equal @expected.encoded, Contacts.create_signup(@expected.date).encoded
end
def test_notify_admin
@expected.subject = 'Contacts#notify_admin'
@expected.body = read_fixture('notify_admin')
@expected.date = Time.now
assert_equal @expected.encoded, Contacts.create_notify_admin(@expected.date).encoded
end
end
|
require 'rails_helper'
describe 'As a logged in user' do
before(:each) do
user_logs_in
end
context 'when I visit a company show page' do
let(:company) { company = create_approved_company("Test Company") }
scenario 'I see add findings box' do
visit company_path(company)
expect(page).to have_content("Add Findings")
end
scenario "I enter my findings" do
visit company_path(company)
select '2', from: 'finding_viability'
check 'finding_hiring'
click_on "Submit findings"
expect(current_path).to eq(company_path(company))
expect(page).to have_content("Findings")
expect(page).to have_content("Viability")
expect(page).to have_content("2")
expect(page).to have_content("Hiring?")
expect(page).to have_content("true")
end
end
end
|
class InvestorsUsers < ActiveRecord::Migration
def change
create_table :investors_users do |t|
t.references :user
t.references :investor
t.string :position
t.timestamps
end
add_index :investors_users, :user_id
add_index :investors_users, :investor_id
end
end
|
class Judge::LogReporter
def initialize(logger)
@log = logger
end
def start(solution)
@log.puts "start processing of #{solution.unique_name(:global)}"
end
def compiling
@log.puts "compiling"
end
def compilation_error(output)
@log.puts "compilation error, compiler output is:"
@log.puts output
end
def testing(test)
@log.puts "testing on test #{test.unique_name(:solution)}"
end
def invokation_error(reason)
@log.puts "invokation error: #{reason}"
end
def invokation_finished(stats)
@log.puts "invokation finished."
end
def checking
@log.puts "checking"
end
def checking_problem(reason)
@log.puts "checker problem: #{reason}."
end
def checking_finished(result, stats)
@log.puts "checking done: #{result}."
end
def finished
@log.puts "finished."
end
end
|
class QuotesController < ApplicationController
def index
@quotes = Quote.all
json_response(@quotes)
end
def search
@quotes = Quote.search_by_term(params[:query])
json_response(@quotes)
end
def show
@quote = Quote.find(params[:id])
json_response(@quote)
end
def create
@quote = Quote.create!(quote_params)
json_response(@quote, :created)
end
def update
@quote = Quote.find(params[:id])
if @quote.update!(quote_params)
render status: 200, json: {
message: "This quote has been successfully updated"
}
end
end
def destroy
@quote = Quote.find(params[:id])
# api_key = params[:api_key]
# authorized_key = "#{api_key}"
# # do we need to create a .env file? is this a proper way to add API_KEY into our 'params'?
if @quote.destroy
render status: 200, json: {
message: "You've successfully DESTROYED this quote"
}
end
end
private
def quote_params
params.permit(:author, :content)
end
end |
require 'rails_helper'
feature "cart" do
fixtures :categories
fixtures :items
fixtures :users
before(:each) do
visit "/"
end
it "can visit the cart page" do
click_link("Cart")
expect(current_path).to eq("/cart")
end
it "can add items" do
click_link("All Products")
first(:button, "Add To Cart").click
expect(current_path).to eq("/cart")
expect(page).to have_content("Item A")
expect(page).to have_content("$11.11")
end
context "user is logged in" do
before(:each) {
visit "/login"
fill_in "Email", with: "jeff@gmail.com"
fill_in "Password", with: "pass"
click_button("Login")
}
it "can checkout to buy items" do
click_link("All Products")
first(:button, "Add To Cart").click
click_link_or_button("Checkout")
expect(current_path).to eq("/dashboard")
end
end
context "user is not logged in" do
it "must log in before checking out" do
visit "/"
click_link("All Products")
first(:button, "Add To Cart").click
expect(page).to have_content("Please login before checking out.")
expect(page).to have_content("Login")
expect(page).not_to have_content("Checkout")
end
it "can log in and proceed to checkout" do
visit "/"
click_link("All Products")
first(:button, "Add To Cart").click
within(:css, ".cart-right") do
click_link("Login")
end
expect(current_path).to eq("/login")
fill_in "Email", with: "jeff@gmail.com"
fill_in "Password", with: "pass"
click_button("Login")
expect(current_path).to eq("/cart")
end
context "we already have an item in our cart" do
before(:each) do
visit "/"
click_link("All Products")
first(:button, "Add To Cart").click
end
it "lets you add the same item/joke twice" do
visit "/"
click_link("All Products")
first(:button, "Add To Cart").click
expect(page).to have_selector(".cart-row", count: 1)
end
it "updates the cart Quantity" do
visit "/"
click_link("All Products")
first(:button, "Add To Cart").click
expect(page).to have_selector(".dad-quantity[value='2']")
end
end
end
end
|
=begin
* DJKSTRA ALGORITHM
* Description :Calculate the shortest path within the graph depends on the calculate cost
For Time : Every fligth add
=end
class Shortestpath
#Variable to penalyze every layover/stops
TIME_PER_AIR = 2
TIME_AVG_DELAY = 0.5
TOTAL = TIME_AVG_DELAY + TIME_PER_AIR
Vertex = Struct.new(:name, :neighbours, :dist, :prev)
=begin
* Initialized the graph with the related costs every time merge is updated
=end
def initialize(graph)
@vertices = Hash.new{|h,k| h[k]=Vertex.new(k,[],Float::INFINITY)}
@edges = {}
graph.each do |(v1, v2, dist)|
@vertices[v1].neighbours << v2
@vertices[v2].neighbours << v1
@edges[[v1, v2]] = @edges[[v2, v1]] = dist#vertexes are non directional
end
@dijkstra_source = nil
end
=begin
* Seached for the chortest route in an efficient way with all the cost related
=end
def dijkstra(source, operation)
return if @dijkstra_source == source
vertex_cost = @vertices.values#initialize all the costs
vertex_cost.each do |v|
#initializes vertex to infinity
v.dist = Float::INFINITY
v.prev = nil
end
@vertices[source].dist = 0
until vertex_cost.empty?# no more vertexes to search
u = vertex_cost.min_by {|vertex| vertex.dist}
break if u.dist == Float::INFINITY
vertex_cost.delete(u)
u.neighbours.each do |v|
vertex_path = @vertices[v]#always save the best path
if vertex_cost.include?(vertex_path)
alt = u.dist + @edges[[u.name, v]]
if(operation == "TIME")#if the operation is Time there is a stop between fligths --> adjust
if alt+TOTAL < vertex_path.dist
vertex_path.dist = alt+TOTAL
vertex_path.prev = u.name
end
else
if alt < vertex_path.dist
vertex_path.dist = alt
vertex_path.prev = u.name
end
end
end
end
end
@dijkstra_source = source
end
=begin
* Finds the shortest path available, djkstra return all the path , and the algorithm keeps the best one
* and returns it
=end
def DjkstraShortestPath(source, target, operation)
dijkstra(source, operation)
path = []
u = target
while u
path.unshift(u)
u = @vertices[u].prev
end
return path, @vertices[target].dist
end
end |
class Milestone < ApplicationRecord
include Filterable
enum target_type: { revenue: 0,
deals: 1 }
enum status: { active: 0,
archived: 1 }
has_many :user_milestones, inverse_of: :milestone
has_many :users, through: :user_milestones
scope :status, ->(status) { where status: status }
def deals
Deal.joins("INNER JOIN users ON users.id = deals.user_id")
.where('date_of_closing > ? AND date_of_closing < ?',
start_date,
due_date)
end
def progress
return deals.count if target_type == :deals.to_s
deals.sum(:amount_cents).to_money / 100
end
def target
return self[:target].to_i if target_type == :deals.to_s
self[:target].to_money
end
def target_name
return 'Deals' if target_type == :deals.to_s
'Revenue'
end
end
|
require File.join(File.dirname(__FILE__), '..', 'unit_test_helper')
# initialize
# ----------
class IQ::Processor::Adapters::Base::InitializeTest < Test::Unit::TestCase
def test_should_raise_when_no_block_given
assert_raise(ArgumentError) { IQ::Processor::Adapters::Base.new('/path/to/file') }
end
def test_should_raise_when_format_is_not_a_string_or_nil
assert_raise(ArgumentError) { IQ::Processor::Adapters::Base.new('/path/to/file', :not_string) {} }
end
def test_should_accept_path_to_file_without_format
assert_nothing_raised { IQ::Processor::Adapters::Base.new('/path/to/file') {} }
end
def test_should_raise_if_argument_is_not_a_string
assert_raises(ArgumentError) { IQ::Processor::Adapters::Base.new(1) {} }
assert_raises(ArgumentError) { IQ::Processor::Adapters::Base.new(:not_a_string) {} }
end
def test_should_set_format_instance_variable_to_value_of_format_argument
instance = IQ::Processor::Adapters::Base.new('/path/to/file', 'gif') {}
assert_equal 'gif', instance.instance_variable_get('@format')
end
def test_should_set_file_path_instance_variable_to_value_of_file_path_argument
instance = IQ::Processor::Adapters::Base.new('/path/to/file') {}
assert_equal '/path/to/file', instance.instance_variable_get('@file_path')
end
end
# write
# -----
class IQ::Processor::Adapters::Base::WriteTest < Test::Unit::TestCase
def test_should_respond
assert_respond_to(
IQ::Processor::Adapters::Base.new('/path/to/file') {},
:write
)
end
end
|
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.references :food, index: true, foreign_key: true
t.references :order, index: true, foreign_key: true
t.string :cheese
t.string :sauce
t.string :crust
t.string :size
t.integer :slices
t.timestamps null: false
end
end
end
|
class Cluster < ActiveRecord::Base
belongs_to :user
has_many :posts
validates_presence_of :name, :description, :user
default_scope :order => 'clusters.created_at DESC'
end
|
class CreatePesticideApplications < ActiveRecord::Migration
def change
create_table :pesticide_applications do |t|
t.datetime :StartDateTime
t.datetime :EndDateTime
t.string :RestrictedEntryInterval
t.string :ApplicationRate
t.references :Location, index: true, foreign_key: true
t.string :Commodity
t.string :TargetPest
t.string :TotalProduct
t.references :Pesticide, index: true, foreign_key: true
t.timestamps null: false
end
end
end
|
require 'uri'
require 'ping'
def check_vars(name,url)
returns = []
begin
uri = URI.parse(url)
uri_url = "#{uri.scheme}://#{uri.host}"
url_return = `wget -O/dev/null -q "#{uri_url}" && echo "1" || echo "0"`
if url_return[0] != 49 # 1
returns << :url_not_exist
end
rescue URI::InvalidURIError
returns << :url_invalid
end
if name.length < 1
returns << :no_name
end
if name =~ /.*\/.*/
returns << :name_slash
end
if returns.empty?
return true
else
return returns
end
end
def err_check(name,url)
vc = check_vars(name,url)
if vc == true
yield if block_given?
return "",""
end
url_messages = []
name_messages = []
vc.each do |err|
case err
when :url_invalid
url_messages << "invalid url."
when :url_not_exist
url_messages << "site doesn't exist."
when :no_name
name_messages << "please specify a name."
when :name_slash
name_messages << "names cannot contain slashes."
end
end
return [name_messages.join(" and "), url_messages.join(" and ")]
end |
# Write a method consonant_cancel that takes in a sentence and returns a new
# sentence where every word begins with it's first vowel.
def consonant_cancel(sentence)
words = sentence.split(" ")
new_words = []
vowels = "aeiou"
words.each do |word|
word.each_char.with_index do |c,i|
if vowels.include?(c)
new_words << word[i..-1]
break
end
end
end
return new_words.join(" ")
end
puts consonant_cancel("down the rabbit hole") #=> "own e abbit ole"
puts consonant_cancel("writing code is challenging") #=> "iting ode is allenging"
|
require 'rails_helper'
describe ScribblesController do
it "should have a canvas element" do
visit "scribbles/new"
expect(page).to have_css "canvas"
end
describe "interactions" do
before(:each) do
Capybara.current_driver = :selenium
visit new_scribble_path
subject { page }
@before = page.execute_script("return delegator.toDataURL();")
find(".upper-canvas").click
@after = page.execute_script("return delegator.toDataURL();")
end
after(:all) do
Capybara.use_default_driver
end
describe "freehand drawing" do
it "should respond to clicks" do
expect(@before).not_to eq(@after)
end
end
describe "updating image field" do
it "should copy data URL to hidden field" do
@hidden = page.execute_script("return $('#image_data').attr('value');")
expect(@hidden).to eq(@after)
end
end
describe "changing the color" do
it "should update the brush color" do
color_el = find('#color-red')
color_el.click
@color = page.execute_script('return canvas.freeDrawingBrush.color;')
expect(@color).to eq(color_el['data-color'])
end
end
end
end
|
require 'rails_helper'
# http://matthewlehner.net/rails-api-testing-guidelines/ used as a starting point
describe "Sales API" do
describe 'GET' do
before(:each) do
# sale = FactoryGirl.create(:sale) # FactoryGirl could be used when this project grows
sale_params = single_sale[:sales].first
@sales = Sale.create! [ sale_params.merge!(password: '123') ]
end
it 'retrieves a specific sale with password' do
get "/sales/#{@sales.first.id}.json", password: '123'
# test for the 200 status-code
expect(response).to be_success
# check that the sale attributes are the same.
expect(json_data['code']).to eq('DO')
expect(json_data['hashed_password']).to be_truthy
end
it 'returns and error if password not specified' do
get "/sales/#{@sales.first.id}.json"
expect(response).to have_http_status(:not_found)
end
it 'returns error for wrong password' do
get "/sales/#{@sales.first.id}.json", password: 'wrong'
# TODO: staus: 403 if sale with id exists but password does not match
# e.g. expect(response).to have_http_status(403)
expect(response).to have_http_status(:not_found)
end
end
describe 'POST' do
it 'creates sales with the correct date and time' do
# TODO: DRY up (this is used elsewhere)
params = multiple_sales.merge(password: 'correct')
post "/sales", params
expect(json_data_array.first['date']).to eq('20140103')
expect(json_data_array.last['date']).to eq('20140103')
expect(json_data_array.first['time']).to eq('0700')
expect(json_data_array.last['time']).to eq('0815')
end
it 'creates a sale with the correct date and time' do
# TODO: DRY up (this is used elsewhere)
params = single_sale.merge(password: 'correct')
post "/sales", params
expect(json_data.first['date']).to eq('20140103')
expect(json_data.first['time']).to eq('0815')
end
end
describe 'DELETE' do
# The question does not mention passwords for destroying a sale
sale_params = single_sale[:sales].first
sale = Sale.create! sale_params.merge!(password: '123')
sale.reload
it 'destroys a sale' do
expect{ delete "/sales/#{sale.id}"}.to change(Sale, :count).by(-1)
end
end
end |
class CreateMods < ActiveRecord::Migration[6.0]
def change
create_table :mods do |t|
t.belongs_to :event
t.belongs_to :mod_section
t.integer :participation_limit, null: false, default: 0
t.string :name, null: false
t.string :timeframe, null: false
t.text :description, null: true
t.json :constraint, null: true
t.timestamps
end
end
end
|
require 'rails_helper'
RSpec.describe SendMassMessageJob, active_job: true, type: :job do
describe '#perform' do
let(:department) { create :department }
let(:user) { create :user, department: department }
let!(:client_1) { create :client, user: user }
let!(:client_2) { create :client, user: user }
let!(:client_3) { create :client, user: user }
let(:rr_1) { ReportingRelationship.find_by(user: user, client: client_1) }
let(:rr_2) { ReportingRelationship.find_by(user: user, client: client_2) }
let(:rr_3) { ReportingRelationship.find_by(user: user, client: client_3) }
let(:message_body) { 'hello this is message one' }
let(:rrs) { [rr_1.id, rr_3.id] }
let(:send_at) { Time.zone.now }
subject do
SendMassMessageJob.perform_now(
rrs: rrs,
body: message_body,
send_at: send_at.to_s
)
end
it 'sends message to multiple rrs' do
subject
expect(ScheduledMessageJob).to have_been_enqueued.twice
expect(user.messages.count).to eq 2
expect(client_1.messages.count).to eq 1
expect(client_1.messages.first.body).to eq message_body
expect(client_1.messages.first.number_from).to eq department.phone_number
expect(client_2.messages.count).to eq 0
expect(client_3.messages.count).to eq 1
expect(client_3.messages.first.body).to eq message_body
expect(client_3.messages.first.number_from).to eq department.phone_number
end
it 'sends an analytics event for each message in mass message' do
subject
expect_analytics_events(
'message_send' => {
'mass_message' => true
}
)
expect_analytics_event_sequence(
'message_send',
'message_send'
)
end
context 'a send_at date is set' do
let(:send_at) { Time.zone.now.change(sec: 0, usec: 0) + 2.days }
it 'sends message to multiple rrs at the right time' do
subject
expect(client_1.messages.first.send_at).to eq send_at
expect(client_3.messages.first.send_at).to eq send_at
end
it 'sends an analytics event for each message in mass message' do
subject
expect_analytics_events(
'message_scheduled' => {
'mass_message' => true
}
)
expect_analytics_event_sequence(
'message_scheduled',
'message_scheduled'
)
end
end
end
end
|
# config valid only for current version of Capistrano
lock '3.4.0'
set :application, 'ideapool'
set :repo_url, 'git@github.com:tka/ideapool.git'
# Default branch is :master
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp
# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, '/home/ideapool'
# Default value for :scm is :git
# set :scm, :git
# Default value for :format is :pretty
# set :format, :pretty
# Default value for :log_level is :debug
# set :log_level, :debug
# Default value for :pty is false
# set :pty, true
# Default value for :linked_files is []
set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/secrets.yml', 'config/application.yml')
# Default value for linked_dirs is []
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'public/uploads', 'node_modules')
# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
# Default value for keep_releases is 5
set :keep_releases, 5
# unicorn
set :unicorn_pid, '/home/ideapool/shared/unicorn.pid'
set :unicorn_config_path, '/home/ideapool/shared/config/unicorn.rb'
namespace :deploy do
task :restart do
invoke 'unicorn:restart'
end
task :webpack_assets do
on release_roles(:app) do
within release_path do
execute :webpack
end
end
end
end
after 'deploy:updated', 'deploy:webpack_assets'
after 'deploy:publishing', 'deploy:restart'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.