text stringlengths 10 2.61M |
|---|
class MemeController < ApplicationController
before_action :authenticate_user!
def index
@memes = Meme.all
@meme = Meme.new
@search = Search.new(params[:search])
@memes = @search.search
if params[:search]
@category = search_params[:category]
@categories = Meme.where(category: @category)
render :display
display(@categories)
end
end
def new
@meme = Meme.new
end
def display(category)
@categories = category
end
def create
@meme = Meme.new meme_params
@meme.user = current_user
if @meme.save
redirect_to root_path
else
render :new
end
end
private
def meme_params
params.require(:meme).permit(:photo, :category)
end
private
def search_params
params.require(:search).permit(:category)
end
end
|
Rails.application.routes.draw do
namespace :file_upload_cache do
resources :cached_files, :only => :show
end
end
|
class AddCreatedByUserToSignatures < ActiveRecord::Migration[5.0]
def change
add_column :agreements, :created_by_user_id, :uuid
end
end
|
namespace :set do
# Run with rake set:super_user["dlee"]
desc "Grants user super_user and administrator rights"
task :super_user, [:login] => :environment do |t,args|
user = User.find_by_login(args.login)
Permission.create(role: Role.find_by_name('super user'), user: user)
Permission.create(role: Role.find_by_name('administrator'), user: user)
end
end
|
Rails.application.routes.draw do
devise_for :users
resource :users
root :to => 'visitors#index'
end
|
class AddCurrencyToBalances < ActiveRecord::Migration[6.0]
def change
add_column :balances, :currency, :text, null: false, default: "MXN"
remove_index :balances, [:date, :account_id]
add_index :balances, [:date, :account_id, :currency], unique: true, name: "one_currency_balance_per_day"
end
end
|
class MomentumCms::Template < ActiveRecord::Base
# == MomentumCms ==========================================================
include MomentumCms::BelongsToSite
include MomentumCms::ActAsPermanentRecord
self.table_name = 'momentum_cms_templates'
# == Constants ============================================================
# == Relationships ========================================================
has_many :pages,
dependent: :destroy
has_many :block_templates,
dependent: :destroy
# == Extensions ===========================================================
has_paper_trail
has_ancestry
# == Validations ==========================================================
validate :valid_liquid_value
validates :label,
presence: true
validates :identifier,
presence: true
validates :identifier,
uniqueness: { scope: :site_id }
# == Scopes ===============================================================
scope :has_yield,
-> {
where(has_yield: true)
}
# == Callbacks ============================================================
before_validation :update_has_yield
after_save :sync_block_identifiers,
:update_descendants_block_templates
# == Class Methods ========================================================
def self.ancestry_select(require_root = true, set = nil, path = nil)
momentum_cms_templates_tree = if set.nil?
MomentumCms::Template.all
else
set
end
select = []
momentum_cms_templates_tree.each do |momentum_cms_template|
next if require_root && !momentum_cms_template.is_root?
select << { id: momentum_cms_template.id, label: "#{path} #{momentum_cms_template.label}" }
select << MomentumCms::Template.ancestry_select(false, momentum_cms_template.children, "#{path}-")
end
select.flatten!
select.collect! { |x| [x[:label], x[:id]] } if require_root
select
end
def self.ancestor_and_self!(template)
if template && template.is_a?(MomentumCms::Template)
[template.ancestors.to_a, template].flatten.compact
else
[]
end
end
# == Instance Methods =====================================================
protected
def valid_liquid_value
tbs = TemplateBlockService.new(self)
unless tbs.valid_liquid?
errors.add(:value, 'is not a valid liquid template')
end
if !self.new_record? && !tbs.has_block?(MomentumCms::Tags::CmsYield) && self.has_children?
errors.add(:value, 'is not a valid parent liquid template, you must include {% cms_yield %}')
end
end
def sync_block_identifiers
if self.identifier_changed?
to = self.identifier_change.last
end
end
def update_has_yield
tbs = TemplateBlockService.new(self)
self.has_yield = tbs.has_block?(MomentumCms::Tags::CmsYield)
true
end
def update_descendants_block_templates
TemplateBlockService.new(self).create_or_update_block_templates_for_self!
end
end
|
require 'nokogiri'
require 'open-uri'
namespace :carriers do
task :load => :environment do
desc "Carriers loading into DB"
Carrier.delete_all
doc = Nokogiri::HTML(open('http://avrefdesk.com/two_letter_airline_codes.htm'))
items = doc.xpath('//table/tr[@height=17]')
objects = []
items.each do |item|
objects << {:name => item.search('td')[0].text.gsub(/\s{2,}/, " "), :code => item.search('td')[1].text}
end
Carrier.create(objects)
end
end |
# frozen_string_literal: true
module GraphQL
class Schema
class Directive < GraphQL::Schema::Member
class Deprecated < GraphQL::Schema::Directive
description "Marks an element of a GraphQL schema as no longer supported."
locations(GraphQL::Schema::Directive::FIELD_DEFINITION, GraphQL::Schema::Directive::ENUM_VALUE, GraphQL::Schema::Directive::ARGUMENT_DEFINITION, GraphQL::Schema::Directive::INPUT_FIELD_DEFINITION)
reason_description = "Explains why this element was deprecated, usually also including a "\
"suggestion for how to access supported similar data. Formatted "\
"in [Markdown](https://daringfireball.net/projects/markdown/)."
argument :reason, String, reason_description, default_value: Directive::DEFAULT_DEPRECATION_REASON, required: false
default_directive true
end
end
end
end
|
require 'test_helper'
class QuastionsControllerTest < ActionController::TestCase
setup do
@quastion = quastions(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:quastions)
end
test "should get new" do
get :new
assert_response :success
end
test "should create quastion" do
assert_difference('Quastion.count') do
post :create, quastion: { discription: @quastion.discription, image: @quastion.image, rate: @quastion.rate, topic: @quastion.topic }
end
assert_redirected_to quastion_path(assigns(:quastion))
end
test "should show quastion" do
get :show, id: @quastion
assert_response :success
end
test "should get edit" do
get :edit, id: @quastion
assert_response :success
end
test "should update quastion" do
put :update, id: @quastion, quastion: { discription: @quastion.discription, image: @quastion.image, rate: @quastion.rate, topic: @quastion.topic }
assert_redirected_to quastion_path(assigns(:quastion))
end
test "should destroy quastion" do
assert_difference('Quastion.count', -1) do
delete :destroy, id: @quastion
end
assert_redirected_to quastions_path
end
end
|
# /Users/rasheqrahman/.rvm/rubies/ruby-1.9.3-p194/bin/ruby
# load relevant gems
require 'rubygems'
require 'linkedin'
require 'markaby'
require 'pdfkit'
require 'yajl'
require 'eventbrite-client'
require 'yaml'
# load config variables from config.yml. Helps keep the code tidy!
APP_CONFIG = YAML.load_file("config.yml")
# Profile fields from https://developer.linkedin.com/documents/profile-fields
LinkedIn.default_profile_fields = APP_CONFIG['LinkedIn_profile_fields']
# Output files (html, pdf)
output_file_name = APP_CONFIG['file_prefix'] + ".html"
pdf_file_name = APP_CONFIG['file_prefix'] + ".pdf"
# Establish a connection to the LinkedIn API
client = LinkedIn::Client.new(APP_CONFIG['api_key'], APP_CONFIG['api_secret'])
# Use the api authorised values to gain access to the LinkedIn API
client.authorize_from_access(APP_CONFIG['api_token_authorized'], APP_CONFIG['api_secret_authorized'])
# Connect to the EventBrite API
eb_auth_tokens = { app_key: APP_CONFIG['eb_app_key'],
user_key: APP_CONFIG['eb_user_key'] }
eb_client = EventbriteClient.new(eb_auth_tokens)
# Load all the attendees for a single event specified in config.yml
attendee_list = Hash.new
response = eb_client.event_list_attendees(id: APP_CONFIG['eb_event_id'])
attendees = response["attendees"]
attendees.each do |attendee| # Load a single attendee's data
attendee = attendee["attendee"] # JSON structure requires you to index each attendee with "attendee"
first_name = attendee["first_name"] # Attendee's First Name - default Eventbrite field
last_name = attendee["last_name"] # Attendee's Last Name - default Eventbrite field
bio = attendee["answers"][1]["answer"]["answer_text"] # Attendee's Bio - I used an Evenbrite registration 'question' field to store the attendee's bio. I gave users an option to provide text bio or link to public LinkedInP profile URL. Eventbrite's JSON feed provides the values as "Answers"
title = attendee["job_title"] # Attendee's Job Title - default Eventbrite field
company = attendee["company"] # Attendee's Company - default Eventbrite field
if bio.include? ('linkedin.com') # Check if user provided a public LinkedIn Profile URL
url = bio # If bio is a LinkedIn public profile URL, assign URL to LinkedIn Profile URL and set to bio field to ""
bio = ""
else
url = "" # If bio is NOT a LinkedIn public profile URL, assign URL to LinkedIn Profile URL
end
attendee_key = first_name + last_name # Create an Attendee Key for each attendee's data that is a concatenation of the attendee's first and last name.
attendee_key = attendee_key.gsub(/\s+/, "").to_sym # Remove all spaces in the Attendee Key and convert it to a symbol
attendee_list[attendee_key] = {:first_name => first_name, :last_name => last_name, :url => url, :bio => bio, :title => title, :company => company}
end
# Use Markaby gem to build the HTML web page where the Linkedin Profile information wil be displayed
mab = Markaby::Builder.new
mab.html do
head {
title "LinkedIn Profiles"
link "rel" => "stylesheet", "href" => 'stylesheets/foundation.min.css' # Use foundation framework for css
link "rel" => "stylesheet", "href" => 'stylesheets/app.css'
}
body do
div.row do
div :class => "twelve columns" do
h1 "Attendee Profile Information"
end
hr
end
sorted_attendee_list = attendee_list.sort_by { |k, v| v[:last_name] } # Sort attendee list hash by last name
sorted_attendee_list.each do |attendee| # Access a single attendee
attendee = attendee[1] # Pick up the attendee's data
if attendee[:url] != "" # If the attendee's URL is not empty, use its URL as the public LinkedIn profile URL in the LinkedIn API
linkedin_url = attendee[:url].strip
if linkedin_url.start_with?('www') # People often cut and paste their public Linkedin profile URLs from their LinkedIn profile pages. These cut and paste URLs start with www but LinkedIn API requires URLs to start with 'http://', so this code creates a 'http' URL.
linkedin_url = "http://" + linkedin_url
end
user_profile = client.profile(:url => linkedin_url)
unless (user_profile.positions.nil? || user_profile.positions.total.zero?)
titles = user_profile.positions.all.map{|t| t.title} # Retrieve the current title of the LinkedIn profile from a collection of positions
companies = user_profile.positions.all.map{|c| c.company } # Retrieve the current company (organization) of the LinkedIn profile from a collection of positions
end
if user_profile.picture_url? #If the LinkedIn Profile has picture, retrieve the URL and the associated picture
div.row do
div :class => "two columns" do
a.th do
img "src" => user_profile.picture_url
end
end
end
end
end
div.row do
div :class => "twelve colunns" do
h2 attendee[:first_name] + " " + attendee[:last_name] # Print the first and last name of the Attendee using data from the Eventbrite registration
if attendee[:title].to_s.strip != "" && attendee[:company].to_s.strip != "" # Pull out the title and company name from the Eventbrite registration. If they are not blank, then print them out.
h3.subheader do
" #{attendee[:title]} at #{attendee[:company]}"
end
else
if titles and companies # If the Eventbrite title and company fields are blank, try retrieving the information from the LinkedIn profile.
h3.subheader do
titles.first + " at " + companies.first.name
end
end
end
if attendee[:bio] != "" # If the Eventbrite bio is not a LinkedIn profile URL, then retrieve the bio entered into the EventBrite registration
p attendee[:bio]
else
p user_profile.summary # If the Eventbrite bio is not a LinkedIn profile URL, then retrieve the LinkedIn profile summary data
a linkedin_url, "href" => linkedin_url
end
end
hr
end
end
end
end
File.open(output_file_name, 'w') { |file| file.write(mab.to_s) } # create the HTML file with all of the retrieved LinkedIn profiles. I do this as a backup so I can post the HTML file online as well.
kit = PDFKit.new(mab.to_s, :page_size => 'Letter') # create a letter-sized PDF file
kit.stylesheets << 'stylesheets/foundation.min.css' # use the Zurb Foundation css for formatting
file = kit.to_file(pdf_file_name)
|
module Refinery
module Testimonials
module Admin
class TestimonialsController < ::Refinery::AdminController
crudify :'refinery/testimonials/testimonial',
title_attribute: :flash_name,
:xhr_paging => false,
:paging => false,
:order => "position ASC",
include: [:translations]
helper :'refinery/testimonials/admin'
protected
def testimonial_params
params.require(:testimonial).permit(:name, :quote, :teaser, :company, :job_title, :website, :received_date, :received_channel, :picture_id, :position)
end
end
end
end
end
|
module Api
module V2
class RatesController < ApplicationController
skip_before_action :verify_authenticity_token, raise: false # TODO: Replace with verify_API_key
def create
if Rate.valid_params?(api_params)
ratable = api_params[:ratable_type] == 'Chain' ? Chain.find_by(id: api_params[:ratable_id]) : Exchange.find_by(id: api_params[:ratable_id])
if ratable
ratable.update(rates_source: api_params[:source])
api_params[:currencies].each do |currency|
rate = Rate.find_or_create_by(ratable_type: api_params[:ratable_type], ratable_id: api_params[:ratable_id], currency: currency[:currency])
unless rate.update_by_api(api_params[:source], api_params[:quote], currency)
render json: {status: 'wrong data for currency ' + currency[:currency]}
return
end
end
render json: {status: 'ok'}
else
render json: {errors: 'ratable not found'}
end
else
render json: {errors: 'invalid params'}
end
end
def api_params
# params.permit(:source, :ratable_type, :ratable_id, :base_currency, :quote_currency, :buy, :sell, :buy_markup, :sell_markup)
params.permit!
end
end
end
end
|
module ApplicationHelper
def error_notices(error_resource)
error_resource.errors.each do |error|
"<li>#{error}</li>"
end
end
def current_user_is_authorized_to_delete(resource)
logged_in? && current_user.id == resource.user_id
end
def current_user? (user)
logged_in? && current_user == user
end
end
|
class Card
include Comparable
attr_reader :suit, :value
def initialize(value, suit)
@value = value
@suit = suit
end
def <=>(other)
value_comp = self.value <=> other.value
value_comp == 0 ? self.suit <=> other.suit : value_comp
end
def to_s
"#{Value.to_s(@value)} of #{Suit.to_s(@suit)}"
end
end
module Suit
SUITS = { "DIAMOND" => 0, "CLUB" => 1, "HEART" => 2, "SPADE" => 3 }.freeze
def self.suit(key)
Suit::SUITS[key]
end
def self.to_s(value)
Suit::SUITS.key(value)
end
end
module Value
VALUES = {
"TWO" => 2,
"THREE" => 3,
"FOUR" => 4,
"FIVE" => 5,
"SIX" => 6,
"SEVEN" => 7,
"EIGHT" => 8,
"NINE" => 9,
"TEN" => 10,
"JACK" => 11,
"QUEEN" => 12,
"KING" => 13,
"ACE" => 14
}.freeze
def self.value(key)
Value::VALUES[key]
end
def self.to_s(value)
Value::VALUES.key(value)
end
end
|
class AddCourtDateToClient < ActiveRecord::Migration[5.1]
def change
add_column :clients, :next_court_date_at, :date, null: true
end
end
|
Given(/^I am a guest$/) do
end
When(/^I visit application homepage$/) do
visit home_path
end
Then(/^I should see the homepage layout$/) do
expect(page).to have_title("Happy New Year!")
expect(page).to have_selector("nav")
expect(page).to have_selector("header")
end
|
require 'redis'
require 'ohm'
module ConnectionHelpers
module Redis
extend self
def build_connection
@conncetion ||= ::Redis.new ConnectionHelpers.config_of('redis')
end
def build_ohm_connection
if @ohm_connection.nil?
::Ohm.connect :url => url
@ohm_connection = ::Ohm.redis
end
end
def url
redis = ConnectionHelpers.config_of('redis')
"redis://#{redis['host']}:#{redis['port']}"
end
end
end
|
=begin
Insights Service Approval APIs
APIs to query approval service
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
class Template < ApplicationRecord
acts_as_tenant(:tenant, :has_global_records => true)
has_many :workflows
validates :title, :presence => :title
def self.seed
template = find_or_create_by!(:title => 'Basic')
template.update_attributes(
:description => 'A basic approval workflow that supports multi-level approver groups through email notification',
:ext_ref => 'containers/ApprovalService/processes/BasicEmail'
)
end
end
|
class RemoveWinPercentageFromUsers < ActiveRecord::Migration
def change
remove_column :users, :win_percentage
end
end
|
FactoryGirl.define do
factory :group, class: "Group" do
name "Thaiband 🇹🇭"
project "Create a catchy music video"
submission "https://www.youtube.com/watch?v=y6120QOlsfU"
score "100"
end
factory :group2, class: "Group" do
name "ภาพยนตร์ที่ฉันรู้"
project "Search a movie that you think shows best side of humanity"
submission "www.imdb.com/title/tt0050083/"
end
end |
class AddSchoolIdToFeeInvoice < ActiveRecord::Migration
# adding school id to add db uniquess
def self.up
add_column :fee_invoices, :school_id, :integer
end
def self.down
remove_column :fee_invoices, :school_id
end
end
|
#
# Cookbook Name:: devpi
# Provider:: devpi_nginx_site
#
# Copyright 2013-2015, Dave Shawley
#
# 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.
#
include Chef::DSL::IncludeRecipe
def whyrun_supported?
true
end
use_inline_resources if defined? use_inline_resources
action :create do
service 'nginx' do
action :nothing
end
data_dir = new_resource.data_directory || ::File.join(
[new_resource.directory, 'data'])
bash "generate nginx config for #{new_resource.name}" do
cwd '/tmp'
code <<-EOC
#{new_resource.directory}/bin/devpi-server \
--serverdir #{data_dir} --outside-url='http://#{node['fqdn']}:80/' \
--port #{new_resource.port} --gen-config
install -o root -g #{new_resource.admin_group} -m 0664 \
gen-config/nginx-devpi.conf \
#{node['nginx']['dir']}/sites-available/#{new_resource.name}
rm -fr gen-config
chown -R #{new_resource.daemon_user} #{data_dir}
chgrp -R #{new_resource.admin_group} #{data_dir}
EOC
end
if new_resource.enable
nginx_site new_resource.name do
enable true
end
end
end
|
require 'rails_helper'
RSpec.describe Store, type: :model do
let(:populated_store) { described_class.new(uuid: '32db7ef9-1144-464e-b561-9c8880b41d28', hash_store: { hash_key: :key_value }) }
it "stores a SecureRandom.uuid" do
store = described_class.new(uuid: '8002e436-dc3a-452e-a4fd-9ba466c737b1')
expect(store.uuid).to eql '8002e436-dc3a-452e-a4fd-9ba466c737b1'
end
it "serializes hash_store to retain hash type" do
store = described_class.new(hash_store: {})
expect(store.hash_store).to be_a(Hash)
end
it "stores an empty hash" do
store = described_class.new(hash_store: {})
expect(store.hash_store).to be_empty
end
it "stores a populated hash" do
store = described_class.new(hash_store: { key: "value" })
expect(store.hash_store[:key]).to eql "value"
end
it "saves the uuid to the database" do
store = described_class.new(uuid: '8002e436-dc3a-452e-a4fd-9ba466c737b1')
expect(store.save).to be true
end
it "generates a uuid before save" do
store = described_class.new
store.save
expect(store.uuid).to be_a(String)
end
it "saves the hash_store to the database" do
store = described_class.new(hash_store: { key: "value" })
expect(store.save).to be true
end
it "loads the uuid from the database" do
expect(populated_store.uuid).to eql '32db7ef9-1144-464e-b561-9c8880b41d28'
end
it "loads the hash_store from the database" do
expect(populated_store.hash_store).to eql(hash_key: :key_value)
end
end
|
class Image < ActiveRecord::Base
has_many :image_comments
has_many :comments, dependent: :destroy
has_many :favorites, dependent: :destroy
has_many :users, through: :favorites
validates :url, uniqueness: true
def self.search term
images = Image.where("keywords LIKE ?", "%#{term}%")
where(content_type: 'Image', content_id: images)
end
end
|
require 'rspec'
require 'numbers_to_words'
describe 'translate_number' do
it 'returns the word form of an integer below 9' do
translate_number(7).should eq 'seven'
end
it 'returns the word form of an integer below 19' do
translate_number(13).should eq 'thirteen'
end
it 'returns the word form of any integer below 100' do
translate_number(87).should eq 'eighty seven'
end
it 'returns the word form of any integer below 100, for numbers ending in 0' do
translate_number(50).should eq 'fifty'
end
it 'returns the word form of any integer below 1000' do
translate_number(175).should eq 'one hundred seventy five'
end
it 'returns the word form of any integer below 1000, for numbers ending in a teen' do
translate_number(117).should eq 'one hundred seventeen'
end
it 'returns the word form of any integer below 1 million' do
translate_number(198345).should eq 'one hundred ninety eight thousand three hundred forty five'
end
it 'returns the word form of any integer below 1 billion' do
translate_number(119310254).should eq 'one hundred nineteen million three hundred ten thousand two hundred fifty four'
end
it 'returns the word form of any integer below 1 trillion' do
translate_number(19303849404).should eq 'nineteen billion three hundred three million eight hundred forty nine thousand four hundred four'
end
it 'returns the word form of any integer below 1 trillion, for numbers with lots of zeroes' do
translate_number(19300000404).should eq 'nineteen billion three hundred million four hundred four'
end
end |
# Write a program that will take a number from 0 to 999,999,999,999 and spell out that number in British English.
# In other words, if the input to the program is 12345 then the output should be twelve thousand three hundred forty-five.
class Say
ONES = %w{NO one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty}
TENS = %w{NO NO twenty thirty forty fifty sixty seventy eighty ninety}
IONS = ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion"]
attr_accessor :number
def initialize(num)
@number = num
end
def in_english
return "zero" if @number == 0
num_str = @number.to_s
num_digits = num_str.size
# sanitize so num_digits is divisible by 3
num_str = ("00" + num_str) if num_digits % 3 == 1
num_str = ("0" + num_str) if num_digits % 3 == 2
# separate number string into array of three digits each
num_array = num_str.scan(/.../)
word = ""
index = 0
num_array.reverse_each do |three_digit_str|
added = if three_digit_str == "000"
" and"
else
hundreds(three_digit_str) + " " + IONS[index]
end
word = added + " " + word
index += 1
end
word.strip.gsub(/\s+/," ").gsub(/( and)+/, " and").gsub(/ and$/, "")
end
def tens(two_digit_str)
first_digit = two_digit_str[0].to_i
second_digit = two_digit_str[1].to_i
both_digits = two_digit_str.to_i
if two_digit_str == "00"
""
elsif both_digits <= 20
ONES[both_digits]
else
added = second_digit==0 ? "" : ("-" + ONES[second_digit])
TENS[first_digit] + added
end
end
def hundreds(three_digit_str)
first_digit = three_digit_str[0].to_i
next_two_str = three_digit_str[1,2]
if three_digit_str.between?("000","099")
tens(next_two_str)
elsif three_digit_str.between?("100","999")
and_word = next_two_str=="00" ? "" : "and "
ONES[first_digit] + " hundred " + and_word + tens(next_two_str)
end
end
end
|
module PUBG
class Telemetry
require "pubg/telemetry/log_player_login"
require "pubg/telemetry/log_player_create"
require "pubg/telemetry/log_player_position"
require "pubg/telemetry/log_player_attack"
require "pubg/telemetry/log_item_equip"
require "pubg/telemetry/log_item_pickup"
require "pubg/telemetry/log_item_unequip"
require "pubg/telemetry/log_vehicle_ride"
def initialize(args)
@args = args
end
def original
@args
end
def playerLogin
@args.select {|data| data["_T"] == "LogPlayerLogin" }
end
def playerCreate
@args.select {|data| data["_T"] == "LogPlayerCreate" }
end
def playerPosition
@args.select {|data| data["_T"] == "LogPlayerPosition" }
end
def playerAttack
@args.select {|data| data["_T"] == "LogPlayerAttack" }
end
def itemPickup
@args.select {|data| data["_T"] == "LogItemPickup" }
end
def itemEquip
@args.select {|data| data["_T"] == "LogItemEquip" }
end
def itemUnequip
@args.select {|data| data["_T"] == "LogItemUnequip" }
end
def vehicleRide
@args.select {|data| data["_T"] == "LogVehicleRide" }
end
def LogMatchDefinition
end
def LogMatchStart
end
def LogGameStatePeriodic
end
def LogVehicleLeave
end
def LogPlayerTakeDamage
end
def LogPlayerLogout
end
def LogItemAttach
end
def LogItemDrop
end
def LogPlayerKill
end
def LogItemDetach
end
def LogItemUse
end
def LogCarePackageSpawn
end
def LogVehicleDestroy
end
def LogCarePackageLand
end
def LogMatchEnd
end
end
end |
input = File.read("/Users/hhh/JungleGym/advent_of_code/2021/inputs/day04.in").split "\n\n"
# input = File.read("/Users/hhh/JungleGym/advent_of_code/2021/inputs/day04test.in").split "\n\n"
nums = input.shift
nums = nums.split ","
p nums
class Board
attr_reader :board
attr_accessor :marks, :last_num, :won
def initialize str
@board = str.split("\n").map { |row| row.split " " }
@marks = Array.new(5) { Array.new(5) }
end
def mark num
board.each_with_index do |row, i|
row.each_with_index do |y, j|
if y == num
self.marks[i][j] = true
@last_num = num
end
end
end
end
def winning?
has_row = marks.any? { |row| row.all? { |m| m == true } }
has_col = marks.transpose.any? { |row| row.all? { |m| m == true } }
has_row || has_col
end
def score
sum = 0
marks.each_with_index do |row, i|
row.each_with_index do |y, j|
if y.nil?
sum += board[i][j].to_i
end
end
end
sum * last_num.to_i
end
end
boards = input.map do |s|
Board.new s
end
count = 0
nums.each do |n|
boards.each do |b|
b.mark n
if b.winning? && !b.won
b.won = true
count += 1
if count == 1
p "Part 1: #{b.score}"
end
if count == boards.size
p "Part 2: #{b.score}"
end
end
end
end
|
class Circle < ActiveRecord::Base
attr_accessible :title, :user_id
validates_presence_of :title
belongs_to :master, :class_name => 'User', :foreign_key => "user_id"
belongs_to :friend, :class_name => 'User', :foreign_key => "friend_id"
end
|
class Snake < ExObj
@@STATE_WAITING = 0
@@STATE_HISSING = 1
@@STATE_BITING = 2
@@STATE_BITTEN = 3
def initialize()
super("snake")
@state = @@STATE_WAITING
end
def getDescription()
return "A poisonous snake."
end
def resetState()
@state = @@STATE_WAITING
end
def timerTick()
if(@state < @@STATE_BITTEN)
@state = @state + 1
end
end
def getStateDescription
if @state == @@STATE_WAITING
return "The snake sits coiled."
elsif @state == @@STATE_HISSING
return "The snake hisses!"
elsif @state == @@STATE_BITING
return "The snake bites!"
elsif @state == @@STATE_BITTEN
return "The snake watches you carefully."
else
return "The snake does something weird: #{@state}"
end
end
def isBiting?()
return @state == @@STATE_BITING
end
end |
# What output does this code print? Fix this class so that there are no surprises waiting in store for the unsuspecting developer.
class Pet
attr_reader :name
def initialize(name)
@name = name.to_s
end
def to_s
# @name.upcase!
"My name is #{@name.upcase}."
end
end
name = 'Fluffy'
fluffy = Pet.new(name)
puts fluffy.name
puts fluffy
puts fluffy.name
puts name
# output:
# Fluffy
# My name is FLUFFY
# FLUFFY
# Fluffy
# Change made:
# remove destructive method call upcase!
# instead use upcase method in the method return |
# # -*- mode: ruby -*-
# # vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
VAGRANT_BOX = 'ubuntu/bionic64'# Memorable name for your
VM_NAME = 'al-yw-vm'# VM User — 'vagrant' by default
VM_USER = 'vagrant'# Username
# VM_PORT = 8080
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
#config.vm.provider "docker"
config.vm.provider "virtualbox"
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.box = VAGRANT_BOX
#config.vbguest.auto_update = true
#config.vbguest.auto_reboot = true
# Actual machine name
config.vm.hostname = VM_NAME # Set VM name in Virtualbox
#not sure if i need this
#config.vm.network "forwarded_port", guest: 8080, host: 7000, host_ip: "127.0.0.1", auto_correct: true
# If we want to stick with a vagrant solution use below for dev
#config.vm.provision "docker", run: "once"
# Set VM name in Virtualbox
#config.vm.provider "virtual-box" do |v|
#DHCP — commert this out if planning on using NAT instead
#config.vm.network "private_network", type: "dhcp" # # Port forwarding — uncomment this to use NAT instead of DHCP
# config.vm.network "forwarded_port", guest: 80, host: VM_PORT # Sync folder
config.vm.provision "ansible_local" do |ansible|
ansible.config_file = "/vagrant/ansible.cfg"
ansible.extra_vars = { ansible_python_interpreter:"/usr/bin/python3" }
ansible.galaxy_role_file = "provisioning/requirements.yml"
ansible.galaxy_command = "ansible-galaxy install --role-file=%{role_file}"
ansible.playbook = "playbooks/al-playbook.yml"
end
end
|
require 'account'
describe 'Withdrawal feature tests' do
let(:account) { Account.new }
it 'allows user to deposit funds' do
account.deposit(1000)
expect(account.balance).to eq(1000)
end
it 'throws error if user tries to deposit invalid amount' do
expect { account.deposit(-5) }
.to raise_error('Amount must be greater than zero')
end
it 'throws error unless user enters a number' do
expect { account.deposit('cash') }
.to raise_error('Please enter a valid amount')
end
end
|
require 'rails_helper'
describe PlayerVsPlayer do
let(:primary) { FactoryBot.create :player }
let(:secondary) { FactoryBot.create :player }
let(:day) { DateTime.now.beginning_of_month.strftime('%m/%d/%y') }
subject { PlayerVsPlayer.new(primary, secondary) }
context '#games_won' do
let(:expected_games_won) { [{x: day, y: 1}, {x: day, y: 3}] }
before do
3.times { GameCreator.new(primary.id, secondary.id).save }
GameCreator.new(secondary.id, primary.id).save
end
it 'returns the games won each day played' do
expect(subject.games_won).to include expected_games_won
end
end
end
|
module Concerns::EngineMaster::Validation
extend ActiveSupport::Concern
included do
validates :name, uniqueness: true, presence: true
end
end
|
require "spec_helper"
require "stanford_corenlp_xml_adapter"
RSpec.describe StanfordCorenlpXmlAdapter do
it "has a version number" do
expect(StanfordCorenlpXmlAdapter::VERSION).not_to be nil
end
describe ".doc" do
it "returns a Nokogiri object" do
expect(StanfordCorenlpXmlAdapter.doc(valid_xml).class)
.to eq Nokogiri::XML::Document
end
it "raises exception if the input doc is not " +
"empty and not valid xml" do
expect{StanfordCorenlpXmlAdapter.doc(invalid_xml)}
.to raise_exception StanfordCorenlpXmlAdapter::InvalidXML
end
it "raises exception if the input doc does not " +
"contain <document> node" do
expect{StanfordCorenlpXmlAdapter.doc(valid_xml_no_doc)}
.to raise_exception StanfordCorenlpXmlAdapter::InvalidXML
end
end
end
|
require './lib/terms'
require 'oj'
describe "Terms" do
before :all do
terms_stub = Oj.load( '{
"@mroth":"Matthew Rothenberg",
"@kellan":"Kellan Elliott-McCrea",
"@curlyjazz":"Jasmine Trabelsi"
}' )
@terms = Terms.new(terms_stub)
end
context "after fresh initialization" do
it "should not be empty" do
@terms.list.count.should be > 0
end
end
context "when normalizing terms" do
it "should convert from hashtag nomenclature to twitter handle" do
@terms.normalize("MatthewRothenberg").should eq "@mroth"
end
it "should convert from Full Name nomenclature to twitter handle" do
@terms.normalize("Matthew Rothenberg").should eq "@mroth"
end
it "should leave a twitter handle alone" do
@terms.normalize("@mroth").should eq "@mroth"
end
end
end |
module DJ
class Worker
attr_accessor :worker_class_name
class << self
def enqueue(*args)
self.new(*args).enqueue!
end
end
def dj_object=(dj)
@dj_object = dj.id
end
def dj_object
DJ.find(@dj_object)
end
def worker_class_name
if self[:id]
@worker_class_name ||= File.join(self.class.to_s.underscore, self[:id].to_s)
else
@worker_class_name ||= self.class.to_s.underscore
end
end
def enqueue!(priority = self.priority, run_at = self.run_at)
job = DJ.enqueue(:payload_object => self, :priority => priority, :run_at => run_at)
job.worker_class_name = self.worker_class_name
job.user_id = self.user_id unless self.user_id.nil?
job.save
return job
end
alias_method :save, :enqueue!
# Needs to be implemented by subclasses! It's only here
# so people can hook into it.
def perform
raise NoMethodError.new('perform')
end
def clone # :nodoc:
cl = super
cl.run_at = nil
cl
end
end # Worker
end # DJ |
# XSD4R - XMLScan XML parser library.
# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 2003, or any later version.
require 'xsd/xmlparser'
require 'xmlscan/scanner'
module XSD
module XMLParser
class XMLScanner < XSD::XMLParser::Parser
include XMLScan::Visitor
def do_parse(string_or_readable)
@attrs = {}
@curattr = nil
@scanner = XMLScan::XMLScanner.new(self)
@scanner.kcode = XSD::Charset.charset_str(charset) if charset
@scanner.parse(string_or_readable)
end
def scanner_kcode=(charset)
@scanner.kcode = XSD::Charset.charset_str(charset) if charset
self.xmldecl_encoding = charset
end
ENTITY_REF_MAP = {
'lt' => '<',
'gt' => '>',
'amp' => '&',
'quot' => '"',
'apos' => '\''
}
def parse_error(msg)
raise ParseError.new(msg)
end
def wellformed_error(msg)
raise NotWellFormedError.new(msg)
end
def valid_error(msg)
raise NotValidError.new(msg)
end
def warning(msg)
p msg if $DEBUG
end
# def on_xmldecl; end
def on_xmldecl_version(str)
# 1.0 expected.
end
def on_xmldecl_encoding(str)
self.scanner_kcode = str
end
# def on_xmldecl_standalone(str); end
# def on_xmldecl_other(name, value); end
# def on_xmldecl_end; end
# def on_doctype(root, pubid, sysid); end
# def on_prolog_space(str); end
# def on_comment(str); end
# def on_pi(target, pi); end
def on_chardata(str)
characters(str)
end
# def on_cdata(str); end
def on_etag(name)
end_element(name)
end
def on_entityref(ref)
characters(ENTITY_REF_MAP[ref])
end
def on_charref(code)
characters([code].pack('U'))
end
def on_charref_hex(code)
on_charref(code)
end
# def on_start_document; end
# def on_end_document; end
def on_stag(name)
@attrs = {}
end
def on_attribute(name)
@attrs[name] = @curattr = ''
end
def on_attr_value(str)
@curattr << str
end
def on_attr_entityref(ref)
@curattr << ENTITY_REF_MAP[ref]
end
def on_attr_charref(code)
@curattr << [code].pack('U')
end
def on_attr_charref_hex(code)
on_attr_charref(code)
end
# def on_attribute_end(name); end
def on_stag_end_empty(name)
on_stag_end(name)
on_etag(name)
end
def on_stag_end(name)
start_element(name, @attrs)
end
add_factory(self)
end
end
end
|
FactoryBot.define do
factory :lessonplan do
name "MyString"
attachment "MyString"
teacher nil
end
end
|
require 'test_helper'
describe Flyer do
it 'has 2 object from fixtures' do
Flyer.count.must_equal 3
end
it 'title should be more then 5 symbols' do
Flyer.new(title: 'abcde').must_be :valid?
end
end
|
describe Exporter::Overtimes do
include_context "exporter"
let!(:overtime_kirk) { create(:overtime_kirk) }
it "exports" do
export
expect(record["employee_id"]).to eql("1701")
expect(record["name"]).to eql("Kirk,James")
expect(record["rank"]).to eql("SgtDet")
expect(record["assigned"]).to eql("A-1 DCU SQUAD")
expect(record["charged"]).to eql("A-1 DCU SQUAD")
expect(record["date"]).to eql("2014-01-02")
expect(record["code"]).to eql("280")
expect(record["description"]).to eql("COURT:TRIAL")
expect(record["start_time"]).to eql("0830")
expect(record["end_time"]).to eql("1030")
expect(record["worked_hours"]).to eql("2.0")
expect(record["ot_hours"]).to eql("4.0")
expect(record["officer_employee_id"]).to eql("1701")
end
end
|
require 'digest/sha1'
class User < ActiveRecord::Base
RESERVED_LOGINS = %w(home unknown_user user_has_no_url login signup activate_account logout admin forgotten_password fyp unfyp login_express fyp_express unfyp_express legal_info)
attr_accessor :password
attr_accessor :terms_of_use_acceptance
attr_accessor :new_password
validates_presence_of :login,
:message => 'You must choose a <strong>login</strong>'
validates_length_of :login,
:within => 3..40,
:if => Proc.new { |user| !user.login.blank?},
:too_long => 'The <strong>login</strong> is too long. Cannot have more than 40 characters',
:too_short => 'The <strong>login</strong> is too short. Cannot have less than 3 characters'
validates_format_of :login,
:with => /\A(\w|_)+\z/,
:if => Proc.new { |user| !user.login.blank?},
:message => "The <strong>login</strong> contains characters that aren't allowed. " +
"Use only letters, numbers or underscores"
validates_uniqueness_of :login,
:case_sensitive => false,
:message => 'We\'re sorry. The <strong>login</strong> has already been taken. Try another one'
validates_exclusion_of :login, :in => RESERVED_LOGINS,
:message => "We're sorry. That <strong>login</strong> cannot be taken by anyone. Try another one"
validates_presence_of :password,
:if => Proc.new { |user| user.new_password && !user.login.blank?},
:message => 'You must choose a <strong>password</strong>'
validates_length_of :password,
:within => 4..32,
:if => Proc.new { |user| user.new_password && !user.password.blank? },
:too_long => 'The <strong>password</strong> is too long. Cannot have more than 32 characters',
:too_short => 'The <strong>password</strong> is too short. Cannot have less than 4 characters'
validates_confirmation_of :password,
:if => Proc.new { |user| user.new_password && !user.password.blank? },
:message => 'The <strong>password</strong> doesn\'t match the <strong>confirmation</strong>'
validates_presence_of :email,
:message => 'You must provide an <strong>e-mail</strong>'
validates_uniqueness_of :email,
:case_sensitive => false,
:message => 'We\'re sorry. That <strong>email</strong> is already being used. Try another one'
validates_acceptance_of :terms_of_use_acceptance,
:message => 'You must accept the <strong>terms of use</strong>'
validates_format_of :email,
:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
:message => 'The <strong>e-mail</strong> seems to be wrong'
before_create :make_activation_code
before_save :encrypt_password
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
def self.authenticate(login, password)
u = find :first, :conditions => ['login = ? and activated_at IS NOT NULL', login]
u && u.authenticated?(password) ? u : nil
end
# Encrypts some data with the salt.
def self.encrypt(password, salt)
Digest::SHA1.hexdigest("--#{salt}--#{password}--")
end
# Encrypts the password with the user salt
def encrypt(password)
self.class.encrypt(password, salt)
end
def authenticated?(password)
crypted_password == encrypt(password)
end
def remember_token?
remember_token_expires_at && Time.now.utc < remember_token_expires_at
end
# These create and unset the fields required for remembering users between browser closes
def remember_me
self.remember_token_expires_at = 4.weeks.from_now.utc
self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
save(false)
end
def forget_me
self.remember_token_expires_at = nil
self.remember_token = nil
save(false)
end
# Activates the user in the database.
def activate
@activated = true
update_attributes(:activated_at => Time.now.utc, :activation_code => nil)
end
# Returns true if the user has just been activated.
def recently_activated?
@activated
end
#
#
#
def new_random_password
self.password= Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--")[0,8]
password = self.password_confirmation = self.password
self.new_password = false
self.save
password
end
protected
# before filter
def encrypt_password
return if password.blank?
self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
self.crypted_password = encrypt(password)
end
def password_required?
crypted_password.blank? || !password.blank?
end
def make_activation_code
self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
end
end
|
require_relative '../helpers/palindrome_counter'
class OEIS
# Number of strings of length n over a 7 letter alphabet that begin with a
# nontrivial palindrome.
def self.a249640(n)
palindrome_count(n, 7)
end
end
|
module GithubService
class DeleteParser < BaseParser
def able_to_parse?
@event == 'delete'
end
private
def username
@params[:sender][:login]
end
def type
@params[:ref_type]
end
def name
@params[:ref]
end
def message
%(#{username} deleted #{type} "#{name}")
end
def url
@params[:repository][:html_url]
end
end
end
|
#encoding: utf-8
class Fila < ActiveRecord::Base
# attr_accessible :title, :body
validates_presence_of :nome, :message => "preenchimento obrigatório"
validates_presence_of :cpf, :message => "preenchimento obrigatório"
validates_presence_of :rg, :message => "preenchimento obrigatório"
validates_presence_of :celular, :message => "preenchimento obrigatório"
validates_presence_of :email, :message => "preenchimento obrigatório"
validates_presence_of :endereco, :message => "preenchimento obrigatório"
validates_presence_of :numero, :message => "preenchimento obrigatório"
validates_presence_of :complemento, :message => "preenchimento obrigatório"
validates_presence_of :bairro, :message => "preenchimento obrigatório"
validates_presence_of :cep, :message => "preenchimento obrigatório"
validates_presence_of :aluno, :message => "preenchimento obrigatório"
validates_presence_of :tamanho, :message => "preenchimento obrigatório"
after_update :diminuir_fila
after_create :enviar_notificaoes
belongs_to :esporte_full, :class_name => "Esporte", :foreign_key => "esporte"
def enviar_notificaoes
AvisoMailer.notificar_secretaria(self).deliver
AvisoMailer.notificar_pai_aguardando(self).deliver
end
def diminuir_fila
if self.status == 3
esporte = Esporte.find(self.esporte)
esporte.vagas = esporte.vagas - 1
esporte.save
AvisoMailer.notificar_pai_confirmacao(self).deliver
end
end
def status_str
case self.status
when 1 then "Aguarando confirmação"
when 3 then "Matrículado"
end
end
end
|
#!/usr/bin/ruby
require 'uri'
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
if ENV['BITRISE_GIT_BRANCH'] != 'master'
puts 'Not on main branch, skipping notification'
exit 0
end
env_sdk_failure_notif_endpoint = ENV['SDK_FAILURE_NOTIFICATION_ENDPOINT']
env_sdk_failure_notif_endpoint_hmac_key = ENV['SDK_FAILURE_NOTIFICATION_ENDPOINT_HMAC_KEY']
if !env_sdk_failure_notif_endpoint || !env_sdk_failure_notif_endpoint_hmac_key
puts 'Two environment variables required: `SDK_FAILURE_NOTIFICATION_ENDPOINT` and `SDK_FAILURE_NOTIFICATION_ENDPOINT_HMAC_KEY`'
puts 'Visit http://go/ios-sdk-failure-notification-endpoint for details'
exit 102
end
uri = URI(env_sdk_failure_notif_endpoint)
hmac_key = Base64.decode64(env_sdk_failure_notif_endpoint_hmac_key)
http = Net::HTTP.new(uri.host, uri.port).tap do |http|
http.use_ssl = true
end
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
params = {
project: 'RUN_MOBILESDK',
summary: "Job failed: #{ENV['BITRISE_TRIGGERED_WORKFLOW_TITLE']}",
description: "Please investigate the failure: #{ENV['BITRISE_BUILD_URL']}",
components: %w[iOS]
}
req.body = params.to_json
# Auth
digest = OpenSSL::Digest.new('sha256')
header_data = OpenSSL::HMAC.digest(digest, hmac_key, req.body)
header_data_64 = Base64.strict_encode64(header_data)
req.add_field 'X-TM-Signature', header_data_64
http.request(req)
|
require 'bigdecimal/util'
namespace :alerts do
desc "User can receive alert based on MAX_NEW value"
task min: :environment do
@alerts = Alert.all
@alerts.each do |alert|
unless alert.expired?
present_value = alert.get_value('price_usd').to_d
new_percent_delta = alert.percent_changed
if (alert.direction == "up" && new_percent_delta > alert.min_new) || (alert.direction == "down" && new_percent_delta < alert.min_new)
alert.send_message("#{alert.currency} is currently #{alert.direction} by #{new_percent_delta}%")
end
end
end
end
end |
class Sebastian::Item::FlowBox < Sebastian::Item
@@defaults = {
flowbox_orientation: Clutter::FlowOrientation::VERTICAL
}.merge(@@defaults)
def initialize(options = {})
super()
@state[:children] = []
@state[:options] = {
orientation: @@defaults[:flowbox_orientation]
}.merge(options)
on_init do |state, main|
box = Clutter::Actor.new
box.layout_manager = Clutter::FlowLayout.new state[:options][:orientation]
state[:actor] = box
init_children(main)
end
on_update do |state, main|
state[:children].each do |child|
child.update(main)
end
end
end
def init_children(main)
@state[:children].each do |child|
child.init(main)
add_child(child)
end
end
def add_child(child)
kids = @state[:children]
kids.push(child) unless kids.include? child
#^ That guarantees @state[:children] to be
# a unique set, but if a child is added twice
# it means that the array won't reflect the
# actual layout as seen on screen.
if @state.member? :actor
act = child.state[:actor]
if act.is_a? Clutter::Actor
@state[:actor].add_child(act)
else
puts "Expected Clutter::Actor, found #{act.inspect}."
end
end
end
end
|
class NewsfeedsController < ApplicationController
# GET /newsfeeds
# GET /newsfeeds.xml
def index
@newsfeeds = Newsfeed.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @newsfeeds }
end
end
# GET /newsfeeds/1
# GET /newsfeeds/1.xml
def show
@newsfeed = Newsfeed.find params[:id], :include => :newsitems
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @newsfeed }
end
end
# GET /newsfeeds/new
# GET /newsfeeds/new.xml
def new
@newsfeed = Newsfeed.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @newsfeed }
end
end
# GET /newsfeeds/1/edit
def edit
@newsfeed = Newsfeed.find(params[:id])
end
# POST /newsfeeds
# POST /newsfeeds.xml
def create
@newsfeed = Newsfeed.new(params[:newsfeed])
respond_to do |format|
if @newsfeed.save
flash[:notice] = 'Newsfeed was successfully created.'
format.html { redirect_to(@newsfeed) }
format.xml { render :xml => @newsfeed, :status => :created, :location => @newsfeed }
else
format.html { render :action => "new" }
format.xml { render :xml => @newsfeed.errors, :status => :unprocessable_entity }
end
end
end
# PUT /newsfeeds/1
# PUT /newsfeeds/1.xml
def update
@newsfeed = Newsfeed.find(params[:id])
respond_to do |format|
if @newsfeed.update_attributes(params[:newsfeed])
flash[:notice] = 'Newsfeed was successfully updated.'
format.html { redirect_to(@newsfeed) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @newsfeed.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /newsfeeds/1
# DELETE /newsfeeds/1.xml
def destroy
@newsfeed = Newsfeed.find(params[:id])
@newsfeed.destroy
respond_to do |format|
format.html { redirect_to(newsfeeds_url) }
format.xml { head :ok }
end
end
end
|
class MakeLawsPublic < ActiveRecord::Migration
def up
Agenda.transaction do
# make all new laws public
puts "making #{Agenda.where(:parliament_id => 2).count} laws public"
start = Time.now
index = 0
Agenda.where(:parliament_id => 2).find_each(:batch_size => 100) do |agenda|
puts "-- index = #{index} at #{Time.now}" if index % 100 == 0
index += 1
agenda.not_update_vote_count = true
agenda.is_public = 1
agenda.made_public_at = Time.now
if !agenda.valid?
puts "*** agenda errors (#{agenda.xml_id}): #{agenda.errors.full_messages}"
raise ActiveRecord::Rollback
return
end
agenda.save
end
puts "time to make laws public = #{Time.now - start} seconds"
puts "updating vote count for delegates"
AllDelegate.update_vote_counts(2)
end
end
def down
Agenda.where(:parliament_id => 2).update_all(:is_public => false)
AllDelegate.update_vote_counts(2)
end
end
|
RSpec.describe Hanami::Controller do
describe ".configuration" do
before do
Hanami::Controller.unload!
module ConfigurationAction
include Hanami::Action
end
end
after do
Object.send(:remove_const, :ConfigurationAction)
end
it "exposes class configuration" do
expect(Hanami::Controller.configuration).to be_kind_of(Hanami::Controller::Configuration)
end
it "handles exceptions by default" do
expect(Hanami::Controller.configuration.handle_exceptions).to be(true)
end
it "inheriths the configuration from the framework" do
expected = Hanami::Controller.configuration
actual = ConfigurationAction.configuration
expect(actual).to eq(expected)
end
end
describe ".configure" do
before do
Hanami::Controller.unload!
end
after do
Hanami::Controller.unload!
end
it "allows to configure the framework" do
Hanami::Controller.class_eval do
configure do
handle_exceptions false
end
end
expect(Hanami::Controller.configuration.handle_exceptions).to be(false)
end
it "allows to override one value" do
Hanami::Controller.class_eval do
configure do
handle_exception ArgumentError => 400
end
configure do
handle_exception NotImplementedError => 418
end
end
expect(Hanami::Controller.configuration.handled_exceptions).to include(ArgumentError)
end
end
describe ".duplicate" do
before do
Hanami::Controller.configure { handle_exception ArgumentError => 400 }
module Duplicated
Controller = Hanami::Controller.duplicate(self)
end
module DuplicatedCustom
Controller = Hanami::Controller.duplicate(self, "Controllerz")
end
module DuplicatedWithoutNamespace
Controller = Hanami::Controller.duplicate(self, nil)
end
module DuplicatedConfigure
Controller = Hanami::Controller.duplicate(self) do
reset!
handle_exception StandardError => 400
end
end
end
after do
Hanami::Controller.unload!
Object.send(:remove_const, :Duplicated)
Object.send(:remove_const, :DuplicatedCustom)
Object.send(:remove_const, :DuplicatedWithoutNamespace)
Object.send(:remove_const, :DuplicatedConfigure)
end
it "duplicates the configuration of the framework" do
actual = Duplicated::Controller.configuration
expected = Hanami::Controller.configuration
expect(actual.handled_exceptions).to eq(expected.handled_exceptions)
end
it "duplicates a namespace for controllers" do
expect(defined?(Duplicated::Controllers)).to eq("constant")
end
it "generates a custom namespace for controllers" do
expect(defined?(DuplicatedCustom::Controllerz)).to eq("constant")
end
it "does not create a custom namespace for controllers" do
expect(defined?(DuplicatedWithoutNamespace::Controllers)).to be(nil)
end
it "duplicates Action" do
expect(defined?(Duplicated::Action)).to eq("constant")
end
it "sets action_module" do
configuration = Duplicated::Controller.configuration
expect(configuration.action_module).to eq(Duplicated::Action)
end
it "optionally accepts a block to configure the duplicated module" do
configuration = DuplicatedConfigure::Controller.configuration
expect(configuration.handled_exceptions).to_not include(ArgumentError)
expect(configuration.handled_exceptions).to include(StandardError)
end
end
end
|
require 'rails_helper'
describe "editing" do
before(:each) do
@user = create(:user_with_recipes)
sign_in
visit edit_user_recipe_path @user, @user.recipes.first
end
it "allows you to delete recipes" do
expect(@user.recipes.count).to eq(5)
click_link 'Delete Recipe'
Capybara.current_driver = :selenium
page.evaluate_script('window.confirm = function() { return true; }')
Capybara.use_default_driver
expect(page).to have_content "Recipe removed"
expect(@user.recipes.count).to eq(4)
end
end |
require 'builder'
require 'saml_idp/algorithmable'
require 'saml_idp/signable'
module SamlIdp
class AssertionBuilder
include Algorithmable
include Signable
attr_accessor :reference_id
attr_accessor :issuer_uri
attr_accessor :principal
attr_accessor :audience_uri
attr_accessor :saml_request_id
attr_accessor :saml_acs_url
attr_accessor :raw_algorithm
attr_accessor :authn_context_classref
attr_accessor :expiry
attr_accessor :encryption_opts
attr_accessor :skip_issuer
attr_accessor :nest_subject_to_samlp
attr_accessor :assertion_type
delegate :config, to: :SamlIdp
def initialize(reference_id, issuer_uri, principal, audience_uri, saml_request_id, saml_acs_url, raw_algorithm, authn_context_classref, expiry=60*60, encryption_opts=nil, skip_issuer=false, nest_subject_to_samlp = false, assertion_type = "mindtouch")
self.reference_id = reference_id
if skip_issuer
# don't output the issuer as a standalone element; this matters to some SPs but not to others
else
self.issuer_uri = issuer_uri
end
self.principal = principal
self.audience_uri = audience_uri
self.saml_request_id = saml_request_id
self.saml_acs_url = saml_acs_url
self.raw_algorithm = raw_algorithm
self.authn_context_classref = authn_context_classref
self.expiry = expiry
self.encryption_opts = encryption_opts
self.nest_subject_to_samlp = nest_subject_to_samlp
self.assertion_type = assertion_type
end
def fresh
# if self.assertion_type == "lithium"
# raise "in lithium"
# elsif self.assertion_type == "mindtouch"
# raise "in mindtouch"
# end
builder = Builder::XmlMarkup.new
builder.Assertion xmlns: Saml::XML::Namespaces::ASSERTION,
ID: reference_string,
IssueInstant: now_iso,
Version: "2.0" do |assertion|
assertion.Issuer issuer_uri
sign assertion
assertion.Subject do |subject|
subject.NameID name_id, Format: name_id_format[:name]
subject.SubjectConfirmation Method: Saml::XML::Namespaces::Methods::BEARER do |confirmation|
# turn off InResponseTo if its blank; problem with Lithium
if saml_request_id.blank?
confirmation.SubjectConfirmationData "",
NotOnOrAfter: not_on_or_after_subject,
Recipient: saml_acs_url
else
confirmation.SubjectConfirmationData "", InResponseTo: saml_request_id,
NotOnOrAfter: not_on_or_after_subject,
Recipient: saml_acs_url
end
end
end
assertion.Conditions NotBefore: not_before, NotOnOrAfter: not_on_or_after_condition do |conditions|
conditions.AudienceRestriction do |restriction|
restriction.Audience audience_uri
end
end
if asserted_attributes
assertion.AttributeStatement do |attr_statement|
asserted_attributes.each do |friendly_name, attrs|
attrs = (attrs || {}).with_indifferent_access
attr_statement.Attribute Name: attrs[:name] || friendly_name,
NameFormat: attrs[:name_format] || Saml::XML::Namespaces::Formats::Attr::URI,
FriendlyName: friendly_name.to_s do |attr|
values = get_values_for friendly_name, attrs[:getter]
values.each do |val|
attr.AttributeValue val.to_s
end
end
end
end
end
assertion.AuthnStatement AuthnInstant: now_iso, SessionIndex: reference_string do |statement|
statement.AuthnContext do |context|
context.AuthnContextClassRef authn_context_classref
end
end
end
end
alias_method :raw, :fresh
private :fresh
def fresh_1
builder = Builder::XmlMarkup.new
builder.tag!
builder.tag!("saml:Assertion", {"xmlns:saml": Saml::XML::Namespaces::ASSERTION}) do |sa|
end
end
def fresh0
builder = Builder::XmlMarkup.new
builder.tag!
#builder.tag!("saml:Assertion", {"xmlns:saml": Saml::XML::Namespaces::ASSERTION}) do |sa|
builder.Assertion "xmlns:saml": Saml::XML::Namespaces::ASSERTION,
ID: reference_string,
IssueInstant: now_iso,
Version: "2.0" do |assertion|
assertion.tag!("saml:Assertion") do |sa|
assertion.Issuer issuer_uri
sign assertion
begin
logger = Logger.new("/var/www/apps/sso_portal/current/log/production.log"); logger.info("ASSERTION_BUILDER.fresh before if");
rescue StandardError => e
end
if nest_subject_to_samlp || 3 == 4
begin
logger = Logger.new("/var/www/apps/sso_portal/current/log/production.log"); logger.info("ASSERTION_BUILDER.fresh in if nest_subject_to_samlp");
rescue StandardError => e
end
else
#assertion.Subject do |subject|
#
# THIS IS THE MAGIC BULLET TO REWRITING THIS
#
assertion.tag!('saml:Subject', {}) do |subject|
assertion.tag!('saml:NameID', {}) do |name_id|
subject.NameID name_id, Format: name_id_format[:name], xmlns: "urn:oasis:names:tc:SAML:2.0:assertion"
subject.SubjectConfirmation Method: Saml::XML::Namespaces::Methods::BEARER do |confirmation|
assertion.tag!("saml:SubjectConfirmationData", {}) do |sc|
confirmation.SubjectConfirmationData "", InResponseTo: saml_request_id,
NotOnOrAfter: not_on_or_after_subject,
Recipient: saml_acs_url
end
end
end
end
end
assertion.tag!('saml:Conditions', {}) do |condition|
assertion.Conditions NotBefore: not_before, NotOnOrAfter: not_on_or_after_condition do |conditions|
# xml.tag!('gp:contactGet') do
# xml.gp :contactID, "199434"
# end
conditions.AudienceRestriction do |restriction|
restriction.Audience audience_uri
end
end
end
if asserted_attributes
assertion.AttributeStatement do |attr_statement|
asserted_attributes.each do |friendly_name, attrs|
attrs = (attrs || {}).with_indifferent_access
attr_statement.Attribute Name: attrs[:name] || friendly_name,
NameFormat: attrs[:name_format] || Saml::XML::Namespaces::Formats::Attr::URI,
FriendlyName: friendly_name.to_s do |attr|
values = get_values_for friendly_name, attrs[:getter]
values.each do |val|
attr.AttributeValue val.to_s
end
end
end
end
end
assertion.AuthnStatement AuthnInstant: now_iso, SessionIndex: reference_string do |statement|
statement.AuthnContext do |context|
context.AuthnContextClassRef authn_context_classref
end
end
end
end
end
alias_method :raw, :fresh
private :fresh
def encrypt(opts = {})
raise "Must set encryption_opts to encrypt" unless encryption_opts
raw_xml = opts[:sign] ? signed : raw
require 'saml_idp/encryptor'
encryptor = Encryptor.new encryption_opts
encryptor.encrypt(raw_xml)
end
def asserted_attributes
my_logger = Logger.new("#{Rails.root}/log/saml.log")
my_logger.info("in asserted_attributes -- principal = #{principal}")
my_logger.info("result of principal.respond_to?(:asserted_attributes) is #{principal.respond_to?(:asserted_attributes)}")
if principal.respond_to?(:asserted_attributes)
principal.send(:asserted_attributes)
elsif !config.attributes.nil? && !config.attributes.empty?
config.attributes
end
end
private :asserted_attributes
def get_values_for(friendly_name, getter)
result = nil
if getter.present?
if getter.respond_to?(:call)
result = getter.call(principal)
else
message = getter.to_s.underscore
result = principal.public_send(message) if principal.respond_to?(message)
end
elsif getter.nil?
message = friendly_name.to_s.underscore
result = principal.public_send(message) if principal.respond_to?(message)
end
Array(result)
end
private :get_values_for
def name_id
name_id_getter.call principal
end
private :name_id
def name_id_getter
getter = name_id_format[:getter]
if getter.respond_to? :call
getter
else
->(principal) { principal.public_send getter.to_s }
end
end
private :name_id_getter
def name_id_format
@name_id_format ||= NameIdFormatter.new(config.name_id.formats).chosen
end
private :name_id_format
def reference_string
"_#{reference_id}"
end
private :reference_string
def now
@now ||= Time.now.utc
end
private :now
def now_iso
iso { now }
end
private :now_iso
def not_before
iso { now - 5 }
end
private :not_before
def not_on_or_after_condition
iso { now + expiry }
end
private :not_on_or_after_condition
def not_on_or_after_subject
iso { now + 3 * 60 }
end
private :not_on_or_after_subject
def iso
yield.iso8601
end
private :iso
end
end
|
class FavoriteArticlesController < ApplicationController
before_action :signed_in?
def create
@favorite_article = FavoriteArticle.new(user_id: current_user.id, article_id: params[:article_id])
if @favorite_article.save
redirect_to user_path(current_user)
else
render 'article/show'
end
end
def destroy
@favorite_article = FavoriteArticle.find_by(article_id: params[:article_id])
if @favorite_article.destroy
redirect_to user_path(current_user)
else
render 'article/show'
end
end
end
|
require 'htph';
# Produces lists of gd_ids where those ids can be joined by one or more
# of oclc, sudoc, lccn, and/or issn.
def main
@log = HTPH::Hathilog::Log.new();
@log.d("Started");
db = HTPH::Hathidb::Db.new();
conn = db.get_conn();
# Get each distinct value of a given attribute (oclc, sudoc, ...)
# and a count how many distinct records contain it,
# ordered highest count to lowest count
sql_get_str_ids_xxx = %w[
SELECT hx.str_id, COUNT(DISTINCT hx.gd_id) AS c
FROM hathi_xxx AS hx
GROUP BY str_id
ORDER BY c DESC
].join(' ');
# Get each distinct document that has a given attribute value (e.g. oclc str_id 174003)
sql_get_gd_ids_xxx = %w[
SELECT DISTINCT gd_id
FROM hathi_xxx
WHERE str_id = ?
].join(' ');
@item_to_set = {};
@set_to_item = {};
ignore_top_x = 10;
# Use i in set_id below, instead attribute name, to save memory.
i = 0;
# These are the kinds of ids we are interested in, look them up with sql_get_str_ids_xxx.
the_ids = %w[oclc sudoc lccn issn];
the_ids.each do |attr|
@log.d(attr);
# Replace xxx in the queries with the current attribute.
sql_get_str_ids = sql_get_str_ids_xxx.sub('xxx', attr);
sql_get_gd_ids = sql_get_gd_ids_xxx.sub('xxx', attr);
q_get_gd_ids = conn.prepare(sql_get_gd_ids);
j = 0;
=begin
Get attribute values and counts.
SELECT hx.str_id, COUNT(DISTINCT hx.gd_id) AS c
FROM hathi_oclc AS hx
GROUP BY str_id
ORDER BY c DESC
+----------+-------+
| str_id | c |
+----------+-------+
| 321862 | 51592 |
| 3911324 | 13461 |
| 12573018 | 13125 |
| 12575725 | 11807 |
| 137944 | 8969 |
| 174008 | 8883 |
| 5469957 | 8455 |
| 128444 | 7755 |
| 12590898 | 7399 |
| 12576231 | 7072 |
| 133757 | 6649 |
| 134555 | 6374 |
| 174003 | 6137 |
...
| 6971475 | 1 |
+----------+-------+
=end
conn.query(sql_get_str_ids) do |str_id_row|
j += 1;
# The ignore_top_x most common strings we assume are bad predictors.
# But is it safe to just skip them? We might actually lose some docs between the cracks.
# For now, just skip. If we get clusters in the 100K size, then we'll run out of memory.
next if j <= ignore_top_x;
if j % 50000 == 0 then
@log.d(j);
end
str_id = str_id_row[:str_id];
# For each value in each category (oclc, sudoc, etc) create a set id.
# Use i instead of category name to save memory.
# So for oclc 174003, create set_id "0_174003".
set_id = "#{i}_#{str_id}";
@set_to_item[set_id] = {};
# For each attribute value, get gd_ids for all docs with that value for that attribute.
# E.g, find the gd_id of all records with oclc str_id 174003.
q_get_gd_ids.enumerate(str_id) do |gd_id_row|
gd_id = gd_id_row[:gd_id].to_i;
@set_to_item[set_id][gd_id] = 1; # => @set_to_item["0_174003"][555] = 1;
# Do reverse indexing also.
@item_to_set[gd_id] ||= {};
@item_to_set[gd_id][set_id] = 1; # => @item_to_set[555]["0_174003"] = 1;
end
end
i += 1;
end
@log.d("Started merging.");
@item_to_set.keys.sort.each do |item|
# We are deleting from the hash we are looping over,
# so make sure we don't do anything with a non-existing key.
next unless @item_to_set.has_key?(item);
merge_sets = {};
merge_items = {};
# r_get_overlap will populate merge_items with gd_ids as keys.
r_get_overlap(merge_sets, merge_items, item);
# Determine if we got any overlap (output "cluster") or not (output "solo").
if merge_items.keys.size > 1 then
puts "cluster\t#{merge_items.keys.sort.join(',')}";
else
puts "solo\t#{item}";
end
# Through power of transitivity, if we're recursing correctly then we never need to revisit these:
merge_sets.keys.each do |s|
@set_to_item.delete(s);
end
merge_items.keys.each do |i|
@item_to_set.delete(i);
end
end
@log.d("Finished merging.");
end
# seen_sets and seen_items start out as empty hashes.
# Start with an item (gd_id).
# Look up all the sets the item occurs in. Remember those sets so we don't look them up again.
# Look up all the items in those sets. Add those items to seen_items. For each found item, recurse.
# (... rubs eyes and yawns ...)
# So, in more detail, we call
# r_get_overlap ({}, {}, 555)
# Then, look up all the sets: @item_to_set[555].
# This gives us some set ids, like "0_174003"
# Look up what are the ids in that set using the reverse index, @set_to_item["0_174003"].
# Add those to seen_items and recurse for each item.
# As we go deeper, ignore any previously seen item or set.
def r_get_overlap (seen_sets, seen_items, item)
@item_to_set[item].map{|x| x.first}.each do |set|
# Make sure we only look at a set once.
next if seen_sets.has_key?(set);
seen_sets[set] = 1;
# look up set in set_to_item
items = @set_to_item[set];
# items is an array of gd_ids
items.keys.each do |other_item|
# other_item is also a gd_id
# Make sure we only look at an item once.
next if seen_items.has_key?(other_item);
seen_items[other_item] = 1;
r_get_overlap(seen_sets, seen_items, other_item);
end
end
# When we aren't getting any previously unseen items or sets, we're done recursing.
# The payload is the keys (gd_ids) in the seen_items hash.
return;
end
main() if $0 == __FILE__;
|
class AddIndexesOnTimeTableClassTiming < ActiveRecord::Migration
def self.up
add_index :time_table_class_timings, [:timetable_id,:batch_id], :name => :timetable_id_and_batch_id_index
add_index :time_table_class_timing_sets, :time_table_class_timing_id
end
def self.down
remove_index :time_table_class_timings, :timetable_id_and_batch_id_index
remove_index :time_table_class_timing_sets, :time_table_class_timing_id
end
end
|
module GuidConverter
def self.to_oracle_raw16(string, strip_dashes: true, dashify_result: false)
oracle_format_indices = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15]
string = string.gsub("-"){ |_match| "" } if strip_dashes
parts = split_into_chunks(string)
result = oracle_format_indices.map { |index| parts[index] }.reduce("") { |str, part| "#{str}#{part}" }
if dashify_result
result = [result[0..7], result[8..11], result[12..15], result[16..19], result[20..result.size]].join('-')
end
result
end
def self.split_into_chunks(string, chunk_length = 2)
chunks = []
while string.size >= chunk_length
chunks << string[0, chunk_length]
string = string[chunk_length, string.size]
end
chunks << string unless string.empty?
chunks
end
def self.pack_guid(string)
[to_oracle_raw16(string)].pack('H*')
end
def self.unpack_guid(hex)
to_oracle_raw16(hex.unpack1('H*'), dashify_result: false)
end
end
|
require 'rails_helper'
require 'shoulda-matchers'
RSpec.describe User, type: :model do
before(:each) do
@user = User.create(email: "email@test.com", password_digest: "ppppp")
end
context "Valid User" do
it "should not allow to be created without an email" do
@user.email = nil
expect(@user).to_not be_valid # funciona
end
# the same of above, but with Shoulda Matchers
it { should validate_presence_of(:email) }
it "should not allow to be created without a password" do
@user.password_digest = nil
expect(@user).to_not be_valid # Não sei pq esse não funciona!!!
end
# the same of above, but with Shoulda Matchers
it{should validate_presence_of(:password_digest)}
it "should have at least 5 chars in password (RSPEC)" do
@user.password_digest = "aaaa"
expect(@user).to_not be_valid
end
# the same of above, but with Shoulda Matchers
it "Should have at leat 5 chars in password (Shoulda MATCHERS)" do
should validate_length_of(:password_digest).is_at_least(5)
end
it { should validate_uniqueness_of(:email)}
end
end
|
class TravelerSerializer < ActiveModel::Serializer
attributes :id, :name, :age, :liked_sights, :reviewed_sights
# has_many :sightseeings, through: :likes
has_many :likes
has_many :reviews
end
|
class ItemsController < ApplicationController
#<-------All GET methods
#GET /items?id=:id
def get
@id = params[:id] #collect input
@item = nil
#check to make sure the id isn't null
if !@id.nil?
@item = Item.find_by(id: @id)
end
#check to make sure the item isn't null
if !@item.nil?
render json: @item.to_json, status: 200
else
head 404
end
end
#<-------All POST methods
#POST /items
def create
# defined object to receive strict item_params including :description, :price, :stockQty ; else return 400
@item = Item.new(item_params)
if @item.save
render json: @item.to_json, status: 201
else
head 400
end
end
#<-------All PUT methods
#PUT /items/order
#PUT /items
def processItemsOrder
@id = params[:itemID]
@description = params[:description]
@price = params[:price]
@award = params[:award]
@item = Item.find_by(id: @id)
if @item.save
head 204
else
# test
render json: @item.to_json, status: 400
# originally
#head 400
end
end
#<-------Validation methods
#Define custom method for receiving discrete member instantiation method, is used in methods above
def item_params
params.require(:item).permit(:description, :price, :stockQty)
#validates :price, presence: true
#validates :description, presence: true
#validates :stockQty, presence: true
end
end
|
class Duck < ApplicationRecord
belongs_to :student
validates :student_id, :description, :name, presence: :true
end
|
class CreatePlanets < ActiveRecord::Migration[6.0]
def change
create_table :planets do |t|
t.string :planet_name
t.integer :rotation_period
t.integer :orbital_period
t.integer :diameter
t.string :gravity
t.integer :surface_water
t.integer :population
t.references :home_world, null: false, foreign_key: true
t.timestamps
end
end
end
|
# frozen_string_literal: true
json.results do
json.total @count
json.notifications do
json.array! @notifications do |notification|
json.id notification.id
json.unread !notification.read?
json.template render partial: "notifications/#{notification.notifiable_type.underscore.pluralize}/#{notification.action}",
locals: { notification: notification },
formats: [:html]
end
end
end
|
class RailwayStationsRoute < ActiveRecord::Base
belongs_to :railway_station
belongs_to :route
validates :railway_station_id, uniqueness: {scope: :route_id}
end |
Rails.application.routes.draw do
mount Chato::Engine => "/chato"
end
|
class Cart < ApplicationRecord
belongs_to :cd
belongs_to :user
validates :cd_id, presence: true
validates :user_id, presence: true
validates :quantity, presence: true
def self.search_all(search)
Cart.where(['cd_id LIKE ?', "#{search}"])
end
end
|
class UserNotifier < ActionMailer::Base
default from: "cudalign@gmail.com"
def send_done_processing_alignment_email(alignment)
@alignment = alignment
mail(to: @alignment.callback_email, subject: 'We just finished processing your alignment request!')
end
end
|
# ENVIRONMENT HELPER
# Primarily to allow different domains and static domains for local and remote sites
# When Jekyll builds, you can use the Liquid filter to output the correct paths
# 1. Create a file named `_env` and put in it the name of your environment
# 2. Configure your paths in _config.yml
# 3. Use the Liquid filter in your templates
# <link href="{{"static"|env}}/theme.css" rel="stylesheet">
module Jekyll
module EnvFilter
def env(input)
env = Jekyll::EnvFilterHelper.get_env()
if @context.registers[:config]
url = @context.registers[:config]['env'][env][input]
else
url = @context.registers[:site].config['env'][env][input]
end
"#{url}"
end
end
# Using a separate module to hide this method from liquid
module EnvFilterHelper
@@env = nil
# Helper method to load the env file
def EnvFilterHelper.get_env(config=nil)
if @@env.nil?
envfile = File.expand_path(File.dirname(__FILE__) + '/../_env')
@@env = 'prod'
if File.exists?(envfile)
@@env = IO.read(envfile).strip!
end
end
@@env
end
end
end
Liquid::Template.register_filter(Jekyll::EnvFilter)
|
# frozen_string_literal: true
class MovieApiService
SERVICE_DOMAIN = "https://pairguru-api.herokuapp.com"
SERVICE_ENDPOINT = "/api/v1/movies/"
API_URL = "#{SERVICE_DOMAIN}#{SERVICE_ENDPOINT}"
DEFAULTS = { poster: "", plot: "", rating: 0.0 }.freeze
NO_MOVIE_MSG = "Couldn't find Movie"
def initialize(title)
@title = ERB::Util.url_encode(title)
end
def adapt
return DEFAULTS if invalid_response?
parsed_response.dig(:data, :attributes).tap do |attributes|
attributes[:poster] = "#{SERVICE_DOMAIN}#{attributes[:poster]}"
end
rescue StandardError => e
Rails.logger.warn("#{self.class.name}/#{e.class.name}: #{e.message}")
DEFAULTS
end
private
def invalid_response?
response.code > 299 || parsed_response[:message] == NO_MOVIE_MSG
end
def parsed_response
@parsed_response ||= JSON.parse(response.body).with_indifferent_access
end
def response
@response ||= HTTParty.get("#{API_URL}#{@title}")
end
end
|
class CreateEmployeeTasks < ActiveRecord::Migration[5.2]
def change
create_table :employee_tasks do |t|
t.decimal :hours_done
t.integer :task_id
t.integer :employee_id
t.timestamps
end
end
end
|
# rspec spec -t type:collection
describe [1, 7, 9], 'All', type: :collection do
it { is_expected.to all(be_odd.and(be_an(Integer))) }
it { expect(%w[ruby rails]).to all(be_a(String).and(include('r'))) }
end
|
class SleepsController < ApplicationController
before_action :authenticate_user!
def index
sleep_date = Date.today
# Sleep grouped by month in hash
@sleep_months = @sleeps.group_by { |s| s.sleep_date.beginning_of_month }.sort { |a,b| a[0] <=> b[0] }
# Sleep grouped for use in calendar helper
# @todo move to helper method
sleeps_by_date = sleeps.grouped_by_date
# Date used in calendar and month range
@date = params[:date] ? Date.parse(params[:date]) : Date.today
@year_range = @sleeps.where(:sleep_date => sleep_date.beginning_of_year..sleep_date.end_of_year)
# Array of hours slept since recording began
@total_sleep_months_array = @sleep_months.map { |month, sleep| month.strftime("%b") }
@current_year_sleep_array = @year_range.map { |year_range| year_range.hours }
# Do I need total?????
# @total_sleep_array = @sleeps.map { |sleeps| sleeps.hours }
# @total_average_sleep_time = median(@total_sleep_array)
# @current_month_average_sleep_time = median(@current_month_sleep_array)
respond_to do |format|
format.html { render action: 'index' }
format.js
end
end
def new
@sleep = current_user.sleeps.new
end
def edit
@sleep = current_user.sleeps.find(params[:id])
end
def create
@sleep = current_user.sleeps.new(params[:sleep])
respond_to do |format|
if @sleep.save
format.html { redirect_to sleeps_url, notice: 'Sleep was successfully recorded.' }
else
format.html { render action: 'new' }
end
end
end
def update
sleep.attributes = permitted_params
if sleep.save
redirect_to sleeps_url, notice: 'Sleep was successfully updated.'
else
render action: 'edit'
end
end
def destroy
sleep.destroy
redirect_to sleeps_url
end
private
# whitelisted parameters
#
# @return [ActionController::Parameters]
def permitted_params
params.require(:sleep).permit(:user_id, :hour, :sleep_date)
end
# Memoized current user
#
# @return [ActiveRecord::Relation<User>]
def user
@user ||= current_user
end
# A users sleeps
#
# @return [ActiveRecord::Collection<Sleep>]
def sleeps
user.sleeps
end
# A sleep
#
# @return [ActiveRecord::Relation<Sleep>]
def sleep
sleeps.find_or_initialize_by(id: params.fetch(:id, nil))
end
helper_method :user, :sleeps, :sleep
end
|
class CreateBooks < ActiveRecord::Migration[6.0]
def change
create_table :books do |t|
t.string :book_name, null: false, limit: 30
t.text :description, null: false, limit: 300
t.integer :category_id, null: false
t.integer :age, null: false
t.integer :price, null: false
t.references :user, null: false, foreign_key: true
t.timestamps
end
end
end
|
class Expand < ActiveRecord::Migration[5.0]
def change
change_column :line_items, :id, :integer, limit: 8
end
end
|
# This migration comes from inyx_catalogue_rails (originally 20140912135705)
class CreateInyxCatalogueRailsCategoryCatalogues < ActiveRecord::Migration
def change
create_table :inyx_catalogue_rails_category_catalogues do |t|
t.string :title
t.string :description
t.timestamps
end
end
end
|
#t.string "name", null: false
class State < ActiveRecord::Base
has_many :cities
belongs_to :country
validates_presence_of :name
end
|
require "fog/core/model"
module Fog
module Compute
class Brkt
class Volume < Fog::Model
module State
READY = "READY"
end
# @!group Attributes
identity :id
attribute :name
attribute :description
attribute :computing_cell, :aliases => :computing_cell_id
attribute :billing_group, :aliases => :billing_group_id
attribute :instance, :aliases => ["instance_id", :instance_id]
attribute :size_in_gb, :type => :integer
attribute :iops, :type => :integer
attribute :iops_max, :type => :integer
attribute :large_io, :type => :boolean
attribute :deleted, :type => :boolean
attribute :expired, :type => :boolean
attribute :auto_snapshot_duration_days, :type => :integer
attribute :provider_bracket_volume
attribute :iscsi_target_ip
# @!endgroup
def initialize(attributes={})
self.provider_bracket_volume = {}
super
end
# Create or update volume.
# Required attributes for create: {#name}, {#computing_cell}, {#billing_group},
# {#size_in_gb}, {#iops}, {#iops_max}
#
# @return [true]
def save
if persisted?
requires :id
data = service.update_volume(id, attributes).body
else
requires :name, :computing_cell, :billing_group, :size_in_gb, :iops, :iops_max
data = service.create_volume(attributes).body
end
merge_attributes(data)
true
end
# Delete volume
#
# @return [true]
def destroy
requires :id
service.delete_volume(id)
true
end
def ready?
provider_bracket_volume["state"] == State::READY
end
# Create volume snapshot
#
# @return [Volume] new volume instance
def create_snapshot
requires :id, :name, :billing_group
snapshot_data = service.create_volume_snapshot(:id, {
"name" => "#{name} snapshot", # TODO: customize?
"billing_group" => billing_group # TODO: customize?
}).body
collection.new(snapshot_data)
end
def target_name
requires :id
"brkt-tgt:#{id}"
end
# Get volume attachments
#
# @return [Array] Volume attachments
def attachments
service.volume_attachments(:bracket_volume => self.id)
end
end
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
API_KEY = 'AIzaSyBHaVnhN3gSB5otSpmKqutxuMaL878KItY'
alice = User.create!(
:name => "Alice Bar",
:email => "alice.bar@repap.com",
:phone => "+23769520125",
:password => "alicebar",
:password_confirmation => "alicebar"
)
bob = User.create!(
:name => "Bob Bar",
:email => "bob.bar@repap.com",
:phone => "+23769520125",
:password => "bobbar",
:password_confirmation => "bobbar"
)
path = File.join(File.dirname(__FILE__), "./hotels.json")
records = JSON.parse(File.read(path))
records.each do |record|
hotel = Hotel.create(
:name => record["name"],
:address => record["address"],
:phone => record["phone"].empty? ? Faker::PhoneNumber.phone_number : record["phone"],
:latlng => record["latlng"],
:price => Faker::Commerce.price,
:website => record["website"],
:url => record["url"],
:rating => record["rating"],
:user => [alice, bob].sample
)
doit = [true, false].sample
if doit
Favorite.create!(:user => alice, :hotel => hotel)
end
doit = [true, false].sample
if doit
Favorite.create!(:user => bob, :hotel => hotel)
end
record["photos"].each do |photo|
url = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=#{photo["width"]}&photoreference=#{photo["photo_reference"]}&key=#{API_KEY}"
download = open(url)
hotel.photos.attach(io: download, filename: Faker::File.file_name(ext: "jpg"))
hotel.save!
end
end
|
class CreateLeads < ActiveRecord::Migration
def change
create_table :leads do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :phone
t.string :company
t.integer :interested
t.integer :status
t.integer :source
t.text :company
t.text :address
t.timestamps
end
end
end
|
class CreateBooks < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.string :name, default: nil, null: false, unique: true
t.text :description
t.string :cover_image
t.timestamp :create_at
end
end
def self.down
drop_table :books
end
end
|
module ActualResults
class CalculatedRating
attr_reader :sorted_teams
attr_reader :teams
def self.cache_key(contest)
"c#{contest.respond_to?(:id) ? contest.id : contest}-rating"
end
def self.preload_classes
ActualResults::TeamState
ActualResults::TestState
ActualResults::SubmittionState
ActualResults::ProblemState
end
def self.try_get(contest, rdef, team)
self.preload_classes
Cache.get(cache_key(contest))
end
def self.recalc(contest, rdef, team)
self.preload_classes
r = self.new
r.calculate(contest, rdef, team)
Cache.put(cache_key(contest), r)
end
def self.invalidate(contest)
Cache.delete(cache_key(contest))
end
def initialize
@problems = {}
@teams = {}
@sorted_teams = []
end
def calculate(contest, rdef, team)
state = IntermediateState.new
puts "1"
runs = contest.evaluated_runs.find(:all)
puts "2"
runs.sort {|a,b| a.submitted_at <=> b.submitted_at}
puts "3"
all_teams = contest.teams.find(:all)
puts "4"
runs.delete_if do |run| all_teams.find { |t| t.id == run.team_id }.disqualified? end
puts "loading problems"
contest.problems.find(:all).each do |problem|
state.add_problem!(problem)
end
puts "calculating tests"
tests = RunTest.find(:all, :select => 'id, run_id, test_ord', :conditions => {:run_id => runs})
run_tests = {}
tests.each { |test| (run_tests[test.run_id] ||= []) << test }
# runs.each do |run|
# puts " - run #{run.id}"
# problem = (@problems[run.problem_id] ||= ProblemState.new(run.problem))
# run_tests[run.id].each { |test| problem.add_test(test) }
# end
# state.problems_by_id = @problems
runs.each do |run|
puts "run #{run.id}"
team = (@teams[run.team_id] ||= TeamState.new(run.team_id))
team.add_run(run, state)
end
@teams.each do |team_id, team|
puts "finalizing team #{team_id}"
team.finalize!(state)
end
puts "sorting"
#RAILS_DEFAULT_LOGGER.info "teams: #{@teams.values.join(', ')}"
case contest.rules
when 'acm'
@sorted_teams = @teams.values.sort do |a, b|
((b.solved_problems <=> a.solved_problems) * 10 + (a.penalty_time <=> b.penalty_time) * 4) <=> 0
end
when 'ioi'
@sorted_teams = @teams.values.sort do |a, b|
(b.points <=> a.points) * 10 + (a.compilation_errors <=> b.compilation_errors)
end
end
end
end
end
|
class ChangeColumnNameTuenti < ActiveRecord::Migration
def up
rename_column :tuenti_data, :actions_text, :actions
end
def down
rename_column :tuenti_data, :actions, :actions_text
end
end
|
#a. Erstellen Sie eine Klasse Game mit einem Konstruktor, der eine Instanzvariable title anlegt.
#Zugleich soll ein leeres Array mit dem Namen players erstellt werden.
#b. die Klasse Game bekommt eine Methode add_player der ein Spieler hinzugefuegt wird
#c. eine Methode play erzeugt folgenden Ausdruck:
# There are 3 players in Knuckleheads:
# I'm Moe with a health of 100 and a score of 103.
# I'm Larry with a health of 60 and a score of 65.
# I'm Curly with a health of 125 and a score of 130.
# Moe got blammed!
# Moe got w00ted!
# Moe got w00ted!
# I'm Moe with a health of 120 and a score of 123.
# Larry got blammed!
# Larry got w00ted!
# Larry got w00ted!
# I'm Larry with a health of 80 and a score of 85.
# Curly got blammed!
# Curly got w00t#d!
# Curly got w00ted!
#I'm Curly with a health of 145 and a score of 150.
class Game
def initialize(titel)
@titel = titel
@players = []
end
def add_player(player)
@players << player
end
def play
puts "There are #{@players.size} players in #{@titel}:"
@players.each do |player|
puts player
end
@players.each do |player|
player.blam
player.w00t
player.w00t
puts player #.to_S ist der standard und kann wegelassen werden
end
end
end
class Player
attr_accessor :name
attr_reader :health
def initialize(name, health=100)
@name = name.capitalize
@health = health
end
def to_s
"I'm #{@name} with a health of #{@health} and a score of #{score}."
end
def blam
@health -= 10
puts "#{@name} got blammed!"
end
def w00t
@health += 15
puts "#{@name} got w00ted!"
end
def score
@health + @name.length
end
end
player1 = Player.new("moe")
player2 = Player.new("larry", 60)
player3 = Player.new("curly", 125)
game2 = Game.new("Schach")
game2.add_player()
#players = [player1, player2, player3]
#game1 = Game.new("Knuckleheads")
#players.each do |player|
# game1.add_player(player)
#end
#game1.play |
class MessangersController < ApplicationController
def create
@user = User.friendly.find(params[:user_id])
@message = Messanger.new(message_params)
@message.receiver_id = @user.id
@message.sender_id = current_user.id
@message.save
redirect_to @user
end
def index
@user = User.friendly.find(params[:user_id])
@messages = Messanger.where('(receiver_id = ? and sender_id = ?) or (receiver_id = ? and sender_id = ?)',
current_user.id, @user.id, @user.id, current_user.id).page(params[:page]).per(6)
end
def maillist
@users = current_user.received_ms.map(&:sender) + current_user.send_ms.map(&:receiver)
@users = @users.uniq
end
def destroy
message = Messanger.find(params[:id])
message.destroy
redirect_to :back
end
def restore
message = Messanger.with_deleted.find(params[:id])
message.restore
redirect_to :back
end
private
def message_params
params.require(:messanger).permit(:message)
end
end
|
module Chanko
module UpdatingLoad
module Loadable
def self.included(obj)
obj.class_eval do
def require_or_updating_load(path)
ActiveSupport::Dependencies.require_or_updating_load(path)
end
end
end
end
module Dependencies
def self.included(obj)
obj.class_eval do
@@timestamps = {}
@@defined_classes = {}
class<<self
def reset_timestamps_and_defined_classes
@@timestamps = {}
@@defined_classes = {}
end
def require_or_updating_load(path)
if Chanko.config.cache_classes
return require(path.to_s)
end
absolute_path = expand_to_fullpath(path.to_s)
return false unless file_updated?(absolute_path)
save_timestamp(absolute_path)
result = nil
clear_defined_classes(absolute_path)
newly_defined_paths = new_constants_in(Object) do
Kernel.load absolute_path
end
@@defined_classes[absolute_path] = newly_defined_paths
return true
end
def clear_defined_classes(path)
absolute_path = expand_to_fullpath(path.to_s)
return unless @@defined_classes[absolute_path]
@@defined_classes[absolute_path].each do |klass|
Object.send(:remove_const, klass)
end
@@defined_classes[absolute_path] = []
end
private :clear_defined_classes
def expand_to_fullpath(path)
if path =~ /\A\/.*/
return path if File.exist?(path)
return "#{path}.rb" if File.exist?("#{path}.rb")
raise LoadError, "#{path} not found"
end
$:.each do |prefix|
fullpath = "#{prefix}/#{path}.rb"
next unless File.exist?(fullpath)
return fullpath
end
raise LoadError, "#{path} not found"
end
private :expand_to_fullpath
def file_updated?(path)
absolute_path = expand_to_fullpath(path.to_s)
return true unless @@timestamps[absolute_path]
return false unless File.exist?(absolute_path)
tv_sec = File.ctime(absolute_path).tv_sec
@@timestamps[absolute_path] == tv_sec ? false : true
end
private :file_updated?
def save_timestamp(path)
return false unless File.exist?(path)
@@timestamps[path] = File.ctime(path).tv_sec
end
private :save_timestamp
end
end
end
end
end
end
|
class LibView::LibraryCatsController < ApplicationController
before_action :set_locale_info
# GET /libraries
def index
@library_cats = LibraryCat.
joins("INNER JOIN library_#{@current_locale}s USING(library_id) INNER JOIN library_cat_#{@current_locale}s ON library_cat_id=library_vcats.id").
active_library_cat.order("library_#{@current_locale}s.name,library_cat_#{@current_locale}s.name")
@library_subjs = LibrarySubj.joins("library_subj_#{@current_locale}".to_sym).order('name')
end
def lib_index
@library_cats = LibraryCat.
joins("INNER JOIN library_#{@current_locale}s USING(library_id) INNER JOIN library_cat_#{@current_locale}s ON library_cat_id=library_vcats.id").
active_library_cat.order("library_#{@current_locale}s.name,library_cat_#{@current_locale}s.name")
render :lib_index
end
def subj_index
@library_subjs = LibrarySubj.joins("library_subj_#{@current_locale}".to_sym).order('name')
render :subj_index
end
# GET /library_cats/1
def show
case params[:id]
when 'lib_index'
lib_index
return
when 'subj_index'
subj_index
return
end
@library_cat = LibraryCat.includes(@cat_text_table).find(params[:id])
@covers = get_covers
@slick_carousel = true
end
private
# Use callbacks to share common setup or constraints between actions.
# Find the latest covers from the last 3 months
def get_covers
date = Date::today
dir_entries = Array.new
catalog_records = Hash.new
year = date.year
month = date.strftime('%m')
look_back_months = 0
libraries_dir = UbPub::Application.config.cat_covers_libraries
# @library_cat.library_code without any trailling "*"
library_code = @library_cat.lib_code.chomp('*')
while catalog_records.count < UbPub::Application.config.cat_covers_max do
month_dir = "#{libraries_dir}/#{year}/#{month}/#{library_code}"
if Dir.exist? month_dir
dir_entries = Dir.entries month_dir
dir_entries.reject! { |x| /[.]{1,2}/ =~ x }
# Read the JSON data for each catalog entry
dir_entries.each do |dir_entry|
file = "#{month_dir}/#{dir_entry}"
# Only read from existing records (records may be removed and thus
# the links broken during an update)
if File.exist? file
catalog_record = JSON.parse File.read(file)
if File.exist? "#{UbPub::Application.config.cat_covers_images_path}/#{catalog_record['isn']}.jpg"
catalog_records[catalog_record['id']] = catalog_record
end
end
end
end
look_back_months += 1
# Look back another month for covers
unless look_back_months < 3
break
end
date = date << 1
year = date.year
month = date.strftime('%m')
end
# Only show the latest cat_covers_max covers
# NB: sort_by returns an Array!
catalog_records = catalog_records.sort_by { |x, y| y <=> x } # Latest first
i = 0
covers = Array.new
catalog_records.each do |catalog_record|
covers[i] = catalog_record.pop
i += 1
if i == UbPub::Application.config.cat_covers_max
break
end
end
return covers
end
def set_locale_info
@cat_text_table = "library_cat_#{@current_locale}".to_sym
end
end
|
#MICHELLE: any time a comment is put above a line of code it is explaining what it is there for (not below)
# Homepage (Root path)
get '/' do
erb :index
end
get '/messages' do
#our server needs to load the messages from the database, render them as HTML, and send that HTML back as a response to their browser. @messages allows us to load all the messages before rendering the HTML
@messages = Message.all
erb :'messages/index'
end
get '/messages/new' do
erb :'messages/new'
end
#below is from question 7: we want to add an action that allows us to respond to a url like /message/2 instead of defining an action for each potential message ID. By doing the below, we are defining one action that will accept ANY id in the url. After doing this is when we implemented the show.erb file; the :id part tells sinatra to amtch anything and give it pack to us as a "param". Since the :id is the record ID of the msg, we can use active record's 'find' method to grab it from the DB for us!
get '/messages/:id' do
@message = Message.find params[:id]
erb :'messages/show'
end
post '/messages' do
@message= Message.new(
title: params[:title],
content: params[:content],
author: params[:author]
)
#we need to make sure that we aren'ts saving a message if all fields are left blank. So we need to validate it with Acitve Record. We will put the validation in the models/messages/message.rb file
#Question 9: No extra code was added below, but we added in code for the new.rb file to say that if @message had any errors to redirect them to a page that says that there was something wrong with their message entry attempt
if @message.save
redirect '/messages'
else
erb :'messages/new'
end
end
|
require 'rake'
desc "Home-baked spec task"
task :spec do
# this obviously need some cleaning - it's currently getting the job done though
if RUBY_PLATFORM == 'i386-mswin32'
system("ir spec/mspec/bin/mspec-run --format spec spec/*_spec.rb")
else
unless ENV["RUBY_EXE"]
# MSpec needs RUBY_EXE env var now - guess it from env
ruby_exe = `which ir`.strip
puts "Setting RUBY_EXE to '#{ruby_exe}'"
ENV["RUBY_EXE"] = ruby_exe
end
# system("ir spec/mspec/bin/mspec-run --format spec spec/*_spec.rb")
# for some reason the latest build of ir (in the path) throws an error - works if I use older build
system("mono /Users/thbar/Work/git/ironruby-labs/Release/ir.exe spec/mspec/bin/mspec-run --format spec spec/*_spec.rb")
end
end
desc "Compress all magic files into a single lib for use in Silverlight"
task :compress do
File.open(File.dirname(__FILE__) + "/../magic-compressed.rb","w") do |output|
output << "# compressed version of magic - do not modify\n"
Dir["lib/**/*.rb"].each do |file|
output << "\n\n# content for #{file}\n\n"
output << IO.read(file).gsub(/^require/,"# disabled: require")
end
end
end
begin
require 'jeweler'
Jeweler::Tasks.new do |s|
s.name = "magic"
s.summary = %Q{TODO}
s.email = "thibaut.barrere@gmail.com"
s.homepage = "http://github.com/thbar/magic"
s.description = "TODO"
s.authors = ["Thibaut Barrère"]
end
rescue LoadError
puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
end
require 'rake/rdoctask'
Rake::RDocTask.new do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'magic'
rdoc.options << '--line-numbers' << '--inline-source'
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('lib/**/*.rb')
end
require 'rake/testtask'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib' << 'test'
t.pattern = 'test/**/*_test.rb'
t.verbose = false
end
begin
require 'rcov/rcovtask'
Rcov::RcovTask.new do |t|
t.libs << 'test'
t.test_files = FileList['test/**/*_test.rb']
t.verbose = true
end
rescue LoadError
puts "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
end
begin
require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:features)
rescue LoadError
puts "Cucumber is not available. In order to run features, you must: sudo gem install cucumber"
end
task :default => :test
|
# Copyright 2007-2014 Greg Hurrell. All rights reserved.
# Licensed under the terms of the BSD 2-clause license.
require 'walrat'
module Walrat
class ParsletOmission < ParsletCombination
attr_reader :hash
# Raises an ArgumentError if parseable is nil.
def initialize parseable
raise ArgumentError, 'nil parseable' if parseable.nil?
@parseable = parseable
# fixed offset to avoid unwanted collisions with similar classes
@hash = @parseable.hash + 46
end
def parse string, options = {}
raise ArgumentError, 'nil string' if string.nil?
substring = StringResult.new
substring.start = [options[:line_start], options[:column_start]]
substring.end = [options[:line_start], options[:column_start]]
# possibly should catch these here as well
#catch :NotPredicateSuccess do
#catch :AndPredicateSuccess do
# one of the fundamental problems is that if a parslet throws such a
# symbol any info about already skipped material is lost (because the
# symbols contain nothing)
# this may be one reason to change these to exceptions...
catch :ZeroWidthParseSuccess do
substring = @parseable.memoizing_parse(string, options)
end
# not enough to just return a ZeroWidthParseSuccess here; that could
# cause higher levels to stop parsing and in any case there'd be no
# clean way to embed the scanned substring in the symbol
raise SkippedSubstringException.new(substring,
:line_start => options[:line_start],
:column_start => options[:column_start],
:line_end => substring.line_end,
:column_end => substring.column_end)
end
def eql?(other)
other.instance_of? ParsletOmission and other.parseable.eql? @parseable
end
protected
# For determining equality.
attr_reader :parseable
end # class ParsletOmission
end # module Walrat
|
require_relative 'questions_database'
require_relative 'user'
require 'byebug'
class QuestionFollow
def self.find_by_id(id)
data = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
question_follows
WHERE
id = ?
SQL
question_follow = QuestionFollow.new(data[0])
end
def self.followers_for_question_id(question_id)
data = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
u.*
FROM
question_follows qf
JOIN
users u
ON
qf.user_id = u.id
JOIN
questions q
ON
qf.question_id = q.id
WHERE
q.id = ?
SQL
users = data.map { |datum| User.new(datum) }
end
def self.followed_questions_for_user_id(userid)
data = QuestionsDatabase.instance.execute(<<-SQL, userid)
SELECT
q.*
FROM
question_follows qf
JOIN
questions q
ON
qf.question_id = q.id
WHERE
qf.user_id = ?
SQL
data.map { |datum| Question.new(datum) }
end
def self.most_followed_questions(n)
data = QuestionsDatabase.instance.execute(<<-SQL, n)
SELECT
q.*
FROM
questions q
JOIN
(SELECT
q.id, COUNT(DISTINCT qf.user_id) AS n_followers
FROM
questions q
JOIN
question_follows qf
ON
q.id = qf.question_id
GROUP BY
q.id
) s
ON q.id = s.id
ORDER BY s.n_followers DESC
LIMIT ?
SQL
questions = data.map { |datum| Question.new(datum) }
end
attr_accessor :id, :question_id, :user_id
def initialize(options)
@id = options['id']
@question_id = options['question_id']
@user_id = options['user_id']
end
end |
def Donation
@@all = []
attr_reader :artist, :donor
def initialize(artist, donor)
@artist = artist
@donor = donor
@@all << self
end
def self.all
@@all
end
end |
class ReviewsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def create
@user = User.find(current_user)
@review = Review.new(review_params)
property = Property.find(@review.property_id)
if @review.save!
redirect_to property
else
flash[:danger] = "Review not added please report this to the site admin."
redirect_to property
end
end
def new
@property = Property.find(params[:id])
@user = User.find(current_user)
@review = Review.new
end
def current_property
@current_property ||= Property.find_by(params[:id])
end
def destroy
@review = Review.find(params[:id])
@property = Property.find(@review.property_id)
@review.destroy
redirect_to @property
end
private
def review_params
params.require(:review).permit(:user_id, :reviewText, :reviewTitle, :rating_area,
:rating_cost, :rating_cleanliness,
:rating_landlord, :property_id)
end
def correct_user
@review = Review.find(params[:id])
puts @review
redirect_to root_url if @review.nil?
end
end
|
module ApplicationHelper
# shorten a string to a set number of characters to the word number (closing tags if needed)
# this method counts tags or formatting symbols as characters for shortening
def truncate_words(string, count = 30, end_str=' ...')
trunc = string
if string.length >= count
shortened = string[0, count]
splitted = shortened.split(/\s/)
words = splitted.length
trunc = splitted[0, words-1].join(" ") + end_str
end
trunc = close_tags(trunc) if trunc.scan(/\>|\</)
trunc
end
# close any <> tags that may be open in the string
def close_tags(text)
open_tags = []
text.scan(/\<([^\>\s\/]+)[^\>\/]*?\>/).each { |t| open_tags.unshift(t) }
text.scan(/\<\/([^\>\s\/]+)[^\>]*?\>/).each { |t| open_tags.slice!(open_tags.index(t)) }
open_tags.each {|t| text += "</#{t}>" }
text
end
# create path for blogs/:blog_id/:tag_name (mapped in routes)
def blog_tag_name_url(blog, tag, options = {})
url_for({:only_path => false, :controller => "posts", :action => "tagged",
:blog_id => "#{blog.id}", :tag => tag.name.gsub(' ', '_')}.merge(options))
end
# append script string or js file includes in layouts
def javascript(script = '', files = [])
js = ""
files.each { |file| js += "<script src=\"#{file}\" type=\"text/javascript\"></script>\n " }
content_for(:javascript) { js + script }
end
end |
class RedirectController < ApplicationController
def index
url = params[:next_url] || root_url
redirect_to url
end
end
|
class EncryptedFile
COORDS = [1000, 2000, 3000]
Number = Struct.new(:value, :position)
def initialize(values)
@numbers = values.map.with_index { |v, i| Number.new(v, i) }
@order = @numbers.dup
end
def mix!(times = 1)
times.times do
@order.each do |number|
@numbers.rotate!(@numbers.index(number))
@numbers.shift
@numbers.rotate!(number.value)
@numbers.unshift(number)
end
end
end
def coords
values = @numbers.map(&:value)
i = values.index(0)
COORDS.map { |c| values[(i + c) % values.size] }
end
end
NUMBERS = INPUT.split("\n").map(&:to_i)
file = EncryptedFile.new(NUMBERS)
file.mix!
solve!(
"The sum of the grove coordinates is:",
file.coords.sum
)
DECRYPTION_KEY = 811589153
file = EncryptedFile.new(NUMBERS.map { |n| n * DECRYPTION_KEY })
file.mix!(10)
solve!(
"The sum of the decrypted grove coordinates is:",
file.coords.sum
)
|
class SearchController < ApplicationController
def index
service = FuelStationService.new(params[:q])
@stations = service.stations
end
end
|
class CreatePomodoros < ActiveRecord::Migration
def self.up
create_table :pomodoros do |t|
t.integer :id
t.integer :activity_id
t.timestamp :start_time
t.timestamp :end_time
t.integer :interruption_type
t.timestamps
end
end
def self.down
drop_table :pomodoros
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
def create_esb_server (config, hostname, ip1, ip2)
config.vm.define hostname do |esb|
esb.vm.provider "virtualbox" do |provider|
provider.customize ["modifyvm", :id, "--memory", 2048]
end
esb.vm.network "private_network", ip: ip1
esb.vm.host_name = hostname
esb.vm.network "private_network", ip: ip2
end
end
Vagrant::configure("2") do |config|
config.vm.box = "wheezy64"
create_esb_server config, "esb-a", "192.168.1.10", "192.168.1.20"
create_esb_server config, "esb-b", "192.168.1.11", "192.168.1.21"
create_esb_server config, "esb-c", "192.168.1.12", "192.168.1.22"
create_esb_server config, "esb-d", "192.168.1.13", "192.168.1.23"
config.vm.provision :shell, inline: $install_pub_key_auth_script
end
$install_pub_key_auth_script = <<END
# create user and group jenkins
sudo useradd --home-dir /home/jenkins -m -p disabled --shell /bin/bash jenkins
sudo useradd --home-dir /usr/share/apache-servicemix -m -p disabled --shell /bin/bash smx-fuse
# create the home drive with ssh config
sudo mkdir -p /home/jenkins/.ssh
# configure pub key authentication
sudo echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDAerQTrfOJKN8sf4WW16YZNP6YhaeKZGwgZUSVTzwmng/EVBfeSKI+mO4K2xSX+0UrPCzip2aQYVyzoodJ6GmSRwIV8lwjei0bewuT+/jEDIvXru2wDlGL6Ud2v86m4D1x/wqXEJzhsJe/qs0SSgq91lVqMyTgzrBOry847Tc0dip8QvPToGqZa+dR6uugqCVwuykMmCUyQDXsDF84kURPDKdNZWaAviiG+1pp70xEROsnNgEmpKJU0WDdzGvvYClkKyVdnfLFEN2O6O0miUOYvyuW9+fO0/CjkqHUVMRvr/IphYDrRG1xo05/kuMmp9BbKJaf9IHLlxbK2UoNInLB brh@brh-ThinkPad-W520" > /home/jenkins/.ssh/authorized_keys
sudo chmod 2700 /home/jenkins/.ssh
sudo chmod 2700 /home/jenkins
sudo chmod 600 /home/jenkins/.ssh/authorized_keys
sudo chown -R jenkins.jenkins /home/jenkins
# install servicemix
sudo apt-get update
sudo apt-get -y --force-yes install oracle-java7-jdk
cd /usr/share
sudo cp /vagrant/apache-servicemix-4.4.1-fuse-07-11.tar.gz .
sudo tar xvfz apache-servicemix-4.4.1-fuse-07-11.tar.gz
sudo rm -rf /usr/share/apache-servicemix
sudo ln -s /usr/share/apache-servicemix-4.4.1-fuse-07-11 /usr/share/apache-servicemix
sudo chown -R smx-fuse.smx-fuse /usr/share/apache-servicemix
sudo chown -R smx-fuse.smx-fuse /usr/share/apache-servicemix-4.4.1-fuse-07-11
sudo cp /vagrant/servicemix/etc/* /usr/share/apache-servicemix/etc
sudo cp /vagrant/servicemix/deploy/* /usr/share/apache-servicemix/deploy
sudo cp /vagrant/servicemix/bin/* /usr/share/apache-servicemix/bin
sudo chown -R smx-fuse.smx-fuse /usr/share/apache-servicemix
sudo cp /vagrant/servicemix/servicemix.init /etc/init.d/servicemix
sudo chmod +x /etc/init.d/servicemix
sudo update-rc.d servicemix defaults 99
sudo /etc/init.d/servicemix start
# Install the sudoers file
sudo cp /vagrant/servicemix/jenkins /etc/sudoers.d
sudo chmod 600 /etc/sudoers.d/jenkins
sudo chown root /etc/sudoers.d/jenkins
END
|
End of preview. Expand
in Data Studio
- Downloads last month
- 13