text stringlengths 10 2.61M |
|---|
class EndecaRecordChangesAddIndex < ActiveRecord::Migration
def self.up
add_index :endeca_record_changes, [:status, :review_id], :name => :endeca_record_changes_status_and_review_id_index
end
def self.down
remove_index :endeca_record_changes, :name => :endeca_record_changes_status_and_review_id_index
end
end
|
Rails.application.routes.draw do
root to: "projects#index"
resources :projects do
resources :milestones
end
devise_for :users
get 'public/:id', to: "public#show"
end
|
class Patient < ApplicationRecord
enum gender: [:male, :female, :other]
has_many :allergies
has_many :chronic_conditions, -> {where code: "chronic"}, class_name: 'Diagnosis'
has_many :medications, class_name: 'MedicationOrder'
has_many :diagnoses, class_name: 'Diagnosis'
has_many :treatments
has_many :diagnostic_procedures
belongs_to :admission, optional: true
def summary(facility_name)
"This #{self.age} years old #{self.gender} was admitted to #{facility_name} on #{self.admission.date} at #{self.admission.time}
due to #{self.admission.list_of_diagnoses_descriptions(self.id).to_sentence}. The observed symptoms on admission were
#{self.admission.symptoms.collect(&:description).to_sentence}.
Upon asking about known allergies, the patient disclosed #{self.list_of_allergies}. Upon asking about the chronic conditions,
the patient disclosed #{self.chronic_conditions.collect(&:description).to_sentence}. The patient was administered with #{self.list_of_medications}.
The staff performed #{self.diagnostic_procedures_sentence} revealing #{(self.diagnoses.collect(&:description)).to_sentence}.
Our team proceeded to #{self.treatments_sentence}."
end
def age
now = Time.now.utc.to_date
now.year - self.dob.year - ((now.month > self.dob.month || (now.month == self.dob.month && now.day >= self.dob.day)) ? 0 : 1)
end
def full_name
"#{self.first_name} #{self.last_name}"
end
def treatments_sentence
self.treatments.collect { |treatment| "#{treatment.description} to #{treatment.necessity}"}.to_sentence
end
def list_of_allergies
self.allergies.collect(&:description).to_sentence if self.allergies
end
def list_of_medications
self.medications.collect { |medication| "#{medication.name} #{medication.dosage.to_f} #{medication.order_frequency.value}#{medication.order_frequency.unit} to #{medication.necessity}"}.to_sentence
end
def diagnostic_procedures_sentence
self.diagnostic_procedures.collect { |procedure| "#{procedure.description} on #{procedure.date} at #{procedure.time}"}.to_sentence
end
end
|
class AddUserIdTopicIdToUserTopics < ActiveRecord::Migration
def change
add_column :user_topics, :user_id, :string
add_column :user_topics, :topic_id, :string
end
end
|
# class ApplicationController < ActionController::Base
# # Prevent CSRF attacks by raising an exception.
# # For APIs, you may want to use :null_session instead.
# #protect_from_forgery with: :exception
# end
class ApplicationController < ActionController::Base
# def current_user
# @current_user ||= User.find(session[:user_id])
# end
def can_administer?
true
# current_user.try(:admin?)
end
protect_from_forgery
# rowsPerPage 한 페이지당 표시될 게시물 수
# 모든 컨트롤러에서 사용가능하게 여기에 정의한다.
def rowsPerPage
@rowsPerPage ||= 5
end
end |
class Screenshot < ActiveRecord::Base
attr_accessible :screenshot
belongs_to :project
mount_uploader :screenshot, ScreenshotUploader
end
|
module RendezvousRegistrationsHelper
STEP_ARRAY = [ 'welcome', 'sign', 'register', 'review', 'payment', 'vehicles' ]
def registration_progress_indicator(current_step, step, registration = nil)
if step == current_step
klass = 'active'
elsif STEP_ARRAY.index(step) < STEP_ARRAY.index(current_step)
klass = 'complete'
else
klass = 'to_do'
end
end
def donation_list(raw_values)
list = raw_values.map{ |v| ["$#{v.to_s}", v] }
list << ['Other', 'other']
end
def payment_options
[['I wish to pay by credit card now', 'credit card'], [' I wish to pay by check', 'check']]
end
end
|
class BookGenre < ActiveRecord::Base
belongs_to :book
belongs_to :genre
validates :genre_id, uniqueness: {scope: :book_id}
end
|
#!/usr/bin/env ruby
require 'Matrices_Dispersas_ETSII'
require "Matrices_Dispersas_ETSII/version"
module Matrices_Dispersas_ETSII
class Matriz
attr_accessor :rows, :cols, :data
undef rows=, cols=
def initialize(rows, cols)
@rows, @cols = rows, cols
@data = Array.new(@rows) {Array.new(@cols)}
end
def [](i)
@data[i]
end
def [](i, value)
@data[i] = value
end
end
class Densa
end
class Dispersa
end
end
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2020 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Net
autoload :HTTP, 'net/http'
end
module Mongo
class Socket
# OCSP endpoint verifier.
#
# After a TLS connection is established, this verifier inspects the
# certificate presented by the server, and if the certificate contains
# an OCSP URI, performs the OCSP status request to the specified URI
# (following up to 5 redirects) to verify the certificate status.
#
# @see https://ruby-doc.org/stdlib/libdoc/openssl/rdoc/OpenSSL/OCSP.html
#
# @api private
class OcspVerifier
include Loggable
# @param [ String ] host_name The host name being verified, for
# diagnostic output.
# @param [ OpenSSL::X509::Certificate ] cert The certificate presented by
# the server at host_name.
# @param [ OpenSSL::X509::Certificate ] ca_cert The CA certificate
# presented by the server or resolved locally from the server
# certificate.
# @param [ OpenSSL::X509::Store ] cert_store The certificate store to
# use for verifying OCSP response. This should be the same store as
# used in SSLContext used with the SSLSocket that we are verifying the
# certificate for. This must NOT be the CA certificate provided by
# the server (i.e. anything taken out of peer_cert) - otherwise the
# server would dictate which CA authorities the client trusts.
def initialize(host_name, cert, ca_cert, cert_store, **opts)
@host_name = host_name
@cert = cert
@ca_cert = ca_cert
@cert_store = cert_store
@options = opts
end
attr_reader :host_name
attr_reader :cert
attr_reader :ca_cert
attr_reader :cert_store
attr_reader :options
def timeout
options[:timeout] || 5
end
# @return [ Array<String> ] OCSP URIs in the specified server certificate.
def ocsp_uris
@ocsp_uris ||= begin
# https://tools.ietf.org/html/rfc3546#section-2.3
# prohibits multiple extensions with the same oid.
ext = cert.extensions.detect do |ext|
ext.oid == 'authorityInfoAccess'
end
if ext
# Our test certificates have multiple OCSP URIs.
ext.value.split("\n").select do |line|
line.start_with?('OCSP - URI:')
end.map do |line|
line.split(':', 2).last
end
else
[]
end
end
end
def cert_id
@cert_id ||= OpenSSL::OCSP::CertificateId.new(
cert,
ca_cert,
OpenSSL::Digest::SHA1.new,
)
end
def verify_with_cache
handle_exceptions do
return false if ocsp_uris.empty?
resp = OcspCache.get(cert_id)
if resp
return return_ocsp_response(resp)
end
resp, errors = do_verify
if resp
OcspCache.set(cert_id, resp)
end
return_ocsp_response(resp, errors)
end
end
# @return [ true | false ] Whether the certificate was verified.
#
# @raise [ Error::ServerCertificateRevoked ] If the certificate was
# definitively revoked.
def verify
handle_exceptions do
return false if ocsp_uris.empty?
resp, errors = do_verify
return_ocsp_response(resp, errors)
end
end
private
def do_verify
# This synchronized array contains definitive pass/fail responses
# obtained from the responders. We'll take the first one but due to
# concurrency multiple responses may be produced and queued.
@resp_queue = Queue.new
# This synchronized array contains strings, one per responder, that
# explain why each responder hasn't produced a definitive response.
# These are concatenated and logged if none of the responders produced
# a definitive respnose, or if the main thread times out waiting for
# a definitive response (in which case some of the worker threads'
# diagnostics may be logged and some may not).
@resp_errors = Queue.new
@req = OpenSSL::OCSP::Request.new
@req.add_certid(cert_id)
@req.add_nonce
@serialized_req = @req.to_der
@outstanding_requests = ocsp_uris.count
@outstanding_requests_lock = Mutex.new
threads = ocsp_uris.map do |uri|
Thread.new do
verify_one_responder(uri)
end
end
resp = begin
::Timeout.timeout(timeout) do
@resp_queue.shift
end
rescue ::Timeout::Error
nil
end
threads.map(&:kill)
threads.map(&:join)
[resp, @resp_errors]
end
def verify_one_responder(uri)
original_uri = uri
redirect_count = 0
http_response = nil
loop do
http_response = begin
uri = URI(uri)
Net::HTTP.start(uri.hostname, uri.port) do |http|
path = uri.path
if path.empty?
path = '/'
end
http.post(path, @serialized_req,
'content-type' => 'application/ocsp-request')
end
rescue IOError, SystemCallError => e
@resp_errors << "OCSP request to #{report_uri(original_uri, uri)} failed: #{e.class}: #{e}"
return false
end
code = http_response.code.to_i
if (300..399).include?(code)
redirected_uri = http_response.header['location']
uri = ::URI.join(uri, redirected_uri)
redirect_count += 1
if redirect_count > 5
@resp_errors << "OCSP request to #{report_uri(original_uri, uri)} failed: too many redirects (6)"
return false
end
next
end
if code >= 400
@resp_errors << "OCSP request to #{report_uri(original_uri, uri)} failed with HTTP status code #{http_response.code}" + report_response_body(http_response.body)
return false
end
if code != 200
# There must be a body provided with the response, if one isn't
# provided the response cannot be verified.
@resp_errors << "OCSP request to #{report_uri(original_uri, uri)} failed with unexpected HTTP status code #{http_response.code}" + report_response_body(http_response.body)
return false
end
break
end
resp = OpenSSL::OCSP::Response.new(http_response.body)
unless resp.basic
@resp_errors << "OCSP response from #{report_uri(original_uri, uri)} is #{resp.status}: #{resp.status_string}"
return false
end
resp = resp.basic
unless resp.verify([ca_cert], cert_store)
# Ruby's OpenSSL binding discards error information - see
# https://github.com/ruby/openssl/issues/395
@resp_errors << "OCSP response from #{report_uri(original_uri, uri)} failed signature verification; set `OpenSSL.debug = true` to see why"
return false
end
if @req.check_nonce(resp) == 0
@resp_errors << "OCSP response from #{report_uri(original_uri, uri)} included invalid nonce"
return false
end
resp = resp.find_response(cert_id)
unless resp
@resp_errors << "OCSP response from #{report_uri(original_uri, uri)} did not include information about the requested certificate"
return false
end
# TODO make a new class instead of patching the stdlib one?
resp.instance_variable_set('@uri', uri)
resp.instance_variable_set('@original_uri', original_uri)
class << resp
attr_reader :uri, :original_uri
end
unless resp.check_validity
@resp_errors << "OCSP response from #{report_uri(original_uri, uri)} was invalid: this_update was in the future or next_update time has passed"
return false
end
unless [
OpenSSL::OCSP::V_CERTSTATUS_GOOD,
OpenSSL::OCSP::V_CERTSTATUS_REVOKED,
].include?(resp.cert_status)
@resp_errors << "OCSP response from #{report_uri(original_uri, uri)} had a non-definitive status: #{resp.cert_status}"
return false
end
# Note this returns the redirected URI
@resp_queue << resp
rescue => exc
Utils.warn_bg_exception("Error performing OCSP verification for '#{host_name}' via '#{uri}'", exc,
logger: options[:logger],
log_prefix: options[:log_prefix],
bg_error_backtrace: options[:bg_error_backtrace],
)
false
ensure
@outstanding_requests_lock.synchronize do
@outstanding_requests -= 1
if @outstanding_requests == 0
@resp_queue << nil
end
end
end
def return_ocsp_response(resp, errors = nil)
if resp
if resp.cert_status == OpenSSL::OCSP::V_CERTSTATUS_REVOKED
raise_revoked_error(resp)
end
true
else
reasons = []
errors.length.times do
reasons << errors.shift
end
if reasons.empty?
msg = "No responses from responders: #{ocsp_uris.join(', ')} within #{timeout} seconds"
else
msg = "For responders #{ocsp_uris.join(', ')} with a timeout of #{timeout} seconds: #{reasons.join(', ')}"
end
log_warn("TLS certificate of '#{host_name}' could not be definitively verified via OCSP: #{msg}")
false
end
end
def handle_exceptions
begin
yield
rescue Error::ServerCertificateRevoked
raise
rescue => exc
Utils.warn_bg_exception(
"Error performing OCSP verification for '#{host_name}'",
exc,
**options)
false
end
end
def raise_revoked_error(resp)
if resp.uri == resp.original_uri
redirect = ''
else
redirect = " (redirected from #{resp.original_uri})"
end
raise Error::ServerCertificateRevoked, "TLS certificate of '#{host_name}' has been revoked according to '#{resp.uri}'#{redirect} for reason '#{resp.revocation_reason}' at '#{resp.revocation_time}'"
end
def report_uri(original_uri, uri)
if URI(uri) == URI(original_uri)
uri
else
"#{original_uri} (redirected to #{uri})"
end
end
def report_response_body(body)
if body
": #{body}"
else
''
end
end
end
end
end
|
module AntorchaHelper
%w[
step message definition transaction reaction role
organization delivery user castable cancellation identity certificate
reception notifier
].each do |model|
self.class_eval <<-RUBY
def mock_#{model} name = :default
@mock_#{model} ||= {}
@mock_#{model}[name] ||= mock_model(#{model.classify})
end
def mock_#{model.pluralize} name = :default
@mock_#{model.pluralize} ||= {}
@mock_#{model.pluralize}[name] ||= [mock_#{model}(name), mock_#{model}(name)]
end
RUBY
end
%w[message_delivery transaction_cancellation send_notification].each do |job|
self.class_eval <<-RUBY
def stub_new_#{job}_job
Jobs::#{job.classify}Job.stub(:new => mock_#{job}_job)
end
def mock_#{job}_job
@mock_#{job}_job ||= mock(Jobs::#{job.classify}Job)
end
RUBY
end
%w[worker].each do |model|
self.class_eval <<-RUBY
def stub_new_#{model}
#{model.classify}.stub(:new => mock_#{model})
end
def mock_#{model}
@mock_#{model} ||= mock(#{model.classify})
end
def mock_#{model.pluralize}
@mock_#{model.pluralize} ||= [mock_#{model}, mock_#{model}]
end
RUBY
end
def turn_of_devise_and_cancan_because_this_is_specced_in_the_ability_spec
controller.stub \
:authenticate_user! => nil,
:authorize! => nil
end
def have_devise_before_filter
have_before_filter(:authenticate_user!)
end
def sign_in_user type = 'communicator', options = {}
@user = User.create!(:email => "test@example.com", :username => "test", :password => "qwerty", :password_confirmation => "qwerty")
@user.update_attribute :user_type, type.to_s
@user.stub :castables => castables_for(options.delete(:as)) if options[:as]
sign_in @user
stub_current_user_so_that_cancan_uses_the_mock_for_testing_abilities
end
def view_as_user type = 'communicator', option = {}
@user = User.create!(:email => "test@example.com", :username => "test", :password => "qwerty", :password_confirmation => "qwerty")
@user.update_attribute :user_type, type.to_s
@user.stub :castables => castables_for(options.delete(:as)) if options[:as]
stub_current_user_so_that_cancan_uses_the_mock_for_testing_abilities
end
def stub_current_user_so_that_cancan_uses_the_mock_for_testing_abilities
controller.stub :current_user => @user if self.respond_to?(:controller)
@controller.stub :current_user => @user if @controller
end
def castables_for roles
Array(roles).map {|title| mock(Castable, :role => mock(Role, :title => title.to_s))}
end
def act_as who
raise "THIS HELPER IS DEPRECATED"
# session[:user] = [who]
# session[:user] = sign_in_user.id
end
def mock_search
@mock_search ||= mock(Searchlogic::Search, :id => nil)
end
def stub_search mocked_models
mocked_models.first.class.stub :search => mock_search
mock_search.stub :all => mocked_models
end
def stub_new(mocked_model, params = nil)
s = mocked_model.class.stub(:new)
s = s.with(params) if params
s.and_return(mocked_model)
end
def stub_create(mocked_model, params = nil)
s = mocked_model.class.stub(:create)
s = s.with(params) if params
s.and_return(mocked_model)
end
def stub_update(mocked_model, succes = true, params = nil)
s = mocked_model.stub(:update_attributes)
s = s.with(params) if params
s.and_return(succes)
end
def stub_succesful_update(mocked_model, params = nil)
stub_update(mocked_model, true, params)
end
def stub_unsuccesful_update(mocked_model, params = nil)
stub_update(mocked_model, false, params)
end
def stub_new_on(finder, mocked_model, params = nil)
s = finder.stub(:new)
s = s.with(params) if params
s.and_return(mocked_model)
end
def stub_build_on(finder, mocked_model, params = nil)
s = finder.stub(:build)
s = s.with(params) if params
s.and_return(mocked_model)
end
def stub_find_on(finder, mocked_model, params = nil)
s = finder.stub(:find)
s = s.with(params) if params
s.and_return(mocked_model)
end
def stub_all(mocked_model_or_models)
case mocked_model_or_models
when Array:
mocked_model = mocked_model_or_models.first
mocked_models = mocked_model_or_models
when Object:
mocked_model = mocked_model_or_models
mocked_models = [mocked_model]
end
mocked_model.class.stub(:all => mocked_models)
end
def stub_find(mocked_model)
mocked_model.class.stub(:find).with(mocked_model.to_param).and_return(mocked_model)
end
def stub_find_by model, options
scope = options.delete :on
scope ||= model.class
model.stub options unless model.nil?
options.each do |key, value|
scope.stub("find_by_#{key}").with(value).and_return(model)
end
end
def stub_find_by! model, hash
model.stub hash
hash.each do |key, value|
model.class.stub("find_by_#{key}!").with(value).and_return(model)
end
end
def stub_successful_save_for(mocked_model)
mocked_model.stub(:save => true)
end
def stub_unsuccessful_save_for(mocked_model)
mocked_model.stub(:save => false)
end
def stub_authorize!
controller.stub :authorize! => nil
end
def expect_authorize how, what
controller.should_receive(:authorize!).with(how, what)
end
def debug(x)
puts "<div class=\"debug\" style=\"background: #ddd; padding: 1em;\"><pre>"
puts ERB::Util.html_escape(x)
puts "</pre></div>"
end
def debunk(x)
puts "<div class=\"debug\" style=\"background: #ddd; padding: 1em;\"><pre>"
puts ERB::Util.html_escape(x)
puts "</pre></div>"
end
Spec::Matchers.define :have_before_filter do |expected|
match do |actual|
actual.class.before_filters.include?(expected)
end
failure_message_for_should do |actual|
"expected that #{actual} would have a before filter #{expected}"
end
failure_message_for_should_not do |actual|
"expected that #{actual} would not have before filter #{expected}"
end
description do
"have before filter #{expected}"
end
end
def stub_render_partial
template.stub(:render).with(hash_including(:partial => anything())).and_return('')
end
def should_render_partial name
template.should_receive(:render).with(hash_including(:partial => name))
end
def stub_authenticated_soap_service
@controller = SoapController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
User.create! \
:username => 'aap', :email => 'aap@example.com',
:password => 'nootjes', :password_confirmation => 'nootjes'
@warden = mock('warden')
@controller.stub :warden => @warden
@warden.stub :set_user => nil
end
end
|
class Salon < ApplicationRecord
def to_s
"#{nombre}"
end
end
|
require 'date'
require 'yaml'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/file_storage'
require 'google/api_client/auth/installed_app'
require 'active_support/time'
## Read Latcraft global configuration
global_config = YAML.load_file('/etc/latcraft.yml')
## Extract GA stats specific configuration
global_opts = global_config['youtube_analytics'] || {}
# These OAuth 2.0 access scopes allow for read-only access to the authenticated
# user's account for both YouTube Data API resources and YouTube Analytics Data.
YOUTUBE_SCOPES = ['https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/yt-analytics.readonly']
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
YOUTUBE_ANALYTICS_API_SERVICE_NAME = 'youtubeAnalytics'
YOUTUBE_ANALYTICS_API_VERSION = 'v1'
class YTClient
attr_reader :client
def initialize(opts)
application_name = opts['application_name']
application_version = opts['application_version']
authorization_oauth2_json = opts['oauth2_json_authorization']
client_oauth2_json = opts['oauth2_json_client_secret']
@client = Google::APIClient.new(
:application_name => application_name,
:application_version => application_version)
file_storage = Google::APIClient::FileStorage.new(authorization_oauth2_json)
if file_storage.authorization.nil?
client_secrets = Google::APIClient::ClientSecrets.load(client_oauth2_json)
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => YOUTUBE_SCOPES
)
@client.authorization = flow.authorize(file_storage)
else
@client.authorization = file_storage.authorization
end
@client.retries = 5
## Request a token for our service account
@client.authorization.fetch_access_token!
@youtube = discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)
@youtube_analytics = discovered_api(YOUTUBE_ANALYTICS_API_SERVICE_NAME, YOUTUBE_ANALYTICS_API_VERSION)
end
def query_iterate!(parameters, &block)
# Retrieve the channel resource for the authenticated user's channel.
ws_iterate!(
:api_method => @youtube.channels.list,
:parameters => { :mine => true, :part => 'id', }) do |channels_response|
channels_response.items.each do |channel|
# Call the Analytics API to retrieve a report. For a list of available
# reports, see:
# https://developers.google.com/youtube/analytics/v1/channel_reports
parameters ||= {}
parameters['ids'] ||= "channel==#{channel.id}"
ws_iterate!(
{
:api_method => @youtube_analytics.reports.query,
:parameters => parameters
}) { |yt_stats| block.call(yt_stats) }
end
end
end
def fetch_videos_snippets!(videoIds)
meta = {}
ws_iterate!(
:api_method => @youtube.videos.list,
:parameters => {
:part => 'snippet',
:id => videoIds.join(','),
}) do |response|
response.items.inject(meta) {|meta, item| meta[item.id] = item; meta}
end
meta
end
private
def discovered_api(service, version)
api = nil
cache = "#{ENV["TMPDIR"] || "/tmp/"}/.yt-#{service}-#{version}.cache"
## Load cached discovered API, if it exists. This prevents retrieving the
## discovery document on every run, saving a round-trip to the discovery service.
if File.exists? cache
File.open(cache) do |file|
api = Marshal.load(file)
end
else
api = @client.discovered_api(service, version)
File.open(cache, 'w') do |file|
Marshal.dump(api, file)
end
end
api
end
def ws_iterate!(request, &block)
loop do
result = @client.execute!(request)
# At some endpoints Google API fails to propogate errors properly.
# Just to "double-confirm"
#
# Instead we need to check result for HTTP status codes ourselves (manually).
# In our case we've decided to throw exception.
if result.status == 200 then
# Everything is OK
else
# Error, like HTTP 403, permission denied
# Rewrap in Google ClientError
raise Google::APIClient::ClientError.new "YT error #{result.data.error['code']}: #{result.data.error['message']}"
end
block.call(result.data)
break unless result.next_page_token
request = result.next_page
end
end
end
client = YTClient.new(global_opts)
class YoutubeSchedule
def initialize(client)
@client = client
end
end
class YoutubeTop10Watched < YoutubeSchedule
def call(job)
begin
period_start = DateTime.now.prev_month.at_beginning_of_month.strftime("%Y-%m-%d")
period_end = DateTime.now.prev_month.at_end_of_month.strftime("%Y-%m-%d")
dimensions='video'
metrics='estimatedMinutesWatched,views,likes,subscribersGained'
max_results='10'
sort='-estimatedMinutesWatched'
@client.query_iterate!({
'start-date' => period_start,
'end-date' => period_end,
'dimensions' => dimensions,
'metrics' => metrics,
'sort' => sort,
'start-index' => 1,
'max-results' => max_results
}) do |yt_stats|
meta = @client.fetch_videos_snippets!(yt_stats.rows.map {|video| video[0]})
top_videos = yt_stats.rows.map {|video|
{
:label => meta[video[0]].snippet.title,
:value => "#{video[1]} / #{video[2]}",
}
}
send_event('yt_top_10_watched', { items: top_videos })
end
rescue => e
puts e.backtrace
puts "\e[33mFor the Youtube check /etc/latcraft.yml for the credentials and metrics YML.\n\tError: #{e.message}\e[0m"
end
end
end
SCHEDULER.every '30m', YoutubeTop10Watched.new(client)
SCHEDULER.at Time.now, YoutubeTop10Watched.new(client)
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: slack_configurations
#
# created_at :datetime not null
# event_id :integer not null, indexed
# id :bigint(8) not null, primary key
# room_webhook :string not null
# updated_at :datetime not null
#
# Indexes
#
# index_slack_configurations_on_event_id (event_id)
#
# Foreign Keys
#
# fk_rails_9dbb8d5cb7 (event_id => events.id)
#
module Slack
class SlackConfiguration < ApplicationRecord
belongs_to :event
validates :room_webhook, presence: true
end
end
|
require_relative 'ship'
require_relative 'grid'
class Board
attr_reader :ships
def initialize
@ships = []
end
def receive_ship(ship)
ship.place
@ships << ship
ship
end
end
|
class AddApprovedAtAndCompletedAtToTasks < ActiveRecord::Migration
def change
add_column :tasks, :approved_at, :date
add_column :tasks, :completed_at, :date
end
end
|
require 'spec_helper'
require 'data_mapper'
feature 'signing up' do
scenario 'I can sign up as a new user' do
expect { sign_up }.to change(User, :count).by(1)
expect(page).to have_content('Welcome in chitter')
expect(current_path).to eq('/users/welcome')
expect(User.first.email).to eq('alice@example.com')
end
scenario 'I cannot sign up with an existing username' do
sign_up
expect { sign_up }.to_not change(User, :count)
expect(current_path).to eq('/users/failed')
expect(page.status_code).to eq(200)
end
scenario 'I cannot sign up with an existing email' do
sign_up
expect { sign_up }.to_not change(User, :count)
expect(current_path).to eq('/users/failed')
expect(page.status_code).to eq(200)
end
end
def sign_up
visit '/users/new'
expect(page.status_code).to eq(200)
fill_in :email, with: 'alice@example.com'
fill_in :password, with: 'aliali'
fill_in :name, with: 'alice'
fill_in :username, with: 'alice82'
click_button 'Sign up'
end |
#!/usr/bin/env ruby
# encoding: utf-8
# File: tiers_spec.rb
# Created: 25/01/12
#
# (c) Michel Demazure <michel@demazure.com>
module JacintheReports
module Jaccess
module Model
# Instance Methods for J2R::Tiers
module TiersInstanceMethods
## other J2R objects connected to the Tiers
# @return [Array<J2R::Clients>] solutions of client_sage_client_final = self
# @param hash [Hash] filtering condition
def clients(hash = {})
@clients ||= J2R::Client.filter({ client_sage_client_final: id }.merge(hash))
end
# @return [Array<String>] reports on particularities
def particularites
J2R::Particularite.where(particularite_tiers: id).map do |part|
part.format([:type_particularite_nom])
end.flatten.sort.join(', ')
end
# @return [String] reports on infos complements
def infos_complementaires
J2R::VueTiersInfos.filter(vue_tiers_infos_tiers: id).first.vue_tiers_infos_complementaires
end
# @param [Integer] usage id in table usage_adresse
# @return [J2R::VueAdresse] vue_adresse record
def address(usage = 1)
J2R::VueAdresse.filter(vue_adresse_tiers: id,
vue_adresse_etat: 1,
vue_adresse_usage: usage).first
end
## Output formats
# @return [Array<String>] normalized address
def afnor
Patterns.afnor_clean(format(Patterns::AFNOR))
end
# @return [Array<String>] reporting of "rapports"
def rapports
self_id = id
sources = J2R::Rapport.where(rapport_tiers_source: self_id)
targets = J2R::Rapport.where(rapport_tiers_but: self_id)
(sources.all + targets.all).map do |rap|
rap.format(Patterns::RAPPORTS)
end
end
end
end
end
end
|
class PermitDocument < ApplicationRecord
has_one_attached :document
belongs_to :permit_submission
attribute :permit_submission_id, :uuid
end
|
class TagSerializer < ActiveModel::Serializer
attribute :tag_name, key: :'tag-name'
attributes :id
has_many :posts
end
|
class AddUsernameToStudents < ActiveRecord::Migration
def change
add_column :students, :reg_number, :integer
add_index :students, :reg_number, unique: true
end
end
|
users = [
{ 'username': 'ife', password: 'password' },
{ 'username': 'ife1', password: 'password1' },
{ 'username': 'ife2', password: 'password2' },
{ 'username': 'ife3', password: 'password3' },
{ 'username': 'ife4', password: 'password4' },
{ 'username': 'ife5', password: 'password5' },
]
puts "Welcome to the authenticator"
25.times { print "-" }
puts
puts "This program will take input from the user and compare password"
puts "If the password is correct, you will get back the user object"
attempts = 1
while attempts < 4
print "Username: "
username = gets.chomp
print "Password: "
password = gets.chomp
users.each do |user|
if user[:username] == username && user[:password] == password
puts user
else
puts "Credentials were not correct"
end
end
puts "Press n to quit or any other key to continue:"
input = gets.chomp.downcase
break if input == "n"
attempts += 1
end |
class ConvertString
class << self
def get_prefix_code str
index = 0
str.strip.split("").each_with_index do |value, i|
temp = Integer(value) rescue false
if temp.is_a? Numeric
index = i
break
end
end
str.slice(0, index)
end
end
end
|
# ## Schema Information
#
# Table name: `users`
#
# ### Columns
#
# Name | Type | Attributes
# --------------------- | ------------------ | ---------------------------
# **`id`** | `integer` | `not null, primary key`
# **`nickname`** | `string` |
# **`created_at`** | `datetime` | `not null`
# **`updated_at`** | `datetime` | `not null`
# **`image_url`** | `text` |
# **`role`** | `integer` | `default("user"), not null`
# **`socialplus_uid`** | `string` | `not null`
#
# ### Indexes
#
# * `index_users_on_socialplus_uid`:
# * **`socialplus_uid`**
#
FactoryGirl.define do
factory :user do
end
end
|
#!/usr/bin/env ruby
# A few helpful tips about the Rules file:
#
# * The string given to #compile and #route are matching patterns for
# identifiers--not for paths. Therefore, you can’t match on extension.
#
# * The order of rules is important: for each item, only the first matching
# rule is applied.
#
# * Item identifiers start and end with a slash (e.g. “/about/” for the file
# “content/about.html”). To select all children, grandchildren, … of an
# item, use the pattern “/about/*/”; “/about/*” will also select the parent,
# because “*” matches zero or more characters.
require 'compass'
Compass.add_project_configuration '.compass/compass.rb'
sass_options = Compass.sass_engine_options
#
# Compile section
#
compile '/assets/*/' do
nil
end
compile '/stylesheets/*/_*/' do
# Don’t compile partials
nil
end
compile '/stylesheets/*' do
filter :sass, sass_options.merge(:syntax => item[:extension].to_sym)
end
compile '*' do
filter :erb
layout item[:layout] ? item[:layout] : 'default'
end
#
# Route section
#
route '/stylesheets/*/*/' do
nil
end
route '/stylesheets/*/' do
item.identifier.chop + '.css'
end
route '/assets/javascripts/*/' do
'/javascripts/' + File.basename(item.identifier)
end
route '/assets/fonts/*/' do
'/fonts/' + File.basename(item.identifier)
end
route '/assets/images/*/' do
'/images/' + File.basename(item.identifier)
end
route '/' do
'/index.html'
end
route '/*' do
item.identifier.chop + '.html'
end
layout '*', :erb
|
require "logger"
require "singleton"
module Lucie
class Log
class SingletonLogger
include Singleton
FORMAT = "%Y-%m-%d %H:%M:%S"
attr_reader :path
def path= path
@path = path
@logger = ::Logger.new( @path )
@logger.datetime_format = FORMAT
end
def method_missing message, *args
@logger.__send__ message, *args if @logger
end
end
def self.verbose= verbose
SingletonLogger.instance.level = ( verbose ? ::Logger::DEBUG : ::Logger::INFO )
end
def self.method_missing message, *args
SingletonLogger.instance.__send__ message, *args
end
end
end
### Local variables:
### mode: Ruby
### coding: utf-8-unix
### indent-tabs-mode: nil
### End:
|
class AddColumnToUrlBuilders < ActiveRecord::Migration
def change
add_column :url_builders, :profile, :integer
end
end
|
class Sudoku
def initialize(board='')
@grid = gen
if board.length == 81
makeboard(board)
end
@grid
end
def values
@grid
end
def peers(cell)
row = cell.split[0]
col = cell.split[1]
keys = []
@grid.keys.each {
|x| if x.include?(row) or x.include?(col)
keys << x
end
}
@@squares.each {
|x| if x.include?(cell)
keys << x
end
}
end
private
@@rows='ABCDEFGHI'
@@cols='123456789'
@@squares = make_squares
def makeboard(board)
input= board.split(//)
@grid.each {
|k, v| x=0
@grid[k]= input[x]
x+= 1
}
end
def combine(a, b)
r = []
for x in a do
for y in b do
r << (x+y).to_sym
end
end
r
end
def gen
grid = {}
combine(@@rows.split(//), @@cols.split(//)).each {
|x| grid[x] = '0'
}
grid
end
def make_squares
squares = []
@@rows.scan(/.{3}/).each { |row|
@@cols.scan(/.{3}/).each { |col|
squares << combine(row, col)
}
}
squares
end
end
|
module LoginHelpers
def login(userOrUsername, password = FixtureBuilder.password)
username = userOrUsername.is_a?(String) ? userOrUsername : userOrUsername.username
visit(WEBPATH['login_route'])
wait_for_ajax
fill_in 'username', :with => username
fill_in 'password', :with => password
click_button "Login"
wait_for_ajax(20)
wait_until { current_route == '/' || page.all('.has_error').size > 0 || page.all('.errors li').size > 0 }
end
def logout
visit("/#/logout")
end
end
|
class LocationsController < ApplicationController
def index
@stay = Stay.find(params[:stay_id])
@hotel = Hotel.find(params[:hotel_id])
# @locations = Location.all
@locations = Location.all
@locations = Location.where.not(latitude: nil, longitude: nil)
@locations = @locations.select { |l| l.category == "Restaurants"} if params[:filter] == 'restaurant'
@locations = @locations.select { |l| l.category == "Rentals"} if params[:filter] == 'rentals'
@locations = @locations.select { |l| l.category == "Sights"} if params[:filter] == 'Sights'
@hash = convert_to_hash(@locations, @stay, @hotel)
end
def show
@stay = Stay.find(params[:stay_id])
@hotel = Hotel.find(params[:hotel_id])
@location = Location.find(params[:id])
end
private
def convert_to_hash(locations, stay, hotel)
Gmaps4rails.build_markers(locations) do |location, marker|
marker.lat location.latitude
marker.lng location.longitude
marker.infowindow render_to_string(partial: "/locations/mapbox", locals: { stay: stay, hotel: hotel, location: location } )
end
end
end
|
# rubocop:disable Metrics/LineLength
# Cookbook Name:: cuckoo
# Spec:: default
#
require 'spec_helper'
describe 'cuckoo::default' do
context 'When all attributes are default, on an unspecified platform' do
before(:all) do
stub_command("getcap /usr/sbin/tcpdump | grep '/usr/sbin/tcpdump = cap_net_admin,cap_net_raw+eip'").and_return(true)
stub_command("getcap /usr/sbin/tcpdump | grep '/usr/sbin/tcpdump = cap_net_admin,cap_net_raw+eip'").and_return(true)
stub_command('test -L /etc/nginx/sites-enabled/default').and_return(true)
stub_command('/usr/bin/vboxmanage list extpacks | grep 5.0.16').and_return(true)
end
cached(:chef_run) do
runner = ChefSpec::ServerRunner.new
runner.converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
it 'includes cuckoo::host recipe' do
expect(chef_run).to include_recipe('cuckoo::host')
end
end
end
|
class Version < ActiveRecord::Base
attr_accessible :audience_id, :campaign_id, :creative, :creative_approval, :from, :subject_line
validates :creative, :campaign_id, :presence => true
validates :creative_approval, :inclusion => {:in => [true, false]}
belongs_to :campaign
has_many :demographics
has_many :audiences, :through => :demographics
amoeba do
enable
clone [:demographics]
set :creative_approval => 0
end
after_initialize :init
def counts_subtotal
subtotal = 0; demographics.each { |d| subtotal += d.count }; subtotal
end
def audience_list
(demographics.collect { |d| d.audience.code }).join(', ')
end
def all_audiences_have_counts?
demographics.each { |d| return FALSE if d.count == 0 }
end
private
def init
self.creative_approval ||= FALSE
end
end
|
class UserSetting < ActiveRecord::Base
attr_accessible :user, :amount_threshold, :time_zone, :model_params, :model_type
belongs_to :user
validates :amount_threshold, numericality: { greater_than_or_equal_to: 0 }
validates :time_zone, inclusion: { in: ActiveSupport::TimeZone.zones_map.keys }
@@stored_models = {}
def fraud_model
merchant_id = user.id
unless @@stored_models.has_key?(merchant_id)
@@stored_models[merchant_id] = FraudModel.new(merchant_id: merchant_id, class: model_type, model_params_string: model_params)
end
return @@stored_models[merchant_id]
end
def adjustable_model_parameters
begin
klass = model_type.constantize
rescue
klass = FraudModel.default_class
end
klass.adjustable_model_parameters(self.model_params)
end
def set_model_parameters(params)
raise "only the merchant can set the model parameters" unless user.merchant?
begin
array = self.model_type.split("::")
klass = array.reduce(Kernel) {|memo, name| memo.const_get(name)}
rescue
klass = FraudModel.default_class
end
str = klass.apply_params(model_params, params)
self.model_params = str
@@stored_models.delete( user.id )
str
end
end
|
class Category < ActiveRecord::Base
extend FriendlyId
attr_accessible :title, :parent_id
acts_as_nested_set
has_many :bookmarks
friendly_id :title, use: :slugged
end
|
require 'spec_helper'
describe "Rubros" do
before do
@user = Factory(:user)
integration_sign_in(@user)
end
it "link de acceso" do
visit home_path
response.should have_selector("a", :href => rubros_path, :content => "Rubros")
click_link "Rubros"
response.should render_template('rubros/index')
end
end
|
module API_v1
class API < Grape::API
version 'v1', using: :path
format :json
prefix :api
require 'rack/contrib'
use Rack::JSONP
# responses
SUCCESS = 0
FAILURE = 400
helpers do
def response(ret, obj=nil)
if obj.nil?
return {ret: ret}
else
return {obj: obj}
end
end
end
get :test do
response(SUCCESS,
[
{title: 'test1:テキスト', type: 'テキスト', required: false, options: []},
{title: 'test2:ラジオ', type: 'ラジオボタン', required: true, options: [{name:'男性'}, {name:'女性'}, {title:'その他'}]},
{title: 'test3:チェック', type: 'チェックボックス', required: false, options: [{checked:false, name:'吉祥寺'}, {checked:false, name:'三鷹'}]},
{title: 'test4:年月日', type: '年月日', required: false, options: []},
{title: 'test5:名前', type: '名前', required: true, options: []},
{title: 'test6:名前カナ', type: '名前(カナ)', required: false, options: []},
{title: 'test7:電話', type: '電話番号', required: true, options: []},
{title: 'test8:メール', type: 'メールアドレス', required: true, options: []},
{title: 'test9:url', type: 'URL', required: false, options: []},
{title: 'test10:住所', type: '住所', required: false, options: []},
{title: 'test11:都道府県', type: '都道府県', required: true, options: []}
]
)
end
end
end |
require_relative 'term'
module Opener
module KAF
class Document
attr_reader :document
attr_reader :lexicons
attr_accessor :map
def initialize xml
@document = xml
end
def self.from_xml xml
new Nokogiri::XML xml
end
def language
@language ||= @document.at_xpath('KAF').attr 'xml:lang'
end
def terms
@terms ||= collection 'KAF/terms/term', Term
end
def add_linguistic_processor name, version, layer, timestamp: false
header = @document.at('kafHeader') || @document.root.add_child('<kafHeader/>').first
procs = header.css('linguisticProcessors').find{ |l| l.attr(:layer) == layer }
procs ||= header.add_child("<linguisticProcessors layer='#{layer}'/>").first
lp = procs.add_child('<lp/>')
lp.attr(
timestamp: if timestamp then Time.now.iso8601 else '*' end,
version: version,
name: name,
)
lp
end
def to_xml
@document.to_xml indent: 2
end
protected
def collection query, wrapper
@document.xpath(query).map{ |node| wrapper.new self, node }
end
end
end
end
|
class FeedbacksController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy, :search, :student_find, :find]
before_filter :correct_user, only: :destroy # NEW LINE
def new
@feedback = Feedback.new
@cs = CourseSubject.where(course_id: current_user.course.id)
@subjects = []
@cs.each {|s| @subjects << s.subject }
end
def search
subject = Subject.find params[:subject]
@feedbacks = Feedback.where(subject_id: subject.id, user_id: current_user.id)
@title = subject.name
end
def search_student
user = User.find params[:user_id]
@feedbacks = Feedback.where(user_id: user.id)
@title = user.name
render 'search'
end
def student_find
@users = User.all
end
def find
@subjects = Subject.all
end
def create
@feedback = current_user.feedbacks.new(feedback_params)
puts @current_user.course_id
if @feedback.save
flash[:success] = "Feedback created!"
redirect_to root_url
else
@feed_items = []
render 'feedbacks/new'
end
end
# UPDATED IMPLEMENTATION
def destroy
@feedback.destroy
redirect_to root_url
end
# NEW PRIVATE METHOD
private
def correct_user
@feedback = current_user.feedbacks.find_by_id(params[:id])
redirect_to root_url if @feedback.nil?
end
def feedback_params
params.require(:feedback).permit(:user_id, :subject_id, :strengths, :weaknesses, :recommendations, :rating)
end
end |
module Noodall
class Field
include MongoMapper::EmbeddedDocument
plugin MongoMapper::Plugins::MultiParameterAttributes
key :_type, String, :required => true
key :name, String, :required => true
key :label, String
key :default, String
key :required, Boolean, :default => false
embedded_in :form
before_save :default_label
def default_label
self.label = self.name if self.label.blank?
end
def underscored_name
name.parameterize.gsub('-','_').to_s
end
def default_class(response)
'default-value' if response.send(underscored_name.to_sym) == default
end
def mandatory?
Form::MANDATORY_FIELDS.include?(self.name)
end
end
end
|
# -*- coding: utf-8 -*-
require "s7n/s7ncli/command"
module S7n
class S7nCli
# 機密情報をインポートするコマンドを表現する。
class EntryCollectionImportCommand < Command
command("import",
["entry_collection:import",
"entry_collection:read",
"entry_collection:load",
"read",
"load"],
_("Import the entry colleciton from file."),
_("usage: import [PATH] [OPTIONS]"))
def initialize(*args)
super
@config["type"] = "gpass"
@config["path"] = "~/.gpass/passwords.gps"
@options.push(StringOption.new("type", _("type")),
StringOption.new("path", _("path")))
end
# コマンドを実行する。
def run(argv)
option_parser.parse!(argv)
if argv.length > 0
config["path"] = argv.shift
end
case config["type"]
when "gpass"
path = File.expand_path(config["path"])
if !File.file?(path)
raise NotExist.new(path)
end
puts(_("Import the entry collection in the GPass file: %s") % path)
gpass_file = GPassFile.new
begin
msg = _("Enter the master passphrase for GPass(^D is cancel): ")
passphrase = S7nCli.input_string_without_echo(msg)
if passphrase
ec = gpass_file.read(passphrase, path)
# TODO: UNDO スタックにタグの追加と機密情報の追加の操作を積む。
world.entry_collection.merge(ec)
world.changed = true
puts(_("Imported %d entries.") % ec.entries.length)
else
canceled
end
rescue InvalidPassphrase => e
puts(e.message)
retry
end
else
raise ArgumentError, _("not supported type: %s") % config["type"]
end
return true
end
end
end
end
|
require 'sys-uname'
require 'util/miq-system'
if Sys::Platform::IMPL == :linux && MiqSystem.arch == :x86_64
require 'linux_block_device'
require 'disk/modules/RawBlockIO'
end
module MiqLargeFile
def self.open(file_name, flags)
if Sys::Platform::IMPL == :linux && MiqLargeFileStat.new(file_name).blockdev?
RawBlockIO.new(file_name, flags)
else
MiqLargeFileOther.new(file_name, flags)
end
end
def self.size(file_name)
f = open(file_name, "r")
s = f.size
f.close
s
end
# For camcorder interposition.
class MiqLargeFileStat
def initialize(file_name)
@file_name = file_name
end
def blockdev?
File.stat(@file_name).blockdev?
end
end
class MiqLargeFileOther < File
def write(buf, _len)
super(buf)
end
def size
return stat.size unless stat.blockdev?
LinuxBlockDevice.size(fileno)
end
end
end
|
module RelationsExtension::RelationsTags
include Radiant::Taggable
desc %{
}
tag 'related_pages' do |tag|
tag.expand
end
tag 'related_pages:each' do |tag|
related_pages = tag.locals.page.related_pages
related_pages.inject('') do |result, related_page|
tag.locals.page = related_page
result + tag.expand
end
end
end |
require 'rails_helper'
describe "Registrations" do
let!(:user) { FactoryGirl.create(:user) }
it "signs up a user" do
visit '/sign_up'
within("form#new_user") do
fill_in 'Email', :with => 'abc123@email.com'
fill_in 'Senha', :with => '123456'
fill_in 'Confirme sua senha', :with => '123456'
end
click_button 'Cadastrar'
expect(page).to have_success_message 'Success'
end
it "does not sign up a user with same one's email" do
visit '/sign_up'
within("form#new_user") do
fill_in 'Email', :with => user.email
fill_in 'Senha', :with => '1234567'
fill_in 'Confirme sua senha', :with => '123456'
end
click_button 'Cadastrar'
expect(page).to have_failure_message 'Email já está em uso'
end
end
|
require 'rails_helper'
RSpec.describe "events/show.html.erb", type: :view do
it "displays the event venue" do
event = Event.new
event.publish = false
event.name = 'Việt Nam Thử Thách 2018'
event.starts_at = DateTime.parse('Fri, 20 Sep 2016 7:00 AM+0700')
event.ends_at = DateTime.parse('Sun, 28 Sep 2016 3:00 PM+0700')
event.venue = Venue.new(name: "RMIT")
event.category = Category.new(name: 'category')
event.user = User.find_by(email: 'user1@gmail.com')
event.hero_image_url = 'https://az810747.vo.msecnd.net/eventcover/2015/10/25/C6A1A5.jpg?w=1040&maxheight=400&mode=crop&anchor=topcenter'
event.extended_html_description = <<-DESC
<p style="text-align:center"><span style="font-size:20px">VIỆT NAM THỬ THÁCH CHIẾN THẮNG 2016</span></p>
<p style="text-align:center"><span style="font-size:20px">Giải đua xe đạp địa hình 11-13/03/2016</span></p>
<p style="text-align:center"><span style="font-size:16px"><span style="font-family:arial,helvetica,sans-serif">Việt Nam Th</span>ử Thách Chiến Thắng là giải đua xe đạp địa hình được tổ chức như một sự tri ân, và cũng nhằm thỏa mãn lòng đam mẹ của những người yêu xe đạp địa hình nói chung, cũng như cho những ai đóng góp vào môn thể thao đua xe đạp tại thành phố Hồ Chí Minh. Cuộc đua diễn ra ở thành phố cao nguyên hùng vĩ Đà Lạt, với độ cao 1,500m (4,900ft) so với mặt nước biển. Đến với đường đua này ngoài việc tận hưởng cảnh quan nơi đây, bạn còn có cơ hội biết thêm về nền văn hóa của thành phố này. </span></p>
<p style="text-align:center"><span style="font-size:16px">Hãy cùng với hơn 350 tay đua trải nghiệm 04 lộ trình đua tuyệt vời diễn ra trong 03 ngày tại Đà Lạt và bạn sẽ có những kỉ niệm không bao giờ quên!</span></p>
<p style="text-align:center"><span style="font-size:16px">Để biết thêm thông tin chi tiết và tạo thêm hứng khởi cho cuộc đua 2016, vui lòng ghé thăm trang web</span></p>
<p style="text-align:center"><span style="font-size:16px"><strong><span style="background-color:transparent; color:rgb(0, 0, 0)">www.vietnamvictorychallenge.com. </span></strong></span></p>
DESC
event.save! validate: false
assign(:event, event)
render
expect(rendered).to include("Việt Nam Thử Thách 2018")
end
end
|
class Entry
attr_reader :first_name, :last_name, :phone_number
def initialize(data)
@first_name = data[:first_name]
@last_name = data[:last_name]
@phone_number = data[:phone_number]
end
def name
"#{@first_name} #{@last_name}"
end
end
|
FactoryBot.define do
factory :ingredients_prescription do
association :prescription
association :ingredient
percentage 5.0
end
end
|
require "linear_hash"
RSpec.describe LinearHash do
describe "without grow" do
it "get none exist key" do
hash = LinearHash::Hash.new
expect(hash.get(1024)).to eq(nil)
end
it "put and get" do
hash = LinearHash::Hash.new
hash.put(1, 10)
expect(hash.get(1)).to eq(10)
end
it "for same position" do
hash = LinearHash::Hash.new
hash.put(1, 10)
expect(hash.get(5)).to eq(nil)
end
end
describe "overflow without grow" do
it "put and get" do
hash = LinearHash::Hash.new
hash.put(1, 10)
hash.put(5, 50)
expect(hash.get(1)).to eq(10)
expect(hash.get(5)).to eq(50)
end
end
describe "handle grow" do
it "grow once" do
hash = LinearHash::Hash.new
hash.put(1, 10)
hash.put(5, 50) # will split one
expect(hash.get(1)).to eq(10)
expect(hash.get(5)).to eq(50)
hash.maybe_grow # grow should be idempotent
expect(hash.get(1)).to eq(10)
expect(hash.get(5)).to eq(50)
end
it "grow part of level" do
hash = LinearHash::Hash.new
hash.put(1, 10) # 1: 1
hash.put(5, 50) # 5: 101
expect(hash.get(1)).to eq(10)
expect(hash.get(5)).to eq(50)
hash.put(9, 90) # 9: 1001
expect(hash.get(9)).to eq(90)
expect(hash.get(9)).to eq(90)
expect(hash.get(1)).to eq(10)
expect(hash.get(5)).to eq(50)
end
end
describe "integration test" do
it "test" do
keys = [5, 1, 3, 20, 16, 4, 13, 17, 8, 15, 11, 12, 7, 14, 19]
# puts "for random keys #{keys}"
hash = LinearHash::Hash.new
keys.each do |key|
hash.put(key, key * 10)
expect(hash.get(key)).to eq(key * 10)
end
keys.each do |key|
expect(hash.get(key)).to eq(key * 10)
end
end
it "100 random keys" do
keys = (1..100).to_a.shuffle
hash = LinearHash::Hash.new
keys.each do |key|
hash.put(key, key * 10)
expect(hash.get(key)).to eq(key * 10)
end
keys.each do |key|
expect(hash.get(key)).to eq(key * 10)
end
end
it "100000 random keys" do
keys = []
100000.times do
keys << rand(1000000)
end
keys.uniq! # do not support duplicated keys
hash = LinearHash::Hash.new
keys.each do |key|
hash.put(key, key * 10)
expect(hash.get(key)).to eq(key * 10)
end
keys.each do |key|
expect(hash.get(key)).to eq(key * 10)
end
table = hash.instance_variable_get("@table")
max_overflow_segment_size = 0
table.each do |segment|
overflow_segment_size = segment.overflow_segment.size
max_overflow_segment_size = [max_overflow_segment_size, overflow_segment_size].max
end
puts "max_overflow_segment_size is #{max_overflow_segment_size}"
end
end
end
|
class Api::V1::CommentsController < ActionController::Base
before_action :authenticate_user!, only: %i[create update destroy]
before_action :set_comment, only: %i[update destroy]
def index
request_params = request.path.split('/')
comments = Comments::IndexService.new(request_params, current_user, page_number).perform
return unless comments.success?
#response.headers['pages_count'] = comments.data.total_pages.to_s
render json: comments.data, each_serializer: Comment::CommentsSerializer
end
def create
request_params = request.path.split('/')
comment = Comments::CreateService.new(request_params, comment_params, current_user).perform
if comment.success?
render json: comment.data, serializer: Comment::CommentsSerializer
else
render_json_errors(comment.data)
end
end
def update
comment = Comments::UpdateService.new(@comment, comment_params, current_user).perform
if comment.success?
render json: comment.data
else
render_json_errors(comment.data)
end
end
def destroy
@comment.destroy if current_user.id != @comment.user_id
render json: 'ok'
end
private
def set_comment
@comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:title, :body)
end
end |
class UpdateColumnsTypeToProductsAttributesFromStringToText < ActiveRecord::Migration
def change
change_column :products, :category, :text
change_column :products, :textures, :text
change_column :products, :image, :text
change_column :products, :price, :text
change_column :products, :shape, :text
end
end
|
class Team < ApplicationRecord
has_many :dancers, foreign_key: :team_id, class_name: "User"
has_many :donations_received, through: :dancers, foreign_key: :dancer_id
validates :name, presence: true, uniqueness: true
validates :goal, presence: true, numericality: { greater_than: 0 }
def team_total
d_amounts = donations_received.map{|d| d.amount}
d_amounts.inject(0){|sum,x| sum + x }
end
end
|
def valid_number?(number_string)
number_string.to_i.to_s == number_string
end
def quit?(choice)
choice == 'q' || choice == 'Q'
end
def enough_lines?(number_of_lines)
number_of_lines >= 3
end
def print_lines(number_of_lines)
number_of_lines.times do
puts "Launch School is the best!"
end
end
loop do
puts '>> How many output lines do you want? Enter a number >= 3: (q to quit)'
choice = gets.chomp.to_s
if valid_number?(choice)
choice = choice.to_i
if enough_lines?(choice)
print_lines(choice)
else
puts ">> That's not enough lines."
end
elsif quit?(choice)
break
end
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
# ▶︎ Database Authenticatable
#データベースに保存されたパスワードが正しいかどうかの検証とを行ってくれます。また暗号化も同時に行うためセキュリティ面でも安心できます。
# ▶︎ Omniauthable
#twitter, facebookなど現代のwebサービスで必須なSNS認証を行うためのモジュールです。SNS認証をする場合このほかにもgemを追加する必要が出てくるので注意が必要です。
# ▶︎ Confirmable
# 登録後メールを送り、そのメールのURLをクリックすると本登録が完了するといったような仕組みを作ることが可能になります。
# ▶︎ Recoverable
# パスワードをリセットするためのモジュールです。
# ▶︎ Registerable
# 基本的にUser登録、編集、削除機能を作成することができます。
# ▶︎ Rememberable
# 20日間ログインしたままにすると言った、永続ログイン機能を作成することができます。ログイン画面の下の方にチェックボックスがあって、それをチェックすると永続ログインが有効化するといったような仕組みを作ることができます。
# ▶︎ Trackable
# サインイン回数、サインイン時間など、ユーザーの分析に必要なデータを保存しておくことができます。サービスが成長するにはユーザーの分析が不可欠なので、有用な機能ですね。
# ▶︎ Timeoutable
# 一定期間活動していないアカウントのログインを破棄する機能です。ログインしたままだとログイン情報がオンライン上に残ってしまい悪用されてしまう可能性もあります。セキュリティ面での向上を期待できる機能です。
# ▶︎ Validatable
# emailのフォーマットやパスワードの長さなど、一般的なバリデーションを追加してくれるモジュールです。
# ▶︎ Lockable
# ログインに何度も失敗すると、アカウントをロックすることができる機能です。こちらの機能もセキュリティ面で向上が期待できますね。
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :tweets
has_many :comments
end
|
require_relative '../proofs_init'
title 'Event Naming'
module EventNamingProofs
module Builder
extend self
module Other
class SomeClass
end
end
def sut
::Events::EventNaming
end
def event
Other::SomeClass.new
end
end
end
def build
EventNamingProofs::Builder
end
proof 'Event instances can be converted to an event name' do
sut = build.sut
event = build.event
result = sut.create_event_name_from_event(event)
result.prove { eql? :some_class }
end
proof 'Event names can be converted to an event handler name' do
sut = build.sut
event = build.event
result = sut.create_handler_name("some_class")
result.prove { eql? :handle_some_class }
end
proof 'Event instances can be converted to an event handler name' do
sut = build.sut
event = build.event
result = sut.create_handler_name(event)
result.prove { eql? :handle_some_class }
end
|
#! /usr/bin/env ruby
APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__)
require APP_PATH
begin
Rails.application.require_environment!
rescue ActiveRecord::AdapterNotSpecified => e
$stderr.puts "No such Rails environment: \"#{Rails.env}\"."
exit 1
end
begin
require 'agi_server'
server_instance = AGIServer::server()
rescue SignalException => e
case e.signo
when 1
$stderr.puts "Signal 1 caught, exiting"
when 2
$stderr.puts "Interrupt signal caught, exiting"
when 15
$stderr.puts "Exit signal caught, exiting"
else
$stderr.print "#{e.class.to_s}"
$stderr.print " (Signal #{e.signo.to_s})" if e.respond_to?(:signo) && e.signo
end
$stderr.puts ""
exit (e.signo + 128)
end
exit 0
|
require File.dirname(__FILE__) + "/../spec_helper"
describe Preflight::Rules::MinBleed do
it "pass files with an image that doesn't require bleed" do
filename = pdf_spec_file("image_no_bleed_5mm_gap")
# objects within 1mm of the TrimBox must have at least 4mm bleed
rule = Preflight::Rules::MinBleed.new(1, 4, :mm)
PDF::Reader.open(filename) do |reader|
reader.page(1).walk(rule)
rule.issues.should be_empty
end
end
it "pass files with an image that has 5mm bleed" do
filename = pdf_spec_file("image_5mm_bleed")
# objects within 1mm of the TrimBox must have at least 4mm bleed
rule = Preflight::Rules::MinBleed.new(1, 4, :mm)
PDF::Reader.open(filename) do |reader|
reader.page(1).walk(rule)
rule.issues.should be_empty
end
end
it "fail files with an image that touches the TrimBox but doesn't bleed" do
filename = pdf_spec_file("image_no_bleed")
rule = Preflight::Rules::MinBleed.new(1, 4, :mm)
PDF::Reader.open(filename) do |reader|
reader.page(1).walk(rule)
rule.issues.should_not be_empty
end
end
it "pass files with a rectangle that doesn't require bleed" do
filename = pdf_spec_file("rectangle_no_bleed_5mm_gap")
# objects within 1mm of the TrimBox must have at least 4mm bleed
rule = Preflight::Rules::MinBleed.new(1, 4, :mm)
PDF::Reader.open(filename) do |reader|
reader.page(1).walk(rule)
rule.issues.should be_empty
end
end
it "pass files with a rectangle that has 5mm bleed" do
filename = pdf_spec_file("rectangle_5mm_bleed")
# objects within 1mm of the TrimBox must have at least 4mm bleed
rule = Preflight::Rules::MinBleed.new(1, 4, :mm)
PDF::Reader.open(filename) do |reader|
reader.page(1).walk(rule)
rule.issues.should be_empty
end
end
it "fail files with a rectangle that touches the TrimBox but doesn't bleed" do
filename = pdf_spec_file("rectangle_no_bleed")
rule = Preflight::Rules::MinBleed.new(1, 4, :mm)
PDF::Reader.open(filename) do |reader|
reader.page(1).walk(rule)
rule.issues.should_not be_empty
end
end
end
|
class Movie < ApplicationRecord
# t.string "title"
# t.integer "user_id"
# t.string "description"
# t.datetime "created_at", null: false
# t.datetime "updated_at", null: false
belongs_to :user
validates :title, :description, presence: true
has_many :movie_reactions, :dependent => :delete_all
paginates_per 10
def likes
self.movie_reactions.where(liked: true).count || 0
end
def dislikes
self.movie_reactions.where(liked: false).count || 0
end
end
|
class AddHowTheyFoundUsToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :how_they_found_us, :string
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
editable_keys = [:cpf, :first_name, :last_name, :birthday, :address, :phone_number, :photo]
devise_parameter_sanitizer.permit(:sign_up, keys: [:display_name])
devise_parameter_sanitizer.permit(:account_update, keys: editable_keys)
end
end
|
require 'json'
class Datastore::Client::CLI
def self.get(uuid, scope, host)
return "You must specify a UUID! Use --help get for more information." unless uuid
client = Datastore::Client.new(host)
data = client.get(scope, uuid)
return "No data stored for #{scope}/#{uuid}" unless data
JSON.pretty_generate(data)
end
def self.set(uuid, json, scope, host)
data = JSON.parse(json)
return "You must specify a UUID! Use --help get for more information." unless uuid
client = Datastore::Client.new(host)
client.set(scope, uuid, data)
"Saved:\n" + JSON.pretty_generate(data)
end
def self.create(json, scope, host)
data = JSON.parse(json)
client = Datastore::Client.new(host)
uuid = client.create(scope, data)
"Created:\nUUID: #{uuid}\nData:\n" + JSON.pretty_generate(data)
end
end
|
class Organization < ApplicationRecord
has_many :People
has_many :CustomerJobs
accepts_nested_attributes_for :people
has_many :customers, through Organization
has_many :suppliers, through Organization
validates :name, presence: true
end
|
# mixins
puts "\n***********************************\nmixins"
module ContactInfo
attr_accessor :first_name, :last_name, :city, :zip_code
def full_name
return @first_name + ' ' + @last_name
end
def address
result = @city
result = "#{@zip_code} #{result}" if @zip_code
return result
end
end
class Person
include ContactInfo
end
class Teacher < Person
attr_accessor :lesson_plans
end
class Student
include ContactInfo
attr_accessor :books, :grades
end
teacher = Teacher.new
teacher.first_name = 'John'
teacher.last_name = 'Doe'
puts teacher.full_name
student = Student.new
student.first_name = 'Little'
student.last_name = 'Jimmy'
puts student.full_name
|
require 'active_resource'
require 'thor'
require 'aeolus_cli/model/base'
require 'aeolus_cli/model/provider_type'
class AeolusCli::CommonCli < Thor
class_option :conductor_url, :type => :string
class_option :username, :type => :string
class_option :password, :type => :string
def initialize(*args)
super
load_aeolus_config(options)
end
# abstract-y methods
desc "list", "List all"
def list(*args)
self.shell.say "Implement me."
end
desc "add", "Add one"
def add(*args)
self.shell.say "Implement me."
end
protected
class << self
def banner(task, namespace = nil, subcommand = false)
"#{basename} #{task.formatted_usage(self, false, true)}"
# Above line Overrides the line from Thor, below, so the printed usage
# line is correct, e.g. for "aeolus provider help list" we get
# Usage:
# aeolus provider list
# instead of
# Usage:
# aeolus list
#"#{basename} #{task.formatted_usage(self, $thor_runner, subcommand)}"
end
end
def load_aeolus_config(options)
# set logging defaults
ActiveResource::Base.logger = Logger.new(STDOUT)
ActiveResource::Base.logger.level = Logger::WARN
# locate the config file if one exists
config_fname = nil
if ENV.has_key?("AEOLUS_CLI_CONF")
config_fname = ENV["AEOLUS_CLI_CONF"]
if !is_file?(config_fname)
raise AeolusCli::ConfigError.new(
"environment variable AEOLUS_CLI_CONF with value "+
"'#{ ENV['AEOLUS_CLI_CONF']}' does not point to an existing file")
end
else
["~/.aeolus-cli","/etc/aeolus-cli"].each do |fname|
if is_file?(fname)
config_fname = fname
break
end
end
end
# load the config file if we have one
if config_fname != nil
@config = YAML::load(File.open(File.expand_path(config_fname)))
if @config.has_key?(:conductor)
[:url, :password, :username].each do |key|
raise AeolusCli::ConfigError.new \
("Error in configuration file: #{key} is missing"
) unless @config[:conductor].has_key?(key)
end
AeolusCli::Model::Base.site = @config[:conductor][:url]
AeolusCli::Model::Base.user = @config[:conductor][:username]
AeolusCli::Model::Base.password = @config[:conductor][:password]
else
raise AeolusCli::ConfigError.new("Error in configuration file")
end
if @config.has_key?(:logging)
if @config[:logging].has_key?(:logfile)
if @config[:logging][:logfile].upcase == "STDOUT"
ActiveResource::Base.logger = Logger.new(STDOUT)
elsif @config[:logging][:logfile].upcase == "STDERR"
ActiveResource::Base.logger = Logger.new(STDERR)
else
ActiveResource::Base.logger =
Logger.new(@config[:logging][:logfile])
end
end
if @config[:logging].has_key?(:level)
log_level = @config[:logging][:level]
if ! ['DEBUG','WARN','INFO','ERROR','FATAL'].include?(log_level)
raise AeolusCli::ConfigError.new \
("log level specified in configuration #{log_level}, is not valid."+
". shoud be one of DEBUG, WARN, INFO, ERROR or FATAL")
else
ActiveResource::Base.logger.level = eval("Logger::#{log_level}")
end
end
end
end
# allow overrides from command line
if options[:conductor_url]
AeolusCli::Model::Base.site = options[:conductor_url]
end
if options[:username]
AeolusCli::Model::Base.user = options[:username]
end
if options[:password]
AeolusCli::Model::Base.password = options[:password]
end
end
# Given a hash of attribute key name to pretty name and an active
# resource collection, print the output.
def print_table( keys_to_pretty_names, ares_collection)
t = Array.new
# Add the first row, the column headings
t.push keys_to_pretty_names.values
# Add the data
ares_collection.each do |ares|
row = Array.new
keys_to_pretty_names.keys.each do |key|
row.push ares.attributes[key].to_s
end
t.push row
end
# use Thor's shell.print_table()
self.shell.print_table(t)
end
def provider_type(type_s)
# we need to hit the API to get the map of provider_type.name =>
# provider_type.id, so make sure we only do this once.
@provider_type_hash ||= provider_type_hash
@provider_type_hash[type_s]
end
def provider_type_hash
deltacloud_driver_to_provider_type = Hash.new
provider_types = AeolusCli::Model::ProviderType.all
if provider_types.size == 0
raise "Retrieved zero provider types from Conductor"
end
provider_types.each do |pt|
deltacloud_driver_to_provider_type[pt.deltacloud_driver] = pt
end
deltacloud_driver_to_provider_type
end
# TODO: Consider ripping all this file-related stuff into a module or
# class for better encapsulation and testability
def is_file?(path)
full_path = File.expand_path(path)
if File.exist?(full_path) && !File.directory?(full_path)
return true
end
false
end
end
|
module WillToggle
module ViewHelpers
@@toggle_index ||= 0
def will_toggle(options = {})
@@toggle_index += 1
attribute = nil
generate_html(attribute, options).html_safe
end
def will_toggle_radio(options = {})
@@toggle_index += 1
generate_radio_html(options).html_safe
end
def generate_html(attribute, options = {})
<<-HTML
<div class='will-toggle-wrapper'>
<div class='field check-box'>
#{ get_check_box(attribute, options) }
</div>
<div class='will-toggle-content' id="will-toggle-#{ @@toggle_index }" style="display: #{ visibility(options[:checked]) };">
#{ get_partial(options) }
</div>
</div>
HTML
end
def generate_radio_html(options = {})
<<-HTML
<div class='will-toggle-wrapper'>
<div class='field radio-button'>
#{ get_radio_button(options) }
</div>
<div class='will-toggle-content' id="will-toggle-#{ @@toggle_index }" style="display: #{ visibility(options[:checked]) };">
#{ get_partial(options) }
</div>
</div>
HTML
end
def visibility(checked = false)
checked ? :block : :none
end
def get_check_box(attribute, options = {})
html = ''
if attribute
html << options[:form].check_box(attribute, onChange: js_call(options), class: 'check-box will-toggle-check-box')
html << options[:form].label(attribute, options[:label])
else
html << check_box_tag(nil, nil, options[:checked], onChange: js_call(options), class: 'check-box will-toggle-check-box')
html << label_tag(nil, options[:label], class: 'will-toggle-label')
end
html
end
def get_radio_button(options = {})
html = ''
html << radio_button_tag(options[:name], nil, options[:checked], onChange: js_radio_call(options[:name], options), class: 'check-box will-toggle-radio-button', value: options[:value])
html << label_tag(nil, options[:label], class: 'will-toggle-label')
html
end
def get_partial(options = {})
render partial: options[:partial],
locals: options[:locals]
end
def js_call(options)
"willToggle.toggleNext(\'#will-toggle-#{ @@toggle_index }\'#{ js_options(options) });".html_safe
end
def js_radio_call(name, options)
"willToggle.toggleRadios(name, \'#will-toggle-#{ @@toggle_index }\'#{ js_options(options) });".html_safe
end
def js_options(options)
" , #{ options[:clear_data] }" if options[:clear_data]
end
end
end |
class Pius < Formula
homepage "http://www.phildev.net/pius/"
url "https://downloads.sourceforge.net/project/pgpius/pius/2.0.11/pius-2.0.11.tar.bz2"
sha1 "0c9b74f271bf195d8636d8406fbb56cc024195ad"
depends_on :gpg
def install
# Replace hardcoded gpg path: https://sourceforge.net/p/pgpius/bugs/12/
inreplace "pius", "/usr/bin/gpg", HOMEBREW_PREFIX/"bin/gpg"
bin.install "pius"
bin.install "pius-keyring-mgr"
bin.install "pius-party-worksheet"
end
def caveats; <<-EOS.undent
The gpg path is hardcoded in pius. You can specific your own gpg path
by adding follow line into ~/.pius file:
gpg-path=/path/to/gpg
EOS
end
test do
system "#{bin}/pius", "-T"
end
end
|
require 'pry'
# Build a class EmailParser that accepts a string of unformatted
# emails. The parse method on the class should separate them into
# unique email addresses. The delimiters to support are commas (',')
# or whitespace (' ').
class EmailParser
attr_accessor :emails
@@parse = []
def initialize(emails) #emails is a string of emails
@emails = emails #writer method
end
def parse
@emails.split.map do |email| #take the string of emails, splits them into substrings at whitespace points, and throws them into an array; loops through that array
email.split(',') #takes each email element in the array and further splits it at commas
end.flatten.uniq #flattens array and only shows unique elements
end
end |
# Binary Search Tree
class Node
include Enumerable
# module that gives you the ability to directly compare the data
# values of node using <, <=, ==, >, >=, and between? instance methods.
include Comparable
attr_accessor :data, :left, :right
def initialize(data)
@data = data
end
def each(&block)
left.each(&block) if left
block.call(self)
right.each(&block) if right
end
def values
self.collect { |node| node.data }
end
def include?(data)
values.include?(data)
end
def count_nodes_between(a, b)
values.select { |data| data.between?(a, b) }.size
end
# Ruby can compare two Nodes and tell which one is greater.
# This allows it to implement sort, min and max methods.
def <=>(other_node)
data <=> other_node.data
end
def insert(data)
if data <= self.data
do_insert('left', data)
else
do_insert('right', data)
end
end
def do_insert(side, data)
if send(side)
send(side).insert(data)
else
send("#{side}=", Node.new(data))
end
end
# def find_node(node, data)
# if self.data == data
# return self
# elsif data < self.data
# find_node(node.left, data)
# else
# find_node(node.right, data)
# end
# end
end
root = Node.new(7)
root.left = Node.new(3)
root.right = Node.new(12)
root.insert 9
root.insert 2
root.insert 8
puts root.values
puts root.include? 10
puts root.include? 2
puts root.include? 8
puts root.include? 12
puts root.include? 6
# Enumerable provides some of these methods
=begin
puts "SUM"
puts root.inject(0) { |memo, val| memo += val.data }
puts "MAX"
puts root.max.data
puts "SORT"
puts root.sort.map(&:data)
Comparable provides methods like <, <=, >, ==, between? to compare data values of Nodes
root = Node.new(7)
root.left = Node.new(3)
root.right = Node.new(12)
root.between?(root.left, root.right) # true
root.left < root.right # true
=end |
Rails.application.routes.draw do
resources :queries, only: [] do
member do
get 'first'
get 'all'
end
end
end
|
require 'spec_helper'
describe 'fork_collab' do
include CommandHelpers
context 'through CLI' do
it "requires the repository be specified" do
expect {
teachers_pet(:fork_collab)
}.to raise_error(Thor::RequiredArgumentMissingError, /--repository/)
end
it "passes the options to the action" do
expect_to_be_run_with(TeachersPet::Actions::ForkCollab,
'api' => 'https://api.github.com/',
'dry_run' => false,
'password' => 'abc123',
'repository' => 'testorg/testrepo',
'username' => ENV['USER'],
'web' => 'https://www.github.com/'
)
teachers_pet(:fork_collab, repository: 'testorg/testrepo', password: 'abc123')
end
it "succeeds for basic auth" do
request_stubs = []
request_stubs << stub_get_json('https://testteacher:abc123@api.github.com/repos/testorg/testrepo/forks?per_page=100', [
{
owner: {
login: 'teststudent',
type: 'User'
}
}
])
request_stubs << stub_request(:put, 'https://testteacher:abc123@api.github.com/repos/testorg/testrepo/collaborators/teststudent')
teachers_pet(:fork_collab,
repository: 'testorg/testrepo',
username: 'testteacher',
password: 'abc123'
)
request_stubs.each do |request_stub|
expect(request_stub).to have_been_requested.once
end
end
it "succeeds for OAuth" do
request_stubs = []
request_stubs << stub_get_json('https://api.github.com/repos/testorg/testrepo/forks?per_page=100', [
{
owner: {
login: 'teststudent',
type: 'User'
}
}
]).with(headers: {'Authorization' => 'token tokentokentoken'})
request_stubs << stub_request(:put, 'https://api.github.com/repos/testorg/testrepo/collaborators/teststudent').
with(headers: {'Authorization' => 'token tokentokentoken'})
teachers_pet(:fork_collab,
repository: 'testorg/testrepo',
token: 'tokentokentoken'
)
request_stubs.each do |request_stub|
expect(request_stub).to have_been_requested.once
end
end
it "prints the users on a dry run" do
request_stub = stub_get_json('https://testteacher:abc123@api.github.com/repos/testorg/testrepo/forks?per_page=100', [
{
owner: {
login: 'teststudent',
type: 'User'
}
}
])
output = capture(:stdout) do
teachers_pet(:fork_collab,
repository: 'testorg/testrepo',
username: 'testteacher',
password: 'abc123',
dry_run: true
)
end
expect(output).to include('teststudent')
expect(request_stub).to have_been_requested.once
end
end
end
|
module PryByebug
# Wrapper for Byebug.breakpoints that respects our Processor and has better
# failure behavior. Acts as an Enumerable.
#
module Breakpoints
extend Enumerable
extend self
class FileBreakpoint < SimpleDelegator
def source_code
Pry::Code.from_file(source).around(pos, 3).with_marker(pos)
end
def to_s
"#{source} @ #{pos}"
end
end
class MethodBreakpoint < SimpleDelegator
def initialize(byebug_bp, method)
__setobj__ byebug_bp
@method = method
end
def source_code
Pry::Code.from_method(Pry::Method.from_str(@method))
end
def to_s
@method
end
end
def breakpoints
@breakpoints ||= []
end
# Add method breakpoint.
def add_method(method, expression = nil)
validate_expression expression
Pry.processor.debugging = true
owner, name = method.split(/[\.#]/)
byebug_bp = Byebug.add_breakpoint(owner, name.to_sym, expression)
bp = MethodBreakpoint.new byebug_bp, method
breakpoints << bp
bp
end
# Add file breakpoint.
def add_file(file, line, expression = nil)
real_file = (file != Pry.eval_path)
raise ArgumentError, 'Invalid file!' if real_file && !File.exist?(file)
validate_expression expression
Pry.processor.debugging = true
path = (real_file ? File.expand_path(file) : file)
bp = FileBreakpoint.new Byebug.add_breakpoint(path, line, expression)
breakpoints << bp
bp
end
# Change the conditional expression for a breakpoint.
def change(id, expression = nil)
validate_expression expression
breakpoint = find_by_id(id)
breakpoint.expr = expression
breakpoint
end
# Delete an existing breakpoint with the given ID.
def delete(id)
deleted = Byebug.started? &&
Byebug.remove_breakpoint(id) &&
breakpoints.delete(find_by_id(id))
raise ArgumentError, "No breakpoint ##{id}" if not deleted
Pry.processor.debugging = false if to_a.empty?
end
# Delete all breakpoints.
def clear
@breakpoints = []
Byebug.breakpoints.clear if Byebug.started?
Pry.processor.debugging = false
end
# Enable a disabled breakpoint with the given ID.
def enable(id)
change_status id, true
end
# Disable a breakpoint with the given ID.
def disable(id)
change_status id, false
end
# Disable all breakpoints.
def disable_all
each do |breakpoint|
breakpoint.enabled = false
end
end
def to_a
breakpoints
end
def size
to_a.size
end
def each(&block)
to_a.each(&block)
end
def find_by_id(id)
breakpoint = find { |b| b.id == id }
raise ArgumentError, "No breakpoint ##{id}!" unless breakpoint
breakpoint
end
private
def change_status(id, enabled = true)
breakpoint = find_by_id(id)
breakpoint.enabled = enabled
breakpoint
end
def validate_expression(expression)
if expression && # `nil` implies no expression given, so pass
(expression.empty? || !Pry::Code.complete_expression?(expression))
raise "Invalid breakpoint conditional: #{expression}"
end
end
end
end
|
require 'mqtt'
require 'i2c'
require 'fileutils'
require 'json'
require 'pp'
require 'date'
require 'yaml'
require 'timeout'
class RasPiIotShadow
attr_accessor :airconmode
def initialize(path, address = 0x27, airconmode= 0)
#i2c
@device = I2C.create(path)
@address = address
@time = 0
@temp = 0
@humidity = 0
#airconSetting
@setTemp = 20
@airconmode = airconmode #TunrnedOnAircon -> 1, TurnedOffAircon -> 0
iotconfig = YAML.load_file("iot.yml")
#toKinesis and tempChecker
@host = iotconfig["iotShadowConfig"]["host"]
@topic = iotconfig["iotShadowConfig"]["topic"]
@port = iotconfig["iotShadowConfig"]["port"]
@certificate_path = iotconfig["iotShadowConfig"]["certificatePath"]
@private_key_path = iotconfig["iotShadowConfig"]["privateKeyPath"]
@root_ca_path = iotconfig["iotShadowConfig"]["rootCaPath"]
@thing = iotconfig["iotShadowConfig"]["thing"]
#turnOnAircon and turnOffAircon
@topicTurnedOn = iotconfig["airconConfig"]["topicOn"]
@topicTurnedOff = iotconfig["airconConfig"]["topicOff"]
end
#fetch Humidity & Temperature with i2c device
def dataChecker
s = @device.read(@address, 0x04)
hum_h, hum_l, temp_h, temp_l = s.bytes.to_a
status = (hum_h >> 6) & 0x03
@time = Time.now.to_i
hum_h = hum_h & 0x3f
hum = (hum_h << 8) | hum_l
temp = ((temp_h << 8) | temp_l) / 4
@temp = temp * 1.007e-2 - 40.0
@humidity = hum * 6.10e-3
if @temp <= @setTemp
puts @airconmode = 0 #puts: For debug
end #if @temp... end
jsonToKinesis = JSON.generate({"datetime" => @time, "temp" => @temp, "humidity" => @humidity, "airconmode" => @airconmode})
return jsonToKinesis
end #def fetch_humidity_temperature end
def airconmodeGetter
MQTT::Client.connect(host:@host, port:@port, ssl: true, cert_file:@certificate_path, key_file:@private_key_path, ca_file: @root_ca_path) do |client|
client.subscribe(@topic) #subscribe message of airconmode
topic, @airconmode = client.get
puts @airconmode
end #MQTT end
end #airconmodeGetter end
#Output data to KinesisStream via AWSIoT
def toKinesis
inputData = dataChecker
MQTT::Client.connect(host:@host, port:@port, ssl: true, cert_file:@certificate_path, key_file:@private_key_path, ca_file: @root_ca_path) do |client|
client.publish(@topic, inputData) #publish room-temperature to AWSIoT
end #MQTT end
end #def toKinesis end
end #class RasPiIotShadow end
#Following are processed codes
sensingWithRaspi = RasPiIotShadow.new('/dev/i2c-1')
Process.daemon(nochdir = true, noclose = nil)
#dataChecker and toKinesis process
loop do
begin
Timeout.timeout(3) do #wait 1 sec nad if false -> call rescue
sensingWithRaspi.airconmodeGetter
puts "Received airconmode" + sensingWithRaspi.airconmode
end
rescue Timeout::Error
puts "dataChecker" + sensingWithRaspi.dataChecker
end
sensingWithRaspi.toKinesis
end
|
class Catalog::ProductsController < ApplicationController
def index
return unless params[:search]
query = params[:search][:query]
return if query.size < 3
@products = Product.where(
"name LIKE :q OR factory LIKE :q OR code LIKE :q OR keywords LIKE :qq",
q: "#{query}%", qq: "%#{query}%"
)
end
def show
@document = Catalog::ProductDocument.(params[:path], params[:path_id])
end
end
|
module Kilomeasure
class BulkCalculationsRunner < ObjectBase
fattrs :inputs,
:measure,
:formulas
boolean_attr_accessor :strict
def self.run(**options)
new(options).results
end
def initialize(*)
super
raise ArgumentError, :inputs unless inputs
raise ArgumentError, :formulas unless formulas
end
def results
evaluator.store(inputs)
expressions_hash = formulas.each_with_object({}) do |formula, hash|
next if inputs.keys.include?(formula.name)
hash[formula.name] = formula.expression
end
errors_hash = {}
results_hash = evaluator.solve(expressions_hash) do |error, name|
if error.is_a?(Dentaku::UnboundVariableError)
errors_hash[name] = error.unbound_variables.map(&:to_sym)
elsif error.is_a?(ZeroDivisionError)
errors_hash[name] = [:infinite]
end
nil
end
results_hash.each do |key, value|
next unless value.is_a?(String)
results_hash[key] = nil
errors_hash[key] = [:unresolved]
end
errors_hash.symbolize_keys!
CalculationsSet.new(
results: results_hash,
errors_hash: errors_hash,
measure: measure,
inputs: inputs)
end
memoize :results
private
def evaluator
Dentaku::Calculator.new.tap do |evaluator|
evaluator.add_function(
:pow,
:numeric,
->(mantissa, exponent) { mantissa**exponent }
)
end
end
memoize :evaluator
end
end
|
class SurfspotsController < ApplicationController
include ApplicationHelper
before_filter :requires_authentication, :except => [ :index, :show, :search, :browse, :sessions, :photos ]
before_filter :requires_admin, :only => [ :new, :create, :edit, :update, :destroy ]
before_filter :setup_surfspot, :only => [ :show, :edit, :update, :destroy, :sessions, :photos ]
before_filter :setup_side_content, :only => [:show, :sessions, :photos ]
# GET /surfspots
def index
@title = "Index of all surfspots | Surftrottr"
@surfspots = Surfspot.order("state, city, name")
respond_to do |format|
format.html
end
end
# GET /surfspots/1
def show
@title = "Surf reports for #{@surfspot.full_name} | Surftrottr"
#@tweets = MiddleMan.worker(:twit_worker).twitter_search(:arg => @surfspot)
@reports = Report.paginate :page => params[:page], :per_page => 10,
:conditions => "surfspot_id = #{@surfspot.id}",
:order => "actual_created_at DESC"
respond_to do |format|
format.html
##format.mobile
end
end
# GET /surfspots/new
def new
@title = "Create a new surfspot | Surftrottr"
@surfspot = Surfspot.new
respond_to do |format|
format.html
end
end
# GET /surfspots/1/edit
def edit
@title = "Edit a surfspot | Surftrottr"
end
# POST /surfspots
def create
@surfspot = Surfspot.new(params[:surfspot])
respond_to do |format|
if @surfspot.save
format.html { redirect_to admin_path }
else
format.html { render :action => "new" }
end
end
end
# PUT /surfspots/1
def update
respond_to do |format|
if @surfspot.update_attributes(params[:surfspot])
format.html { redirect_to admin_path }
else
format.html { render :action => "edit" }
end
end
end
# DELETE /surfspots/1
def destroy
@surfspot.destroy
respond_to do |format|
format.html { redirect_to(surfspots_url) }
end
end
# GET /surfspots/browse
# Browse surfspots by state and city.
def browse
@title = "Browse surfspots | Surftrottr"
@surfspots = Surfspot.order("state, city, name")
respond_to do |format|
format.html # browse.html.erb
format.js
end
end
# GET /surfspots/search
# Search for surfspots.
def search
@title = "Search surfspots | Surftrottr"
#if not params[:commit].nil?
# @surfspots = Surfspot.geo_search(params)
#elsif not params[:q].nil?
if not params[:q].nil?
@surfspots = Surfspot.text_search(params[:q])
end
respond_to do |format|
format.html # search.html.erb
end
end
# GET /surfspots/request
# Suggest a new surfspot to be added to Surftrottr.
def suggest
@surfspot = flash[:suggested_surfspot] ? flash[:suggested_surfspot] : SuggestedSurfspot.new
respond_to do |format|
format.html # suggest.html.erb
format.xml { render :xml => @surfspots }
end
end
# GET /surfspots/:id/sessions
def sessions
@title = "Surf sessions for #{@surfspot.full_name} | Surftrottr"
@sessions = SurfSession.paginate :page => params[:page], :per_page => 10,
:conditions => "surfspot_id = #{@surfspot.id}",
:order => "actual_date DESC"
respond_to do |format|
format.html
##format.mobile
end
end
# GET /surfspots/:id/photos
def photos
@title = "Photos for #{@surfspot.full_name} | Surftrottr"
@photos = @surfspot.photos
respond_to do |format|
format.html
##format.mobile
end
end
private
# Retrieve the Surfspot object.
def setup_surfspot
begin
@surfspot = Surfspot.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:error] = "Surfspot does not exist."
redirect_to_forwarding_url
end
end
def setup_side_content
# http://github.com/ewildgoose/ym4r_gm
@map = GMap.new("map_div")
@map.control_init(:large_map => true, :map_type => false)
@map.center_zoom_init([@surfspot.latitude, @surfspot.longitude], 13)
@map.overlay_init(GMarker.new([@surfspot.latitude, @surfspot.longitude], :title => @surfspot.full_name, :info_window => @surfspot.full_name))
# Find surfspots within a 10 miles range.
@nearby_spots = Surfspot.geo_search(@surfspot, 20)
@nearby_spots.each { |spot|
marker = GMarker.new([spot.latitude, spot.longitude], :title => spot.full_name, :info_window => spot.full_name)
@map.overlay_init(marker)
}
end
end
|
module AddressBook
module Data
class User < Base
key(:email_address) { Defaults.translate :email_address }
key(:password) { Defaults.translate :password }
end
end
end
|
require 'rails_helper'
describe "Customers API" do
let!(:customer) { create(:customer) }
it 'loads all customers' do
get '/api/v1/customers'
customer = JSON.parse(response.body).first
expect(response).to be_success
expect(response.code).to eq("200")
expect(customer.keys).to include("id","first_name","last_name")
end
it 'loads one customer' do
get "/api/v1/customers/#{customer.id}"
customer = JSON.parse(response.body)
expect(response).to be_success
expect(response.code).to eq("200")
expect(customer.keys).to include("id","first_name","last_name")
end
end
|
#
# Cookbook:: bender_is_great
# Recipe:: default
#
# Copyright:: 2017, The Authors, All Rights Reserved.
# Bite my shiny metal ass!
# Create a primary group
group node['bender_is_great']['group']
# Create sudo user for the instance
user node['bender_is_great']['user'] do
group node['bender_is_great']['group']
system node['bender_is_great']['system_user']
end
# Update our caches, depending on OS
case node['platform']
when 'ubuntu'
include_recipe 'apt'
when 'centos'
include_recipe 'yum'
else
log 'This is the worst kind of discrimination there is: the kind against me!' do
message <<-EOD
The platform #{node['platform']} isn't supported. Please choose between
centos or ubuntu.
EOD
level :warn
end
end
%w(apache bender).each do |recipe|
include_recipe "bender_is_great::#{recipe}"
end
|
# require 'pry'
class Hangman
attr_reader :guesser, :referee, :board, :gleft
def initialize(options = {})
default = standard_game
options = default.merge(options)
@guesser = options[:guesser]
@referee = options[:referee]
@gleft = options[:max]
binding.pry
end
def play
setup
take_turn until win
ending
end
def setup
word_length = referee.pick_secret_word
guesser.register_secret_length(word_length)
@board = '_' * word_length
end
def take_turn
display
letter = guesser.guess(board)
space = referee.check_guess(letter)
guesser.handle_response(letter, space)
update_board(space, letter)
end
def display
system('clear')
puts "#{gleft} guesses left\n"
puts "guesses so far #{guesser.guesses}\n\n#{board}"
end
def update_board(space, letter)
if space.empty?
@gleft -= 1
else
space.each { |position| board[position] = letter }
end
end
def standard_game
{
guesser: ComputerPlayer.new(File.readlines('dictionary.txt')),
referee: HumanPlayer.new,
max: 8
}
end
def win
board == referee.secret_word || gleft.zero?
end
def ending
if gleft.zero?
p "you lose...word was #{referee.secret_word}"
else
p "you win! #{board} is right"
end
end
end
module PlayerMethods
attr_reader :secret_word, :guesses
def check_guess(letter)
raise 'not a letter' unless letter.is_a?(String)
positions = []
@secret_word.chars.each_with_index do |ch, idx|
next unless ch == letter
positions << idx
end
positions
end
end
class HumanPlayer
include PlayerMethods
def initialize
@guesses = []
end
def pick_secret_word
p 'pick the word you want'
@secret_word = gets.chomp
secret_word.length
end
def register_secret_length(length)
length
end
def guess(board)
puts "Guess a letter! (#{board.length} ch long)\n"
gets.chomp
end
def handle_response(string, array)
# system('clear')
p "#{string} was found at #{array} positions #{@board}"
guesses << string
end
end
class ComputerPlayer
include PlayerMethods
attr_reader :dictionary, :alpha, :candidate_words, :secret_word
def self.player_with_dict_file
dict = File.readlines('dictionary.txt')
dict = dict.map(&:chomp)
ComputerPlayer.new(dict)
end
def initialize(dictionary)
@dictionary = dictionary
@alpha = ('a'..'z').to_a
@guesses = []
end
def pick_secret_word
random_word = @dictionary.sample.chomp
@secret_word = random_word
random_word.length
end
def guess(board)
best_letter(board)
end
def best_letter(board)
#turn into hash
combined = candidate_words.join
alpha.delete_if { |letter| board.include?(letter) }
z = alpha.reduce { |x, y| combined.count(x) > combined.count(y) ? x : y }
alpha.delete(z)
end
def handle_response(string, array)
# only updates candidate words
guesses << string
candidate_words.keep_if do |word|
(0...word.length).select { |i| word[i] == string } == array
end
end
def register_secret_length(length)
@candidate_words = @dictionary.select { |word| word.length == length }
end
end
if __FILE__ == $PROGRAM_NAME
print "Guesser: Computer (yes/no)? "
if gets.chomp == "yes"
guesser = ComputerPlayer.player_with_dict_file
else
guesser = HumanPlayer.new
end
print "Referee: Computer (yes/no)? "
if gets.chomp == "yes"
referee = ComputerPlayer.player_with_dict_file
else
referee = HumanPlayer.new
end
Hangman.new({guesser: guesser, referee: referee}).play
end
|
module Rooms
class ValidateRoomPresence
include Interactor
delegate :room, to: :context
def call
context.fail! unless context.room
end
end
end
|
class CreateUserSettings < ActiveRecord::Migration
def change
create_table :user_settings do |t|
t.boolean :voting_visible, default: false
t.integer :tenant_id
t.timestamps null: false
end
end
end
|
class ORS
class Config
CONFIG_FILENAME = "config/deploy.yml"
@@args = []
@@options = {}
def initialize(options)
parse_options(options)
parse_config_file
end
def _options
@@options
end
def [](key)
@@options[key]
end
def []=(key, value)
@@options[key] = value
end
def parse_options(options)
@@options[:pretending] = true if options.delete("-p") || options.delete("--pretend")
if options.delete("-ng") || options.delete("--no-gateway")
@@options[:use_gateway] = false
else
@@options[:use_gateway] = true
end
# grab environment
index = options.index("to") || options.index("from")
unless index.nil?
@@options[:environment] = options.delete_at(index + 1)
options.delete_at(index)
end
@@options[:args] = options.dup
set_default_options
end
def set_default_options
@@options[:environment] ||= "production"
@@options[:remote] ||= "origin"
@@options[:branch] ||= @@options[:environment]
@@options[:pretending] ||= false
@@options[:log_lines] = 100
@@options[:gateway] = "deploy-gateway"
@@options[:user] = "deployer"
@@options[:base_path] = "/var/www"
@@options[:web_servers] = %w(koala)
@@options[:app_servers] = %w(eel jellyfish squid)
@@options[:migration_server] = "tuna"
@@options[:console_server] = "tuna"
@@options[:cron_server] = "tuna"
end
def parse_config_file
if File.exists?(CONFIG_FILENAME)
YAML.load(File.read(CONFIG_FILENAME)).each do |(name, value)|
@@options[name.to_sym] = value
end
end
end
def finalize!
@@options[:name] = name
@@options[:remote_url] = remote_url
@@options[:deploy_directory] = deploy_directory
@@options[:revision] = git.log(1).first.sha
@@options[:ruby_servers] = [@@options[:app_servers], @@options[:console_server], @@options[:cron_server], @@options[:migration_server]].flatten.compact.uniq
@@options[:all_servers] = [@@options[:web_servers], @@options[:ruby_servers]].flatten.compact.uniq
end
def git
@git ||= Git.open(Dir.pwd)
end
def valid?
name.to_s.size > 0
end
private
#
# methods to help finalize the config
#
def remote_url
if git.config.has_key?("remote.#{@@options[:remote]}.url")
git.config["remote.#{@@options[:remote]}.url"]
else
raise StandardError, "There is no #{@@options[:remote]} remote in your git config, please check your config/deploy.yml"
end
end
def name
remote_url.gsub(/^[\w]*(@|:\/\/)[^\/:]*(\/|:)([\w\.\/_\-]+)$/, '\3').gsub(/\.git$/i, '')
end
def deploy_directory
directory = File.join(@@options[:base_path], @@options[:name])
if @@options[:environment] == "production"
directory
else
"#{directory}_#{@@options[:environment]}"
end
end
end
end
|
RSpec.describe 'jamrb-lex', :output_specs do
project_path = JamRb[:root] + "/jamrb-lex"
fixtures_path = JamRb[:root] + "/jamrb-lex/test/rb-sx-tests"
make_executable_in project_path
fetch_fixtures(fixtures_path).each do |fixture|
input = File.basename fixture
output = "#{input}.out"
navigate_to project_path
result, status = execute "./bin/jamrb_lex < #{fixture}"
describe 'lexer' do
it 'exits with zero status' do
expect(status).to eq 0
end
it "tokenizes #{input} to match the contents of #{output}" do
expect(result).to eq File.read "#{fixture}.out"
end
end
end
end
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../bear.rb')
require_relative('../river.rb')
require_relative('../fish.rb')
class FishTest < MiniTest::Test
def setup
fish1 = Fish.new('nemo')
fish2 = Fish.new('ponyo')
fish3 = Fish.new('dory')
fishes = [fish1, fish2, fish3]
@river = River.new('Amazon', fishes)
@bear = Bear.new('Beorn', 'Grizzly')
end
def test_bear_has_name
assert_equal('Beorn', @bear.name)
end
def test_bear_has_type
assert_equal('Grizzly', @bear.type)
end
def test_bear_has_empty_stomach
assert_equal(0, @bear.food_count)
end
def test_bear_can_catch_fish
@bear.catch_fish(@river, @river.fishes[0])
assert_equal(1, @bear.food_count)
assert_equal(2, @river.fish_count)
end
def test_bear_can_roar
assert_equal('Roarrrrr!!!', @bear.roar)
end
end
|
require 'fuelsdk'
require_relative 'sample_helper'
begin
stubObj = FuelSDK::Client.new auth
# Create List
p '>>> Create List'
postList = FuelSDK::List.new
postList.authStub = stubObj
postList.props = {"ListName" => 'RubyAssetList', "Description" => "This list was created with the RubySDK", "Type" => "Private" }
postResponse = postList.post
p 'Post Status: ' + postResponse.status.to_s
p 'Code: ' + postResponse.code.to_s
p 'Message: ' + postResponse.message.to_s
p 'Result Count: ' + postResponse.results.length.to_s
p 'Results: ' + postResponse.results.inspect
raise 'Failure creating list for asset' unless postResponse.success?
# In order for this sample to run, it needs to have an asset that it can associate the campaign to
ExampleAssetType = "LIST"
ExampleAssetItemID = postResponse.results[0][:new_id]
# Retrieve all Campaigns
p '>>> Retrieve all Campaigns'
getCamp = FuelSDK::Campaign.new
getCamp.authStub = stubObj
getResponse = getCamp.get
p 'Retrieve Status: ' + getResponse.status.to_s
p 'Code: ' + getResponse.code.to_s
p 'Message: ' + getResponse.message.to_s
p 'MoreResults: ' + getResponse.more?.to_s
p "Results: #{getResponse.results}"
p 'Results(Items) Length: ' + getResponse.results['items'].length.to_s
p '-----------------------------'
raise 'Failure retrieving campaigns' unless getResponse.success?
while getResponse.more? do
p '>>> Continue Retrieve all Campaigns with GetMoreResults'
getResponse = getCamp.continue
p 'Retrieve Status: ' + getResponse.status.to_s
p 'Code: ' + getResponse.code.to_s
p 'Message: ' + getResponse.message.to_s
p 'MoreResults: ' + getResponse.more?.to_s
p 'Results(Items) Length: ' + getResponse.results['items'].length.to_s
end
# Create a new Campaign
p '>>> Create a new Campaign'
postCamp = FuelSDK::Campaign.new
postCamp.authStub = stubObj
postCamp.props = {"name" => "RubySDKCreatedForTest1", "description"=> "RubySDKCreatedForTest", "color"=>"FF9933", "favorite"=>"false"}
postResponse = postCamp.post
p 'Post Status: ' + postResponse.status.to_s
p 'Code: ' + postResponse.code.to_s
p 'Message: ' + postResponse.message.to_s
p 'Results: ' + postResponse.results.to_json
p '-----------------------------'
raise 'Failure creating campaign' unless postResponse.success?
IDOfpostCampaign = postResponse.results['id']
# Retrieve the new Campaign
p '>>> Retrieve the new Campaign'
getCamp = FuelSDK::Campaign.new
getCamp.authStub = stubObj
getCamp.props = {"id" => IDOfpostCampaign}
getResponse = getCamp.get
p 'Retrieve Status: ' + getResponse.status.to_s
p 'Code: ' + getResponse.code.to_s
p 'Message: ' + getResponse.message.to_s
p 'Results: ' + getResponse.results.to_json
p '-----------------------------'
raise 'Failure retrieving campaign' unless getResponse.success?
# Update the new Campaign
p '>>> Update the new Campaign'
patchCamp = FuelSDK::Campaign.new
patchCamp.authStub = stubObj
patchCamp.props = {"id"=> IDOfpostCampaign, "name" => "RubySDKCreated-Updated!"}
patchResponse = patchCamp.patch
p 'Patch Status: ' + patchResponse.status.to_s
p 'Code: ' + patchResponse.code.to_s
p 'Message: ' + patchResponse.message.to_s
p 'Results: ' + patchResponse.results.to_json
p '-----------------------------'
raise 'Failure updating campaign' unless patchResponse.success?
# Retrieve the updated Campaign
p '>>> Retrieve the updated Campaign'
getCamp = FuelSDK::Campaign.new
getCamp.authStub = stubObj
getCamp.props = {"id" => IDOfpostCampaign}
getResponse = getCamp.get
p 'Retrieve Status: ' + getResponse.status.to_s
p 'Code: ' + getResponse.code.to_s
p 'Message: ' + getResponse.message.to_s
p 'Results: ' + getResponse.results.to_json
p '-----------------------------'
raise 'Failure retrieving campaign' unless getResponse.success?
# Create a new Campaign Asset
p '>>> Create a new Campaign Asset'
postCampAsset = FuelSDK::Campaign::Asset.new
postCampAsset.authStub = stubObj
postCampAsset.props = {"id" => IDOfpostCampaign, "ids"=> [ExampleAssetItemID], "type"=> ExampleAssetType}
postResponse = postCampAsset.post
p 'Post Status: ' + postResponse.status.to_s
p 'Code: ' + postResponse.code.to_s
p 'Message: ' + postResponse.message.to_s
p 'Results: ' + postResponse.results.to_json
p '-----------------------------'
raise 'Failure creating campaign assets' unless postResponse.success?
IDOfpostCampaignAsset = postResponse.results[0]['id']
# Retrieve all Campaign Asset for a campaign
p '>>> Retrieve all Campaign Asset for a Campaign'
getCampAsset = FuelSDK::Campaign::Asset.new
getCampAsset.authStub = stubObj
getCampAsset.props = {"id" => IDOfpostCampaign}
getResponse = getCampAsset.get
p 'Retrieve Status: ' + getResponse.status.to_s
p 'Code: ' + getResponse.code.to_s
p 'Message: ' + getResponse.message.to_s
p 'Results: ' + getResponse.results.inspect
p '-----------------------------'
raise 'Failure retrieving campaign assets' unless getResponse.success?
# Retrieve a single new Campaign Asset
p '>>> Retrieve a single new Campaign Asset'
getCampAsset = FuelSDK::Campaign::Asset.new
getCampAsset.authStub = stubObj
getCampAsset.props = {"id" => IDOfpostCampaign, "assetId" => IDOfpostCampaignAsset}
getResponse = getCampAsset.get
p 'Retrieve Status: ' + getResponse.status.to_s
p 'Code: ' + getResponse.code.to_s
p 'Message: ' + getResponse.message.to_s
p 'Results: ' + getResponse.results.inspect
p '-----------------------------'
raise 'Failure retrieving campaign asset' unless getResponse.success?
# Delete the new Campaign Asset
p '>>> Delete the new Campaign Asset'
deleteCampAsset = FuelSDK::Campaign::Asset.new
deleteCampAsset.authStub = stubObj
deleteCampAsset.props = {"id" => IDOfpostCampaign, "assetId"=> IDOfpostCampaignAsset}
deleteResponse = deleteCampAsset.delete
p 'Delete Status: ' + deleteResponse.status.to_s
p 'Code: ' + deleteResponse.code.to_s
p 'Message: ' + deleteResponse.message.to_s
p 'Results: ' + deleteResponse.results.to_json
p '-----------------------------'
raise 'Failure deleting campaign asset' unless deleteResponse.success?
# Get a single a new Campaign Asset to confirm deletion
p '>>> Get a single a new Campaign Asset to confirm deletion'
getCampAsset = FuelSDK::Campaign::Asset.new
getCampAsset.authStub = stubObj
getCampAsset.props = {"id" => IDOfpostCampaign}
getResponse = getCampAsset.get
p 'Retrieve Status: ' + getResponse.status.to_s
p 'Code: ' + getResponse.code.to_s
p 'Message: ' + getResponse.message.to_s
p 'Results: ' + getResponse.results.inspect
p '-----------------------------'
raise 'Failure retrieving campaign asset' unless getResponse.success?
raise 'Failure retrieving campaign asset' unless getResponse.results['totalCount'] == 0
rescue => e
p "Caught exception: #{e.message}"
p e.backtrace
ensure
# Delete the new Campaign
p '>>> Delete the new Campaign'
deleteCamp = FuelSDK::Campaign.new
deleteCamp.authStub = stubObj
deleteCamp.props = {"id"=> IDOfpostCampaign}
deleteResponse = deleteCamp.delete
p 'Delete Status: ' + deleteResponse.status.to_s
p 'Code: ' + deleteResponse.code.to_s
p 'Message: ' + deleteResponse.message.to_s
p 'Results: ' + deleteResponse.results.to_json
p '-----------------------------'
raise 'Failure deleting campaign asset' unless deleteResponse.success?
p '>>> Delete List'
deleteSub = FuelSDK::List.new()
deleteSub.authStub = stubObj
deleteSub.props = {"ID" => ExampleAssetItemID}
deleteResponse = deleteSub.delete
p 'Delete Status: ' + deleteResponse.status.to_s
p 'Code: ' + deleteResponse.code.to_s
p 'Message: ' + deleteResponse.message.to_s
p 'Results Length: ' + deleteResponse.results.length.to_s
p 'Results: ' + deleteResponse.results.to_s
end
|
module Jsonapi
module Matchers
class ErrorIncluded
include Jsonapi::Matchers::Shared
def with_code(error_code)
@error_code = error_code
self
end
def matches?(target)
@target = normalize_target(target)
return false unless @target
@value = @target.try(:[], :errors)
if @error_code
includes_error?
else
has_error?
end
end
def failure_message
@failure_message
end
private
def has_error?
@failure_message = "expected any error code, but got '#{@value}'"
!@value.nil? && @value.any?
end
def includes_error?
@failure_message = "expected error code '#{@error_code}', but got '#{@value}'"
!@value.nil? && @value.any? { |v| v['code'] == @error_code }
end
end
module Error
def have_jsonapi_error
ErrorIncluded.new
end
end
end
end
|
INITIAL_MARKER = ' '
PLAYER_MARKER = 'X'
COMPUTER_MARKER = 'O'
WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +
[[1, 4, 7], [2, 5, 8], [3, 6, 9]] +
[[1, 5, 9], [3, 5, 7]]
def joinor(array, delimiter1 = ', ', delimiter2 = 'or')
if array.length > 2
string1 = array.first((array.length) - 1).join(delimiter1)
string2 = array.pop.to_s
return string1 + "#{delimiter1} #{delimiter2} " + string2
else
array.join(" #{delimiter2} ")
end
end
p joinor([1, 2]) # => "1 or 2"
p joinor([1, 2, 3]) # => "1, 2, or 3"
p joinor([1, 2, 3], '; ') # => "1; 2; or 3"
p joinor([1, 2, 3], ', ', 'and') # => "1, 2, and 3"
# make computer play defensive
def computer_places_piece!(brd)
square = ''
WINNING_LINES.each do |line|
if brd.values_at(line[0], line[1], line[2]).count(PLAYER_MARKER) == 2
square = brd.slice(*line).key(INITIAL_MARKER)
else
square = empty_squares(brd).sample
end
end
brd[square] = COMPUTER_MARKER
end
|
flowmatic_on = false
flowmatic_on = true
class Animal
attr_accessor :name
def initialize(name, legs=4)
@name = name
@legs = legs
end
end
monkey = Animal.new('George', 2)
monkey.name = 'Kong'
dog = Animal.new('Bigelow')
class Monkey
attr_accessor :name
def initialize(name)
@name = name
@legs = 2
end
end
monkey = Monkey.new('George')
puts monkey.name
class Dog
attr_accessor :name
def initialize(name)
@name = name
@legs = 4
end
end
dog = Dog.new('Bigelow')
puts dog.name
class Dog2 < Animal
def bark
puts 'Arf!'
end
end
dog = Dog2.new('Bigelow')
puts dog.name
dog.bark
class Monkey2 < Animal
def make_sounds
puts 'EEh ooh ooh!'
end
end
monkey = Monkey2.new('George', 2)
monkey.name = 'Oxnard'
monkey.make_sounds
class MySuperclass
def say_hello
puts 'Hello!'
end
end
class MySubClass < MySuperclass
def say_goodbye
puts 'Goodbye!'
end
end
subby = MySubClass.new
subby.say_hello
subby.say_goodbye
class Person
attr_reader :name
def initialize(name)
@name = name
end
def speak
puts 'Hello!'
end
end
class Pirate < Person
def speak
puts 'Arr!'
end
end
esmeralda = Person.new('Esmeralda')
rubybeard = Pirate.new('RubyBeard')
puts esmeralda.name
puts rubybeard.name
esmeralda.speak
rubybeard.speak
class Dog3 < Animal
def initialize(name)
puts 'Just made a new dog!'
super
end
def bark
puts 'Arf!'
end
end
dog = Dog3.new('Bigelow')
dog.bark
class GuardDog < Dog3
attr_accessor :strength
def initialize(name, strength)
@strength = strength
super(name)
end
def bark
puts 'Stop, in the name of the law!'
end
def attack
puts "Did #{rand(strength)} damage!"
end
end
rex = GuardDog.new('Rex', 7)
puts rex.strength
rex.bark
rex.attack
rex.attack
class Monkey3 < Animal
attr_reader :name, :arms
def initialize(name, arms = 2)
@name = name
@arms = arms
end
def make_sounds
puts 'Eeh ooh ooh!'
end
end
class FlyingMonkey < Monkey3
attr_reader :wings
def initialize(name, wings, arms = 2)
@wings = wings
super(name, arms)
end
def throw_coconuts
coconuts = rand(arms)
damage = coconuts * wings
puts "Threw #{coconuts} coconuts! It did #{damage} damage."
end
end
oswald = FlyingMonkey.new('Oswald', 6, 4)
oswald.make_sounds
oswald.throw_coconuts
class Account
attr_accessor :username, :password
def initialize(username, password)
@username = username
@password = password
end
end
class SuperSecretAccount < Account
def initialize(username, password)
@reset_attempts = 0
super(username, password)
end
def password=(new_password)
while @reset_attempts < 3
print 'Current password?: '
current_password = gets.chomp
if @password == current_password
@password = new_password
puts "Password changed to #{new_password}"
break
else
@reset_attempts += 1
puts "That's not the right password."
puts "Attempt #{@reset_attempts} of 3 used up!"
end
end
end
def password
'The password is secret!'
end
end
regular = Account.new('Your name', 'your password')
super_safe = SuperSecretAccount.new('Your name', 'your password')
puts "Your regular account password is #{regular.password}"
regular.password = 'Something else!'
puts "Your regular account password is now #{regular.password}"
puts "If we try to see the secret account password, we get: #{super_safe.password}"
changed_password = 'Something else!'
puts "Trying to change your secret account password to #{changed_password}"
super_safe.password = changed_password
|
require 'test_helper'
module Launchrock
class ClientTest < MiniTest::Unit::TestCase
def test_find_user_success
fakeweb_post("/v1/platformUserLogin", {
:platform_user => {
:session_id => 'YOLO', :UID => '1'
}
})
c = Client.find_by_email_and_password('omg', 'lol')
assert_equal 'YOLO', c.session_id
assert_equal '1', c.client_id
end
def test_find_user_fail
fakeweb_post("/v1/platformUserLogin", {}, false)
u = Client.find_by_email_and_password('omg', 'lol')
assert_nil u
end
def test_sites
fakeweb_post("/v1/getPlatformUserSites", {'platform_user_sites' => [{'SID' => '1', 'siteName' => 'SWAG'} ] } )
sites = Launchrock::Client.new(1, 'yolo').sites
assert_equal 1, sites.count
site = sites.first
assert_equal '1', site.id
assert_equal 'SWAG', site.name
end
def test_site_named
fakeweb_post("/v1/getPlatformUserSites", {'platform_user_sites' => [{'SID' => '1', 'siteName' => 'SWAG'} ] } )
site = Launchrock::Client.new(1, 'yolo').site_named('SWAG')
assert_equal '1', site.id
assert_equal 'SWAG', site.name
end
end
end
|
class LinksController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :handle_link_not_found
def new
@link = Link.new
end
def create
@link = Link.new(link_params)
locals = @link.save ? current_hostname : {}
render :new, locals: locals
end
def show
@link = Link.find_by_shortcode(params[:shortcode])
@link.log_visit!
redirect_to @link.url, status: 301
end
private
def link_params
params.require(:link).permit(:url)
end
def handle_link_not_found
render :not_found
end
def current_hostname
{ hostname: request.host_with_port }
end
end
|
# Pad an Array
# I worked on this challenge [by myself, with: ]
# I spent [] hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# 0. Pseudocode
# What is the input?
# Input is the array, and minimum size of the array, and padding value.
# What is the output? (i.e. What should the code return?)
# Output is the array padded to the the minimum size.
# What are the steps needed to solve the problem?
# method to count length of array
# see if length is less than min
# method to push variable to minimum size with padding value
=begin# 1. Initial Solution
def pad!(array, min_size, value = nil) #destructive
if array.length >= min_size
array
else
until array.length== min_size
array.push(value)
end
end
return array
end
def pad(array, min_size, value = nil) #non-destructive
new_array = array.dup
if new_array.length>= min_size
new_array
else
until new_array.length == min_size
new_array.push(value)
end
return new_array
end
end
=end
# 3. Refactored Solution
def pad!(array, min_size, value = nil) #destructive
array << value while array.length < min_size
array
end
def pad(array, min_size, value = nil) #non-destructive
new_array = array.dup
new_array << value while new_array.length < min_size
new_array
end
=begin
# 4. Reflection
-Were you successful in breaking the problem down into small steps?
Yes
Once you had written your pseudocode, were you able to easily translate it into code? What difficulties and successes did you have?
More or less, there were some challenges in some of the specific syntax, but for the most part the initial solution was fairly straight forward.
Was your initial solution successful at passing the tests? If so, why do you think that is? If not, what were the errors you encountered and what did you do to resolve them?
We had some basic syntax issues, but once we solved them the initial program passed the tests.
When you refactored, did you find any existing methods in Ruby to clean up your code?
Yes we did.
How readable is your solution? Did you and your pair choose descriptive variable names?
It seems pretty readible to me, I imagine you need to have some basic coding knowledge to understand it, but all the variables make sense for what they are.
What is the difference between destructive and non-destructive methods in your own words?
destructive methods replace the input completely, where non-destructive methods make a copy of the initial input so changes are made to the copy, preserving the integrity of the input.
=end |
#!/usr/bin/env ruby
#Using the following function signature, write a C# function that prints out every combination of indices using Console.WriteLine() whose values add up to a specified sum, n. Values of 0 should be ignored.
#public void PrintSumCombinations(List<int> numbers, int n);
#• It’s okay to use additional private functions to implement the public function
#• Be sure to print out the indices of numbers and not the values at those indices
#• Don’t worry too much about memory or CPU optimization; focus on correctness
#To help clarify the problem, calling the function with the following input:
#List<int> numbers = new List<int> { 1, 1, 2, 2, 4 };
#PrintSumCombinations(numbers, 4);
#Should result in the following console output (the ordering of the different lines isn’t important and may vary by implementation):
#0 1 2 (i.e. numbers[0] + numbers[1] + numbers[2] = 1 + 1 + 2 = 4)
#0 1 3
#2 3
#4
#ref: http://www.careercup.com/page?pid=software-engineer-in-test-interview-questions
# This question specifies a C# implementation, but I will implement this in Ruby.
class Array
def sum_combinations(sum)
numbers = self
indices = (0..numbers.length-1).to_a
q = 1.upto(numbers.length).collect do |n|
s = indices.combination(n).collect do |a|
a if a.inject(0) {|t,i| t += numbers[i]} == sum
end.compact
s.empty? ? nil : s
end.compact
solution = []
q.each{|v| v.each{|r| solution << r}}
solution
end
end
def print_sum_combinations(numbers,sum)
numbers.sum_combinations(sum).each do |s|
p s
end
end
tests =
[
[[1,1,2,2,4],4],
[[1,7,3,4,5,6,2],7]
]
tests.each do |t|
puts "numbers: #{t[0]}, sum: #{t[1]}"
print_sum_combinations(t[0],t[1])
puts
end
|
source 'https://rubygems.org'
# Declare your gem's dependencies in auth_forum.gemspec.
# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.
gemspec
# Declare any dependencies that are still in development here instead of in
# your gemspec. These might include edge Rails or gems from your path or
# Git. Remember to move these dependencies to your gemspec before releasing
# your gem to rubygems.org.
# To use a debugger
# gem 'byebug', group: [:development, :test]
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'will_paginate', '3.0.5'
gem 'forem', :github => "radar/forem", :branch => "rails4"
gem 'devise'
gem 'activeadmin', github: 'activeadmin'
gem 'mysql2', '~> 0.3.20'
gem "factory_girl_rails", "~> 4.0"
gem 'minitest-rails'
gem 'simplecov', :require => false, :group => :test
gem 'carmen-rails', '~> 1.0.0'
gem 'carmen' |
require 'rspec'
require 'rules/ca/on/is_holiday'
module Rules
module Ca
module On
describe IsHoliday do
describe 'processing by itself' do
describe 'when there is no overtime' do
let(:criteria) {
{
holidays_overtime: true
}
}
context 'when activity lands on a holiday' do
let(:overtime_rule) { IsHoliday.new(nil, OpenStruct.new(attributes_for(:activity, total_hours: 4.0, from: DateTime.parse("2019-04-19 9:00am"),
to: DateTime.parse("2019-04-19 1:00pm"))), criteria) }
subject { overtime_rule.process_activity }
it "should have all hours in overtime" do
expect(subject.overtime).to eq(4.0)
expect(subject.total).to eq(4.0)
end
it "should be overtime" do
expect(overtime_rule.check).to be true
end
end
context 'when activity does not land on a holiday' do
let(:overtime_rule) { IsHoliday.new(nil, OpenStruct.new(attributes_for(:activity, total_hours: 4.0, from: DateTime.parse("2019-04-18 9:00am"),
to: DateTime.parse("2019-04-18 1:00pm"))), criteria) }
subject { overtime_rule.process_activity }
it "should not have all hours in overtime" do
expect(subject.overtime).to eq(0.0)
expect(subject.total).to eq(4.0)
end
it "should not be overtime" do
expect(overtime_rule.check).to be false
end
end
end
end
end
end
end
end |
require_relative '../test_helper'
require 'yaml'
describe Store do
let(:product) { Product.new(code: 'VOUCHER', name: 'Cabify Voucher', price: 5.00) }
before do
Store.empty
end
it 'cant add nil to store' do
Store.add_product nil
Store.products.length.must_equal 0
end
it 'can add products to store' do
Store.add_product product
Store.products.length.must_equal 1
end
it 'cant add duplicate products to store' do
Store.add_product product
Store.add_product product
Store.products.length.must_equal 1
end
it 'can remove produts from store' do
Store.add_product product
Store.products.length.must_equal 1
Store.remove_product product
Store.products.length.must_equal 0
end
it 'can find product by product_code' do
Store.add_product product
Store.find_product_by_code(product.code).must_equal product
end
it 'populate inventory with yaml file products' do
source_file = 'test/resources/products_test.yml'
total_products = YAML.load_file(source_file).length
Store.setup_products(source_file)
Store.products.length.must_equal total_products
end
end
|
require 'view'
describe View do
describe '.all' do
it 'shows all diary entries' do
connection = PG.connect(dbname: 'daily_diary_test')
connection.exec("INSERT INTO entries (title) VALUES ('diary_entry_one');")
connection.exec("INSERT INTO entries (title) VALUES ('diary_entry_two');")
connection.exec("INSERT INTO entries (title) VALUES ('diary_entry_three');")
expect(subject.all).to include("diary_entry_one")
expect(subject.all).to include("diary_entry_two")
expect(subject.all).to include("diary_entry_three")
end
end
end
|
# frozen_string_literal: true
# Number controller class
class NumberController < ApplicationController
def index; end
def armstrong
@result = find_armstrong(params[:n].to_i)
respond_to do |format|
format.html
format.js
end
end
private
def find_armstrong(dig)
return unless dig.positive?
((10**(dig - 1))..(10**dig - 1)).select { |v| v.to_s.split('').map { |d| d.to_i**dig }.reduce(:+).eql?(v) }
end
end
|
module M2m
def self.event(to_name, from_name=nil)
M2m::Event.new(to_name,from_name).fire_transitions
end
class << self
attr_accessor :transitions
attr_accessor :actions
attr_accessor :data
end
def self.reset(json=nil)
self.transitions = []
self.actions={}
self.data={}
interpret(json) if json
end
self.reset
def self.interpret(json)
jq=JsonQuery.new(json)
jq.transitions(:unset => true).each do |i|
self.transitions.reject!{|j| j['when'] == i['when'] && j['action'] == i['action']}
end
jq.transitions.each do |i|
self.transitions.push(Transition.new(i))
end
jq.actions.each do |i|
self.actions[i['id']] = i
end
self.data.merge!(jq.data)
jq.transitions(:now => true) do |i|
Transition.new(i).fire
end
json
end
private
class JsonQuery
def initialize(json)
@json = json['m2m'] || {}
end
def transitions(opts={})
opts = {:now => false, :unset => false}.merge(opts)
return [] if json['transitions'].blank?
if now
json['transitions'].select{|i| i['when'] == 'now'}
else
json['transitions'].reject{|i| i['when'] == 'now'}
end
end
def actions
return [] if json['actions'].blank?
json['actions'].select{|i| i['id']}
end
def data
return {} if json['data'].blank?
json['data']
end
end
end
|
<<<<<<< HEAD
# short-circuit assignment
def result
result = nil || 1
return result
end
put result
# default values - "OR"
# tweets = timeline.tweets || []
# short-circuit evaluation. the second member is not evaluated unless current session is nit
# def sign_in
# current_session || sign_user_in
# end
# conditional assignement
i_was_set = 1
i_was_set ||= 2
puts i_was_set
i_was_not_set ||= 2
puts i_was_not_set
options = {}
options[:country] ||= "US"
options[:privacy] ||= true
options[:geotag] || = true
# conditional return values
options[:path] = if true
"/Lecongolais.net/Lecongolais.net"
else
"/mazembo"
def list_url(user_name, list_name)
if list_name
"https://twitter.com/#{user_name}/#{list_name}"
else
"https://twitter.com/#{user_name}"
end
end
#case statement value
client_name = web
client_url = case client_name
when "web"
"http://twitter.com"
when "Facebook"
"http://www.facebook.com/twitter"
else
nil
end
puts client_url
#case -ranges
popularity = case tweet.retweet_count
when 0..9
nil
when 10..99
"trending"
else
"hot"
end
tweet_type = case tweet.status
when /\A@\w+/
:mention
when /\Ad\s+\w+/
:direct_message
else
:public
end
tweet_type = case tweet.status
when /\A@\w+/ then :mention
when /\Ad\s+\w+/ then :direct_message
else :public
end
# Not the best
# if ! tweets.empty?
# puts "Timeline:"
# puts tweets
# end
unless tweets.empty?
puts "Timeline: "
puts tweets
end
# Not the best || unless with else is confusing
# unless tweets.empty?
# puts "Timeline: "
# puts tweets
# else
# puts "No tweets found -better follow some people!"
# end
if tweets.empty
puts "No tweets found -better follow some people!"
else
puts "Timeline: "
puts tweets
end
# Nil is false
# Not best
# if attachment.file_path != nil
# attachment.post
# end
if attachment.file_path
attachment.post
end
#In ruby only nil is false
name = ""
quantity = 0
tweets = []
unless name.length
warn "User name required "
end
# the statement above will never be false
#inline conditionals
#Not the best
if password.length < 8
fail "Password too short "
end
unless user_name
fail "No username set "
end
# Rather the below inline statements
fail "Password too short " if password.length < 8
fail "No user same set " unless username
#short circuit "AND"
# not the best...
if user
if user.signed_in?
end
end
# Rather this || If user is nil, second half never runs v
if user && user.signed_in?
end
#Methods and Classes
#Optional arguments
#Not optimal
def tweet(message, lat, long)
#
end
tweet("Practicing Ruby-Fu", nil, nil) #location isn't always used, so let's add defaults
def tweet (message, lat = nil, long = nil )
#
end
tweet ("Practicing Ruby-Fu") # location is now optional
def tweet(message, lat = nil, long = nil, reply_id = nil)
#
end
tweet("Practicing Ruby Fu", 28.55, -81.33, 227946) # calls to it are hard to read
tweet("Practicing Ruby Fu", nil, nil, 227946) # have to keep placeholders for arguments you're not using
#Hash arguments
def tweet(message, options = {})
status = Status.new
status.lat = options[:lat]
status.long = options[:long]
status.body = message
status.reply_id = options[:reply_id]
status.post
end
tweet("Practicing Ruby-Fu!",
:lat => 28.55,
:long => -81.33
:reply_id => 227946
)
# keys show meaning || all combined into options argument
=======
# short-circuit assignment
def result
result = nil || 1
return result
end
put result
# default values - "OR"
# tweets = timeline.tweets || []
# short-circuit evaluation. the second member is not evaluated unless current session is nit
# def sign_in
# current_session || sign_user_in
# end
# conditional assignement
i_was_set = 1
i_was_set ||= 2jj
puts i_was_set
i_was_not_set ||= 2
puts i_was_not_set
options = {}
options[:country] ||= "US"
options[:privacy] ||= true
options[:geotag] || = true
# conditional return values
options[:path] = if true
"/Lecongolais.net/Lecongolais.net"
else
"/mazembo"
def list_url(user_name, list_name)
if list_name
"https://twitter.com/#{user_name}/#{list_name}"
else
"https://twitter.com/#{user_name}"
end
end
#case statement value
client_name = web
client_url = case client_name
when "web"
"http://twitter.com"
when "Facebook"
"http://www.facebook.com/twitter"
else
nil
end
puts client_url
#case -ranges
popularity = case tweet.retweet_count
when 0..9
nil
when 10..99
"trending"
else
"hot"
end
tweet_type = case tweet.status
when /\A@\w+/
:mention
when /\Ad\s+\w+/
:direct_message
else
:public
end
tweet_type = case tweet.status
when /\A@\w+/ then :mention
when /\Ad\s+\w+/ then :direct_message
else :public
end
# Not the best
# if ! tweets.empty?
# puts "Timeline:"
# puts tweets
# end
unless tweets.empty?
puts "Timeline: "
puts tweets
end
# Not the best || unless with else is confusing
# unless tweets.empty?
# puts "Timeline: "
# puts tweets
# else
# puts "No tweets found -better follow some people!"
# end
if tweets.empty
puts "No tweets found -better follow some people!"
else
puts "Timeline: "
puts tweets
end
# Nil is false
# Not best
# if attachment.file_path != nil
# attachment.post
# end
if attachment.file_path
attachment.post
end
#In ruby only nil is false
name = ""
quantity = 0
tweets = []
unless name.length
warn "User name required "
end
# the statement above will never be false
#inline conditionals
#Not the best
if password.length < 8
fail "Password too short "
end
unless user_name
fail "No username set "
end
# Rather the below inline statements
fail "Password too short " if password.length < 8
fail "No user same set " unless username
#short circuit "AND"
# not the best...
if user
if user.signed_in?
end
end
# Rather this || If user is nil, second half never runs v
if user && user.signed_in?
end
#Methods and Classes
#Optional arguments
#Not optimal
def tweet(message, lat, long)
#
end
tweet("Practicing Ruby-Fu", nil, nil) #location isn't always used, so let's add defaults
def tweet (message, lat = nil, long = nil )
#
end
tweet ("Practicing Ruby-Fu") # location is now optional
def tweet(message, lat = nil, long = nil, reply_id = nil)
#
end
tweet("Practicing Ruby Fu", 28.55, -81.33, 227946) # calls to it are hard to read
tweet("Practicing Ruby Fu", nil, nil, 227946) # have to keep placeholders for arguments you're not using
#Hash arguments
def tweet(message, options = {})
status = Status.new
status.lat = options[:lat]
status.long = options[:long]
status.body = message
status.reply_id = options[:reply_id]
status.post
end
tweet("Practicing Ruby-Fu!",
:lat => 28.55,
:long => -81.33
:reply_id => 227946
)
# keys show meaning || all combined into options argument
>>>>>>> sinatra stuff and docker scripts
|
class CreateQuestoes < ActiveRecord::Migration
def change
create_table :questoes do |t|
t.text :enunciado
t.integer :prova_id
t.integer :disciplina_id
t.string :gabarito
t.integer :anulada
t.integer :texto_id
t.integer :quantidade_comentarios
t.timestamps null: false
end
end
end
|
class CreateOrderDetails < ActiveRecord::Migration[5.2]
def change
create_table :order_details do |t|
t.integer :order_id
t.string :book_id
t.float :price
t.string :cover_image
t.boolean :iscancel, :default => false
t.timestamps
end
end
end
|
require 'spec_helper'
describe "widgets/index" do
before(:each) do
assign(:widgets, [
stub_model(Widget,
:page_id => 1,
:template_location => "Template Location",
:resource_id => 2,
:resource_type => "Resource Type"
),
stub_model(Widget,
:page_id => 1,
:template_location => "Template Location",
:resource_id => 2,
:resource_type => "Resource Type"
)
])
end
it "renders a list of widgets" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "tr>td", :text => 1.to_s, :count => 2
assert_select "tr>td", :text => "Template Location".to_s, :count => 2
assert_select "tr>td", :text => 2.to_s, :count => 2
assert_select "tr>td", :text => "Resource Type".to_s, :count => 2
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.