text stringlengths 10 2.61M |
|---|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'pushjs/version'
Gem::Specification.new do |spec|
spec.name = "pushjs"
spec.version = Pushjs::VERSION
spec.authors = ["Zainal Mustofa"]
spec.email = ["zainalmustof@gmail.com"]
spec.summary = "Pushjs on rails"
spec.description = "This gem provides the push.js Javascript library for your Rails application."
spec.homepage = "https://github.com/zainalmustofa/pushjs"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.14"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
|
#####
# @author Mars
#####
require 'test_helper'
# make sure the doctor can be saved if all data is provided
class DoctorTest < ActiveSupport::TestCase
test "doctor object can be not saved if no license is provided" do
doctor = Doctor.new
assert_not doctor.save, "doctor object is saved without license"
end
test "doctor object can be saved to the database" do
doctor = doctors(:doctorone)
assert doctor.save, "doctor object could not be saved even if it has all data"
end
end |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# password_digest :string(255)
# admin :boolean
# uid :string(255)
# confirmation_code :string(255)
# country :string(255)
# state :string(255)
# remember_token :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# status :string(255)
#
require 'spec_helper'
describe User do
before { @user = User.new name: "Example User", email: "user@example.com",
password: "password", country: "United States of America", state: "California" }
subject { @user }
it { should respond_to :name }
it { should respond_to :email }
it { should respond_to :admin }
it { should respond_to :password }
it { should respond_to :uid }
it { should respond_to :status }
it { should respond_to :confirmation_code }
it { should respond_to :country }
it { should respond_to :state }
it { should respond_to :remember_token }
it { should be_valid }
it { should_not be_admin }
describe "with admin attribute set to true" do
before { @user.toggle! :admin }
it { should be_admin }
end
describe "Validation" do
describe "when name is too long" do
before { @user.name = "a" * 51 }
it { should_not be_valid }
end
describe "when email not present" do
before { @user.email = " " }
it { should_not be_valid }
end
describe "when email format is invalid" do
invalid_addresses = %w[uesr@mail,com user_at_mail.org example.user@mail.]
invalid_addresses.each do |invalid_address|
before { @user.email = invalid_address }
it { should_not be_valid }
end
end
describe "when email format is valid" do
valid_addresses = %w[user@mail.com A_USER@g.m.org frst.lst@mail.jp a+b@baz.cn]
valid_addresses.each do |valid_address|
before { @user.email = valid_address }
it { should be_valid }
end
end
describe "when email address is already taken" 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 "when password is not present" do
before { @user.password = " " }
it { should_not be_valid }
end
describe "with a password that's too short" do
before { @user.password = "a" * 5 }
it { should_not be_valid }
end
describe "when country is not present" do
before { @user.country = " " }
it { should_not be_valid }
end
describe "when country format is invalid" do
invalid_countries = %w[Finite Rock usa Im]
invalid_countries.each do |invalid_countries|
before { @user.country = invalid_countries }
it { should_not be_valid }
end
end
describe "when country format is valid" do
User::COUNTRIES.each do |valid_country|
before { @user.country = valid_country }
it { should be_valid }
end
end
describe "when state is not present" do
before { @user.state = " " }
it { should_not be_valid }
end
describe "when state format is invalid" do
invalid_states = %w[Finite Rock arz]
invalid_states.each do |invalid_state|
before { @user.state = invalid_state }
it { should_not be_valid }
end
end
describe "when state format is valid" do
valid_states = %w[California Arizona Georgia]
User::STATES.each do |valid_state|
before { @user.state = valid_state }
it { should be_valid }
end
end
end
describe "return value of authenticate method" do
before { @user.save }
let(:found_user) { User.find_by_email @user.email }
describe "with valid password" do
it { should == found_user.authenticate(@user.password) }
end
describe "with invalid password" do
let(:user_for_invalid_password) { found_user.authenticate "invalid" }
it { should_not == user_for_invalid_password }
specify { user_for_invalid_password.should be_false }
end
end
describe "columns generated at save time" do
before { @user.save }
its(:remember_token) { should_not be_blank }
its(:confirmation_code) { should_not be_blank }
its(:uid) { should_not be_blank }
its(:status) { should_not be_blank }
end
end
|
class User < ApplicationRecord
has_many :accounts
has_many :activity_logs
has_many :conversation_contexts
has_many :otps
def fullname
"#{firstname} #{lastname}"
end
def get_statement
state = accounts.pluck(:account_num, :account_type, :balance).map do |acc|
"Account number: #{acc[0]}\nAccount type: #{acc[1]}\nAccount balance: #{acc[2]}\n"
end
state.join("\n")
end
end
|
class ConversationDecorator
include ActionView::Helpers::DateHelper
attr_reader :conversation
def initialize(conversation, current_user)
@conversation, @current_user = conversation, current_user
end
def simple_decorate
{
:conversee_avatar => conversee_avatar,
:id => id,
:is_first_message_unread => is_first_message_unread,
:conversee => conversee
}
end
def decorate
{
:conversee => conversee,
:messages => messages,
:id => id,
:is_first_message_unread => is_first_message_unread,
:conversee_avatar => conversee_avatar,
:conversee_url_slug => conversee_url_slug
}
end
def conversee_url_slug
if @current_user.id != @conversation.author_id
sender_url_slug
else
recipient_url_slug
end
end
def conversee
if @current_user.id != @conversation.author_id
sender_name
else
recipient_name
end
end
def conversee_avatar
if @current_user.id != @conversation.author_id
sender_avatar
else
recipient_avatar
end
end
def id
@conversation.id
end
def author
User.where(:id => @conversation.author_id).first || nil
end
def recipient
User.where(:id => @conversation.recipient_id).first || nil
end
def sender_url_slug
author.url_slug unless author.nil?
end
def recipient_url_slug
recipient.url_slug unless recipient.nil?
end
def sender_name
if author.nil?
"Deleted User"
else
author.first_name
end
end
def recipient_name
if author.nil?
"Deleted User"
else
recipient.first_name
end
end
def recipient_avatar
picture(recipient.thumbnail_image) unless recipient.nil?
end
def sender_avatar
picture(author.thumbnail_image) unless author.nil?
end
def picture(thumbnail)
if Rails.env.production?
if thumbnail.present?
URI.join('https:' + thumbnail.url(:thumbnail)).to_s
end
elsif thumbnail.present?
URI.join(Rails.configuration.static_base_url, thumbnail.url(:thumbnail)).to_s
end
end
def messages
@conversation.messages.collect{ |message| MessageDecorator.new(message, @current_user).decorate }
end
def is_first_message_unread
latest_message.unread && @current_user.id != latest_message.user_id
end
def latest_message
@conversation.messages.first
end
end
|
module Traject
# Just some internal utility methods
module Util
def self.exception_to_log_message(e)
indent = " "
msg = indent + "Exception: " + e.class.name + ": " + e.message + "\n"
msg += indent + e.backtrace.first + "\n"
caused_by = e.cause
# JRuby Java exception might have getRootCause
if caused_by == nil && e.respond_to?(:getRootCause) && e.getRootCause
caused_by = e.getRootCause
end
if caused_by == e
caused_by = nil
end
if caused_by
msg += indent + "Caused by\n"
msg += indent + caused_by.class.name + ": " + caused_by.message + "\n"
msg += indent + caused_by.backtrace.first + "\n"
end
return msg
end
# From ruby #caller method, you get an array. Pass one line
# of the array here, get just file and line number out.
def self.extract_caller_location(str)
str.split(':in `').first
end
# Provide a config source file path, and an exception.
#
# Returns the line number from the first line in the stack
# trace of the exception that matches your file path.
# of the first line in the backtrace matching that file_path.
#
# Returns `nil` if no suitable backtrace line can be found.
#
# Has special logic to try and grep the info out of a SyntaxError, bah.
def self.backtrace_lineno_for_config(file_path, exception)
# For a SyntaxError, we really need to grep it from the
# exception message, it really appears to be nowhere else. Ugh.
if exception.kind_of? SyntaxError
if m = /:(\d+):/.match(exception.message)
return m[1].to_i
end
end
# Otherwise we try to fish it out of the backtrace, first
# line matching the config file path.
# exception.backtrace_locations exists in MRI 2.1+, which makes
# our task a lot easier. But not yet in JRuby 1.7.x, so we got to
# handle the old way of having to parse the strings in backtrace too.
if (exception.respond_to?(:backtrace_locations) &&
exception.backtrace_locations &&
exception.backtrace_locations.length > 0)
location = exception.backtrace_locations.find do |bt|
bt.path == file_path
end
return location ? location.lineno : nil
else # have to parse string backtrace
exception.backtrace.each do |line|
if line.start_with?(file_path)
if m = /\A.*\:(\d+)\:in/.match(line)
return m[1].to_i
end
end
end
# if we got here, we have nothing
return nil
end
end
# Extract just the part of the backtrace that is "below"
# the config file mentioned. If we can't find the config file
# in the stack trace, we might return empty array.
#
# If the ruby supports Exception#backtrace_locations, the
# returned array will actually be of Thread::Backtrace::Location elements.
def self.backtrace_from_config(file_path, exception)
filtered_trace = []
found = false
# MRI 2.1+ has exception.backtrace_locations which makes
# this a lot easier, but JRuby 1.7.x doesn't yet, so we
# need to do it both ways.
if (exception.respond_to?(:backtrace_locations) &&
exception.backtrace_locations &&
exception.backtrace_locations.length > 0)
exception.backtrace_locations.each do |location|
filtered_trace << location
(found=true and break) if location.path == file_path
end
else
filtered_trace = []
exception.backtrace.each do |line|
filtered_trace << line
(found=true and break) if line.start_with?(file_path)
end
end
return found ? filtered_trace : []
end
# Ruby stdlib queue lacks a 'drain' function, we write one.
#
# Removes everything currently in the ruby stdlib queue, and returns
# it an array. Should be concurrent-safe, but queue may still have
# some things in it after drain, if there are concurrent writers.
def self.drain_queue(queue)
result = []
queue_size = queue.size
begin
queue_size.times do
result << queue.deq(:raise_if_empty)
end
rescue ThreadError
# Need do nothing, queue was concurrently popped, no biggie, but let's
# stop iterating and return what we've got.
return result
end
return result
end
def self.is_jruby?
unless defined?(@is_jruby)
@is_jruby = defined?(JRUBY_VERSION)
end
@is_jruby
end
# How can we refer to an io object input in logs? For now, if it's a file-like
# object, we can use #path.
def self.io_name(io_like_object)
io_like_object.path if io_like_object.respond_to?(:path)
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
#### Users ####
User.create(name: "Boos")
User.create(name: "Andro 3000")
#### Bike Networks ####
BikeNetwork.create(location: "New York City", name:"City Cycles", company:"sycle-group", num_of_stations: 4, free_bikes: 0)
#### Trips ####
Trip.create(user_id: 1, bike_network_id: 1, times_used: 3, start_time: Time.new, end_time: Time.new)
Trip.create(user_id: 2, bike_network_id: 1, times_used: 3, start_time: Time.new, end_time: Time.new)
|
require File.dirname(__FILE__) + "/spec_helper"
describe Integrity::Notifier::Jabber do
include AppSpecHelper
include NotifierSpecHelper
it_should_behave_like "A notifier"
def klass
Integrity::Notifier::Jabber
end
describe "notifying the world of a build" do
before { klass.stub!(:new).and_return(notifier) }
it "should instantiate a notifier with the given build and config" do
klass.should_receive(:new).with(mock_build, anything).and_return(notifier)
klass.notify_of_build(mock_build, notifier_config)
end
it "should pass the notifier options to the notifier" do
klass.should_receive(:new).with(anything, notifier_config).and_return(notifier)
klass.notify_of_build(mock_build, notifier_config)
end
it "should deliver the notification" do
notifier.should_receive(:deliver!)
klass.notify_of_build(mock_build, notifier_config)
end
end
describe "generating a form for configuration" do
describe "with a field for the recipients" do
it "should have the proper name, id and label" do
the_form.should have_textfield("jabber_notifier_recipients").named("notifiers[Jabber][recipients]").with_label("Recipients").with_value(nil)
end
it "should use the config's 'to' value if available" do
the_form(:config => { 'recipients' => 'test@example.com' }).should have_textfield("jabber_notifier_recipients").with_value("test@example.com")
end
end
it "should have a subtitle 'Jabber Server Configuration'" do
the_form.should have_tag("h3", "Jabber Server Configuration")
end
describe "with a field for the user" do
it "should have the proper name, id and label" do
the_form.should have_textfield("jabber_notifier_user").named("notifiers[Jabber][user]").with_label("User").with_value(nil)
end
it "should use the config's 'to' value if available" do
the_form(:config => { 'user' => 'test@morejabber.com' }).should have_textfield("jabber_notifier_user").with_value("test@morejabber.com")
end
end
describe "with a field for the pass" do
it "should have the proper name, id and label" do
the_form.should have_textfield("jabber_notifier_pass").named("notifiers[Jabber][pass]").with_label("Pass").with_value(nil)
end
it "should use the config's 'to' value if available" do
the_form(:config => { 'pass' => '42' }).should have_textfield("jabber_notifier_pass").with_value("42")
end
end
end
describe 'when sending a notify with jabber' do
it 'should send a message to each recipients' do
@jabber_client = mock('jabber')
Jabber::Simple.stub!(:new).and_return(@jabber_client)
@jabber_notifier = Integrity::Notifier::Jabber.new(mock_build, notifier_config)
@jabber_notifier.recipients.each { |r| @jabber_client.stub!(:deliver).with(r, anything).and_return(true) }
@jabber_notifier.deliver!
end
end
describe 'building a message' do
before do
Jabber::Simple.stub!(:new).and_return(mock('jabber'))
@jabber_notifier = Integrity::Notifier::Jabber.new(mock_build, notifier_config)
end
it 'should prepare a list of recipients' do
@jabber_notifier.recipients.should == ['ph@hey-ninja.com', 'more@foom.com']
end
describe 'the content of the message' do
it "should include the commit message" do
@jabber_notifier.message.should =~ /Commit Message: 'the commit message'/
end
it "should include the commit date" do
@jabber_notifier.message.should =~ /at Fri Jul 25 18:44:00 [+|-]\d\d\d\d 2008/
end
it "should include the commit author" do
@jabber_notifier.message.should =~ /by Nicolás Sanguinetti/
end
it "should include the link to the integrity build" do
@jabber_notifier.message.should =~ /\/integrity\/builds\/e7e02bc669d07064cdbc7e7508a21a41e040e70d/
end
end
end
def notifier_config
@configs ||= { :recipients => 'ph@hey-ninja.com more@foom.com' }
end
end
|
class Quarter
include Comparable
PARSE_REGEX = /\AQ(\d)-(\d{4})\z/
def self.current
new(date: Date.current)
end
def self.parse(string)
date = if (match = string.match(PARSE_REGEX))
number = Integer(match[1])
year = Integer(match[2])
quarter_month = quarter_to_month(number)
Date.new(year, quarter_month).beginning_of_month
elsif string.respond_to?(:to_date)
string.to_date
else
raise ArgumentError, "Quarter.parse expects a a string in QX-YYYY format or an object that responds to to_date; provided: #{string}"
end
new(date: date)
end
def self.quarter_to_month(quarter_number)
((quarter_number - 1) * 3) + 1
end
attr_reader :date
attr_reader :number
attr_reader :year
# Create a Quarter with any date-like object, needs to respond to `to_date`. So Date, DateTime, and Time will
# all work. Note that the stored date is normalized to a proper Date object to keep things consistent.
def initialize(date:)
@date = date.to_date.freeze
@year = date.year.freeze
@number = QuarterHelper.quarter(date).freeze
end
def to_s(format = :default_period)
case format
when :dhis2
"#{year}Q#{number}"
when :quarter_string
"#{year}-#{number}"
else
"Q#{number}-#{year}"
end
end
def next_quarter
advance(months: 3)
end
alias_method :succ, :next_quarter
def previous_quarter
advance(months: -3)
end
def advance(options)
self.class.new(date: date.advance(options))
end
def downto(number)
(1..number).inject([self]) do |quarters, number|
quarters << quarters.last.previous_quarter
end
end
def upto(number)
(1..number).inject([self]) do |quarters, number|
quarters << quarters.last.next_quarter
end
end
def to_date
date
end
def begin
date.beginning_of_quarter.beginning_of_day
end
def end
date.end_of_quarter.end_of_day
end
def to_period
Period.quarter(self)
end
alias_method :beginning_of_quarter, :begin
alias_method :end_of_quarter, :end
def inspect
"#<Quarter:#{object_id} #{to_s.inspect}>"
end
def ==(other)
to_s == other.to_s
end
alias_method :eql?, :==
def <=>(other)
return -1 if year < other.year
return -1 if year == other.year && number < other.number
return 0 if self == other
return 1 if year > other.year
return 1 if year == other.year && number > other.number
end
def hash
year.hash ^ number.hash
end
end
|
class Puppy
def initialize
puts "Initializing new puppy instance ..."
end
def fetch(toy)
puts "I brought back the #{toy}!"
toy
end
def speak(times)
puts "Woof! "*times
end
def roll_over
puts "*rolls over*"
end
def dog_years(human_years)
human_years*7
end
def sit
puts "I am sitting!"
end
end
class Kitty
def initialize
puts "Initializing a kitty ..."
end
def pur
puts "Purrrr"
end
def ignore_human
puts "I am ignoring you."
end
end
geoff = Puppy.new
geoff.fetch("ball")
geoff.speak(3)
geoff.roll_over
puts geoff.dog_years(4)
geoff.sit
count = 0
kitties = []
while count < 50
kitties.push(Kitty.new)
count += 1
end
kitties.each do |kitty|
kitty.pur
kitty.ignore_human
end |
class Comment < ActiveRecord::Base
#belongs_to :commentable, :polymorphic => true
belongs_to :page
default_scope :order => "created_at DESC"
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:format => {:with => email_regex}
validates_presence_of :user_name
validates_presence_of :rate
end
|
require 'sinatra'
before do
content_type :txt
end
get '/' do
headers "X-Custom-Value" => "This is a custom HTTP header"
'Custom header set'
end
get '/multiple' do
headers "X-Custom-Value" => "foo", "X-Custom-Value2" => "bar"
'Multiple custom headers set'
end
#Header son parte dl HTTP request y response
#proporcionar informacion adicional para los clientes y servidores
#sinatra provee de un metodo headers para manipularlos
#hay una serie de cabeceras standar definidas por las espcificacin de HTTP
#la convención es el uso de un prefijo X para valores personalizados de cbecera
# como en el ejemplo: "X-Custom-Value"
#mas información
#http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html.
|
require 'test/unit'
require './game/match'
require './interface/renderer'
class MyTest < Test::Unit::TestCase
# Called before every test method runs. Can be used
# to set up fixture information.
def setup
@renderer = Renderer.new
@match = Match.new(@renderer, Input.new(@renderer))
end
# Called after every test method runs. Can be used to tear
# down fixture information.
def teardown
# Do nothing
end
def test_guess_no
assert_equal(0, @match.guess_no)
end
end |
require 'test_helper'
class DestroySurveyTest < Capybara::Rails::TestCase
include Warden::Test::Helpers
Warden.test_mode!
after do
Warden.test_reset!
end
feature 'Destroy' do
scenario 'clicking "Delete Survey" as admin deletes the survey' do
admin = create(:user, :admin)
presentation = create(:presentation)
survey = create(:survey, presentation_id: presentation.id)
login_as(admin, scope: :user)
visit presentation_surveys_path(presentation)
click_on 'Delete Survey'
refute(page.has_content?(survey.title))
end
scenario 'clicking "Delete Survey" as presenter deletes the survey' do
presenter = create(:user)
presentation = create(:presentation)
create(:participation, :presenter,
user_id: presenter.id,
presentation_id: presentation.id)
survey = create(:survey, presentation_id: presentation.id)
login_as(presenter, scope: :user)
visit presentation_surveys_path(presentation)
click_on 'Delete Survey'
refute(page.has_content?(survey.title))
end
scenario 'a presenter cannot delete another presenters survey' do
presenter1 = create(:user)
presenter2 = create(:user)
presentation = create(:presentation)
create(:participation, :presenter,
user_id: presenter1.id,
presentation_id: presentation.id)
create(:participation, :presenter,
user_id: presenter2.id,
presentation_id: presentation.id)
create(:survey,
presentation_id: presentation.id,
presenter_id: presenter2.id)
login_as(presenter1, scope: :user)
visit presentation_surveys_path(presentation)
button = find_link('Delete Survey')
assert(button[:class].include?('disabled'))
end
end
end
|
# Represents an @supports conditional rule
module CSSPool
module CSS
class SupportsRule < CSSPool::Node
attr_accessor :conditions
attr_accessor :rule_sets
def initialize conditions
@conditions = conditions
@rule_sets = []
end
end
end
end
|
class RefreshBsnlSmsJwt
attr_reader :service_id, :username, :password, :token_id
def initialize(service_id, username, password, token_id)
@service_id = service_id
@username = username
@password = password
@token_id = token_id
end
def call
abort "Aborting, need BSNL credentials to refresh JWT." unless service_id && username && password && token_id
http = Net::HTTP.new(Messaging::Bsnl::Api::HOST, Messaging::Bsnl::Api::PORT)
http.use_ssl = true
request = Net::HTTP::Post.new("/api/Create_New_API_Token", "Content-Type" => "application/json")
request.body = {Service_Id: service_id,
Username: username,
Password: password,
Token_Id: token_id}.to_json
response = http.request(request)
if response.is_a?(Net::HTTPSuccess)
jwt = response.body.delete_prefix('"').delete_suffix('"')
config = Configuration.find_or_create_by(name: "bsnl_sms_jwt")
config.update!(value: jwt)
end
end
end
|
class Category < ActiveRecord::Base
has_many :inventories
has_many :products, through: :inventories
end
|
#
# Cookbook Name:: rethinkdb
# Attributes:: rethinkdb
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
default['rethinkdb']['package']['version'] = "1.11.3"
default['rethinkdb']['package']['apt']['url'] = "http://ppa.launchpad.net/rethinkdb/ppa/ubuntu/"
default['rethinkdb']['package']['apt']['key_server'] = "keyserver.ubuntu.com"
default['rethinkdb']['package']['apt']['key'] = "11D62AD6"
default['rethinkdb']['package']['yum']['url'] = "http://download.rethinkdb.com/centos/6/#{node['kernel']['machine']}"
|
# frozen_string_literal: true
require_relative '../lib/common'
require_relative '../lib/baseband'
QUALCOMM_BBCFG_HEADER = 'a4L<L<L<QQQa8'
namespace :data do
namespace :baseband do
namespace :bbcfg do
desc 'pull out blobs from a bbcfg'
task :qc_blobs, [:file] do |_task, args|
unless File.exist?(args[:file])
puts "#{args[:file]} is not a regular file"
exit(-1)
end
file = File.open(args[:file], 'rb')
values = file.read(48).unpack(QUALCOMM_BBCFG_HEADER)
if (values[0] != "\0GFC") || (values[1] != 3) ||
(values[4] != 229_947_300_631_343_066) || (values[7] != 'BBCFGMBN')
print("Invalid Header:\n\n#{values.inspect}")
exit(-1)
end
parser = OpenSSL::ASN1.decode(file.read)
print("Build Type: #{parser.entries[0].value}\n")
print("Build Number: #{parser.entries[1].value}\n")
print("Build Host: #{parser.entries[2].value}\n")
print("Build User: #{parser.entries[3].value}\n")
print("Build IP: #{parser.entries[4].value}\n")
print("Build Commit Hash: #{parser.entries[5].value}\n")
print("Build Date: #{parser.entries[6].value}\n")
print("Build Branch: #{parser.entries[7].value}\n")
# TODO: Loop over 8 and handle MCC/MNC or whatever those are....
#
base_dir = File.dirname(args[:file])
extracted_dir = File.join(base_dir, "#{File.basename(args[:file])}_extracted")
Dir.mkdir extracted_dir
parser.entries[9].value.each do |blob|
hash = blob.value[0].value
content = blob.value[1].value
if content[0..3] == 'MAVZ'
print("Found MAVZ compressed file with hash #{hash}\n")
output_file = File.join(extracted_dir, "#{hash}.bin")
File.write(output_file, Zlib.inflate(content[8..]))
else
print("Found ASN1 coded patch file with hash #{hash}\n")
output_file = File.join(extracted_dir, "#{hash}.stream")
File.write(output_file, blob.value[1].value)
print("Enumerating files in patch file:\n\n")
print_files_in_patch(output_file)
end
end
end
end
end
end
|
require 'spec_fast_helper'
require 'hydramata/works/property_presenter_dom_helper'
require 'hydramata/works/work'
require 'hydramata/works/conversions/property'
require 'hydramata/works/predicate'
module Hydramata
module Works
describe PropertyPresenterDomHelper do
let(:work) { Work.new(work_type: 'a work type') }
let(:predicate) { Predicate.new(identity: 'my_predicate', validations: { required: true } ) }
let(:property) { double('property', predicate: predicate, presenter_dom_class: 'property', dom_class: 'my-predicate') }
subject { described_class.new(property) }
context '#label_attributes' do
it 'handles a :suffix' do
expect(subject.label_attributes(suffix: 'hello')).
to eq({ :id=>"label_for_work_my_predicate_hello", :class=>["property-label", "my-predicate", "required"] })
end
it 'handles an :index' do
expect(subject.label_attributes(index: 1, suffix: 'hello')).
to eq({ :id=>"label_for_work_my_predicate_hello_1", :class=>["property-label", "my-predicate", "required"] })
end
it 'has a default' do
expect(subject.label_attributes).
to eq({ :id=>"label_for_work_my_predicate", :class=>["property-label", "my-predicate", "required"] })
end
it 'merges attributes' do
expect(subject.label_attributes(:id => 'override_id', :class => 'another_class', 'data-attribute' => 'a data attribute')).
to eq({ :id=>"override_id", :class=>["another_class", "property-label", "my-predicate", "required"], 'data-attribute' => 'a data attribute' })
end
end
context '#value_attributes' do
it 'handles a :suffix' do
expect(subject.value_attributes(suffix: 'hello')).
to eq({ 'aria-labelledby'=>"label_for_work_my_predicate_hello", :class=>["property-value", "my-predicate"] })
end
it 'handles an :index' do
expect(subject.value_attributes(index: 1, suffix: 'hello')).
to eq({ 'aria-labelledby'=>"label_for_work_my_predicate_hello_1", :class=>["property-value", "my-predicate"] })
end
it 'has a default' do
expect(subject.value_attributes).
to eq({ 'aria-labelledby'=>"label_for_work_my_predicate", :class=>["property-value", "my-predicate"] })
end
it 'merges attributes' do
expect(subject.value_attributes('aria-labelledby' => 'override_id', :class => 'another_class', 'data-attribute' => 'a data attribute')).
to eq({ 'aria-labelledby'=>"override_id", :class=>["another_class", "property-value", "my-predicate"], 'data-attribute' => 'a data attribute' })
end
end
context '#input_attributes' do
it 'handles a :suffix' do
expect(subject.input_attributes(suffix: 'hello')).
to eq({ 'aria-labelledby'=>"label_for_work_my_predicate_hello", :class=>["property-input", "my-predicate"], :name => "work[my_predicate][hello][]", :required => 'required' })
end
it 'handles an :index' do
expect(subject.input_attributes(index: 1, suffix: 'hello')).
to eq({ 'aria-labelledby'=>"label_for_work_my_predicate_hello_1", :class=>["property-input", "my-predicate"], :name => "work[my_predicate][hello][]", :required => 'required' })
end
it 'has a default' do
expect(subject.input_attributes).
to eq({ 'aria-labelledby'=>"label_for_work_my_predicate", :class=>["property-input", "my-predicate"], :name => "work[my_predicate][]", :required => 'required' })
end
it 'merges attributes' do
expect(subject.input_attributes('aria-labelledby' => 'override_id', :class => 'another_class', 'data-attribute' => 'a data attribute')).
to eq({ 'aria-labelledby'=>"override_id", :class=>["another_class", "property-input", "my-predicate"], :name => "work[my_predicate][]", 'data-attribute' => 'a data attribute', :required => 'required' })
end
it 'only renders required attribute on first rendering' do
expect(subject.input_attributes.key?(:required)).to be_truthy
expect(subject.input_attributes.key?(:required)).to be_falsey
end
end
end
end
end
|
Rails.application.routes.draw do
devise_for :users
root 'frees#index'
resources :frees
resources :users
end
|
require 'spec_helper'
describe RoutesController do
describe "GET /routes" do
it 'routes to routes#index' do
get('/routes').should route_to(controller: 'routes', action: 'index')
end
end
describe "POST /routes" do
it 'routes to routes#create' do
post('/routes').should route_to(controller: 'routes', action: 'create')
end
end
describe "GET /routes/new" do
it 'routes to routes#new' do
get('/routes/new').should route_to(controller: 'routes', action: 'new')
end
end
describe "GET /routes/:id/edit" do
it 'routes to routes#edit' do
get('/routes/1/edit').should route_to(controller: 'routes', action: 'edit', id: '1')
end
end
describe "GET /routes/:id" do
it 'routes to routes#show' do
get('/routes/1').should route_to(controller: 'routes', action: 'show', id: '1')
end
end
describe "PUT /routes/:id" do
it 'routes to routes#update' do
put('/routes/1').should route_to(controller: 'routes', action: 'update', id: '1')
end
end
describe "DELETE /routes/:id" do
it 'routes to routes#destroy' do
delete('/routes/1').should route_to(controller: 'routes', action: 'destroy', id: '1')
end
end
describe "POST /routes/remove" do
it 'routes to routes#remove' do
post('/routes/remove').should route_to(controller: 'routes', action: 'remove')
end
end
end
|
class QuestionMailer < ApplicationMailer
default from: "micorreo@gmail.com"
def send_question(question)
@question = question
mail(to:"utesishelp@gmail.com", subject:"nueva duda para Utesis")
end
end
|
# @param {Integer[][]} graph
# @return {Integer[][]}
def all_paths_source_target(graph)
edges = {}
graph.each_with_index do |edge, i|
edges[i] = []
edge.each do |e|
edges[i] << e
end
end
breadth_first_traversal_paths(0, edges, graph.size-1)
end
def breadth_first_traversal_paths(node, edges, n, tmp_path = [])
queue = [[node, [node]]]
paths = []
until queue.empty?
v, path = queue.shift
if v == n
paths << path
end
edges[v].each do |e|
queue.push([e, path + [e]])
end
end
paths
end
|
class Store
@@register_detail = {}
@@rows = []
# @@register_detail = {'Veggies': {'items': {'Tomato': {'count': 100, 'price': 2, 'name': 'Tomato'}, 'Carrot': {'count': 100, 'price': 7, 'name': 'Carrot'}}, 'name': 'Veggies'}, 'Fruits': {'items': {'orange': {'count': 100, 'price': 17, 'name': 'orange'}, 'Apple': {'count': 100, 'price': 23, 'name': 'Apple'}}, 'name': 'Fruits'}}
def initialize
create_register
add_items_to_register
Store.show_item_list
end
def create_register
puts "Enter the register name"
store_name=gets.chomp
@@register_detail[store_name] = {items: []}
puts "Do you want to add more registers (Y/N)"
if gets.chomp == "Y"
create_register
end
end
def add_items_to_register(indx = nil)
@register_detail_keys = self.class.register_detail_keys
unless indx
puts "Please select register to add Items."
list_registers = self.class.list_registers
if list_registers == true
return true
else
indx = list_registers[0]
@register_detail_keys = list_registers[1]
end
end
register = @@register_detail[@register_detail_keys[indx]]
if register
add_item_details(indx)
puts "do u want to add more items (Y/N)"
if gets.chomp == "Y"
add_items_to_register(indx)
else
add_items_to_register
end
else
add_items_to_register
end
end
def add_item_details(indx)
puts "enter item name"
item_name = gets.chomp
puts "enter item price"
item_price = gets.chomp
puts "total no of item stock"
item_count = gets.chomp
@@register_detail[@register_detail_keys[indx]][:items] << { item_name: item_name, item_price: item_price, item_count: item_count }
end
def self.show_item_list
@@rows = []
reg_hash = Store.register_detail_keys.include?(:employee_discount) ? @@register_detail.dup.delete(:employee_discount) : @@register_detail
reg_hash.each.with_index(1) { |register, idx| register[1][:items].each { |item| @@rows << [@@rows.size+1, register[0], item[:item_name], item[:item_price], item[:item_count]] } }
table = Terminal::Table.new :title => "Items List", :headings => ['No', 'Register Name', 'Item Name', 'Item Price', 'Stock'], :rows => @@rows
puts table
end
def self.register_detail_keys
@@register_detail.keys
end
def self.list_registers
register_detail_keys = self.register_detail_keys << "Back"
register_detail_keys.each.with_index(1) { |reg_name, index| puts "#{index}. #{reg_name}" }
indx = gets.chomp.to_i
if indx == (register_detail_keys.index("Back") + 1)
return true
else
indx -= 1
end
register_detail_keys.pop
return indx, register_detail_keys;
end
def self.register_detail
@@register_detail
end
def self.rows
@@rows
end
end |
# Write a method, least_common_multiple, that takes in two numbers and returns the smallest number that is a mutiple
# of both of the given numbers
def least_common_multiple(num_1, num_2)
mult = num_1 * num_2
max = [num_1,num_2].max
(max).upto(mult) do |m|
return m if m % num_1 == 0 && m % num_2 == 0
end
end
# Write a method, most_frequent_bigram, that takes in a string and returns the two adjacent letters that appear the
# most in the string.
def most_frequent_bigram(str)
hash = Hash.new(0)
(0...str.length - 1).each do |i|
bigram = str[i] + str[i+1]
hash[bigram] += 1
end
bigrams = hash.sort_by {|k,v|v}
bigrams.last[0]
end
class Hash
# Write a method, Hash#inverse, that returns a new hash where the key-value pairs are swapped
def inverse
new_hash = {}
self.each { |k, v| new_hash[v] = k }
new_hash
end
end
class Array
# Write a method, Array#pair_sum_count, that takes in a target number returns the number of pairs of elements that sum to the given target
def pair_sum_count(num)
count = 0
self.each_with_index do |ele1, idx1|
self.each_with_index do |ele2, idx2|
count += 1 if idx2 > idx1 && ele1 + ele2 == num
end
end
count
end
# Write a method, Array#bubble_sort, that takes in an optional proc argument.
# When given a proc, the method should sort the array according to the proc.
# When no proc is given, the method should sort the array in increasing order.
def bubble_sort(&prc)
prc ||= Proc.new { |a, b| a <=> b}
sorted = false
while !sorted
sorted = true
(0...self.length - 1).each do |idx|
if prc.call(self[idx], self[idx + 1]) == 1
self[idx], self[idx + 1] = self[idx +1], self[idx]
sorted = false
end
end
end
self
end
end
|
require 'sinatra/base'
require 'sinatra/flash'
require 'sinatra/reloader'
require './lib/peep'
require './lib/user'
require 'pg'
require './database_connection_setup'
class Chitter < Sinatra::Base
enable :sessions, :method_override
register Sinatra::Flash
configure :development do
register Sinatra::Reloader
end
get '/' do
'Peeps'
end
get '/users/new' do
erb :'/users/new'
end
post '/peeps' do
Peep.create(text: params['peep'])
redirect '/peeps'
end
post '/users' do
user = User.create(email: params['email'], password: params['password'])
if user
session[:user_id] = user.id
redirect '/peeps'
else
flash[:notice] = 'You already have an account. Please sign in'
redirect '/users/new'
end
end
delete '/peeps/:id' do
Peep.delete(id: params['id'])
redirect '/peeps'
end
get '/peeps' do
@user = User.find(session[:user_id])
@peeps = Peep.all
erb :'peeps/index'
end
get '/session/new' do
erb :'session/new'
end
post '/session' do
user = User.authenticate(email: params['email'], password: params['password'])
if user
session[:user_id] = user.id
redirect '/peeps'
else
flash[:notice] = 'Incorrect credentials.'
redirect '/session/new'
end
end
run! if app_file == $0
end
|
class LinksController < ApplicationController
before_filter :authorize, only: [:destroy]
# GET /links
def index
if current_user
@links = current_user.links
else
@links = Link.where(user_id: nil).order('created_at DESC')
end
end
# GET /l/:short_name
# See routes.rb for how this is set up.
def show
@link = Link.find_by_short_name(params[:short_name])
if @link
@link.clicked!
redirect_to @link.url
else
render text: 'No such link.', status: 404
end
end
# GET /links/new
def new
@link = Link.new
end
# POST /links
def create
@link = Link.new(link_params)
@link.user_id = current_user.id if user_signed_in?
if @link.save
redirect_to root_url, notice: 'Link was successfully created.'
else
render :new
end
end
def destroy
@link = Link.find_by_short_name(params[:short_name])
@link.destroy
redirect_to action: :index, notice: 'Link deleted!'
end
private
# Only allow a trusted parameter "white list" through.
def link_params
params.require(:link).permit(:url, :shortname)
end
end
|
require "test_helper"
class WatchlistCoinsControllerTest < ActionDispatch::IntegrationTest
setup do
@watchlist_coin = watchlist_coins(:one)
end
test "should get index" do
get watchlist_coins_url, as: :json
assert_response :success
end
test "should create watchlist_coin" do
assert_difference('WatchlistCoin.count') do
post watchlist_coins_url, params: { watchlist_coin: { coin_id: @watchlist_coin.coin_id, watchlist_id: @watchlist_coin.watchlist_id } }, as: :json
end
assert_response 201
end
test "should show watchlist_coin" do
get watchlist_coin_url(@watchlist_coin), as: :json
assert_response :success
end
test "should update watchlist_coin" do
patch watchlist_coin_url(@watchlist_coin), params: { watchlist_coin: { coin_id: @watchlist_coin.coin_id, watchlist_id: @watchlist_coin.watchlist_id } }, as: :json
assert_response 200
end
test "should destroy watchlist_coin" do
assert_difference('WatchlistCoin.count', -1) do
delete watchlist_coin_url(@watchlist_coin), as: :json
end
assert_response 204
end
end
|
require 'down'
require 'rexml/document'
require 'zaru'
module Dri::Exporter::BagIt
class BagItExporter
include REXML
attr_reader :export_path, :user_email, :user_token
BASE_URL = 'https://repository.dri.ie'.freeze
def initialize(export_path:, user_email:, user_token:)
raise "No output directory given" unless export_path
@export_path = export_path
@user_email = user_email
@user_token = user_token
end
def export(object_ids:)
response = ::Dri::Exporter::DriService.parse(url, object_ids)
response.each do |r|
metadata = r['metadata']
metadata_download = ::Down.download(metadata_url(r['pid']))
identifier = extract_identifier(metadata_download.path) || r['pid']
if r['metadata'].key?('doi')
doi = r['metadata']['doi'].first['url']
end
bag_info = {}
bag_info['Internal-Sender-Identifier'] = identifier
bag_info['Internal-Sender-Description'] = BASE_URL + '/catalog/' + r['pid']
bag_info['External-Identifier'] = doi if doi
filename = identifier ? ::Zaru.sanitize!(identifier) : r['pid']
base_path = File.join(export_path, filename)
factory = BagFactory.new(base_path: base_path, bag_info: bag_info)
if !factory.empty?
::Dri::Exporter.logger.warn "bag already exists for #{identifier} #{r['pid']}"
next
end
factory.add_metadata(metadata_download.path)
r['files'].each do |file|
next unless file.key?('masterfile')
masterfile_download = ::Down.download(file['masterfile'] + "?" + auth_params)
data_dir = file.key?('preservation') ? 'preservation' : 'data'
factory.add_data(
File.join(data_dir, masterfile_download.original_filename),
masterfile_download.path
)
end
factory.create_bag
end
end
private
def extract_identifier(metadata_download_path)
xmlfile = File.new(metadata_download_path)
xmldoc = Document.new(xmlfile)
identifier = XPath.match(xmldoc, "//dc:identifier").map {|i| i.text }
identifier.empty? ? nil : identifier.first
end
def metadata_url(id)
BASE_URL + "/objects/" + id + "/metadata?" + auth_params
end
def url
BASE_URL + "/get_objects.json?" + auth_params + "&preservation=true"
end
def auth_params
"user_email=" + user_email + "&user_token=" + user_token
end
end
end
|
class AddTypeToTags < ActiveRecord::Migration[5.1]
def change
add_column :tags, :type, :string, null: false, default: ''
add_index :tags, :type
end
end
|
#
# Cookbook Name:: motd
# Recipe:: default
#
# Copyright (c) 2015 The Authors, All Rights Reserved.
#
include_recipe 'motd::console'
include_recipe 'motd::updates'
secpkg = ''
motd_file = '/etc/motd'
case node['platform_family'].to_s
when 'rhel'
case node['platform_version'].to_i
when 6
secpkg = 'yum-plugin-security'
when 5
secpkg = 'yum-security'
end
rpmquery = Mixlib::ShellOut.new('rpm -qi basesystem')
rpmquery.run_command
rpmquery_matched = rpmquery.stdout.match(/Install\s*Date.*/i).to_s
built = rpmquery_matched.gsub!(/.*Install\s*Date\W*((\S+\s?)+).*/i, '\1')
node.default['dsw']['built'] = built
when 'debian'
motd_file = '/etc/motd.dsw'
template '/etc/update-motd.d/00-chef_header' do
source '00-chef_header.erb'
owner 'root'
group 'root'
mode 00755
end
end
package secpkg do
action :install
only_if { secpkg != '' }
end
motd_ohai = {
manufacturer: '',
product_name: '',
serial_number: ''
}
if !node['dmi'].nil? && !node['dmi']['system'].nil?
dmi = node['dmi']['system'] ? node['dmi']['system'] : {}
motd_ohai = {
manufacturer: dmi['manufacturer'].nil? ? '' : dmi['manufacturer'],
product_name: dmi['product_name'].nil? ? '' : dmi['product_name'],
serial_number: dmi['serial_number'].nil? ? '' : dmi['serial_number']
}
puts motd_ohai
end
randy = rand(node['motd']['flavor'].length)
header = "#{node['motd']['company']} - #{node['motd']['flavor'][randy]}"
template motd_file do
source 'motd.erb'
owner 'root'
group 'root'
mode 00644
variables(
motd: node['motd'],
header: header,
dsw: node['dsw'],
console: defined?(node['console']['ip']) ? node['console']['ip'] : '',
motd_ohai: motd_ohai
)
end
template '/etc/issue' do
source 'issue.erb'
owner 'root'
group 'root'
mode 00644
variables(
issue: node['motd']['issue']
)
end
|
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
make_users
make_restaurants
make_reservations
end
end
def make_users
admin = User.create!(first_name: "Brent",
last_name: "Raines",
email: "bt.raines@gmail.com",
password: "foobar123",
password_confirmation: "foobar123",
role: "admin")
5.times do |n|
first_name = "Test"
last_name = "User #{n+1}"
email = "test-user-#{n+1}@reservester.com"
password = "password"
role = "owner"
User.create!(first_name: first_name,
last_name: last_name,
email: email,
password: password,
password_confirmation: password,
role: role)
end
end
def make_restaurants
users = User.all(limit: 6)
20.times do |n|
name = "Testaurant #{n+1}"
street = "123 Third Street"
city = "Cambridge"
state = "MA"
zip = "02141"
phone = "012-345-6789"
description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
users[rand(0..4)].restaurants.create!(name: name,
street: street,
city: city,
state: state,
zip: zip,
phone: phone,
description: description)
end
end
def make_reservations
restaurants = Restaurant.all
50.times do |n|
email = "test@example.com"
time = "2013-11-15 #{rand(0..23)}:09:36"
comment = "One member of the party has peanut allergies."
restaurants[rand(0..19)].reservations.create!(email: email,
time: time,
comment: comment)
end
end |
class PlacesController < InheritedResources::Base
private
def place_params
params.require(:place).permit(:name, :latitude, :longitude)
end
end
|
require 'test/unit'
require 'r4digitalnz'
include R4DigitalNZ
class Test_DigitalNZ < Test::Unit::TestCase
def setup
api_key = "xxxx"
@digitalNZ = DigitalNZ.new api_key
end
def test_simple_search
assert_nothing_raised do
r = @digitalNZ.search "Karori photograph"
assert_equal 20, r.num_results_requested
assert_equal 232, r.result_count
assert_equal 0, r.start
assert_equal "71382", r[0].id
end
end
def test_result
data = {"metadata_url"=>"http://api.digitalnz.org/records/v1/71382", "category"=>"Images", "title"=>"Karori Road, Karori, Wellington, soon after it was constructed", "content_provider"=>"Alexander Turnbull Library", "source_url"=>"http://api.digitalnz.org/records/v1/71382/source", "syndication_date"=>"2009-03-25T03:40:14.023Z", "id"=>"71382", "date"=>"", "thumbnail_url"=>"http://digital.natlib.govt.nz/get/23442?profile=thumb", "description"=>"Karori Road, Karori, Wellington, soon after it was constructed, circa 1882/3. Photograph taken by...", "display_url"=>"http://timeframes.natlib.govt.nz/logicrouter/servlet/LogicRouter?PAGE=object&OUTPUTXSL=object.xslt&pm_RC=REPO02DB&pm_OI=26617&pm_GT=Y&pm_IAC=Y&api_1=GET_OBJECT_XML&num_result=0&Object_Layout=viewimage_object"}
r = Result.new data
assert_equal "Karori Road, Karori, Wellington, soon after it was constructed", r.title
assert_equal "Alexander Turnbull Library", r.content_provider
end
def test_api_key_exception
digitalNZ = DigitalNZ.new "badkey"
assert_raise APIException do
digitalNZ.search "Karori photograph"
end
end
def test_search_with_options
r = @digitalNZ.search "Karori photograph", :num_results => 5, :start => 10
assert_equal 5, r.num_results_requested
assert_equal 232, r.result_count
assert_equal 10, r.start
assert_equal "64611", r[0].id
end
def test_search_enumerable
require 'test/data.rb'
s = SearchResult.new $data
assert s.respond_to? :collect
assert_not_nil s.find {|r| r.title.include?('Futuna')}
ids = ["71382", "98664", "63515", "95241", "110244", "101403", "70640", "123870", "58939", "62361", "64611", "61161", "102568", "73093", "88550", "97210", "97211", "99877", "101866", "101867"]
assert_equal ids, s.collect { |d| d.id}
end
def test_metadata
require 'test/data.rb'
meta_data = MetaData.new $mets
# assert_equal 2, meta_data.sections.length
assert_equal "timeframes:26617", meta_data.objid
assert_equal 'GDL-NLNZ', meta_data.profile
section = meta_data.section 'dc'
assert_equal 'dc', section.id
assert_equal 'text/xml', section.mime_type
assert_equal 'DC', section.mdtype
assert_equal ["Karori Road", "1882/1883"], section.coverage
assert_equal "StillImage", section.type
assert !section.respond_to?(:rights_url)
assert meta_data.section('dnz').respond_to?(:rights_url)
end
def test_content_partners
assert @digitalNZ.content_partners.include? "Unknown origin"
end
end
|
# coding: utf-8
require "test_helper"
require "googlemaps_polyline/decoder"
require "stringio"
class DecoderTest < Test::Unit::TestCase
def setup
@klass = GoogleMapsPolyline::Decoder
end
def test_initialize
io = sio
encoder = @klass.new(io)
assert_same(io, encoder.io)
end
def test_decode_points__1
assert_equal(
[[0, 0]],
@klass.new(sio("??")).decode_points)
end
def test_decode_points__2
assert_equal(
[[0, 0], [0, 0]],
@klass.new(sio("????")).decode_points)
end
def test_decode_points__3
assert_equal(
[[1, 0]],
@klass.new(sio("A?")).decode_points)
end
def test_decode_points__4
assert_equal(
[[0, 1]],
@klass.new(sio("?A")).decode_points)
end
def test_decode_points__5
assert_equal(
[[1, 1], [1, 1]],
@klass.new(sio("AA??")).decode_points)
end
def test_decode_points__6
assert_equal(
[[1, 2], [2, 4], [3, 8], [4, 16], [5, 32]],
@klass.new(sio("ACACAGAOA_@")).decode_points)
end
def test_decode_levels
assert_equal(
[0, 1, 2, 3],
@klass.new(sio("?@AB")).decode_levels)
end
def test_read_point
decoder = @klass.new(sio)
read_point = proc { |io| decoder.instance_eval { read_point(io) } }
assert_equal( 0, read_point[sio("?")])
assert_equal( 1, read_point[sio("A")])
assert_equal( -1, read_point[sio("@")])
assert_equal( 12345678, read_point[sio("{sopV")])
assert_equal(-12345678, read_point[sio("zsopV")])
assert_equal( 18000000, read_point[sio("_gsia@")])
assert_equal(-18000000, read_point[sio("~fsia@")])
assert_raise(ArgumentError) { read_point[sio("")] }
end
def test_read_level
decoder = @klass.new(sio)
read_level = proc { |io| decoder.instance_eval { read_level(io) } }
assert_equal(0, read_level[sio("?")])
assert_equal(1, read_level[sio("@")])
assert_equal(2, read_level[sio("A")])
assert_equal(3, read_level[sio("B")])
assert_raise(ArgumentError) { read_level[sio("")] }
end
private
def sio(string = nil)
return StringIO.new(string || "")
end
end
|
namespace :old_data do
desc ""
task :makevars => :environment do
include ActionView::Helpers::DateHelper
overall_start_time = Time.now
puts "--> importing data via rake at #{overall_start_time}.\n"
require 'faster_csv'
vars=[]
open(File.join('export.sql')) do |file| #{ |f| f.each('\n\n') { |record| p record } }
puts "--> parsing raw data..."
n=1
file.each do |record|
match = /^`([^`]+)` (VARCHAR|INT|DATETIME|TINYINT|TINYBLOB|DECIMAL|BLOB|).*$/.match(record)
if match
type = case match[2]
when "VARCHAR" then 'string'
when "INT" then 'integer'
when "DATETIME" then 'datetime'
when "TINYINT" then 'integer'
when "TINYBLOB" then 'binary'
when "DECIMAL" then 'decimal'
when "BLOB" then 'binary'
end
vars << [match[1], type]
end
end
end
vars.uniq!
File.open("vars.csv", 'w') do |file|
vars.each do |var|
line = []
file.puts(var.join(','))
end
end
end
end
|
class CreateMaxAuthentications < ActiveRecord::Migration
def change
create_table :max_authentications, force: true do |t|
# the cookie key provided from the browser 'navigator' object
t.text :navigator_sha
# using the inital request header to generate the password salt
t.text :request_header_salt
# the hash-salted password for this very entry
t.text :hashed_password
# when does the entire entry expire and a new confirmation by any authorized user is required
t.datetime :valid_to
# user type/id that accepted the authorization
t.string :authorizer_type
t.string :authorizer_id
# allow users with with current session to authorize further users
t.boolean :allow_further_authorization, default: false
end
end
end |
require 'singleton'
require_relative 'piece.rb'
class NullPiece < Piece
include Singleton
def initialize
@color = nil
@name = " ⧠ "
end
end
|
class Api::V4::QuestionnairesController < Api::V4::SyncController
def sync_to_user
__sync_to_user__("questionnaires")
end
def transform_to_response(questionnaire)
Api::V4::QuestionnaireTransformer.to_response(questionnaire)
end
def current_facility_records
# TODO: Current implementation always responds with 1 JSON minimum. Reason:
# process_token.last_updated_at has precision upto 3 milliseconds & is always lesser than updated_at.
dsl_version = params.require("dsl_version")
dsl_version_major = dsl_version.split(".")[0]
# For dsl_version "1.5", return all questionnaires from "1" to "1.5".
# De-duplicate multiple questionnaires of same type by choosing latest dsl_version.
Questionnaire
.for_sync
.select("DISTINCT ON (questionnaire_type) questionnaire_type, dsl_version, id, layout, updated_at")
.where(dsl_version: dsl_version_major..dsl_version)
.order(:questionnaire_type, dsl_version: :desc)
.updated_on_server_since(current_facility_processed_since, limit)
end
def other_facility_records
[]
end
private
def locale_modified?
process_token[:locale] != I18n.locale.to_s
end
def force_resync?
locale_modified? || resync_token_modified?
end
def current_facility_processed_since
return Time.new(0) if force_resync?
process_token[:current_facility_processed_since].try(:to_time) || Time.new(0)
end
def response_process_token
{
current_facility_processed_since: processed_until(current_facility_records) || current_facility_processed_since,
locale: I18n.locale.to_s,
resync_token: resync_token
}
end
end
|
require 'benchmark'
require 'prime'
BOUND = 1_000_000
# Objectives:
# Find the sum of the longest string of consecutive primes under bound n.
# Make the algorithm general to handle max bounds up to 10**10.
# By longest, I mean the longest consecutive string that gives a sum below
# max bound 'bound'.
# Returns an array of the elements of the consecutive prime string.
def longest_sum_of_consecutive_primes_below(bound)
primes = generate_primes(bound)
ans = find_consecutive_that_is_prime(primes)
end
# Returns an array of consecutive primes based from a max bound.
# Note that this needs to be filtered such that the array reduces to a prime,
# AND has the most number of elements.
def generate_primes(bound)
prime_generator = Prime.each
primes = [] << prime_generator.next
primes << prime_generator.next until primes.reduce(:+) >= bound
primes.pop # The last one makes the resulting sum just a *little* over,
# therefore we have to remove it.
primes
end
# Returns the most consecutive primes that folds to a prime.
def find_consecutive_that_is_prime(primes)
# primes_left is the array the method uses to check the left tail of the array
primes_left = primes.dup
primes_right = primes.dup # Same here, but for the right tail of the array.
loop do
primes_left.shift
primes_right.pop
# We're biased to the left tail because significantly smaller terms are
# removed at each iteration.
return primes_left if primes_left.reduce(:+).prime?
return primes_right if primes_right.reduce(:+).prime?
end
end
time = Benchmark.measure do
longest_consecutive_primes = longest_sum_of_consecutive_primes_below(BOUND)
ans = longest_consecutive_primes.reduce(:+)
terms = longest_consecutive_primes.size
puts "The prime, below #{BOUND}, that can be written as the sum of the most"\
" consecutive primes is #{ans}"\
" with #{terms} terms"
end
puts "Time elapsed (in seconds): #{time}"
|
require 'cgi'
class UrlParser
def initialize(url)
@url = url
@scheme = GetScheme()
@domain = GetDomain()
@port = GetPort()
@path = GetPath()
@query_string = GetQueryString()
@fragment_id = GetFragment()
end
attr_accessor :url
attr_accessor :scheme
attr_accessor :domain
attr_accessor :port
attr_accessor :path
attr_accessor :query_string
attr_accessor :fragment_id
def GetScheme
@url.split(":")[0]
end
def GetDomain
@url.split("//")[1].split("/")[0].split(":")[0]
end
def GetPort
scheme = @url.split(":")[0]
port = @url.split("//")[1].split("/")[0].split(":")[1]
if(!port and scheme == "http")
port = "80"
end
if(!port and scheme == "https")
port = "443"
end
port
end
def GetPath
path = @url.split("//")[1].split("/")[1].split("?")[0]
if path == ""
path = nil
end
path
end
def GetQueryString
query = @url.split("?")[1]
if(query)
query = query.split("#")[0]
end
if(query)
CGI::parse(query).transform_values(&:last)
else
nil
end
end
def GetFragment
@url.split("#")[1]
end
end |
class AnswersController < ApplicationController
layout "bare"
cache_sweeper :profile_sweeper, :only => [:update]
def index
@web_analytics.page_stack = ['Profile', 'Profile Answer Form']
@web_analytics.page_type = 'Profile Edit'
@answers = session_user.find_answers
render :update do |page|
render_lightbox(page, "answers")
end
end
def update
answers = session_user.find_answers
answers.each do |answer|
answer.update_attribute(:text, params["answer_#{answer.id}"])
end
render :update do |page|
page << "window.top.location.href='/aboutme'"
end
end
end
|
class User
include DataMapper::Resource
property :id, Serial
property :uid, String
property :name, String
property :nickname, String
property :email, String
property :created_at, DateTime
has n, :backups
def self.create_from_omniauth auth
User.first_or_create(
{
uid: auth["uid"]
},
{
name: auth["info"]["name"],
nickname: auth["info"]["nickname"],
email: auth["info"]["email"],
created_at: Time.now
}
)
end
end |
class Feed
attr_accessor :user
def initialize(user)
@user = user
end
def get()
if user.present?
Post.joins(%{
inner join connections on connections.to_user_id = posts.user_id
}).where('posts.id > coalesce(connections.last_seen_post_id, 0) and connections.user_id = ?', user.id).order('posts.created_at DESC')
else
Post.all
end
end
def mark_seen_untle(post)
user.connection.where(to_user_id: post.user_id).first.update(last_seen_post_id: post.id)
end
end |
class HoursController < ApplicationController
def index
render json: Hour.all
end
private
def hour_params
params.require(:hour).permit(:period, :efficiency)
end
end
|
module VagrantPlugins
module ReverseProxy
module Action
class WriteNginxConfig
def initialize(app, env, action)
@app = app
@action = action
end
def call(env)
@app.call(env)
# Does this make much sense? What if we disable it later
# for one specific machine? Then, the config should still
# be removed.
return unless env[:machine].config.reverse_proxy.enabled?
# Determine temp file and target file
nginx_config_file = env[:machine].config.reverse_proxy.nginx_config_file || '/etc/nginx/vagrant-proxy-config'
# Get the directory of the config file
nginx_config_dir = File.dirname(nginx_config_file)
unless File.directory?(nginx_config_dir)
env[:ui].error("Could not update nginx configuration: directory '#{nginx_config_dir}' does not exist. Continuing without proxy...")
return
end
tmp_file = env[:machine].env.tmp_path.join('nginx.vagrant-proxies')
env[:ui].info('Updating nginx configuration. Administrator privileges will be required...')
sm = start_marker(env[:machine])
em = end_marker(env[:machine])
# This code is so stupid: We write a tmp file with the
# current config, filtered to exclude this machine. Later,
# we put this machine's config back in. It might have
# changed, and might not have been present originally.
File.open(tmp_file, 'w') do |new|
begin
File.open(nginx_config_file, 'r') do |old|
# First, remove old entries for this machine.
while ln = old.gets() do
if sm == ln.chomp
# Skip lines until we find EOF or end marker
until !ln || em == ln.chomp do
ln = old.gets()
end
else
# Keep lines for other machines.
new.puts(ln)
end
end
end
rescue Errno::ENOENT
# Ignore errors about the source file not existing;
# we'll create it soon enough.
end
if @action == :add # Removal is already (always) done above
# Write the config for this machine
if env[:machine].config.reverse_proxy.enabled?
new.write(sm+"\n"+server_block(env[:machine])+em+"\n")
end
end
end
# Finally, copy tmp config to actual config
Kernel.system('sudo', 'cp', tmp_file.to_s, nginx_config_file)
# And reload nginx
nginx_reload_command = env[:machine].config.reverse_proxy.nginx_reload_command || 'sudo nginx -s reload'
Kernel.system(nginx_reload_command)
end
def server_block(machine)
if machine.config.reverse_proxy.vhosts
vhosts = machine.config.reverse_proxy.vhosts
else
host = machine.config.vm.hostname || machine.name
vhosts = {host => host}
end
ip = get_ip_address(machine)
vhosts.collect do |path, vhost|
# Rewrites are matches literally by nginx, which means
# http://host:80/... will NOT match http://host/...!
port_suffix = vhost[:port] == 80 ? '' : ":#{vhost[:port]}"
<<EOF
location /#{path}/ {
proxy_set_header Host #{vhost[:host]};
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-Base-Url http://$host:$server_port/#{path}/;
proxy_pass http://#{ip}#{port_suffix}/;
proxy_redirect http://#{vhost[:host]}#{port_suffix}/ /#{path}/;
}
EOF
end.join("\n")
end
def start_marker(m)
"# BEGIN #{m.id} #"
end
def end_marker(m)
"# END #{m.id} #"
end
# Also from vagrant-hostmanager
def get_ip_address(machine)
ip = nil
machine.config.vm.networks.each do |network|
key, options = network[0], network[1]
ip = options[:ip] if key == :private_network
break if ip
end
ip || (machine.ssh_info ? machine.ssh_info[:host] : nil)
end
end
end
end
end
|
class User < ActiveRecord::Base
extend ActiveHash::Associations::ActiveRecordExtensions
include Clearance::User
# Callbacks
before_validation :set_defaults
# Associations
belongs_to_active_hash :role
has_many :products, through: :products_users
has_many :products_users
# Validations
validates :role, inclusion: { in: Role.all }
# Delegations
delegate :admin?, to: :role
private
def set_defaults
self.role ||= Role.user
true
end
end
|
class AddViewToPic < ActiveRecord::Migration
def change
add_column :pics, :view, :integer
end
end
|
class Indocker::Containers::Container
attr_reader :name, :parent_containers, :dependent_containers, :soft_dependent_containers,
:volumes, :networks, :servers, :start_command,
:before_start_proc, :after_start_proc, :after_deploy_proc,
:build_args, :start_options, :redeploy_schedule
def initialize(name)
@name = name
@daemonize = true
@parent_containers = []
@dependent_containers = []
@soft_dependent_containers = []
@volumes = []
@networks = []
@servers = []
@start_options = {}
@build_args = {}
@redeploy_schedule = nil
end
def set_build_args(opts)
@build_args = opts
end
def set_before_start_proc(proc)
@before_start_proc = proc
end
def set_after_start_proc(proc)
@after_start_proc = proc
end
def set_after_deploy_proc(proc)
@after_deploy_proc = proc
end
def set_start_command(name)
@start_command = name
end
def set_tags(tag_list)
@tags = tag_list
end
def set_scale(count)
@start_options[:scale] = count
end
def set_attached
@daemonize = false
end
def tags
@tags || (raise ArgumentError.new("tags not defined for container :#{@name}"))
end
def set_image(image)
@image = image
end
def image
@image || (raise ArgumentError.new("image not defined for container :#{@name}"))
end
def servers
@servers || (raise ArgumentError.new("servers not defined for container :#{@name}"))
end
def daemonize(flag)
@daemonize = flag
@attach = false
end
def is_daemonized?
@daemonize
end
def set_servers(servers)
@servers = servers
end
def add_parent_container(container)
@parent_containers.push(container) if !@parent_containers.include?(container)
end
def add_dependent_container(container)
container.add_parent_container(self)
@dependent_containers.push(container) if !@dependent_containers.include?(container)
end
def add_soft_dependent_container(container)
@soft_dependent_containers.push(container) if !@soft_dependent_containers.include?(container)
end
def set_start_options(opts)
@start_options = opts
end
def get_start_option(name, default: nil)
@start_options.fetch(name) { default }
end
def set_volumes(volumes)
@volumes = volumes
end
def set_networks(networks)
@networks = networks
networks.each do |network|
network.add_container(self)
end
end
def set_redeploy_schedule(schedule)
@redeploy_schedule = schedule
end
end |
# @summary
# Transform a supposed boolean to On or Off. Passes all other values through.
#
Puppet::Functions.create_function(:'apache::bool2httpd') do
# @param arg
# The value to be converted into a string.
#
# @return
# Will return either `On` or `Off` if given a boolean value. Return's a string of any
# other given value.
# @example
# $trace_enable = false
# $server_signature = 'mail'
#
# bool2httpd($trace_enable) # returns 'Off'
# bool2httpd($server_signature) # returns 'mail'
# bool2httpd(undef) # returns 'Off'
#
def bool2httpd(arg)
return 'Off' if arg.nil? || arg == false || arg =~ %r{false}i || arg == :undef
return 'On' if arg == true || arg =~ %r{true}i
arg.to_s
end
end
|
module UsersHelper
def is_author?(user)
user == current_user
end
end
|
class AddColumnCountryToBillingAddress < ActiveRecord::Migration
def change
add_column :billing_addresses,:country,:string
end
end
|
class AddUserIdToIncident < ActiveRecord::Migration[6.0]
def change
add_column :incidents, :user_id, :integer
end
end
|
name 'ganeti_webmgr'
maintainer 'OSU Open Source Lab'
maintainer_email 'chance@osuosl.org'
license 'All rights reserved'
description 'Installs/Configures Ganeti Web Manager'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.1'
depends 'application'
depends 'application_python'
depends 'application_nginx'
|
class ExportsController < ApplicationController
include Searching
include ProjectScoped
def show
@sources = Source.by_search_params(search_params).by_project(@project)
@users = User.all
disposition = params.key?(:download) ? 'attachment' : 'inline'
respond_to do |format|
format.pdf do
render pdf: 'export',
template: 'exports/export',
dpi: '300',
margin: {top: 10, bottom: 10, left: 20, right: 20},
user_xserver: false,
disposition: disposition
end
format.bib do
render plain: Source.to_bibliography(@sources).to_s
end
end
end
end
|
module WineBouncer
module AuthMethods
attr_accessor :doorkeeper_access_token
def protected_endpoint=(protected)
@protected_endpoint= protected
end
def protected_endpoint?
@protected_endpoint || false
end
def resource_owner
instance_eval(&WineBouncer.configuration.defined_resource_owner)
end
def client_credential_token?
has_doorkeeper_token? && doorkeeper_access_token.resource_owner_id.nil?
end
def doorkeeper_access_token
@_doorkeeper_access_token
end
def doorkeeper_access_token=(token)
@_doorkeeper_access_token = token
end
def has_doorkeeper_token?
!!@_doorkeeper_access_token
end
def has_resource_owner?
has_doorkeeper_token? && !!doorkeeper_access_token.resource_owner_id
end
end
end
|
class AddAttachmentAvatarToComentario < ActiveRecord::Migration
def self.up
add_column :comentarios, :avatar_file_name, :string
add_column :comentarios, :avatar_content_type, :string
add_column :comentarios, :avatar_file_size, :integer
add_column :comentarios, :avatar_updated_at, :datetime
end
def self.down
remove_column :comentarios, :avatar_file_name
remove_column :comentarios, :avatar_content_type
remove_column :comentarios, :avatar_file_size
remove_column :comentarios, :avatar_updated_at
end
end
|
#
# Author:: Seth Chisamore (<schisamo@opscode.com>)
# Author:: Lucas Hansen (<lucash@opscode.com>)
# Cookbook Name:: php
# Recipe:: package
#
# Copyright 2013, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
if platform?("windows")
include_recipe 'iis::mod_cgi'
install_dir = File.expand_path(node['php']['conf_dir']).gsub('/', '\\')
windows_package node['php']['windows']['msi_name'] do
source node['php']['windows']['msi_source']
installer_type :msi
options %W[
/quiet
INSTALLDIR="#{install_dir}"
ADDLOCAL=#{node['php']['packages'].join(',')}
].join(" ")
end
# WARNING: This is not the out-of-the-box go-pear.phar. It's been modified to patch this bug:
# http://pear.php.net/bugs/bug.php?id=16644
cookbook_file "#{node['php']['conf_dir']}/PEAR/go-pear.phar" do
source "go-pear.phar"
end
template "#{node['php']['conf_dir']}/pear-options" do
source "pear-options.erb"
end
execute "install-pear" do
cwd node['php']['conf_dir']
command "go-pear.bat < pear-options"
creates "#{node['php']['conf_dir']}/pear.bat"
end
ENV['PATH'] += ";#{install_dir}"
windows_path install_dir
else
node['php']['packages'].each do |pkg|
package pkg do
action :install
end
end
end
template "#{node['php']['conf_dir']}/php.ini" do
source "php.ini.erb"
unless platform?("windows")
owner "root"
group "root"
mode "0644"
end
variables(:directives => node['php']['directives'])
end
|
require 'sinatra/base'
require 'resque'
require 'digest/sha1'
require 'haml'
require 'sass'
class GoogleBooks < Sinatra::Base
configure do
REDIS = Redis.new
BOOKS_PER_PAGE = 20
end
helpers do
def image(src, alt=nil)
src ? "<img src='#{src}' alt='#{alt}'/>" : "N.A."
end
def pagination_range(page_number, total_books)
# display 20 items per page
# all non-numeric and blank strings will evaluate to 0
page_number == 0 ? @head = 0 : @head = (page_number * BOOKS_PER_PAGE) - BOOKS_PER_PAGE
@tail = @head + 19
@head <= total_books ? (@head..@tail) : (0..19)
end
def pagination_bar(page_number, total_books)
amount_of_pages = (total_books / BOOKS_PER_PAGE) + 1
pagination = ''
amount_of_pages.times do |i|
if page_number == (i + 1)
pagination << "<li class='active'><a href='/?page=#{i + 1}'>#{i + 1}</a></li>"
else
pagination << "<li><a href='/?page=#{i + 1}'>#{i + 1}</a><li>"
end
end
pagination
end
def get_cached_page
page_tag = request.url
page = REDIS.get(page_tag)
end
def set_cache_for_page(page)
REDIS.lpush('cached_page_ids', request.url)
REDIS.set(request.url, page)
page
end
end
##### helpers #####
get '/' do
# http caching
# if browser sends matching etag headers, it will return 304 immediately
etag( Digest::SHA1.hexdigest(REDIS.get("app:last_updated")) || Time.now) if REDIS.get("app:last_updated")
# page caching
# however, it does not always send etag headers
# then we serve a cached page
html = get_cached_page
return html if html
# in case we could serve thru http or page caching,
# that means this request is the first for this page after data-refresh
@book_ids = REDIS.lrange('book_ids', 0, -1).reverse
@books = @book_ids[ pagination_range(params[:page].to_i, @book_ids.size) ].map{ |b| REDIS.hgetall(b)}
set_cache_for_page(haml(:index))
haml(:index)
end
# SASS stylesheet
get '/styles.css' do
etag( Digest::SHA1.hexdigest(REDIS.get("app:last_updated")) || Time.now) if REDIS.get("app:last_updated")
scss = get_cached_page
return scss if scss
set_cache_for_page(scss(:styles))
scss(:styles)
end
end |
class Review < ApplicationRecord
belongs_to :evaluation
belongs_to :evaluation_image
belongs_to :user
belongs_to :trip
has_many :favorites, dependent: :destroy
has_many :review_photos, dependent: :destroy
accepts_nested_attributes_for :review_photos
accepts_attachments_for :review_photos, attachment: :review_image
# 画像投稿
# お気に入りしているかどうか
def favorited_by?(user)
favorites.where(user_id: user.id).exists?
end
end
|
class SolarSystem
attr_reader :star_name, :planets
def initialize(star_name)
@star_name = star_name
@planets = Array.new
end
def add_planet(planet)
@planets << planet
end
def list_planets
return "\nPlanets orbiting #{@star_name}:\n",
@planets.each_with_index.map do |planet, i|
"#{i+1}. #{planet.name}"
end
end
def find_planet_by_name(planet_name)
raise ArgumentError.new("Argument must be a string") unless planet_name.is_a? String
@planets.each do |planet|
return planet if planet.name.downcase == planet_name.downcase
end
end
end |
CWD = File.expand_path(File.dirname(__FILE__))
def sys(cmd)
puts " -- #{cmd}"
unless ret = xsystem(cmd)
raise "#{cmd} failed, please report to https://github.com/tmm1/perfools.rb/issues/new with #{CWD}/src/mkmf.log and #{CWD}/src/gperftools-2.0/config.log"
end
ret
end
require 'mkmf'
require 'fileutils'
if RUBY_VERSION > "1.9.3"
begin
require 'debase/ruby_core_source'
rescue LoadError
require 'rubygems/dependency_installer'
installer = Gem::DependencyInstaller.new
installer.install 'debase-ruby_core_source'
Gem.refresh
Gem::Specification.find_by_name('debase-ruby_core_source').activate
require 'debase/ruby_core_source'
end
else
begin
require "debugger/ruby_core_source"
rescue LoadError
require 'rubygems/user_interaction' # for 1.9.1
require 'rubygems/dependency_installer'
installer = Gem::DependencyInstaller.new
installer.install 'debugger-ruby_core_source'
Gem.refresh
if Gem.method_defined? :activate
Gem.activate('debugger-ruby_core_source') # for 1.9.1
else
Gem::Specification.find_by_name('debugger-ruby_core_source').activate
end
require "debugger/ruby_core_source"
end
end
perftools = File.basename('gperftools-2.0.tar.gz')
dir = File.basename(perftools, '.tar.gz')
puts "(I'm about to compile google-perftools.. this will definitely take a while)"
ENV["PATCH_GET"] = '0'
Dir.chdir('src') do
FileUtils.rm_rf(dir) if File.exists?(dir)
sys("tar zpxvf #{perftools}")
Dir.chdir(dir) do
if ENV['DEV']
sys("git init")
sys("git add .")
sys("git commit -m 'initial source'")
end
[ ['perftools', true],
['perftools-notests', true],
['perftools-pprof', true],
['perftools-gc', true],
['perftools-osx', false], # fixed in 2.0
['perftools-debug', true],
['perftools-objects', true],
['perftools-frames', true],
['perftools-realtime', true],
['perftools-pause', true]
].each do |patch, apply|
if apply
sys("patch -p1 < ../../../patches/#{patch}.patch")
sys("git commit -am '#{patch}'") if ENV['DEV']
end
end
sys("sed -i -e 's,SpinLock,ISpinLock,g' src/*.cc src/*.h src/base/*.cc src/base/*.h")
sys("git commit -am 'rename spinlock'") if ENV['DEV']
end
Dir.chdir(dir) do
FileUtils.cp 'src/pprof', '../../../bin/'
FileUtils.chmod 0755, '../../../bin/pprof'
end
Dir.chdir(dir) do
if RUBY_PLATFORM =~ /darwin10/
ENV['CFLAGS'] = ENV['CXXFLAGS'] = '-D_XOPEN_SOURCE'
end
sys("./configure --disable-heap-profiler --disable-heap-checker --disable-debugalloc --disable-shared")
sys("make")
FileUtils.cp '.libs/libprofiler.a', '../../librubyprofiler.a'
end
end
$LIBPATH << CWD
$libs = append_library($libs, 'rubyprofiler')
def add_define(name)
$defs.push("-D#{name}")
end
case RUBY_PLATFORM
when /darwin/, /linux/, /freebsd/
CONFIG['LDSHARED'] = "$(CXX) " + CONFIG['LDSHARED'].split[1..-1].join(' ')
end
if RUBY_VERSION >= "1.9"
add_define 'RUBY19'
if RUBY_VERSION >= "2.0"
add_define 'HAVE_RB_NEWOBJ_OF'
end
hdrs = proc {
have_header("method.h") # exists on 1.9.2
have_header("vm_core.h") and
(have_header("iseq.h") or have_header("iseq.h", ["vm_core.h"])) and
have_header("insns.inc") and
have_header("insns_info.inc")
}
core_source = Debugger rescue Debase
unless core_source::RubyCoreSource::create_makefile_with_core(hdrs, "perftools")
STDERR.puts "\n\n"
STDERR.puts "***************************************************************************************"
STDERR.puts "****************** Debugger::RubyCoreSource::create_makefile FAILED *******************"
STDERR.puts "***************************************************************************************"
exit(1)
end
else
add_define 'RUBY18'
have_func('rb_during_gc', 'ruby.h')
create_makefile 'perftools'
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Version: 0.5.3
# Try reading package.name from ./site/package.json
begin
$hostname = JSON.parse(File.read(__dir__ + '/site/package.json'))['name']
rescue StandardError
end
# hostname fallback to 'vagrant' if nil or empty
$hostname = 'vagrant' if $hostname.nil? || $hostname.empty?
# clean hostname and add '.test' TLD
$hostname = $hostname
.downcase
.gsub(/[^a-z0-9]+/, '-') # sanitize non-alphanumerics to hyphens
.gsub(/^-+|-+$/, '') # strip leading or trailing hyphens
$devDomain = $hostname.gsub(/(\.dev|\.test)*$/, '') + '.test'
# Explicitly set $hostname here to override everything above
# $hostname = "dev.example.test"
# Read version from package.json
begin
$version = JSON.parse(File.read(__dir__ + '/package.json'))['version']
rescue StandardError
end
# Placeholder version if missing, nil or empty
$version = '?.?.?' if $version.nil? || $version.empty?
# Read Ansible config from config.yml, set default for use_ssl
$ansible_config = YAML.load_file('config.yml') if File.file?('config.yml')
$ansible_config ||= { "use_ssl" => false }
Vagrant.configure(2) do |config|
config.ssh.insert_key = false
config.vm.box = "ideasonpurpose/basic-wp"
config.vm.box_version = ">= 1.5.0"
# config.vm.box = "basic-wp"
config.vm.hostname = $hostname
config.vm.define $devDomain
config.vm.post_up_message = Proc.new {
ip = File.read(__dir__ + '/.ip_address').strip
protocol = $ansible_config['use_ssl'] ? 'https://' : 'http://'
msg = " Thank you for using Basic WordPress Vagrant (v#{$version})\n"
msg << " https://github.com/ideasonpurpose/basic-wordpress-vagrant\n\n"
msg << " Local server addresses:\n" if Vagrant.has_plugin? 'vagrant-hostmanager'
msg << " #{ protocol }#{ $devDomain }\n" if Vagrant.has_plugin? 'vagrant-hostmanager'
msg << " Local server address:\n" if not Vagrant.has_plugin? 'vagrant-hostmanager'
msg << " #{ protocol }#{ ip }\n"
msg << "-"
msg
}
if Vagrant.has_plugin? 'vagrant-auto_network'
config.vm.network :private_network, auto_network: true, id: "basic-wordpress-vagrant_#{$hostname}"
else
config.vm.network "private_network", type: "dhcp"
end
config.vm.synced_folder ".", "/vagrant", owner:"www-data", group:"www-data", mount_options:["dmode=775,fmode=664"]
config.vm.provider "virtualbox" do |v|
# v.gui = true # for debugging
v.customize ["modifyvm", :id, "--cpus", 1]
v.customize ["modifyvm", :id, "--memory", 512]
v.customize ["modifyvm", :id, "--vram", 4]
v.customize ["modifyvm", :id, "--name", $devDomain]
v.customize ["modifyvm", :id, "--ioapic", "on"]
v.customize ["modifyvm", :id, "--paravirtprovider", "kvm"]
v.customize ["modifyvm", :id, "--cableconnected1", 'on']
end
config.vm.provision "ansible_local" do |ansible|
ansible.compatibility_mode = "2.0"
ansible.playbook = "ansible/main.yml"
ansible.extra_vars = {
site_name: (Vagrant.has_plugin? 'vagrant-hostmanager') ? $devDomain : nil,
theme_name: $hostname,
vagrant_cwd: File.expand_path(__dir__)
}
end
if Vagrant.has_plugin? 'vagrant-hostmanager'
config.vm.provision :hostmanager
config.hostmanager.enabled = true
config.hostmanager.manage_host = true
config.hostmanager.manage_guest = true
config.hostmanager.aliases = [$devDomain]
config.hostmanager.ip_resolver = proc do |vm, resolving_vm|
ip_addr = ""
cmd = "VBoxControl --nologo guestproperty get /VirtualBox/GuestInfo/Net/1/V4/IP | cut -f2 -d' '" #" | tee /vagrant/.ip_address"
vm.communicate.sudo(cmd) do |type, data|
ip_addr << data.strip
end
ip_addr
end
end
end
|
require 'pry'
# Write a method that will return all palindromes within a string
def is_palindrome?(word)
letters = word.split('')
center_idx = (word.length)/2 - 1
start_half = letters[0..center_idx]
last_half = ''
if word.length.even?
last_half = letters[(center_idx+1)..-1]
else
last_half = letters[(center_idx+2)..-1]
end
start_half.length.times do
return false unless start_half.shift == last_half.pop
end
true
end
def substrings(word)
start = (0..(word.length-1)).to_a
finish = (0..(word.length-1)).to_a
ranges = start.product(finish)
substring_arr = []
ranges.each do |range|
next if range.first > range.last
substring_arr << word[range.first..range.last]
end
trash = substring_arr.select {|str| str.length == 1}
substring_arr.delete_if {|str| trash.include?(str)}
end
def palindromes(word)
substrings(word).select {|word| is_palindrome?(word)}
end
def longest_palindrome(palindromes)
longest_item = ''
palindromes.each do |item|
longest_item = item if item.length > longest_item.length
end
longest_item
end
p palindromes("ppop") #=> ['pp','pop']
p longest_palindrome(palindromes("ppop")) #=> ['pop'] |
require 'spec_helper'
describe RobotsController do
let(:double_io) { double(:io, read: 'data', meta: {}) }
before :each do
Time.stub(:now).and_return 1
end
describe "GET #sitemap" do
it 'with no :id' do
controller.should_receive(:open).with('http://res.cloudinary.com/wlabs/raw/upload/v1/test_sitemap.xml.gz', proxy: AppConfig.proxy).and_return double_io
get :sitemap
end
it 'with an :id' do
controller.should_receive(:open).with('http://res.cloudinary.com/wlabs/raw/upload/v1/test_sitemap1.xml.gz', proxy: AppConfig.proxy).and_return double_io
get :sitemap, id: 1
end
end
end |
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ubuntu/trusty64"
config.hostmanager.enabled = true
config.hostmanager.manage_host = true
config.hostmanager.ignore_private_ip = false
config.hostmanager.include_offline = false
config.vm.network :private_network, ip: '192.168.177.178'
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.hostname = 'groundsource'
config.hostmanager.aliases = %w(groundsource.dev www.groundsource.dev)
config.vm.synced_folder './app', '/home/vagrant/app', nfs: true
end
|
class Participation < ActiveRecord::Base
belongs_to :game
belongs_to :user
enum state: [:pending, :accepted, :denied]
def self.create_invitation(game, user)
participation = self.new(game: game, user: user)
participation.state = :pending
participation.save!
end
def accept_invite
self.accepted!
CheckInvitesWorker.perform_async(game.id)
end
def deny_invite
self.destroy!
CheckInvitesWorker.perform_async(game.id)
end
end
|
# frozen_string_literal: true
class ChangeImageToFilenameInStudentImages < ActiveRecord::Migration[5.0]
def change
rename_column :student_images, :image, :filename
end
end
|
module MyData
class Node
attr_accessor :name
attr_reader :children
def initialize
@name = ""
@children = []
end
def child_exist?
!@children.empty?
end
def add_child(node)
@children << node
end
def to_xml
result = ""
result += '<node Text="'
result += @name
if child_exist?
result += '">'
@children.each do |node|
result += node.to_xml
end
result += '</node>'
else
result += '"/>'
end
end
end
end
|
# frozen_string_literal: true
class Jersey < ApplicationRecord
has_many :jersey_orders
has_many :orders, through: :jersey_orders
belongs_to :team
has_one_attached :image
validates :name, :description, :price, presence: true
validates :price, numericality: { only_decimal: true }
end
|
# frozen_string_literal: true
class Board
def initialize(knight)
@knight = knight
@knight.set_board(self)
end
# takes an array of size 2
def valid_position?(position)
return false if position.length != 2
position.all? { |coordinate| coordinate >= 0 && coordinate <= 7 }
end
end
|
require 'spec_helper'
describe GroupDocs::Subscription::Limit do
it_behaves_like GroupDocs::Api::Entity
it { should have_accessor(:Id) }
it { should have_accessor(:Min) }
it { should have_accessor(:Max) }
it { should have_accessor(:Description) }
it { should alias_accessor(:id, :Id) }
it { should alias_accessor(:min, :Min) }
it { should alias_accessor(:max, :Max) }
it { should alias_accessor(:description, :Description) }
end
|
class JobMailer < ApplicationMailer
default from: ENV['DEFAULT_FROM']
def job_created(job)
@job = job
mail(to: ENV['ADMIN_EMAIL'], subject: "Revisar vaga: #{job.title}")
end
end
|
require 'rails_helper'
require 'cve_file_parser'
RSpec.describe CveFileParser, as: :lib do
it 'can parse a document' do
expect(Vulnerability.count).to eq(0)
parser = CveFileParser.new('spec/samples/allitems-cvrf.xml')
parser.parse
expect(Vulnerability.count).to eq(4)
end
end
|
require 'redis'
require 'json'
module BroadcastEcho
module Publisher
class RedisPublisher
attr_accessor :config
def initialize(args)
@config = args[:config]
end
def process
redis = Redis.new(host: config.host, port: config.port, db: config.database)
redis.publish "private-channel", {msg: "abc"}.to_json
end
end
end
end
|
require 'test_helper'
class ScheduleBlocksControllerTest < ActionController::TestCase
setup do
@schedule_block = schedule_blocks(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:schedule_blocks)
end
test "should get new" do
get :new
assert_response :success
end
test "should create schedule_block" do
assert_difference('ScheduleBlock.count') do
post :create, schedule_block: @schedule_block.attributes
end
assert_redirected_to schedule_block_path(assigns(:schedule_block))
end
test "should show schedule_block" do
get :show, id: @schedule_block.to_param
assert_response :success
end
test "should get edit" do
get :edit, id: @schedule_block.to_param
assert_response :success
end
test "should update schedule_block" do
put :update, id: @schedule_block.to_param, schedule_block: @schedule_block.attributes
assert_redirected_to schedule_block_path(assigns(:schedule_block))
end
test "should destroy schedule_block" do
assert_difference('ScheduleBlock.count', -1) do
delete :destroy, id: @schedule_block.to_param
end
assert_redirected_to schedule_blocks_path
end
end
|
class AddLevelToWordProgress < ActiveRecord::Migration
def change
add_column :word_progresses, :level, :integer
end
end
|
class Image
def initialize
@view = ([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
])
end
def output_image
@view.each do |row|
puts row.join("")
end
end
def blur!(distance=1)
distance.times do
blur_points!
# This method finds the distance,1, from all indexes with a value of 1.
end
end
private
def blur_points!
blur_points = []
@view.each_with_index do |row, i|
row.each_with_index do |x, row_i|
blur_points << [i, row_i] if x == 1
# This method iterates through each row and element
# and any index with a value of one is stored into the array
# "blur_points!".
end
end
blur_points.each do |point|
@view[point[0]][point[1] + 1] = 1 if point[1] + 1 <= @view[point[0]].length - 1
@view[point[0]][point[1] - 1] = 1 if point[1] - 1 >= 0
@view[point[0] + 1][point[1]] = 1 if point[0] + 1 <= @view.length - 1
@view[point[0] - 1][point[1]] = 1 if point[0] - 1 >= 0
# This method is the index value modifier. It is iterating through
# the stored indexes with val 1, and any index within a distance of one
# index whos value is zero is converted to a value of 1.
end
end
end
image = Image.new
image.blur!(2)
# This call can be run for distance 1 or more
# depending on argument value.
image.output_image
|
## Division
# Have the function Division(num1,num2) take both parameters being passed and
# return the Greatest Common Factor. That is, return the greatest number that
# evenly goes into both numbers with no remainder. For example: 12 and 16 both
# are divisible by 1, 2, and 4 so the output should be 4. The range for both
# parameters will be from 1 to 10^3.
def Division(num1, num2)
num1 < num2 ? number = num1 : number = num2
factors =[]
(number - 1).downto(1) {|i| factors << i if (num1 % i == 0)&&(num2 % i == 0)}
factors.max
end
|
#!/usr/bin/env ruby
require 'set'
require 'optparse'
require 'json'
class SeatingChart
def initialize(options)
@lock = Mutex.new
@best = {iter: -1, array: nil, students: nil, deviation: 10}
@count = options[:students]
@length = options[:rounds]
@output = options[:format]
@out_file = options[:output]
@input = options[:input]
@names = options[:names]
@options = options
end
def eol
create_names(@count)
b = @best
STDERR.puts "Best Results: #{b[:iter] + 1}"
print_grid(b[:students])
STDERR.puts "Distribution:"
counts = Hash.new(0)
b[:students].each {|row| row.each {|cell| counts[cell] += 1}}
counts.delete(99)
counts = Hash[counts.map{|k, v| [k, v / 2]}]
counts.each do |o|
STDERR.puts " %2d => %d" % o
end
STDERR.puts "Standard Deviation: #{b[:deviation].round 3}"
print_out(b[:array])
end
def start
if @input
data = File.open(@input, 'r'){|f| JSON.parse(f.read)}
create_names(data.first.flatten.length)
print_out(data)
else
run
end
end
def run
4.times.map do
Thread.new do
loop do
catch :died do
students = Array.new(@count) do |i|
x = Array.new(@count, 0)
x[i] = 99
x
end
all_groups = []
max = 1
@length.times do |iter|
groups = []
used = Set.new
index = 0
g3 = (4 - @count % 4) % 4
total = (@count / 4.0).ceil
if iter % (total - 1) == 0 #&& iter < @count / 4 || iter % (@count / 4) == 0 && iter > @count / 4
max += 1
end
total.times do |round|
indexes = @count.times.reject{|i| used.include?(i)}
index = indexes.delete(indexes.sample)
group = [index]
used << index
(total - g3 <= round ? 2 : 3).times do
valid = nil
1.upto(max) do |n|
valid = indexes.reject{|i| group.inject(false){|m,o| m || students[o][i] >= n}}
break if valid.length > 0
end
throw :died if valid.length < 1
local_index = valid.sample
indexes.delete(local_index)
used << local_index
group.each do |i|
students[i][local_index] += 1
students[local_index][i] += 1
end
group << local_index
end
groups << group
end
all_groups << groups
std_dev = std_deviation(students)
@lock.synchronize do
if iter > @best[:iter] || iter == @best[:iter] && std_dev < @best[:deviation]
STDERR.puts "#{Time.now} | Best: %2d, STDDEV: #{std_dev.round 4}" % iter
@best = {iter: iter, array: all_groups, students: students, deviation: std_dev}
end
end
end
end
end
end
end.map(&:join)
end
private
def print_grid(grid)
STDERR.print ' '
0.upto(grid.length - 1){|n| STDERR.print ' %2d' % n}
STDERR.puts
grid.each_with_index do |line, num|
STDERR.print ' %2d' % num
out = ''.dup
line.each {|x| out << ('%3d' % x)}
STDERR.puts out
end
end
def std_deviation(students)
counts = Hash.new(0)
students.each {|row| row.each {|cell| counts[cell] += 1}}
counts.delete(99)
counts = Hash[counts.map{|k, v| [k, v / 2]}]
number = counts.values.inject(:+)
mean = counts.inject(0.0) {|m,o| m + o[0] * o[1] } / number
Math.sqrt(counts.inject(0.0) {|m,o| m + o[1] * ((o[0] - mean) ** 2) / number })
end
def print_out(data)
out = @out_file && @out_file != '-' && File.open(@out_file, 'w') || STDOUT
case @output
when :grouped
longest = @names.inject(0){|m,o| [m, o.length, (data.first.length / 10.0).ceil + 6].max}
data.each_with_index do |line, index|
unless index == 0
out.puts '---------------------------------------'
out.puts
end
out.puts "Groupings ##{index + 1}\n\n"
formatting = "| %-#{longest}s |"
line.each_slice(4).each_with_index do |people, index|
out.puts(people.length.times.map do |t|
"| Group %-#{longest - 6}d |" % (index * 4 + t + 1)
end.join(' '))
people.delete_at(0).zip(*people) do |row|
output = ""
row.each_with_index do |num, i|
output << ' ' unless i == 0
output << (formatting % @names[num]) unless num.nil?
end
out.puts output
end
out.puts
end
end
when :json
out.puts JSON.dump(data)
when :list
data.each_with_index do |line, index|
unless index == 0
out.puts '---------------------------------------'
out.puts
end
out.puts "Groupings ##{index + 1}\n\n"
line.each do |row|
row.each do |num|
out.puts " #{@names[num]}"
end
out.puts
end
end
end
ensure
out.close unless out == STDOUT
end
def create_names(count)
@names ||= Array.new(count) {|i| (i + 1).to_s}
end
end
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: seating.rb [options]"
opts.on("-s", "--students COUNT", Integer, "Number of students") do |s|
options[:students] = s
end
opts.on("-n", "--names FILE", String, "File containing names. One per line. (This overrides student count)") do |f|
options[:names] = File.open(f, 'r'){|f| f.read.split("\n")}
options[:students] = options[:names].length
end
opts.on("-r", "--rounds ROUNDS", Integer, "Number of rounds to perform") do |r|
options[:rounds] = r
end
opts.on("-o", "--output FILE", String, "File to output to (defaults to stdout)") do |f|
options[:format] = :json if f.include?('.json')
options[:output] = f
end
options[:format] ||= :list
opts.on("-f", "--format FORMAT", [:json, :grouped, :list], "Format to output data") do |f|
options[:format] = f
end
opts.on("-i", "--input FILE", String, "Will change format of a JSON file") do |f|
options[:input] = f
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end.parse!
chart = SeatingChart.new(options)
Signal.trap("INT") {
chart.eol
exit
}
# Trap `Kill`
Signal.trap("TERM") {
chart.eol
exit
}
chart.start
|
require 'rbbt'
require 'rbbt/workflow'
require 'rbbt/rest/common/locate'
require 'rbbt/rest/common/misc'
require 'rbbt/rest/common/render'
require 'rbbt/rest/common/forms'
require 'rbbt/rest/common/users'
require 'rbbt/rest/workflow/locate'
require 'rbbt/rest/workflow/render'
require 'rbbt/rest/workflow/jobs'
require 'sinatra/base'
require 'json'
module Sinatra
module RbbtRESTWorkflow
WORKFLOWS = []
def add_workflow_resource(workflow, priority_templates = false)
views_dir = workflow.respond_to?(:libdir)? workflow.libdir.www.views.find(:lib) : nil
if views_dir and views_dir.exists?
Log.debug "Registering views for #{ workflow }: #{ views_dir.find } - priority #{priority_templates}"
RbbtRESTMain.add_resource_path(views_dir, priority_templates)
end
end
def add_workflow(workflow, add_resource = false)
raise "Provided workflow is not of type Workflow" unless Workflow === workflow
RbbtRESTWorkflow::WORKFLOWS.push workflow unless RbbtRESTWorkflow::WORKFLOWS.include? workflow
Log.debug "Adding #{ workflow } to REST server"
add_workflow_resource(workflow, add_resource == :priority) if add_resource
workflow.documentation
if ENV["RBBT_WORKFLOW_EXPORT_ALL"] == "true"
workflow.export *workflow.tasks.keys
end
self.instance_eval workflow.libdir.lib['sinatra.rb'].read, workflow.libdir.lib['sinatra.rb'].find if workflow.respond_to?(:libdir) and File.exist? workflow.libdir.lib['sinatra.rb']
get "/#{workflow.to_s}" do
case @format
when :json
content_type "application/json"
@can_stream = ENV["RBBT_WORKFLOW_TASK_STREAM"] == 'true'
{:stream => workflow.stream_exports, :exec => workflow.exec_exports, :synchronous => workflow.synchronous_exports, :asynchronous => workflow.asynchronous_exports, :can_stream => !!@can_stream}.to_json
else
workflow_render('tasks', workflow, nil, @clean_params)
end
end
get "/#{workflow.to_s}/documentation" do
case @format
when :html
workflow_render('tasks', workflow)
when :json
content_type "application/json"
workflow.documentation.to_json
else
raise "Unsupported format specified: #{ @format }"
end
end
get "/#{workflow.to_s}/:task/info" do
task = consume_parameter(:task)
raise Workflow::TaskNotFoundException.new workflow, task unless workflow.tasks.include? task.to_sym
case @format
when :html
workflow_render('task_info', workflow, nil, :cache => false )
when :json
content_type "application/json"
workflow.task_info(task.to_sym).to_json
else
raise "Unsupported format specified: #{ @format }"
end
end
get "/#{workflow.to_s}/:task/dependencies" do
task = consume_parameter(:task)
raise Workflow::TaskNotFoundException.new workflow, task unless workflow.tasks.include? task.to_sym
case @format
when :html
workflow_render('task_dependencies', workflow)
when :json
content_type "application/json"
workflow.task_dependencies[task.to_sym].to_json
else
raise "Unsupported format specified: #{ @format }"
end
end
get "/#{workflow.to_s}/description" do
halt 200, workflow.documentation[:description] || ""
end
get "/#{workflow.to_s}/:task" do
task = consume_parameter(:task)
jobname = consume_parameter(:jobname)
raise Workflow::TaskNotFoundException.new workflow, task unless workflow.tasks.include? task.to_sym
execution_type = execution_type(workflow, task)
task_parameters = consume_task_parameters(workflow, task, params)
task_parameters[:jobname] = jobname
if complete_input_set(workflow, task, task_parameters) || @format != :html || jobname
issue_job(workflow, task, jobname, task_parameters)
else
workflow_render('form', workflow, task, task_parameters)
end
end
post "/#{workflow.to_s}/:task" do
task = consume_parameter(:task)
jobname = consume_parameter(:jobname)
raise Workflow::TaskNotFoundException.new workflow, task unless workflow.tasks.include? task.to_sym
execution_type = execution_type(workflow, task)
task_parameters = consume_task_parameters(workflow, task, params)
if params.include?('__input_file_bundle')
inputs = workflow.task_info(task)[:inputs]
input_types = workflow.task_info(task)[:input_types]
file = params['__input_file_bundle'][:tempfile].path
task_parameters = task_parameters.merge(Workflow.load_inputs(file, inputs, input_types))
end
issue_job(workflow, task, jobname, task_parameters)
end
get "/#{workflow.to_s}/:task/:job" do
task = consume_parameter(:task)
job = consume_parameter(:job)
raise Workflow::TaskNotFoundException.new workflow, task unless workflow.tasks.include? task.to_sym
execution_type = execution_type(workflow, task)
job = workflow.fast_load_id(File.join(task, job))
halt 404, "Job not found: #{job.path} (#{job.status})" if job.status == :noinfo and not job.done?
abort_job(workflow, job) and halt 200 if update.to_s == "abort"
clean_job(workflow, job) and halt 200 if update.to_s == "clean"
recursive_clean_job(workflow, job) and halt 200 if update.to_s == "recursive_clean"
begin
status = job.status
started = job.started?
waiting = job.waiting?
done = job.done?
error = job.error? || job.aborted?
dirty = (done || status == :done) && job.dirty?
started = started || done || error
done = false if dirty
if done
show_result job, workflow, task, params
else
if started || waiting
exec_type = execution_type(workflow, task)
case
when dirty
error_for job
when error
error_for job
when (exec_type == :asynchronous or exec_type == :async)
case @format.to_s
when 'json', 'raw', 'binary'
halt 202
else
@title = [[job.workflow.to_s, job.task_name] * "#", job.clean_name] * " "
wait_on job
end
else
job.join
raise RbbtRESTHelpers::Retry
end
else
halt 404, "Job not found: #{status}"
end
end
rescue RbbtRESTHelpers::Retry
retry
end
end
get "/#{workflow.to_s}/:task/:job/info" do
task = consume_parameter(:task)
job = consume_parameter(:job)
raise Workflow::TaskNotFoundException.new workflow, task unless workflow.tasks.include? task.to_sym
execution_type = execution_type(workflow, task)
job = workflow.load_id(File.join(task, job))
not_started = true unless job.started? or job.waiting? or job.error? or job.aborted?
dirty = true if (job.done? || job.status == :done) && job.dirty?
begin
check_step job unless job.done? or not_started
rescue Aborted
end
halt 404, "Job not found: #{job.path} (#{job.status})" if job.status == :noinfo and not job.done?
case @format
when :html
workflow_render('job_info', workflow, task, :job => job, :info => job.info)
when :input_bundle
task_info = workflow.task_info(task)
input_types = task_info[:input_types]
task_inputs = task_info[:inputs]
TmpFile.with_file do |basedir|
dir = File.join(basedir, 'inputs')
Step.save_job_inputs(job, dir)
filename = File.join(basedir, job.clean_name + '.input_bundle.tar.gz')
content_type "application/tar+gzip"
Misc.consume_stream(Misc.tarize(dir), false, filename)
send_file filename, :filename => File.basename(filename)
end
when :json
halt 200, {}.to_json if not_started
content_type "application/json"
info_json = {}
job.info.each do |k,v|
info_json[k] = case v.to_s
when "NaN"
"NaN"
when "Infinity"
"Infinity"
else
v
end
end
if dirty
info_json[:status] = :error
info_json[:messages] ||= []
info_json[:messages] << "Job dirty, please reissue."
end
halt 200, info_json.to_json
else
raise "Unsupported format specified: #{ @format }"
end
end
get "/#{workflow.to_s}/:task/:job/files" do
task = consume_parameter(:task)
job = consume_parameter(:job)
raise Workflow::TaskNotFoundException.new workflow, task unless workflow.tasks.include? task.to_sym
execution_type = execution_type(workflow, task)
job = workflow.fast_load_id(File.join(task, job))
case @format
when :html
workflow_render('job_files', workflow, task, :info => job.info, :job => job)
when :json
content_type "application/json"
job.files.to_json
else
raise "Unsupported format specified: #{ @format }"
end
end
get "/#{workflow.to_s}/:task/:job/file/*" do
task = consume_parameter(:task)
job = consume_parameter(:job)
filename = params[:splat].first
raise Workflow::TaskNotFoundException.new workflow, task unless workflow.tasks.include?(task.to_sym)
execution_type = execution_type(workflow, task)
job = workflow.fast_load_id(File.join(task, job))
path = job.file(filename)
#require 'mimemagic'
#mime = nil
#Open.open(path) do |io|
# begin
# mime = MimeMagic.by_path(io)
# if mime.nil?
# io.rewind
# mime = MimeMagic.by_magic(io)
# end
# if mime.nil?
# io.rewind
# mime = "text/tab-separated-values" if io.gets =~ /^#/ and io.gets.include? "\t"
# end
# rescue Exception
# Log.exception $!
# end
#end
mime = file_mimetype(path)
content_type mime if mime
send_file path
end
delete "/#{workflow.to_s}/:task/:job" do
task = consume_parameter(:task)
job = consume_parameter(:job)
job = workflow.fast_load_id(File.join(task, job))
raise Workflow::TaskNotFoundException.new workflow, task unless workflow.tasks.include? task.to_sym
clean_job(workflow, job)
end
end
def self.registered(base)
base.module_eval do
helpers WorkflowRESTHelpers
if ENV["RBBT_WORKFLOW_TASK_STREAM"] == 'true'
require 'rbbt/rest/workflow/stream_task'
Log.info "Preparing server for streaming workflow tasks"
use StreamWorkflowTask if not @can_stream
@can_stream = true
else
@can_stream = false
end
end
end
end
end
|
require 'podspec_editor/version'
require 'pathname'
require 'ostruct'
require 'json'
require 'cocoapods'
module PodspecEditor
class Helper
def self.openstruct_to_hash(object, hash = {})
return object unless object.is_a?(OpenStruct)
object.each_pair do |key, value|
hash[key] = if value.is_a?(OpenStruct)
openstruct_to_hash(value)
elsif value.is_a?(Array)
value.map { |v| openstruct_to_hash(v) }
else
value
end
end
hash
end
end
class Spec
attr_accessor :inner_spec
def initialize(json_content)
@inner_spec = JSON.parse(json_content, object_class: OpenStruct)
end
# read
def method_missing(method, *args, &block)
inner_spec.send(method, *args, &block)
end
end
class Editor
attr_accessor :origin_json_content
attr_accessor :spec
def self.default_json_spec_content(pod_name)
content = File.read(File.expand_path('TEMPLATE.podspec.json', __dir__))
content.gsub('POD_NAME', pod_name)
end
def spec_to_json(spec_path)
Pod::Specification.from_file(spec_path).to_pretty_json.chomp
end
def initialize(args)
json_path = args[:json_path]
if json_path
unless Pathname.new(json_path).exist?
raise ArgumentError, "invalid json path #{json_path}"
end
@origin_json_content = File.read(json_path).chomp
end
json_content = args[:json_content]
@origin_json_content = json_content if json_content
spec_path = args[:spec_path]
if spec_path
unless Pathname.new(spec_path).exist?
raise ArgumentError, "invalid spec path #{spec_path}"
end
@origin_json_content = spec_to_json spec_path
end
@spec = Spec.new @origin_json_content
end
def current_hash
Helper.openstruct_to_hash(@spec.inner_spec)
end
def current_json_content
JSON.pretty_generate(current_hash)
end
end
end
|
require "mkmf"
abort "errno.h is required" unless have_header("errno.h")
abort "launch.h is required" unless have_header("launch.h")
unless have_header("ruby/io.h") or have_header("rubyio.h")
abort "ruby/io.h or rubyio.h is required"
end
unless have_struct_member("rb_io_t", "fd", "ruby/io.h") or have_struct_member("rb_io_t", "f", %w[ruby.h rubyio.h])
abort "rb_io_t.fd or rb_io_t.f is required"
end
# $defs << "-HAVE_RUBY_19" if RUBY_VERSION >= "1.9"
# $CFLAGS << " -Werror"
create_makefile "launch"
|
require 'rails_helper'
RSpec.describe "Request: Favourite an artist API", type: :request do
context 'favourite an artist' do
before do
@data = '{ "data": { "type": "artists", "attributes": {
"external_urls": "https://open.spotify.com/artist/7dGJo4pcD2V6oG8kP0tJRR",
"genres": ["hiphop", "rap"],
"href": "https://api.spotify.com/v1/artists/7dGJo4pcD2V6oG8kP0tJRR",
"spotify_id": "7dGJo4pcD2V6oG8kP0tJRR",
"name": "Eminem" } } }'
end
it 'returns http status created' do
headers = { "CONTENT_TYPE" => "application/vnd.api+json" }
post '/api/v1/favourites', params: @data, headers: headers
expect(response).to have_http_status(:created)
expect(response.content_type).to eq 'application/vnd.api+json'
end
end
end
|
# Print all odd numbers from 1 to 99, inclusive. All numbers should be
# printed on separate lines.
(1..99).each do |n|
p n if n.odd?
end
range_array = (1..99)
odd_array = range_array.select { |n| n.odd? }
odd_array.each { |n| p n }
|
require 'bcrypt'
class PropertyOwner
attr_reader :id, :name, :username, :email, :password
def initialize(id:, name:, username:, email:, password:)
@id = id
@name = name
@username = username
@email = email
@password = password
end
def self.list
Database.query( "SELECT * FROM property_owner" ).map do | row |
PropertyOwner.new(id: row['id'], name: row['name'], username: row['username'], email: row['email'], password: row['password'])
end
end
def self.add(name:, username:, email:, password:)
if (Database.query("SELECT * FROM property_owner WHERE email = '#{email}'") || Database.query("SELECT * FROM property_owner WHERE username = '#{username}'")).any?
return
else
encrypted_password = BCrypt::Password.create(password)
result = Database.query( "INSERT INTO property_owner(name, username, email, password) VALUES('#{name}', '#{username}', '#{email}', '#{encrypted_password }') RETURNING id, name, username, email, password;")
PropertyOwner.new(id: result[0]['id'], name: result[0]['name'], username: result[0]['username'], email: result[0]['email'], password: result[0]['password'])
end
end
def self.login(email:, password:)
result = Database.query( "SELECT * FROM property_owner WHERE email = '#{email}'")
return unless result.any?
return unless BCrypt::Password.new(result[0]['password']) == password
PropertyOwner.new(id: result[0]['id'], name: result[0]['name'], username: result[0]['username'], email: result[0]['email'], password: result[0]['password'])
end
end
|
class SessionsController < ApplicationController
include SessionsHelper
def create
unless request.env['omniauth.auth'][:uid]
flash[:danger] = '連携に失敗しました'
redirect_to root_url
end
user_data = request.env['omniauth.auth']
user = User.find_by(uid: user_data[:uid])
file = File.dirname(__FILE__)
if user
log_in user
flash[:success] = 'ログインしました'
redirect_to root_url
else
new_user = User.new(
uid: user_data[:uid],
nickname: user_data[:info][:nickname],
name: user_data[:info][:name],
image: user_data[:info][:image],
)
if new_user.save
value = `python #{file}/concerns/hackason/first_main.py -i #{new_user.nickname}`
value = value.split(' ')
# first_main.pyにログを吐かせる
# Rails.application.config.another_logger.info("
# tweet_hash: #{value[0]}\n
# start_time: #{start_time}\n
# end_time: #{end_time}\n
# count: #{value[0]}
# ")
# TweetHashを作成
tweet_hash = TweetHash.create(tweet_hash: value[0], user_id: new_user.id, start_time: value[1], end_time: value[2], count: value[3])
if tweet_hash.save
# 変数tweet_hashが正しく保存されるとき、ログインする
log_in new_user
flash[:success] = 'ユーザー登録成功'
else
# 変数tweet_hashが正しく保存されないとき、ユーザーの情報を削除する
new_user.destroy
flash[:danger] = "予期せぬエラーが発生しました"
end
else
flash[:danger] = '予期せぬエラーが発生しました'
end
redirect_to root_url
end
end
def destroy
log_out if logged_in?
flash[:success] = 'ログアウトしました'
redirect_to root_url
end
end |
# frozen_string_literal: true
require 'terminal-table'
class Presenter
class << self
def call(repeat_config, command)
content = content(repeat_config, command)
Terminal::Table.new do
self.rows = content
self.style = { padding_left: 2, border_x: '-', border_i: '' }
end
end
private
def content(repeat_config, command)
[
['Minute:', present_array(repeat_config.fetch(:minutes))],
['Hour:', present_array(repeat_config.fetch(:hours))],
['Day', present_array(repeat_config.fetch(:days_of_month))],
['Month', present_array(repeat_config.fetch(:months))],
['Days of the week', present_array(repeat_config.fetch(:days_of_week))],
['Command:', command]
]
end
def present_array(value)
value.join(' ')
end
end
end
|
require 'test_helper'
class PostsControllerTest < ActionController::TestCase
def setup
login! 1
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:posts)
end
test "should create post" do
assert_difference('Post.count') do
post :create, :post => { }
end
assert_response 302
end
test "should show post" do
get :show, :id => posts(:one).to_param
assert_response :success
end
end
|
require 'spec_helper'
describe "Course category pages" do
describe "List all category pages" do
it"should have h1 'all categories'" do
visit "/course_category/list_all"
page.should have_selector('h1', :text=> 'All Categories')
end
end
end
|
class GridWithCustomFilter < Netzke::Basepack::Grid
def configure(c)
super
c.model = "Author"
c.columns = [
:first_name,
:last_name,
{
name: :name,
filter_with: ->(rel, value, op) {rel.where("first_name like ? or last_name like ?", "%#{value}%", "%#{value}%")},
sorting_scope: :sorted_by_name
}
]
end
end
|
class Site < ActiveRecord::Base
belongs_to :trial, counter_cache: true
MAXIMUM_FACILITY_LENGTH = 40
geocoded_by :address
after_validation(
:geocode,
if: :should_be_geocoded?,
)
def self.without_coordinates
where("latitude IS NULL or longitude IS NULL")
end
def facility_address
"#{facility} #{address}".gsub("&", "and")
end
def address
[city, state, country, zip_code].select(&:present?).join(", ")
end
def in_united_states?
country == "United States"
end
def display_location
locations_to_include = [city, state]
unless facility_too_long?
locations_to_include.unshift(facility)
end
unless in_united_states?
locations_to_include << country
end
locations_to_include.select(&:present?).join(", ")
end
def should_be_geocoded?
no_coordinates? && address.present? && geocoding_enabled?
end
def no_coordinates?
latitude.nil? && longitude.nil?
end
def geocoding_enabled?
ENV["DISABLE_SITE_GEOCODING"] != "true"
end
private
def facility_too_long?
facility.length > MAXIMUM_FACILITY_LENGTH
end
end
|
require 'faster_csv'
class DataExporter
include ApplicationHelper
def self.automart_photo_url(user)
return nil unless user.primary_photo
photo = user.primary_photo
url = File.join("http://www.viewpoints.com", photo.get_thumbnail_url)
photo_html = "<a title=\"#{user.screen_name}\" "
photo_html += "style=\"background: transparent url(#{url}) no-repeat #{convert_position(photo.horizontal_position)} #{convert_position(photo.vertical_position)};display:block;height:98px;max-height:100px;width:120px;\""
photo_html += "href=\"#{url} />\""
#<<-EOS
# <a title="#{user.screen_name}" style="background: transparent url(#{url}) no-repeat #{convert_position(photo.horizontal_position)} #{convert_position(photo.vertical_position)};display:block;height:98px;max-height:100px;width:120px;" href="#{url}" />"
#EOS
end
# Stole this from app helper. Do it better next time.
def self.convert_position(position)
return position if %w(top center bottom left right).include? position
"#{position.to_f.ceil}px"
end
def self.generate_automart_export
file = File.join(RAILS_ROOT,'tmp',"automart-#{Time.now.strftime('%Y%m%d')}.txt")
FasterCSV.open(file, "w", :col_sep => "\t") do |csv|
# Header row
csv << ["Publication Date", "Car Make", "Car Model", "Car Year", "Sound Bite", "I AM graphic URL",
"I AM tags", "Star Rating", "Star Rating URL", "Author Photo URL", "Author Screen Name",
"Helpful vote count", "Review Link Text", "Review URL", "Attribution Text", "Attribution URL"]
Category.find(2643).active_reviews.each do |review|
tag_list = review.i_ams_list.first(5) * ", "
# Validations
next unless review.cobrand.short_name == "viewpoints"
next if review.content.blank?
next if tag_list.blank?
next if review.product.answer(1345) == nil
next if review.product.answer(1346) == nil
next if review.product.answer(1347) == nil
product = review.product
csv << [
# Publication Date
review.published_at,
# Car Make
review.product.answer(1345),
# Car Model
review.product.answer(1346),
# Car Year
review.product.answer(1347),
# Headline/Sound bite
review.sound_bite,
# I AM graphic URL
"http://www.viewpoints.com/images/i_am_51_am.png",
# I AM tags in comma separated list
tag_list,
# Star Rating (1-5)
review.stars,
# Star Rating URL (for image)
"http://www.viewpoints.com/images/r#{review.stars}.gif",
# Author Photo URL (for thumbnail)
automart_photo_url(review.user),
# Author Screen Name & Location
"#{review.user.screen_name}",
# Helpful vote count
review.helpful_count,
# Review link text
"Read full car review - #{review.product.answer(1347)} #{review.product.answer(1345)} #{review.product.answer(1346)}",
# Click-through URL to read the full review
File.join("http://www.viewpoints.com", review.to_param),
# Viewpoints attribution text
"Reviews by",
# Viewpoints attribution image URL
"http://www.viewpoints.com/images/vp88x31.gif"
]
end
end
end
end
|
require 'spec_helper'
describe Spree::MailToFriend do
it { should validate_presence_of :subject }
it { should validate_presence_of :sender_name }
it { should validate_presence_of :recipient_name }
context 'Validate required fields' do
it 'verify test data hase been generated' do
expect(build(:mail)).to be_valid
end
end
context 'invalid recipents should be removed' do
let(:mail) do
build(:mail,
invalid_recipients: 'invaild',
recipient_email: 'ryan@spreecommerce.com, xyx')
end
it 'check email format with REGEX' do
expect(mail).not_to be_valid
end
it 'persist function should return false' do
mail_to_friend = Spree::MailToFriend.new
expect(mail_to_friend.persisted?).to be_false
end
end
end |
object @form => :data
attributes :user
node(:errors) { @form.errors.full_messages }
|
class EnqueueTweetFetchJob::JobRunner
def execute!
with_log do
Event.featured.each do |event|
TweetFetchJob.perform_later(event)
end
end
end
private
def logger
Rails.logger
end
def with_log
begin
logger.info("Enqueue Tweet Fetch Job")
yield
logger.info("Enqueued Tweet Fetch Job")
rescue => e
logger.fatal(e.full_message)
logger.fatal(e.backtrace.join("\n"))
logger.info("Faild to enqueue Tweet Fetch Job")
raise
end
end
end
|
require 'spec_helper'
require 'shared/connection_examples'
describe 'Zookeeper chrooted' do
let(:path) { "/_zkchroottest_" }
let(:data) { "underpants" }
let(:chroot_path) { '/slyphon-zookeeper-chroot' }
let(:connection_string) { "#{Zookeeper.default_cnx_str}#{chroot_path}" }
before do
@zk = Zookeeper.new(connection_string)
end
after do
@zk and @zk.close
end
def zk
@zk
end
describe 'non-existent' do
describe 'with existing parent' do
let(:chroot_path) { '/one-level' }
describe 'create' do
before do
with_open_zk { |z| rm_rf(z, chroot_path) }
end
after do
with_open_zk { |z| rm_rf(z, chroot_path) }
end
it %[should successfully create the path] do
rv = zk.create(:path => '/', :data => '')
rv[:rc].should be_zero
rv[:path].should == ''
end
end
end
describe 'with missing parent' do
let(:chroot_path) { '/deeply/nested/path' }
describe 'create' do
before do
with_open_zk do |z|
rm_rf(z, chroot_path)
end
end
it %[should return ZNONODE] do
rv = zk.create(:path => '/', :data => '')
rv[:rc].should_not be_zero
rv[:rc].should == Zookeeper::Exceptions::ZNONODE
end
end
end
end
describe do
before :all do
logger.warn "running before :all"
with_open_zk do |z|
z.create(:path => chroot_path, :data => '')
end
end
after :all do
with_open_zk do |z|
rm_rf(z, chroot_path)
end
end
it_should_behave_like "connection"
end
end
|
# frozen_string_literal: true
FactoryBot.define do
factory :kiosk do
name { 'circ' }
map_default_floor_number { 2 }
association :kiosk_layout, factory: :kiosk_layout
end
end
|
# genre: The genre(s) that a song "belongs" to.
# A hierarchy; each genre can have 0+ parents (e.g. Latin, Dance -> Latin Dance).
class CreateGenres < ActiveRecord::Migration
def change
create_table :genres do |t|
t.string :name
t.string :slug
t.string :parent_slugs, array: true
t.timestamps null: false
end
end
end
# source: Used to identify songs that came from movies, TV shows, &c.
class CreateSources < ActiveRecord::Migration
def change
create_table :sources do |t|
t.string :name
t.string :type_slug # 'movie'|'tv'
t.string :slug
t.string :tag_slugs, array: true
t.timestamps null: false
end
end
end
# origin: The geographic origin of the artist.
# Hierarchical.
class CreateOrigins < ActiveRecord::Migration
def change
create_table :origins do |t|
t.string :name
t.string :type_slug # 'movie'|'tv'
t.string :slug
t.string :tag_slugs, array: true
t.timestamps null: false
end
end
end
# Tags add metadata to songs and artists. They are used to build playlists.
class CreateTags < ActiveRecord::Migration
def change
create_table :tags do |t|
t.string :title
t.string :slug
t.string :description
t.timestamps null: false
end
end
end
class CreateArtists < ActiveRecord::Migration
def change
create_table :artists do |t|
t.string :name
t.string :type
t.string :genre_slugs, array: true
t.string :origin_slug
t.string :birth_era_slug
t.string :death_era_slug
t.string :tags, array: true
t.string :member_slugs, array: true # for groups, slugs of members
t.boolean :complete
t.timestamps null: false
end
end
end
class CreateSongs < ActiveRecord::Migration
def change
create_table :songs do |t|
t.string :title
t.integer :source_id
t.string :debut_era_slug
t.string :origin_slug
t.string :genre_slugs, array: true
t.float :ranks, array: true
t.float :score
t.timestamps null: false
end
end
end
# Associations of artists to songs.
# See https://github.com/jbnv/SongChartsRails/wiki/Song-Artists.
class CreateSongArtists < ActiveRecord::Migration
def change
create_table :song_artists do |t|
t.integer :song_id
t.integer :artist_id
t.string :role_slug # "primary" (default) | "featured" | "backup" | "member" | "writer" | "producer"
t.timestamps null: false
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.