text stringlengths 10 2.61M |
|---|
class MyFogHelper
def initialize(username, api_key)
@username = username
@api_key = api_key
end
def create_server
flavor = service.flavors.first
# pick the first Ubuntu image we can find
image = service.images.find {|image| image.name =~ /Ubuntu/}
server_name = "test_server"
server = service.servers.create :name => server_name,
:flavor_id => flavor.id,
:image_id => image.id
server.wait_for(600, 5) {
ready?
}
server
end
def service
@service ||= Fog::Compute.new({
:provider => 'rackspace',
:rackspace_username => @username,
:rackspace_api_key => @api_key,
:version => :v2,
:rackspace_region => :ord})
end
end |
#!/usr/bin/env ruby
$:.unshift(File.join("..", "lib"))
require "topaz"
# Receive MIDI clock messages
# A mock sequencer
class Sequencer
def step
@i ||= 0
p "step #{@i+=1}"
end
end
# Select a MIDI input
@input = UniMIDI::Input.gets
sequencer = Sequencer.new
@tempo = Topaz::Clock.new(@input, :midi_transport => true) do
sequencer.step
puts "tempo: #{@tempo.tempo}"
end
puts "Waiting for MIDI clock..."
puts "Control-C to exit"
puts
@tempo.start
|
class WithArgs
attr_reader :calling_method, :arguments
attr_writer :collection
def initialize(calling_method, *arguments)
@calling_method = calling_method
@arguments = arguments
end
def to_proc
Proc.new {|object|
object.send(calling_method, *get_arguments(object))
}
end
def get_arguments(object)
arguments.map do |argument|
if (argument.is_a?(String) || argument.is_a?(Symbol)) && argument.to_s.match(/^\&/)
meth = argument.to_s[1..-1]
argument = object.send(meth) if object.respond_to?(meth)
end
argument
end
end
def call(method, collection)
collection.send(method, &self)
end
def self.call(collection, collection_method, calling_method, arguments)
new(calling_method, *arguments).call(collection_method, collection)
end
end
module ToProcWithArgs
def with_args(calling_method, *args)
WithArgs.new(calling_method, *args)
end
end
class Array
include ToProcWithArgs
def to_proc
with_args(shift, *self).to_proc
end
end
#ActiveRecord::Base.send(:include, ToProcWithArgs)
|
class CreateTodos < ActiveRecord::Migration
def change
create_table :todos do |t|
t.string :title, null: false
t.text :body, null: false
t.boolean :done, inclusion: {in: [true, false]}, default: false
t.timestamps null: false
end
end
end
|
class Candidate
attr_accessor :name, :age, :occupation, :hobby, :birthplace
def initialize (name, age:, occupation:, hobby: nil, birthplace: 'Sleepy Hallow')
self.name = name
self.age = age
self.occupation = occupation
self.hobby = hobby
self.birthplace = birthplace
end
end
def print_summary(candidate)
puts "Candidate: #{candidate.name}"
puts "Age: #{candidate.age}"
puts "Occupation: #{candidate.occupation}"
puts "Hobby: #{candidate.hobby}"
puts "Birthplace: #{candidate.birthplace}"
end
barnes = Candidate.new("Carl Barnes",age: 49,occupation: "Attorney", birthplace: "Miami")
print_summary(barnes)
amy = Candidate.new("Amy Nguyen", :age => 37, :hobby => "Lacrosse", :occupation => "Engineer", :birthplace => "Seattle")
print_summary(amy)
new_candidate = Candidate.new("New Candidate")
print_summary(new_candidate)
bad_candidate = Candidate.new("Bad Candidate", aeg: 0, ocpation: 'Nothing')
print_summary(new_candidate)
raise "The end"
lines = []
File.open('votes.txt') do |file|
lines = file.readlines
end
p lines
votes = {}
lines.each do |candidate|
candidate = candidate.chomp
if votes[candidate]
votes[candidate] += 1
else
votes[candidate] = 1
end
end
p votes
##Create votes as a Hash object and set a default value
votes = Hash.new(0)
lines.each do |candidate|
candidate = candidate.chomp.upcase!
votes[candidate] += 1
end
votes.each do |name,count|
puts "#{name}: #{count}"
end
|
# frozen_string_literal: true
class Image
include Mongoid::Document
include Mongoid::Paperclip
has_mongoid_attached_file :file, styles: {medium: '300x300>', thumb: '100x100>'}
validates_attachment_presence :file
end
|
class Book < Product
attr_accessor :title, :genre, :author
def initialize(params)
super
@title = params[:title]
@genre = params[:genre]
@author = params[:author]
end
def update(params)
super
@title = params[:title] if params[:title]
@genre = params[:genre] if params[:genre]
@author = params[:author] if params[:author]
end
def self.from_file(path)
line = File.readlines(path, ecncoding: "UTF-8", chomp: true)
self.new(title: line[0], genre: line[1], author: line[2], price: line[3].to_i, amount: line[4].to_i)
end
def to_s
"Книга «#{@title}», #{@genre}, автор — #{@author}, #{@price} руб. (осталось #{@amount})"
end
end
|
class RemoveIdentifiableIdFromStudentUsers < ActiveRecord::Migration
def change
remove_column :student_users, :identifiable_id, :integer
end
end
|
class Castmember < ActiveRecord::Base
belongs_to :actor
belongs_to :tour
validates :actor, presence: true
validates :tour, presence: true
end |
RSpec.feature 'Not logged in user redirected to homepage', type: :feature do
scenario 'User redirected from private page to homeage' do
visit('/users/0/posts')
expect(current_path).to eq('/')
end
end
|
require 'spec_helper'
describe TimeFilter do
let(:filter) { TimeFilter.new }
describe '#convert' do
before { @result = filter.convert(interval, time) }
subject { @result }
context 'when momentary' do
let(:interval) { 'momentary' }
[
'2013',
'2013-01',
'2013-01-01',
'2013-01-01 00',
'2013-01-01 00:00',
'2013-01-01 00:00:00',
].each do |time|
context 'time = ' + time.inspect do
let(:time) { time }
it { should == '2013-01-01 00:00:00' }
end
end
end
context 'when daily' do
let(:interval) { 'daily' }
context 'time is 2013-01-01' do
let(:time) { '2013-01-01' }
it { should == '2013-01-01' }
end
end
context 'when monthly' do
let(:interval) { 'monthly' }
context 'time is 2013-01' do
let(:time) { '2013-01' }
it { should == '2013-01-01' }
end
end
end
end
|
class Public::CandidatesController < ApplicationController
def create
@shop = Shop.find(params[:shop_id])
candidate = current_customer.candidates.new(shop_id: @shop.id)
candidate.save
@shop = candidate.shop
end
def destroy
@shop = Shop.find(params[:shop_id])
candidate = current_customer.candidates.find(params[:id])
candidate.destroy
@shop = candidate.shop
end
private
def shop_params
@shop = Shop.find(params[:id])
end
end
|
# frozen_string_literal: true
require 'integration_test'
class AnnualMeetingsControllerTest < IntegrationTest
setup do
@annual_meeting = annual_meetings(:last)
login(:uwe)
end
test 'should get index' do
get annual_meetings_path
assert_response :success
end
test 'should get new' do
get new_annual_meeting_path
assert_response :success
end
test 'should create annual_meeting' do
assert_difference('AnnualMeeting.count') do
post annual_meetings_path, params: { annual_meeting: {
start_at: @annual_meeting.start_at,
} }
end
assert_redirected_to annual_meeting_path(AnnualMeeting.last)
end
test 'should show annual_meeting' do
get annual_meeting_path(@annual_meeting)
assert_response :success
end
test 'should get edit' do
get edit_annual_meeting_path(@annual_meeting)
assert_response :success
end
test 'should update annual_meeting' do
put annual_meeting_path(@annual_meeting), params: { annual_meeting: {
start_at: @annual_meeting.start_at,
} }
assert_redirected_to annual_meeting_path(@annual_meeting)
end
test 'should destroy annual_meeting' do
assert_difference('AnnualMeeting.count', -1) do
delete annual_meeting_path(@annual_meeting)
end
assert_redirected_to annual_meetings_path
end
end
|
Rails.application.routes.draw do
devise_for :users
root to: "home#index"
namespace :platform do
root 'home#index'
end
end
|
require 'rake'
require 'open-uri'
require 'mechanize'
require 'nokogiri'
require 'date'
require 'time'
require 'kyutech_bot'
namespace :cron do
@tweet_base_url = "https://kyutechapp.planningdev.com/api/v2/notices/redirect/"
#データベース用ハッシュ
#
#お知らせはid = 15 に変更しました
#objに代入直前に変えてるからだいぶわかりずらいよ
category = {"お知らせ" => 0,
"おしらせ" => 15,
#=================================
"時間割・講義室変更" => 6,
"休講通知" => 3,
"補講通知" => 2,
"学生呼出" => 5,
"授業調整・期末試験" => 4,
"各種手続き" => 7,
"奨学金" => 1,
"集中講義" => 8,
"留学・語学学習支援" => 9,
"学部生情報" => 10,
"大学院生情報" => 11,
"重要なお知らせ" => 12,
"ニュース" => 13,
"イベント" => 14,
#全てとおいうより未分類=============
"全て" => 99
#バグりたくないからかえてない
#アプリ側の解釈は未分類
#==================================
}
department = {"全て" => 99,
"学部" => 1,
"大学院" => 2,
"知能情報" => 3,
"電子情報" => 4,
"システム" => 5,
"機械情報" => 6,
"生命情報" => 7,
"未分類" => 99
}
campus = {"戸畑" => 0,
"飯塚" => 1,
"若松" => 2
}
desc "飯塚の掲示板から情報を取得する。"
task :kit_i => :environment do
#共通部分のURL
@timetable_update = "391"
@students_call = "393"
url = 'https://db.jimu.kyutech.ac.jp/cgi-bin/cbdb/db.cgi?page=DBView&did='
notice_url = {"お知らせ" => "357",
"奨学金" => "367",
"補講通知" => "363",
"休講通知" => "361",
"授業調整" => "364",
"学生呼出" => @students_call,
"時間割変更" => @timetable_update,
"各種手続き" => "373",
"集中講義" => "379",
"留学支援" => "372",
"学部生情報" => "368",
"大学院生情報" => "370"}
# divがあるかどうか
notice_div = {"お知らせ" => 0,
"奨学金" => 0,
"補講通知" => 0,
"休講通知" => 0,
"授業調整" => 1,
"学生呼出" => 1,
"時間割変更" => 1,
"各種手続き" => 0,
"集中講義" => 0,
"留学支援" => 0,
"学部生情報" => 0,
"大学院生情報" => 0}
# 正規表現用学部名
$department_name = {"全て" => "全",
"学部" => "学部",
"大学院" => "大学院",
"知能情報" => "知能",
"電子情報" => "電子",
"システム創成" => "シス",
"機械情報" => "機械",
"生命情報" => "生命",}
# CSSパスの値
$css_record = "td.record-value-" # グローバル変数
# title_record = ["7", "116"]
# detail_record = ["121","10","11","12","131","129"]
# department_record = ["109","6"]
# date_record = ["4"]
# period_record = ["221","200","94"]
# grade_record = ["111","109","119"]
# place_record = ["6","113"]
subject_record = ["203"]
# teacher_record = ["204","8"]
before_record = ["205"]
after_record = ["206"]
# note_record = ["6","201"]
# document1_record = ["109","117","169"]
# document2_record = ["110","114","120","170"]
# document3_record = ["111","150","171","188"]
# document4_record = ["112","151","172","189"]
# document5_record = ["113","152","173","190"]
# record番号選択メソッド
# パスがカテゴリによって重なっているため、分類するメソッド
def title_record(key)
if key == "時間割変更" then
return ["116"]
else
return ["7"]
end
end
def detail_record(key)
if key == "学生呼出" then
return ["121","11","12"]
elsif key == "各種手続き" then
return ["10","11"]
elsif key == "集中講義" then
return ["11","10"]
elsif key == "学部生情報" then
return ["11","131"]
elsif key == "大学院生情報" then
return ["11","129"]
else
return ["11"]
end
end
def department_record(key)
if key == "時間割変更" then
return ["6"]
else
return ["109"]
end
end
def period_record(key)
if key == "お知らせ" then
return ["221"]
elsif key == "時間割変更"
return ["200"]
else
return ["94"]
end
end
def grade_record(key)
if (key == "お知らせ") || (key == "授業調整") then
return ["111"]
elsif (key == "時間割変更") || (key == "休講通知") || (key == "補講通知") then
return ["109"]
else
return ["119"]
end
end
def place_record(key)
if (key == "お知らせ") || (key == "各種手続き") then
return ["6"]
elsif (key == "補講通知") || (key == "授業調整") || (key == "留学支援") then
return ["113"]
else
return ["9"]
end
end
def teacher_record(key)
if (key == "時間割変更") then
return ["204"]
else
return ["8"]
end
end
def note_record(key)
if (key == "奨学金") then
return ["6"]
else
return ["201"]
end
end
def document1_record(key)
if (key == "各種手続き") || (key == "奨学金") || (key == "集中講義") || (key == "留学支援") || (key == "学部生情報") || (key == "大学院生情報") then
return ["109"]
elsif key == "お知らせ" then
return ["117"]
else
return ["169"]
end
end
def document2_record(key)
if key == "お知らせ" then
return ["120"]
elsif key =="授業調整" then
return ["170"]
elsif key == "奨学金" then
return ["114"]
else
return ["110"]
end
end
def document3_record(key)
if (key == "各種手続き") || (key == "留学支援") || (key == "学部生情報") ||(key == "大学院生情報") then
return ["111"]
elsif key == "お知らせ" then
return ["188"]
elsif key == "授業調整" then
return ["171"]
else
return ["150"]
end
end
def document4_record(key)
if key == "お知らせ" then
return ["189"]
elsif key == "授業調整" then
return ["172"]
elsif key == "集中講義" then
return ["151"]
else
return ["112"]
end
end
def document5_record(key)
if (key == "学部生情報") || (key == "大学院生情報") then
return ["113"]
elsif key == "お知らせ"
return ["190"]
elsif key == "授業調整"
return ["173"]
else
return ["152"]
end
end
# 文字列取得メソッド
def get_varchar(page,record)
text = ""
record.each do |rec|
doc = page.search($css_record + rec).inner_text
text << doc
end
return text
end
# 詳細取得メソッド
def get_detail(page,record)
text = ""
record.each do |rec|
doc = page.search($css_record + rec).inner_text
if !doc.empty? then
if doc.length != 0 then
text << "\n"
end
text << doc
end
end
return text
end
# 学部ID取得メソッド
def get_departmentID(page,record,key)
depID = Array.new
# 掲示板によって、学科IDを決定
if (key == "各種手続き") || (key == "奨学金") || (key == "集中講義") || (key == "留学支援") then
depID.push(0)
elsif key == "学部生情報" then
depID.push(1)
elsif key == "大学院生情報" then
depID.push(2)
else
# 文字列から対象学科を捜索。そこからIDを決定
# 対象学部の文字列を取得
text = ""
record.each do |rec|
doc = page.search($css_record + rec).inner_text
text << doc
end
# 対象学部の文字列を比較 IDを取得する
$department_name.each_with_index do |dep,i|
dep.each do |name|
if text.include?(name) then
depID.push(i)
break
end
end
end
# 対象学部の文字列が無ければ、未分類
if depID.length <= 0 then
depID.push(99)
end
end
return depID
end
# 日付取得メソッド
def get_date(page,key)
# 日付の文字列を取得
text = page.search($css_record + "4").inner_text
if key == "集中講義" then
text = text.gsub(/平成/,'H')
text = text.gsub(/昭和/,'S')
text = text.gsub(/年|月/,'.')
text = text.gsub(/日/,'')
date = Date.parse(text)
elsif (key == "学部生情報") || (key == "大学院生情報") then
# 日付がない
date = nil
else
date = Date.strptime(text,'%Y年%m月%d日')
end
unless date.blank?
unixtime = Time.parse(date.to_s).to_i
end
return unixtime
end
# 添付資料のURLを取得
def get_href(page,div)
urls = [""]
url = 'https://db.jimu.kyutech.ac.jp/cgi-bin/cbdb/'
href_xpath = '/html/body/table//tr/td[2]/a'
href_xpath_div = '/html/body/div[3]/table//tr/td[2]/a'
if div == 1 then
url_xpath = href_xpath_div
else
url_xpath = href_xpath
end
page.search(url_xpath).each do |doc|
urls.push(url + doc["href"])
end
return urls
end
# task kit_i スクレイピングメイン文
agent = Mechanize.new
# 全ての基礎となるURL
url = 'https://db.jimu.kyutech.ac.jp/cgi-bin/cbdb/db.cgi?page=DBView&did='
# div付詳細ページへのXPATH
detail_xpath_div = '/html/body/div[3]/table//tr/td/table[3]//tr[2]/td/table//tr/td[1]/table//tr/td/a'
# div無詳細ページへのXPATH
detail_xpath = '/html/body/table//tr/td/table[3]//tr[2]/td/table//tr/td[1]/table//tr/td/a'
#各掲示板を回る
notice_url.each_with_index do |(key, value), inx|
page = agent.get(url + value)
puts key
# 詳細ページのXPATHを選択
if notice_div[key] == 1 then
detail_href = detail_xpath_div
else
detail_href = detail_xpath
end
# 一覧から、詳細ページへのURLを探す
# tbodyがあると検索できないっぽいので外す
page.search(detail_href).each do |detail_url|
detail_page = page.link_with(:href => detail_url[:href]).click # 詳細ページへのリンクをクリック。リンク先のpage情報ゲット
@notice = Notice.new
# 各情報をGET
if value == @timetable_update
@notice.title = get_varchar(detail_page,subject_record)
elsif value == @students_call
@notice.title = get_varchar(detail_page,title_record(key)) + "・" + get_varchar(detail_page,["109"])
else
@notice.title = get_varchar(detail_page,title_record(key))
end
@notice.details = get_detail(detail_page,detail_record(key))
@notice.category_id = inx == 0 ? 15 : inx
@notice.department_id = get_departmentID(detail_page,department_record(key),key)[0].to_i == 0 ? 99 : get_departmentID(detail_page,department_record(key),key)[0]
@notice.campus_id = 1
@notice.date = get_date(detail_page,key)
@notice.period_time = get_varchar(detail_page,period_record(key))
@notice.grade = get_varchar(detail_page,grade_record(key))
@notice.place = get_varchar(detail_page,place_record(key))
@notice.subject = get_varchar(detail_page,subject_record)
@notice.teacher = get_varchar(detail_page,teacher_record(key))
@notice.before_data = get_varchar(detail_page,before_record)
@notice.after_data = get_varchar(detail_page,after_record)
@notice.note = get_varchar(detail_page,note_record(key))
@notice.document1_name = get_varchar(detail_page,document1_record(key))
@notice.document2_name = get_varchar(detail_page,document2_record(key))
@notice.document3_name = get_varchar(detail_page,document3_record(key))
@notice.document4_name = get_varchar(detail_page,document4_record(key))
@notice.document5_name = get_varchar(detail_page,document5_record(key))
@notice.regist_time = Time.now.to_i
document_url = get_href(detail_page, notice_div[key])
@notice.document1_url = document_url[1]
@notice.document2_url = document_url[2]
@notice.document3_url = document_url[3]
@notice.document4_url = document_url[4]
@notice.document5_url = document_url[5]
detail_url = detail_page.uri.to_s
@notice.web_url = detail_url.sub!(/(.*)&Head.*/){$1}
begin
@notice.save
print "save succeed"
puts @notice.title
@save_obj = Notice.find_by(title: @notice.title, category_id: @notice.category_id, department_id: @notice.department_id, campus_id: @notice.campus_id, web_url: @notice.web_url)
@tweet_url = @tweet_base_url + @save_obj.id.to_s
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id),department.key(@notice.department_id), @notice.campus_id, @tweet_url)
rescue => e
print "no save"
p e
end
puts "---"
end
end
end # taks kit_i
desc "飯塚のHPから情報を取得する"
task :kit_i_hp => :environment do
# 飯塚のHPにアクセスし、情報を取得する。
# 日付
def get_unixtime(date)
d = Date.strptime(date,"%Y.%m.%d")
unixtime = Time.parse(date).to_i
return unixtime
end
url = 'http://www.iizuka.kyutech.ac.jp/'
charset = nil # 変数charsetにnilを代入 = 初期化かな
html = open(url) do |f| # 変数htmlにopen文を代入し、UTLにアクセスし、そのURLを開く
charset = f.charset # 文字種別を取得
f.read # htmlを読み込み、変数htmlに渡すメソッド
end
doc = Nokogiri::HTML.parse(html,nil,charset)
puts "飯塚"
#重要なお知らせ
puts "重要なお知らせ"
doc.xpath('//*[@id="news"]/ul[1]/li').each do |node|
@notice = Notice.new
@notice.title = node.xpath('a').inner_text
@notice.web_url = node.xpath('a').attribute('href').value
@notice.category_id = category["重要なお知らせ"]
@notice.department_id = department["全て"]
@notice.campus_id = campus["飯塚"]
@notice.regist_time = Time.now.to_i
begin
@notice.save
puts "save succeed"
@save_obj = Notice.find_by(title: @notice.title, category_id: @notice.category_id, department_id: @notice.department_id, campus_id: @notice.campus_id, web_url: @notice.web_url)
@tweet_url = @tweet_base_url + @save_obj.id.to_s
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id), department.key(@notice.department_id), @notice.campus_id, @tweet_url)
rescue => e
p e
puts "no save"
end
end
# EVENT
puts "イベント"
doc.xpath('//*[@id="news"]/dl/table/tbody/tr').each do |node|
@notice = Notice.new
@notice.title = node.xpath('td[4]/a').inner_text
@notice.web_url = node.xpath('td[4]/a').attribute('href').value
date = node.xpath('td[2]/a').inner_text
@notice.date = get_unixtime(date)
@notice.category_id = category["イベント"]
@notice.department_id = department["全て"]
@notice.campus_id = campus["飯塚"]
@notice.regist_time = Time.now.to_i
begin
@notice.save
puts "save succeed"
@save_obj = Notice.find_by(title: @notice.title, category_id: @notice.category_id, department_id: @notice.department_id, campus_id: @notice.campus_id, web_url: @notice.web_url)
@tweet_url = @tweet_base_url + @save_obj.id
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id), department.key(@notice.department_id), @notice.campus_id, @tweet_url)
rescue => e
puts "no save"
end
end
# TOPICS,PRESS SCRAP,WATH'S NEW
puts "ニュース"
doc.xpath('//*[@id="news"]/ul/table/tbody/tr').each do |node|
@notice = Notice.new
@notice.title = node.xpath('td[4]/a').inner_text
@notice.web_url = node.xpath('td[4]/a').attribute('href').value
date = node.xpath('td[2]/a').inner_text
@notice.date = get_unixtime(date)
@notice.category_id = category["ニュース"]
@notice.department_id = department["全て"]
@notice.campus_id = campus["飯塚"]
@notice.regist_time = Time.now.to_i
begin
@notice.save
puts "save succeed"
@save_obj = Notice.find_by(title: @notice.title, category_id: @notice.category_id, department_id: @notice.department_id, campus_id: @notice.campus_id, web_url: @notice.web_url)
@tweet_url = @tweet_base_url + @save_obj.id
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id), department.key(@notice.department_id), @notice.campus_id, @tweet_url)
rescue => e
puts "no save"
end
end
end # task kit_i_hp
desc "戸畑のHPから情報を取得する"
task :kit_e_hp => :environment do
# 戸畑のHPにアクセスし、情報を取得する
# 日付取得メソッド
def get_unixtime(date)
d = Date.strptime(date,"%Y-%m-%d")
unixtime = Time.parse(date).to_i
return unixtime
end
url = 'http://www.tobata.kyutech.ac.jp'
charset = nil # 変数charsetにnilを代入 = 初期化かな
html = open(url) do |f| # 変数htmlにopen文を代入し、UTLにアクセスし、そのURLを開く
charset = f.charset # 文字種別を取得
f.read # htmlを読み込み、変数htmlに渡すメソッド
end
doc = Nokogiri::HTML.parse(html,nil,charset)
puts "戸畑"
# 重要なお知らせ
puts "重要なお知らせ"
doc.xpath('//*[@id="block-views-news-list-block-1"]/div/div[1]/div').each do |node|
@notice = Notice.new
@notice.title = node.xpath('span/span[1]/a').inner_text
@notice.web_url = url + node.xpath('span/span[1]/a').attribute('href').value
date = node.xpath('span[1]').inner_text.strip!
@notice.date = get_unixtime(date)
@notice.category_id = category["重要なお知らせ"]
@notice.department_id = department["全て"]
@notice.campus_id = campus["戸畑"]
@notice.regist_time = Time.now.to_i
begin
@notice.save
puts "save succeed"
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id), department.key(@notice.department_id), @notice.campus_id, @notice.web_url)
rescue
puts "no save"
end
end
#EVENT
puts "イベント"
doc.xpath('//*[@id="block-views-event-list-block-1"]/div/div[1]/div').each do |node|
@notice = Notice.new
@notice.title = node.xpath('span/span[1]/a').inner_text
@notice.web_url = url + node.xpath('span/span[1]/a').attribute('href').value
date = node.xpath('span[1]').inner_text.strip!
@notice.date = get_unixtime(date)
@notice.category_id = category["イベント"]
@notice.department_id = department["全て"]
@notice.campus_id = campus["戸畑"]
@notice.regist_time = Time.now.to_i
begin
@notice.save
puts "save succeed"
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id),
department.key(@notice.department_id), @notice.campus_id, @notice.web_url)
rescue
puts "no save"
end
end
#ニュース
puts "ニュース"
doc.xpath('//*[@id="block-views-commend-block-1"]/div/div[1]/div').each do |node|
@notice = Notice.new
@notice.title = node.xpath('div/span/a').inner_text
@notice.web_url = url + node.xpath('div/span/a').attribute('href').value
@notice.category_id = category["ニュース"]
@notice.department_id = department["全て"]
@notice.campus_id = campus["戸畑"]
@notice.regist_time = Time.now.to_i
begin
@notice.save
puts "save succeed"
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id),
department.key(@notice.department_id), @notice.campus_id, @notice.web_url)
rescue
puts "no save"
end
end
end # task kit_e_hp
desc "若松のHPから情報を取得する"
task :kit_b_hp => :environment do
# 若松のHPにアクセスし、情報を取得する
# 日付
def get_unixtime(date)
d = Date.strptime(date,"%Y.%m.%d")
unixtime = Time.parse(date).to_i
return unixtime
end
url = 'http://www.lsse.kyutech.ac.jp/'
charset = nil # 変数charsetにnilを代入 = 初期化かな
html = open(url) do |f| # 変数htmlにopen文を代入し、UTLにアクセスし、そのURLを開く
charset = f.charset # 文字種別を取得
f.read # htmlを読み込み、変数htmlに渡すメソッド
end
doc = Nokogiri::HTML.parse(html,nil,charset)
#重要なお知らせ
puts "重要なお知らせ"
doc.xpath('//*[@id="main"]/div[1]/ul/li').each do |node|
@notice = Notice.new
@notice.title = node.xpath('a').inner_text
@notice.web_url = node.xpath('a').attribute('href').value
@notice.category_id = category["重要なお知らせ"]
@notice.department_id = department["全て"]
@notice.campus_id = campus["若松"]
@notice.regist_time = Time.now.to_i
begin
@notice.save
puts "save succeed"
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id), department.key(@notice.department_id), @notice.campus_id, @notice.web_url)
rescue
puts "no save"
end
end
# ニュース
puts "ニュース"
doc.xpath('//*[@id="main"]/div[2]/dl/dd').each_with_index do |node, i|
@notice = Notice.new
@notice.title = node.xpath('a').inner_text
@notice.web_url = node.xpath('a').attribute('href').value
num = "#{i+1}"
path = '//*[@id="main"]/div[2]/dl/dt[' + num + ']'
date = doc.xpath(path).inner_text
@notice.date = get_unixtime(date)
@notice.category_id = category["ニュース"]
@notice.department_id = department["全て"]
@notice.campus_id = campus["若松"]
@notice.regist_time = Time.now.to_i
begin
@notice.save
puts "save succeed"
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id),
department.key(@notice.department_id), @notice.campus_id, @notice.web_url)
rescue
puts "no save"
end
end
# イベント
puts "イベント"
doc.xpath('//*[@id="main"]/div[3]/dl/dt').each_with_index do |node, i|
@notice = Notice.new
@notice.title = node.xpath('a').inner_text
@notice.web_url = node.xpath('a').attribute('href').value
puts @notice.title
puts @notice.web_url
num = "#{i+1}"
path = '//*[@id="main"]/div[3]/dl/dd[' + num + ']'
detail = doc.xpath(path).inner_text
/\d{4,4}\.\d{1,2}\.\d{1,2}/ =~ detail
puts $&
@notice.date = get_unixtime($&)
/[場所]/ =~ detail
puts $'
# @notice.place = $'
@notice.category_id = category["イベント"]
@notice.department_id = department["全て"]
@notice.campus_id = campus["若松"]
@notice.regist_time = Time.now.to_i
begin
@notice.save
puts "save succeed"
Kyutech_bot.tweet_new(@notice.title, category.key(@notice.category_id),
department.key(@notice.department_id), @notice.campus_id, @notice.web_url)
rescue
puts "no save"
end
end
end # task kit_b_hp
desc "本日の予定をツイートする"
task :morning_tweet => :environment do
today = Date::today
puts today
unixtime = Time.parse(today.to_s).to_i
puts unixtime
Notice.where(date: unixtime).each do |recode|
if recode.campus_id == 1
@tweet_url = @tweet_base_url + recode.id.to_s
else
@tweet_url = recode.web_url
end
Kyutech_bot.tweet_morning(recode.title, category.key(recode.category_id),department.key(recode.department_id), recode.campus_id, @tweet_url)
end
end # task morning_tweet
end # namespace
|
class CartDecorator < Draper::Decorator
delegate_all
def total_price
object.cart_items.reduce(0) do |sum,citem| sum + (citem.quantity * citem.price) end
end
def number_approved
object.approvals.where(role: 'approver').where(status: 'approved').count
end
def total_approvers
object.approvals.where(role: 'approver').count
end
def generate_status_message
number_approved == total_approvers ? completed_status_message : progress_status_message
end
def completed_status_message
"All #{number_approved} of #{total_approvers} approvals have been received. Please move forward with the purchase of Cart ##{object.external_id}."
end
def progress_status_message
"#{number_approved} of #{total_approvers} approved."
end
end
|
FactoryBot.define do
factory :visit do
id 'b3a55b78-182c-459f-aaf0-890d9da33fe6'
visitor_id '2ba5754c-ae63-4f14-a704-1370842659f2'
ip '68.173.187.194'
user_agent 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0'
referrer ''
landing_page 'https://blackopswiki.herokuapp.com/'
browser 'Firefox'
os 'Ubuntu'
device_type 'desktop'
screen_height '1024'
screen_width '600'
started_at DateTime.now
end
end |
# -*- coding: utf-8 -*-
require_relative 'error'
require_relative 'keep'
require_relative 'model/lost_world'
require 'digest/sha1'
Plugin.create(:world) do
# 登録されている全てのWorldを列挙する。
# 次のような方法で、Enumeratorを取得できる。
# ==== Example
# collect(:worlds)
defevent :worlds, prototype: [Pluggaloid::COLLECT]
# 新たなアカウント _1_ を追加する
defevent :world_create, prototype: [Diva::Model]
# アカウント _1_ が変更された時に呼ばれる
defevent :world_modify, prototype: [Diva::Model]
# アカウント _1_ を削除する
defevent :world_destroy, prototype: [Diva::Model]
world_struct = Struct.new(:slug, :name, :proc)
@world_slug_dict = {} # world_slug(Symbol) => World URI(Diva::URI)
defdsl :world_setting do |world_slug, world_name, &proc|
filter_world_setting_list do |settings|
[settings.merge(world_slug => world_struct.new(world_slug, world_name, proc))]
end
end
def world_order
at(:world_order) || []
end
def load_world
Plugin::World::Keep.accounts.map { |id, serialized|
provider = Diva::Model(serialized[:provider])
if provider
provider.new(serialized)
else
Miquire::Plugin.load(serialized[:provider])
provider = Diva::Model(serialized[:provider])
if provider
provider.new(serialized)
else
activity :system, _('アカウント「%{world}」のためのプラグインが読み込めなかったため、このアカウントは現在利用できません。') % {world: id},
description: _('アカウント「%{world}」に必要な%{plugin}プラグインが見つからなかったため、このアカウントは一時的に利用できません。%{plugin}プラグインを意図的に消したのであれば、このアカウントの登録を解除してください。') % {plugin: serialized[:provider], world: id}
Plugin::World::LostWorld.new(serialized)
end
end
}.compact.freeze.tap(&method(:check_world_uri))
end
def worlds_sort(world_list)
world_list.sort_by.with_index do |a, index|
[world_order.find_index(world_order_hash(a)) || Float::INFINITY, index]
end
end
def check_world_uri(new_worlds)
new_worlds.each do |w|
if @world_slug_dict.key?(w.slug)
if @world_slug_dict[w.slug] != w.uri
warn "The URI of World `#{w.slug}' is not defined. You must define a consistent URI for World Model. see: https://dev.mikutter.hachune.net/issues/1231"
end
else
@world_slug_dict[w.slug] = w.uri
end
end
end
def world_order_hash(world)
Digest::SHA1.hexdigest("#{world.slug}mikutter")
end
collection(:worlds) do |mutation|
mutation.rewind { |_| worlds_sort(load_world) }
on_world_create do |new|
return if new.is_a?(Plugin::World::LostWorld)
Plugin::World::Keep.account_register(new.slug, **new.to_hash, provider: new.class.slug)
mutation.rewind { |_| worlds_sort(load_world) }
Plugin.call(:world_after_created, new)
Plugin.call(:service_registered, new) # 互換性のため
rescue Plugin::World::AlreadyExistError
description = {
new_world: new.title,
duplicated_world: collect(:worlds).find{|w| w.slug == new.slug }&.title,
world_slug: new.slug }
activity :system, _('既に登録されているアカウントと重複しているため、登録に失敗しました。'),
description: _('登録しようとしたアカウント「%{new_world}」は、既に登録されている「%{duplicated_world}」と同じ識別子「%{world_slug}」を持っているため、登録に失敗しました。') % description
end
on_world_modify do |target|
return if target.is_a?(Plugin::World::LostWorld)
if Plugin::World::Keep.accounts.has_key?(target.slug.to_sym)
Plugin::World::Keep.account_modify(target.slug, { **target.to_hash, provider: target.class.slug })
mutation.rewind { |_| worlds_sort(load_world) }
end
end
on_world_destroy do |target|
Plugin::World::Keep.account_destroy(target.slug)
mutation.rewind { |_| worlds_sort(load_world) }
Plugin.call(:service_destroyed, target) # 互換性のため
end
# Worldのリストを、 _worlds_ の順番に並び替える。
on_world_reorder do |new_order|
store(:world_order, new_order.map(&method(:world_order_hash)))
mutation.rewind do |worlds|
worlds_sort(worlds).tap do |reordered|
Plugin.call(:world_reordered, reordered)
end
end
end
end
end
|
$:.push File.expand_path("../lib", __FILE__)
require 'renoval/version'
Gem::Specification.new do |s|
s.name = 'reno'
s.version = Renoval::VERSION
s.date = '2016-03-23'
s.summary = "Release Notes/changelog Validator"
s.description = "A tool to validate the content in the renogen generated files."
s.authors = "Miquel Oliete"
s.email = 'miqueloliete@gmail.com'
s.files = Dir.glob("{bin,lib,spec}/**/**/**") + %w(README.md LICENSE)
s.homepage = 'https://github.com/mob1970/renoval'
s.license = 'GPL-3.0'
s.executables << 'renoval'
s.required_ruby_version = '~> 2.0'
s.add_development_dependency 'rspec', '~> 3.0'
end
|
require 'test_helper'
class PlanningItemsControllerTest < ActionDispatch::IntegrationTest
setup do
@planning_item = planning_items(:one)
end
test "should get index" do
get planning_items_url
assert_response :success
end
test "should get new" do
get new_planning_item_url
assert_response :success
end
test "should create planning_item" do
assert_difference('PlanningItem.count') do
post planning_items_url, params: { planning_item: { day: @planning_item.day, end_time: @planning_item.end_time, planning_id: @planning_item.planning_id, start_time: @planning_item.start_time, status: @planning_item.status } }
end
assert_redirected_to planning_item_url(PlanningItem.last)
end
test "should show planning_item" do
get planning_item_url(@planning_item)
assert_response :success
end
test "should get edit" do
get edit_planning_item_url(@planning_item)
assert_response :success
end
test "should update planning_item" do
patch planning_item_url(@planning_item), params: { planning_item: { day: @planning_item.day, end_time: @planning_item.end_time, planning_id: @planning_item.planning_id, start_time: @planning_item.start_time, status: @planning_item.status } }
assert_redirected_to planning_item_url(@planning_item)
end
test "should destroy planning_item" do
assert_difference('PlanningItem.count', -1) do
delete planning_item_url(@planning_item)
end
assert_redirected_to planning_items_url
end
end
|
module Jenner
module LiquidFilters
def asset_from_path(path)
@context.registers[:site].assets.find { |asset| asset.path == path } || "Asset with path '#{path}' not found"
end
def item_from_path(path)
@context.registers[:site].items.find { |item| item.local_path == path } || "Item with path '#{path}' not found"
end
def items_from_path(path)
@context.registers[:site].items.select {|item| item.local_path =~ /^#{path}/ } || []
end
def tag(name)
@context.registers[:site].tags.find { |tag| tag.name == name } || "Tag with name '#{name}' not found"
end
def items_with_data(key, value=nil)
key_matches = @context.registers[:site].items.select { |item|
item.data.keys.include?(key)
}
return key_matches if value.nil?
# value was provided
key_matches.select do |item|
if item.data[key].is_a?(Array)
item.data[key].include?(value)
else
item.data[key] == value
end
end
end
def assign_to(value, name)
@context[name] = value
nil
end
def stylesheet_tag(path)
%(<link href="#{path}" media="all" rel="stylesheet" type="text/css" />)
end
def javascript_tag(path)
%(<script type="text/javascript" src="#{path}"></script>)
end
def link_to(item)
%(<a href="#{item.url}">#{item.title}</a>)
end
end
end
Liquid::Template.register_filter(Jenner::LiquidFilters)
|
class Booking < ApplicationRecord
validates :listing_id, :guest_id, :arrival_date, :departure_date, :num_guests, presence: true
validate :does_not_overlap_another_booking
validate :num_guests_does_not_exceed_max_guests
belongs_to :listing
belongs_to :guest,
foreign_key: :guest_id,
class_name: :User
has_one :host,
through: :listing,
source: :owner
def overlapping_bookings
Booking
.where.not(id: self.id)
.where(listing_id: self.listing_id)
.where.not('arrival_date >= :departure_date OR departure_date <= :arrival_date',
arrival_date: arrival_date, departure_date: departure_date)
end
def does_not_overlap_another_booking
unless overlapping_bookings.empty?
errors[:base] <<
'Booking conflicts with a pre-existing booking'
end
end
def num_guests_does_not_exceed_max_guests
unless num_guests <= self.listing.max_guests
errors[:num_guests] <<
'must be less than the allowed numbers of guests'
end
end
end
|
require 'spec_helper'
describe User do
before do
@user = User.new(name: "user", email: "user@example.com",
password: "foobarbar", password_confirmation: "foobarbar")
end
subject { @user }
it { should be_valid }
# shoulda relations
it { should have_one(:main_photo).class_name('Photo')}
it { should have_many(:blogs)}
it { should have_many(:albums)}
it { should have_many(:photos)}
it { should have_many(:videos)}
it { should have_many(:news)}
it { should have_and_belong_to_many(:subscriptions).class_name('User')}
it { should have_many(:events).class_name('Event').dependent(:destroy)}
it { should have_many(:event_points).class_name('Event')}
it { should have_many(:event_points).through(:subscriptions)}
it { should have_many(:updates)}
# relations
it { should respond_to(:main_photo)}
it { should respond_to(:blogs)}
it { should respond_to(:albums)}
it { should respond_to(:photos)}
it { should respond_to(:videos)}
it { should respond_to(:news)}
it { should respond_to(:subscriptions)}
it { should respond_to(:events)}
it { should respond_to(:event_points)}
it { should respond_to(:updates)}
# attributes
it { should respond_to(:name)}
it { should respond_to(:email)}
it { should respond_to(:password)}
it { should respond_to(:password_confirmation)}
it { should respond_to(:name)}
# FACTORY (:USER)
describe "Factory" do
let(:facuser) { FactoryGirl.create(:user) }
subject { facuser }
it { should be_valid }
end
# USER. NAME
describe "no name" do
before { @user.name = " " }
it { should_not be_valid }
end
# USER. EMAIL
describe "no email" do
before { @user.email = " "}
it { should_not be_valid }
end
describe "email already taken(case not sensitive)" do
before do
user_with_same_email = @user.dup
user_with_same_email.email = @user.email.upcase
user_with_same_email.save
end
it { should_not be_valid }
end
describe "mixed case email" do
let(:mixed_case_email) { "Foo@ExAMPle.CoM" }
it "doesn't save as all lower-case" do
@user.email = mixed_case_email
@user.save
expect(@user.reload.email).to eq mixed_case_email.downcase
end
end
#describe "invalid email" do
# it "should be invalid" do
# addresses = %w[user@foo,com user_at_foo.org example.user@foo.
# foo@bar_baz.com foo@bar+baz.com foo@bar..com]
# addresses.each do |invalid_address|
# @user.email = invalid_address
# expect(@user).not_to be_valid
# end
# end
#end
#describe "valid email" do
# it "should be valid" do
# addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn]
# addresses.each do |valid_address|
# @user.email = valid_address
# expect(@user).to be_valid
# end
# end
#end
# USER. PASSWORD
describe "no password" do
before { @user.password = " "}
it { should_not be_valid}
end
describe "no confirm" do
before { @user.password_confirmation = " "}
it { should_not be_valid }
end
describe "short password" do
before { @user.password = @user.password_confirmation = "a" * 5 }
it { should be_invalid }
end
describe "password and conformation match" do
before { @user.password_confirmation = "mismatch" }
it { should_not be_valid }
end
# omnomnom test?
# like
# describe "signing in" do
# before { sign_in @user }
# it { should eq current_user }
# end
# acts_as_messageable
end
|
class AddPrizeRelationalColumnsToRewards < ActiveRecord::Migration
def change
add_column :rewards, :prize_type, :integer, default: 0
add_column :rewards, :points_to_unlock, :integer
add_column :rewards, :redeem_confirm_msg, :text
end
end
|
class RenameNameAndSurnameColumns < ActiveRecord::Migration
def change
rename_column :participants, :name, :first_name
rename_column :participants, :surname, :last_name
end
end
|
# Ruby Neural Network Library
#
# Basic implementation of a (currently) feed forward neural network.
#
# = Basic Usage
#
# nn = NeuralNetwork.new("unique_name")
#
# # Assign number of randomly built neurons to layer
# il = NetworkLayer.new(3)
# hl = NetworkLayer.new(5)
# ol = NetworkLayer.new(3)
#
# nn.pushInputLayer(il)
# nn.pushHiddenLayer(hl)
# nn.pushOutputLayer(ol)
#
# nn.run # Returns a NetworkLayer by default, override with nn.return_vector = true
#
# Author:: Brian Jones (mailto:mojobojo@gmail.com)
# Copyright:: Copyright (c) 2009 Brian Jones
# License:: The MIT License
include Math
# = Network Loader
#
# Saves and loads a serliazed neural network from disk.
# Networks are named with a unique id and a .network extension.
class NetworkLoader
# The default path is set to the local ./data directory.
@@path = "./data"
# The extension with which to save a network.
@@extension = "network"
# Overrides the current @@path default.
def setPath(path)
@@path = path
end
# Overrides the current @@extension default.
def setExtension(ext)
@@extension = ext
end
# Writes a network out to disk.
def saveNetwork(nn)
data = Marshal.dump(nn)
f = File.new("%s/%s.%s" % [@@path, nn.id, @@extension], "w")
f.write(data)
f.close
end
# Loads a network with the corresponding id from disk and returns it.
def loadNetwork(id)
f = File.open("%s/%s.%s" % [@@path, id, @@extension], "r")
data = Marshal.load(f)
f.close
return data
end
end
# = Neural Network
#
# Basic feed forward neural network. Consists of
# an input layer, output layer, and 1..n hidden layers.
# Layers are derived from the NetworkLayer class.
#
# * If set to true, network.squash will condense values to a range of 0..1
# * If set to true, network.return_vector will return a vector instead of a layer
class NeuralNetwork
attr_reader :id
attr_writer :return_vector, :squash
# Initializes the network with a given id.
# This id determines how the network will be
# both tracked, saved, and loaded.
def initialize(id)
@id = id
@layers = Array.new
# Track if layer was pushed onto layer stack
@input_pushed = nil
@output_pushed = nil
# Return layer (default), or a vector
@return_vector = nil
# Squash return values to 0, 1?
@squash = nil
# Default min/max values
@MIN = 0.0
@MAX = 1.0
end
# Override the @MIN value.
def setMin(value)
@MIN = value
end
# Override the @MAX value.
def setMax(value)
@MAX = value
end
# Runs the network with given input.
# Results are stored in the output layer.
#
# Input can be given in two forms:
# * A vector of values.
# * A NetworkLayer consisting of NetworkNeurons.
def run(input=nil)
# If input isn't nil, then a vector or layer is being passed in instead of a preinit'ed input layer
if !input.nil?
if input.kind_of?(NetworkLayer)
last_layer = input
elsif input.kind_of?(Array)
last_layer = NetworkLayer.new(input.size)
last_layer.getNeurons.each do |n|
n.output = input.shift()
end
end
else
l = @layers # Copy the layers array
last_layer = l.shift() # Pop input layer off copied stack
end
# Process the data
@layers.each do |l|
l.getNeurons.each do |n|
sum = 0.0
# Sum the weight of the neuron against the input values
for neuron in last_layer.getNeurons
sum = n.weight * neuron.output + sum
end
# Smooth the sum using the neurons activation function
value = eval("%s(sum)" % n.activation_function)
if !@squash.nil? # Squash the value
if n.threshold < value
n.output = @MIN
else
n.output = @MAX
end
else # Return the raw value
n.output = value
end
end
last_layer = l
end
if @return_vector.nil?
return last_layer # Last layer will be the output layer
else
d = Array.new
last_layer.getNeurons.each do |n|
d.push(n.output)
end
return d # Return back a vector instead of a layer
end
end
# Push a new input layer into the stack.
def pushInputLayer(layer)
if @input_pushed.nil?
if layer.kind_of?(NetworkLayer)
@layers.unshift(layer)
elsif layer.kind_of?(Fixnum)
l = NetworkLayer.new(layer)
@layers.unshift(layer)
else
raise "No valid input layer data pushed to method"
end
else
raise "An input layer was already pushed onto the stack"
end
@input_pushed = true
end
# Push hidden layers onto the stack.
def pushHiddenLayer(layer)
if layer.kind_of?(NetworkLayer)
l = layer
elsif layer.kind_of?(Fixnum)
l = NetworkLayer.new(layer)
else
raise "No valid layer data pushed to method"
end
if !@output_pushed.nil? # Output layer was pushed, insert before it
ol = @layers.pop() # Pop the output layer
@layers.push(l) # Push the new layer
@layers.push(ol) # Push the output layer
else
@layers.push(l)
end
end
# Push the output layer onto the stack.
def pushOutputLayer(layer)
if @output_pushed.nil?
if layer.kind_of?(NetworkLayer)
l = layer
elsif layer.kind_of?(Fixnum)
l = NetworkLayer.new(layer)
else
raise "No valid output layer data pushed to method"
end
else
raise "An output layer was already pushed onto stack"
end
@layers.push(l)
@output_pushed = true
end
# Render relevant data about the network.
def printNetwork
print "Network Name: %s\n" % @id
print "----\n"
count = 0
@layers.each do |l|
count = count + 1
print "Layer: %i\n" % count
print "Layer Id: %s\n" % l.id
ncount = 0
l.getNeurons.each do |n|
ncount = ncount + 1
print " - Neuron Id: %s\n" % n.id
print " - Neuron: %i\n" % ncount
print " -- Weight: %f\n" % n.weight
print " -- Threshold: %f\n" % n.threshold
end
end
end
end
# = Network Layer
#
# Contains a set of NetworkNeurons.
class NetworkLayer
@@type = "Layer"
attr_reader :id
# Either initializes with a vector of neurons,
# or just a number of neurons to create.
# Gets a unique id from NetworkIdGeneratorClass.
def initialize(neurons)
@id = NetworkIdGeneratorClass.generateId(@@type)
@neurons = Array.new
if neurons.kind_of?(Integer)
buildLayer(neurons)
else
@neurons = neurons
end
end
# If a numeric value was set during initialization,
# build the layer with NetworkNeurons.
def buildLayer(neurons)
neurons.times do
neuron = NetworkNeuron.new
@neurons.push(neuron)
end
end
# Return the neurons for this layer.
def getNeurons
return @neurons
end
end
# = Network Neuron
#
# The neurons within a layer.
# Neurons are assigned a default activation function referenced by string,
# currently set to the sigmoid function. This can be overridden.
class NetworkNeuron
@@type = "Neuron"
@@default_af = "sigmoid"
attr_reader :id, :weight, :threshold, :activation_function, :output
attr_writer :weight, :threshold, :activation_function, :output
# Initializes a neuron with either a passed floating point value,
# or will default to 0.0.
#
# * The threshold and weight values are set to a random value.
# * The neuron is assigned a unique id.
# * The weight, threshold, and activation function can be overridden.
def initialize(input=nil)
@id = NetworkIdGeneratorClass.generateId(@@type)
if !input.nil?
@output = input
else
@output = 0.0
end
@threshold = rand(0)
@weight = rand(0)
@activation_function = @@default_af # Initializes to the default
end
# Randomize the neurons weight.
def randWeight
@weight = rand(0)
end
# Randomize the neurons threshold.
def randThreshold
@threshold = rand(0)
end
# Randomize both the weight and threshold.
def randAll
randWeight()
randThreshold()
end
# Override the @weight value.
def setWeight(value)
@weight = value
end
# Override the @threshold value.
def setThreshold(value)
@threshold = value
end
end
# = Network Id Generator
#
# Generates a new id, starting from 100.
class NetworkIdGenerator
@@counter = 100
def generateId(type)
@@counter = @@counter + 1
return "%s-%i" % [type, @@counter]
end
# Returns the current value of @@counter.
def current
return @@counter
end
end
NetworkIdGeneratorClass = NetworkIdGenerator.new
# = Sigmoid activation function.
def sigmoid(x)
return (1.0 / (1.0 + exp(-x)))
end |
require File.dirname(__FILE__) + '/../test_helper'
require 'expenses_controller'
# Re-raise errors caught by the controller.
class ExpensesController; def rescue_action(e) raise e end; end
class ExpensesControllerTest < Test::Unit::TestCase
fixtures :expenses, :categories, :users
def setup
@controller = ExpensesController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_should_require_login
get :index
assert_response :redirect
assert_redirected_to new_session_url
end
def test_should_show_index
login_as :quentin
get :index
assert_response :success
end
def test_should_create_expense
login_as :quentin
assert_no_difference Category, :count do
assert_difference categories(:quentins_software).expenses(:refresh), :size do
put :create, :expense => @@default_expense.merge({:category => categories(:quentins_software).name})
assert_valid assigns(:expense)
assert_equal assigns(:expense).errors.size, 0
assert_redirected_to expenses_url
# dunno why i have to force the refresh here :(
categories(:quentins_software).expenses(:refresh)
end
end
end
def test_should_require_name
login_as :quentin
assert_no_difference Expense, :count do
put :create, :expense => @@default_expense.merge({:name => nil})
assert_template "index"
end
end
def test_should_sum_expenses
login_as :quentin
get :index
assert_equal assigns(:total_price), (4995.0+2995.0)/100.0
end
def test_should_delete_expense
login_as :quentin
assert_difference Expense, :count, -1 do
xhr :delete, :destroy, :id => expenses(:agile_web_dev).id
assert_response :success
assert_rjs :visual_effect, :fade, assigns(:dom_id)
end
end
def test_should_edit_expense
login_as :quentin
assert_no_difference Expense, :count do
xhr :get, :edit, :id => expenses(:agile_web_dev).id
assert_response :success
assert_rjs :replace_html, assigns(:expense).dom_id
end
end
def test_should_update_expense
login_as :quentin
assert_no_difference Expense, :count do
xhr :put, :update, :id => expenses(:agile_web_dev).id, :expense => {:name => "bobo"}
assert_response :success
assert_rjs :replace_html, assigns(:expense).dom_id
assert_template "show"
end
end
def test_should_create_expense
login_as :quentin
assert_difference Category, :count do
assert_difference Expense, :count do
xhr :post, :create, :expense => {:name => "something", :category => "BozosRUs", :price => "14.95"}
assert_response :success
assert_rjs :insert_html, :top, 'expenses'
assert_rjs :visual_effect, :highlight, assigns(:expense).dom_id
end
end
end
end
|
# == Schema Information
#
# Table name: access_tokens
#
# id :integer not null, primary key
# encrypted_token_value :string
# encrypted_token_value_iv :string
# user_id :integer
# device_id :string not null
#
# Indexes
#
# index_access_tokens_on_user_id (user_id)
#
RSpec.describe AccessToken, type: :model do
it { should belong_to(:user) }
it { should validate_presence_of(:encrypted_token_value) }
it { should validate_presence_of(:device_id) }
describe 'uniqueness validators' do
# Create a model first, since the database will not allow an empty field, then test the model for uniqueness
subject { create(:access_token) }
it { should validate_uniqueness_of(:device_id) }
end
context '#compare_tokens' do
let!(:user) { create(:user) }
describe 'successful' do
it 'given the same device id, it should return the token itself' do
access_token = AccessTokens::CreateService.new(user: user).call
authenticated_token = AccessToken.compare_tokens(
token_value: access_token.token_value,
device_id: access_token.device_id
)
expect(authenticated_token).to be_a_kind_of(AccessToken)
end
end
describe 'failure' do
it 'given the same device id, if the token is wrong, it should raise an AccessTokenError' do
access_token = AccessTokens::CreateService.new(user: user).call
expect{ AccessToken.compare_tokens(
token_value: "THE WRONGEST ACCESS TOKEN IN THE WORLD!",
device_id: access_token.device_id
) }.to raise_error(Errors::InvalidAccessTokenError)
end
end
end
end
|
class Tag < ActiveRecord::Base
attr_accessible :tag_group_id, :title
has_many :gallery_images
belongs_to :tag_group
validates :title, presence: true
end
|
class WaybillsController < ApplicationController
layout 'app'
def self.waybill_resave(waybill, force_new = true)
if waybill.reprint(force_new)
waybill.delay.resave
end
end
def can_view(wb)
return true unless wb
return get_current_org.id == wb.wb_invoice.organization.id
end
def print
waybill = Waybill.find(params[:id])
redirect_to(invoices_url, :notice => 'არ გაქვთ ამ სასაქონლო ზედნადების დაბეჭდვის უფლება.') and return unless can_view(waybill)
send_file(waybill.file_path, :disposition => 'inline', :x_sendfile=>true, :type => :pdf, :filename => "#{waybill.print_file}.pdf")
end
def check_print
waybill = Waybill.find(params[:id])
if waybill.is_ready_for_print
render :text => 'ok'
else
WaybillsController.waybill_resave(waybill, false)
render :text => 'not ready'
end
end
def show
@waybill = Waybill.find(params[:id])
redirect_to(invoices_url, :notice => 'არ გაქვთ ამ ზედნადების ნახვის უფლება.') and return unless can_view(@waybill)
respond_to do |format|
format.pdf do
output = WaybillReportNew.new.to_pdf(@waybill)
send_data output, :filename => "waybill_#{@waybill.wb_invoice.number}.pdf", :type => :pdf, :disposition => 'inline'
end
end
end
end
|
class CreateRides < ActiveRecord::Migration[5.1]
def up
create_table :rides do |t|
t.float :source_latitude
t.float :source_longitude
t.float :destination_latitude
t.float :destination_longitude
t.references :cab, foreign_key: true
t.timestamps
end
end
def down
drop_table :rides
end
end
|
class UtilityController < ApplicationController
def set_locale
session[:locale] ||= I18n.default_locale
super
end
end
|
class CreateSequence < ActiveRecord::Migration
def change
create_table :sequences do |t|
t.string :category,default: 'integer' #string or integer
t.integer :capacity,default: 0
t.integer :value
t.string :name,index: true
t.timestamps
end
end
end
|
class Owner < ActiveRecord::Base
has_many :estates,
inverse_of: :owner,
dependent: :nullify
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :email
validates_format_of :email,
with: /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i
def estate_names
address = []
if self.estates.present?
self.estates.each do |estate|
address << estate.street_address
end
address.join(",")
else
"Not a badass"
end
end
class << self
def names
self.pluck(:last_name)
end
end
end |
require 'capybara/cucumber'
require_relative '../../pastebit'
Capybara.app = PasteBit.new
Given /^I have some text$/ do
@content = "Hello world!"
end
When /^I go to the homepage$/ do
visit '/'
end
Then /^I can paste some text$/ do
fill_in "pasted_content", with: @content
find_button('paste_button').click
end
Then /^be redirected to a unique page$/ do
current_path.should =~ /\/[a-zA-Z0-9]{40}/
end
Then /^be redirected to a unique page with the pasted content on$/ do
page.should have_content @content
end
|
require 'spec_helper'
describe Event do
it { should validate_presence_of :description }
it { should validate_presence_of :location }
it { should validate_presence_of :start }
it { should validate_presence_of :end }
end
|
class Piece
attr_reader :set, :position
def initialize(name, position, set, valid_moves)
@name = name
@position = position
@set = set
@valid_moves = valid_moves
end
module Set
BLACK = :black
WHITE = :white
end
def move_to(position)
if is_move_valid(position)
return @position = position
end
raise(Exceptions::InvalidMoveException)
end
def state
{
name: @name,
position: {
x: @position.x_coordinate,
y: @position.y_coordinate
},
set: @set,
}
end
private
def is_move_valid(proposed_position)
@valid_moves.select { |move| move.call(@position, proposed_position) }.length > 0
end
end |
class CollaborationsController < ApplicationController
before_action :set_collaboration, only: [:show, :update, :destroy]
def index
@collaborations = Collaboration.all
render json: @collaborations
end
def show
render json: @collaboration
end
def create
@collaboration = Collaboration.new(collaboration_params)
if @collaboration.save
render json: @collaboration, status: :created, location: @collaboration
else
render json: @collaboration.errors, status: :unprocessable_entity
end
end
def update
if @collaboration.update(collaboration_params)
render json: @collaboration
else
render json: @collaboration.errors, status: :unprocessable_entity
end
end
def destroy
@collaboration.destroy
end
private
def set_collaboration
@collaboration = Collaboration.find(params[:id])
end
def collaboration_params
params.require(:collaboration).permit(:message, :requester_id, :requestee_id, :requester_goal_id, :requestee_goal_id, :request_status_id)
end
end
|
class RemoveEncryptedUsernameFromStudent < ActiveRecord::Migration
def change
remove_column :students, :encrypted_username, :student
end
end
|
include_recipe 'heads'
include_recipe 'git'
include_recipe 'gcc::depends'
build_user = 'heads'
build_home = '/home/' + build_user
build_dir = build_home + '/gdc'
prefix = '/usr/local/gdc-head'
build_sh = build_home + '/build/gdc.sh'
gcc_git_repo = 'git://gcc.gnu.org/git/gcc.git'
flags = '--enable-lto --disable-multilib --without-ppl --without-cloog-ppl --enable-checking=release --disable-nls'
gdc_git_repo = 'https://github.com/D-Programming-GDC/GDC.git'
languages = 'd'
bash 'git clone gcc for gdc' do
action :run
user 'root'
cwd build_home
code <<-SH
su - #{build_user} -c '
mkdir -p #{build_dir}
git clone #{gcc_git_repo} #{build_dir + '/gcc-source'}
cd #{build_dir + '/gcc-source'}
git checkout master
'
SH
not_if "test -d #{build_dir + '/gcc-source'}"
end
bash 'git clone gdc' do
action :run
user 'root'
cwd build_home
code <<-SH
su - #{build_user} -c '
mkdir -p #{build_dir}
git clone #{gdc_git_repo} #{build_dir + '/gdc-source'}
cd #{build_dir + '/gdc-source'}
git checkout master
'
SH
not_if "test -d #{build_dir + '/gdc-source'}"
end
file build_sh do
mode '0755'
user 'root'
group 'root'
content <<-SH
#!/bin/bash
set -ex
su - #{build_user} -c '
set -ex
cd #{build_dir}/gdc-source
git clean -xdqf
git reset --hard
git pull
git clean -xdqf
#cd libphobos
#autoreconf -i
sed -i "s/d-warn = .*/\\\\0 -Wno-suggest-attribute=format/" gcc/d/Make-lang.in
sed -i "s/real sgngam = 1/real sgngam = 1.0L/" libphobos/src/std/internal/math/gammafunction.d
cd #{build_dir}/gcc-source
git clean -xdqf
git reset --hard
git pull
'
cd /home/heads/gdc/gcc-source
VERSION=`cut -d- -f3 < ../gdc-source/gcc.version`
BEFORE=`date "+%Y-%m-%d" -d "$VERSION next day"`
COMMIT=`TZ=UTC git log -n1 --pretty=tformat:%H --before=$BEFORE`
echo $COMMIT > commit
su - heads -c '
set -ex
cd /home/heads/gdc/gcc-source
git reset --hard `cat commit`
git clean -xdqf
cd #{build_dir}/gdc-source
./setup-gcc.sh #{build_dir}/gcc-source
rm -rf #{build_dir}/build || true
mkdir #{build_dir}/build
cd #{build_dir}/build
#{build_dir}/gcc-source/configure --prefix=#{prefix} --enable-languages=#{languages} #{flags}
nice make -j2
'
cd #{build_dir}/build
make install
SH
end
# test building
bash 'test building gdc-head' do
action :run
user 'root'
code build_sh
not_if "test -e #{prefix + '/bin/gdc'}"
end
|
class CreateUserEventLogs < ActiveRecord::Migration
def change
create_table :user_event_logs do |t|
t.references :event_subscription, index: true
t.decimal :weight
t.date :date
t.text :comment
t.timestamps
end
end
end
|
class Instructor < ActiveRecord::Base
has_many :courses
belongs_to :department
end
|
# Method to create a list
# input: string of items separated by spaces (example: "carrots apples cereal pizza")
# steps:
# break up string of items into seperate values
# assign values as keys in a hash with default quantity of 1
# print the list to the console [can you use one of your other methods here?]
# output: list of items and quantities in a hash
list_of_items = "lemonade tomatoes onions ice-cream"
def grocery_list (list_of_items)
split_list = list_of_items.split(" ")
items_hash = Hash.new
split_list.each do |food|
items_hash[food] = "1"
end
return items_hash
end
items_hash = grocery_list(list_of_items)
# Method to add an item to a list
# input: item name and optional quantity
# steps: add item and quantiity to the container
# output: new container that includes the new item
def add_item(item, quantity)
items_hash[item]= quantity
return items_hash
end
puts add_item("potato", "2")
# # Method to remove an item from the list
# # input: item we want to delete
# # steps: delete specfic key
# # output: new container without the item we removed
def remove_item(item)
smaller_items_hash = new_items_hash.delete[item]
return smaller_items_hash
end
smaller_items_hash = remove_item("lemonade")
# # # Method to update the quantity of an item
# # # input: new quantity
# # # steps: overwrite item and quantity with new quantity
# # # output: new container with new quantity
def update_item(item, quantity)
update_items_hash = smaller_items_hash[item] = [quantity]
return update_items_hash
end
update_item("ice cream", "1")
# # # Method to print a list and make it look pretty
# # # input: print command
# # # steps: use print command
# # # output: pretty list
def print_list(update_items_hash)
puts update_items_hash
end
# # puts( your_hash.map{ |k,v| "#{k} => #{v}" }.sort )
|
# frozen_string_literal: true
require 'bundler/audit/task'
require 'bundler/gem_tasks'
require 'rspec/core/rake_task'
require 'rubocop/rake_task'
Bundler::Audit::Task.new
RSpec::Core::RakeTask.new(:spec)
RuboCop::RakeTask.new
desc 'Run CI'
task :ci do
Rake::Task['bundle:audit'].invoke
Rake::Task['rubocop'].invoke
Rake::Task['spec'].invoke
end
task default: :ci
|
require 'rails_helper'
describe Contact, type: :model do
it "has a valid factory" do
expect(FactoryGirl.create(:contact)).to be_valid
end
it "is invalid without a firstname" do
expect(FactoryGirl.build(:contact, first_name: nil)).to_not be_valid
end
it "is invalid without a lastname" do
expect(FactoryGirl.build(:contact, last_name: nil)).to_not be_valid
end
it "allows contact photo upload"
end
|
# A builder is looking to build a row of N houses that can be of K different colors.
# He has a goal of minimizing cost while ensuring that no two neighboring houses are
# of the same color.
# Given an N by K matrix where the nth row and kth column represents the cost to build
# the nth house with kth color, return the minimum cost which achieves this goal. |
require 'rails_helper'
RSpec.describe Candidate, :type => :model do
before do
@question = FactoryGirl.create :question
@candidate = FactoryGirl.create :candidate
end
it 'starts off not having answered a question' do
expect(@candidate.has_answered?(@question)).to be(false)
end
it 'can answer a question' do
@candidate.gives_answer_to(@question)
expect(@candidate.has_answered?(@question)).to be(false)
end
end
|
module TheCityAdmin
FactoryGirl.define do
factory :group_export, :class => TheCityAdmin::GroupExport do
created_at "02/06/2012 11:36 PM (EST)"
authenticated_s3_url ""
id 62706
state "inqueue"
end
end
end
|
Rails.application.routes.draw do
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :stories
get :view_all_stories, to: 'stories#view_all_stories'
get :my_stories, to: 'stories#my_stories'
post :mark_as_favourite, to:'stories#mark_as_favourite'
get :my_favourite_stories, to: 'stories#my_favourite_stories'
root :to => "homes#index"
end
|
class Contact
attr_reader(:name, :job_title, :company, :id, :phone_numbers, :emails, :addresses)
@@contacts = []
define_method(:initialize) do |attributes|
@name = attributes.fetch(:name)
@job_title = attributes.fetch(:job_title)
@company = attributes.fetch(:company)
@id = @@contacts.length() + 1
@phone_numbers = []
@emails = []
@addresses = []
end
define_method(:first_name) do
@name.split(" ")[0]
end
define_method(:last_name) do
@name.split(" ").last()
end
define_method(:save) do
@@contacts.push(self)
end
define_method(:add_number) do |number|
@phone_numbers.push(number)
end
define_method(:add_email) do |email|
@emails.push(email)
end
define_method(:add_address) do |address|
@addresses.push(address)
end
define_method(:get_number) do
@phone_numbers[0]
end
define_singleton_method(:clear) do
@@contacts = []
end
define_singleton_method(:all) do
@@contacts
end
define_singleton_method(:find) do |id|
@@contacts[id - 1]
end
end
|
class Vehicle < ActiveRecord::Base
belongs_to :brand
belongs_to :vehicle_type
belongs_to :customer
attr_accessible :name, :brand_id, :vehicle_type_id, :customer_id, :precio, :cantkm, :tipocombustible, :anio
validates :name, :brand_id, :presence => {:message => 'pone algo'}#valida que no esten nulos
validates :phone, :numericality => true, :allow_blank =>true
def full_name
"#{brand.name} -#{name} (#{vehicle_type.name})"
end
end
|
require 'spec_helper'
describe Manager::QuestpagesController do
render_views
before :each do
Questpage.all.each { |q| q.remove }
@questpage = FactoryGirl.create :questpage
end
it '#index' do
get :index
response.should be_success
response.should render_template( 'manager/questpages/index' )
assigns( :questpages ).should_not eql nil
end
it '#new' do
get :new
response.should be_success
response.should render_template( 'manager/questpages/new' )
expect(response.body).to have_tag( "body" )
assigns( :questpage ).should_not eql nil
end
it '#edit' do
get :edit, :id => @questpage.id
response.should be_success
response.should render_template( 'manager/questpages/edit' )
assigns( :questpage ).should_not eql nil
end
it '#update' do
# patch :update, :id => @questpage.id, :questpage => { :unavailable_mouseover => 'xxunavailable_mouseoverxx' }
# result = Questpage.find @questpage.id
# result.unavailable_mouseover.should eql 'xxunavailable_mouseoverxx'
end
end
|
class TypeOfTechnicalFile < ActiveRecord::Base
has_many :technical_files
end
|
# Chris Durtschi
# CS 4820
# David Hart
# MicroCom - Code Generation Phase
class CodeGenerator
@@arithmetic_operators = {'PlusOp' => 'ADD', 'MinusOp' => 'SUB',
'MultiplyOp' => 'MPY', 'DivideOp' => 'DIV'}
@@io_operators = {'ReadSym' => 'IN', 'WriteSym' => 'OUT'}
def initialize(lis_path, tas_path, atoms, symbol_table, int_literal_table)
@lis_path = lis_path
@tas_path = tas_path
@atoms = atoms
@symbol_table = symbol_table
@int_literal_table = int_literal_table
@instructions = []
@labels = []
end
def generate
create_instructions_from_atoms
@instructions.push({:label => pop_next_label, :operator => 'STOP'})
add_symbols
add_int_literals
add_temps
@instructions.push({:operator => 'END'})
optimize_instructions
write_tas
message = 'Code generation successful - .tas file generated'
write_lis(message)
puts(message)
end
private
def create_instructions_from_atoms
@atoms.reverse!
while atom = @atoms.pop
operator = atom.first
if @@arithmetic_operators.include?(operator)
generate_arithmetic(atom)
elsif @@io_operators.include?(operator)
generate_io(atom)
elsif operator == 'AssignOp'
generate_assignment(atom)
elsif operator == 'Tst'
generate_test(atom)
elsif operator == 'Br'
generate_branch(atom)
elsif operator == 'Lbl'
@labels.push(atom.last)
else
raise 'First atom is not PlusOp, MinusOp, MultiplyOp, DivideOp,
AssignOp, Tst, Lbl, Br, ReadSym, or WriteSym'
end
end
end
def generate_arithmetic(atom)
second = atom.pop
first = atom.pop
result = atom.pop
operator = atom.pop
@instructions.push({:label => pop_next_label, :operator => 'LD',
:operand => first})
@instructions.push({:operator => @@arithmetic_operators[operator],
:operand => second})
@instructions.push({:operator => 'STO', :operand => result})
end
def generate_io(atom)
value = atom.pop
operator = atom.pop
@instructions.push({:label => pop_next_label,
:operator => @@io_operators[operator], :operand => value})
end
def generate_assignment(atom)
value = atom.pop
result = atom.pop
@instructions.push({:label => pop_next_label, :operator => 'LD',
:operand => value})
@instructions.push({:operator => 'STO', :operand => result})
end
def generate_test(atom)
false_label = atom.pop
operator = atom.pop
operand2 = atom.pop
operand1 = atom.pop
case operator
when 'EqSym'
generate_equal_test(operand1, operand2, false_label)
when 'NotEqSym'
generate_not_equal_test(operand1, operand2, false_label)
when 'GrSym'
generate_gr_ls_test(operand1, operand2, false_label)
when 'LsSym'
generate_gr_ls_test(operand2, operand1, false_label)
when 'GrEqSym'
generate_gr_ls_eq_test(operand1, operand2, false_label)
when 'LsEqSym'
generate_gr_ls_eq_test(operand2, operand1, false_label)
else
raise 'Test is not EqSym, NotEqSym, GrSym, LsSym, GrEqSym, or LsEqSym'
end
end
def generate_equal_test(operand1, operand2, false_label)
@instructions.push({:label => pop_next_label, :operator => 'LD',
:operand => operand1})
@instructions.push({:operator => 'SUB', :operand => operand2})
@instructions.push({:operator => 'BGTR', :operand => false_label})
@instructions.push({:operator => 'LD', :operand => operand2})
@instructions.push({:operator => 'SUB', :operand => operand1})
@instructions.push({:operator => 'BGTR', :operand => false_label})
end
def generate_not_equal_test(operand1, operand2, false_label)
@instructions.push({:label => pop_next_label, :operator => 'LD',
:operand => operand1})
@instructions.push({:operator => 'SUB', :operand => operand2})
@instructions.push({:operator => 'BZ', :operand => false_label})
end
def generate_gr_ls_test(operand1, operand2, false_label)
@instructions.push({:label => pop_next_label, :operator => 'LD',
:operand => operand2})
@instructions.push({:operator => 'SUB', :operand => operand1})
@instructions.push({:operator => 'BGTR', :operand => false_label})
@instructions.push({:operator => 'BZ', :operand => false_label})
end
def generate_gr_ls_eq_test(operand1, operand2, false_label)
@instructions.push({:label => pop_next_label, :operator => 'LD',
:operand => operand2})
@instructions.push({:operator => 'SUB', :operand => operand1})
@instructions.push({:operator => 'BGTR', :operand => false_label})
end
def generate_branch(atom)
@instructions.push({:label => pop_next_label, :operator => 'B',
:operand => atom.last })
end
def add_symbols
@symbol_table.each do |symbol|
@instructions.push({:label => "#{symbol}:", :operator => 'DC',
:operand => '0'})
end
end
def add_int_literals
@int_literal_table.each do |int|
id = "_int#{@int_literal_table.index(int)}:"
@instructions.push({:label => id, :operator => 'DC', :operand => int})
end
end
def add_temps
temps = []
@instructions.each do |code|
operand = code[:operand]
if operand && temp_symbol?(operand)
temps.push(operand) if !temps.include?(operand)
end
end
temps.each do |temp|
@instructions.push({:label => "#{temp}:", :operator => 'DC',
:operand => '0'})
end
end
def pop_next_label
label = @labels.pop
return "#{label}:" if label
end
def optimize_instructions
@instructions.reverse!
@labels = []
optimized = []
while code = @instructions.pop
if code[:operator] == 'STO'
# Find out if the next operation is LD
next_code = @instructions.pop
if next_code && next_code[:operator] == 'LD' &&
next_code[:operand] == code[:operand]
if temp_symbol?(code[:operand])
# This is a STO/LD combo with a temporary variable,
# discard both instructions and continue.
@labels.push(next_code[:label]) if next_code[:label]
@labels.push(code[:label]) if code[:label]
next
else
# This is a STO/LD combo with a non-temporary variable,
# keep the STO, discard the LD.
@labels.push(next_code[:label]) if next_code[:label]
optimized.push(code)
end
else
# This is not a STO/LD combo, push both instructions back
# to the optimized stack.
code[:label] = @labels.pop if !code[:label]
next_code[:label] = @labels.pop if !next_code[:label]
optimized.push(code)
optimized.push(next_code)
end
else
# This is not a STO instruction, no optimization needed,
# push code onto optimized stack.
code[:label] = @labels.pop if !code[:label]
optimized.push(code)
end
end
@instructions = optimized
end
def temp_symbol?(symbol)
return symbol.match(/^_temp\d+$/)
end
def write_tas
File.open(@tas_path, "w") do |file|
@instructions.each do |code|
file.printf("%-9s %-5s %s\n", code[:label], code[:operator],
code[:operand])
end
end
end
def write_lis(message)
File.open(@lis_path, "a") do |file|
file.puts(message)
end
end
end |
require 'spec_helper'
describe "SimpleDBAdapter ActiveRecord where statement" do
before :each do
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection($config)
ActiveRecord::Base.connection.create_domain($config[:domain_name])
Person.create!(Person.valid_params)
end
after :each do
ActiveRecord::Base.connection.delete_domain($config[:domain_name])
end
it "should be return items by conditions with different type values" do
Person.valid_params.each do |name, value|
result = Person.where(name => value).first
result.try(name).should == value
end
end
it "should be return items by condition with table name prefix" do
result = Person.where("people.state" => 'paid').first
result.state.should == 'paid'
end
end
|
require 'csv'
require 'sunlight/congress'
require 'erb'
require 'pry'
Sunlight::Congress.api_key = "e179a6973728c4dd3fb1204283aaccb5"
def clean_zipcode(zipcode)
zipcode.to_s.rjust(5, "0")[0..4]
end
def number_formatter(number)
[3, 7].each { |x| number.insert(x, "-") }
number
end
def clean_phone_numbers(number)
return "-" if number.nil?
number.to_s.gsub!(/\D/, "")
if number.length == 10
number_formatter(number)
elsif number.length == 11 && number[0] == "1"
number[0] = ""
number_formatter(number)
else
"-"
end
end
@registration_hours = []
def format_time(time)
DateTime.strptime(time, "%m/%d/%y %k:%M")
end
def group_registration_by_hour
@registration_hours.group_by { |time| time.hour }
end
def print_registration_by_hour
max_hours = group_registration_by_hour.values.max { |a, b| a.length <=> b.length }.length
group_registration_by_hour.select { |k, v| v.length >= max_hours }.each do |k, v|
puts v[0].strftime("The busiest registration hour(s): %l%p")
end
end
def group_registration_by_weekday
@registration_hours.group_by { |time| time.wday }
end
def print_registration_by_weekday
max_days = group_registration_by_weekday.values.max { |a, b| a.length <=> b.length }.length
group_registration_by_weekday.select { |k, v| v.length >= max_days }.each do |k, v|
puts v[0].strftime("The busiest registration day(s): %A")
end
end
def legislators_by_zipcode(zipcode)
Sunlight::Congress::Legislator.by_zipcode(zipcode)
end
def save_thank_you_letters(id, form_letter)
Dir.mkdir("output") unless Dir.exists?("output")
filename = "output/thanks_#{id}.html"
File.open(filename, 'w') do |file|
file.puts form_letter
end
end
puts "EventManager initialized."
contents = CSV.open "event_attendees.csv", headers: true, header_converters: :symbol
template_letter = File.read("form_letter.erb")
erb_template = ERB.new(template_letter)
contents.each do |row|
id = row[0]
name = row[:first_name]
zipcode = clean_zipcode(row[:zipcode])
numbers = row[:homephone]
time = row[:regdate]
@registration_hours << format_time(time)
legislators = legislators_by_zipcode(zipcode)
form_letter = erb_template.result(binding)
save_thank_you_letters(id, form_letter)
end
|
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.6.3'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.3', '>= 6.0.3.4'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
#gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Active Storage variant
gem 'image_processing', '~> 1.2'
################ STYLES ################
gem 'tailwindcss', '~> 1.0', '>= 1.0.3'
gem 'bootstrap', '~> 5.0.0.alpha2'
gem 'bootstrap_form', '~> 4.5'
gem 'bootstrap-datepicker-rails', '~> 1.9', '>= 1.9.0.1'
################ JS ################
gem 'jquery-rails'
################ URLS
################
gem 'friendly_id', '~> 5.4'
################ FORMS ################
gem 'simple_form', '~> 5.0', '>= 5.0.3'
################ MEMBERSHIP ################
gem 'devise', '~> 4.7', '>= 4.7.3'
gem 'devise_invitable', '~> 2.0', '>= 2.0.2'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '~> 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
gem "better_errors"
gem "binding_of_caller"
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of web drivers to run system tests with browsers
gem 'webdrivers'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
#RESOURCES FORMS
#https://webypress.fr/meilleurs-formulaires-inscription-bootstrap-gratuits-2019/
#RESOURCES DESIGN
#tailwind css section ICON
#https://tailwindcss.com/resources#icons
#IMAGES DRAW
#https://undraw.co/ AND https://undraw.co/illustrations
#STACK IMAGES
#https://unsplash.com/
#ICON HEROICONS
#https://github.com/tailwindlabs/heroicons
#ICON ZONDICONS
#http://www.zondicons.com/icons.html
#HERO PATTERN
#http://www.heropatterns.com/
#RESOURCES
#https://hackademy.io/tutoriel-videos/nouveaute-rails-41-active-record-methode-enum
#SCOLARITE FORMAT
#https://www.pdftron.com/blog/rails/how-to-generate-pdf-with-ruby-on-rails/
#http://rails-generate-pdf.herokuapp.com/invoices/1
#https://github.com/PDFTron/rails-generate-pdf
#https://www.synbioz.com/blog/tech/generation-de-pdf
#https://www.grzegorowski.com/using-prawn-gem-for-generating-pdfs-in-rails-5
#https://www.grzegorowski.com/using-prawn-gem-for-generating-pdfs-in-rails-5
#UUUID
#https://itnext.io/using-uuids-to-your-rails-6-application-6438f4eeafdf
|
class Request < ApplicationRecord
belongs_to :job
has_many :messages, dependent: :destroy
belongs_to :destinator, class_name: 'User'
belongs_to :creator, class_name: 'User'
validates :start_at, presence: true
validates :end_at, presence: true
validates :job_id, presence: true
end
|
#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__), ".", "..", "lib")
require 'rubygems'
require 'hpricot'
require 'fileutils'
require 'net/smtp'
require 'PipelineHelper'
require 'FCBarcodeFinder'
require 'EmailHelper'
#This class is a wrapper for SlxUniqueness.jar to find unique reads.
#It works on per-lane basis only.
class FindUniqueReads
def initialize()
jarName = File.dirname(File.dirname(__FILE__)) + "/java/SlxUniqueness.jar"
@lanes = "" # Lanes to consider for running uniqueness
@fcName = ""
@limsBarcode = ""
javaVM = "-Xmx8G" # Specifies maximum memory size of JVM
@coreCmd = "java " + javaVM + " -jar " + jarName
@helper = PipelineHelper.new
begin
#findLaneNumbers()
#findFCName()
@lanes = @helper.findAnalysisLaneNumbers()
@fcName = @helper.findFCName()
obj = FCBarcodeFinder.new
@limsBarcode = obj.getBarcodeForLIMS()
findUniqueness()
rescue Exception => e
puts e.message
puts e.backtrace.inspect
exit -1
end
end
private
# Method to build JAR command for the specified lane.
# Works with only one lane per GERALD directory
def findUniqueness()
puts "Generating Uniqueness for lane : " + @lanes.to_s
fileNames = findSequenceFileNames(@lanes.to_s)
buildJarCommand(fileNames)
end
def buildJarCommand(fileNames)
resultFileName = "Uniqueness_" + @limsBarcode.to_s + ".txt"
# Create temp directory
# Use the scratch directory on the cluster nodes for the temporary files.
# If scratch directory on cluster nodes should not be used, simply remove
# "/space1/tmp/" prefix from the tmpDir name.
processID = $$
tmpDir = "/space1/tmp/tmp_" + @limsBarcode.to_s + "_" + processID.to_s
puts "Creating temp directory : " + tmpDir.to_s
FileUtils.mkdir(tmpDir)
# Select analysis as fragment or paired
if fileNames.length == 2
analysisMode = "paired"
else
analysisMode = "fragment"
end
cmd = @coreCmd + " AnalysisMode=" + analysisMode + " TmpDir=" + tmpDir +
" DetectAdaptor=true "
fileNames.each do |fname|
cmd = cmd + " Input=" + fname
end
puts cmd
resultFile = File.new(resultFileName, "w")
resultFile.write("Flowcell Lane : " + @limsBarcode.to_s)
resultFile.close()
# resultFile.write("")
puts "Computing Uniqueness Results"
cmd = cmd + " >> " + resultFileName
puts "Starting Time : " + Time.now.to_s
`#{cmd}`
puts "Completion Time : " + Time.now.to_s
#emailUniquenessResults(resultFileName)
puts "Finished Computing Uniqueness Results."
# Upload uniqueness results to LIMS
uploadResultsToLIMS(resultFileName)
# Remove the temporary directory
FileUtils.remove_dir(tmpDir, true)
# Stop saving files to mini analysis
#copyFileMiniAnalysis(resultFileName)
end
# Helper method to email uniqueness results
def emailUniquenessResults(resultFileName)
adaptorPlotFile = "AdaptorReadsDistribution.png"
emailFrom = "sol-pipe@bcm.edu"
emailSubject = "Illumina Uniqueness Results"
emailTo = nil
emailText = nil
obj = EmailHelper.new()
emailTo = obj.getResultRecepientEmailList()
resultFile = File.open(resultFileName, "r")
emailText = resultFile.read()
if !File::exist?(adaptorPlotFile) || !File::readable?(adaptorPlotFile) ||
File::size(adaptorPlotFile) == 0
obj.sendEmail(emailFrom, emailTo, emailSubject, emailText)
else
# Send the adaptor plot distribution as email attachment
obj.sendEmailWithAttachment(emailFrom, emailTo, emailSubject, emailText, adaptorPlotFile)
end
end
# Helper method to find sequence files for a given lane
# Find Sequence files only of the format s_x_sequence.txt (fragment),
# s_x_1_sequence.txt (read1), s_x_2_sequence.txt (read2).
# Sort the filenames to feed the filenames to the java in the correct order
# (read 1 before read2).
def findSequenceFileNames(laneNum)
sequenceFiles = Dir["s_" + laneNum.to_s + "*sequence.txt"]
result = Array.new
sequenceFiles.each do |file|
if file.match(/s_\d_sequence.txt/) || file.match(/s_\d_1_sequence.txt/) ||
file.match(/s_\d_2_sequence.txt/)
result << file
end
end
result.sort!
return result
end
# Helper method to upload uniqueness percentage to LIMS
#TODO: Make upload part of another script (maybe helper)
# and perform error detection if upload to LIMS fails
def uploadResultsToLIMS(resultFile)
limsUploadCmd = "perl /stornext/snfs5/next-gen/Illumina/ipipe/" +
"third_party/setIlluminaLaneStatus.pl " + @limsBarcode +
" UNIQUE_PERCENT_FINISHED UNIQUE_PERCENT "
foundUniquenessResult = false
lines = IO.readlines(resultFile)
lines.each do |line|
if line.match(/\% Unique Reads/)
foundUniquenessResult = true
line.gsub!(/^\D+/, "")
uniqPer = line.slice(/^[0-9\.]+/)
puts uniqPer.to_s
cmd = limsUploadCmd + uniqPer.to_s
puts "Uploading uniqueness results"
puts cmd
output = `#{cmd}`
puts "Output from LIMS upload command : " + output.to_s
return
end
end
if foundUniquenessResult == false
raise "Did not find uniqueness percentage"
end
end
end
obj = FindUniqueReads.new()
|
module Directions
UP, RIGHT, DOWN, LEFT = (0..3).to_a
end
class OriMaze
include Directions
attr_accessor :width, :height, :size, :exit
def initialize(width, height, exitrow)
@width, @height = width, height
@exit = exitrow * @width
@size = @width * @height
@shift = @size - 1
@hoffset, @voffset = 1 << @shift, @width << @shift
end
def parse(s) # parse state string as output by format
x = i = free = 0
s.each_byte do |c|
case c
when ?|
x |= (1 << i)
i += 1
when ?-, ?=
i += 1
when ? , ?.
free = i
end
end
(free << @shift) | x
end
def each_cell(x)
free = x >> @shift
@height.times do |i|
@width.times do |j|
if free == 0
yield j,i, ?.
else
yield j,i, (x & 1 == 1 ? ?| : ?-)
x >>= 1
end
free -= 1
end
end
end
def freexy(x)
free = x >> @shift
return free%@width, free/@width
end
def move(x, dir)
free = x >> @shift
lowermask = (freemask = 1 << free) - 1
freecol = free % @width
case dir
when UP
if free >= @width && x[free - @width] == 1 # can move up
rotatemask = lowermask - (lowermask >> @width)
return x - @voffset & ~rotatemask | (x | freemask) >> 1 & rotatemask
else
return -1
end
when RIGHT
if freecol < @width - 1 && x[free] == 0 # can move right
return x + @hoffset
else
return -1
end
when DOWN
if free < @size - @width && x[free + @width - 1] == 1# can move down
rotatemask = ~lowermask - (~lowermask << @width)
return x + @voffset & ~rotatemask | (x << 1 | freemask) & rotatemask
else
return -1
end
when LEFT
if freecol > 0 && x[free - 1] == 0 # can move left
return x - @hoffset
else
return -1
end
end
end
def solved?(x)
free = x >> @shift
free < @exit && x[@exit-1] == 0 || free > @exit && x[@exit] == 0
end
end
class OriMazePlayer
require 'tk'
include Directions
attr_reader :root, :canvas, :pzl, :pos, :scale, :delta, :history, :eps
attr_reader :bg, :vcol, :hcol, :freecol
def bindkey(widget, key, dir, color, dx, dy)
widget.bind(key) {
if (newpos = @pzl.move(@pos, dir)) != -1
bg, freecol = @bg, @freecol
x, y = @pzl.freexy(@pos)
x *= @scale; y *= @scale
x += 10; y += 10
TkcRectangle.new(@canvas,x,y,x+@scale,y+@scale) { fill bg; outline bg }
TkcOval.new(@canvas,x+dx,y+dy,x+@scale-dx,y+@scale-dy) { fill color }
x, y = @pzl.freexy(@pos = newpos)
x *= @scale; y *= @scale
x += 10; y += 10
TkcRectangle.new(@canvas,x,y,x+@scale,y+@scale) { fill bg; outline bg }
TkcRectangle.new(@canvas,x+@delta,y+@delta,x+@scale-@delta,y+@scale-@delta) { fill freecol }
if !@history.empty? && dir^@history[-1]==2
@history.pop
else
@history << dir
end
n = @history.length
TkcText.new(@canvas,x+@scale/2,y+@scale/2) { text "#{n}" }
@root.title("Solved!") if @pzl.solved?(@pos)
end
}
end
def initialize(width, height, exitrow, puzzle)
@pzl = OriMaze.new(width, height, exitrow)
@pos = @pzl.parse(puzzle)
@scale = 50
@delta = 10
@eps = 2
@history = []
@bg, @vcol, @hcol, @freecol = "black", "magenta", "green", "white"
@root = TkRoot.new { title "OriMaze 1.0" }
root.bind('q') { exit }
@canvas = TkCanvas.new(root) {
background "black"
}.pack
@pzl.each_cell(@pos) { |x,y,c|
x *= @scale; y *= @scale
x += 10; y += 10
if c == ?.
color = @freecol
TkcRectangle.new(@canvas,x+@delta,y+@delta,x+@scale-@delta,y+@scale-@delta) { fill color }
TkcText.new(@canvas,x+@scale/2,y+@scale/2) { text "GO!" }
else
if c == ?-
dx,dy,color = 0, @delta, @hcol
else
dx,dy,color = @delta, 0, @vcol
end
TkcOval.new(@canvas,x+dx,y+dy,x+@scale-dx,y+@scale-dy) { fill color }
end
}
bindkey(root, 'Key-Up', UP, @vcol, @delta, @eps)
bindkey(root, 'Key-Right', RIGHT, @hcol, @eps, @delta)
bindkey(root, 'Key-Down', DOWN, @vcol, @delta, @eps)
bindkey(root, 'Key-Left', LEFT, @hcol, @eps, @delta)
Tk.mainloop
end
end
OriMazePlayer.new(5,5,0,"||||-\n-||--\n|--|.\n||--|\n|---|")
|
class MoviesController < ApplicationController
def show
id = params[:id] # retrieve movie ID from URI route
@movie = Movie.find(id) # look up movie by unique ID
# will render app/views/movies/show.<extension> by default
end
def update_session_data_with_params(tracked_params)
redirect = false
params_list = Hash.new
tracked_params.each do |t|
if params[t] != nil then
session[t] = params[t] # update session hash
elsif session[t] != nil then
redirect = true # URI missing params so redirect
end
params_list[t] = session[t]
end
return redirect, params_list
end
def index
redirect_needed, parameter_list = update_session_data_with_params([:ratings, :sort_by])
if redirect_needed then
flash.keep
redirect_to movies_path( parameter_list )
end
@all_ratings = Movie.select(:rating).map {|r| r.rating}.uniq.sort
selected_ratings = Array.new
if params[:ratings] != nil then
params[:ratings].each{|k,v| if v then selected_ratings << k end}
else
selected_ratings = @all_ratings
end
if params[:sort_by] == "title" then
@movies = Movie.where(:rating => selected_ratings).order("title ASC")
elsif params[:sort_by] == "release_date" then
@movies = Movie.where(:rating => selected_ratings).order("release_date ASC")
else
@movies = Movie.where(:rating => selected_ratings)
end
h = Hash.new
@all_ratings.each {|x| h[x] = false}
selected_ratings.each {|x| h[x] = true}
flash[:ratings] = h
end
def new
# default: render 'new' template
end
def create
@movie = Movie.create!(params[:movie])
flash[:notice] = "#{@movie.title} was successfully created."
redirect_to movies_path
end
def edit
@movie = Movie.find params[:id]
end
def update
@movie = Movie.find params[:id]
@movie.update_attributes!(params[:movie])
flash[:notice] = "#{@movie.title} was successfully updated."
redirect_to movie_path(@movie)
end
def destroy
@movie = Movie.find(params[:id])
@movie.destroy
flash[:notice] = "Movie '#{@movie.title}' deleted."
redirect_to movies_path
end
end
|
require "spec_helper"
describe JwtRest::Secrets do
describe "#rsa_private_key" do
it "demands the developer to fix override the method" do
expect { described_class.rsa_private_key }.to raise_error(StandardError)
end
end
describe "#rsa_private" do
it "checks if the RSA_PRIVATE is a Base64 encoded and valid RSA private key" do
described_class.define_singleton_method :rsa_private_key do
"asdf"
end
expect { described_class.rsa_private }.to raise_error(/^Unable to decode your private key.*/)
end
it "returns a valid RSA private key" do
sample = OpenSSL::PKey::RSA.generate 2048
sample = Base64.encode64(sample.to_s).gsub("\n", "")
described_class.define_singleton_method :rsa_private_key do
sample
end
expect(described_class.rsa_private).to be_an(OpenSSL::PKey::RSA)
end
end
end
|
class Spree::FastlyConfiguration < Spree::Preferences::Configuration
attr_accessor :perform_purges
# see https://github.com/fastly/fastly-rails#configuration
preference :api_key, :string
preference :user, :string
preference :password, :strong
preference :max_age, :integer, :default => 2592000
preference :service_id, :string
def perform_purges?
perform_purges && FastlyRails.configuration.authenticatable?
end
def disable_purges!
self.perform_purges = false
end
def enable_purges!
self.perform_purges = true
end
def purged_collections
Set.new [
:products,
:taxonomies,
:taxons,
:users
]
end
def purge_all!
purged_collections.each do |collection|
clazz = "Spree::#{collection.to_s.classify}".safe_constantize
clazz.purge_all if clazz
end
end
end
|
class AddKioskToSlides < ActiveRecord::Migration[5.0]
def change
add_reference :slides, :kiosk, foreign_key: true
end
end
|
class ListingSerializer < ActiveModel::Serializer
attributes :id, :content, :title
belongs_to :user
end
|
class RemoveColumnDefaultSsDatatransfer < ActiveRecord::Migration
def change
change_column_default(:ss_data_transfers, :upload_data, nil)
change_column_default(:ss_data_transfers, :download_data, nil)
end
end
|
helpers do
def valid_password?(user, password)
user.password_hash == BCrypt::Engine.hash_secret(password, user.salt)
end
def login?
session[:current_user_id] ? true : false
end
def login(user)
session[:current_user_id] = user.id
end
def current_user
User.find(session[:current_user_id])
end
end
|
class CreateTransactionHistories < ActiveRecord::Migration[6.1]
def change
create_table :transaction_histories do |t|
t.string :user_id
t.string :transaction_type
t.string :reference_id
t.decimal :amount, :precision => 32, :scale => 16
t.decimal :current_wallet_balance, :precision => 32, :scale => 16
t.string :status
t.timestamps
end
end
end
|
require 'spec_helper'
describe ImageSerializer do
let(:image_model) { Image.new }
it 'exposes the attributes to be jsonified' do
serialized = described_class.new(image_model).as_json
expected_keys = [
:id,
:category,
:name,
:source,
:description,
:type,
:expose,
:ports,
:links,
:environment,
:volumes,
:volumes_from,
:command
]
expect(serialized.keys).to match_array expected_keys
end
it 'rolls up the image categories into a singular category in the json' do
image_model.categories = ['foo']
serialized = described_class.new(image_model).as_json
expect(serialized[:category]).to eq image_model.categories.first
end
end
|
class Admin::PostsController < ApplicationController
include ::ActionView::Layouts
before_action :set_post, only: [:show, :edit, :update, :destroy, :toggle_state]
before_action :authenticate_user
layout 'admin'
def index
@posts = Post.order('created_at DESC').all
@props = @posts.map do |post|
{
title: post.title,
body: post.body,
created_at: post.created_at,
id: post.id,
post_url: admin_post_path(post),
destroy_url: admin_post_path(post),
state: post.state,
toggle_state_url: toggle_state_admin_post_path(post),
preview_url: post_path(post)
}
end
end
def show
respond_to do |format|
format.json { render json: {title: @post.title, body: @post.body}}
end
end
def new
@post = Post.new
end
def edit
end
def update
if @post.update(post_params)
render json: {
title: @post.title,
body: @post.body,
created_at: @post.created_at,
id: @post.id,
post_url: admin_post_path(@post),
destroy_url: admin_post_path(@post),
state: @post.state,
toggle_state_url: toggle_state_admin_post_path(@post),
preview_url: post_path(@post)
}.to_json
end
end
def destroy
id = @post.id
@post.update_attribute(:deleted, true)
render json: {id: id}
end
def toggle_state
if @post.update_attribute(:state,
@post.state == 'published' ? 'draft' : 'published'
)
render json: {id: @post.id, state: @post.state}
end
end
def create
@post = Post.new(post_params)
if @post.save
render json: {
title: @post.title,
body: @post.body,
created_at: @post.created_at,
id: @post.id,
post_url: admin_post_path(@post),
destroy_url: admin_post_path(@post),
state: @post.state,
toggle_state_url: toggle_state_admin_post_path(@post),
preview_url: post_path(@post)
}.to_json
else
render nothing: true, status: 422
end
end
end
private
def authenticate_user
if current_user.try(:usertype) == 'admin'
authenticate_user!
else
redirect_to root_path
end
end
def set_post
@post = Post.where(permalink: params[:id]).first
end
def post_params
params.require(:post).permit(:title, :body)
end
|
ApuntaNotas::Application.routes.draw do
devise_for :users
namespace :api do
resources :notes do
collection do
match 'delete_all', to: 'notes#delete_all', via: :delete
end
end
resources :categories
end
root to: "home#index"
match '*path', to: 'home#index'
end
|
require './test/test_helper'
require './lib/bowling'
class BowlingTest < Minitest::Test
def setup
@game = Bowling.new
end
def test_empty_game
score = @game.score
assert_equal(0, score,
'score worth no single pin')
end
def test_gutter_game
20.times do
@game.roll(0)
end
score = @game.score
assert_equal(0, score,
'score worth no single pin')
end
def test_game_of_ones
20.times do
@game.roll(1)
end
score = @game.score
assert_equal(20, score,
'sum of all pins rolled')
end
def test_game_with_a_spare
@game.roll(3)
@game.roll(7)
@game.roll(4)
@game.roll(5)
16.times do
@game.roll(0)
end
score = @game.score
assert_equal((3 + 7 + 4) + (4 + 5), score,
'sum with bonus for next roll after spare')
end
def test_game_with_a_spare_at_the_end
18.times do
@game.roll(0)
end
@game.roll(3)
@game.roll(7)
@game.roll(4)
score = @game.score
assert_equal(3 + 7 + 4, score,
'sum with bonus for next roll after spare')
end
def test_game_with_a_strike
@game.roll(10)
@game.roll(7)
@game.roll(2)
18.times do
@game.roll(0)
end
score = @game.score
assert_equal((10 + 7 + 2) + (7 + 2), score,
'sum with bonus for next two roll after strike')
end
def test_perfect_game
12.times do
@game.roll(10)
end
score = @game.score
assert_equal(300, score,
'10 x 30 score because of 12 strikes')
end
end |
class ProductMeta < ApplicationRecord
belongs_to :product
end
|
class User < ActiveRecord::Base
devise :omniauthable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :provider, :uid
validates :name, :presence => true
has_many :adminable_events, :class_name => 'Event', :foreign_key => :owner_id
def social_graph
if provider == "facebook" && access_token.present?
FbGraph::User.me(access_token).fetch
end
end
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
user = User.where(:email => data["email"]).first
unless user
user = User.create(name: data["name"],
email: data["email"],
password: Devise.friendly_token[0,20]
)
end
user
end
def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
unless user
user = User.create(name:auth.extra.raw_info.name,
provider:auth.provider,
uid:auth.uid,
email:auth.info.email,
password:Devise.friendly_token[0,20]
)
end
user
end
end
|
#
# Cookbook Name:: pi2-cookbook
# Recipe:: default
#
# Copyright (c) 2015 The Authors, All Rights Reserved.
#
# us keyboard
replace_or_add 'us keyboard' do
path '/etc/default/keyboard'
pattern 'XKBLAYOUT'
line 'XKBLAYOUT="US"'
end
replace_or_add 'xkboptions = nocaps' do
path '/etc/default/keyboard'
pattern 'XKBOPTIONS'
line 'XKBOPTIONS=ctrl:nocaps'
end
node.default['packages'].merge!( {
'dnsutils' => 'install',
'mpg123' => 'install',
'mplayer' => 'install',
'omxplayer' => 'install',
'ruby-dev' => 'install'
})
%w{ colored }.each do |gem|
gem_package gem
end
|
class User < ActiveRecord::Base
require 'digest/md5'
mount_uploader :image, ImageUploader
#attr_accessible :name, :password, :password_confirmation
before_save :encrypt_password
validates :name,
:presence => TRUE,
:length =>
{
:minimum => 4,
:allow_blank => FALSE
}
validates :password,
:presence => TRUE,
:length =>
{
:minimum => 6,
:allow_blank => TRUE
},
:confirmation => TRUE
validates :password_confirmation,
:presence => TRUE
def encrypt_password
self.password = Digest::MD5.hexdigest(password)
end
def self.validate_login(name,password)
user = User.find_by_name(name)
if user && user.password == Digest::MD5.hexdigest(password)
user
else
nil
end
end
end
|
class WorkExperienceLookedHistoriesController < ApplicationController
before_action :forbid_history_destroy_user, only: [:destroy]
def destroy
set_history
@history.destroy
redirect_to user_path(@current_user), notice: "記事「#{@history.work_experience.title}」を閲覧履歴から削除しました。"
end
private
def set_history
@history = current_user.work_experience_looked_histories.find_by(work_experience_id: params[:work_experience_id])
end
def forbid_history_destroy_user
set_history
redirect_to user_url(@current_user), notice: '権限がありません' unless @current_user.id == @history.user_id
end
end
|
# frozen_string_literal: true
class Book
include Mongoid::Document
include Mongoid::Timestamps
field :title, type: String
field :subtitle, type: String
field :sort, type: Integer
field :chapter, type: HasMany
embedded_in :comic
end
|
class Addprofiletousers < ActiveRecord::Migration
def change
add_column :users, :image_id, :string
add_column :users, :name, :string
add_column :users, :gender, :string
add_column :users, :intrested_in, :string
add_column :users, :description, :string
add_column :users, :dob, :date
end
end |
class Hearing < ApplicationRecord
belongs_to :committee
has_many :bills
end
|
require "./avl_tree_node.rb"
class AVLTree
def insert(key, node=@root)
if node.key.nil?
node.key = key
elsif key < node.key
if node.has_left_child?
insert(key, node.left_child)
else
node.left_child = AVLTreeNode.new(key, node)
perform_rotation(node)
end
else
if node.has_right_child?
insert(key, node.right_child)
else
node.right_child = AVLTreeNode.new(key, node)
perform_rotation(node)
end
end
end
def find(key, node=@root)
if node.nil? || node.key.nil?
nil
elsif node.key == key
node
elsif key < node.key
find(key, node.left_child)
else
find(key, node.right_child)
end
end
def delete(key, node=@root)
if key < node.key
delete(key, node.left_child)
elsif key > node.key
delete(key, node.right_child)
else
if node.has_left_child? && node.has_right_child?
# action_node = successor
successor = get_successor(node)
# Guaranteed to fall into the has_right_child? case, because of the way
# the successor was chosen.
delete(successor.key, successor)
node.replace_with(successor)
elsif node.has_left_child?
# action_node = node
node.replace_with(node.left_child)
elsif node.has_right_child?
# action_node = node
node.replace_with(node.right_child)
else
# action_node = node.parent
node.hard_remove
end
end
nil
end
private
def perform_rotation(node)
if node.balance_factor == 2
if node.right_child.balance_factor == 1
rotate_rl(node)
elsif node.right_child.balance_factor == -1
rotate_rr(node)
end
else
if node.left_child.balance_factor == 1
rotate_lr(node)
elsif node.left_child.balance_factor == -1
rotate_ll(node)
end
end
end
def rotate_ll(node)
b = node.left_child
f = node.parent
node.left_child = b.right_child
node.left_child.parent = node
b.right_child = node
node.parent = b
if f.nil?
@root = b
else
if f.right_child == a
f.right_child = b
else
f.left_child = b
end
end
end
def rotate_rr(node)
b = node.right_child
f = node.parent
node.right_child = b.left_child
node.right_child.parent = node
b.left_child = node
node.parent = b
if f.nil?
@root = b
else
if f.right_child == a
f.right_child = b
else
f.left_child = b
end
end
end
def rotate_lr(node)
f = node.parent
b = node.left_child
c = b.right_child
node.left_child = c.right_child
node.left_child.parent = node
b.right_child = c.left_child
b.right_child.parent = b
c.left_child = b
b.parent = c
c.right_child = node
node.parent = c
if f.nil?
@root = c
else
if f.right_child == node
f.right_child = c
else
f.left_child = c
end
end
end
def rotate_rl(node)
f = node.parent
b = node.right_child
c = b.left_child
b.left_child = c.right_child
b.left_child.parent = b
node.right_child = c.left_child
node.right_child.parent = node
c.right_child = b
b.parent = c
c.left_child = node
node.parent = c
if f.nil?
@root = c
else
if f.right_child == node
f.right_child = c
else
f.left_child = c
end
end
end
def get_successor(node)
get_left_most_child(node.right_child)
end
def get_first_imbalanced(start_node)
current_node = start_node
while node.balance_factor.between?(-1, 1) && node.has_parent?
current_node = current_node.parent
end
current_node
end
def get_left_most_child(node)
if node.has_left_child?
get_left_most_child(node.left_child)
else
node
end
end
def find_smallest(node)
current = node
while current.has_left_child?
current = current.left_child
end
current
end
def remove_node(node, replacement=nil)
if node.left_child?
node.parent.left_child = nil
else
node.parent.right_child = nil
end
if !!replacement
replacement.parent = node.parent
node.parent = nil
replacement.parent.left_child = replacement
end
end
def populate(arr)
arr.each { |el| insert(el) }
end
end
|
class Conversation < ActiveRecord::Base
belongs_to :empresa_request
belongs_to :user
has_many :messages, -> { order("id ASC")}, dependent: :destroy
validates_uniqueness_of :user_id, :scope => :empresa_request_id
def send_message(from, body)
return false if !from.is_a?(User) || body.blank?
self.messages.create(:user=>from, :body=>body)
end
end |
# frozen_string_literal: true
Rails.application.routes.draw do
devise_for :admins, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get 'impressum' => 'static_pages#impressum', :as => :impressum
get 'legal_notice' => 'static_pages#legal_notice', :as => :legal_notice
get 'manual' => 'static_pages#manual', :as => :manual
get 'about' => 'static_pages#about', :as => :about
get 'index' => 'main_page#index'
get 'show' => 'main_page#show'
get 'download' => 'data_tables#download', :as => :download
get 'show_preview_with_diff' => 'data_tables#show_preview_with_diff', :as => :show_preview_with_diff
resource :data_table, only: [:new, :create]
resources :data_sources, only: [] do
member do
get 'download'
get 'download_diff'
end
end
root to: 'main_page#index'
end
|
module Clot
module ModelTag
def set_primary_attributes(context)
@item = context['form_model']
if @item
@attribute_name = resolve_value(@params.shift,context)
@first_attr = context['form_class_name']
else
@first_attr = @params.shift
if @params[0] && ! @params[0].match(/:/)
@attribute_name = resolve_value(@params.shift,context)
end
@item = context[@first_attr]
end
attribute_names = @attribute_name.split('.')
unless @item.source.respond_to?(:"#{attribute_names[0]}=")
raise "#{attribute_names[0]} is not a valid form field for #{@first_attr.camelize}."
end
if attribute_names.size == 3
@name_string = @first_attr + "[" + attribute_names[0].to_s + "_attributes][" + attribute_names[1].to_s + "_attributes][" + attribute_names[2].to_s + "]"
@id_string = @first_attr + "_" + attribute_names[0].to_s + "_attributes_" + attribute_names[1].to_s + "_" + attribute_names[2].to_s
@value_string = ""
if @item
@subitem = @item[attribute_names[0]][attribute_names[1]]
if @subitem
@value_string = @subitem[attribute_names[2].to_sym]
end
end
elsif attribute_names.size == 2
@name_string = @first_attr + "[" + attribute_names[0].to_s + "_attributes][" + attribute_names[1].to_s + "]"
@id_string = @first_attr + "_" + attribute_names.join('_')
@value_string = ""
if @item
@subitem = @item[attribute_names[0]]
if @subitem
@value_string = @subitem[attribute_names[1].to_sym]
end
end
else
@id_string = "#{@first_attr}_#{@attribute_name}"
@name_string = "#{@first_attr}[#{@attribute_name}]"
@value_string = @item[@attribute_name.to_sym]
end
@errors = context['form_errors'] || []
end
def render(context)
super(context)
end
end
class FileField < FileFieldTag
include ModelTag
def render_string
@value_string = nil
super
end
end
class PasswordField < PasswordFieldTag
include ModelTag
end
class TextField < TextFieldTag
include ModelTag
end
class TextArea < TextAreaTag
include ModelTag
end
class Label < LabelTag
include ModelTag
def get_label_for(label)
label.humanize
end
def set_primary_attributes(context)
super context
if @params[0] && ! @params[0].match(/:/)
@value_string = resolve_value(@params.shift,context)
else
@value_string = get_label_for(@attribute_name)
end
end
end
class CollectionSelect < ClotTag
# usage:
# {% collection_select "order[bill_address_attributes]" method:"country_id", collection:available_countries, value_method:'id', text_method:'name', html_options:"{class:'large-field'}" %}
def render(context)
super(context)
# collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
method = @attributes['method']
collection = @attributes['collection']
value_method = @attributes['value_method']
text_method = @attributes['text_method']
@attributes.has_key?('options') ? options = @attributes['options'] : options = {}
@attributes.has_key?('html_options') ? html_options = @attributes['html_options'] : html_options = {}
context.registers[:action_view].collection_select(@form_object, method, collection, value_method, text_method, options, html_options)
end
end
class CheckBox < ClotTag
include ModelTag
def set_primary_attributes(context)
super(context)
if @params.length > 1 && ! @params[0].match(/:/) && ! @params[1].match(/:/)
@true_val = resolve_value(@params.shift,context)
@false_val = resolve_value(@params.shift,context)
else
@true_val = 1
@false_val = 0
end
end
def render_string
if @item[@attribute_name.to_sym]
@checked_value = %{checked="checked" }
end
%{<input name="#{@name_string}" type="hidden" value="#{@false_val}" />} + %{<input #{@disabled_string}#{@class_string}#{@checked_value}id="#{@id_string}" name="#{@name_string}" type="checkbox" value="#{@true_val}" />}
end
end
end
|
class RemoveCreatedAtFromStudent < ActiveRecord::Migration
def change
remove_column :students, :created_at, :datetime
end
end
|
require 'rails_helper'
describe BookDecorator do
let :book do
author = build(:author, first_name: 'Ivan', last_name: 'Lopis')
author2 = build(:author, first_name: 'Vasiliy', last_name: 'Lipa')
build(:book, :long_description, authors: [author, author2]).decorate
end
describe '#authors_list' do
it 'return authors with coma' do
expect(book.authors_list).to eq('Ivan Lopis, Vasiliy Lipa')
end
end
describe '#short_description' do
context 'when description longer than 350' do
it 'return cut description with link' do
expect(book.short_description).to eq(book.description.slice(0, 347) +
"...<a class=\"in-gold-500 ml-10\" id=\"read_link\" href=\"#\">Read More</a>")
end
end
context 'when description less than 350' do
it 'return description' do
book.description = 'test'
expect(book.short_description).to eq(book.description)
end
end
end
describe '#dimensions_list' do
it "return dimensions in H: n” x W: n” x D: n”" do
expect(book.dimensions_list).to eq("H: 2.4” x W: 1.3” x D: 0.6”")
end
end
describe 'in_current_order?' do
context 'when book is in current order' do
it 'return true' do
order = Order.new(order_items: [OrderItem.new(book: book)])
allow(book.h).to receive(:current_order).and_return(order)
expect(book.in_current_order?).to eq(true)
end
end
context 'when book is not in current order' do
it 'return false' do
allow(book.h).to receive(:current_order).and_return(Order.new)
expect(book.in_current_order?).to eq(false)
end
end
end
end
|
class ApplicationController < ActionController::Base
# Devise param config
before_action :configure_permitted_parameters, if: :devise_controller?
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def error_404
respond_to do |format|
format.html { render template: 'errors/error_404', layout: 'layouts/application', status: 404 }
format.all { render nothing: true, status: 404 }
end
end
def error_422
respond_to do |format|
format.html { render template: 'errors/error_422', layout: 'layouts/application', status: 500 }
format.all { render nothing: true, status: 500}
end
end
def error_500
respond_to do |format|
format.html { render template: 'errors/error_500', layout: 'layouts/application', status: 500 }
format.all { render nothing: true, status: 500}
end
end
private
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_in) << :login
devise_parameter_sanitizer.for(:sign_up) << :name
devise_parameter_sanitizer.for(:sign_up) << :is_employer
devise_parameter_sanitizer.for(:sign_up) << :username
devise_parameter_sanitizer.for(:sign_up) << :name
devise_parameter_sanitizer.for(:sign_up) << :company
devise_parameter_sanitizer.for(:sign_up) << :website
devise_parameter_sanitizer.for(:sign_up) << :address
devise_parameter_sanitizer.for(:sign_up) << :phone
devise_parameter_sanitizer.for(:sign_up) << :email
devise_parameter_sanitizer.for(:account_update) << :name
devise_parameter_sanitizer.for(:account_update) << :description
devise_parameter_sanitizer.for(:account_update) << :company
devise_parameter_sanitizer.for(:account_update) << :website
devise_parameter_sanitizer.for(:account_update) << :address
devise_parameter_sanitizer.for(:account_update) << :phone
devise_parameter_sanitizer.for(:account_update) << :avatar
devise_parameter_sanitizer.for(:account_update) << :remove_avatar
devise_parameter_sanitizer.for(:account_update) << :username
devise_parameter_sanitizer.for(:account_update) << :email
if user_signed_in? and !current_user.is_employer
devise_parameter_sanitizer.for(:account_update) << :resume
devise_parameter_sanitizer.for(:account_update) << :remove_resume
end
end
end
|
# This class displays the user's dashboard which contains:
# * The current_user's recent games
# * The current_user's top games
# * The current_user's Watched Friends' information as the same
class DashboardController < ApplicationController
before_action :authenticate_user!
# This method is used to setup and display the data for the user's
# dashboard
def show
@steam_profile = current_user.steam_profile
@favorite_library_entries = current_user.library_entries.favorites
@recent_library_entries = current_user.library_entries.recent
@watched_steam_profiles = current_user.watched_steam_profiles
.order('vanity_name ASC')
end
end
|
module Sluggable
extend ActiveSupport::Concern
included do
before_create -> { create_slug }
end
def create_slug
field = self::sluggable_fields.pop # %TODO: use multiple fields, for now just use 1
self.slug = (self[field]).parameterize
end
end
# %TODO: how to genereate unique when duplicates exist?
# see https://stackoverflow.com/questions/1302022/best-way-to-generate-slugs-human-readable-ids-in-rails
# https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize
|
require "thor"
module Katar
module Commands
class EditCommand < Thor
desc "edit", "Edit the Katar.yaml file"
def edit
if windows?
exec "start #{Katar::DIR}/Katar.yaml"
end
exec "open #{Katar::DIR}/Katar.yaml"
end
private
def windows?
(/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil
end
end
end
end
Katar::Commands::EditCommand.start(ARGV) |
Pod::Spec.new do |spec|
spec.name = 'SNM'
spec.version = '0.0.1'
spec.license = { :type => 'MIT' }
spec.homepage = 'https://github.com/Henawey/SNM'
spec.author = { 'Ahmed Henawey' => 'Henawey@gmailcom' }
spec.summary = 'Simple Network Management is a small abstraction wrapper layer for URLSession and URLSessionDataTask.'
spec.source = { :git => 'https://github.com/Henawey/SNM.git', :tag => '0.0.1' }
spec.swift_version = '5.0'
spec.ios.deployment_target = '12.0'
spec.source_files = 'SNM/SNM/**/*.{swift}'
spec.requires_arc = true
end
|
class Client::ExperiencesController < ApplicationController
def new
@experience = {}
render 'new.html.erb'
end
def create
@experience = {
start_date: "",
end_date: "",
job_title: "",
company_name: "",
details: ""
}
response = Unirest.post("https://morning-oasis-72057.herokuapp.com/api/experiences", parameters: @experience)
if response.code == 200
flash[:success] = "Successfully created Product"
redirect_to "/client/students/#{current_user_id}"
elsif response.code == 401
flash[:warning] = "You are not authorized to make a product"
redirect_to '/'
elsif
@errors = response.body['errors']
render 'new.html.erb'
end
end
def update
@experience = {
experience_id: params[:id],
start_date: params[:start_date],
end_date: params[:end_date],
job_title: params[:job_title],
company_name: params[:company_name],
details: params[:details]
}
response = Unirest.patch(
"https://morning-oasis-72057.herokuapp.com/api/experiences/#{params['id'] }",
parameters: @experience
)
if response.code == 200
flash[:success] = "Successfully updated Experience"
redirect_to "/client/students/#{current_user_id}"
elsif response.code == 401
flash[:warning] = "You are not authorized to update a experience"
redirect_to '/'
else
@errors = response.body['errors']
render 'edit.html.erb'
end
end
def destroy
response = Unirest.delete("https://morning-oasis-72057.herokuapp.com/api/experiences/#{params['id'] }")
if response.code == 200
flash[:success] = "Successfully destroyed experience"
redirect_to "/client/students/#{current_user_id}"
else
flash[:warning] = "You are not authorized"
redirect_to '/'
end
end
end
|
require './lib/activity'
class Reunion
attr_reader :name,
:activities
def initialize(name)
@name = name
@activities = []
end
def add_activity(activity)
@activities << activity
end
def total_cost
total = 0
@activities.each do |activity|
total += activity.total_cost
end
total
end
def breakout
results = {}
@activities.each do |activity|
activity.owed.keys.each do |participant|
if results.include?(participant)
results[participant] += activity.owed[participant]
else
results.store(participant, activity.owed[participant])
end
end
end
results
end
def print_summary
owed = breakout
message = ""
owed.keys.each do |participant|
message += p "#{participant}: #{owed[participant]}\n"
end
message
end
end
|
# Find an *internal* IP Address (if any)
module Opscode
module HostAliases
module Helpers
# Inspects the node to find all the assigned ip addresses
def interface_addresses
ip_addresses = []
if node.has_key?("network") and node["network"].has_key?("interfaces")
node["network"]["interfaces"].each do |iface|
# iface is [<name>, {"addresses"=>{}, ... }]
ip_addresses.concat begin
ip_addresses.concat iface[1]["addresses"].keys
rescue
[]
end
end
end
ip_addresses
end
# Returns the first ip address that starts with 192 or 10 or nil
def find_private_ip
ip_addresses = interface_addresses
ip_addresses.each do |ip|
if ip.start_with?("192") || ip.start_with?("10")
return ip
end
end
return nil
end
def internal_ip
private_ip = find_private_ip
internal_ip = begin
if node.attribute?("cloud") && node.cloud.attribute?("local_ipv4")
Chef::Log.info "node.cloud.local_ipv4: #{node.cloud.local_ipv4}"
Chef::Log.info "Using Cloud IP: #{node.cloud.local_ipv4}"
node.cloud.local_ipv4
elsif private_ip
Chef::Log.info "Using Private IP: #{private_ip}"
private_ip
else
# Anything else would yield a public IP, e.g.
# node.cloud.public_ipv4
# node.ipaddress
# Therefore, just return nil and handle this case elsewhere.
nil
end
end
end
end
end
end
# Include helper "internal_ip" to query internal IP addresses
::Chef::Recipe.send(:include, Opscode::HostAliases::Helpers)
host_entries = []
node[:host_aliases].each do |node_name|
search(:node, "name:#{node_name}") do |node|
ip = begin
addr = internal_ip
if addr.nil?
node.ipaddress
else
addr
end
end
host_entries << "#{ip} #{node.name}".strip if not (ip.empty? || ip.nil?) and not node.name.empty?
end
end
template "/etc/hosts" do
source "hosts.erb"
owner "root"
group "root"
mode 0644
end
|
require_relative './test_helper'
require 'mocha/minitest'
require 'csv'
require 'bigdecimal'
require './lib/customer_repository'
class CustomerRepositoryTest < Minitest::Test
def setup
@engine = mock
@repository = CustomerRepository.new("./fixture_data/customers_sample.csv", @engine)
end
def test_it_exists
assert_instance_of CustomerRepository, @repository
end
def test_it_has_attributes
assert_equal 124, @repository.all.count
assert_equal 11, @repository.all[0].id
assert_equal "Logan", @repository.all[0].first_name
assert_equal "Kris", @repository.all[0].last_name
assert_equal @engine, @repository.engine
end
def test_it_finds_by_id
assert_nil @repository.find_by_id(1001)
assert_equal "Logan", @repository.find_by_id(11).first_name
end
def test_find_all_by_first_name
assert_equal 1, @repository.find_all_by_first_name("LoGan").count
assert_equal [], @repository.find_all_by_first_name("little lord fauntleroy")
end
def test_find_all_by_last_name
assert_equal 1, @repository.find_all_by_last_name("kris").count
assert_equal [], @repository.find_all_by_last_name("little lord fauntleroy")
end
def test_new_highest_id
assert_equal 999, @repository.new_highest_id
end
def test_it_can_create
@repository.create(:first_name => "Jaqob",
:last_name => "Hilario",
:created_at => Time.now,
:updated_at => Time.now)
assert_equal "Jaqob", @repository.all[-1].first_name
end
def test_it_can_update_customer
original_time = @repository.find_by_id(14).updated_at
attributes = {first_name: "Charles",
last_name: "Vera"}
assert_equal "Kirstin", @repository.all[2].first_name
assert_equal "Wehner", @repository.all[2].last_name
@repository.update(14, attributes)
assert_equal "Kirstin", @repository.all[2].first_name
assert_equal "Wehner", @repository.all[2].last_name
assert_equal true, @repository.find_by_id(14).updated_at > original_time
end
def test_it_can_delete_customer
@repository.delete(1000)
assert_nil @repository.find_by_id(1000)
end
def test_inspect
assert_equal "<CustomerRepository 124 rows>", @repository.inspect
end
end
|
class Card < ApplicationRecord
include Repetition
mount_uploader :image, ImageUploader
belongs_to :deck
belongs_to :user
validates :original_text, :translated_text, presence: true
validates :original_text, exclusion: { in: :translated_text}
validates :original_text, :translated_text, :format => { :without =>/[0-9]/,
:message => "Только буквы!" }
before_validation do
self.original_text=original_text.capitalize
self.translated_text=translated_text.capitalize
end
scope :check_date, -> {where('next_repetition <= ?', Date.today)}
def succeed!(params)
if params>10
self.set_next_repetition_date
else
mark = case params
when 1..5
5
when 5..10
4
end
self.process_recall_result(mark)
end
self.save
end
def failed!
unless self.try==2
self.tryplus
else
self.set_next_repetition_date
self.save
self.tryzero
end
end
def misspelling?(params)
Levenshtein.distance(params, self.original_text) == 1
end
def right_translation?(params)
self.original_text==params or self.misspelling?(params)
end
def tryplus
self.update(try: self.try+1)
end
def tryzero
self.update(try: 0)
end
before_create :set_next_repetition_date
def set_next_repetition_date
self.next_repetition=1.days.from_now
end
end |
class AddHostelTypeToHostel < ActiveRecord::Migration
def change
add_column :hostels, :hostel_type, :string
end
end
|
RSpec.describe Game do
let(:commons) { Location.lookup("bar/common") }
let(:docks) { Location.lookup("docks/entrance") }
let(:basement) { Location.lookup("bar/basement") }
let(:wait) { Event.lookup('wait_1_hour') }
let(:post_job) { Event.lookup('bar/post_job') }
let(:shop) { Store.lookup('brewery') }
let(:wren) { build_wren }
describe "setup!" do
context "game setup" do
subject do
game = Game.new
game.setup!
game
end
its(:bar_name) { should == "XXX" }
end
context "player setup" do
subject do
game = Game.new
game.setup!
game.player
end
its(:role) { should == "player" }
its(:first_name) { should == "Maldrasen" }
its(:last_name) { should == "Des'Tempre" }
its(:gender) { should == "male" }
end
end
describe "start_game!" do
subject {
game = user.games.build
game.setup!
game.save!
game
}
its(:time) { should == Game::START_TIME }
# TODO: Needs game locations, events, and characters first.
# its(:location) { should == Location.game_start }
# it "has the game_start event in the queue" do
# expect(subject).to have_queued_events ["game_start"]
# end
# it "forges the characters that are built at game start" do
# expect(subject.characters.count).to eq 2
# end
end
# TODO: Events Needed?
# describe "locked?" do
# before do
# game.dequeue_all_events!
# end
# it "is locked when there is a current_event" do
# game.enqueue_event! wait
# expect(game.locked?).to be_true
# end
# it "is locked when there is a conversation" do
# game.start_conversation! wren
# expect(game.locked?).to be_true
# end
# it "is locked when there is a store" do
# game.goto_store! shop
# expect(game.locked?).to be_true
# end
# it "is free otherwise" do
# expect(game.free?).to be_true
# end
# end
describe "advance_time!" do
it "advances the time in minutes" do
time = game.time
game.advance_time! 60
expect(game.time).to eq (time + 1.hour)
end
# TODO: Redoing the current location stuff.
#
# it "moves a character accorting to their schedule" do
# expect(wren.current_location).to eq commons
# wren.tasks.destroy_all
# game.advance_time! 60
# wren.reload
# expect(wren.current_location).to eq nil
# end
it "sets the number of times that the hours have been processed." do
game.advance_time! 60
expect(game.hours_processed).to eq 1
end
it "processess hourly tasks" do
allow(game).to receive(:process_hourly_activities!).exactly(3).times
game.advance_time! 200
end
end
describe "hours_that_have_passed" do
it "0 hours have passed at 59 minutes" do
game.advance_time! 59
expect(game.hours_that_have_passed).to eq 0
end
it "1 hour has passed at 60 minutes" do
game.advance_time! 60
expect(game.hours_that_have_passed).to eq 1
end
it "1 hour has passed at 119 minutes" do
game.advance_time! 119
expect(game.hours_that_have_passed).to eq 1
end
end
describe "process_hourly_activities!" do
it "checks for applicants" do
allow(JobPosting).to receive(:check_for_applicants!).with(game).once
game.advance_time! 60
end
end
describe "lookup_action" do
# TODO: Need Events
# it "gets the action off the event if there is a current event" do
# game.dequeue_all_events!
# game.enqueue_event! post_job
# action = post_job.actions.first
# expect(game.lookup_action(action.id)).to eq action
# end
# TODO: Need Events
# it "returns nil if the event is not found on the current event" do
# game.dequeue_all_events!
# game.enqueue_event! post_job
# action = commons.actions.first
# expect(game.lookup_action(action.id)).to be_nil
# end
it "gets the action off of the active conversation if there is one" do
conversation = Conversation.lookup("wren/miniskirt")
action = conversation.actions.first
set_game_conversation wren, conversation
expect(game.lookup_action(action.id)).to eq action
end
it "gets the action off of the location if there is no event" do
game.dequeue_all_events!
game.location = commons
action = commons.actions.first
expect(game.lookup_action(action.id)).to eq action
end
end
# TODO: This is broken
# describe "start_conversation!" do
# before do
# game.start_conversation! wren
# end
# it "raises an exception if there is a conversation" do
# expect { game.start_conversation!(wren) }.to raise_error
# end
# it "sets the active conversation" do
# expect(game.active_conversation).to_not be_nil
# end
# it "sets the active conversation character" do
# expect(game.active_conversation_character).to eq wren
# end
# end
describe "set_conversation!" do
context "when there is a conversation" do
before do
@conv = Conversation.lookup("wren/miniskirt")
@yes = Conversation.lookup("wren/miniskirt_yes")
set_game_conversation wren, @conv
end
it "completes that portion of the conversation" do
allow(wren).to receive(:complete_conversation!).with(@conv)
game.set_conversation! @yes
end
it "updates the active conversation" do
game.set_conversation! @yes
expect(game.active_conversation).to eq @yes
end
end
context "when there is no conversation" do
it "raises an exception" do
expect { game.set_conversation!(@yes) }.to raise_error
end
end
end
describe "complete_conversation!" do
context "when there is a conversation" do
before do
@conv = Conversation.lookup("wren/miniskirt_yes")
set_game_conversation wren, @conv
end
it "completes that portion of the conversation" do
allow(wren).to receive(:complete_conversation!).with(@conv)
game.complete_conversation!
end
it "unsets the active_conversation" do
game.complete_conversation!
expect(game.active_conversation).to be_nil
end
it "unsets the active conversation character" do
game.complete_conversation!
expect(game.active_conversation_character).to be_nil
end
end
context "when there is no conversation" do
it "raises an exception" do
expect { game.complete_conversation! }.to raise_error
end
end
end
# TODO: Exits are being rewritten for maps
# describe "follow_exit!" do
# before do
# game.location = commons
# game.follow_exit! commons.exits.first
# end
# it "changes the location" do
# expect(game.location.code).to eq "bar/front"
# end
# it "advances the time" do
# expect(game.time).to have_advanced_by 1
# end
# end
describe "goto_store!" do
it "sets the store" do
game.goto_store! shop
expect(game.store).to eq shop
end
end
describe "leave_store!" do
it "unsets the store" do
game.goto_store! shop
game.leave_store!
expect(game.store).to be_nil
end
end
end
|
module IOTA
module API
class Commands
def findTransactions(searchValues)
command = {
command: 'findTransactions'
}
searchValues.each { |k, v| command[k.to_sym] = v }
command
end
def getBalances(addresses, threshold)
{
command: 'getBalances',
addresses: addresses,
threshold: threshold
}
end
def getTrytes(hashes)
{
command: 'getTrytes',
hashes: hashes
}
end
def getInclusionStates(transactions, tips)
{
command: 'getInclusionStates',
transactions: transactions,
tips: tips
}
end
def getNodeInfo
{ command: 'getNodeInfo'}
end
def getNeighbors
{ command: 'getNeighbors' }
end
def addNeighbors(uris)
{
command: 'addNeighbors',
uris: uris
}
end
def removeNeighbors(uris)
{
command: 'removeNeighbors',
uris: uris
}
end
def getTips
{ command: 'getTips' }
end
def getTransactionsToApprove(depth, reference = nil)
{
command: 'getTransactionsToApprove',
depth: depth
}.merge(reference.nil? ? {} : { reference: reference })
end
def attachToTangle(trunkTransaction, branchTransaction, minWeightMagnitude, trytes)
{
command: 'attachToTangle',
trunkTransaction: trunkTransaction,
branchTransaction: branchTransaction,
minWeightMagnitude: minWeightMagnitude,
trytes: trytes
}
end
def interruptAttachingToTangle
{ command: 'interruptAttachingToTangle' }
end
def broadcastTransactions(trytes)
{
command: 'broadcastTransactions',
trytes: trytes
}
end
def storeTransactions(trytes)
{
command: 'storeTransactions',
trytes: trytes
}
end
def checkConsistency(tails)
{
command: 'checkConsistency',
tails: tails
}
end
def wereAddressesSpentFrom(addresses)
{
command: 'wereAddressesSpentFrom',
addresses: addresses
}
end
def getNodeAPIConfiguration
{ command: 'getNodeAPIConfiguration' }
end
def getMissingTransactions
{ command: 'getMissingTransactions' }
end
end
end
end
|
module API::V1::Admin
class ProductVariantSerializer < ActiveModel::Serializer
attributes :id,
:barcode,
:compare_at_price_cents,
:compare_at_price_currency,
:fulfillment_service,
:decimal,
:inventory_management,
:inventory_policy,
:inventory_quantity,
:old_inventory_quantity,
:inventory_quantity_adjustment,
:position,
:grams,
:price_cents,
:price_currency,
:requires_shipping,
:sku,
:taxable,
:title,
:weight,
:weight_unit,
:option1,
:option2,
:option3,
:metafields_type,
:metafields_id,
:published
link(:product) { v1_admin_product_url(object.product_id) }
has_many :images
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.