text stringlengths 10 2.61M |
|---|
require 'archive/zip'
require 'optparse'
require 'fileutils'
require_relative '../lib/init'
require_relative '../lib/status'
require_relative '../lib/log'
require_relative '../lib/sync_ftp'
$YAVS_VERSION = 'v0.20'
module YAVS
def self.exist?
File.directory? '.yavs'
end
def self.lock
FileUtils.touch '.yavs/temp/lock'
end
def self.lock?
File.file? '.yavs/temp/lock'
end
def self.unlock
File.delete '.yavs/temp/lock'
end
end
|
class ChangeTo0Default < ActiveRecord::Migration
def change
change_column :products, :shipping, :integer, default: 0
end
end
|
require "rails_helper"
describe User, type: :model do
it { should validate_presence_of :username }
it { should validate_presence_of :email }
it { should validate_presence_of :password }
it { should validate_uniqueness_of :email }
it { should validate_length_of(:password).is_at_least(8) }
describe "access token" do
subject { user.access_token }
context "before the record has been saved" do
let(:user) { User.new(valid_user_attributes) }
it { is_expected.to be_nil }
end
context "after the record has been saved" do
let(:user) { User.create!(valid_user_attributes) }
it { is_expected.to_not be_nil }
end
end
def valid_user_attributes
{
email: Faker::Internet.email,
password: Faker::Internet.password,
username: Faker::Internet.user_name
}
end
end
|
class Admin::AdminController < ApplicationController
before_filter :require_user
filter_access_to :all
def index
@games = Game.find(:all, :order => :title )
end
protected
def permission_denied
flash[:error] = "You don't have permission to access that page"
redirect_to root_url
end
end
|
# The owner name associated with a specific AwardWalletAccount.
#
# Every AwardWalletAccount has an 'owner', which can either be a 'user' (a
# fully-fledged login account on AW.com, which we represent with the
# `AwardWalletUser` class) or a 'member' (just a name which the user adds on
# their AW dashboard.)
#
# 'owners' don't appear to be fully separate entity in the AW API; in the JSON
# we get from the API, the 'owner' is just a 'string' attribute of ecahjk\w
#
class AwardWalletOwner < ApplicationRecord
belongs_to :award_wallet_user
belongs_to :person, optional: true
has_many :award_wallet_accounts
end
|
class LetterFrequency
FREQUENCIES = {
'a' => 8.2,
'b' => 1.5,
'c' => 2.8,
'd' => 4.3,
'e' => 12.7,
'f' => 2.2,
'g' => 2.0,
'h' => 6.1,
'i' => 7.0,
'j' => 0.2,
'k' => 0.8,
'l' => 4.0,
'm' => 2.4,
'n' => 6.7,
'o' => 7.5,
'p' => 1.9,
'q' => 0.1,
'r' => 6.0,
's' => 6.3,
't' => 9.0,
'u' => 2.8,
'v' => 1.0,
'w' => 2.4,
'x' => 0.2,
'y' => 2.0,
'z' => 0.1
}
def self.freq_for_letter(letter)
FREQUENCIES[letter]
end
def self.by_frequency
FREQUENCIES.sort_by {|key, value| value}.map(&:first).reverse
end
end
|
module Enumerable
def accumulate
[].tap do |accumulated|
each { |a| accumulated << yield(a) }
end
end
end
|
RSpec.describe 'api/users/slots', type: :request do
path '/api/users/slots' do
get 'Slots' do
tags 'Slots'
consumes 'application/json'
security [Bearer: {}]
response '200', 'Slots' do
let(:slot) { { doctor_id: 10, user_id: 10} }
run_test!
end
response '422', 'invalid request' do
let(:slot) { {doctor_id: nil} }
run_test!
end
end
end
end
|
namespace :lapis do
task :docs do
abort "E: The current environment is `#{Rails.env}`. Please run CheckAPI in `test` mode to generate the documentation" unless Rails.env.test?
puts %x(cd doc && make clean && make && cd -)
puts 'Check the documentation under doc/:'
puts '- Licenses'
puts '- API endpoints'
puts '- Models and controllers diagrams'
puts '- Swagger UI'
end
end
|
module Defaults
@@defaults = {}
def self.defaults
@@defaults
end
def self.included(klazz)
klazz.extend(ClassMethods)
end
def load_defaults
@@defaults.each do |klazz, local_defaults|
if self.kind_of? klazz
local_defaults.each do |default|
attribute = default[:attribute]
block = default[:block]
if not instance_variable_defined?(attribute)
self.set_default(attribute, &block)
end
end
end
end
end
private
def set_default(attribute)
value = yield self
self.instance_variable_set(attribute, value)
end
module ClassMethods
def default(attribute_raw, &block)
default_exists = Defaults.defaults.key? self
local_defaults = default_exists ? Defaults.defaults[self] : []
attribute = "@".concat(attribute_raw.to_s).to_sym
local_defaults.push({:attribute => attribute, :block => block})
Defaults.defaults[self] = local_defaults if not default_exists
end
end
end
|
class Item < ActiveRecord::Base
belongs_to :restaurant
belongs_to :category
validates :category, presence: true
end
|
class AddDefaultSortAndViewToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :sort, :string, null: false, default: "default"
add_column :users, :view, :string, null: false, default: "default"
end
end
|
module Boxzooka
class ShipmentBillingListResponseBill < BaseElement
# Date/Time the Bill data was received.
scalar :bill_date, type: :datetime
# Weight used to calculate billing, generally based on whichever is
# greater between GravitionalWeight and DimensionalWeight
scalar :chargeable_weight, type: :decimal
# Identifies the consolidation in which the shipment was included.
scalar :consolidation_id, node_name: 'ConsolidationID'
# Date/Time the consolidation was created, if any.
scalar :consolidation_date, type: :datetime
# Unit of measurement used by DimWidth DimHeight & DimLength fields.
# IN or CM
scalar :dim_unit
# Calculated dimensional weight, if needed.
scalar :dimensional_weight, type: :decimal
# Actual weight of package.
scalar :gravitational_weight, type: :decimal
# Height of package, if measured.
scalar :height, type: :decimal
# Length of package, if measured.
scalar :length, type: :decimal
# Order ID corresponding to Bill.
scalar :order_id, node_name: 'OrderID'
# Date/Time the Order data was received.
scalar :order_date, type: :datetime
# Billed cost of shipment.
scalar :price, type: :decimal
# Order Currency, 3-char
scalar :price_currency
# Date/Time that the Shipment prepared for shipment.
scalar :shipment_date, type: :datetime
# Tracking Code.
scalar :tracking_code
# Unit of weight used by Weight field
# LBS or KGS
scalar :weight_unit
# of package, if measured.
scalar :width, type: :decimal
end
end
|
module BlacklightDpla
class SolrDoc
def self.index_docs_from_response(response)
response['docs'].each do |doc|
solr_doc = BlacklightDpla::SolrDoc.from_response_doc doc
pp solr_doc
pp Blacklight.solr.add solr_doc
end
pp Blacklight.solr.commit
end
def self.from_response_doc(doc)
solr_doc = {}
doc.keys.each do |key|
if SOLR_MAPPING.keys.include? key
case key
when 'audio_format_mp3'
m3u = HTTParty.get(doc[key])
mp3 = m3u.split.first
solr_doc[SOLR_MAPPING[key]] = mp3
solr_doc['format'] = 'mp3'
else
solr_doc[SOLR_MAPPING[key]] = doc[key]
end
end
end
solr_doc
end
end
end |
class Api::BaseController < ActionController::Base
before_action :set_cors_headers
# skip_before_action :verify_authenticity_token
private
def set_cors_headers
response.set_header "Access-Control-Allow-Origin", origin
end
def origin
request.headers["Origin"] || "*"
end
end |
class Comment < ActiveRecord::Base
bad_attribute_names :changed
has_many :field_data_comment_bodies, :foreign_key => 'entity_id', :order => 'entity_id DESC'
def last_modified
attributes['changed']
end
def body
data.comment_body_value unless data.nil?
end
def body_format
d = data
d.comment_body_format unless d.nil?
end
private
def data
field_data_comment_bodies.find_by_entity_id(cid)
end
end
|
require 'json'
MyApp.add_route('GET', '/search', {
"resourcePath" => "/Default",
"summary" => "",
"nickname" => "search_get",
"responseClass" => "void",
"endpoint" => "/search",
"notes" => "e.g. /search?q=query-words",
"parameters" => [
{
"name" => "q",
"description" => "",
"dataType" => "String",
"allowableValues" => "",
"paramType" => "query",
},
{
"name" => "start",
"description" => "",
"dataType" => "Integer",
"allowableValues" => "",
"defaultValue" => "0",
"paramType" => "query",
},
{
"name" => "rows",
"description" => "",
"dataType" => "Integer",
"allowableValues" => "",
"defaultValue" => "10",
"paramType" => "query",
},
]}) do
cross_origin
# the guts live here
require 'uri'
require 'httpclient'
client = HTTPClient.new
@param_q = params.has_key?(:q) ? params[:q].to_str : "sccp"
url = URI::HTTPS.build({:host => "opm00h.u-aizu.ac.jp", :path => '/solr/api/v1/search', :query => "q=#{@param_q}&wt=json&site="})
ret = client.get(url)
@result = JSON.parse(ret.body)
output = erb :header
output += erb :main
output += erb :footer
end
MyApp.add_route('GET', '/.spec', {
"resourcePath" => "/Default",
"summary" => "",
"nickname" => "spec_get",
"responseClass" => "void",
"endpoint" => "/.spec",
"notes" => "providing the openapi schema YAML file.",
"parameters" => [
]}) do
cross_origin
# the guts live here
File.read("openapi.yaml")
end
|
require 'net/http'
require 'kafka_rest/event_emitter'
require 'kafka_rest/logging'
require 'kafka_rest/producable'
require 'kafka_rest/broker'
require 'kafka_rest/client'
require 'kafka_rest/consumer'
require 'kafka_rest/consumer_instance'
require 'kafka_rest/consumer_stream'
require 'kafka_rest/partition'
require 'kafka_rest/schema'
require 'kafka_rest/schema_parser'
require 'kafka_rest/topic'
require 'kafka_rest/version'
module KafkaRest
EMPTY_STRING = ''.freeze
TWO_OCTET_JSON = '{}'.freeze
RIGHT_BRACE = '}'.freeze
class << self
def logger
KafkaRest::Logging.logger
end
end
end
|
class CreateShifts < ActiveRecord::Migration[6.0]
def change
create_table :shifts do |t|
t.string :shift_staff, nill: false
t.datetime :start_time
t.datetime :stop_time
t.references :user, null: false, foreign_key: true
t.timestamps
end
end
end
|
require 'test_helper'
require 'wsdl_mapper/type_mapping/string'
module TypeMappingTests
class StringTest < ::WsdlMapperTesting::Test
include WsdlMapper::TypeMapping
def test_to_ruby
assert_equal 'foo', String.to_ruby('foo')
end
def test_to_xml
assert_equal 'foo', String.to_xml('foo')
assert_equal 'foo', String.to_xml(:foo)
assert_equal '1', String.to_xml(1)
assert_equal '1.23', String.to_xml(1.23)
end
def test_ruby_type
assert_equal ::String, String.ruby_type
end
end
end
|
class ClientsController < ApplicationController
def index
@clients = Client.all.reverse
end
def new
@new_client = Client.new
end
def create
@new_client = Client.create(client_params)
if @new_client.save
redirect_to root_path
else
render :new
end
end
private
def client_params
params.require(:client).permit(:name, :age)
end
end |
class Admin::PostsController < Admin::ApplicationController
uses_tiny_mce :only => [:new, :create, :edit, :update]
make_resourceful do
actions :all
end
private
def current_object
@current_object ||= current_model.find_by_permalink(params[:id])
end
def current_objects
@current_objects ||= current_model.all.paginate(:per_page => 20, :page => params[:page], :order => 'created_at DESC')
end
end |
require "rails_helper"
describe "Counts Query API", :graphql do
describe "counts" do
let(:query) do
<<-'GRAPHQL'
query {
counts {
missedCalls
unreadConversations
newVoicemails
}
}
GRAPHQL
end
it "returns counts" do
user = create(:user_with_number)
call = create(:incoming_call, :not_viewed, user: user)
create(:conversation, :unread, user: user)
create(:voicemail, :not_viewed, voicemailable: call)
result = execute query, as: user
missed_calls = result[:data][:counts][:missedCalls]
unread_conversations = result[:data][:counts][:unreadConversations]
new_voicemails = result[:data][:counts][:newVoicemails]
expect(missed_calls).to eq(1)
expect(unread_conversations).to eq(1)
expect(new_voicemails).to eq(1)
end
end
end
|
class WorkersController < ApplicationController
before_action :authenticate_user!
def index
@workers = Worker.all
end
def skills_list
render json: Worker.find_name_by_match(params[:query])
end
def show
@worker = Worker.includes(:skills).where('users.id = ?', params[:id]).first
end
def skills
@worker = current_user
end
def update
if current_user.update(worker_params)
redirect_to workers_path, notice: 'Worker skills were successfully updated.'
else
render :skills
end
end
private
def worker_params
params.require(:worker).permit(:name, :email, skills_list: [])
end
end
|
#digits- Returns the array inluding the digits extracted by place-value notation with radix base of int
p 12345.digits
puts".............."
p 12345.to_s.chars.map(&:to_i).reverse
puts "........."
p 234.digits(100) # setting base 100
puts"................"
#base should be greater than or equal to 2
puts "executing -34324.digit(8)"
begin
puts -34324.digits(8)
rescue => error
p error.message
end
|
require 'mechanize'
require 'date'
module FCleaner
HOMEPAGE_URL = "https://m.facebook.com".freeze
LOGIN_URL = "#{HOMEPAGE_URL}/login.php".freeze
PROFILE_URL = "#{HOMEPAGE_URL}/profile.php".freeze
class ActivityLog
attr_reader :email, :pass
def initialize(email, pass)
@email = email.chomp
@pass = pass.chomp
@agent = Mechanize.new { |agent| agent.user_agent_alias = 'iPhone' }
end
def login
home_page = @agent.get(HOMEPAGE_URL)
login_form = home_page.form
login_form.field_with(:name => 'email').value = @email
login_form.field_with(:name => 'pass').value = @pass
login_page = @agent.submit login_form
if login_page.body.match('Your password was incorrect.')
raise InvalidLoginCredentials, "Your password was incorrect."
end
puts 'Successfully logged in!'
end
def activity_page_url(timestamp)
"#{HOMEPAGE_URL}/#{user_id}/allactivity?timeend=#{timestamp}"
end
def clean
start_date = Date.new(reg_year, 1, 1)
today = Date.today
end_date = Date.new(today.year, today.month, 1)
(start_date..end_date).select {|d| d.day == 1}.each do |date|
puts "Cleaning #{date}"
clean_month(date.year, date.month)
end
end
def clean_month(year, month)
timestamp = DateTime.new(year, month, -1, 23, 59, 59).to_time.to_i
activity_url = activity_page_url(timestamp)
activity_page = @agent.get(activity_url)
activities = activity_page
.parser
.xpath("//div[@id[starts-with(.,'u_0_')]]")
activities.each do |activity|
action = ['Delete','Delete Photo','Unlike','Hide from Timeline'].detect do
|text| !activity.xpath(".//a[text()='#{text}']").empty?
end
if action
url = activity
.xpath(".//a[text()='#{action}']")
.first
.attribute('href')
.value
act_text = activity.xpath("(.//a)[1]").text.strip
puts "#{action} => #{act_text}"
begin
@agent.get(url)
rescue
puts "FAILED => #{action} => #{act_text}"
end
end
end
end
def user_id
@user_id ||= build_user_id
end
def reg_year
@reg_year ||= build_reg_year
end
def build_user_id
@agent.get(PROFILE_URL)
.links_with(:text => 'Activity Log')
.first
.href
.match(%r{/(\d+)/})
.captures
.first
end
def build_reg_year
year_divs = @agent.get("#{HOMEPAGE_URL}/#{self.user_id}/allactivity")
.parser
.xpath("//div[@id[starts-with(.,'year_')]]")
years = year_divs.collect do |div|
div.attribute('id').to_s.gsub(/^year_/, '')
end
reg_year = if years.empty?
Date.today.year
else
years.min.to_i
end
puts "Reg year: #{reg_year}"
reg_year
end
end
class InvalidLoginCredentials < Exception; end;
end
|
require_relative 'db_connection'
require_relative '01_sql_object'
module Searchable
def where(params)
where_line = params.keys.map{ |col| "#{col} = ?"}.join(" AND ")
col_values = params.values
results = DBConnection.execute(<<-SQL, *col_values)
SELECT
*
FROM
#{self.table_name}
WHERE
#{where_line}
SQL
return [] if results.length == 0
results.map { |row| self.new(row) }
end
end
class SQLObject
extend Searchable
# Mixin Searchable here...
end
|
# coding: utf-8
require "spec_helper"
describe Rstt do
describe "module variables" do
describe "responds to .." do
it "should respond to :lang" do
Rstt.respond_to?(:lang).should be_true
end
it "should respond to :content" do
Rstt.respond_to?(:content).should be_true
end
it "should respond to :origin" do
Rstt.respond_to?(:origin).should be_true
end
it "should respond to :tagged" do
Rstt.respond_to?(:tagged).should be_true
end
end # responds to ..
describe "getting" do
it "should print both" do
Rstt.set_input lang: "de", content: "Das ist ein einfacher Dummy Satz."
Rstt.print.should be_true
end
end # getting
describe "setting" do
before(:each) do
@input = {lang: "de", content: "Das ist ein einfacher Dummy Satz."}
end
it "should set both by :set_input " do
Rstt.set_input @input
Rstt.lang.should == @input[:lang]
Rstt.content.should == @input[:content]
end
end # setting
end # module variables
describe "tagging stages" do
before(:each) do
@input = {lang: "de", content: "Das ist ein einfacher Dummy Satz."}
end
it "should pos tagging on given input data" do
Rstt.set_input @input
Rstt.tagging
end
it "origin should be content after preprocessing" do
Rstt.set_input @input
Rstt.preprocessing
Rstt.origin.should == @input[:content]
end
describe "language finding and command building" do
it "should find the right language dependent on input" do
Rstt.set_input lang: "en", content: ""
Rstt.get_command_language.should == ("english")
end
it "should raise an exception if language not supported" do
Rstt.set_input lang: "xy", content: ""
expect {Rstt.get_command_language}.to raise_error
end
it "should raise an exception if language not installed" do
Rstt.set_input lang: "ru", content: ""
expect {Rstt.get_command_language}.to raise_error
end
it "should build the correct tagging command, dependend on input language" do
Rstt.set_input lang: "en", content: ""
Rstt.build_tagging_command.should == ("tree-tagger-english")
end
it "should prefer utf8 over other" do
Rstt.set_input lang: "de", content: ""
Rstt.build_tagging_command.should == ("tree-tagger-german-utf8")
end
end # language finding and command building
describe "output format" do
before(:each) do
@input = {lang: "de", content: "Das ist ein einfacher Dummy Satz"}
end
it "should be an array as output" do
Rstt.set_input @input
Rstt.preprocessing
Rstt.tagging.should be_a Array
end
it "should have correct count" do
Rstt.set_input @input
verfifier = @input[:content].split(" ").length
Rstt.preprocessing
Rstt.tagging
Rstt.tagged.should have(verfifier).things
end
# testing output format, means: for each word in given input gives an array
# with: 1. input word, 2. tagging category, 3. lemma
# could be done over output length
it "should have correct output format" do
Rstt.set_input @input
Rstt.preprocessing
Rstt::LANGUAGES
Rstt.tagging.first.should have(3).things
end
end # output format
end # tagging stages
end
|
class Resources::Catalog::ProductsController < ResourcesController
def show
opts = options :include => {:product => [:pros, :cons, :user_tags]}
order, limit = opts.delete(:order), opts.delete(:limit)
opts.delete :offset
@product = Restful::PartnerProduct.find_by_partner_key! params[:id], opts
reviews = Restful::Review.
find_all_by_product_id @product.resource.product_id,
options(:include => [{:user => :badges}, :pros, :cons, :user_tags], :joins => :stat)
reviews.pagination.path = \
reviews_resources_product_path @product.product.resource, @product.format
@product.product.instance_variable_get(:@loaded)[:reviews] = reviews
return unless stale? :etag => @product, :public => true
# TODO: Last-Modified header?
respond_to do |format|
format.json { render :json => @product }
format.xml { render :xml => @product }
end
end
end
|
#Function that returns all mutants
def get_all_mutants()
request = API_URL + "mutants"
@response = RestClient.get request
#@parsed_response = JSON.parse(@response)
#puts @parsed_response
parse_mutant(@response)
#puts @response
return
end
#Function that returns mutant, given the id
def get_mutant(m_id)
get_request = API_URL + "mutants/#{m_id}"
@response = RestClient.get(get_request){|response, request, result| response }
@parsed_response = JSON.parse(@response)
@parsed_response["status"] ? @parsed_response.merge("code" => @parsed_response["status"]) : parse_mutant(@parsed_response)
return
end
#Function that makes a mutant
def create_mutant(mutant_info)
#mutant_info = DEFAULT_MUTANT.merge(mutant_info)
mutant_info = {"mutant" => mutant_info}
request = API_URL + "mutants"
@response = RestClient.post(request, mutant_info){|response, request, result| response }
@parsed_response = JSON.parse(@response)
if @parsed_response["status"]
@parsed_response.merge("code" => @parsed_response["status"])
return
else
save_mutant_id(@parsed_response["id"])
parse_mutant(@parsed_response)
log_mutant("created")
end
return
end
#Function that updates a mutant, given the id
def update_mutant(m_id, mutant_info)
mutant_info = {"mutant" => mutant_info}
request = API_URL + "mutants/#{m_id}"
@response = RestClient.patch(request, mutant_info){|response, request, result| response }
@parsed_response = JSON.parse(@response)
if @parsed_response["status"]
@parsed_response.merge("code" => @parsed_response["status"])
return
else
parse_mutant(@parsed_response)
log_mutant("updated")
end
return
end
#Function that deletes a mutant, given the id
def delete_mutant(m_id)
request = API_URL + "mutants/#{m_id}"
@response = RestClient.delete request
log_mutant("deleted")
return
end
def parse_mutant(mutant_info)
id = mutant_info["id"]
mutant_name = mutant_info["mutant_name"]
power = mutant_info["power"]
real_name = mutant_info["real_name"]
eligibility_begins_at = mutant_info["eligibility_begins_at"]
eligibility_end_at = mutant_info["eligibility_ends_at"]
may_advise_beginning_at = mutant_info["may_advise_beginning_at"]
url = mutant_info["url"]
end
|
require './Point'
class List
def initialize
@l = []
end
def add (p)
i = 0
while (i < @l.length) && (@l[i].distance < p.distance())
i += 1
end
@l.insert(i, p)
end
def to_s
to_ret = '['
for ps in @l
to_ret += ' ' + ps.to_s
end
return (to_ret + ' ]')
end
def delete(p)
@l.delete(p)
end
def le
puts @l.length
end
def exists(p)
if @l.index(p)
print 'There is a point like: '
puts p.to_s()
else
print 'There is NO point like: '
puts p.to_s()
end
end
def condi_print(p)
for ps in @l
if(ps.dist_between(p) < ps.distance)
puts ps.to_s()
end
end
end
end
|
class ArticlesController < ApplicationController
skip_before_action :require_login, only: [:show]
def show
@article = Article.find_by(id: params[:id])
@user = User.find_by(id: @article.user_id)
end
def new
@user = User.find_by(id: session[:user_id])
@article = Article.new
end
def create
article = Article.new(article_params)
if article.save
user = User.find_by(id: session[:user_id])
user.articles << article
redirect_to article_path(article)
else
@errors = article.errors.full_messages
render new_article_path
end
end
def edit
@article = Article.find_by(id: params[:id])
if authorized?(@article.user_id)
@user = User.find_by(id: @article.user_id)
end
end
def update
@article = Article.find_by(id: params[:id])
if authorized?(@article.user_id)
if @article.update(article_params)
redirect_to article_path(@article)
else
@error = "Nope."
render edit_article_path(@article)
end
end
end
def destroy
@article = Article.find_by(id: params[:id])
if authorized?(@article.user_id)
@article.destroy
redirect_to user_path(session[:user_id])
end
end
private
def article_params
params.require(:article).permit(:user_id, :category_id, :title, :content, :price, :item)
end
end |
#
# Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
#
# 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.
#
Puppet::Type.newtype(:evs_vport) do
@doc = "Manage the configuration of EVS VPort"
ensurable do
newvalue(:present) do
provider.create
end
newvalue(:absent) do
provider.destroy
end
# Resets the specified VPort
newvalue(:reset) do
provider.reset
end
end
newparam(:name) do
desc "The full name of Virtual Port for EVS"
munge do |value|
if value.split("/").length != 3
fail "Invalid VPort name\n" \
"Name convention must be <tenant>/<evs>/<vport>"
else
value
end
end
end
## read/write properties (always updatable) ##
newproperty(:cos) do
desc "802.1p priority on outbound packets on the virtual port"
end
newproperty(:maxbw) do
desc "The full duplex bandwidth for the virtual port"
end
newproperty(:priority) do
desc "Relative priority of virtual port"
newvalues("high", "medium", "low", "")
end
newproperty(:protection) do
desc "Enables one or more types of link protection"
# verify protection value: comma(,) separable
validate do |value|
value.split(",").collect do |each_val|
if not ["mac-nospoof", "restricted", "ip-nospoof",
"dhcp-nospoof", "none", ""].include? each_val
fail "Invalid value \"#{each_val}\". "\
"Valid values are mac-nospoof, restricted, "\
"ip-nospoof, dhcp-nospoof, none."
end
end
end
end
## read-only properties (Settable upon creation) ##
newproperty(:ipaddr) do
desc "The IP address associated with the virtual port"
end
newproperty(:macaddr) do
desc "The MAC address associated with the virtual port"
end
newproperty(:uuid) do
desc "UUID of the virtual port"
end
end
|
require File.dirname(__FILE__) + '/spec_helper'
describe Google do
before(:each) do
@abbr = Google::DidYouMean.new
end
it "should search google for did you mean" do
@abbr.check("exalty").should eql("exactly")
end
it "should split word seperated by underline and search on this seperate" do
@abbr.check("mulipy_exalty").should eql("multiply_exactly")
end
it "should contain description for the changes" do
@abbr.check("multiply_exalty")
@abbr.tool_tip.should eql("No 'Did you mean' found for multiply.\nexalty changed to exactly.")
end
it "should return if one or more words is corrected" do
@abbr.check("exalty")
@abbr.should be_found
end
it "should reset instance variables" do
@abbr.found = true
@abbr.tool_tip = "test"
@abbr.reset
@abbr.should_not be_found
@abbr.tool_tip.should be_empty
end
end |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable,:recoverable, :rememberable, :confirmable,:validatable
validates :first_name,:last_name,:presence=> true,:if=>:not_guest
validates :terms_conditions,:acceptance => true,:if=>:not_guest
validates :email,:presence => true, :uniqueness => true, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i},:if=>:not_an_secondary
attr_accessible :email, :password, :remember_me,:first_name,:last_name,:title,:phone,:mobile,:time_zone,:color,:status,:terms_conditions,:is_guest
has_many :project_guests,:foreign_key=>'guest_id'
has_many :projects
has_many :project_users
has_one :attachment ,:as => :attachable, :dependent=>:destroy
has_many :chats
has_many :messages, :through => :activities, :source => :resource, :source_type => 'Message'
has_many :activities
has_many :secondary_emails
has_many :comments
has_many :task_lists
has_many :tasks,:through=>:task_lists
DEFAULT_AVATAR="/images/1300771661_stock_person.png"
named_scope :all_users, :select=>'email',:order => 'id'
scope :active_users,:conditions=>['status=?',true]
def self.verify_email_id(from_address)
find(:first,:conditions=>['users.email=:email or secondary_emails.email=:email',{:email=>from_address}],:include=>:secondary_emails)
end
def not_guest
self.is_guest ? false : true
end
def not_an_secondary
SecondaryEmail.find_by_email(self.email).nil? ? true : errors.add(:email,"Sorry! The Email you entered is already in use.")
end
def confirmation_required?
!confirmed? && !self.is_guest
end
#overwrite method to login using the secondary emails
def self.find_for_authentication(conditions={})
login = conditions.delete(:email)
find(:first,:conditions=>["(users.email=:value or secondary_emails.email=:value) AND users.is_guest=:fal AND users.status=:valid",{:value => login,:fal=>false,:valid=>true}],:include=>:secondary_emails)
end
#starred messages from all project
def starred_message_comments(sort_by=nil,order=nil)
sort_field=find_sort_field(sort_by)
message=[]
starred_comments(nil,nil).each do |act|
message<<last_created_message(act.resource.commentable.id)
end
message.flatten.uniq
end
def starred_messages(sort_by=nil,order=nil)
order="desc" unless order
sort_field=find_sort_field(sort_by)
activities.where('resource_type=? AND is_starred=? AND is_delete=?',"Message",true,false).order("#{sort_field} #{order}")
end
def starred_comments(sort_by,order)
order="desc" unless order
sort_field=find_sort_field(sort_by)
activities.where('resource_type=? AND is_starred=? AND is_delete=?',"Comment",true,false).order("#{sort_field} #{order}")
end
def all_messages(sort_by,order)
total_messages(sort_by,order).group_by{|m| m.updated_at.to_date}
end
def all_message_ids
Message.all_message_ids(user_active_project_ids)
end
def all_task_ids
Task.all_task_ids(user_active_project_ids)
end
def total_messages(sort_by=nil,order=nil)
sort_field=find_sort_field(sort_by)
order="desc" unless order
if sort_field=="is_starred" || sort_field=="is_read"
activities.where("resource_type=? AND resource_id IN (?) AND is_delete=? AND #{sort_field}=?","Message",all_message_ids,false,true).order("created_at #{order}")
else
activities.where('resource_type=? AND resource_id IN (?) AND is_delete=?',"Message",all_message_ids,false).order("#{sort_field} #{order}")
end
end
def last_created_message(message_id)
activities.where('resource_type=? AND resource_id=? AND is_delete=?',"Message",message_id,false)
end
def find_sort_field(sort)
sort ||="date"
sort.downcase!
sort_field=case sort
when "unread"
"is_read"
when "starred"
"is_starred"
else
"updated_at"
end
sort_field
end
def group_starred_messages(sort_by=nil,order=nil)
(starred_messages(sort_by,order)+starred_message_comments(sort_by,order)).uniq.group_by{|m| m.updated_at.to_date}
end
def group_unread_messages(order=nil)
order="desc" unless order
activities.where('resource_type=? AND is_read=? AND is_delete=?',"Message",false,false).order("updated_at #{order}").group_by{|m| m.updated_at.to_date}
end
#count of all starred messages
def starred_messages_count
starred_messages(nil,nil).count+starred_comments(nil,nil).count
end
def all_messages_count
total_messages.count
end
def starred_tasks
activities.where('resource_type=? AND is_starred=? AND is_delete=?',"Task",true,false)
end
def total_starred_tasks
(starred_tasks+starred_task_com).uniq
end
def starred_task_com
Activity.find_all_activity(self.all_starred_comment_tasks,self.id,"Task")
end
def starred_task_count
starred_tasks.count+starred_task_comments.count
end
def all_task_comments
comments=[]
find_all_tasks.each do |activity|
find_activity_resource=activity.resource
comments<<find_activity_resource.comments.map(&:id)
end
comments.flatten!
end
def starred_task_comments
activities.where('resource_type=? AND resource_id IN (?) AND is_starred=?',"Comment",all_task_comments,true)
end
def all_starred_comment_tasks
task_ids=[]
starred_task_comments.each do |activity|
find_activity_resource_for_starredcomments=activity.resource
task_ids<<find_activity_resource_for_starredcomments.commentable_id
end
task_ids.uniq
end
#starred messages from the project
def project_starred_messages(project_id,sort_by,order)
b=[]
project_id=project_id.to_i
total_messages(sort_by,order).collect{|a| b<<a if a.resource.project_id==project_id}
b
end
def group_project_messages(project_id,sort_by=nil,order=nil)
project_starred_messages(project_id,sort_by,order).group_by{|m| m.updated_at.to_date}
end
#starred count from all project
def starred_count
starred_messages.count
end
#starred count of the individual project
def project_starred_count(project_id)
project_starred_messages(project_id).count
end
def user_active_projects
Project.find(:all,:conditions=>['project_users.status=? AND project_users.user_id=? AND projects.status!=?',true,self.id,ProjectStatus::COMPLETED],:include=>:project_users)
end
def completed_projects
Project.find(:all,:conditions=>['project_users.status=? AND project_users.user_id=? AND projects.status=?',true,self.id,ProjectStatus::COMPLETED],:include=>:project_users)
end
def user_active_project_ids
user_active_projects.map(&:id)
end
def full_name
"#{first_name} #{last_name}"
end
def project_memberships
Project.user_projects(self.id)
end
def message_activity(message_id)
activities.find_by_resource_type_and_resource_id("Message",message_id)
end
def task_activity(message_id)
activities.find_by_resource_type_and_resource_id("Message",message_id)
end
def my_contacts
User.find(:all,:conditions=>['project_users.project_id in (?) AND users.status=? AND project_users.status=?',project_memberships,true,true],:include=>:project_users)
end
def self.members_in_project(project_id)
find(:all,:conditions=>['project_users.project_id=? AND project_users.status=?',project_id,true],:include=>:project_users)
end
def self.members_as_guest(project_id)
find(:all,:conditions=>['project_guests.project_id=? AND project_guests.status=?',project_id,true],:include=>:project_guests)
end
def self.all_members(project_id)
(self.members_in_project(project_id)+self.members_as_guest(project_id)).uniq
end
def self.online_members(project_id)
find(:all,:conditions=>['project_users.project_id=? AND project_users.status=? AND project_users.online_status=?',project_id,true,true],:include=>:project_users)
end
def name
first_name && last_name ? full_name : email
end
def activities_comments(type_ids)
activities.where('resource_type=? and resource_id in (?) and is_delete=?',"Comment",type_ids,false)
end
def is_message_subscribed?(message_id)
activity=message_activity(message_id)
activity.is_subscribed if activity
end
def is_task_subscribed?(task_id)
activity=Activity.find_activity(task_id,self.id,"Task")
activity.is_subscribed
end
def hash_activities_comments(type_ids)
type_ids=[type_ids] unless type_ids.is_a?(Array)
#~ comment_activities=activities.find(:all,:conditions=>['resource_type=? and resource_id in (?) and is_delete=?',"Comment",type_ids,false],:select=>[:is_starred,:is_read,:resource_id,:id])
comment_activities=Activity.check_hash_activities_comments_info(type_ids,self.id)
values=[]
comment_activities.collect {|t| values<<Comment.find_hash(t.resource_id,self).merge(t.attributes)}
values
end
def image_url
attachment ? attachment.public_filename(:small) : DEFAULT_AVATAR
end
def user_time(time)
if time_zone
time_diff=time_zone.split(")")[0].split("GMT")[1].split(":")
hour=time_diff[0].to_i.hours
min=time_diff[1].to_i.minutes
total_diff=hour<0 ? hour-min : hour+min
else
total_diff=0.seconds
end
time.gmtime+total_diff.seconds
end
def guest_message_activities
activities.where('resource_type=?',"Message")
end
def guest_task_activities
activities.where('resource_type=?',"Task")
end
def guest_update_message(project_id)
project_id=project_id.to_i
guest_message_activities.collect{|a| a.update_attribute(:is_delete,false) if a.resource.project_id==project_id}
guest_task_activities.collect{|a| a.update_attribute(:is_delete,false) if a.resource.task_list.project_id==project_id}
project=Project.find_by_id(project_id)
project.messages.each do |message|
create_old(message)
message.comments.each do |comment|
create_old(comment)
end
end
project.tasks.each do |task|
create_old(task)
task.comments.each do |comment|
create_old(comment)
end
end
end
def create_old(object)
activity=activities.find_or_create_by_resource_type_and_resource_id(object.class.name,object.id)
activity.update_attributes(:created_at=>object.created_at,:updated_at=>object.updated_at)
end
def unread_all_message
#~ activities.find(:all,:conditions=>['resource_type=? AND is_read = ? AND is_delete=?',"Message",false,false])
Activity.check_all_unread_messages(self.id,self.all_message_ids)
end
def unread_all_message_count
unread_all_message.count
end
def find_all_tasks(sort_by=nil,order=nil)
Activity.check_all_tasks_info(self.id,all_task_ids,sort_by,order)
end
def all_tasks(order=nil)
#~ activities.find(:all,:conditions=>['resource_type=? AND is_delete=?',"Task",false],:order=>"created_at desc")
not_completed_tasks(find_all_tasks(sort_by=nil,order))
end
def group_all_tasks(order=nil)
sort_group_all_tasks(order)
end
def sort_group_all_tasks(order=nil)
order="asc" unless order
tasks=all_tasks.group_by{|a| a.resource.task_list_id}
temp=tasks
temp.each do |b|
unless b.nil?
if order=="desc"
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}.reverse
else
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}
end
end
end
tasks
end
def find_my_tasks(sort_by)
Activity.check_my_tasks_info(self.id,all_task_ids,sort_by)
end
def my_tasks(sort_by)
#~ activities.find(:all,:conditions=>['resource_type=? AND is_delete=? AND is_assigned=?',"Task",false,true],:order=>"created_at desc")
not_completed_tasks(find_my_tasks(sort_by))
end
def group_my_tasks(sort_by=nil,order=nil)
sort_my_tasks(sort_by,order)
end
def sort_my_tasks(sort_by=nil,order=nil)
order="asc" unless order
tasks=my_tasks(sort_by).group_by{|a| a.resource.task_list_id}
temp=tasks
temp.each do |b|
if order=="desc"
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}.reverse
else
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}
end
end
tasks
end
def find_starred_tasks
Activity.check_starred_task(self.id)
end
def starred_tasks
#~ activities.find(:all,:conditions=>['resource_type=? AND is_delete=? AND is_starred=?',"Task",false,true],:order=>"created_at desc")
not_completed_tasks(find_starred_tasks)
end
def group_starred_tasks(order=nil)
sort_group_sort_tasks(order)
end
def sort_group_sort_tasks(order=nil)
order="asc" unless order
tasks=total_starred_tasks.group_by{|a| a.resource.task_list_id}
temp=tasks
temp.each do |b|
if order=="desc"
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}.reverse
else
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}
end
end
tasks
end
def completed_tasks(sort_by,order)
activities=[]
find_all_tasks(sort_by).collect{|t| activities << t if t.resource && t.resource.is_completed}
activities
end
def sort_completed_tasks(sort_by=nil,order=nil)
order="asc" unless order
tasks=completed_tasks(sort_by,order).group_by{|a| a.resource.task_list_id}
temp=tasks
temp.each do |b|
if order=="desc"
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}.reverse
else
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}
end
end
tasks
end
def group_completed_tasks(sort_by=nil,order=nil)
sort_completed_tasks(sort_by,order)
end
def project_tasks(task_ids)
Activity.user_projects_tasks(task_ids,self.id)
#~ activities.find(:all,:conditions=>['resource_type=? AND is_delete=? AND resource_id IN (?)',"Task",false,task_ids],:order=>"created_at desc")
end
def not_completed_tasks(collection)
activities||=[]
collection.collect{|t| activities << t if t.resource && !t.resource.is_completed}
return activities
end
def group_project_tasks(task_ids,order=nil)
sort_group_project_tasks(task_ids,order)
end
def sort_group_project_tasks(task_ids,order)
order="asc" unless order
tasks=project_tasks(task_ids).group_by{|a| a.resource.task_list_id}
temp=tasks
temp.each do |b|
if order=="desc"
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}.reverse
else
tasks[b[0]]= b[1].sort_by{|a| a.resource.test_date}
end
end
tasks
end
def self.u_count_val
find(:all,:conditions=>['is_guest=?',false])
end
def self.g_count_data
find(:all,:conditions=>['is_guest=?',true])
end
def self.project_team_members(project_id)
find(:all,:conditions=>['project_users.project_id=:project_id AND project_users.status=:value AND users.status=:value',{:project_id=>project_id,:value=>true}],:include=>:project_users,:select=>[:id,:first_name,:last_name])
end
def all_tasks_count
{:completed_count=>completed_tasks(nil,nil).count,:all_count=>all_tasks(nil).count,:starred_count=>starred_task_count,:my_count=>my_tasks(nil).count}
end
def self.find_all_user_except_guest
find(:all,:conditions=>['is_guest=? and status=?',false,true])
end
def self.find_all_user_with_guest
find(:all,:conditions=>['is_guest=? and status=?',true,true])
end
def chat_name
"#{first_name.capitalize} #{last_name.first.capitalize}."
end
def user_data
{:name=>self.full_name,:title=>(title ? title : ""),:email=>email,:id=>id,:image=>self.image_url}
end
def user_chat_data
{:name=>self.chat_name,:color=>color,:id=>id}
end
end |
class CreateMessageThreadSubscriptions < ActiveRecord::Migration
def change
create_table :message_thread_subscriptions do |t|
t.references :user
t.references :thread
t.timestamps
end
add_index :message_thread_subscriptions, :user_id
add_index :message_thread_subscriptions, :thread_id
end
end
|
class AddRateToPhotos < ActiveRecord::Migration
def up
add_column :photos, :rate, :integer, default: 1 unless column_exists? :photos, :rate
end
def down
remove_column :photos, :rate if column_exists? :photos, :rate
end
end
|
require 'matrix'
require 'benchmark'
=begin
class Matrix2 < Array
def initialize(n)
createRandomMatrix(n)
end
def createRandomMatrix(n)
matrix = Array.new(n)
n.times do |i|
row = Array.new(n)
n.times do |j|
row[j-1] = Random.rand(99)
end
self.push row
end
end
def inspect
ret = ""
self.each do |arr|
line = "|"
arr.each_with_index do |arr2, i|
char = arr2.to_s
line += char.rjust(3-char.length, ' ')
line += ", " if i < (arr.length-1)
end
ret += line + "|\n"
end
ret
end
def * (matrix)
return -1 if matrix.length != self.length
n = matrix.length
n2 = n/2
a = self[0...n][0...n]
b = self[0...n][n..-1]
c = self[n..-1][0...n]
d = self[n..-1][n..-1]
e
f
g
h
end
end
=end
def pow2(n)
return n & (n-1) == 0
end
def combine4(m1,m2,m3,m4)
left = m1.to_a + m3.to_a
right = m2.to_a + m4.to_a
#p m1, m2, m3, m4
#p "Left: ", left, " Right: ", right
left.size.times do |i|
left[i-1].concat right[i-1]
end
Matrix.rows(left)
end
def strassen(m1,m2)
flag = false
if (m1.row_count != m2.row_count) || (!m1.square? || !m2.square?)
p "bad"
return -1
end
n = m1.row_count
return Matrix.build(1){m1[0,0] * m2[0,0]} if n == 1
n2 = n/2
a = m1.minor(0...n2, 0...n2)
b = m1.minor(0...n2, n2..-1)
c = m1.minor(n2..-1, 0...n2)
d = m1.minor(n2..-1, n2..-1)
e = m2.minor(0...n2, 0...n2)
f = m2.minor(0...n2, n2..-1)
g = m2.minor(n2..-1, 0...n2)
h = m2.minor(n2..-1, n2..-1)
p1 = strassen(a,f-h)
p2 = strassen(a+b,h)
p3 = strassen(c+d,e)
p4 = strassen(d,g-e)
p5 = strassen(a+d, e+h)
p6 = strassen(b-d,g+h)
p7 = strassen(a-c, e+f)
return combine4(p5+p4-p2+p6, p1+p2, p3+p4, p1+p5-p3-p7)
end
m1 = Matrix.build(64){rand(10)}
m2 = Matrix.build(64){rand(10)}
puts Benchmark.measure{strassen(m1,m2)}
puts Benchmark.measure{ m1 * m2 } |
require "spec_helper"
require "rake"
load "./lib/tasks/paperclip.rake"
describe Rake do
context "calling `rake paperclip:refresh:thumbnails`" do
before do
rebuild_model
allow(Paperclip::Task).to receive(:obtain_class).and_return("Dummy")
@bogus_instance = Dummy.new
@bogus_instance.id = "some_id"
allow(@bogus_instance.avatar).to receive(:reprocess!)
@valid_instance = Dummy.new
allow(@valid_instance.avatar).to receive(:reprocess!)
allow(Paperclip::Task).to receive(:log_error)
allow(Paperclip).to receive(:each_instance_with_attachment).and_yield(@bogus_instance).and_yield(@valid_instance)
end
context "when there is an exception in reprocess!" do
before do
allow(@bogus_instance.avatar).to receive(:reprocess!).and_raise
end
it "catches the exception" do
assert_nothing_raised do
::Rake::Task["paperclip:refresh:thumbnails"].execute
end
end
it "continues to the next instance" do
expect(@valid_instance.avatar).to receive(:reprocess!)
::Rake::Task["paperclip:refresh:thumbnails"].execute
end
it "prints the exception" do
exception_msg = "Some Exception"
allow(@bogus_instance.avatar).to receive(:reprocess!).and_raise(exception_msg)
expect(Paperclip::Task).to receive(:log_error) do |str|
str.match exception_msg
end
::Rake::Task["paperclip:refresh:thumbnails"].execute
end
it "prints the class name" do
expect(Paperclip::Task).to receive(:log_error) do |str|
str.match "Dummy"
end
::Rake::Task["paperclip:refresh:thumbnails"].execute
end
it "prints the instance ID" do
expect(Paperclip::Task).to receive(:log_error) do |str|
str.match "ID #{@bogus_instance.id}"
end
::Rake::Task["paperclip:refresh:thumbnails"].execute
end
end
context "when there is an error in reprocess!" do
before do
@errors = double("errors")
allow(@errors).to receive(:full_messages).and_return([""])
allow(@errors).to receive(:blank?).and_return(false)
allow(@bogus_instance).to receive(:errors).and_return(@errors)
end
it "continues to the next instance" do
expect(@valid_instance.avatar).to receive(:reprocess!)
::Rake::Task["paperclip:refresh:thumbnails"].execute
end
it "prints the error" do
error_msg = "Some Error"
allow(@errors).to receive(:full_messages).and_return([error_msg])
expect(Paperclip::Task).to receive(:log_error) do |str|
str.match error_msg
end
::Rake::Task["paperclip:refresh:thumbnails"].execute
end
it "prints the class name" do
expect(Paperclip::Task).to receive(:log_error) do |str|
str.match "Dummy"
end
::Rake::Task["paperclip:refresh:thumbnails"].execute
end
it "prints the instance ID" do
expect(Paperclip::Task).to receive(:log_error) do |str|
str.match "ID #{@bogus_instance.id}"
end
::Rake::Task["paperclip:refresh:thumbnails"].execute
end
end
end
context "Paperclip::Task.log_error method" do
it "prints its argument to STDERR" do
msg = "Some Message"
expect($stderr).to receive(:puts).with(msg)
Paperclip::Task.log_error(msg)
end
end
end
|
class RemoveGameIdFromCards < ActiveRecord::Migration[5.2]
def change
remove_column :cards, :game_id
remove_column :cards, :hand_id
end
end
|
class MailSender < ActionMailer::Base
default from: 'from@example.com'
def inquiry(inquiry)
@inquiry = inquiry
mail to: inquiry.email
end
end
|
class Tweet
attr_accessor :content
attr_reader :username
ALL_TWEETS=[]
def initialize (username, content)
@username=username
@content=content
ALL_TWEETS << self
end
def self.all
ALL_TWEETS
end
end
|
require_relative '../spec_helper.rb'
describe Role do
subject { role }
describe "role" do
let(:role) { Role }
its(:admin) { should eq("Admin") }
its(:user) { should eq("User") }
its(:denied) { should eq("Denied") }
end
end
|
Vagrant.configure("2") do |config|
# Use "precise32" Ubuntu 10.4 box
config.vm.box = "hashicorp/precise32"
# Our app server will run on port 3000, so mirror that to the host
config.vm.network "forwarded_port", guest: 3000, host: 3000
# On boot, we need to install some dependencies and such
# More precisely (no pun intended):
# 1. Install MongoDB
# - Import code signing key
# - Install the package
# - Start the server
# 2. Install nvm
# - Install curl
# - Download the install script
# - Add nvm commands to our current shell
# - Use nvm to install an appropriate Node version
# - Finally, use that version
# 3. Run our code
# - Change to the code directory
# - Install npm dependencies
# - Run the account bootstrap script to create an admin account
# in the database
# - Start the server
config.vm.provision :shell, inline: <<-END
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
apt-get update
apt-get install -y mongodb-org
service mongod start
apt-get install -y curl
curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs
cd /vagrant
npm install
node bootstrap_accounts.js
END
end
|
class Grid::LockingColumn < Netzke::Basepack::Grid
def configure(c)
super
c.model = 'Book'
end
column :title do |c|
c.locked = true
end
end
|
class AddProxiesToSession < ActiveRecord::Migration
def self.up
add_column :sessions, :forwarded_for, :string, :limit => 100
end
def self.down
remove_column :sessions, :forwarded_for
end
end
|
class LinkedBus::Message
class Metadata
METADATA_MESSAGES = [
:routing_key,
:content_type,
:priority,
:headers,
:timestamp,
:type,
:delivery_tag,
:redelivered?,
:exchange
]
def initialize(data)
@metadata = data
end
def method_missing(method, *arguments, &block)
return super unless METADATA_MESSAGES.include?(method)
@metadata.send(method, *arguments, &block)
end
def respond_to?(method_name, include_private = false)
METADATA_MESSAGES.include?(method_name) || super
end
def to_s
metadata_to_s = []
METADATA_MESSAGES.each do |method|
metadata_to_s.push "#{method.to_s}: [ #{self.send(method)} ]"
end
metadata_to_s.join(" ")
end
end
attr_accessor :payload
def initialize(payload, metadata)
@payload = payload
@metadata = Metadata.new(metadata)
end
def method_missing(method, *arguments, &block)
return super unless @metadata.respond_to?(method.to_sym)
@metadata.send(method.to_sym, *arguments, &block)
end
def to_s
"Payload: [ #{@payload} ] Metadata: #{@metadata}"
end
end
|
# frozen_string_literal: true
require 'spec_helper'
# let these existing styles stand, rather than going in for a deep refactoring
# of these specs.
#
# possible future work: re-enable these one at a time and do the hard work of
# making them right.
#
# rubocop:disable RSpec/ContextWording, RSpec/VerifiedDoubles, RSpec/MessageSpies
# rubocop:disable RSpec/ExpectInHook, RSpec/ExampleLength
describe Mongo::Cluster do
let(:monitoring) do
Mongo::Monitoring.new(monitoring: false)
end
let(:cluster_with_semaphore) do
register_cluster(
described_class.new(
SpecConfig.instance.addresses,
monitoring,
SpecConfig.instance.test_options.merge(
server_selection_semaphore: Mongo::Semaphore.new
)
)
)
end
let(:cluster_without_io) do
register_cluster(
described_class.new(
SpecConfig.instance.addresses,
monitoring,
SpecConfig.instance.test_options.merge(monitoring_io: false)
)
)
end
let(:cluster) { cluster_without_io }
describe 'initialize' do
context 'when there are duplicate addresses' do
let(:addresses) do
SpecConfig.instance.addresses + SpecConfig.instance.addresses
end
let(:cluster_with_dup_addresses) do
register_cluster(
described_class.new(addresses, monitoring, SpecConfig.instance.test_options)
)
end
it 'does not raise an exception' do
expect { cluster_with_dup_addresses }.not_to raise_error
end
end
context 'when topology is load-balanced' do
require_topology :load_balanced
it 'emits SDAM events' do
allow(monitoring).to receive(:succeeded)
register_cluster(
described_class.new(
SpecConfig.instance.addresses,
monitoring,
SpecConfig.instance.test_options
)
)
expect(monitoring).to have_received(:succeeded).with(
Mongo::Monitoring::TOPOLOGY_OPENING, any_args
)
expect(monitoring).to have_received(:succeeded).with(
Mongo::Monitoring::TOPOLOGY_CHANGED, any_args
).twice
expect(monitoring).to have_received(:succeeded).with(
Mongo::Monitoring::SERVER_OPENING, any_args
)
expect(monitoring).to have_received(:succeeded).with(
Mongo::Monitoring::SERVER_DESCRIPTION_CHANGED, any_args
)
end
end
end
describe '#==' do
context 'when the other is a cluster' do
context 'when the addresses are the same' do
context 'when the options are the same' do
let(:other) do
described_class.new(
SpecConfig.instance.addresses, monitoring,
SpecConfig.instance.test_options.merge(monitoring_io: false)
)
end
it 'returns true' do
expect(cluster_without_io).to eq(other)
end
end
context 'when the options are not the same' do
let(:other) do
described_class.new(
[ '127.0.0.1:27017' ],
monitoring,
SpecConfig.instance.test_options.merge(replica_set: 'test', monitoring_io: false)
)
end
it 'returns false' do
expect(cluster_without_io).not_to eq(other)
end
end
end
context 'when the addresses are not the same' do
let(:other) do
described_class.new(
[ '127.0.0.1:27999' ],
monitoring,
SpecConfig.instance.test_options.merge(monitoring_io: false)
)
end
it 'returns false' do
expect(cluster_without_io).not_to eq(other)
end
end
end
context 'when the other is not a cluster' do
it 'returns false' do
expect(cluster_without_io).not_to eq('test')
end
end
end
describe '#has_readable_server?' do
let(:selector) do
Mongo::ServerSelector.primary
end
it 'delegates to the topology' do
expect(cluster_without_io.has_readable_server?)
.to eq(cluster_without_io.topology.has_readable_server?(cluster_without_io))
end
end
describe '#has_writable_server?' do
it 'delegates to the topology' do
expect(cluster_without_io.has_writable_server?)
.to eq(cluster_without_io.topology.has_writable_server?(cluster_without_io))
end
end
describe '#inspect' do
let(:preference) do
Mongo::ServerSelector.primary
end
it 'displays the cluster seeds and topology' do
expect(cluster_without_io.inspect).to include('topology')
expect(cluster_without_io.inspect).to include('servers')
end
end
describe '#replica_set_name' do
let(:preference) do
Mongo::ServerSelector.primary
end
context 'when the option is provided' do
let(:cluster) do
described_class.new(
[ '127.0.0.1:27017' ],
monitoring,
{ monitoring_io: false, connect: :replica_set, replica_set: 'testing' }
)
end
it 'returns the name' do
expect(cluster.replica_set_name).to eq('testing')
end
end
context 'when the option is not provided' do
let(:cluster) do
described_class.new(
[ '127.0.0.1:27017' ],
monitoring,
{ monitoring_io: false, connect: :direct }
)
end
it 'returns nil' do
expect(cluster.replica_set_name).to be_nil
end
end
end
describe '#scan!' do
let(:preference) do
Mongo::ServerSelector.primary
end
let(:known_servers) do
cluster.instance_variable_get(:@servers)
end
let(:server) { known_servers.first }
let(:monitor) do
double('monitor')
end
before do
expect(server).to receive(:monitor).at_least(:once).and_return(monitor)
expect(monitor).to receive(:scan!)
# scan! complains that there isn't a monitor on the server, calls summary
allow(monitor).to receive(:running?)
end
it 'returns true' do
expect(cluster.scan!).to be true
end
end
describe '#servers' do
let(:cluster) { cluster_with_semaphore }
context 'when topology is single' do
before do
skip 'Topology is not a single server' unless ClusterConfig.instance.single_server?
end
context 'when the server is a mongos' do
require_topology :sharded
it 'returns the mongos' do
expect(cluster.servers.size).to eq(1)
end
end
context 'when the server is a replica set member' do
require_topology :replica_set
it 'returns the replica set member' do
expect(cluster.servers.size).to eq(1)
end
end
end
context 'when the cluster has no servers' do
let(:servers) do
[]
end
before do
cluster_without_io.instance_variable_set(:@servers, servers)
cluster_without_io.instance_variable_set(:@topology, topology)
end
context 'when topology is Single' do
let(:topology) do
Mongo::Cluster::Topology::Single.new({}, monitoring, cluster_without_io)
end
it 'returns an empty array' do
expect(cluster_without_io.servers).to eq([])
end
end
context 'when topology is ReplicaSetNoPrimary' do
let(:topology) do
Mongo::Cluster::Topology::ReplicaSetNoPrimary.new({ replica_set_name: 'foo' }, monitoring, cluster_without_io)
end
it 'returns an empty array' do
expect(cluster_without_io.servers).to eq([])
end
end
context 'when topology is Sharded' do
let(:topology) do
Mongo::Cluster::Topology::Sharded.new({}, monitoring, cluster_without_io)
end
it 'returns an empty array' do
expect(cluster_without_io.servers).to eq([])
end
end
context 'when topology is Unknown' do
let(:topology) do
Mongo::Cluster::Topology::Unknown.new({}, monitoring, cluster_without_io)
end
it 'returns an empty array' do
expect(cluster_without_io.servers).to eq([])
end
end
end
end
describe '#add' do
context 'topology is Sharded' do
require_topology :sharded
let(:topology) do
Mongo::Cluster::Topology::Sharded.new({}, cluster)
end
before do
cluster.add('a')
end
it 'creates server with nil last_scan' do
server = cluster.servers_list.detect do |srv|
srv.address.seed == 'a'
end
expect(server).not_to be_nil
expect(server.last_scan).to be_nil
expect(server.last_scan_monotime).to be_nil
end
end
end
describe '#close' do
let(:cluster) { cluster_with_semaphore }
let(:known_servers) do
cluster.instance_variable_get(:@servers)
end
let(:periodic_executor) do
cluster.instance_variable_get(:@periodic_executor)
end
describe 'closing' do
before do
expect(known_servers).to all receive(:close).and_call_original
expect(periodic_executor).to receive(:stop!).and_call_original
end
it 'disconnects each server and the cursor reaper and returns nil' do
expect(cluster.close).to be_nil
end
end
describe 'repeated closing' do
before do
expect(known_servers).to all receive(:close).and_call_original
expect(periodic_executor).to receive(:stop!).and_call_original
end
let(:monitoring) { Mongo::Monitoring.new }
let(:subscriber) { Mrss::EventSubscriber.new }
it 'publishes server closed event once' do
monitoring.subscribe(Mongo::Monitoring::SERVER_CLOSED, subscriber)
expect(cluster.close).to be_nil
expect(subscriber.first_event('server_closed_event')).not_to be_nil
subscriber.succeeded_events.clear
expect(cluster.close).to be_nil
expect(subscriber.first_event('server_closed_event')).to be_nil
end
end
end
describe '#reconnect!' do
let(:cluster) { cluster_with_semaphore }
let(:periodic_executor) do
cluster.instance_variable_get(:@periodic_executor)
end
before do
cluster.next_primary
expect(cluster.servers).to all receive(:reconnect!).and_call_original
expect(periodic_executor).to receive(:restart!).and_call_original
end
it 'reconnects each server and the cursor reaper and returns true' do
expect(cluster.reconnect!).to be(true)
end
end
describe '#remove' do
let(:address_a) { Mongo::Address.new('127.0.0.1:25555') }
let(:address_b) { Mongo::Address.new('127.0.0.1:25556') }
let(:monitoring) { Mongo::Monitoring.new(monitoring: false) }
let(:server_a) do
register_server(
Mongo::Server.new(
address_a,
cluster,
monitoring,
Mongo::Event::Listeners.new,
monitor: false
)
)
end
let(:server_b) do
register_server(
Mongo::Server.new(
address_b,
cluster,
monitoring,
Mongo::Event::Listeners.new,
monitor: false
)
)
end
let(:servers) do
[ server_a, server_b ]
end
let(:addresses) do
[ address_a, address_b ]
end
before do
cluster.instance_variable_set(:@servers, servers)
cluster.remove('127.0.0.1:25555')
end
it 'removes the host from the list of servers' do
expect(cluster.instance_variable_get(:@servers)).to eq([ server_b ])
end
it 'removes the host from the list of addresses' do
expect(cluster.addresses).to eq([ address_b ])
end
end
describe '#next_primary' do
let(:cluster) do
# We use next_primary to wait for server selection, and this is
# also the method we are testing.
authorized_client.tap { |client| client.cluster.next_primary }.cluster
end
let(:primary_candidates) do
if cluster.single? || cluster.load_balanced? || cluster.sharded?
cluster.servers
else
cluster.servers.select(&:primary?)
end
end
it 'always returns the primary, mongos, or standalone' do
expect(primary_candidates).to include(cluster.next_primary)
end
end
describe '#app_metadata' do
it 'returns an AppMetadata object' do
expect(cluster_without_io.app_metadata).to be_a(Mongo::Server::AppMetadata)
end
context 'when the client has an app_name set' do
let(:cluster) do
authorized_client.with(app_name: 'cluster_test', monitoring_io: false).cluster
end
it 'constructs an AppMetadata object with the app_name' do
expect(cluster.app_metadata.client_document[:application]).to eq('name' => 'cluster_test')
end
end
context 'when the client does not have an app_name set' do
let(:cluster) do
authorized_client.cluster
end
it 'constructs an AppMetadata object with no app_name' do
expect(cluster.app_metadata.client_document[:application]).to be_nil
end
end
end
describe '#cluster_time' do
let(:operation) do
client.command(ping: 1)
end
let(:operation_with_session) do
client.command({ ping: 1 }, session: session)
end
let(:second_operation) do
client.command({ ping: 1 }, session: session)
end
it_behaves_like 'an operation updating cluster time'
end
describe '#update_cluster_time' do
let(:cluster) do
described_class.new(
SpecConfig.instance.addresses, monitoring,
SpecConfig.instance.test_options.merge(
heartbeat_frequency: 1000,
monitoring_io: false
)
)
end
let(:result) do
double('result', cluster_time: cluster_time_doc)
end
context 'when the cluster_time variable is nil' do
before do
cluster.instance_variable_set(:@cluster_time, nil)
cluster.update_cluster_time(result)
end
context 'when the cluster time received is nil' do
let(:cluster_time_doc) do
nil
end
it 'does not set the cluster_time variable' do
expect(cluster.cluster_time).to be_nil
end
end
context 'when the cluster time received is not nil' do
let(:cluster_time_doc) do
BSON::Document.new(Mongo::Cluster::CLUSTER_TIME => BSON::Timestamp.new(1, 1))
end
it 'sets the cluster_time variable to the cluster time doc' do
expect(cluster.cluster_time).to eq(cluster_time_doc)
end
end
end
context 'when the cluster_time variable has a value' do
before do
cluster.instance_variable_set(
:@cluster_time,
Mongo::ClusterTime.new(
Mongo::Cluster::CLUSTER_TIME => BSON::Timestamp.new(1, 1)
)
)
cluster.update_cluster_time(result)
end
context 'when the cluster time received is nil' do
let(:cluster_time_doc) do
nil
end
it 'does not update the cluster_time variable' do
expect(cluster.cluster_time).to eq(
BSON::Document.new(
Mongo::Cluster::CLUSTER_TIME => BSON::Timestamp.new(1, 1)
)
)
end
end
context 'when the cluster time received is not nil' do
context 'when the cluster time received is greater than the cluster_time variable' do
let(:cluster_time_doc) do
BSON::Document.new(Mongo::Cluster::CLUSTER_TIME => BSON::Timestamp.new(1, 2))
end
it 'sets the cluster_time variable to the cluster time' do
expect(cluster.cluster_time).to eq(cluster_time_doc)
end
end
context 'when the cluster time received is less than the cluster_time variable' do
let(:cluster_time_doc) do
BSON::Document.new(Mongo::Cluster::CLUSTER_TIME => BSON::Timestamp.new(0, 1))
end
it 'does not set the cluster_time variable to the cluster time' do
expect(cluster.cluster_time).to eq(
BSON::Document.new(
Mongo::Cluster::CLUSTER_TIME => BSON::Timestamp.new(1, 1)
)
)
end
end
context 'when the cluster time received is equal to the cluster_time variable' do
let(:cluster_time_doc) do
BSON::Document.new(Mongo::Cluster::CLUSTER_TIME => BSON::Timestamp.new(1, 1))
end
it 'does not change the cluster_time variable' do
expect(cluster.cluster_time).to eq(
BSON::Document.new(
Mongo::Cluster::CLUSTER_TIME => BSON::Timestamp.new(1, 1)
)
)
end
end
end
end
end
describe '#validate_session_support!' do
shared_examples 'supports sessions' do
it 'supports sessions' do
expect { cluster.validate_session_support! }
.not_to raise_error
end
end
shared_examples 'does not support sessions' do
it 'does not support sessions' do
expect { cluster.validate_session_support! }
.to raise_error(Mongo::Error::SessionsNotSupported)
end
end
context 'in server < 3.6' do
max_server_version '3.4'
let(:cluster) { client.cluster }
context 'in single topology' do
require_topology :single
let(:client) { ClientRegistry.instance.global_client('authorized') }
it_behaves_like 'does not support sessions'
end
context 'in single topology with replica set name set' do
require_topology :replica_set
let(:client) do
new_local_client(
[ SpecConfig.instance.addresses.first ],
SpecConfig.instance.test_options.merge(
connect: :direct,
replica_set: ClusterConfig.instance.replica_set_name
)
)
end
it_behaves_like 'does not support sessions'
end
context 'in replica set topology' do
require_topology :replica_set
let(:client) { ClientRegistry.instance.global_client('authorized') }
it_behaves_like 'does not support sessions'
end
context 'in sharded topology' do
require_topology :sharded
let(:client) { ClientRegistry.instance.global_client('authorized') }
it_behaves_like 'does not support sessions'
end
end
context 'in server 3.6+' do
min_server_fcv '3.6'
let(:cluster) { client.cluster }
context 'in single topology' do
require_topology :single
let(:client) { ClientRegistry.instance.global_client('authorized') }
# Contrary to the session spec, 3.6 and 4.0 standalone servers
# report a logical session timeout and thus are considered to
# support sessions.
it_behaves_like 'supports sessions'
end
context 'in single topology with replica set name set' do
require_topology :replica_set
let(:client) do
new_local_client(
[ SpecConfig.instance.addresses.first ],
SpecConfig.instance.test_options.merge(
connect: :direct,
replica_set: ClusterConfig.instance.replica_set_name
)
)
end
it_behaves_like 'supports sessions'
end
context 'in replica set topology' do
require_topology :replica_set
let(:client) { ClientRegistry.instance.global_client('authorized') }
it_behaves_like 'supports sessions'
end
context 'in sharded topology' do
require_topology :sharded
let(:client) { ClientRegistry.instance.global_client('authorized') }
it_behaves_like 'supports sessions'
end
end
end
{ max_read_retries: 1, read_retry_interval: 5 }.each do |opt, default|
describe "##{opt}" do
let(:client_options) { {} }
let(:client) do
new_local_client_nmio([ '127.0.0.1:27017' ], client_options)
end
let(:cluster) do
client.cluster
end
it "defaults to #{default}" do
expect(default).not_to be_nil
expect(client.options[opt]).to be_nil
expect(cluster.send(opt)).to eq(default)
end
context 'specified on client' do
let(:client_options) { { opt => 2 } }
it 'inherits from client' do
expect(client.options[opt]).to eq(2)
expect(cluster.send(opt)).to eq(2)
end
end
end
end
describe '#summary' do
let(:default_address) { SpecConfig.instance.addresses.first }
context 'cluster has unknown servers' do
# Servers are never unknown in load-balanced topology.
require_topology :single, :replica_set, :sharded
it 'includes unknown servers' do
expect(cluster.servers_list).to all be_unknown
expect(cluster.summary).to match(/Server address=#{default_address}/)
end
end
context 'cluster has known servers' do
let(:client) { ClientRegistry.instance.global_client('authorized') }
let(:cluster) { client.cluster }
before do
wait_for_all_servers(cluster)
end
it 'includes known servers' do
cluster.servers_list.each do |server|
expect(server).not_to be_unknown
end
expect(cluster.summary).to match(/Server address=#{default_address}/)
end
end
end
end
# rubocop:enable RSpec/ContextWording, RSpec/VerifiedDoubles, RSpec/MessageSpies
# rubocop:enable RSpec/ExpectInHook, RSpec/ExampleLength
|
RSpec.shared_examples "has transfer fields" do |transfer|
it { should belong_to(:source).class_name("Activity") }
it { should belong_to(:destination).class_name("Activity") }
describe "validations" do
it { should validate_presence_of(:source) }
it { should validate_presence_of(:destination) }
it { should validate_presence_of(:value) }
it { should validate_presence_of(:financial_year) }
it { should validate_presence_of(:financial_quarter) }
it { should validate_numericality_of(:value).is_less_than_or_equal_to(99_999_999_999.00) }
it { should validate_numericality_of(:value).is_other_than(0) }
end
describe "foreign key constraints" do
subject { create(:outgoing_transfer) }
it "prevents the associated source activity from being deleted" do
source_activity = subject.source
expect { source_activity.destroy }.to raise_exception(/ForeignKeyViolation/)
end
it "prevents the associated destination activity from being deleted" do
destination_activity = subject.destination
expect { destination_activity.destroy }.to raise_exception(/ForeignKeyViolation/)
end
end
end
|
class Comment < ApplicationRecord
belongs_to :user
belongs_to :commentable, polymorphic: true
has_many :comments, as: :commentable, dependent: :destroy
def self.by_recent
order("created_at DESC")
end
end
|
class CreateReviews < ActiveRecord::Migration
def change
create_table :reviews do |t|
t.text :review
t.integer :complaint_id
t.timestamps null: false
end
add_index :reviews, :complaint_id, using: :btree
end
end
|
require_relative 'fixed_array'
describe FixedArray do
describe "let" do
let(:fixedArray) { FixedArray.new(10) }
it "creates a new FixedArray of size 10" do
expect(fixedArray.size).to eq 10
end
it "raises an error if index is out of bounds for FixedArray#get" do
expect { fixedArray.get(11) }.to raise_error FixedArray::OutOfBoundsException, "Error: Index out of bounds"
end
it "raises an error if index is out of bounds for FixedArray#set" do
expect { fixedArray.set(-4, "boo") }.to raise_error FixedArray::OutOfBoundsException, "Error: Index out of bounds"
end
it "sets the value at the index in the FixedArray and returns it" do
fixedArray.set(5, "Index 5")
expect(fixedArray.get(5)).to eq("Index 5")
end
it "returns nil for unset element" do
expect(fixedArray.get(0)).to eq nil
end
end
end
|
class LevelLoader
def initialize()
@levels = [
{
:name => 'Silver Heart',
:description => 'Silver Heart',
:amount_points_of_required => 10,
:image_url => '/images/levels/silver_heart.png'
},{
:name => 'Bronze Heart',
:description => 'Bronze Heart',
:amount_points_of_required => 50,
:image_url => '/images/levels/bronze_heart.png'
},{
:name => 'Gold Heart',
:description => 'Gold Heart',
:amount_points_of_required => 100,
:image_url => '/images/levels/gold_heart.png'
},{
:name => 'Green Heart',
:description => 'Green Heart',
:amount_points_of_required => 500,
:image_url => '/images/levels/green_heart.png'
},
]
end
def load
@levels.each do |level|
level_instance = Level.find_or_initialize_by_name(level[:name])
level_instance.description = level[:description]
level_instance.amount_points_of_required = level[:amount_points_of_required]
level_instance.image_url = level[:image_url]
level_instance.save!
end
end
end
|
class ErrorsController < ActionController::Base
# layout to show with your errors. make sure it's not that fancy because we're
# handling errors.
layout 'application'
def show
@exception = env['action_dispatch.exception']
@status = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code
# @response = ActionDispatch::ExceptionWrapper.rescue_responses[@exception.class.name]
# response contains the error name ex: 404 => "not found"
render status: @status
end
end
|
# frozen_string_literal: true
# An addon to the String class to change the colour of the text
class String
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
end
# The class for displaying the chessboard
class ChessBoard
def initialize(initial_column, initial_row)
@knight = Knight.new(initial_column, initial_row)
@vertices = VertexList.new
draw
end
def draw
8.times do |row_number|
print '---------'
8.times { draw_row_top }
print "+\n"
draw_board_row(row_number)
end
print '---------'
8.times { draw_row_top }
print "+\n"
draw_row_bottom
end
def find_path(target_column, target_row)
@knight.moves_to(target_column, target_row, @vertices)
draw
output_path
end
private
def draw_row_top
print '+---------'
end
def draw_row_bottom
4.times do |row|
print ' |'
8.times do |num|
draw_number_row(num + 1, row + 1)
print '|'
end
print "\n"
end
end
def draw_board_row(row_number)
4.times do |row|
draw_number_row(row_number + 1, row + 1)
8.times do |column|
@knight.print_row(row_number, column, row)
end
print "|\n"
end
end
def draw_number_row(number, row)
number_hash = { 1 => { 1 => ' ', 2 => ' | ', 3 => ' | ', 4 => ' ' },
2 => { 1 => ' __ ', 2 => ' __| ', 3 => ' |__ ', 4 => ' ' },
3 => { 1 => ' __ ', 2 => ' __| ', 3 => ' __| ', 4 => ' ' },
4 => { 1 => ' ', 2 => ' |__| ', 3 => ' | ', 4 => ' ' },
5 => { 1 => ' __ ', 2 => ' |__ ', 3 => ' __| ', 4 => ' ' },
6 => { 1 => ' __ ', 2 => ' |__ ', 3 => ' |__| ', 4 => ' ' },
7 => { 1 => ' __ ', 2 => ' | ', 3 => ' | ', 4 => ' ' },
8 => { 1 => ' __ ', 2 => ' |__| ', 3 => ' |__| ', 4 => ' ' } }
print number_hash[number][row]
end
def output_path
puts "The path from #{@knight.path_coords.first} to #{@knight.path_coords.last} requires a minimum of "\
"#{@knight.path_coords.length - 1} moves. These are as follows:"
@knight.path_coords.each { |position| p position }
end
end
# Representation of a square on the chess board
class Square
attr_accessor :row, :column, :position, :adjacents
def initialize(column, row)
@row = row
@column = column
@position = [column, row]
@adjacents = find_adjacents(column, row)
end
private
def find_adjacents(column, row)
adjacents = initial_adjacents(column, row)
adjacents.select { |position| position[0].between?(1, 8) && position[1].between?(1, 8) }
end
def initial_adjacents(column, row)
[[column + 2, row + 1], [column + 2, row - 1], [column + 1, row + 2], [column + 1, row - 2],
[column - 2, row + 1], [column - 2, row - 1], [column - 1, row + 2], [column - 1, row - 2]]
end
end
# The list of squares on the chessboard
class VertexList
attr_reader :vertex_array
def initialize
@vertex_array = []
build_vertex_list
@size = @vertex_array.length
@vertex_array = index_adjacents
end
def build_vertex_list
8.times do |column|
8.times do |row|
@vertex_array.push(Square.new(column + 1, row + 1))
end
end
end
def breadth_first_search(start_pos, end_pos)
start_pos_index = @vertex_array.index { |square| square.position == start_pos }
end_pos_index = @vertex_array.index { |square| square.position == end_pos }
prev = solve(start_pos_index)
reconstruct_path(start_pos_index, end_pos_index, prev)
end
private
def solve(start)
queue = []
queue.push(start)
visited = Array.new(@size, false)
visited[start] = true
manage_queue(queue, visited, Array.new(@size, nil))
end
def reconstruct_path(_start, end_, prev)
path = []
add_to_path(path, end_, prev)
path.reverse
end
def manage_queue(queue, visited, prev)
return prev if queue.empty?
node = queue.shift
neighbours = @vertex_array[node].adjacents
neighbours.each do |neighbour|
next if visited[neighbour]
queue.push(neighbour)
visited[neighbour] = true
prev[neighbour] = node
end
manage_queue(queue, visited, prev)
end
def add_to_path(path, node, prev)
return path if node.nil?
path.push(node)
add_to_path(path, prev[node], prev)
end
def index_adjacents
@vertex_array.each do |square|
square.adjacents = square.adjacents.map do |position|
@vertex_array.index { |sq| sq.position == position }
end
end
end
end
# The class to represent the knight piece
class Knight
attr_accessor :row, :column, :path, :path_coords
def initialize(column, row)
@row = row
@column = column
@path = []
@path_coords = [[@column, @row]]
end
def print_row(row_number, column, row)
on_path = @path_coords.include?([column + 1, row_number + 1])
if on_path
print "|#{draw(row + 1, @path_coords.index([column + 1, row_number + 1]))}"
else
print '| '
end
end
def moves_to(target_column, target_row, vertices)
@path = vertices.breadth_first_search([@column, @row], [target_column, target_row])
@path_coords = @path.map { |index| vertices.vertex_array[index].position }
end
private
def draw(row, path_number = 1)
knight_hash = { 1 => " __/\\ #{path_number}".colorize(42).colorize(1),
2 => ' /__ \ '.colorize(42).colorize(1),
3 => ' / | '.colorize(42).colorize(1),
4 => ' /____\ '.colorize(42).colorize(1) }
knight_hash[row]
end
end
def start
start_pos = request('initial')
board = ChessBoard.new(start_pos[0], start_pos[1])
target_pos = request('target')
in_range?(target_pos) ? board.find_path(target_pos[0], target_pos[1]) : restart
finish
end
def finish
puts "Would you like to find a path for a different set of start and end points? ('y' for yes, anything else for no)"
answer = gets.chomp.downcase
%w[y yes].include?(answer) ? start : (puts 'Ok, thanks for stopping by!!')
end
def in_range?(position)
position[0].between?(1, 8) && position[1].between?(1, 8)
end
def request(position)
puts "Please specify the #{position} position of your Knight as two comma separated integers, less than 8 "\
"(e.g. '1,5'):"
pos = gets.chomp.split(',')
pos = pos.map(&:to_i)
if in_range?(pos)
pos
else
puts "The #{position} coordinates entered do not fall on the gameboard. Try again...\n"
request(position)
end
end
puts "\n"
puts 'Welcome to Knight Moves, please make sure that your terminal window is wide enough to fit the full chessboard'\
' width on.'
puts "The outputs will look weird if you don\'t!"
puts "\n"
start
|
FactoryBot.define do
factory :article_1, class: Article do
record_id { '28142765' }
title { 'We migrated ToolJet server from Ruby to Node.js' }
url { 'https://blog.tooljet.io/how-we-migrated-tooljet' }
author { 'navaneethpk' }
points { 4 }
num_comments { 1 }
publish_date { '2021-08-10 14:56:06' }
tag { 'story' }
end
factory :article_2, class: Article do
record_id { '28046468' }
title { 'A multithreaded, Postgres-based' }
url { 'https://github.com/bensheldon/good_job' }
author { 'damir' }
points { 1 }
num_comments { 0 }
publish_date { '2021-08-11 15:56:06' }
tag { 'story' }
end
factory :article_3, class: Article do
record_id { '28125042' }
author { 'PragmaticPulp' }
comment_text { 'Comment text example' }
story_id { '28142765' }
story_title { 'Story title example' }
story_url { 'https://nibblestew.blogspot.com/2021/02/story_example' }
parent_id { '28142765' }
publish_date { '2021-08-10 04:04:41' }
tag { 'comment' }
end
end
|
# frozen_string_literal: true
# Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru>
module Huobi
class Websocket < Faye::WebSocket::Client
class Error < StandardError; end
URL = 'wss://api.huobi.pro/ws'
PING = 3
def initialize
super URL, [], ping: PING
@request_id = 0
end
def market_ticker!(symbol)
subscribe "market.#{symbol}.ticker"
end
def multi(streams:, methods:)
streams.each do |stream|
subscribe stream
end
methods.each_pair do |key, method|
on(key) do |event|
catch :ignoreMessage do
method.call(process_event(event))
end
end
end
end
private
def process_event(event)
case event
when Faye::WebSocket::API::ErrorEvent
raise Error, event
when Faye::WebSocket::API::OpenEvent, Faye::WebSocket::API::CloseEvent
event
else
message = Zlib::GzipReader.new(StringIO.new(event.data.pack('C*'))).read
data = JSON.parse(message, symbolize_names: true)
if data[:ping]
send({ pong: data.fetch(:ping) }.to_json)
throw :ignoreMessage
elsif data[:error]
raise Error, "(#{data[:code]}) #{data[:msg]}"
elsif data.key? :status
raise Error, data if data[:status] == 'error'
throw :ignoreMessage
else
data
end
end
end
def request_id
@request_id += 1
end
def subscribe(stream)
send({ sub: stream, id: request_id }.to_json)
end
# Terminating socket connection achieves the same result.
# If you have a use-case for this, please create a GitHub issue.
#
# def unsubscribe(streams)
# send({
# method: "UNSUBSCRIBE",
# params: streams,
# id: request_id,
# }.to_json)
# end
end
end
|
class CreateTeachers < ActiveRecord::Migration[5.2]
def change
create_table :teachers do |t|
t.string :mynumber, null:false
t.string :name, null: false
t.text :research
t.timestamps
t.index :mynumber, unique:true
end
end
end
|
class Pirate
@@all = []
attr_accessor :name, :weight, :height
def initialize(args)
@name = args[:name]
@weight = args[:weight]
@height = args[:height]
@@all << self
end
def self.all
@@all
end
end
|
class Api::MetricsController < ApplicationController
# Fetch all metrics for a given company
def index
metrics = Metric.where(company_id: params[:company_id])
if metrics.blank?
render(
json: {
error: {
code: 404,
message: "No metrics found for company",
errors: {
message: "No metrics found for company"
}
}
})
return
end
render json: {
data: {
kind: Metric.name,
items: metrics.map { |m| m.as_json(include: [:metric_name, :metric_type, :function, :business_unit]) }
}
}
end
# Get metrics dashboard for a given company
def metrics_dashboard
raise ActiveRecord::RecordNotFound unless Company.exists?(params[:company_id])
render json: {
data: Api::MetricsHelper.metrics_dashboard(params[:company_id], current_user)
}
end
def create
raise ActiveRecord::RecordNotFound unless Company.exists?(params[:company_id])
metrics = params[:metrics]
# If there is more than one metric, save a metric_batch random UUID to "batch"
# the metrics together, signifying that they were submitted together
metric_batch = metrics.length > 1 ? SecureRandom.uuid : nil
metrics.each do |metric|
value_description = Metric::METRIC_TO_VALUE_DESC[metric[:metric_name]]
relevant_date = DateTime.new(metric[:relevant_date])
new_metric = Metric.create! metric_name: metric[:metric_name],
company_id: params[:company_id],
value: metric[:value],
value_description: value_description,
relevant_date: relevant_date,
metric_batch: metric_batch,
user_id: current_user.id
end
render json: {
data: {}
}
end
def form_metrics
render json: Api::MetricsHelper.form_metrics
end
end
|
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
layout "standard"
skip_before_filter :require_login_for_non_rest
skip_before_filter :find_portal
# render new.rhtml
def new
end
def create
logout_keeping_session!
user = User.authenticate(params[:login], params[:password])
if user
# Protects against session fixation attacks, causes request forgery
# protection if user resubmits an earlier form using back
# button. Uncomment if you understand the tradeoffs.
# reset_session
self.current_user = user
new_cookie_flag = (params[:remember_me] == "1")
handle_remember_cookie! new_cookie_flag
if self.current_user.change_password
flash[:notice] = "Logged in successfully but you will need to create a new password"
else
flash[:notice] = "Logged in successfully"
end
redirect_back_or_default(home_url)
flash[:notice] = "Logged in successfully"
else
if (user == false)
note_failed_signin(true)
else
note_failed_signin
end
@login = params[:login]
@remember_me = params[:remember_me]
render :action => 'new'
end
end
def destroy
logout_killing_session!
flash[:notice] = "You have been logged out."
redirect_back_or_default(home_url)
end
def show
redirect_to(login_url)
end
def permission_denied
render(:status => 403)
end
protected
# Track failed login attempts
def note_failed_signin(needs_activated = false)
if needs_activated
flash[:error] = "You will need to activate your account before you may log in. Please check your email at the address you provided."
else
flash[:error] = "Couldn't log you in as '#{params[:login]}'"
end
logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip}"
end
end
|
class Api::Merchant::RafflesController < Api::Merchant::BaseController
def create
@raffle = current_merchant.raffles.create(params[:raffle])
if @raffle.errors.blank?
render json: {status: 200, raffle: @raffle.attributes}
else
render json: {status: 205, message: @raffle.errors.full_messages}
end
end
def destroy
@raffle = Raffle.where(id: params[:id]).first
if @raffle
@raffle.destroy
render json: {status: 200, message: "deleted raffle successfully."}
else
render json: {status: 205, message: "coundn't found raffle with id #{params[:id]}."}
end
end
def update
@raffle = Raffle.where(id: params[:id]).first
if @raffle
if @raffle.update_attributes(params[:raffle])
render json: {status: 200, message: "updated raffle successfully."}
else
render json: {status: 205, message: @raffle.errors.full_messages}
end
else
render json: {status: 205, message: "coundn't found raffle with id #{params[:id]}."}
end
end
end
|
module Messenger
module Commands
module Chat
class ShowSettings < Clamp::Command
parameter '[chat_id]', 'chat id'
option %w(-f --force), :flag, 'ignore cache'
def execute
if force?
chat_id = @chat_id || chat_id
response = Messenger.app.api.show_chat chat_id
process_response response do |success, body|
Chat::ChatSettings.current_chat = body['chat'] if success and body.include? 'chat'
end
end
puts Chat::ChatSettings.current_chat
end
end
end
end
end |
Pod::Spec.new do |s|
s.platform = :ios
s.ios.deployment_target = '12.0'
s.name = "MessageToolbar"
s.summary = "MessageToolbar is an elegant drop-in message toolbar for your chat modules."
s.requires_arc = true
s.version = "1.0.0"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Tarek Sabry" => "tareksabry444@outlook.com" }
s.homepage = "https://github.com/tareksabry1337/MessageToolbar"
s.source = { :git => "https://github.com/tareksabry1337/MessageToolbar.git",
:tag => "#{s.version}" }
s.framework = "UIKit"
s.framework = "AudioToolbox"
s.framework = "AVFoundation"
s.dependency 'Shimmer', '~> 1.0.2'
s.source_files = "MessageToolbar/**/*.swift"
s.swift_version = "4.2"
s.resource_bundles = {
'MessageToolbar' => ['MessageToolbar/Assets.xcassets']
}
end
|
require "rails_helper"
RSpec.describe Activity::GroupedActivitiesFetcher do
let(:user) { create(:beis_user) }
context "when the organisation is a service owner" do
let(:organisation) { create(:beis_organisation) }
it "groups all programmes by parent" do
fund = create(:fund_activity)
programme = create(:programme_activity, parent: fund)
project = create(:project_activity, parent: programme)
third_party_project = create(:third_party_project_activity, parent: project)
activities = described_class.new(user: user, organisation: organisation).call
expect(activities).to eq({
fund => {
programme => {
project => [
third_party_project
]
}
}
})
end
it "only includes scoped activities if a scope is provided" do
fund = create(:fund_activity)
non_current_programme = create(:programme_activity, programme_status: "completed", parent: fund)
non_current_project_1 = create(:project_activity, programme_status: "completed", parent: non_current_programme)
programme = create(:programme_activity, parent: fund)
project = create(:project_activity, parent: programme)
third_party_project = create(:third_party_project_activity, parent: project)
_non_current_project_2 = create(:project_activity, parent: programme, programme_status: "stopped")
_non_current_third_party_project = create(:third_party_project_activity, parent: project, programme_status: "stopped")
completed_activities = described_class.new(user: user, organisation: organisation, scope: :current).call
historic_activities = described_class.new(user: user, organisation: organisation, scope: :historic).call
expect(completed_activities).to eq({
fund => {
programme => {
project => [
third_party_project
]
}
}
})
expect(historic_activities).to eq({
fund => {
non_current_programme => {
non_current_project_1 => []
}
}
})
end
end
context "when the organisation is not a service owner" do
let(:organisation) { create(:partner_organisation) }
it "filters by extending organisation" do
fund = create(:fund_activity)
programme = create(:programme_activity, extending_organisation: organisation, parent: fund)
project = create(:project_activity, parent: programme, extending_organisation: organisation)
third_party_project = create(:third_party_project_activity, parent: project, extending_organisation: organisation)
other_programme = create(:programme_activity, parent: fund)
_other_project = create(:project_activity, parent: other_programme)
activities = described_class.new(user: user, organisation: organisation).call
expect(activities).to eq({
fund => {
programme => {
project => [
third_party_project
]
}
}
})
end
end
it "orders the activities by created date" do
organisation = create(:partner_organisation)
fund = create(:fund_activity)
old_programme = create(:programme_activity, extending_organisation: organisation, parent: fund, created_at: 1.month.ago)
new_programme = create(:programme_activity, extending_organisation: organisation, parent: fund, created_at: 3.days.ago)
old_project_1 = create(:project_activity, extending_organisation: organisation, parent: old_programme, created_at: 10.days.ago)
new_project_1 = create(:project_activity, extending_organisation: organisation, parent: old_programme, created_at: 7.days.ago)
old_project_2 = create(:project_activity, extending_organisation: organisation, parent: new_programme, created_at: 4.days.ago)
new_project_2 = create(:project_activity, extending_organisation: organisation, parent: new_programme, created_at: 2.days.ago)
old_third_party_project = create(:third_party_project_activity, extending_organisation: organisation, parent: old_project_2, created_at: 1.days.ago)
new_third_party_project = create(:third_party_project_activity, extending_organisation: organisation, parent: old_project_2)
activities = described_class.new(user: create(:beis_user), organisation: organisation).call
expect(activities).to eq({
fund => {
old_programme => {
old_project_1 => [],
new_project_1 => []
},
new_programme => {
old_project_2 => [
old_third_party_project,
new_third_party_project
],
new_project_2 => []
}
}
})
end
end
|
module Idv
class ScanIdController < ScanIdBaseController
before_action :ensure_fully_authenticated_user_or_token
before_action :ensure_user_not_throttled, only: [:new]
USER_SESSION_FLOW_ID = 'idv/doc_auth_v2'.freeze
def new
SecureHeaders.append_content_security_policy_directives(request,
script_src: ['\'unsafe-eval\''])
render layout: false
end
def scan_complete
if all_checks_passed?
save_proofing_components
token_user_id ? continue_to_ssn_on_desktop : continue_to_ssn
else
idv_failure
end
clear_scan_id_session
end
private
def flow_session
user_session[USER_SESSION_FLOW_ID]
end
def ensure_fully_authenticated_user_or_token
return if user_signed_in? && user_fully_authenticated?
ensure_user_id_in_session
end
def ensure_user_id_in_session
return if token_user_id && token.blank?
result = CaptureDoc::ValidateRequestToken.new(token).call
analytics.track_event(Analytics::DOC_AUTH, result.to_h)
process_result(result)
end
def process_result(result)
if result.success?
reset_session
session[:token_user_id] = result.extra[:for_user_id]
else
flash[:error] = t('errors.capture_doc.invalid_link')
redirect_to root_url
end
end
def all_checks_passed?
scan_id_session && scan_id_session[:instance_id] &&
(selfie_live_and_matches_document? || !liveness_checking_enabled?)
end
def token
params[:token]
end
def continue_to_ssn_on_desktop
CaptureDoc::UpdateAcuantToken.call(token_user_id,
scan_id_session[:instance_id])
render :capture_complete
end
def continue_to_ssn
flow_session[:pii_from_doc] = scan_id_session[:pii]
flow_session[:pii_from_doc]['uuid'] = current_user.uuid
user_session[USER_SESSION_FLOW_ID]['Idv::Steps::ScanIdStep'] = true
redirect_to idv_doc_auth_v2_step_url(step: :ssn)
end
def clear_scan_id_session
session.delete(:scan_id)
session.delete(:token_user_id)
end
def ensure_user_not_throttled
redirect_to idv_session_errors_throttled_url if attempter_throttled?
end
def idv_failure
if attempter_throttled?
redirect_to idv_session_errors_throttled_url
else
redirect_to idv_session_errors_warning_url
end
end
def save_proofing_components
save_proofing_component(:document_check, 'acuant')
save_proofing_component(:document_type, 'state_id')
save_proofing_component(:liveness_check, 'acuant') if selfie_live_and_matches_document?
end
def save_proofing_component(key, value)
Db::ProofingComponent::Add.call(current_user_id, key, value)
end
end
end
|
describe Neo4j::ActiveNode::Initialize do
before do
stub_active_node_class('MyModel') do
property :name, type: String
end
end
describe '@attributes' do
let(:first_node) { MyModel.create(name: 'foo') }
let(:keys) { first_node.instance_variable_get(:@attributes).keys }
it 'sets @attributes with the expected properties' do
expect(keys).to eq(['name', ('uuid' unless MyModel.id_property_name == :neo_id)].compact)
end
end
end
|
require 'spec_helper'
describe Immutable::Vector do
describe '#zip' do
let(:vector) { V[1,2,3,4] }
context 'with a block' do
it 'yields arrays of one corresponding element from each input sequence' do
result = []
vector.zip(['a', 'b', 'c', 'd']) { |obj| result << obj }
result.should eql([[1,'a'], [2,'b'], [3,'c'], [4,'d']])
end
it 'fills in the missing values with nils' do
result = []
vector.zip(['a', 'b']) { |obj| result << obj }
result.should eql([[1,'a'], [2,'b'], [3,nil], [4,nil]])
end
it 'returns nil' do
vector.zip([2,3,4]) {}.should be_nil
end
it 'can handle multiple inputs, of different classes' do
result = []
vector.zip(V[2,3,4,5], [5,6,7,8]) { |obj| result << obj }
result.should eql([[1,2,5], [2,3,6], [3,4,7], [4,5,8]])
end
end
context 'without a block' do
it 'returns a vector of arrays (one corresponding element from each input sequence)' do
vector.zip([2,3,4,5]).should eql(V[[1,2], [2,3], [3,4], [4,5]])
end
end
[10, 31, 32, 33, 1000, 1023, 1024, 1025].each do |size|
context "on #{size}-item vectors" do
it 'behaves like Array#zip' do
array = (rand(9)+1).times.map { size.times.map { rand(10000) }}
vectors = array.map { |a| V.new(a) }
result = vectors.first.zip(*vectors.drop(1))
result.class.should be(Immutable::Vector)
result.should == array[0].zip(*array.drop(1))
end
end
end
context 'from a subclass' do
it 'returns an instance of the subclass' do
subclass = Class.new(Immutable::Vector)
instance = subclass.new([1,2,3])
instance.zip([4,5,6]).class.should be(subclass)
end
end
end
end
|
class Api::V1::SalonController < ApplicationController
skip_before_action :verify_authenticity_token
def index
salons = Salon.all
render json: salons, status:200
end
def show
salon = Salon.find(params[:id])
render json: salon, status:200
end
def create
@salon = Salon.new(salon_params)
if @salon.save
render json: @salon, status: :created
else
render json: @salon.errors, status: :unprocessable_entity
end
end
def delete
Salon.find(params[:id]).destroy
if @salon.destroy
render json: :nothing, status: :ok
else
render json: :nothing, status: :unprocessable_entity
end
end
def update
@salon = Salon.find(params[:id])
if @salon.update(salon_param)
render json: @salon, status: :ok
else
render json: @salon.errors, status: :unprocessable_entity
end
end
def salon_param
params.require(:salon).permit(:nombre, :horario, :localizacion)
end
def salon_params
params.require(:salons).permit(:nombre, :horario, :localizacion)
end
end
|
# To finish the installation, you need to call this script from domready. I haven't
# included that part for fear of conflicts.
#
# $(document).ready(function () {
# imgSizer.collate();
# });
after_bundler do
# Add fluid image script
get_vendor_javascript 'http://unstoppablerobotninja.com/demos/resize/imgSizer.js', 'imgsizer'
# Tell it where our spacer gif is
get_support_file 'app/assets/images/blank.gif'
gsub_file 'vendor/assets/javascripts/imgsizer.js', %r{/path/to/your/spacer.gif}, '<%= image_path "blank.gif" %>'
run 'mv vendor/assets/javascripts/imgsizer.js vendor/assets/javascripts/imgsizer.js.erb'
# Require it
require_javascript 'imgsizer'
end
__END__
name: Img Sizer
description: Add script to handle fluid images on IE
website: http://unstoppablerobotninja.com/entry/fluid-images/
author: mattolson
category: polyfill
|
class AddFieldsToWelcomers < ActiveRecord::Migration
def change
add_column :welcomers, :first_name, :string
add_column :welcomers, :last_name, :string
end
end
|
require 'rest-client'
module RestClientHasher
class Requests
def self.post_json_to_url input_url, json_body
response = RestClient.post(input_url, json_body, :content_type => 'application/json')
response.code.should == 200
JSON.parse response.body
end
def self.put_json_to_url input_url, json_body
response = RestClient.put(input_url, json_body, :content_type => 'application/json')
response.code.should == 200
JSON.parse response.body
end
def self.get_json_from_url input_url
response = RestClient.get(input_url)
response.code.should == 200
JSON.parse response.body
end
end
end
|
module HandleObjectNotFound
extend ActiveSupport::Concern
def ensure_found_all_from_params(finder_class, finder_value)
raise Errors::ObjectNotFoundError.new(finder_value) unless params[finder_value].is_a?(Array)
array_of_ids = params[finder_value].map { |elem| elem[:id] }
finder_class.where(id: array_of_ids)
end
# Implied that if we are looking for a course using course_id, if we do not find course_id in the parameter list, then we won't find it--at least we report to the user that course_id is missing, not that we can't find a course using that course_id
def ensure_found_object_from_params(finder_class, finder_value, finder_index='id')
ensure_params_are_present(finder_value)
found_object = finder_class.find_by(finder_index => params[finder_value])
if found_object
found_object
else
fail Errors::ObjectNotFoundError.new(finder_class)
end
end
# "Cannot find course with that id."
def render_not_found_if_object_not_found(params)
render json: { error: "Cannot find #{params.to_s.tableize.singularize} with that id." }, status: 404 and return
end
included do
rescue_from Errors::ObjectNotFoundError, with: :render_not_found_if_object_not_found
end
end
|
shared_examples_for 'a relation' do
describe '#respond_to?' do
it 'resolves associations' do
is_expected.to respond_to(:author)
end
end
describe '#association' do
it 'builds a table from the associated class' do
expect(table.association(:author)).to be_a(BabySqueel::Table)
end
it 'allows chaining attributes' do
assoc = table.association :author
expect(assoc.id).to be_a(Arel::Attributes::Attribute)
end
it 'raises an error for non-existant associations' do
expect {
table.association :non_existent
}.to raise_error(
BabySqueel::AssociationNotFoundError,
/named 'non_existent'(.+)for Post/
)
end
end
describe '#method_missing' do
it 'resolves associations' do
expect(table.author).to be_a(BabySqueel::Association)
end
it 'raises a custom error for things that look like columns' do
expect { table.non_existent_column }.to raise_error(BabySqueel::NotFoundError)
end
end
end
|
require 'formula'
HOMEBREW_CTRD_BRANCH='runu-darwin-master-190607'
HOMEBREW_CTRD_VERSION='beta'
class Containerd < Formula
homepage 'https://github.com/ukontainer/containerd'
url 'https://github.com/ukontainer/containerd.git', :branch => HOMEBREW_CTRD_BRANCH
version "#{HOMEBREW_CTRD_BRANCH}-#{HOMEBREW_CTRD_VERSION}"
head 'https://github.com/ukontainer/containerd.git', :branch => HOMEBREW_CTRD_BRANCH
depends_on 'go' => :build
def install
ENV['GOPATH'] = buildpath
system 'go', 'get', 'github.com/opencontainers/runtime-spec/specs-go'
system 'go', 'get', 'github.com/urfave/cli'
system 'go', 'get', 'github.com/sirupsen/logrus'
system 'go', 'get', 'github.com/opencontainers/runc/libcontainer/specconv'
mkdir_p buildpath/'src/github.com/containerd/'
ln_sf buildpath, buildpath/'src/github.com/containerd/containerd'
system 'cd src/github.com/containerd/containerd && make'
bin.install Dir['src/github.com/containerd/containerd/bin/*']
end
end
|
# frozen_string_literal: true
module ApplicationHelper
def display_style(flag)
flag ? 'display: none' : 'display: block'
end
end
|
require "spec_helper"
describe "Distributed Systems Learning" do
describe "a reading list" do
class DistributedSystems < ReadingList
name "Distributed Systems"
url "https://github.com/xoebus/reading-lists/tree/master/distributed-systems"
read? false
end
let(:reading_list) { DistributedSystems.new }
it "is read" do
expect(reading_list).to be_read
end
end
describe "a code project to learn the fundamentals" do
class Distribute < Project
name "Distribute"
url "https://github.com/xoebus/distribute"
finished? false
end
let(:distribute) { Distribute.new }
it "is finished" do
expect(distribute).to be_finished
end
end
end
|
require 'pr_cleaner/version'
require 'io/console'
require 'octokit'
require 'pry'
module PrCleaner
extend self
def clear(repo:, pr_number:, username:)
each_comment_of(repo, pr_number) do |comment|
next unless comment[:user][:login] == username
client.delete_pull_request_comment(repo, comment[:id])
end
end
private
def each_comment_of(repo, pr_number, &blk)
client.pull_request_comments(repo, pr_number).each(&blk)
end
def client
@client ||= begin
puts 'Enter your Github login:'
login = STDIN.gets.chomp
puts 'Enter your Github password:'
password = STDIN.noecho(&:gets).chomp
puts "Removing comments created by #{ARGV[2]}, this may take a while..."
Octokit::Client.new(login: login, password: password)
end
end
end
|
class BroFulfillmentMailer < ApplicationMailer
default from: "Bro Caps <brocaps@#{ENV['app_url']}>"
def shipping(fulfillment)
@fulfillment = fulfillment
@bro_order = @fulfillment.bro_order
@shipping_address = @fulfillment.shipping_address
@line_items = @fulfillment.line_items
mail(to: @bro_order.email, subject: "Your Bro Caps are on the way!")
end
def shipment_delivered(fulfillment)
@fulfillment = fulfillment
@bro_order = @fulfillment.order
@shipping_address = @fulfillment.shipping_address
@line_items = @fulfillment.line_items
mail(to: @bro_order.email, subject: "#{short_guid @order} Shipment delivered")
end
end |
# ActiveRecord
########################################################
# ActiveRecord::Base.configurations = YAML.load_file('database.yml')
# ActiveRecord::Base.establish_connection(:development)
ActiveRecord::Base.establish_connection(
adapter: "postgresql",
database: ENV['DB_NAME2'],
host: "",
username: ENV['DB_USER'],
password: ENV['DB_PASSWORD'],
encoding: "utf8"
)
class Member < ActiveRecord::Base
has_secure_password
belongs_to :author
validates :userid, {presence: {message: "ใฆใผใถใผIDใๅ
ฅๅใใฆไธใใ"}, uniqueness: {message: "ใใฎใฆใผใถใผIDใฏไฝฟ็จใใใฆใใใใใๆๅฎใงใใพใใ"}}
validates :password, {presence: {message: "ใในใฏใผใใๅ
ฅๅใใฆไธใใ"}, confirmation: {message: "ใในใฏใผใใไธ่ดใใพใใ"}}
validates :password_confirmation, {presence: {message: "ใในใฏใผใใๅ
ฅๅใใฆไธใใ"}}
end
class Author < ActiveRecord::Base
has_many :members
end
class Page < ActiveRecord::Base
validates :title, {presence: {message: "ใฟใคใใซใๅ
ฅๅใใฆไธใใ"}}
validates :permalink, {presence: {message: "ใใผใใชใณใฏใๅ
ฅๅใใฆไธใใ"}, uniqueness: {message: "ๅ
ฅๅใใใใใผใใชใณใฏใฏใใงใซไฝฟใใใฆใใใใใๆๅฎใงใใพใใ"}}
end
class Competition < ActiveRecord::Base
belongs_to :compe_kind
belongs_to :event
belongs_to :pref
belongs_to :generation
belongs_to :tag
validates :title, {presence: {message: "ใฟใคใใซใๅ
ฅๅใใฆไธใใ"}}
validates :event_id, {presence: {message: "็ซถๆ็จฎ็ฎใ้ธๆใใฆไธใใ"}}
validates :pref_id, {presence: {message: "ๅฐๅใ้ธๆใใฆไธใใ"}}
validates :generation_id, {presence: {message: "ๅนดไปฃใ้ธๆใใฆไธใใ"}}
validates :compe_kind_id, {presence: {message: "ๆ็จฟใฎ็จฎ้กใ้ธๆใใฆไธใใ"}}
end
class CompeKind < ActiveRecord::Base
has_many :competitions
end
class Event < ActiveRecord::Base
has_many :competitions
validates :name, {presence: {message: "ๅๅใๅ
ฅๅใใฆไธใใ"}}
validates :slug, {presence: {message: "ในใฉใใฐใๅ
ฅๅใใฆไธใใ"}, uniqueness: {message: "ๅ
ฅๅใใใในใฉใใฐใฏใใงใซไฝฟใใใฆใใใใใๆๅฎใงใใพใใ"}}
end
class Pref < ActiveRecord::Base
belongs_to :area
has_many :competitions
validates :name, {presence: {message: "ๅๅใๅ
ฅๅใใฆไธใใ"}}
validates :slug, {presence: {message: "ในใฉใใฐใๅ
ฅๅใใฆไธใใ"}, uniqueness: {message: "ๅ
ฅๅใใใในใฉใใฐใฏใใงใซไฝฟใใใฆใใใใใๆๅฎใงใใพใใ"}}
end
class Area < ActiveRecord::Base
has_many :prefs
end
class Generation < ActiveRecord::Base
has_many :competitions
validates :name, {presence: {message: "ๅๅใๅ
ฅๅใใฆไธใใ"}}
validates :slug, {presence: {message: "ในใฉใใฐใๅ
ฅๅใใฆไธใใ"}, uniqueness: {message: "ๅ
ฅๅใใใในใฉใใฐใฏใใงใซไฝฟใใใฆใใใใใๆๅฎใงใใพใใ"}}
end
class Tag <ActiveRecord::Base
has_many :competitions
validates :name, {presence: {message: "ๅๅใๅ
ฅๅใใฆไธใใ"}}
validates :slug, {presence: {message: "ในใฉใใฐใๅ
ฅๅใใฆไธใใ"}, uniqueness: {message: "ๅ
ฅๅใใใในใฉใใฐใฏใใงใซไฝฟใใใฆใใใใใๆๅฎใงใใพใใ"}}
end
class New < ActiveRecord::Base
belongs_to :newscategory
validates :title, {presence: {message: "ใฟใคใใซใๅ
ฅๅใใฆไธใใ"}}
validates :newscategory_id, {presence: {message: "ใใฅใผในใซใใดใชใ้ธๆใใฆไธใใ"}}
end
class Newscategory < ActiveRecord::Base
has_many :news
validates :name, {presence: {message: "ใฟใคใใซใๅ
ฅๅใใฆไธใใ"}}
validates :slug, {presence: {message: "ในใฉใใฐใๅ
ฅๅใใฆไธใใ"}, uniqueness: {message: "ๅ
ฅๅใใใในใฉใใฐใฏใใงใซไฝฟใใใฆใใใใใๆๅฎใงใใพใใ"}}
end
class Slider < ActiveRecord::Base
validates :title, {presence: {message: "ใฟใคใใซใๅ
ฅๅใใฆไธใใ"}}
validates :image, {presence: {message: "็ปๅใๆฟๅ
ฅใใฆไธใใ"}}
end
class Sponcer < ActiveRecord::Base
validates :title, {presence: {message: "ใฟใคใใซใๅ
ฅๅใใฆไธใใ"}}
validates :image, {presence: {message: "็ปๅใๆฟๅ
ฅใใฆไธใใ"}}
end
class Setting < ActiveRecord::Base
end
# ActionMailer
########################################################
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
address: ENV['MAILER_ADDRESS'],
port: ENV['MAILER_PORT'],
domain: ENV['MAILER_DOMAIN'],
user_name: ENV['MAILER_USER_NAME'],
password: ENV['MAILER_PASSWORD']
}
ActionMailer::Base.view_paths = File.expand_path('views/mailer')
class InquiryMailer < ActionMailer::Base
def send_user(name, mail, title, content)
@name = name
@mail = mail
@title = title
@content = content
mail(
to: @mail,
from: ENV['SEND_USER_FROM'],
subject: 'ใใฝใใจ๏ฝใๅใๅใใใใใใจใใใใใพใ',
) do |format|
format.text
end
end
def send_admin(name, mail, title, content)
@name = name
@mail = mail
@title = title
@content = content
mail(
to: ENV['SEND_ADMIN_TO'],
from: ENV['SEND_ADMIN_FROM'],
subject: 'ใใฝใใจ๏ฝใตใคใใใใๅใๅใใใใใใพใใ',
) do |format|
format.text
end
end
end
class SponcerMailer < ActionMailer::Base
def send_sponcer(company, zip, address, position, name, furi, mail, tel, fax, content)
@company = company
@zip = zip
@address = address
@position = position
@name = name
@furi = furi
@mail = mail
@tel = tel
@fax = fax
@content = content
mail(
to: @mail,
from: ENV['SEND_USER_FROM'],
subject: 'ใใฝใใจ๏ฝใๅใๅใใใใใใจใใใใใพใ',
) do |format|
format.text
end
end
def send_admin(company, zip, address, position, name, furi, mail, tel, fax, content)
@company = company
@zip = zip
@address = address
@position = position
@name = name
@furi = furi
@mail = mail
@tel = tel
@fax = fax
@content = content
mail(
to: ENV['SEND_ADMIN_TO'],
from: ENV['SEND_ADMIN_FROM'],
subject: 'ใใฝใใจ๏ฝใตใคใใใในใใณใตใผๆฒ่ผไพ้ ผใใใใพใใ',
) do |format|
format.text
end
end
end |
class Product < ActiveRecord::Base
validates_presence_of :name, :legacy_id
has_many :orders, through: :order_details
end
|
class Comment < ApplicationRecord
belongs_to :commenter, class_name: "User"
belongs_to :commentable, polymorphic: true
validates :comment_content, presence: true, length: { minimum: 1 }
end
|
class CreateMovies < ActiveRecord::Migration[5.1]
def change
create_table :movies do |t|
t.integer :site, null: false
t.string :name, null: false
t.date :open
t.string :code, null: false
t.references :artist, foreign_key: true, null: false
t.integer :total_view, default: 0
t.timestamps
end
end
end
|
require "puppet/provider/package"
Puppet::Type.type(:package).provide(:homebrew, :parent => Puppet::Provider::Package) do
desc "Package management using Homebrew."
commands :brew => "brew"
has_feature :installable, :uninstallable, :versionable
def self.installed
brew(:list, "-v").split("\n").map { |line| line.split }
end
def self.instances
installed.map { |name, version|
ensure_value = if version == "HEAD"
:head
else
:present
end
new(:name => name, :ensure => ensure_value, :provider => :homebrew)
}
end
def install
if resource[:ensure] == :head
brew(:install, "--HEAD", resource[:name])
else
brew(:install, resource[:name])
end
end
def query
unless brew(:list, "-v", resource[:name]).strip.empty?
{ :name => resource[:name], :ensure => :present, :provider => :homebrew }
end
end
def uninstall
brew(:remove, resource[:name])
end
end
|
class CreateEndecaRecordChanges < ActiveRecord::Migration
def self.up
create_table :endeca_record_changes do |t|
t.column :review_id, :bigint
t.column :product_id, :bigint
t.column :change, :enum, EndecaRecordChange::CHANGE_DB_OPTS
t.column :status, :enum, EndecaRecordChange::STATUS_DB_OPTS
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
add_index :endeca_record_changes, :status
end
def self.down
drop_table :endeca_record_changes
end
end
|
require "spec_helper"
describe ORS::Commands::Update do
context "#run" do
before do
ORS.config.parse_options([])
ORS.config.parse_config_file
end
it "should update code, bundle install, and set up cron" do
ORS.config[:all_servers] = :all_servers
ORS.config[:ruby_servers] = :ruby_servers
ORS.config[:cron_server] = :cron_server
mock(subject).info /updating/
mock(subject).execute_in_parallel(:all_servers)
mock(subject).execute_in_parallel(:ruby_servers)
mock(subject).execute_command(:cron_server, is_a(Array), is_a(String))
subject.execute
end
end
end
|
class CubesController < ApplicationController
def index
@cubes = Cube.all
end
def show
@cube = Cube.find_by_serial params[:id]
@rooms = @cube.rooms
respond_to do |format|
format.html { render }
format.json { render json: @cube }
end
end
end |
file = File.join(Rails.root, 'config', "sidekiq-#{Rails.env}.yml")
file = File.join(Rails.root, 'config', 'sidekiq.yml') unless File.exist?(file)
require File.join(Rails.root, 'lib', 'middleware_sidekiq_server_retry')
require "sidekiq"
require "sidekiq/cloudwatchmetrics"
Sidekiq::Extensions.enable_delay!
# Only enable CloudWatch metrics for Live, not Travis or other
# integration test environments.
#
if "#{ENV['DEPLOY_ENV']}" == 'live'
Sidekiq::CloudWatchMetrics.enable!(
namespace: "sidekiq_checkapi_#{Rails.env}",
additional_dimensions: { "ClusterName" => "Sidekiq-#{ENV['DEPLOY_ENV']}" } )
end
REDIS_CONFIG = {}
if File.exist?(file)
require 'sidekiq/middleware/i18n'
require 'connection_pool'
SIDEKIQ_CONFIG = YAML.load_file(file)
Rails.application.configure do
config.active_job.queue_adapter = :sidekiq
redis_url = { host: SIDEKIQ_CONFIG[:redis_host], port: SIDEKIQ_CONFIG[:redis_port], db: SIDEKIQ_CONFIG[:redis_database], namespace: "cache_checkapi_#{Rails.env}" }
config.cache_store = :redis_cache_store, redis_url
end
redis_config = { url: "redis://#{SIDEKIQ_CONFIG[:redis_host]}:#{SIDEKIQ_CONFIG[:redis_port]}/#{SIDEKIQ_CONFIG[:redis_database]}", namespace: "sidekiq_checkapi_#{Rails.env}", network_timeout: 5 }
REDIS_CONFIG.merge!(redis_config)
Sidekiq.configure_server do |config|
config.redis = redis_config
config.server_middleware do |chain|
chain.add ::Middleware::Sidekiq::Server::Retry
end
end
Sidekiq.configure_client do |config|
config.redis = redis_config
config.logger.level = Logger::WARN if Rails.env.test?
end
end
|
require("minitest/autorun")
require("minitest/rg")
require_relative("../extension_solution")
class TestLibrary < MiniTest::Test
def setup
@book1 = {
title: "lord_of_the_rings",
rental_details: {
student_name: "Jeff",
date: "01/12/18"
}
}
@book2 = {
title: "Harry Potter",
rental_details: {
student_name: "Louise",
date: "11/11/18"
}
}
@book3 = {
title: "The Hobbit",
rental_details: {
student_name: "Paula",
date: "07/08/18"
}
}
@library = Library.new()
@library.add_book(@book1)
end
def test_add_book()
@library.add_book(@book2)
result = @library.books
assert_equal(2, result.size())
end
def test_get_book_by_title()
result = @library.find_by_title("lord_of_the_rings")
assert_equal(@book1, result)
end
def test_get_rental_details_by_title()
result = @library.get_rental_details("lord_of_the_rings")
assert_equal(@book1[:rental_details], result)
end
def test_add_book_without_rental_details()
@library.add_book_by_title("The Hobbit")
expected_book = {
title: "The Hobbit",
rental_details: {
student_name: "",
date: ""
}
}
actual_book = @library.find_by_title("The Hobbit")
assert_equal(expected_book, actual_book)
end
def test_change_rental_details()
@library.change_rental_details("lord_of_the_rings", "Bob", "25/12/18")
result = @library.find_by_title("lord_of_the_rings")
expected_book = {
title: "lord_of_the_rings",
rental_details: {
student_name: "Bob",
date: "25/12/18"
}
}
assert_equal(expected_book, result)
end
end
|
module Wikify
# Methods that get included on models using wikify
module Methods
# The Wikify update operation
#
# Creates a new version, records the cached object and saves it as an update
def wikify_update
new_version = self.send(wikify_options[:assoc_name]).new
new_version.data = @wikify_cached_object
new_version.event = (@wikify_override[:event] || "update")
new_version.save
end
# The Wikify create operation
#
# Creates a new version with no data and sets the event to create
def wikify_create
new_version = self.send(wikify_options[:assoc_name]).new
new_version.event = "create"
new_version.save
@wikify_cached_object = self.attributes
end
# The Wikify destroy operation
#
# Creates a new version recods the cached object and saves it as a destroy
def wikify_destroy
new_version = self.send(wikify_options[:assoc_name]).new
new_version.data = @wikify_cached_object
new_version.event = "destroy"
new_version.save
end
# The hash used to find versions
def wikify_search_hash
{"#{wikify_options[:assoc_as]}_id".to_sym => self.id, "#{wikify_options[:assoc_as]}_type".to_sym => self.class.to_s}
end
end
end |
require 'spec_helper'
describe Revent::Providers::RabbitMQ do
describe '#initialize' do
subject { described_class.new }
it 'creates mocked connection' do
expect(subject.conn.class).to eq BunnyMock::Session
expect(subject.channel.class).to eq BunnyMock::Channel
expect(subject.queue.class).to eq BunnyMock::Queue
end
end
describe '#publish' do
let(:event_name) { 'account.create' }
let!(:event) do
ActiveSupport::Notifications::Event.new(
event_name,
Time.now,
Time.now,
SecureRandom.hex(8),
{ foo: :bar }
)
end
subject { described_class.new.publish(event) }
it 'sends event message to queue' do
expect(subject.message_count).to eq 1
end
it 'sends event payload' do
message = JSON.parse(subject.pop.last)
expect(message['event']).to eq event_name
expect(message['payload']).to eq({ 'foo' => 'bar' })
end
end
end
|
# encoding: utf-8
# ัะพะดะตัะถะธััั: String, Walls, Creation, Matrix
# SizeM = rand(15 .. 20)
SizeM = 15
class String
def black; "\033[30m#{self}\033[0m" end
def red; "\033[31m#{self}\033[0m" end
def green; "\033[32m#{self}\033[0m" end
def brown; "\033[33m#{self}\033[0m" end
def blue; "\033[34m#{self}\033[0m" end
def magenta; "\033[35m#{self}\033[0m" end
def cyan; "\033[36m#{self}\033[0m" end
def gray; "\033[37m#{self}\033[0m" end
def bg_black; "\033[40m#{self}\033[0m" end
def bg_red; "\033[41m#{self}\033[0m" end
def bg_green; "\033[42m#{self}\033[0m" end
def bg_brown; "\033[43m#{self}\033[0m" end
def bg_blue; "\033[44m#{self}\033[0m" end
def bg_magenta; "\033[45m#{self}\033[0m" end
def bg_cyan; "\033[46m#{self}\033[0m" end
def bg_gray; "\033[47m#{self}\033[0m" end
def bold; "\033[1m#{self}\033[22m" end
def reverse_color; "\033[7m#{self}\033[27m" end
end
#///////////////////////////////////////////////////////////////////////////////
class Walls
def initialize
@walls = []
@ch = 'โ'.bold.black
end
def wall; @ch; end
def add_walls(x, y)
@walls << [x, y]
@walls.uniq!
end
def is_wall?(x, y)
@walls.include?([x, y]) ? true : false
end
def delete_wall(x, y)
@walls.delete([x, y])
@walls.compact!
end
def return_w; @walls end
end
#///////////////////////////////////////////////////////////////////////////////
class Creation
def initialize
@hp = hp
@attack = attack
end
def get_damage(d); @hp -= d end
def give_damage; @attack end
def x; @x end
def y; @y end
end
#///////////////////////////////////////////////////////////////////////////////
class Matrix
def initialize
@matrix = []
for i in 0 .. SizeM
@matrix << []
for k in 0 .. SizeM
@matrix[-1] << nil
end
end
end
def get_matrix; @matrix end
def get_elem(x, y)
@matrix[x][y] != nil ? @matrix[x][y] : nil
end
def delete(x, y)
@matrix[x + 1][y + 1] = nil
end
def add(a)
if a.class == Trank
x = a.x
y = a.y
@matrix[x][y] = a.trank
end
if a.class == Orda
if a.orda[0].class == Enemy
i = 0
while a.orda[i] != nil
x = a.orda[i].x + 1
y = a.orda[i].y + 1
if @matrix[x][y] == nil
@matrix[x][y] = a.orda[i]
elsif @matrix[x][y].class != Enemy
a.delete(x - 1, y - 1)
i -= 1
end
i += 1
end
end
elsif a.class == Walls
for i in 0 .. a.return_w.size - 1
x = a.return_w[i][0] + 1
y = a.return_w[i][1] + 1
@matrix[x][y] = a.wall if @matrix[x][y] == nil
end
elsif a.class == Tunnel
@matrix[a.x + 1][a.y + 1] = a.tunnel
end
end
def add_you(x, y)
@matrix[x + 1][y + 1] = 'Y'.bold.green
end
def display(option)
if option == 0
@matrix.reverse!
for i in 0 .. SizeM #10x10 ะผะฐััะธัะฐ
for k in 0 .. SizeM
if @matrix[i][k].class == Enemy
print 'E'.red
else
if @matrix[i][k] != nil
print @matrix[i][k]
else
print ' '
end
end
end
puts
end
@matrix.reverse!
elsif option == 1
system "clear"
puts "\\ / _____ O ___".red
puts " \\ / [ ] | | \\ /\\ / | | |\\ | | |".blue
puts " \\ / | | | | \\ / \\ / | | | \\ | | |".cyan
puts " | | | | | \\ / \\ / | | | \\ | | |".magenta
puts " | | | | | \\ / \\ / | | | \\ | | |".cyan
puts " | [_____] [______] \\/ \\/ |_| | \\| O ".gray
else
system "clear"
puts "\\ / _____ _____ ____ _____ ".red
puts " \\ / [ ] | | | [ ] | | | |".red
puts " \\ / | | | | | | | \\ | ".red
puts " | | | | | | | | \\ |_____ ".red
puts " | | | | | | | | \\_ | ".red
puts " | [_____] [______] |______ [_____] ____] |_____|".red
end
end
end
|
require 'httparty'
require 'shopware/api/client/articles'
require 'shopware/api/client/categories'
require 'shopware/api/client/property_groups'
require 'shopware/api/client/variants'
module Shopware
module API
class Client
include HTTParty
headers 'Content-Type' => 'application/json', 'charset' => 'utf-8'
format :json
query_string_normalizer proc { |query| query.to_json }
def initialize(options = {})
self.class.base_uri options['uri']
self.class.digest_auth options['username'], options['key']
end
include Articles
include Categories
include PropertyGroups
include Variants
end
end
end |
# frozen_string_literal: true
class ChangeResearcherToGlobalGuest < ActiveRecord::Migration[5.1]
def up
execute <<~SQL.squish
UPDATE roles
SET name = 'global_guest'
WHERE name = 'researcher' AND resource_id IS NULL
SQL
end
def down
execute <<~SQL.squish
UPDATE roles
SET name = 'researcher'
WHERE name = 'global_guest'
SQL
end
end
|
# -------------------------------------------------------------------------- #
# Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------- #
$: << "#{File.dirname(__FILE__)}/../../"
require 'rubygems'
require 'openvz'
require 'lib/parsers/im'
require 'file_utils'
require 'open_vz_data'
require 'scripts_common'
module OpenNebula
# OpenVzDriver represents driver capable of performing basic operations characterized by OpenNebula vmm specification
#
class OpenVzDriver
# OpenVzDriver exception class
class OpenVzDriverError < StandardError;
end
# a directory where the context iso img is mounted
CTX_ISO_MNT_DIR = '/mnt/isotmp'
# enforce using sudo since opennebula runs script as a oneadmin
OpenVZ::Util.enforce_sudo = true
# Creates new vm based on its description file
#
# * *Args* :
# - +open_vz_data+ -> reference to openvz data descriptor. An instance of OpenNebula::OpenVzData class
# - +container+ -> reference to container. An instance of OpenVZ::Container class
def deploy(open_vz_data, container)
OpenNebula.log_debug("Deploying vm #{open_vz_data.vmid} using ctid:#{container.ctid}")
# create symlink to enable ovz to find image
template_name = "#{open_vz_data.context[:distro]}-#{container.ctid}"
template_cache = create_template template_name, open_vz_data.disk
# options to be passed to vzctl create
options = process_options open_vz_data.raw, {:ostemplate => template_name}
# create and run container
container.create(options)
container.start
# set up networking
apply_network_settings container, open_vz_data.networking
# and contextualise it if user provided any context info
contextualise container, open_vz_data.context_disk, open_vz_data.context if open_vz_data.context != {} and open_vz_data.context_disk.to_s != ''
container.ctid
rescue RuntimeError => e
raise OpenVzDriverError, "Container #{container.ctid} can't be deployed. Details: #{e.message}"
ensure
# cleanup template cache - we don't need it anymore
File.delete template_cache if template_cache and File.exists? template_cache
# TODO cleanup after a failed attempt to deploy, e.g. destroy a partly-deployed container
end
# Sends shutdown signal to a VM
#
# * *Args* :
# - +container+ -> reference to container. An instance of OpenVZ::Container class
def shutdown(container)
OpenNebula.log_debug "Shutdowning container: #{container.ctid}"
container.stop
rescue RuntimeError => e
raise OpenVzDriverError, "Container #{container.ctid} can't be stopped. Details: #{e.message}"
end
# Destroys a Vm
#
# * *Args* :
# - +container+ -> reference to container. An instance of OpenVZ::Container class
def cancel(container)
OpenNebula.log_debug "Canceling container: #{container.ctid}"
container.stop
container.destroy
rescue RuntimeError => e
raise OpenVzDriverError, "Container #{container.ctid} can't be canceled. Details: #{e.message}"
end
# Suspends a VM
def save(container, destination_file)
OpenNebula.log_debug "Saving container: #{container.ctid} to #{destination_file}"
container.checkpoint destination_file
rescue RuntimeError => e
raise OpenVzDriverError, "Container #{container.ctid} can't be saved. Details: #{e.message}"
end
# Restores a VM to a previous saved state
def restore(container, source_file)
OpenNebula.log_debug "Restoring container from #{source_file}"
container.restore source_file
rescue RuntimeError => e
raise OpenVzDriverError, "Container #{container.ctid} can't be restored. Details: #{e.message}"
end
# Performs live migration of a VM
def migrate(container, host)
OpenNebula.log_debug "Migrating container: #{container.ctid} to host: #{host}"
# TODO migration will crash when container.ctid is used at destination host
# however this will require modification of ruby-openvz (ie. allowing of quering remote host for ids)
container.migrate host
rescue RuntimeError => e
raise OpenVzDriverError, "Container #{container.ctid} can't be migrated. Details: #{e.message}"
end
def reboot(container)
OpenNebula.log_debug "Rebooting container: #{container.ctid}"
container.restart
rescue RuntimeError => e
raise OpenVzDriverError, "Container #{container.ctid} can't be rebooted. Details: #{e.message}"
end
# Gets information about a VM
#
# * *Args* :
# - +container+ -> reference to container. An instance of OpenVZ::Container class
def poll(container)
info = Hash.new 0
# state
states = {'exist' => 'a', 'deleted' => 'd', 'suspended' => 'p'}
states.default = '-'
status = container.status
# state can be either active or deleted
info[:state] = states[status[0]]
# however if there is additional status field then it may be also suspended (see vzctl status comamnd)
info[:state] = states[status[3]] if status.size == 4
# if ct is down there is nothing we can do here
return info if info[:state] != 'a'
# ONE requires usedcpu to be equal to cpu utilization on all processors
# ex. usedcpu=200 when there are 2 fully loaded cpus
# currently i get only average pcpu and multiply it by number of cpus
out = (container.command "cat /proc/cpuinfo").split
cpu_amount = out.find_all { |line| /processor/ =~ line }.size
out = (container.command "ps axo pcpu=").split
info[:usedcpu] = cpu_amount * out.inject(0.0) { |sum, current| sum + current.to_f }
# net transmit & receive
netrx, nettx = IMBaseParser.in_out_bandwith container.command "cat /proc/net/dev"
info[:netrx] += netrx.to_i
info[:nettx] += nettx.to_i
# computer container memory usage
_, used_memory, _ = IMBaseParser.memory_info container.command "free -k"
info[:usedmemory] = used_memory.to_i
info
rescue RuntimeError => e
raise OpenVzDriverError, "Can't get container #{container.ctid} status. Details: #{e.message}"
end
# Get the ctid.
#
# * *Args* :
# - +inventory+ -> reference to inventory which lists all taken ctids
# - +vmid+ -> vmid used by opennebula
# - +offset+ -> offset between vmid and proposed ctid.
# It's used becouse vmids used by ONE starts from 0, whereas OpenVZ reserves ctids < 100 for special purposes.
# Hence, offset should be at least 100
def self.ctid(inventory, vmid, offset = 690)
# returned id is equal to vmid + offset. If there is already such id, then the nearest one is taken
# we internally operate on ints
ct_ids = inventory.ids.map { |e| e.to_i }
proposed = vmid.to_i
# attempty to return propsed id
proposed += offset
return proposed.to_s unless ct_ids.include? proposed
# if that id is already taken chose the closest one to avoid conflict
ct_ids = ct_ids.find_all { |x| x >= proposed }
# return string since ruby-openvz takes for granted that id is a string
# note that ct_ids are assumed to be sorted in ascending order
ct_ids.inject(proposed) do |mem, var|
break mem unless mem == var
mem += 1
end.to_s
end
private
# A method that applies network settings provided in the deployment file
#
# * *Args* :
# - +networking+ -> hash with specified options
def apply_network_settings container, networking
OpenNebula.log_debug "Configuring network"
nic_settings = {
# ifname and host_mac
:ipadd => networking[:ip]
}
container.command "\"echo 'nameserver #{networking[:nameserver]}' > /etc/resolv.conf\""
container.set nic_settings
end
# Helper method used for template creation by symlinking it to the vm's datastore disk location
#
# * *Args* :
# - +template_name+ -> name of the template cache to ve
# - +disk_file+ -> path to vm diskfile
def create_template(template_name, disk_file)
disk_file_type = FileUtils.archive_type disk_file
# TODO such hardcoded paths have to be moved out to some configuration files
template_file = File.join("/", "vz", "template", "cache", "#{template_name}.#{disk_file_type}")
File.symlink disk_file, template_file
template_file
end
# Method used to merge vzctl options provided within:
# - <raw> section of deployment file
# - arbitrary data passed by options
#
# * *Args* :
# - +raw+ -> The container to contextualise. An instance of OpenVZ::Container class
# - +options+ -> arbitrary data, ex ostemplate, ip_add
def process_options(raw, options = {})
raw.merge!(options)
# normalize all keys to lowercase
new_hash = {}
raw.each { |k, v| new_hash.merge!(k.to_s.downcase.to_sym => v) }
# filter out type -> it is only meaningful to opennebula
new_hash.delete(:type)
new_hash
end
# Method used during deployment of the given vm to contextualise it
#
# * *Args* :
# - +container+ -> The container to contextualise. An instance of OpenVZ::Container class
# - +iso_file+ -> Path to ISO file which holds context data. An instance of String class
# - +context+ -> Context parameters. An instance of Hash class
def contextualise(container, iso_file, context)
OpenNebula.log_debug "Applying contextualisation using #{iso_file}, files: #{context[:files]}"
# TODO such hardcoded paths have to be moved out to some configuration files
ctx_mnt_dir = "/vz/root/#{container.ctid}#{CTX_ISO_MNT_DIR}"
# mount the iso file
container.command "mkdir #{CTX_ISO_MNT_DIR}"
OpenNebula.exec_and_log "sudo mount #{iso_file} #{ctx_mnt_dir} -o loop"
# run all executable files. It's up to them whether they use context.sh or not
files = FileUtils.filter_executables context[:files]
files.each do |abs_fname|
fname = File.basename abs_fname
container.command ". #{CTX_ISO_MNT_DIR}/#{fname}"
end
rescue => e
OpenNebula.log_error "Exception while performing contextualisation: #{e.message}"
# reraise the exception
raise OpenVzDriverError, "Exception while performing contextualisation: #{e.message}"
ensure
# cleanup
OpenNebula.exec_and_log "sudo mountpoint #{ctx_mnt_dir}; if [ $? -eq 0 ]; then " \
" sudo umount #{ctx_mnt_dir};" \
" sudo rmdir #{ctx_mnt_dir};" \
" fi" if ctx_mnt_dir
end
end
end
|
class SessionsController < ApplicationController
skip_before_action :verify_authenticity_token
def new
redirect_to site_root_url and return if current_merchant.present?
end
def create
merchant = Merchant.find_by_email(params[:email])
if merchant && merchant.authenticate(params[:password])
session[:merchant_id] = merchant.id
redirect_to merchant_dashboard_path and return
else
@errors = ['Email or password is invalid']
render 'new'
end
end
def destroy
session.delete(:merchant_id)
redirect_to site_root_url and return
end
end
|
class CreateKingdomCitizens < ActiveRecord::Migration
def change
create_table :kingdom_citizens do |kc|
kc.integer :kingdom_id
kc.integer :citizen_id
end
end
end
|
class BidsController < ApplicationController
before_action :set_round, only: [:index, :create]
before_action :set_player, only: [:create]
def create
bid = Bid.new(
round: @round,
player: @player,
pass: bid_params[:pass],
number_of_tricks: bid_params[:number_of_tricks],
suit: bid_params[:suit]
)
if bid.save
render json: bid.round, serializer: RoundSerializer, status: :created, locals: { errors: [] }
else
render json: { errors: bid.errors }, status: :unprocessable_entity
end
end
private
def set_round
@round = Round.find(bid_params[:round_id])
end
def set_player
@player = @round.game.players.find_by(user: current_user)
end
def bid_params
params.permit(:round_id, :pass, :number_of_tricks, :suit)
end
end
|
Rails.application.routes.draw do
resources :emergencies, only: [:create, :index, :patch]
resources :responders, only: [:create, :index, :patch]
match '*unmatched_route', to: 'application#render_not_found', via: :all
end
|
Rails.application.routes.draw do
devise_for :users, module: :users
get 'home/index'
get 'home/root'
get 'touring_routes/archives'
root to: "home#root"
resources :comments
resources :touring_routes
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.