text stringlengths 10 2.61M |
|---|
module Alf
module Operator
#
# Specialization of Operator for operators that are shortcuts for longer
# expressions.
#
module Shortcut
include Operator
#
# Sets the operator input
#
def pipe(input, env = environment)
self.environment = env
self.datasets = input
self
end
protected
# (see Operator#_each)
def _each
longexpr.each(&Proc.new)
end
#
# Compiles the longer expression and returns it.
#
# @return (Iterator) the compiled longer expression, typically another
# Operator instance
#
def longexpr
end
undef :longexpr
#
# This is an helper ala Lispy#chain for implementing (#longexpr).
#
# @param [Array] elements a list of Iterator-able
# @return [Operator] the first element of the list, but piped with the
# next one, and so on.
#
def chain(*elements)
elements = elements.reverse
elements[1..-1].inject(elements.first) do |c, elm|
elm.pipe(c, environment)
elm
end
end
end # module Shortcut
end # module Operator
end # module Alf
|
class ItemsController < ApplicationController
before_filter :load_standup
def create
@standup = Standup.find_by_id(params[:standup_id])
@item = @standup.items.build(params[:item])
if @item.save
redirect_to @item.post ? edit_post_path(@item.post) : standup_path(@standup)
else
render 'items/new'
end
end
def new
@standup = Standup.find_by_id(params[:standup_id])
options = (params[:item] || {}).merge(post_id: params[:post_id])
@item = Item.new(options)
render_custom_item_template @item
end
def index
@standup = Standup.find_by_id(params[:standup_id])
@items = @standup.items.orphans
end
def destroy
@item = Item.find(params[:id])
@item.destroy
redirect_to @item.post ? edit_post_path(@item.post) : @standup
end
def edit
@item = Item.find(params[:id])
render_custom_item_template @item
end
def update
@item = Item.find(params[:id])
@item.update_attributes(params[:item])
if @item.save
redirect_to @item.post ? edit_post_path(@item.post) : @standup
else
render_custom_item_template @item
end
end
def presentation
@items = Item.orphans
render layout: 'deck'
end
private
def render_custom_item_template(item)
if item.possible_template_name && template_exists?(item.possible_template_name)
render item.possible_template_name
else
render "items/new"
end
end
def load_standup
if params[:standup_id].present?
@standup = Standup.find(params[:standup_id])
else
@standup = Item.find(params[:id]).standup
end
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
let(:user){ User.create!(name: "Testing", email: "paul@testing.com") }
it "creates" do
expect(user.persisted?).to eq true
end
end
|
Rails.application.routes.draw do
resources :contacts
devise_for :users
root to: 'home#index'
resources :umims do
member do
post :fullcontact_information_received
end
end
end
|
class Admissions::FoldersController < Admissions::AdmissionsController
before_filter :set_folder, only: [:edit, :update]
load_resource find_by: :permalink
authorize_resource
def index
respond_to do |format|
format.html {
order = params[:order]
dir = (params[:dir].blank? || params[:dir] == "asc") ? "asc" : "desc"
@role_id = params[:role_id]
@folders = Folder.paginate(page: params[:page],
per_page: @per_page).includes(:user)
unless order.blank?
@folders = @folders.order("#{order} #{dir}")
else
@folders = @folders.ordered
end
unless @role_id.blank?
@folders = @folders.joins(:user).where("users.role_id = ? ", @role_id).paginate(page: params[:page], per_page: @per_page)
end
}
format.csv {
send_data Folder.to_csv,
type: 'text/csv; charset=iso-8859-1; header=present',
disposition: "attachment; filename=folders-#{DateTime.now}.csv"
}
end
end
def edit
end
def confirm_destroy
end
def generate_slug_from_name name=''
value = name.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n, '').to_s
value.gsub!(/[']+/, '')
value.gsub!(/\W+/, ' ')
value.strip!
value.downcase!
value.gsub!(' ', '-')
value
end
def update
# generate a slug from the title
# if one hasn't been set.
# logger.warn params.inspect
f = params[:folder]
if f['is_featured'] == '1'
if f['slug'].blank?
# if no slug, generate from title.
f['slug'] = generate_slug_from_name Folder.find(@folder.id).name
else
# This 'validates' - or rather slugifies, the slug.
f['slug'] = generate_slug_from_name f['slug']
end
end
if @folder.update_attributes(f)
if params[:edit_location] == 'recommendation'
redirect_to admin_folder_recommendations_url
end
# if !params[:recommendation_id].blank?
# FolderRecommendation.destroy(params[:recommendation_id])
# end
end
end
private
def set_folder
@folder = Folder.find_by_id!(params[:id])
end
end
|
class Kaggle::MessagesController < ApplicationController
wrap_parameters :kaggle_message, :include => ['reply_to', 'html_body', 'subject', 'recipient_ids', 'workspace_id']
def create
kaggleParams = prepared_parameters(params[:kaggle_message])
Kaggle::API.send_message(kaggleParams)
render :json => {}, :status => 200
rescue Kaggle::API::MessageFailed => e
present_errors({:fields => {:kaggle =>
{ :GENERIC => {:message => e.message}}}},
{:status => :unprocessable_entity})
end
private
def prepared_parameters(input_params)
params = {}
kaggle_config = Chorus::Application.config.chorus['kaggle']
params["apiKey"] = kaggle_config['api_key'] if kaggle_config
params["subject"] = input_params["subject"]
params["userId"] = input_params["recipient_ids"]
params["htmlBody"] = input_params["html_body"]
params["replyTo"] = input_params["reply_to"]
params
end
end |
require 'formula'
class XercesC < Formula
homepage 'http://xerces.apache.org/xerces-c/'
url 'http://www.apache.org/dyn/closer.cgi?path=xerces/c/3/sources/xerces-c-3.1.1.tar.gz'
sha1 '177ec838c5119df57ec77eddec9a29f7e754c8b2'
bottle do
cellar :any
revision 1
sha1 "c967a33a63188465037bad103417e30ae4bcbed8" => :yosemite
sha1 "d6312f24c9eebe9dadf87785c162c3750ec7c88d" => :mavericks
sha1 "233d55c81c9d9f97b5f083426cc1c9dbda2bd032" => :mountain_lion
end
option :universal
def install
ENV.universal_binary if build.universal?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
# Remove a sample program that conflicts with libmemcached
# on case-insensitive file systems
(bin/"MemParse").unlink
end
end
|
# class Animal
# def speak
# "Hello!"
# end
# end
# class GoodDog < Animal
# attr_accessor :name
# def initialize(n)
# self.name = n
# end
# def speak
# "#{self.name} says arf!"
# end
# end
# class Cat < Animal
# end
# sparky = GoodDog.new("Sparky")
# paws = Cat.new
# puts sparky.speak
# puts paws.speak
# ------------------------------------
# class Animal
# def speak
# "Hello!"
# end
# end
# class GoodDog < Animal
# def speak
# super + " from GoodDog class"
# end
# end
# sparky = GoodDog.new
# puts sparky.speak
# ------------------------------------
# class Animal
# attr_accessor :name
# def initialize(name)
# @name = name
# end
# end
# class GoodDog < Animal
# def initialize(color)
# super
# @color = color
# end
# end
# class BadDog < Animal
# def initialize(age, name)
# super(name)
# @age = age
# end
# end
# bruno = GoodDog.new("brown")
# p bruno
# p BadDog.new(2, "bear")
# ------------------------------------
# module Swimmable
# def swim
# "I'm swimming!"
# end
# end
# class Animal; end
# class Fish < Animal
# include Swimmable
# end
# class Mammal < Animal
# end
# class Cat < Mammal
# end
# class Dog < Mammal
# include Swimmable
# end
# sparky = Dog.new
# neemo = Fish.new
# paws = Cat.new
# p sparky.swim
# p neemo.swim
# p paws.swim
# ------------------------------------
# module Walkable
# def walk
# "I'm walking."
# end
# end
# module Swimmable
# def swim
# "I'm swimming."
# end
# end
# module Climbable
# def climb
# "I'm climbing."
# end
# end
# class Animal
# include Walkable
# def speak
# "I'm an animal, and I speak!"
# end
# end
# class GoodDog < Animal
# include Swimmable
# include Climbable
# end
# puts "---GoodDog method lookup"
# puts GoodDog.ancestors
# ------------------------------------
# module Mammal
# class Dog
# def speak(sound)
# p "#{sound}"
# end
# end
# class Cat
# def say_name(name)
# p "#{name}"
# end
# end
# def self.some_out_of_place_method(num)
# num * 2
# end
# end
# buddy = Mammal::Dog.new
# kitty = Mammal::Cat.new
# buddy.speak('Arf!')
# kitty.say_name('kitty')
# p value = Mammal.some_out_of_place_method(4)
# ------------------------------------
# class GoodDog
# DOG_YEARS = 7
# attr_accessor :name, :age
# def initialize(n,a)
# self.name = n
# self.age = a
# end
# def public_disclosure
# "#{self.name} in human years is #{human_years}"
# end
# private
# def human_years
# age * DOG_YEARS
# end
# end
# sparky = GoodDog.new("Sparky", 4)
# p sparky.public_disclosure
# ------------------------------------
# class Animal
# def a_public_method
# "Will this work? " + self.a_protected_method
# end
# protected
# def a_protected_method
# "Yes, I'm protected"
# end
# end
# fido = Animal.new
# p fido.a_public_method
# p fido.a_protected_method
# ------------------------------------
class Parent
def say_hi
p "Hi, from Parent."
end
end
class Child < Parent
def say_hi
p "Hi, from Child."
end
def send
p "send from Child..."
end
def instance_of?
p "I am a fake instance"
end
end
heir = Child.new
heir.instance_of? Child
|
require 'spec_helper_acceptance'
describe 'openstacklib mysql' do
context 'default parameters' do
it 'should work with no errors' do
pp= <<-EOS
Exec { logoutput => 'on_failure' }
class { 'mysql::server': }
$charset = $::operatingsystem ? {
'Ubuntu' => 'utf8mb3',
default => 'utf8',
}
openstacklib::db::mysql { 'ci':
charset => $charset,
collate => "${charset}_general_ci",
password_hash => mysql::password('keystone'),
allowed_hosts => '127.0.0.1',
}
EOS
# Run it twice and test for idempotency
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :catch_changes => true)
end
describe port(3306) do
it { is_expected.to be_listening.with('tcp') }
end
it 'should have ci database' do
command("mysql -e 'show databases;' | grep -q ci") do |r|
expect(r.exit_code).to eq 0
end
end
end
end
|
class SessionsController < ApplicationController
include ResetCart
def new
@user = User.new
end
def logout
session.clear
redirect_to root_path
end
def create
user = User.find_by(username: params[:session][:username])
if !user
return try_login_again
end
if user.admin? && user.authenticate(params[:session][:password])
flash[:welcomeadmin] = "Welcome, #{user.username.capitalize}!"
redirect_to '/admin/inventory'
session[:user_id] = user.id
elsif user && user.authenticate(params[:session][:password])
session[:user_id] = user.id
redirect_to :back
else
try_login_again
end
end
private
def user_params
params.require(:session).permit(:username, :password)
end
def try_login_again
@user = User.create(user_params.merge({full_name: "failed_login", email: "failed@example.com"}))
@user.errors.messages.each do |field, msg|
flash[field] = "#{field.to_s.humanize} #{msg[0]}"
end
redirect_to :back
end
end
|
require 'rails_helper'
describe Task do
describe 'class methods' do
before do
@user = create(:user)
@new_task = create(:task, user: @user, created_at: Timecop.freeze(Time.now))
@old_task = create(:task, user: @user, created_at: 7.days.ago)
@completed_task = create(:task, user: @user, completed: true)
end
describe '#expiration_date' do
it 'for the maximum' do
expect(@new_task.expiration_date).to eq(Time.now + 7.days)
end
it 'for the minimum' do
expect(@old_task.expiration_date).to eq(Time.now)
end
end
describe '#days_remaining' do
it 'for the maximum' do
expect(@new_task.days_remaining).to eq(7)
end
it 'for the minimum' do
expect(@old_task.days_remaining).to eq(0)
end
end
describe '#hide_completed scope' do
it 'does not include completed tasks' do
expect(Task.hide_completed).not_to include(@completed_task)
end
end
describe '.delete_tasks' do
it 'deletes old and completed tasks' do
Task.delete_tasks
expect(Task.count).to eq(1)
end
end
describe 'ActiveModel validations' do
it { expect(@new_task).to validate_presence_of(:description).with_message(/can't be blank/) }
it { ensure_inclusion_of(:completed).in_array([true, false]) }
end
describe 'ActiveRecord associations' do
it { expect(@new_task).to belong_to(:user) }
it { expect(@new_task).to have_db_index(:user_id) }
end
end
end
|
class Links::Misc::AbstractPlayerUsage < Links::Base
def site_name
"Hockey Abstract"
end
def description
"Player Usage Charts"
end
def url
"http://www.hockeyabstract.com/playerusagecharts"
end
def group
2
end
def position
0
end
end
|
# encoding: utf-8
# copyright: 2016, you
# license: All rights reserved
# date: 2016-09-16
# description: The Microsoft Internet Explorer 11 Security Technical Implementation Guide (STIG) is published as a tool to improve the security of Department of Defense (DoD) information systems. Comments or proposed revisions to this document should be sent via e-mail to the following address: disa.stig_spt@mail.mil
# impacts
title 'V-46615 - Internet Explorer must be set to disallow users to add/delete sites.'
control 'V-46615' do
impact 0.5
title 'Internet Explorer must be set to disallow users to add/delete sites.'
desc 'This setting prevents users from adding sites to various security zones. Users should not be able to add sites to different zones, as this could allow them to bypass security controls of the system. If you do not configure this policy setting, users will be able to add or remove sites from the Trusted Sites and Restricted Sites zones at will and change settings in the Local Intranet zone. This configuration could allow sites that host malicious mobile code to be added to these zones, and users could execute the code.'
tag 'stig', 'V-46615'
tag severity: 'medium'
tag checkid: 'C-49781r2_chk'
tag fixid: 'F-50385r1_fix'
tag version: 'DTBI318-IE11'
tag ruleid: 'SV-59479r1_rule'
tag fixtext: 'Set the policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer Security Zones: Do not allow users to add/delete sites to Enabled.'
tag checktext: 'The policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer Security Zones: Do not allow users to add/delete sites must be Enabled. Procedure: Use the Windows Registry Editor to navigate to the following key: HKLM\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings Criteria: If the value "Security_zones_map_edit" is REG_DWORD = 1, this is not a finding.'
# START_DESCRIBE V-46615
describe registry_key({
hive: 'HKLM',
key: 'Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings',
}) do
its('Security_zones_map_edit') { should eq 1 }
end
# STOP_DESCRIBE V-46615
end
|
# Adding columns "day" and "season" to shows database
class AddDataAttrToShows < ActiveRecord::Migration[4.2]
def change
add_column(:shows, :day, :string)
add_column(:shows, :season, :string)
end
end |
module AWS
module S3
class InvalidAccessKeyId < ResponseError; end
class NoSuchBucket < ResponseError; end
end
end
|
class Bitmap
def initialize(width, length)
@width = width
@length = length
@DEFAULT_COLOR = 'O'
@array = Array.new(length) { Array.new(width, @DEFAULT_COLOR) }
end
def length
@length
end
def width
@width
end
def valid?
(1..250).include?(@width) && (1..250).include?(@length)
end
def render
@array.each do |arr|
puts arr.join
end
end
def color_horizontal_segment(**args)
set_vars(args)
check_in_bounds(cols: [@col1, @col2], row: @row)
row = @array[@row]
row[@col1..@col2] = row[@col1..@col2].map {|char| char = @color}
end
def color_vertical_segment(**args)
set_vars(args)
check_in_bounds(col: @col, rows: [@row1, @row2])
@array.slice(@row1, @row2).each do |arr|
arr[@col] = @color
end
end
def clear_grid
@array.each do |arr|
arr.map! {|c| c = @DEFAULT_COLOR}
end
end
def color(**args)
set_vars(args)
check_in_bounds(col: @col, row: @row)
@array[@row][@col] = @color
end
private
def set_vars(args)
@color = args[:color]
args[:coords].each do |k, v|
instance_variable_set "@#{k}", v - 1
end
end
def check_in_bounds(**args)
args.each do |k, v|
case k
when :col
validate_coord(v, @width, :column)
when :row
validate_coord(v, @length, :row)
when :cols
args[:cols].each do |col|
validate_coord(col, @width, :column)
end
when :rows
args[:rows].each do |row|
validate_coord(row, @length, :row)
end
end
end
end
def validate_coord(coord, dimension, type)
if !(1..dimension).include?(coord + 1)
abort "#{type.to_s.capitalize} coordinates must be between 1 and #{dimension}"
end
end
end |
describe ContextModuleProgression do
include_context 'stubbed_network'
let(:user) { User.create }
let(:course) { Course.create }
let!(:context_module) { ContextModule.create!(context: course) }
let(:context_module_progression) { ContextModuleProgression.create(context_module: context_module, user: user) }
let!(:enrollment) { Enrollment.create(user: user, course: course, type: 'StudentEnrollment') }
before do
allow(SettingsService).to receive(:get_enrollment_settings).and_return({"sequence_control"=>false})
end
describe "#prerequisites_satisfied?" do
it 'returns true when sequence control is off' do
expect(context_module_progression.prerequisites_satisfied?).to be(true)
end
end
describe "#locked?" do
it 'returns false when sequence control is off' do
expect(context_module_progression.locked?).to be(false)
end
end
context "Pipeline" do
context "User is not enrolled as a student" do
let!(:enrollment) { Enrollment.create(user: user, course: course, type: 'TeacherEnrollment') }
it 'does not publish course progress to the pipeline' do
expect(PipelineService::Nouns::CourseProgress).to_not receive(:new)
ContextModuleProgression.create(user: user, context_module: context_module)
end
end
it 'publishes course progress to the pipeline' do
expect(PipelineService).to receive(:publish)
ContextModuleProgression.create(user: user, context_module: context_module)
end
it 'builds a course progress noun' do
cmp = ContextModuleProgression.create(user: user, context_module: context_module)
expect(PipelineService::Nouns::CourseProgress).to receive(:new).with(cmp)
cmp.update(user: user)
end
end
end
|
# == Schema Information
#
# Table name: lprofiles
#
# id :integer not null, primary key
# firstname :string(255)
# lastname :string(255)
# phone :integer
# landlord_id :integer
# created_at :datetime
# updated_at :datetime
# customerid :string(255)
#
class Lprofile < ActiveRecord::Base
belongs_to :landlord
has_many :landlordccs
end
|
class RemoveVisitedCountFromShortUrls < ActiveRecord::Migration
def change
remove_column :short_urls, :visits_count
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)
User.create!(name: 'Zack', email: 'zlivingston42@hotmail.com', password: 'testp', password_confirmation: 'testp', admin: true, activated: true, activated_at: Time.zone.now)
99.times do |n|
User.create(name: "Zack#{n}", email: "ex#{n}@example.com", password: 'testp', password_confirmation: 'testp', activated: true, activated_at: Time.zone.now)
end
users = User.order(:created_at).take(6)
50.times do
users.each {|user| user.microposts.create(content: Faker::Lorem.sentence(5))}
end |
class Economy::InvoiceMailer < ActionMailer::Base
def funkis_invoice(invoice)
setup_email(invoice)
@subject << 'Faktura / Invoice'
@from = 'SOF2011 <sof-controller@lintek.liu.se>'
if invoice.booking.cash
template "funkis_invoice_cash"
else
@content_type = 'text/html'
template "funkis_invoice"
end
end
def funkis_invoice_reminder(invoice)
end
def funkis_invoice_expired(invoice)
setup_email(invoice)
@subject << "Obetald faktura: #{invoice.invoice_number} / Unpaid invoice: #{invoice.invoice_number}"
end
def ticket_invoice_expired(invoice)
setup_ticket_email(invoice)
@subject << "Obetald faktura: #{invoice.invoice_number} / Unpaid invoice: #{invoice.invoice_number}"
@content_type = 'text/html'
end
def ticket_invoice(invoice)
setup_ticket_email(invoice)
@subject << "Faktura: #{invoice.invoice_number} / Invoice: #{invoice.invoice_number}"
if invoice.booking.cash
template "ticket_invoice_cash"
else
@content_type = 'text/html'
template "ticket_invoice"
end
end
def ticket_invoice_changed(invoice)
setup_ticket_email(invoice)
@subject << "Faktura ändrad / Invoice changed"
@remaining = @amount - @paid
end
def ticket_confirmation(invoice)
setup_ticket_email(invoice)
@subject << "Betalningsbekräftelse: #{invoice.invoice_number} / Payment confirmation: #{invoice.invoice_number}"
end
def ticket_underpaid(invoice)
setup_ticket_email(invoice)
@content_type = 'text/html'
@subject << "Underbetald faktura: #{invoice.invoice_number} / Underpaid invoice: #{invoice.invoice_number}"
@remaining = @amount - @paid
end
def ticket_overpaid(invoice)
setup_ticket_email(invoice)
@content_type = 'text/html'
@subject << "Överbetald faktura: #{invoice.invoice_number} / Overpaid invoice: #{invoice.invoice_number}"
@bcc = 'sof-controller@lintek.liu.se'
@remaining = @paid - @amount
end
def ticket_handout_information(invoice)
setup_ticket_email(invoice)
@subject << "Uppdaterad information om utlämning av armband / Updated information about ticket-bracelet handout"
end
def ticket_correction(invoice)
setup_ticket_email(invoice)
@subject << "Faktura rättelse / Invoice correction"
end
protected
def setup_ticket_email(invoice)
@recipients = "#{invoice.user.email}"
@from = 'SOF2011 <sof-controller@lintek.liu.se>'
@subject = "[#{APP_CONFIG[:mail_subject]}] "
@site_url = APP_CONFIG[:site_url]
@sent_on = Time.now
@name = invoice.user.name
@tickets = invoice.booking.tickets
@ticket_names_sv = []
@tickets.each do |ticket|
@ticket_names_sv << ticket.ticket_type.name_sv
end
@ticket_names_sv_flat = @ticket_names_sv.uniq
@ticket_names_en = []
@tickets.each do |ticket|
@ticket_names_en << ticket.ticket_type.name_en
end
@ticket_names_en_flat = @ticket_names_en.uniq
@ticket_numbers = []
@ticket_names_sv_flat.each do |name_flat|
@ticket_numbers << @ticket_names_sv.select{ |name| name == name_flat }.length
end
@amount = invoice.amount
@paid = invoice.paid_sum
@ocr = invoice.ocr
@last_payment_day = invoice.last_payment_day
@invoice_number = invoice.invoice_number
@ticket_type = @tickets.first.ticket_type
end
def setup_email(invoice)
account = invoice.user.account
@recipients = "#{account.email}"
@from = 'SOF2011 <sof-controller@lintek.liu.se>'
@subject = "[#{APP_CONFIG[:mail_subject]}] "
@site_url = APP_CONFIG[:site_url]
@sent_on = Time.now
@body[:account] = account
@body[:deposition_price] = 400
@body[:ticket_price] = invoice.amount - 400
@body[:amount] = invoice.amount
@body[:ocr] = invoice.ocr
@body[:expire_on_in_swedish] = invoice.expire_on
@body[:expire_on_in_english] = invoice.expire_on
@body[:role_name_in_swedish] = invoice.user.job.team.role.name_sv
@body[:role_name_in_english] = invoice.user.job.team.role.name_en
@body[:name] = invoice.user.name
end
end
|
class AddBirthYearToSurveytest < ActiveRecord::Migration
def change
add_column :surveytests, :birth_year, :integer
end
end
|
require 'spec_helper'
describe "kassociations/edit.html.erb" do
before(:each) do
@kassociation = assign(:kassociation, stub_model(Kassociation,
:typus => "MyString",
:description => "MyText",
:source => nil,
:target => nil
))
end
it "renders the edit kassociation form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form", :action => kassociations_path(@kassociation), :method => "post" do
assert_select "input#kassociation_typus", :name => "kassociation[typus]"
assert_select "textarea#kassociation_description", :name => "kassociation[description]"
assert_select "input#kassociation_source", :name => "kassociation[source]"
assert_select "input#kassociation_target", :name => "kassociation[target]"
end
end
end
|
# frozen_string_literal: true
class CreateOrderItems < ActiveRecord::Migration[5.2]
def change
create_table :order_items do |table|
table.belongs_to :order, index: true
table.integer :price
table.integer :count
table.belongs_to :product_item, index: true
table.timestamps
end
end
end
|
require_relative "ruby_api/version"
require_relative "marvel/api"
module RubyApi
# Collect all the Marvel characters using this method
def self.characters(offset:0, limit:5)
marvel = ::Marvel::API.new('8b2c5b7810c6ffd0ad183b2df0df0c54', YOUR_PRIVATE_KEY)
marvel.characters(offset, limit)
end
# Get details about a character using character id received from above method
def self.get_character(cid)
marvel = ::Marvel::API.new('8b2c5b7810c6ffd0ad183b2df0df0c54', YOUR_PRIVATE_KEY)
marvel.get_character(cid)
end
end
|
require 'test_helper'
require 'simple_graph'
require 'bfs'
class BFSTest < Minitest::Test
def setup
@g = SimpleGraph.new :allowed_classes => String
@g.add_edge "Hello", "World"
@g.add_edge "Hello", "Beautiful"
@g.add_edge "Beautiful", "Girl"
@bfs = GraphAlgorithms::BFS.new @g, "Hello"
end
def test_shortest_path
actual = @bfs.shortest_path_to "Girl"
expected = ["Beautiful", "Girl"]
assert_equal expected, actual
end
def test_distance
actual = @bfs.distance_to "Girl"
expected = 2
assert_equal expected, actual
end
end |
class LoansController < ApplicationController
def new
@loan = Loan.new
end
def create
@loan = Loan.new(loan_params)
if @loan.save
redirect_to generate_amortization_schedule_loan_path(@loan)
else
render :new
end
end
def generate_amortization_schedule
@loan = Loan.find(params[:id])
@amortization_schedule = @loan.amortization_schedule
end
def index
@loans = Loan.all
end
private
def loan_params
params.require(:loan).permit(:loan_amount, :term, :interest_rate, :request_date, :amortization_type)
end
end
|
class CreateRooms < ActiveRecord::Migration[5.0]
def change
create_table :rooms do |t|
t.references :roomtype, foreign_key: true
t.string :correlative
t.boolean :available
t.integer :bedsExtra
t.integer :tvsExtra
t.integer :bathsExtra
t.timestamps
end
end
end
|
require 'thor'
require 'release_notes'
require 'release_notes/version'
require 'release_notes/versioning'
require 'release_notes/cli/helpers'
require 'release_notes/generators/release_note'
module ReleaseNotes
class CLI < Thor
package_name 'ReleaseNotes'
map '-v' => :version
desc 'new', 'Create a new release note'
method_option :destination, :aliases => '-d', :default => ReleaseNotes.release_note_folder, :desc => 'relative location of release note folder'
method_option :force, :aliases => '-f', :type => :boolean, :desc => 'overwrite files that already exist'
method_option :increment, :aliases => '-i', :default => 'patch', :banner => 'MODE', :desc => 'increment version by mode - "major", "minor", "patch"'
method_option :message, :aliases => '-m', :desc => 'interactive release note bullet input'
method_option :version, :aliases => '-v', :desc => 'use the given version number'
def new
if options[:version].nil?
last_version = ReleaseNotes::Versioning.current_version_number(options[:destination])
update_version = ReleaseNotes::Versioning::Semantic.increment(last_version, options[:increment])
else
update_version = options[:version]
end
message = ReleaseNotes::CLI::Helpers.setup_message_obj
if options[:message]
message = ReleaseNotes::CLI::Helpers.interactive_bullets(message)
end
ReleaseNotes::Generators::ReleaseNote.start([options[:destination],
message,
update_version,
"--force=#{options[:force] || false}"])
end
desc 'update', "Update #{ReleaseNotes.release_note_model} models"
method_option :destination, :aliases => '-d', :default => ReleaseNotes.release_note_folder, :desc => 'relative location of release note folder'
method_option :no_log, :aliases => '-n', :type => :boolean, :default => false, :desc => 'disable README.md log of release notes'
method_option :reset, :aliases => '-r', :type => :boolean, :default => false, :desc => 'delete all model entries and rebuilds them'
def update
# If reset option is passed delete all release notes in model
if options[:reset]
stamp = nil
release_log = ""
begin
File.delete("#{options[:destination]}/README.md")
rescue Errno::ENOENT
# Nothing to see here... move along.
end
ReleaseNotes.release_note_model.constantize.all.each do |rn|
rn.destroy
end
else
# Checks timestamp of last release note stored
begin
stamp = File.read("#{options[:destination]}/stamp")
rescue Errno::ENOENT
stamp = nil
end
# Reads contents of release note compilation file
begin
release_log = File.read("#{options[:destination]}/README.md")
rescue Errno::ENOENT
release_log = ""
end
end
# Collects relevant files and saves version and content to db
update_files = collect_update_files(options[:destination])
update_files.reverse if options[:reset]
update_files.each do |file|
timestamp = file[0].to_i
if !stamp.nil? and timestamp <= stamp.to_i
next
end
version = file[1..4].join('.')[0..-4]
file = file.join('_')
markdown = File.read("#{options[:destination]}/#{file}")
ReleaseNotes.release_note_model.constantize.create(version: version,
markdown: markdown)
release_log.insert(0, "#{markdown}\n\n---\n\n") unless options[:no_log]
end
# Store the timestamp of the last release note
new_stamp = latest_update_file(options[:destination])
File.write("#{options[:destination]}/stamp", "#{new_stamp}", mode: 'w')
# Store release note compilation file
File.write("#{options[:destination]}/README.md", "#{release_log}", mode: 'w') unless options[:no_log]
say "#{ReleaseNotes.release_note_model} model successfully updated.", :green
say "ReleaseNotes log successfully updated (see #{options[:destination]}/README.md).", :green unless options[:no_log]
end
desc 'version', 'Show version of release_notes'
def version
puts "ReleaseNotes v#{ReleaseNotes::VERSION}"
end
protected
def collect_update_files(dirname)
update_lookup_at(dirname).collect do |file|
File.basename(file).split('_')
end
end
def latest_update_file(dirname)
update_lookup_at(dirname).collect do |file|
File.basename(file).split('_').first.to_i
end.max.to_i
end
def update_lookup_at(dirname)
Dir.glob("#{dirname}/[0-9]*_*.md")
end
end
end |
class Image
attr_accessor :pixels
def initialize (pixels)
@pixels = pixels
end
def find_ones
locations = []
pixels.each_with_index do |row,y|
row.each_with_index do |value,x|
if (value == 1)
locations.push([y,x])
end
end
end
return locations
end
def output_image
@pixels.each do |x|
x.each do |y|
print y
end
puts "\n"
end
end
def blur
find_ones.each do |coord|
y = coord[0]
x = coord[1]
pixels[y-1][x] = 1 if y >= 1;
pixels[y+1][x] = 1 if y <= pixels.length-1;
pixels[y][x-1] = 1 if x >= 1;
pixels[y][x+1] = 1 if y <= pixels.length-1;
end
end
end
image = Image.new ([[0, 1, 0, 0],[0, 1, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0], [0, 0, 0, 0]])
image.blur
image.output_image
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :community do
sequence(:name) {|n| "Community #{n}"}
association :owner, factory: :user
end
end
|
require './canhelplib'
require 'csv'
require 'faker'
require_relative 'shared/actions.rb'
require_relative 'shared/actions_csv.rb'
module CanhelpPlugin
include Canhelp
# create users.csv
# specify true or false to uplaod csv (sis import api)
def self.csv_users(
subdomain = prompt(:subdomain),
user_count = prompt(:user_count),
prefix = prompt(:prefix),
user_type = prompt(:user_type),
state = prompt(:state),
sis_import = prompt(:sis_import_true_or_false)
)
token = get_token
user_count = 1 if user_count.empty?
file_path = "csv/users.csv"
puts "Created User(s):"
create_users_csv(subdomain,file_path,user_count,prefix,user_type,state,sis_import)
end
end
|
# frozen_string_literal: true
RSpec.describe CampaignsSyncOrchestrator do
describe '::call' do
subject { described_class.call }
let(:outer_campaign) do
instance_double(LocalCampaign, external_reference: '1')
end
let(:inner_campaign) do
instance_double(LocalCampaign, external_reference: '2')
end
let(:inner_ad) { instance_double(RemoteAd, reference: '2') }
let(:outer_ad) { instance_double(RemoteAd, reference: '3') }
let(:local_campaigns) { [outer_campaign, inner_campaign] }
let(:remote_ads) { [outer_ad, inner_ad] }
let(:left_inner_difference) do
[
{
'reference' => {
'local' => '1',
'remote' => 'Non Existent'
},
'discrepancies' => [{}]
},
{
'reference' => {
'local' => '2',
'remote' => '2'
},
'discrepancies' => [{}]
}
]
end
let(:right_outer_difference) do
[
{
'reference' => {
'local' => 'Non Existent',
'remote' => '3'
},
'discrepancies' => [{}]
}
]
end
before do
allow(LocalCampaignsRepository)
.to receive(:all)
.with(no_args)
.and_return(local_campaigns)
allow(RemoteAdsRepository)
.to receive(:all)
.with(no_args)
.and_return(remote_ads)
allow(LeftInnerSyncOrchestrator)
.to receive(:call)
.with(remote_ads: remote_ads, local_campaigns: local_campaigns)
.and_return(left_inner_difference)
allow(RightOuterSyncOrchestrator)
.to receive(:call)
.with(remote_ads: [outer_ad])
.and_return(right_outer_difference)
end
it { is_expected.to eq(left_inner_difference + right_outer_difference) }
end
end
|
ActiveAdmin.register Course do
menu :parent => "Courses"
filter :code, :label => "Ticket #"
filter :number, :label => "class #"
filter :department
filter :title
filter :instructor
filter :status, :as => :check_boxes, :collection => proc {Course::VALID_STATUS}
filter :available_seats
filter :created_at
filter :updated_at
filter :term
config.sort_order = "updated_at_desc"
index do
selectable_column
column "Ticket #", :code
column("Name") { |course| "#{course.department.abbr} #{course.number}" }
column :title
column :instructor
column :status
column "Seats", :available_seats
column :term
default_actions
end
form do |f|
f.inputs "Required" do
f.input :code
f.input :number
f.input :title
f.input :status, :as => :select,
:collection => Course::VALID_STATUS
end
f.inputs "Optional" do
f.input :department
f.input :term
f.input :instructor
f.input :available_seats
end
f.buttons
end
sidebar :help do
"Need help?"
end
end
|
class ClassRoomTimetable < ApplicationRecord
self.table_name = "class_rooms_timetables"
scope :get_list_timetable, ->(class_room_id){where "class_room_id = ?",class_room_id}
scope :get_list_class_ids, ->(timetable_id){where "timetable_id = ?",timetable_id}
end
|
require "securerandom"
require "socket"
# get the port and validate it
port = ENV["PORT"].to_i
raise "PORT was not set or was set to 0, please set a real port!" if port == 0
puts "Ruby TCP server port set to: #{port}"
# create the server on the port set via the environment
server = TCPServer.new(port)
puts "Server is running."
# loop
loop do
begin
# wait for a connection
client = server.accept
# get our random text, or just generate some ourself
random_text = ENV["RANDOM_TEXT"] || SecureRandom.hex(50)
# write our text then close
client.puts random_text
puts "Served random text: #{random_text}"
client.close
rescue
end
end
|
# frozen_string_literal: true
class AddRegistrationQuotaToRegistrationPrice < ActiveRecord::Migration[4.2]
def change
add_reference :registration_prices, :registration_quota, index: true
end
end
|
Sketchup::require 'sketchup'
Sketchup::require 'plytool/constants'
Sketchup::require 'bonitotools'
Sketchup::require 'plytool/materials'
Sketchup::require 'plytool/edge_banding_applicator'
Sketchup::require 'plytool/utilities'
Sketchup::require 'plytool/shelves'
module TwoMonks
module Update
class << self
SKETCHUP_GROUP = 'Sketchup::Group'
SKETCHUP_COMPONENT_INSTANCE = 'Sketchup::ComponentInstance'
def start_updating_models(selection)
all_plys_array = TwoMonks::EdgeBanding.get_plys(selection).compact
all_plys_array.each do |ply|
update_component(ply)
end
end
def update_component(entity)
thickness = BackSheet.bonitotools_get_ply_size(entity)
entity = set_base_material_thickneess(entity, thickness)
entities = entity.definition.entities
material_name = FROSTY_WHITE_MATERIAL
if (!Squadro::Materials.check_material_in_model(material_name))
material_name = Squadro::Materials.add_material_to_model(material_name)
end
for face in entities
if(face.typename == FACE_STRING)
edge_length_array = []
for edge in face.edges
edge_length_array << edge.length
end
if(!(edge_length_array.include? thickness.mm))
face.material = material_name
face.set_attribute FACE_DICT_NAME, FACE_TYPE_ATTRIBUTE, NORMAL_FACE
else
face.material = nil
face.set_attribute FACE_DICT_NAME, FACE_TYPE_ATTRIBUTE, EDGE_FACE
face.set_attribute FACE_DICT_NAME, EDGE_THICKNESS_ATTRIBUTE, ZERO_THICKNESS
face.set_attribute FACE_DICT_NAME, EDGE_WIDTH_ATTRIBUTE, ZERO_WIDTH
end
end
end
return entity
end
def get_all_corners_of_trans_ply(ply,trans) #for a ply in group
corners = []
ply_bounds = ply.bounds
for ii in (0..7)
point = ply_bounds.corner(ii)
point2 = point.transform! trans
corners[ii] = point2
end
return corners
end
def get_uniq_array(corners) #for some case "array.uniq!"" is not willing to work , so wrote this for that
corners_sort = corners.sort!
corners_uniq = []
last = Array.new(0)
corners_sort.each do |corn|
if corners_uniq.empty?
corners_uniq.push(corn)
elsif corn != last[0]
corners_uniq.push(corn)
end
last = [corn]
end
return corners_uniq
end
def get_arrays_of_trans_RGB(corners) #for group
array_r = []
array_g = []
array_b = []
corners.each do |point|
array_r << point.x
array_g << point.y
array_b << point.z
end
r = get_uniq_array(array_r)
g = get_uniq_array(array_g)
b = get_uniq_array(array_b)
return [r, g, b]
end
#in some cases normal of a ply may be different because of sevaral reasons ,below function
#to find exact normal with refference main origin
def get_normal_of_trans_ply(ply, trans)
normal = BackSheet.get_normal_of_ply(ply)
normal_trans = normal. transform trans
if normal_trans == XAXIS_PTVE_DIR_VEC || normal_trans == XAXIS_NTVE_DIR_VEC
return X_AXIS
elsif normal_trans == YAXIS_PTVE_DIR_VEC || normal_trans == YAXIS_NTVE_DIR_VEC
return Y_AXIS
elsif normal_trans == ZAXIS_PTVE_DIR_VEC || normal_trans == ZAXIS_NTVE_DIR_VEC
return Z_AXIS
end
end
def get_corners_of_trans_face(face, tran_seln, trans_ply) #for transformed ply - incase ply is in group/Component instance
corners = []
face_bounds = face.bounds
for ii in (0..3)
point = face_bounds.corner(ii)
point2 = point.transform! trans_ply #tran_seln
point3 = point2.transform! tran_seln
corners[ii] = point3
end
return corners
end
def get_corners_of_face(face, tran_sel) #for an ordinary ply
corners = []
face_bounds = face.bounds
for ii in (0..3)
point = face_bounds.corner(ii)
point2 = point.transform! tran_sel
corners[ii] = point2
end
return corners
end
def get_length_direction_of_ply(rgb_array, norm) #this function returns length direction of ply
# s - square
rgb_x = rgb_array[0]
rgb_y = rgb_array[1]
rgb_z = rgb_array[2]
diff_x = (rgb_x[1] - rgb_x[0]).to_mm.abs.round
diff_y = (rgb_y[1] - rgb_y[0]).to_mm.abs.round
diff_z = (rgb_z[1] - rgb_z[0]).to_mm.abs.round
if norm == Z_AXIS
if diff_x > diff_y
return "x"
elsif diff_x < diff_y
return "y"
elsif diff_x == diff_y
return "s"
end
elsif norm == X_AXIS
if diff_z > diff_y
return "z"
elsif diff_z < diff_y
return "y"
elsif diff_z == diff_y
return "s"
end
elsif norm == Y_AXIS
if diff_x > diff_z
return "x"
elsif diff_x < diff_z
return "z"
elsif diff_x == diff_z
return "s"
end
end
end
def detect_groove_face(face, rgb_array_face, bs_points, ply_normal) #sel-may be group,component instance
material = Sketchup.active_model.materials #returns material(laminate) on that face
rgb_array_fac_x = rgb_array_face[0]
rgb_array_fac_y = rgb_array_face[1]
rgb_array_fac_z = rgb_array_face[2]
mat_name = face.material.name
if ply_normal == X_AXIS
if ([8,6].include?((rgb_array_fac_x[0] - bs_points[0]).to_mm.abs.round)) || ([8,6].include?((rgb_array_fac_x[0] - bs_points[1]).to_mm.abs.round))
return mat_name
end
elsif ply_normal == Y_AXIS
if ([8,6].include?((rgb_array_fac_y[0] - bs_points[0]).to_mm.abs.round)) || ([8,6].include?((rgb_array_fac_y[0] - bs_points[1]).to_mm.abs.round))
return mat_name
end
elsif ply_normal == Z_AXIS
if ([8,6].include?((rgb_array_fac_z[0] - bs_points[0]).to_mm.abs.round)) || ([8,6].include?((rgb_array_fac_z[0] - bs_points[1]).to_mm.abs.round))
return mat_name
end
else
return nil
end
end
def detect_groove_side(bs_points_array, ply_points_array, bs_norm, ply_norm)#side - Length and width side
bs_length_dir = get_length_direction_of_ply(bs_points_array, bs_norm)
ply_length_dir = get_length_direction_of_ply(ply_points_array, ply_norm)
if bs_norm == Y_AXIS && ply_norm == X_AXIS
if ply_length_dir == "z"
return "l"
elsif ply_length_dir == "y"
return "w"
elsif ply_length_dir == "s"
return "s"
end
elsif bs_norm == Y_AXIS && ply_norm == Z_AXIS
if ply_length_dir == "x"
return "l"
elsif ply_length_dir == "y"
return "w"
elsif ply_length_dir == "s"
return "s"
end
elsif bs_norm == X_AXIS && ply_norm == Y_AXIS
if ply_length_dir == "z"
return "l"
elsif ply_length_dir == "x"
return "w"
elsif ply_length_dir == "s"
return "s"
end
elsif bs_norm == X_AXIS && ply_norm == Z_AXIS
if ply_length_dir == "y"
return "l"
elsif ply_length_dir == "x"
return "w"
elsif ply_length_dir == "s"
return "s"
end
elsif bs_norm == Z_AXIS && ply_norm == X_AXIS
if ply_length_dir == "z"
return "w"
elsif ply_length_dir == "y"
return "l"
elsif ply_length_dir == "s"
return "s"
end
elsif bs_norm == Z_AXIS && ply_norm == Y_AXIS
if ply_length_dir == "z"
return "w"
elsif ply_length_dir == "x"
return "l"
elsif ply_length_dir == "s"
return "s"
end
end
end
def compare_backsheet_and_ply_cordinates_to_detect_groove(backsheet_points, normal_bs, ply_points, normal_ply)
#the below code compare backsheet coardinates with selected ply in all x,y,z direction
#for Ex; if backsheet normal is in y-axis the its one of x coardinate should lie between both the x-coardinates of a
#selected ply,like this, this code compares with all posible cases in all X Y Z dir
bs_x_corn = backsheet_points[0]
bs_y_corn = backsheet_points[1]
bs_z_corn = backsheet_points[2]
rgb_x = ply_points[0]
rgb_y = ply_points[1]
rgb_z = ply_points[2]
if normal_bs == Y_AXIS
if normal_ply == X_AXIS
if (rgb_x[1] > bs_x_corn[0] && rgb_x[0] < bs_x_corn[0]) || (rgb_x[1] > bs_x_corn[1] && rgb_x[0] < bs_x_corn[1])
if (rgb_y[1] > bs_y_corn[0] && rgb_y[0] < bs_y_corn[0]) && (rgb_y[1] > bs_y_corn[1] && rgb_y[0] < bs_y_corn[1])
if ((rgb_z[1] > bs_z_corn[0] && rgb_z[0] < bs_z_corn[0]) && (rgb_z[1] > bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])) ||
((rgb_z[1] > bs_z_corn[0] && rgb_z[0] > bs_z_corn[0]) && (rgb_z[1] < bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])) ||
((rgb_z[1] > bs_z_corn[0] && rgb_z[0] < bs_z_corn[0]) && (rgb_z[1] < bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])) ||
((rgb_z[1] > bs_z_corn[0] && rgb_z[0] > bs_z_corn[0]) && (rgb_z[1] > bs_z_corn[1] && rgb_z[0] < bs_z_corn[1]))
return bs_x_corn
end
end
end
elsif normal_ply == Z_AXIS
if ((rgb_x[1] > bs_x_corn[0] && rgb_x[0] < bs_x_corn[0]) && (rgb_x[1] > bs_x_corn[1] && rgb_x[0] < bs_x_corn[1])) ||
((rgb_x[1] > bs_x_corn[0] && rgb_x[0] > bs_x_corn[0]) && (rgb_x[1] < bs_x_corn[1] && rgb_x[0] < bs_x_corn[1])) ||
((rgb_x[1] > bs_x_corn[0] && rgb_x[0] < bs_x_corn[0]) && (rgb_x[1] < bs_x_corn[1] && rgb_x[0] < bs_x_corn[1])) ||
((rgb_x[1] > bs_x_corn[0] && rgb_x[0] > bs_x_corn[0]) && (rgb_x[1] > bs_x_corn[1] && rgb_x[0] < bs_x_corn[1]))
if ((rgb_y[1]) > (bs_y_corn[0]) && (rgb_y[0]) < (bs_y_corn[0])) && ((rgb_y[1]) > (bs_y_corn[1] ) && (rgb_y[0] ) < (bs_y_corn[1]))
if (rgb_z[1] > bs_z_corn[0] && rgb_z[0] < bs_z_corn[0]) || (rgb_z[1] > bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])
return bs_z_corn
end
end
end
end
elsif normal_bs == X_AXIS
if normal_ply == Y_AXIS #(normal_ply.transform t).y.round.abs == 1
if (rgb_x[1] > bs_x_corn[0] && rgb_x[0] < bs_x_corn[0]) && (rgb_x[1] > bs_x_corn[1] && rgb_x[0] < bs_x_corn[1])
if (rgb_y[1] > bs_y_corn[0] && rgb_y[0] < bs_y_corn[0]) || (rgb_y[1] > bs_y_corn[1] && rgb_y[0] < bs_y_corn[1])
if ((rgb_z[1] > bs_z_corn[0] && rgb_z[0] < bs_z_corn[0]) && (rgb_z[1] > bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])) ||
((rgb_z[1] > bs_z_corn[0] && rgb_z[0] > bs_z_corn[0]) && (rgb_z[1] < bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])) ||
((rgb_z[1] > bs_z_corn[0] && rgb_z[0] < bs_z_corn[0]) && (rgb_z[1] < bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])) ||
((rgb_z[1] > bs_z_corn[0] && rgb_z[0] > bs_z_corn[0]) && (rgb_z[1] > bs_z_corn[1] && rgb_z[0] < bs_z_corn[1]))
return bs_y_corn
end
end
end
elsif normal_ply == Z_AXIS
if (rgb_x[1] > bs_x_corn[0] && rgb_x[0] < bs_x_corn[0]) && (rgb_x[1] > bs_x_corn[1] && rgb_x[0] < bs_x_corn[1])
if ((rgb_y[1] > bs_y_corn[0] && rgb_y[0] < bs_y_corn[0]) && (rgb_y[1] > bs_y_corn[1] && rgb_y[0] < bs_y_corn[1])) ||
((rgb_y[1] > bs_y_corn[0] && rgb_y[0] > bs_y_corn[0]) && (rgb_y[1] < bs_y_corn[1] && rgb_y[0] < bs_y_corn[1])) ||
((rgb_y[1] > bs_y_corn[0] && rgb_y[0] < bs_y_corn[0]) && (rgb_y[1] < bs_y_corn[1] && rgb_y[0] < bs_y_corn[1])) ||
((rgb_y[1] > bs_y_corn[0] && rgb_y[0] > bs_y_corn[0]) && (rgb_y[1] > bs_y_corn[1] && rgb_y[0] < bs_y_corn[1]))
if (rgb_z[1] > bs_z_corn[0] && rgb_z[0] < bs_z_corn[0]) || (rgb_z[1] > bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])
return bs_z_corn
end
end
end
end
elsif normal_bs == Z_AXIS
if normal_ply == X_AXIS
if ((rgb_x[1] > bs_x_corn[0] && rgb_x[0] < bs_x_corn[0]) || (rgb_x[1] > bs_x_corn[1] && rgb_x[0] < bs_x_corn[1]))
if ((rgb_y[1] > bs_y_corn[0] && rgb_y[0] < bs_y_corn[0]) && (rgb_y[1] > bs_y_corn[1] && rgb_y[0] < bs_y_corn[1])) ||
((rgb_y[1] > bs_y_corn[0] && rgb_y[0] > bs_y_corn[0]) && (rgb_y[1] < bs_y_corn[1] && rgb_y[0] < bs_y_corn[1])) ||
((rgb_y[1] > bs_y_corn[0] && rgb_y[0] < bs_y_corn[0]) && (rgb_y[1] < bs_y_corn[1] && rgb_y[0] < bs_y_corn[1])) ||
((rgb_y[1] > bs_y_corn[0] && rgb_y[0] > bs_y_corn[0]) && (rgb_y[1] > bs_y_corn[1] && rgb_y[0] < bs_y_corn[1]))
if (rgb_z[1] > bs_z_corn[0] && rgb_z[0] < bs_z_corn[0]) && (rgb_z[1] > bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])
return bs_x_corn
end
end
end
elsif normal_ply == Y_AXIS
if ((rgb_x[1] > bs_x_corn[0] && rgb_x[0] < bs_x_corn[0]) && (rgb_x[1] > bs_x_corn[1] && rgb_x[0] < bs_x_corn[1])) ||
((rgb_x[1] > bs_x_corn[0] && rgb_x[0] > bs_x_corn[0]) && (rgb_x[1] < bs_x_corn[1] && rgb_x[0] < bs_x_corn[1])) ||
((rgb_x[1] > bs_x_corn[0] && rgb_x[0] < bs_x_corn[0]) && (rgb_x[1] < bs_x_corn[1] && rgb_x[0] < bs_x_corn[1])) ||
((rgb_x[1] > bs_x_corn[0] && rgb_x[0] > bs_x_corn[0]) && (rgb_x[1] > bs_x_corn[1] && rgb_x[0] < bs_x_corn[1]))
if ((rgb_y[1] > bs_y_corn[0] && rgb_y[0] < bs_y_corn[0]) || (rgb_y[1] > bs_y_corn[1] && rgb_y[0] < bs_y_corn[1]))
if (rgb_z[1] > bs_z_corn[0] && rgb_z[0] < bs_z_corn[0]) && (rgb_z[1] > bs_z_corn[1] && rgb_z[0] < bs_z_corn[1])
return bs_y_corn
end
end
end
end
else
return nil
end
end
def set_groove_from_sel_model(back_sheet,rgb_array_bs, normal_bs) #for groove detection #bs - backsheet
@selection.each do |sel|
trans_sel = sel.transformation
if BackSheet.is_this_entity_a_ply(sel) #for ply not in group
sel.make_unique
thickness_of_sel = BackSheet.bonitotools_get_ply_size(sel)
if thickness_of_sel != 8
normal_sel = BackSheet.get_normal_of_ply(sel)
corners_sel = Utilities.get_all_corners_of_ply(sel)
rgb_array_sel = Utilities.get_arrays_of_RGB(corners_sel)
points_sel = compare_backsheet_and_ply_cordinates_to_detect_groove(rgb_array_bs, normal_bs,rgb_array_sel, normal_sel)
if points_sel != nil
faces_sel_array = sel.definition.entities.grep(Sketchup::Face)
side_sel = detect_groove_side(rgb_array_bs, rgb_array_sel, normal_bs, normal_sel)
faces_sel_array.each do |face|
if face.get_attribute(FACE_DICT_NAME, FACE_TYPE_ATTRIBUTE) == NORMAL_FACE
corners_sel_face = get_corners_of_face(face, trans_sel)
rgb_array_sel_face = Utilities.get_arrays_of_RGB(corners_sel_face)
face_sel = detect_groove_face(face,rgb_array_sel_face, points_sel, normal_sel)
if face_sel != nil
TwoMonks::MovableShelf.set_attribute_for_shelves(sel,"groove"+"#"+"#{side_sel}"+"#"+"#{face_sel}")
break
end
end
end
end
end
else #for a ply in group
ply_array = TwoMonks::EdgeBanding.get_plys(sel)
ply_array.each do |ply|
ply.make_unique
thickness_of_ply = BackSheet.bonitotools_get_ply_size(ply)
if thickness_of_ply != 8
trans_ply = ply.transformation
normal_ply = get_normal_of_trans_ply(ply, trans_sel)
corners_ply = get_all_corners_of_trans_ply(ply, trans_sel)
rgb_array_ply = get_arrays_of_trans_RGB(corners_ply) #rgb array for ply in group
points_ply = compare_backsheet_and_ply_cordinates_to_detect_groove(rgb_array_bs, normal_bs,rgb_array_ply, normal_ply)
if points_ply != nil
faces_ply_array = ply.definition.entities.grep(Sketchup::Face)
side_ply = detect_groove_side(rgb_array_bs, rgb_array_ply, normal_bs, normal_ply)
faces_ply_array.each do |face|
if face.get_attribute(FACE_DICT_NAME, FACE_TYPE_ATTRIBUTE) == NORMAL_FACE
corners_ply_face = get_corners_of_trans_face(face, trans_sel, trans_ply)
rgb_array_ply_face = Utilities.get_arrays_of_RGB(corners_ply_face)
face_ply = detect_groove_face(face, rgb_array_ply_face, points_ply, normal_ply)
if face_ply != nil
TwoMonks::MovableShelf.set_attribute_for_shelves(ply,"groove"+"#"+"#{side_ply}"+"#"+"#{face_ply}")
break
end
end
end
end
end
end
end
end
end
def set_backsheet_and_groove_from_sel_model(seln)
trans_seln = seln.transformation
if BackSheet.is_this_entity_a_ply(seln) #for ordinary ply
seln.make_unique
thickness_of_seln = BackSheet.bonitotools_get_ply_size(seln)
if thickness_of_seln == 8
TwoMonks::MovableShelf.set_attribute_for_shelves(seln,"Back Sheet")
normal_seln = BackSheet.get_normal_of_ply(seln)
corners_seln = Utilities.get_all_corners_of_ply(seln)
rgb_array_seln = Utilities.get_arrays_of_RGB(corners_seln)
set_groove_from_sel_model(seln, rgb_array_seln, normal_seln)
end
else #for a ply in group
ply_array = TwoMonks::EdgeBanding.get_plys(seln)
ply_array.each do |ply|
thickness_of_ply = BackSheet.bonitotools_get_ply_size(ply)
if thickness_of_ply == 8
ply.make_unique
TwoMonks::MovableShelf.set_attribute_for_shelves(ply,"Back Sheet")
trans_ply = ply.transformation
normal_ply = get_normal_of_trans_ply(ply, trans_seln)
corners_ply = get_all_corners_of_trans_ply(ply, trans_seln)
rgb_array_ply = get_arrays_of_trans_RGB(corners_ply)
set_groove_from_sel_model(seln, rgb_array_ply, normal_ply)
end
end
end
end
def set_property_for_models()
@model = Sketchup.active_model
@selection = @model.selection
@selection.each do |sel|
set_backsheet_and_groove_from_sel_model(sel)
end
UI.messagebox "Properties updated successfully"
end
end #end of class
end #end of Module Update
end #end of TwoMonks |
require "test_helper"
describe MostRecentContent do
include RummagerFields
def most_recent_content
@most_recent_content ||= MostRecentContent.new(
content_id: taxon_content_id,
filter_content_store_document_type: %w[authored_article correspondence],
)
end
def taxon_content_id
"a18d16c4-29ff-41c2-a667-022f7615ba49"
end
describe "#fetch" do
it "returns the results from search" do
search_results = {
"results" => [
{ "title" => "First news story" },
{ "title" => "Second news story" },
{ "title" => "Third news story" },
{ "title" => "Fourth news story" },
{ "title" => "Fifth news story" },
],
}
Services.rummager.stubs(:search).returns(search_results)
results = most_recent_content.fetch
assert_equal(results.count, 5)
end
end
it "starts from the first page" do
assert_includes_params(start: 0) do
most_recent_content.fetch
end
end
it "requests five results by default" do
assert_includes_params(count: 5) do
most_recent_content.fetch
end
end
it "requests a limited number of fields" do
fields = RummagerFields::TAXON_SEARCH_FIELDS
assert_includes_params(fields: fields) do
most_recent_content.fetch
end
end
it "orders the results by public_timestamp in descending order" do
assert_includes_params(order: "-public_timestamp") do
most_recent_content.fetch
end
end
it "scopes the results to the current taxon" do
assert_includes_params(filter_part_of_taxonomy_tree: [taxon_content_id]) do
most_recent_content.fetch
end
end
it "filters content by the requested document types only" do
assert_includes_params(filter_content_store_document_type: %w[authored_article correspondence]) do
most_recent_content.fetch
end
end
end
|
class PostsController < ApplicationController
def index
@post = Post.find(3)
end
def create
@post = current_user.posts.build(post_params)
if @post.save
flash.now[:success] = "Post created!"
# redirect_to root_url
end
end
private
def post_params
params.permit(:topic, :content)
end
end
|
class AddPageExtraFields < ActiveRecord::Migration
def self.up
add_column :pages, :menu_order, :integer, :default => 1
add_column :pages, :link_title, :string
end
def self.down
remove_column :pages, :menu_order
remove_column :pages, :link_title
end
end
|
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
require "minitest/autorun"
require "minitest/spec"
require "minitest/mock"
# FIXME Remove once https://github.com/mperham/sidekiq/pull/548 is released.
class String
def blank?
self !~ /[^[:space:]]/
end
end
require "rack/test"
require "celluloid"
require "sidekiq"
require "sidekiq-job-manager"
require "sidekiq/processor"
require "sidekiq/fetch"
require "sidekiq/cli"
require "mock_redis"
Celluloid.logger = nil
Sidekiq.logger.level = Logger::ERROR
REDIS = ConnectionPool.new(:size => 1, :timeout => 5) { MockRedis.new }
|
class Section < ActiveRecord::Base
belongs_to :instrument, inverse_of: :sections
acts_as_list scope: :instrument
has_many :questions, -> { order "position ASC" }, dependent: :destroy
accepts_nested_attributes_for :questions
def previous(evaluation)
evaluation.instrument.sections.where(["position < ?", position]).last
end
def next(evaluation)
evaluation.instrument.sections.where(["position > ?", position]).first
end
end
|
# == Schema Information
#
# Table name: tweets
#
# id :bigint not null, primary key
# content :text not null
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_tweets_on_user_id (user_id)
#
require 'rails_helper'
RSpec.describe Tweet, type: :model do
let!(:user) { create(:user) }
context '内容が入力されている場合' do
let!(:tweet) { build(:tweet, user: user) }
it 'tweetを保存できる' do
expect(tweet).to be_valid
end
end
context '内容が301文字の場合' do
let!(:tweet) { build(:tweet, content: Faker::Lorem.characters(number: 301), user: user) }
before do
tweet.save
end
it 'tweetを保存できない' do
expect(tweet.errors.messages[:content][0]).to eq('は300文字以内で入力してください')
end
end
context '並び順' do
let!(:tweet_yesterday) { create(:tweet, :yesterday, user: user) }
let!(:tweet_one_week_ago) { create(:tweet, :one_week_ago, user: user) }
let!(:tweet_one_month_ago) { create(:tweet, :one_month_ago, user: user) }
it '最も最近の投稿が最初の投稿になっていること' do
expect(tweet_yesterday).to eq Tweet.first
end
end
end
|
require 'spec_helper'
require_relative '../../lib/paths'
using StringExtension
module Jabverwock
using StringExtension
RSpec.describe 'jw basic test' do
subject(:css) { CSS.new "t" }
it "set property" do
css.name = "head"
css.font_size = 10
expect{
css.gogo(1) # no property
}.to raise_error StandardError
end
it "insert property class" do
css.name = "head"
css.font_size = 10
expect(css.str).to eq "head {\nfont-size: 10;\n}"
end
it "property default method, not chain" do
css.name = "head"
css.font_size = 10
css.color = "red"
expect(css.str).to eq "head {\nfont-size: 10;\ncolor: red;\n}"
end
it "property method chain" do
css.name = "head"
css.font_size("10").color("red")
expect(css.str).to eq "head {\nfont-size: 10;\ncolor: red;\n}"
end
it "name divide by space" do
css.name = "head .cls"
css.font_size("10").color("red").font_style("bold")
expect(css.str).to eq "head .cls {\nfont-size: 10;\ncolor: red;\nfont-style: bold;\n}"
end
it "css name define" do
c = CSS.new("head")
c.font_size("10").color("red").font_style("bold")
expect(c.str).to eq "head {\nfont-size: 10;\ncolor: red;\nfont-style: bold;\n}"
end
it "css name symbole case 1" do
c = CSS.new :head
c.font_size("10").color("red").font_style("bold")
expect(c.str).to eq "head {\nfont-size: 10;\ncolor: red;\nfont-style: bold;\n}"
end
it "combineSelectors" do
c = CSS.new "ss,s,h"
expect(c.name).to eq "ss,s,h"
end
# # dpName, addChildrenName, addMembersName
it 'dpName' do
c = CSS.new :head
c2 = c.dpName
expect(c2).to eq "head"
end
it 'dpName import' do
c = CSS.new :head
c2 = CSS.new c.dpName
expect(c2.name).to eq 'head'
end
it "dup and addChildren" do
c = CSS.new :head
c2 = CSS.new c.addChildrenName "p"
expect(c.name).to eq "head"
expect(c2.name).to eq "head p"
end
it "dup and addMembers" do
c = CSS.new :head
c2 = CSS.new c.addMembersName "p"
expect(c.name).to eq "head"
expect(c2.name).to eq "head, p"
end
it "dpName and css property" do
c = CSS.new(:head).color "red"
c2 = CSS.new c.addChildrenName "p"
c2.color("yellow")
expect(c.str).to eq "head {\ncolor: red;\n}"
expect(c2.str).to eq "head p {\ncolor: yellow;\n}"
end
# #css symbole name
it 'symbol Name id' do
c = CSS.new(:id__test).color "red"
expect(c.str).to eq "#test {\ncolor: red;\n}"
end
it 'symbol Name class' do
c = CSS.new(:cls__test).color "red"
expect(c.str).to eq ".test {\ncolor: red;\n}"
end
it 'symbol Name just symbol ' do
c = CSS.new(:a__test).color "red"
expect(c.str).to eq "atest {\ncolor: red;\n}"
end
it 'symbol Name property' do
c = CSS.new("").color "red"
c.name = :id__test
expect(c.str).to eq "#test {\ncolor: red;\n}"
end
end
RSpec.describe 'css no name' do
it 'css no name pattern'do
c = CSS.new
expect(c.name).to eq ""
end
end
end
|
class Bid < ActiveRecord::Base
has_many :sla_items, dependent: :destroy
enum status: %i(submitted accepted rejected withdrawn)
end
|
module Test
module HumbleUnit
module Outputs
class ConsoleOutput < BaseOutput
def flush(test_class_name, messages, stats)
flush_header test_class_name
flush_messages test_class_name, messages
flush_stats stats
end
private
def flush_header test_class_name
printf "--=== Test class: #{test_class_name} ===---\n".to_brown
printf "%-10s %-20s %-51s %s\n", "Status", "Method name", "Error", "Source location"
end
def flush_messages(test_class_name, messages)
flush_header test_class_name
flush_content messages
end
def flush_stats(stats)
printf "%-10s: %-20s\n", "Test result", test_result(stats)
printf "%-10s: %-20s\n", "Passed", stats.passed_count
printf "%-10s: %-20s\n", "Failed", stats.failed_count
printf "%-10s: %-20s\n", "Tests", stats.number_of_tests
printf "%-10s: %-20s\n", "At", stats.time
printf "\n"
end
def flush_content(messages)
order_messages(messages).each do |m|
printf("%-19s %-20s %-60s %s\n", status(m), m.method_name, error(m), "#{m.source_location_file}:#{m.source_location_line_number}")
end
printf "\n"
end
def status(m)
m.pass ? m.status.to_green : m.status.to_red
end
def error(m)
m.pass ? m.error.to_green : m.error.to_red
end
def test_result(stats)
percentage = "(#{stats.percentage}/100.0%)"
stats.all_passed? ? "YES #{percentage}".bg_green : "NO #{percentage}".bg_red
end
end
end
end
end |
class Client < ActiveRecord::Base
def self.auth data
find_by_email_and_password data[:email], data[:password]
end
has_many :orders
scope :from_south, where(state: ["rs", "sc", "pr"])
validates :name, presence: true
validates :email, presence: true, uniqueness: true, format: {with: /\w+@gmail\.com/}
validates :state, inclusion: {in: %w[rs sp rj sc pr es], allow_nil: true}
validates :age, numericality: {greater_than: 17, only_integer: true, allow_nil: true}
validates :terms, acceptance: {accept: 'yes'}
validates :password, presence: true, confirmation: true
validates :password_confirmation, :presence => true
validate :strength_of_password
protected
def strength_of_password
return unless password
if password.count(password[0]) == password.length
errors.add(:password, "too weak")
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
config.vm.box = "fgrehm/trusty64-lxc"
config.vm.provider :lxc do |lxc|
# Same effect as 'customize ["modifyvm", :id, "--memory", "1024"]' for VirtualBox
lxc.customize 'cgroup.memory.limit_in_bytes', '1024M'
lxc.container_name = 'home'
#lxc.backingstore = 'btrfs' # none
end
config.vm.network "private_network", ip: "192.168.2.100", lxc__bridge_name: 'vlxcbr1'
# config.vm.define "db" do |node|
# node.vm.provider :lxc do |lxc|
# lxc.container_name = :machine # Sets the container name to 'db'
# lxc.container_name = 'mysql' # Sets the container name to 'mysql'
# end
# end
end
|
module Api
module Endpoints
class OAuthEndpoint < Grape::API
format :json
namespace :oauth do
desc 'Create a team from an OAuth token.'
params do
requires :code, type: String
end
post do
client = Slack::Web::Client.new
rc = client.oauth_access(client_id: ENV['SLACK_CLIENT_ID'], client_secret: ENV['SLACK_CLIENT_SECRET'], code: params[:code])
token = rc['bot']['bot_access_token']
team = create(Team, with: Api::Presenters::TeamPresenter, from: { 'token' => token })
SlackRubyBot::Service.start! team.token
team
end
end
end
end
end
|
require 'spec_helper'
describe 'ActiveCollab Client' do
if TESTING_API_RESPONSES
context 'authenticating with username and password' do
before :each do
@client = ActiveCollab::Client.new(API_URL)
end
it 'returns token string if authentication succeeds' do
username = CONFIG['user']['name']
password = CONFIG['user']['password']
@client.authenticate(username, password).class.should eq(String)
end
it 'returns false if authentication fails' do
username = "lolwatusername"
password = "lolwatpassword"
@client.authenticate(username, password).should eq(false)
end
end
end
end
|
class CourseTrainer < ApplicationRecord
belongs_to :trainer
belongs_to :course
end
|
class CommentRoutesController < ApplicationController
# controllo se l'utente è loggato
before_filter :signed_in_user
# controllo se l'utente può creare il commento
before_filter :correct_user2, only: :create
# controllo se l'utente può cancellare il commento
before_filter :correct_user, only: :destroy
def create
# creo nuovo commento da info contenute in "new comment" form
@comment_route = current_user.comment_routes.build(params[:comment_route])
#@comment_route = CommentRoute.new()
#@comment_route.content = params[:@comment_route][:content]
#@comment_route.user_id = params[:user_id]
@comment_route.route_id = params[:route_id]
if @comment_route.save
flash[:success] = 'Commento creato!'
redirect_to :back
else
session[:errors]=@comment_route.errors.full_messages
redirect_to :back
end
end
def destroy
@comment_route.destroy
flash[:success] = 'Commento eliminato!'
redirect_to :back
end
private
def correct_user
# l'utente ha un commento con l'id fornito?
@comment_route = current_user.comment_routes.find_by_id(params[:id])
if @comment_route.nil?
@comment_route = CommentRoute.find_by_id(params[:id])
@route = Route.find_by_id(@comment_route.route_id)
# se no, redirect a homepage
redirect_to :back if (current_user!=@route.user)
end
end
def correct_user2
@route = Route.find_by_id(params[:route_id])
if (current_user!=@route.user)
# se no, redirect a homepage
redirect_to :back unless current_user.r_following?(@route)
end
end
end
|
#!/usr/bin/env ruby
$: << File.expand_path('../lib', File.dirname(__FILE__))
require 'test/unit'
require 'spreadsheet'
module Spreadsheet
module Excel
class TestWorkbook < Test::Unit::TestCase
def test_password_hashing
hashing_module = Spreadsheet::Excel::Password
# Some examples found on the web
assert_equal(0xFEF1, hashing_module.password_hash('abcdefghij'))
assert_equal(hashing_module.password_hash('test'), hashing_module.password_hash('zzyw'))
end
end
end
end
|
require 'spec_helper'
describe Rank do
it { should belong_to(:player) }
it { should belong_to(:sport) }
it { should validate_presence_of(:player) }
it { should validate_presence_of(:sport) }
it { should validate_presence_of(:value) }
describe "#for_sport" do
let (:tennis) { FactoryGirl.create(:sport, :name => 'Tennis') }
before {
FactoryGirl.create(:rank)
FactoryGirl.create(:rank, :sport => tennis)
}
it {
ranks = Rank.all()
ranks.length.should == 2
}
it {
Rank.for_sport(tennis).length.should == 1
}
end
describe "#current_rank" do
before {
player1 = FactoryGirl.create(:player)
player2 = FactoryGirl.create(:player)
sport1 = FactoryGirl.create :sport
FactoryGirl.create(:rank, :player => player1, :sport => sport1)
FactoryGirl.create(:rank, :player => player1, :sport => sport1)
FactoryGirl.create(:rank, :player => player2, :sport => sport1)
FactoryGirl.create(:rank, :player => player2, :sport => sport1)
}
it { Rank.all().length.should == 4 }
it { Rank.current_ranks.length.should == 2 }
end
end
|
require './spec/spec_helper.rb'
describe Orientdb::ORM::Persistence, :with_database do
describe ExampleVertex do
context 'with new document' do
subject { ExampleVertex.new('name' => 'Test') }
describe '.save' do
it 'succeeds' do
expect{ subject.save }.not_to raise_error
end
it 'is persisted' do
expect{ subject.save }.to change(subject, :persisted?).from(false).to(true)
end
end
end # with new document
context 'with existing document' do
subject { ExampleVertex.new('name' => 'Test') }
before(:each) { subject.save }
describe '.save' do
it 'succeeds' do
subject.name = 'Another test'
expect{ subject.save }.not_to raise_error
end
it 'is persisted' do
subject.name = 'Another test'
expect{ subject.save }.not_to change(subject, :persisted?).from(true)
end
it 'changes name value' do
expect( subject.name ).to eq('Test')
subject.name = 'Another test'
subject.save
expect( subject.name ).to eq('Another test')
end
end
end # with existing document
end
end |
require 'scoring_engine'
module ScoringEngine
module Checks
class DNSDomainQuery < ScoringEngine::Engine::BaseCheck
FRIENDLY_NAME = "DNS Domain Query"
PROTOCOL = "dns"
VERSION = "ipv4"
def command_str
# @<ip> DNS server address
# -t Type of request - PTR, A, or AAAA
# -q Domain to perform query for
cmd = "dig @#{ip} "
# query-type
query_type = get_random_property('query-type')
# query_type = service.properties.option('query-type')
raise("Missing query-type property") unless query_type
# query
query = get_random_property('query')
# query = service.properties.random('query')
raise("Missing query property") unless query
# Build cmd
cmd << " -t #{query_type} -q #{query} "
return cmd
end
end
end
end |
class MoviesController < ApplicationController
def index
if current_user
@today = Date.today
@movies = Movie.where("date_to > '#{@today}' or date_to is null")
else
render 'welcome'
end
end
def welcome
end
def show
@movie = Movie.find(params[:id])
end
def new
@movie = Movie.new
end
def create
@movie = Movie.new(movie_params)
if @movie.save
redirect_to admins_movies_path, notice: "Movie was successfully created."
else
redirect_to admins_movies_path, notice: "Failed to create a movie."
end
end
def update
@movie = Movie.find(params[:id])
if @movie.update(movie_params)
redirect_to admins_movies_path, notice: "Movie was successfully updated."
else
render :edit
end
end
def destroy
@movie = Movie.find(params[:id])
@movie.destroy
redirect_to admins_movies_path, notice: "Movie was succesfully destroyed."
end
private
def movie_params
params.require(:movie).permit(:title)
end
end
|
require 'ios_toolchain/helpers'
include IosToolchain::Helpers
if config.crashlytics_installed?
namespace :ios do
namespace :distribute do
desc 'Distribute pre-built IPA to Crashlytics'
task :crashlytics, :ipa_path, :configuration do |t, args|
args.with_defaults(ipa_path: 'archive')
puts 'Distributing to crashlytics...'
build_cmd = []
build_cmd << "#{config.crashlytics_framework_path}/submit #{ENV['FABRIC_API_KEY']} #{ENV['FABRIC_BUILD_SECRET']}"
build_cmd << "-ipaPath #{args[:ipa_path]}/#{config.default_scheme}-#{args[:configuration]}.ipa"
build_cmd << "-groupAliases #{args[:configuration]}"
sh(build_cmd.join(' '))
end
end
end
end
|
class AddTimestampsToResearches < ActiveRecord::Migration[5.2]
def change
add_timestamps(:researches)
end
end
|
RSpec.feature 'Posts to a wall are only visible on that particular wall', type: :feature do
scenario 'Posts to a wall are only visible on that particular wall' do
visit('/')
click_on('Signup')
fill_in('user[username]', with: 'user1')
fill_in('user[email]', with: 'test@test.com')
fill_in('user[password]', with: 'password')
page.select('Kashyyyk', from: 'user[planet]')
click_on('Join the Rebel Alliance')
click_on 'New Post'
fill_in 'post[post_content]', with: 'Hey there'
click_on 'Create Post'
expect(page).to have_content('Hey there')
expect(page).to have_content('user1')
click_on 'wookiebook'
expect(page).not_to have_content('Hey there')
expect(page).not_to have_content('user1')
end
end
|
class ChangeFriendshipColumnType < ActiveRecord::Migration
def change
change_column :friendships, :user_id, 'integer USING CAST("user_id" AS integer)'
change_column :friendships, :friend_id, 'integer USING CAST("friend_id" AS integer)'
end
end
|
class Shop < ActiveRecord::Base
validates_presence_of :name, :description, :lines_summary
validates_format_of :image_url, :with => %r{\.(gif|jpg|png)$}i,
:message => "はGIF,JPG,PNG画像でなければなりません"
validates_uniqueness_of :name
has_many :products
end
|
# frozen_string_literal: true
class AddIndexToBooks < ActiveRecord::Migration[6.0]
def change
add_reference :books, :post_user, foreign_key: { to_table: :users }, default: "0"
end
end
|
require 'spec_helper'
describe Csv2hash::Validator do
let(:definition) do
Csv2hash::Definition.new([ { position: [0,0], key: 'name' } ], Csv2hash::Definition::MAPPING).tap do |definition|
definition.validate!
definition.default!
end
end
subject do
Csv2hash.new(definition, 'file_path').tap do |parser|
parser.instance_variable_set :@data_source, data_source
end
end
describe '#message' do
subject { Csv2hash.new double('definition', type: Csv2hash::Definition::COLLECTION), nil }
context 'string value' do
let(:rule) { { foo: 'bar', message: ':foo are value of foo key' } }
it 'substitue value of key' do
subject.send(:message, rule, nil, nil).should eql 'bar are value of foo key'
end
end
context 'array value' do
let(:rule) { { foo: ['bar', 'zone'], message: ':foo are values of foo key' } }
it 'substitue value of key' do
subject.send(:message, rule, nil, nil).should eql '["bar", "zone"] are values of foo key'
end
end
context 'with position' do
let(:rule) { { message: 'value not found on :position' } }
it 'substitue value of key' do
subject.send(:message, rule, 0, 2).should eql 'value not found on [0, 2]'
end
end
end
end
|
class AddProfilevidColumnToMembers < ActiveRecord::Migration
def change
add_column :members, :profilevid, :string
end
end
|
#!/usr/bin/env ruby
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'rubygems'
require 'json'
require 'pp'
require 'convert_cft_to_cat'
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: #{File.basename(__FILE__)} [options]"
opts.on('-f',
'--file FILE_NAME',
'Filename of the CFT file') { |v| options[:filename] = v }
opts.on('-h',
'--help', 'Display this screen') do
puts opts
exit
end
end.parse!
json = File.read(options[:filename])
output_file = options[:filename] + '.cat.rb'
cat_name = File.basename options[:filename], '.*'
convert_cft_to_cat json, output_file, cat_name
|
module Gubby
module Components
module Font
attr_accessor :font
attr_accessor :text
def load_font(window, font_name, height)
@font = Gosu::Font.new(window,font_name,height)
end
end
end
end |
FactoryBot.define do
factory :item do
title {"ヴィトンのシャツ"}
text {"10万円ほどで購入しました。飽きたので売ります。"}
brand_id {1}
status {3}
delivery_charge_id {2}
delivery_origin_id {3}
delivery_size {2}
delivery_method_id {1}
delivery_days {2}
price {100000}
end
end
|
#encoding: UTF-8
require_relative 'SpaceStationToUI'
require_relative 'ShotResult'
require_relative 'CardDealer'
require_relative 'Transformation'
require_relative 'SuppliesPackage'
require_relative 'Hangar'
module Deepspace
class SpaceStation
@@MAXFUEL = 100
@@SHIELDLOSSPERUNITSHOT = 0.1
def initialize (n, supplies, nMedals = 0, pendingDamage = nil, weapons = Array.new, shieldBoosters = Array.new, hangar = nil) # SpaceStation(n : string, supplies : SuppliesPackage)
@name = n
@ammoPower = supplies.ammoPower
@fuelUnits = supplies.fuelUnits
@shieldPower = supplies.shieldPower
@nMedals = nMedals
@pendingDamage = pendingDamage
@weapons = weapons
@shieldBoosters = shieldBoosters
@hangar = hangar
end
attr_reader :name, :ammoPower, :fuelUnits, :shieldPower, :nMedals, :pendingDamage, :weapons, :shieldBoosters, :hangar
def self.newCopy(station) # station : SpaceStation
sup = Deepspace::SuppliesPackage.new(station.ammoPower, station.fuelUnits, station.shieldPower)
new(station.name, sup, station.nMedals, station.pendingDamage.class.newCopy(station.pendingDamage), Array.new(station.weapons), Array.new(station.shieldBoosters), Hangar.newCopy(station.hangar))
end
def getUIversion
SpaceStationToUI.new(self)
end
def to_s
getUIversion.to_s
end
def assignFuelValue (f)
@fuelUnits = f <= @@MAXFUEL ? f : @@MAXFUEL
end
def cleanPendingDamage
if @pendingDamage != nil && @pendingDamage.hasNoEffect
@pendingDamage = nil
end
end
def receiveWeapon(w) # receiveWeapon(w : Weapon) : boolean
if @hangar != nil
@hangar.addWeapon(w) # true si tiene éxito, false si no
else
false
end
end
def receiveShieldBooster(s)
if @hangar != nil
@hangar.addShieldBooster(s) # true si tiene éxito, false si no
else
false
end
end
def receiveHangar(h)
if @hangar.nil?
@hangar = h
end
end
def discardHangar
@hangar = nil
end
def receiveSupplies(s) # s: SuppliesPackage
assignFuelValue(@fuelUnits + s.fuelUnits)
@shieldPower += s.shieldPower
@ammoPower += s.ammoPower
end
def setPendingDamage(d) # setPendingDamage(d : Damage) : void
@pendingDamage = d.adjust(@weapons, @shieldBoosters)
end
def mountWeapon(i) # mountWeapon(i : int) : void
if 0 <= i && i < @hangar.weapons.length
new_weapon = @hangar.weapons.delete_at(i) unless hangar.nil?
@weapons << new_weapon unless new_weapon.nil?
end
end
def mountShieldBooster(i) # mountShieldBooster(i : int) : void
if 0 <= i && i < @hangar.shieldBoosters.length
new_shield_booster = @hangar.shieldBoosters.delete_at(i) unless hangar.nil?
@shieldBoosters << new_shield_booster unless new_shield_booster.nil?
end
end
def discardWeaponInHangar (i)
if @hangar != nil && 0 <= i && i < @hangar.weapons.length
@hangar.removeWeapon(i)
end
end
def discardShieldBoosterInHangar (i)
if @hangar != nil && 0 <= i && i < @hangar.shieldBoosters.length
@hangar.removeShieldBooster(i)
end
end
def getSpeed
@fuelUnits / @@MAXFUEL
end
def move
@fuelUnits = @fuelUnits >= getSpeed ? @fuelUnits - getSpeed : 0
end
def validState
@pendingDamage.nil? || @pendingDamage.hasNoEffect
end
def cleanUpMountedItems
@weapons.delete_if {|x| x.uses == 0} unless @weapons.nil?
@shieldBoosters.delete_if {|x| x.uses == 0} unless @shieldBoosters.nil?
end
def fire
factor = 1.0
@weapons.each {|w| factor *= w.useIt} unless @weapons.nil?
@ammoPower*factor
end
def protection
factor = 1.0
@shieldBoosters.each {|s| factor *= s.useIt} unless @shieldBoosters.nil?
@shieldPower*factor
end
def receiveShot(shot) # receiveShot(shot : float) : ShotResult
myProtection = protection
if myProtection >= shot
@shieldPower = [0.0, @shieldPower - @@SHIELDLOSSPERUNITSHOT*shot].max
ShotResult::RESIST
else
shieldPower = 0.0
ShotResult::DONOTRESIST
end
end
def setLoot(loot) # setLoot(loot : Loot) : Transformation
dealer = CardDealer.instance
h = loot.nHangars
if h > 0
hangar = dealer.nextHangar
receiveHangar(hangar)
end
elements = loot.nSupplies
for i in 1..elements
sup = dealer.nextSuppliesPackage
receiveSupplies(sup)
end
elements = loot.nWeapons
for i in 1..elements
weap = dealer.nextWeapon
receiveWeapon(weap)
end
elements = loot.nShields
for i in 1..elements
sh = dealer.nextShieldBooster
receiveShieldBooster(sh)
end
medals = loot.nMedals
@nMedals += medals
if loot.spaceCity
Transformation::SPACECITY
elsif loot.efficient
Transformation::GETEFFICIENT
else
Transformation::NOTRANSFORM
end
end
def discardWeapon(i) # discardWeapon(i : int) : void
size = @weapons.length
if i >= 0 && i < size
w = @weapons.delete_at(i)
if @pendingDamage != nil
@pendingDamage.discardWeapon(w)
cleanPendingDamage
end
end
end
def discardShieldBooster(i) # discardShieldBooster(i : int) : void
size = @shieldBoosters.length
if i >= 0 && i < size
@shieldBoosters.delete_at(i)
if @pendingDamage != nil
@pendingDamage.discardShieldBooster # He quitado el parámetro de discardShieldBooster
cleanPendingDamage
end
end
end
# Especificación de acceso a métodos privados
private :assignFuelValue, :cleanPendingDamage
end
end
if $0 == __FILE__
=begin
require_relative 'SuppliesPackage'
require_relative 'Weapon'
require_relative 'WeaponType'
require_relative 'Hangar'
require_relative 'Damage'
my_space_station = Deepspace::SpaceStation.new("Nombre de mi estación", Deepspace::SuppliesPackage.new(27, 28, 29))
puts my_space_station.to_s
my_space_station.assignFuelValue(100)
puts my_space_station.to_s
puts
d = Deepspace::Damage.newNumericWeapons(3,3)
puts d.to_s
my_space_station.setPendingDamage(d)
puts my_space_station.to_s
my_space_station.cleanPendingDamage
puts my_space_station.to_s
puts
my_space_station.receiveHangar(Deepspace::Hangar.new(12))
puts my_space_station.to_s
my_space_station.receiveWeapon(Deepspace::Weapon.new(4, 5, 6))
puts my_space_station.to_s
my_space_station.receiveSupplies(Deepspace::SuppliesPackage.new(27, 28, 29))
puts my_space_station.to_s
puts
my_space_station.setPendingDamage(Deepspace::Damage.newSpecificWeapons(Array.new(3){Deepspace::WeaponType::MISSILE}, 1))
puts my_space_station.to_s
puts "\nCosa que quiero comprobar\n\n"
puts my_space_station.mountWeapon(0)
puts my_space_station.to_s
puts my_space_station.mountShieldBooster(3)
puts my_space_station.to_s
puts my_space_station.discardWeaponInHangar(0)
puts my_space_station.to_s
puts my_space_station.discardShieldBoosterInHangar(5)
puts my_space_station.to_s
puts my_space_station.getSpeed
puts my_space_station.move
puts my_space_station.validState
my_space_station.cleanUpMountedItems
puts my_space_station.to_s
=end
require_relative 'SuppliesPackage'
require_relative 'Weapon'
require_relative 'WeaponType'
require_relative 'Hangar'
require_relative 'Damage'
my_space_station = Deepspace::SpaceStation.new("Nombre de mi estación", Deepspace::SuppliesPackage.new(27, 28, 29))
puts my_space_station
puts
my_space_station.receiveHangar(Deepspace::Hangar.new(12))
puts my_space_station.to_s
my_space_station.receiveWeapon(Deepspace::Weapon.new(4, Deepspace::WeaponType::LASER, 6))
puts my_space_station.to_s
my_space_station.receiveSupplies(Deepspace::SuppliesPackage.new(27, 28, 29))
puts my_space_station.to_s
my_space_station.mountWeapon(0)
puts my_space_station
puts my_space_station.fire
puts my_space_station.protection
puts my_space_station.receiveShot(1.5)
my_space_station.setLoot(Deepspace::Loot.new(1,1,1,1,1))
puts my_space_station
my_space_station.discardWeapon(0)
my_space_station.discardShieldBooster(0)
end
|
namespace :store do
desc "delete all of books and database and store.json"
task :drop do
ShareBook.drop_books
ShareBook.drop_db
ShareBook.drop_json
end
end |
require 'digest/md5'
require 'tempfile'
# Asset versioning methods.
module RapperLite::Versioning
def needs_packaging?( type, name )
return true unless File.exists?( self.destination_path( type, name ) )
self.version( type, name ) != @definitions[type][name]["version"]
end
protected
# MD5 version of the concatenated raw asset package.
def version( type, name )
source_paths = self.file_paths( type, name )
destination_file = Tempfile.new( 'rapper' )
self.join_files( source_paths, destination_file.path )
version = Digest::MD5.file( destination_file.path ).to_s[0,7]
destination_file.unlink
version
end
def refresh_versions
[:css, :js].each do |type|
@definitions[type].each do |name, spec|
next if self.config_key?( name )
@definitions[type][name]["version"] = self.version( type, name )
end
end
end
end
|
class CreateAdicionals < ActiveRecord::Migration[5.2]
def change
create_table :adicionals do |t|
t.float :valorAdicional
t.string :descricaoAdicional
t.boolean :statusAdicional
t.timestamps
end
end
end
|
# You are given a two-digit integer n. Return the sum of its digits.
#
# Example
#
# For n = 29, the output should be
# addTwoDigits(n) = 11.
#
# Input/Output
#
# [execution time limit] 4 seconds (rb)
#
# [input] integer n
#
# A positive two-digit integer.
#
# Guaranteed constraints:
# 10 ≤ n ≤ 99.
#
# [output] integer
#
# The sum of the first and second digits of the input number.
def addTwoDigits(n)
first, second = n.to_s.split('')
first.to_i + second.to_i
end
|
ActionController::Base.helper(Bilson::Fileman)
Hash.class_eval do
def classed_values
new_opts = {}
each do |k,v|
if v == 'true'
new_opts[k.to_sym] = true
elsif v == 'false'
new_opts[k.to_sym] = false
elsif v.class == Hash
new_opts[k.to_sym] = v.classed_values
elsif v.represents_f?
new_opts[k.to_sym] = v.to_f
elsif v.represents_i?
new_opts[k.to_sym] = v.to_i
else
new_opts[k.to_sym] = v
end
end
return new_opts
end
end
String.class_eval do
# Does this value represent an integer?
def represents_i?
i_value = self.to_i
# is the string converted to int not equal to zero (because it might be a string)
if i_value != 0
# are we sure this isn't actually a float?
if (i_value - self.to_f) == 0
true
else
false
end
elsif i_value == 0
# is the value equal to the int value converted to_s?
if self == i_value.to_s
true
else
false
end
end
end
# Does this value represent a float?
def represents_f?
f_value = self.to_f
# is this not equal to zero and also not actually an integer?
if (f_value != 0) && (f_value.to_s == self)
true
else
false
end
end
end |
##
## data-utils/like-hash.rb
##
## Add Hash-like behavior to a class.
##
require 'brewed'
module Brewed
module LikeHash
##
# Retrieve a specified property from this object.
#
# Hash objects provide {Hash#fetch} in order to retrieve the value of
# a key. In order to simplify code which accepts either a {Hash} or
# an {Object}, provide {Object#fetch}.
#
# {Object#fetch} uses +respond_to?+ to check if this
# {Object} will respond to the property. If so, {Object#fetch}
# returns the result of +send(property)+. Otherwise, returns +nil+.
#
# @param property [Symbol]
# @return [nil, Object]
#
# @example Fetch the value of a property
# id_val = track.fetch(:id)
##
def fetch(prop)
prop = prop.to_sym if prop.is_a? String
raise "expected String or Symbol for property, got: '#{prop.to_s}'" unless
prop.is_a? Symbol
(self.respond_to? prop) ? self.send(prop) : nil
end
alias :'key?' fetch
##
# Provides the +[]+ operator for {Object}.
#
# @param prop [String, Symbol]
# @return [String, Integer, DateTime]
#
# @example Get the value of :id property
# id_val = track[:id]
##
def [](prop)
prop = prop.to_sym if prop.is_a? String
raise "expected String or Symbol for property, got: '#{prop.to_s}'" unless
prop.is_a? Symbol
(self.respond_to? prop) ? self.send(prop) : nil
end
##
# Provides the +[]=+ operator for {Object}.
#
# @param prop [String, Symbol]
# @param value [Object]
##
def []=(prop, val)
self.send :"#{prop}=", val
end
##
# Construct a +Hash+ from this object's instance variables.
#
# @note Although we use instance_variables to retrieve the names of
# the object's instance variables, we actually retrieve the
# instance variable's value by invoking the accessor method.
# This way we don't bypass anything special that's handled by
# the accessors.
#
# @param props [Array<String, Symbol>]
# (Optional) restrict +Hash+ keys to these properties
#
# @return [Hash]
#
# @example Construct a Hash from a +track_obj+ obj
# track_obj.as_hash
# @example Construct a Hash from particular properties of +track_obj+
# track_obj.as_hash(:title, :composer)
##
def as_hash(*props)
syms =
if props.length == 0
# retrieve the instance variables and chop off the leading '@'.
# discard any variables whose name begins with '_'
self.instance_variables.map do |ivar|
sym = ivar[1...ivar.length]
sym[0] == '_' ? [] : sym
end.flatten
else
# in this case, we do NOT discard properties whose names begin with '_'
props.map { |p| p.to_sym }
end
hash = {}
syms.each do |sym|
hash[sym] = (self.respond_to? sym) ? self.send(sym) : nil
end
hash
end
##
# Set instance variables of this object using the key, value
# pairs of a Hash.
#
# @note For each key in the Hash, if the object has a writer
# accessor method whose name matches the key, we call the
# writer accessor method. Otherwise, we fall back to
# instance_variable_set.
#
# @note After all of the properties from the +Hash+ have been set,
# +self.to_integers!+ is called.
#
# @param props [Hash]
# @return [self]
##
def from_hash!(props = {})
props.each_pair do |k, v|
writer = :"#{k}="
if self.respond_to? writer
self.send writer, v
else
self.instance_variable_set(:"@#{k}", v)
end
end
self.to_integers!
end
##
# Update instance variables of this object from the named
# captures of a MatchData object.
#
##
def from_matchdata!(md)
md.names.each do |nm|
writer = :"#{nm}="
if self.respond_to? writer
self.send writer, md[nm]
else
isym = :"@#{nm}"
self.instance_variable_set(isym, md[nm]) if
self.instance_variable_defined? isym
end
end
self.to_integers!
end
##
# Set instance variables of this object using parallel arrays: an
# array of property names and an array of values.
#
# @param props [Array<Symbol>]
# @param values [Array<Object>]
# @return [self]
##
def from_arrays!(props, values)
raise "the properties array and the values array must be the same length" unless
props.length == values.length
props.each_with_index do |p, index|
writer = :"#{p}="
if self.respond_to? writer
self.send writer, values[index]
else
self.instance_variable_set(:"@#{p}", values[index])
end
end
self.to_integers!
end
##
# Given a list of properties (keys) of this object, convert the
# values for each property to an integer.
#
# If no properties are specified, to_integers!() looks for a
# constant named INTEGER_PROPERTIES in the object's class.
# If this constant exists, those properties have their values
# converted.
#
# @param properties [Array<Symbol>]
# (Optional) list of this object's properties to convert to integers
#
# @example Convert specified properties' values to integers
# process_obj.to_integers! :uid, :pid
# @example Convert all properties listed in INTEGER_PROPERTIES
# process_obj.to_integers!
##
def to_integers!(*properties)
myclass = self.class
props =
if properties.length == 0
# pull the list of integer properties from the
# class constant INTEGER_PROPERTIES
(myclass.constants.include? :INTEGER_PROPERTIES) ?
myclass.const_get(:INTEGER_PROPERTIES) :
[]
elsif properties.length == 1 and properties[0].is_a? Array
properties.first
else
properties
end
props.each do |p|
prop = :"@#{p}"
self.instance_variable_set prop, self.instance_variable_get(prop).to_i
end
self
end
##
# Given an array of names of instance variables, construct an Array of the
# values of this object's instance variables.
#
# @param properties [Array<Symbol>]
# @return [Array<Object>]
##
def values_at(*properties)
raise "no properties were specified" if properties.length == 0
props = (properties.length == 1 and properties[0].is_a? Array) ? properties.first : properties
props.map { |p| self.instance_variable_get :"@#{p}" }
end
end
end
|
require('pg')
require_relative('../db/sql_runner')
class Movie
attr_reader :id
attr_accessor :title, :genre
def initialize(options)
@id = options['id'].to_i() if options['id']
@title = options['title']
@genre = options['genre']
end
def save()
sql = "INSERT INTO movies (title, genre)
VALUES ($1, $2)
RETURNING id"
values = [@title, @genre]
results = SqlRunner.run(sql, values)
@id = results[0]["id"].to_i
end
def update()
sql = "UPDATE movies SET (title, genre) = ($1, $2) WHERE id = $3"
values = [@title, @genre, @id]
SqlRunner.run(sql, values)
end
def self.delete_all()
sql = "DELETE FROM movies"
SqlRunner.run(sql)
end
def stars
sql = "SELECT stars.*
FROM stars
INNER JOIN castings
ON castings.star_id = stars.id
WHERE movie_id = $1"
values = [@id]
movies = SqlRunner.run(sql, values)
result = movies.map { |star| Star.new (star) }
return result
end
end
|
# frozen_string_literal: true
require 'system_spec_helper'
require 'net/scp'
require 'open-uri'
RSpec.describe '#import database' do
context 'copy dump' do
before(:context) do
@project_name = 'magento_1_9_sample'
@project_file_path = ROOT_DIR + '/config/project/' + @project_name + '.json'
@random_string = '2949d3e2173b25a55968f45518e4779d'
@table_name = 'sales_flat_order_address'
@column_name = 'postcode'
@column_type = 'firstname'
@new_table_name = 'some_new_table'
@new_column_name = 'some_column'
@new_column_type = 'firstname'
@default_action = 'update'
open('/tmp/' + @project_name + '.sql.gz', 'wb') do |f|
f << open('https://github.com/DivanteLtd/anonymizer/files/2135881/' + @project_name + '.sql.gz').read
end
config = JSON.parse(
'{
"type": "extended",
"basic_type": "magento_1_9",
"random_string": "' + @random_string + '",
"dump_server": {
"host": "",
"user": "",
"port": "",
"passphrase": "",
"path": "/tmp",
"rsync_options": ""
},
"tables": {
"' + @table_name + '": {
"' + @column_name + '": {
"type": "' + @column_type + '",
"action": "' + @default_action + '"
}
},
"' + @new_table_name + '": {
"' + @new_column_name + '": {
"type": "' + @new_column_type + '",
"action": "' + @default_action + '"
}
}
}
}'
)
File.open(@project_file_path, 'w') do |f|
f.write(config.to_json)
end
@anonymizer = Anonymizer.new @project_name
end
# it 'should exists user private key' do
# expect(File.exist?(ENV['HOME'] + '/.ssh/id_rsa')).to be true
# end
it 'should be loadded extension net/ssh and net/scp' do
expect(Object.const_defined?('Net::SSH')).to be true
expect(Object.const_defined?('Net::SCP')).to be true
end
it 'should has data necessary to connect to remote server' do
expect(@anonymizer.config['dump_server']['host'].is_a?(String)).to be true
expect(@anonymizer.config['dump_server']['user'].is_a?(String)).to be true
expect(@anonymizer.config['dump_server']['port'].is_a?(String)).to be true
end
# it 'should be possible connect to remote server' do
# expected = expect do
# Net::SSH.start(
# @anonymizer.config['dump_server']['host'],
# @anonymizer.config['dump_server']['user'],
# port: @anonymizer.config['dump_server']['port'],
# passphrase: @anonymizer.config['dump_server']['passphrase']
# )
# end
# expected.not_to raise_error
# end
it 'should be possible copy project dump' do
system(
ShellHelper.download_dump(
@project_name,
{
host: @anonymizer.config['dump_server']['host'],
port: @anonymizer.config['dump_server']['port'],
user: @anonymizer.config['dump_server']['user'],
dump_dir: @anonymizer.config['dump_server']['path']
},
'/tmp',
@anonymizer.config['dump_server']['rsync_options']
)
)
expect(File.exist?("/tmp/#{@project_name}.sql.gz")).to be true
end
after(:context) do
FileUtils.rm_f(@project_file_path)
FileUtils.rm_f('/tmp/' + @project_name + '.sql.gz')
end
end
end
|
module Celluloid
# Supervise collections of actors as a group
class SupervisionGroup
include Celluloid
trap_exit :restart_actor
class << self
# Actors or sub-applications to be supervised
def blocks
@blocks ||= []
end
# Start this application (and watch it with a supervisor)
def run!(registry = nil)
group = new(registry) do |_group|
blocks.each do |block|
block.call(_group)
end
end
group
end
# Run the application in the foreground with a simple watchdog
def run(registry = nil)
loop do
supervisor = run!(registry)
# Take five, toplevel supervisor
sleep 5 while supervisor.alive?
Logger.error "!!! Celluloid::SupervisionGroup #{self} crashed. Restarting..."
end
end
# Register an actor class or a sub-group to be launched and supervised
# Available options are:
#
# * as: register this application in the Celluloid::Actor[] directory
# * args: start the actor with the given arguments
def supervise(klass, options = {})
blocks << lambda do |group|
group.add klass, options
end
end
# Register a pool of actors to be launched on group startup
# Available options are:
#
# * as: register this application in the Celluloid::Actor[] directory
# * args: start the actor pool with the given arguments
def pool(klass, options = {})
blocks << lambda do |group|
group.pool klass, options
end
end
end
finalizer :finalize
# Start the group
def initialize(registry = nil)
@members = []
@registry = registry || Celluloid.actor_system.registry
yield current_actor if block_given?
end
execute_block_on_receiver :initialize, :supervise, :supervise_as
def supervise(klass, *args, &block)
add(klass, :args => args, :block => block)
end
def supervise_as(name, klass, *args, &block)
add(klass, :args => args, :block => block, :as => name)
end
def pool(klass, options = {})
options[:method] = 'pool_link'
add(klass, options)
end
def add(klass, options)
member = Member.new(@registry, klass, options)
@members << member
member.actor
end
def actors
@members.map(&:actor)
end
def [](actor_name)
@registry[actor_name]
end
# Restart a crashed actor
def restart_actor(actor, reason)
member = @members.find do |_member|
_member.actor == actor
end
raise "a group member went missing. This shouldn't be!" unless member
if reason
member.restart
else
member.cleanup
@members.delete(member)
end
end
# A member of the group
class Member
def initialize(registry, klass, options = {})
@registry = registry
@klass = klass
# Stringify keys :/
options = options.inject({}) { |h,(k,v)| h[k.to_s] = v; h }
@name = options['as']
@block = options['block']
@args = options['args'] ? Array(options['args']) : []
@method = options['method'] || 'new_link'
@pool = @method == 'pool_link'
@pool_size = options['size'] if @pool
start
end
attr_reader :name, :actor
def start
# when it is a pool, then we don't splat the args
# and we need to extract the pool size if set
if @pool
options = {:args => @args}
options[:size] = @pool_size if @pool_size
@args = [options]
end
@actor = @klass.send(@method, *@args, &@block)
@registry[@name] = @actor if @name
end
def restart
@actor = nil
cleanup
start
end
def terminate
cleanup
@actor.terminate if @actor
rescue DeadActorError
end
def cleanup
@registry.delete(@name) if @name
end
end
private
def finalize
@members.reverse_each(&:terminate) if @members
end
end
end
|
require 'spec_helper'
describe "Places" do
it "shows a place if one is returned by the API" do
BeermappingAPI.stub(:places_in).with("kumpula").and_return([Place.new(name: "Oljenkorsi")])
visit places_path
fill_in('city', with: 'kumpula')
click_button "Search"
expect(page).to have_content "Oljenkorsi"
end
it "shows all places if multiple returned by the API" do
BeermappingAPI.stub(:places_in)
.with("arabia")
.and_return([Place.new(name: "Oljenkorsi"), Place.new(name: "Olotila")])
visit places_path
fill_in('city', with: 'arabia')
click_button "Search"
expect(page).to have_content "Oljenkorsi"
expect(page).to have_content "Olotila"
end
it "shows none if API returns empty list" do
BeermappingAPI.stub(:places_in)
.with("rovaniemi")
.and_return([])
visit places_path
fill_in('city', with: 'rovaniemi')
expect(page).to_not have_content('id')
end
end
|
# == Schema Information
#
# Table name: attachments
#
# id :integer not null, primary key
# asset_file_name :string(255)
# asset_content_type :string(255)
# asset_file_size :integer
# asset_updated_at :datetime
# attachable_id :integer
# attachable_type :string(255)
# type :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class HeroImage < Attachment
has_attached_file :asset,
:styles => { :large => '', :thumbnail => ''},
:convert_options => {
:large => '-gravity center -thumbnail 1000x300^ -extent 1000x300',
:thumbnail => '-gravity center -thumbnail 150x150^ -extent 150x150' }
def image size = :large
self.asset.url(size)
end
end
|
require 'tether/types/any'
module Tether
module Types
class Function < Any
def to_s
'<function>'
end
end
end
end
|
# Required
set_default :slack_url, -> { ENV['SLACK_URL'] }
set_default :slack_room, -> { ENV['SLACK_ROOM'] }
# Optional
set_default :slack_stage, -> { ENV['SLACK_STAGE'] || fetch(:rails_env, 'production') }
set_default :slack_application, -> { ENV['SLACK_APPLICATION'] || application }
set_default :slack_username, -> { ENV['SLACK_USERNAME'] || 'deploybot' }
set_default :slack_emoji, -> { ENV['SLACK_EMOJI'] || ':cloud:' }
# Git
set_default :deployer, -> { ENV['GIT_AUTHOR_NAME'] || %x[git config user.name].chomp }
set_default :deployed_revision, -> { ENV['GIT_COMMIT'] || %x[git rev-parse #{branch}].strip }
|
require "./osm_object.rb"
# Convert OSMPBF::DenseNode to OSM::Node
def convert_dense_node block
node_set = block.primitivegroup[0].dense
string_table = block.stringtable.s
decode_dense_nodes node_set, string_table
end
def decode_dense_nodes dense_nodes, string_table
dense_info = dense_nodes.denseinfo
node_range = 0..(dense_nodes.id.size - 1)
kv_max = dense_nodes.keys_vals.size - 1
id = 0
uid = 0
user_sid = 0
timestamp = 0
lat = 0
lon = 0
kv_now = 0
changeset = 0
visible = 0
node_range.map { |idx|
uid += dense_info.uid[idx]
user_sid += dense_info.user_sid[idx]
timestamp += dense_info.timestamp[idx]
version = dense_info.version[idx]
changeset += dense_info.changeset[idx]
visible += dense_info.visible[idx] if dense_info.visible.size > 0
id += dense_nodes.id[idx]
lat += dense_nodes.lat[idx]
lon += dense_nodes.lon[idx]
tags = {}
(kv_now..kv_max)
.take_while { |idx| dense_nodes.keys_vals[idx] != 0 }
.map { |idx| dense_nodes.keys_vals[idx] }
.each_slice(2) { |pair|
tags[string_table[pair[0]]] = string_table[pair[1]]
}
if tags.size == 0 then
kv_now += 1
else
kv_now += tags.size * 2
end
user = string_table[user_sid]
if visible == 0 then
OSM::Node.new(id, uid, user, timestamp, lat, lon, tags, version, changeset)
else
OSM::Node.new(id, uid, user, timestamp, lat, lon, tags, version, changeset, visible)
end
}
end
# Convert OSMPBF::Way to OSM::Way
def convert_dense_node block
way_set = block.primitivegroup[0].ways
string_table = block.stringtable.s
decode_way way_set, string_table
end
def decode_way way_set, string_table
way_set.map { |way|
ref = 0
refs = way.refs.map { |x| ref += x }
tags = way.keys
.zip(way.vals)
.map { |x| x.map! { |y| string_table[y] } }
.to_h
if way.info == nil then
OSM::Way.new(way.id, nil, nil, nil, tags, refs, nil, nil, nil)
else
# TODO local var in block
OSM::Way.new(way.id, way.info.uid, string_table[way.info.user_sid], way.info.timestamp, tags, refs, way.info.version, way.info.changeset, way.info.visible)
end
}
end
|
# frozen_string_literal: true
RSpec.describe 'solr phrase relevance spec' do
it 'does appropriate phrase searches for keyword Black Lives Matter' do
relevant_id = '541433'
irrelevant_id = '502167'
resp = solr_resp_doc_ids_only({ 'q' => 'black lives matter' })
expect(resp).to include(relevant_id).before(irrelevant_id)
end
it 'search for keyword Digital Divide' do
relevant_ids = %w[556265 529813 524094 344167]
resp = solr_resp_doc_ids_only({ 'q' => 'digital divide' })
expect(resp).to include(relevant_ids).in_first(6).results
end
it 'search for keyword Love and Fear' do
resp = solr_resp_doc_ids_only({ 'q' => 'Love and Fear' })
relevant_id = '591432'
expect(resp).to include(relevant_id).as_first
end
end
|
class Student < ActiveRecord::Base
validates :name, :lateness, :class_id, presence: true
belongs_to :classroom,
primary_key: :id,
foreign_key: :class_id,
class_name: :ClassName
end
|
class Movie < Neo4j::Rails::Model
property :name, :index => :exact, :unique => true
has_n(:actors).from(Actor, :acted_in)
def actors_in_movie
actors = []
self.actors_rels.map{|actor|
actors << actor.start_node.name
}
return actors
end
end |
if defined?(Merb::Plugins)
$:.unshift File.dirname(__FILE__)
load_dependency 'merb-slices'
require 'mauth-core'
Merb::Plugins.add_rakefiles "mauth_password_slice/merbtasks", "mauth_password_slice/slicetasks", "mauth_password_slice/spectasks"
# Register the Slice for the current host application
Merb::Slices::register(__FILE__)
# Slice configuration - set this in a before_app_loads callback.
# By default a Slice uses its own layout, so you can swicht to
# the main application layout or no layout at all if needed.
#
# Configuration options:
# :layout - the layout to use; defaults to :mauth_password_slice
# :mirror - which path component types to use on copy operations; defaults to all
Merb::Slices::config[:mauth_password_slice][:layout] ||= :application
# All Slice code is expected to be namespaced inside a module
module MauthPasswordSlice
# Slice metadata
self.description = "MauthPasswordSlice is a merb slice that provides basic password based logins"
self.version = "0.0.1"
self.author = "Daniel Neighman"
# Stub classes loaded hook - runs before LoadClasses BootLoader
# right after a slice's classes have been loaded internally.
def self.loaded
end
# Initialization hook - runs before AfterAppLoads BootLoader
def self.init
end
# Activation hook - runs after AfterAppLoads BootLoader
def self.activate
raise "Please set the :user_class option for MauthPasswordSlice" unless MPS[:user_class]
MPS[:login_field] ||= {:label => "Login", :method => :login}
MPS[:password_field] ||= {:label => "Password", :method => :password}
# This is where the work happens when users login
Authentication.login_strategies.add(:password_login_from_form) do
MPS[:user_class].authenticate(params[:login], params[:password])
end
Authentication.login_strategies.add(:password_login_basic_auth) do
basic_authentication.authenticate do |login, password|
MPS[:user_class].authenticate(login, password)
end
end
end
# Deactivation hook - triggered by Merb::Slices.deactivate(MauthPasswordSlice)
def self.deactivate
end
# Setup routes inside the host application
#
# @param scope<Merb::Router::Behaviour>
# Routes will be added within this scope (namespace). In fact, any
# router behaviour is a valid namespace, so you can attach
# routes at any level of your router setup.
#
# @note prefix your named routes with :mauth_password_slice_
# to avoid potential conflicts with global named routes.
def self.setup_router(scope)
# example of a named route
# scope.match('/index.:format').to(:controller => 'main', :action => 'index').name(:mauth_password_slice_index)
scope..match("/login", :method => :put).to(:controller => "sessions", :action => "update").name(:mauth_perform_login)
# scope.parent.match("/login", :method => :get).to(:controller => "exceptions", :action => "unauthenticated")
# scope.parent.match("/logout").to(:controller => "sessions", :action => "destroy").name(:logout)
end
end
# Setup the slice layout for MauthPasswordSlice
#
# Use MauthPasswordSlice.push_path and MauthPasswordSlice.push_app_path
# to set paths to mauth_password_slice-level and app-level paths. Example:
#
# MauthPasswordSlice.push_path(:application, MauthPasswordSlice.root)
# MauthPasswordSlice.push_app_path(:application, Merb.root / 'slices' / 'mauth_password_slice')
# ...
#
# Any component path that hasn't been set will default to MauthPasswordSlice.root
#
# Or just call setup_default_structure! to setup a basic Merb MVC structure.
MauthPasswordSlice.setup_default_structure!
MPS = MauthPasswordSlice
# Add dependencies for other MauthPasswordSlice classes below. Example:
# dependency "mauth_password_slice/other"
end |
class CheckfrontDatum < ApplicationRecord
BOOKING_URL = "/api/3.0/booking/"
ITEM_URL = "/api/3.0/item/"
CATEGORY_URL = "/api/3.0/category/"
BOOKING_UPDATE_URL = "/api/3.0/booking/[id]/update"
validates_inclusion_of :singleton_guard, :in => [0]
def self.instance
begin
find(1)
rescue ActiveRecord::RecordNotFound
row = CheckfrontDatum.new
row.singleton_guard = 0
row.save!
row
end
end
def self.get_and_save_latest_bookings
bookings_hash = self.get_bookings_in_the_future
booking_ids = []
bookings_hash.each do |key, bookings|
booking_ids.push(bookings["booking_id"])
end
bookings = []
booking_ids.each do |booking_id|
bookings.push(self.get_booking_by_id booking_id)
end
self.instance.update_attribute(:bookings, bookings)
end
def self.update_booking booking
bookings = eval(CheckfrontDatum.instance.bookings)
bookings.each do |source_booking|
if source_booking["id"] == booking["id"]
bookings = bookings - [source_booking]
bookings << booking
end
end
self.instance.update_attribute(:bookings, bookings)
end
## Methods connecting with Checkfront
#BOOKINGS
def self.get_bookings_in_the_future
url = ENV['HOST'] + BOOKING_URL
end_date = {end_date: ">#{Time.zone.now.beginning_of_day.to_i}"}
@bookings = (Connection.post_json_response url, end_date)["booking/index"]
if not @bookings
return []
else
return @bookings
end
end
def self.get_booking_by_id id
url = ENV['HOST'] + BOOKING_URL + id.to_s
@booking = (Connection.get_json_response url)["booking"]
end
def self.booking_change_param booking_id, name, value
url = ENV['HOST'] + BOOKING_UPDATE_URL
url.sub!("[id]", booking_id.to_s)
update_param = {name => value}
Connection.post_json_response url, update_param
return self.get_booking_by_id booking_id
end
def self.booking_change_status booking_id, value
url = ENV['HOST'] + BOOKING_UPDATE_URL
url.sub!("[id]", booking_id.to_s)
status = {status_id: value, notify: 1}
Connection.post_json_response url, status
return self.get_booking_by_id booking_id
end
#ITEMS
def self.get_item_by_id id
url = ENV['HOST'] + ITEM_URL + id.to_s
@item = (Connection.get_json_response url)["item"]
end
end
|
# == Schema Information
#
# Table name: suggestions
#
# id :integer not null, primary key
# title :string
# desc :text
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Suggestion < ActiveRecord::Base
include DestoryComments
acts_as_commontable
validates :title, :desc, presence: true
####
# filterrific gem for search sort and pagination
####
self.per_page = 10
filterrific(
default_filter_params: { sorted_by: 'created_at_desc' },
available_filters: [
:sorted_by,
:search_query,
:date_on
]
)
scope :search_query, lambda { |query|
return nil if query.blank?
# condition query, parse into individual keywords
terms = query.to_s.downcase.split(/\s+/)
# replace "*" with "%" for wildcard searches,
# append '%', remove duplicate '%'s
terms = terms.map do |e|
('%' + e.tr('*', '%') + '%').gsub(/%+/, '%')
end
# configure number of OR conditions for provision
# of interpolation arguments. Adjust this if you
# change the number of OR conditions.
num_or_conditions = 2
where(
terms.map do
or_clauses = [
'LOWER(suggestions.title) LIKE ?',
'LOWER(suggestions.desc) LIKE ?'
].join(' OR ')
"(#{or_clauses})"
end.join(' AND '),
*terms.map { |e| [e] * num_or_conditions }.flatten
)
}
scope :sorted_by, lambda { |sort_key|
direction = sort_key =~ /desc$/ ? 'desc' : 'asc'
case sort_key.to_s
when /^created_at_/
order("suggestions.created_at #{direction}")
when /^name_/
order("LOWER(suggestions.title) #{direction}")
else
raise(ArgumentError, "Invalid sort option: #{sort_key.inspect}")
end
}
scope :date_on, lambda { |ref_date|
where('suggestions.created_at >= ?', ref_date)
}
end
|
require '~/projects/battleships/lib/ship_class.rb'
class Player
attr_reader :ship_positions, :hits_array, :miss_array, :ships
def initialize
@ships = []
@ship_positions = []
@hits_array = []
@miss_array = []
end
def place ship
@ship_positions.flatten.each do |ship_pos|
ship.position.each {|coor| fail 'That position is taken. Choose another.' if coor == ship_pos}
end
@ships << ship
@ship_positions << ship.position
end
def fire target
hit_ship = @ships.find {|ship| ship.position.include?(target)}
if hit_ship != nil
hit_ship.hits += 1
@ship_positions.each{|ship| ship.delete(target) if ship.include?(target)}
@ship_positions.delete_if{|ship| ship.empty?}
@hits_array << target
ships_left
"Hit"
else
@miss_array << target
"Miss"
end
# if @ship_positions.include?(target)
# @hits_array << target
# @ship_positions.delete(target)
# if @ship_positions.empty?
# fail 'Game over, Player loses.'
# else
# "Hit"
# end
# else
# @miss_array << target
# "Miss"
# end
end
def ships_left
fail 'Game over, Player loses.' if @ship_positions.empty?
end
end |
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
config.vm.provision "shell", inline: <<-SHELL
dpkg --add-architecture i386
cp /etc/apt/sources.list /etc/apt/sources.list.old
# mirror.0x.sg is currently down
# sed -i -e 's/archive\.ubuntu\.com/mirror\.0x\.sg/g' /etc/apt/sources.list
apt-get update
apt-get install -y wget libc6:i386 libncurses5:i386 libstdc++6:i386 gdb python python-pip libssl-dev gcc git binutils socat apt-transport-https ca-certificates libc6-dev-i386 python-capstone libffi-dev
pip install --upgrade pip
pip install ropgadget
pip install pwntools
pip install ipython
pip install ropper
# wget -q -O- https://github.com/hugsy/gef/raw/master/gef.sh | sh # old link
wget -q -O- https://github.com/hugsy/gef/raw/master/scripts/gef.sh | sh
git clone https://github.com/niklasb/libc-database.git /home/ubuntu/libc-database
cd /home/ubuntu/libc-database
/home/ubuntu/libc-database/add /lib/i386-linux-gnu/libc.so.6
/home/ubuntu/libc-database/add /lib/x86_64-linux-gnu/libc.so.6
apt-get update
SHELL
end
|
require "spec_helper"
describe AdaptivePayments::ExecutePaymentRequest do
it_behaves_like "a RequestEnvelope"
subject { AdaptivePayments::ExecutePaymentRequest }
its(:operation) { should == :ExecutePayment }
let(:request) do
AdaptivePayments::ExecutePaymentRequest.new(
:action_type => "PAY",
:pay_key => "ABCD-1234",
:funding_plan_id => "funding123"
)
end
let(:json) { JSON.parse(request.to_json) }
it "maps #action_type to ['actionType']" do
json["actionType"].should == "PAY"
end
it "maps #pay_key to ['payKey']" do
json["payKey"].should == "ABCD-1234"
end
it "maps #funding_plan_id to ['fundingPlanId']" do
json["fundingPlanId"].should == "funding123"
end
end
|
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# Copyright (C) 2010,2011 Yasuhiro ABE <yasu@yasundial.org>
@basedir = File::dirname($0)
require 'rubygems'
require 'bundler/setup'
require 'yalt'
include YALTools::CmdLine
require 'optparse'
def option_parser
ret = {
:filename => "-",
:outfile => "-",
:exclude => false,
:keys => nil,
:debug=>false,
}
OptionParser.new do |opts|
opts.banner = <<-EOF
Usage: #{File::basename($0)} '[json_array]' [-f file] [-o outfile] [-e] [-d] [-h]
#{File::basename($0)} is a tool to print selected key-value pairs of lines.
'[json_array]' will be parsed by JSON.parse('[json_array]').
Example:
$ cat a.json | #{File::basename($0)} '["_id","_rev"]'
{"_id":"0009b95b502e69672","_rev":"2-da6c42c8a7dfd0de46ef1d3d309928b8"}
{"_id":"0009d6d3b0e5d9863","_rev":"2-770eaf3a5c729c52574d7a7bc59ef6d6"}
EOF
opts.separator ''
opts.on('-f', '--file filename', "Set input filename or '-' (default: '-').") { |f|
ret[:filename] = f if FileTest.exist?(f)
ret[:filename] = f if f == "-"
}
opts.on('-o', '--outfile outfile', "Set output filename or '-' (default: '-').") { |f|
ret[:outfile] = f
}
opts.on('-e', '--exclude-mode', 'Argument, json_array, is used as the exclude list. (almost same as "grep -v")') { |r|
ret[:exclude] = r
}
opts.on('-d', '--debug', 'Enable the debug mode') { |d|
ret[:debug] = d
}
opts.on_tail('-h', '--help', 'Show this message') {
$stderr.puts opts
exit
}
begin
opts.parse!(ARGV)
ret[:keys] = JSON.parse(ARGV[0]) if ARGV.length == 1
rescue
$stderr.puts opts
$stderr.puts
$stderr.puts "[error] #{$!}"
exit(1)
end
if ret[:keys] == ""
$stderr.puts opts
exit(1)
end
end
return ret
end
@opts = option_parser
## parse labels
require 'json'
## let's start
begin
load_line(@opts[:filename]) do |line|
json = line_to_json(line)
ret = nil
if @opts[:exclude]
ret = YALTools::ProcJson::exclude_value_from_json(json, @opts[:keys])
else
ret = YALTools::ProcJson::select_value_from_json(json, @opts[:keys])
end
save_data(ret.to_json, @opts[:outfile])
end
ensure
$stderr.puts $! if @opts[:debug]
exit
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
after_filter :set_online
def all_who_are_in_touch
$redis_onlines.keys
end
private
def set_online
$redis_onlines.set( current_user.id, nil, ex: 5*60 ) if !!current_user
end
end
|
class VideosController < ApplicationController
#before_filter :fake_login
before_filter :setup_youtube
def me
if user_signed_in? then
### videos I like
videos_i_like = get_videos_i_like()
update_videos_i_like_in_database(videos_i_like)
### videos I posted
videos_i_posted = get_videos_i_posted()
update_videos_i_posted_in_database(videos_i_posted)
###
out = current_user.videos.find(:all, :conditions => "deleted = false")
out = sort_by_dateish(out)
render json: out
else
render json: []
end
end
def friend
if user_signed_in? then
friend = User.find(:first, :conditions => "uid = #{params[:id]}")
if friend.nil? then
render json: []
else
videos = friend.videos.find(:all, :conditions => "deleted = false")
render json: (videos.nil? || videos.count == 0) ? [] : sort_by_dateish(videos)
end
else
render json: []
end
end
def friends
if user_signed_in? then
render json: get_friends
else
render json: []
end
end
def toggle_starred
video = Video.find(params[:id])
video.starred = !video.starred
video.save
render :text => "bella"
end
def toggle_hidden
video = Video.find(params[:id])
video.hidden = !video.hidden
video.save
render :text => "yo"
end
private
def sort_by_dateish(list)
with_date = list.find_all{|x| x[:action_date].nil? == false}.sort_by{|x|x[:action_date]}
without_date = list.find_all{|x| x[:action_date].nil?}.sort_by{|x|x.id}.reverse
map_factor = without_date.count.to_f / (with_date.count+1)
(0...without_date.count).each {|i|
with_date.insert([i * map_factor, with_date.count].min , without_date[i])
}
with_date.reverse
end
def get_friends
rest = Koala::Facebook::API.new(current_user.authentications.first.token)
rest.graph_call("me/friends")
end
def get_videos_i_like
rest = Koala::Facebook::API.new(current_user.authentications.first.token)
rest.fql_query("SELECT url FROM url_like WHERE user_id = me() AND strpos(lower(url), 'http://www.youtube.com/') == 0")
end
def get_videos_i_posted
rest = Koala::Facebook::API.new(current_user.authentications.first.token)
rest.fql_query("SELECT created_time, url FROM link WHERE owner = me() AND strpos(lower(url), 'http://www.youtube.com/') == 0")
end
def update_videos_i_like_in_database(videos_i_like)
videos_i_like.each do |video|
if Video.find(:first, :conditions => "video_url = '#{video["url"]}'").nil? then
v = current_user.videos.new
v.video_url = video["url"]
v.video_type = "facebook_like"
v.deleted = video_deleted_on_youtube video["url"]
v.save
end
end
end
def setup_youtube
require 'youtube_it'
@youtube = YouTubeIt::Client.new
end
def video_deleted_on_youtube(url)
video_deleted = false
begin
video_youtube_id = url.scan(/v\=([^\&\#]+)/)[0][0]
@youtube.video_by video_youtube_id
rescue
video_deleted = true
end
video_deleted || Video.video_blacklisted(url)
end
def update_videos_i_posted_in_database(videos_i_posted)
videos_i_posted.each do |video|
if Video.find(:first, :conditions => "video_url = '#{video["url"]}'").nil? then
v = current_user.videos.new
v.video_url = video["url"]
v.video_type = "facebook_post"
v.action_date = Time.at(video["created_time"].to_i)
v.deleted = video_deleted_on_youtube video["url"]
v.save
end
end
end
def fake_login
sign_in User.find(1)
end
end |
class AddAttachmentImageProductImageToProductImage < ActiveRecord::Migration
def self.up
add_column :product_images, :image_product_image_file_name, :string
add_column :product_images, :image_product_image_content_type, :string
add_column :product_images, :image_product_image_file_size, :integer
add_column :product_images, :image_product_image_updated_at, :datetime
end
def self.down
remove_column :product_images, :image_product_image_file_name
remove_column :product_images, :image_product_image_content_type
remove_column :product_images, :image_product_image_file_size
remove_column :product_images, :image_product_image_updated_at
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
delete "/sign_out" => "users#destroy", as: "sign_out"
get "/sign_in" => "users#sign_in", as: "sign_in"
post "/login" => "users#login", as: "login"
get "/sign_up" => "users#new", as: "sign_up"
root 'welcome#index'
get "posts/search" => 'posts#search', as: 'search'
get "posts/ajax_search" => 'posts#ajax_search', as: 'ajax_search'
get "posts/gifty" => 'posts#gifty', as: 'gifty'
get "/auth/:provider/callback" => "users#create_from_omniauth"
resources :users, controller: "users", only: [:create, :show] do
resource :password,
controller: "passwords",
only: [:create, :edit, :update]
end
resources :posts
end
|
# PSEUDOCODE
# Please write your pseudocode here and keep it commented
# INPUT: An
# OUPUT: A class representing a die
# What are the steps to solve the problem? Write them out in plain english as best you can.
# Make an instance array with each side name as an element (This was wrong)
# Make an instance variable containing the array passed as an argument
# Calculate how many elements that array has
# Define a method that returns a random element from that array
# INITIAL CODE:
# This is the first version of code to pass the rspec tests and get all green.
class Die
def initialize(labels)
@labels = labels
@sides = @labels.length
raise ArgumentError.new("Too few sides!") unless @sides > 0
end
def labels
@labels
end
def sides
@sides
end
def roll
@labels[rand(@sides)]
end
end
# REFACTORED CODE:
# see: http://sourcemaking.com/refactoring/introduction-to-refactoring
class Die
attr_reader :sides, :labels
def initialize(labels)
@labels = labels
@sides = @labels.length
raise ArgumentError.new("Too few sides!") unless @sides > 0
end
def roll
@labels[rand(@sides)]
end
end
# REVIEW/REFLECT
# Reflection is vital to learning and growth. These challenges should not be thought of as items
# to check off; they are your opportunities to learn and grow as a programmer.
# Use the following questions to reflect on this challenge.
# Was your strategy for solving the challenge successful?
# What part of your strategy worked? What parts were challenging?
# What questions did you have while coding? Did you find answers to them?
# Are there any concepts that are still confusing to you?
# Did you learn any new skills or ruby tricks?
# INCLUDE REFLECTION HERE:
# It almost drives me crazy, I didn't took into account that what was being passed to the initialize method
# was already an array, not an undetermined serie of numbers that we had to turn into an array with the splat argument
# Once I realized that (by looking at the tests), it was easy. Lesson learned (not really) don't overcomplicate things
#
#
# TESTS
die = Die.new(['A', 'B', 'C', 'D', 'E', 'F'])
puts die.labels.length
puts die.labels
puts "sides #{die.sides}" # still returns the number of sides, in this case 6
puts die.roll # returns one of ['A', 'B', 'C', 'D', 'E', 'F'], randomly |
#==============================================================================
# ** Game_InteractiveButton
#------------------------------------------------------------------------------
# Do what it namely does
#==============================================================================
class Game_InteractiveButton
#------------------------------------------------------------------------------
TriggerTimer = 4
Node = Struct.new(:left, :right, :up, :down)
#------------------------------------------------------------------------------
attr_reader :symbol, :image
attr_reader :x, :y, :z
attr_reader :width, :height
attr_reader :handler
attr_reader :active, :group
attr_reader :sprite
attr_reader :help
attr_reader :viewport
attr_reader :show_text
attr_reader :hovered, :triggered
attr_accessor :index, :group_index, :node
attr_reader :icon_id
#------------------------------------------------------------------------------
def initialize(*args)
@hovered = false
@trigger_timer = 0
@index = nil
@group_index = nil
@icon_id = 0
@node = Node.new(self, self, self, self)
if args.size == 1 # hash initializer
inf = args[0]
@symbol = inf.symbol
@image = inf.image
@x, @y = (inf.x || 0), (inf.y || 0)
@width = inf.width || 0
@height = inf.height || 0
@handler = inf.handler
@active = inf.active || 0
@group = inf.group
@help = inf.help || ''
@show_text = inf.show_text || false
else
@symbol = args[0]
@image = args[1]
@x, @y = (args[2] || 0), (args[3] || 0)
@width = args[4] || 0
@height = args[5] || 0
@handler = args[6]
@active = args[7] || false
@group = args[8]
@help = args[9] || ''
@show_text = args[10] || false
end
if @image.is_a?(Symbol) && @image =~ /(?:icon)_(\d+)/i
@icon_id = $1.to_i
end
end
#------------------------------------------------------------------------------
def refresh
return unless @image
@sprite.bitmap.clear
draw_bitmap; draw_text;
end
#------------------------------------------------------------------------------
def active?
@active
end
#------------------------------------------------------------------------------
def activate
@active = true
self
end
#------------------------------------------------------------------------------
def deactivate
@active = false
self
end
#------------------------------------------------------------------------------
def unfocus_sprite
return unless @hovered
@hovered = false
@sprite.opacity = active? ? translucent_alpha : translucent_beta
end
#------------------------------------------------------------------------------
def focus_sprite
return if @hovered
@hovered = true
@sprite.opacity = 0xff
end
#------------------------------------------------------------------------------
def call_handler(*args)
unless @handler
return PONY::ERRNO.raise(:gib_nil_handler)
end
@handler.call(*args)
end
#------------------------------------------------------------------------------
def create_sprite(viewport = nil)
@sprite = ::Sprite.new(viewport)
draw_bitmap
@sprite.opacity = acitve? ? translucent_alpha : translucent_beta
@sprite
end
#------------------------------------------------------------------------------
def show_text=(enabled)
@show_text = enabled
refresh
end
#------------------------------------------------------------------------------
def translucent_alpha
return 0xc0
end
#------------------------------------------------------------------------------
def translucent_beta
return 0x60
end
#------------------------------------------------------------------------------
def dispose
return unless sprite_valid?(@sprite)
@sprite.dispose
@sprite = nil
end
#------------------------------------------------------------------------------
def draw_bitmap
if @icon_id
draw_icon(@icon_id)
elsif @image
@sprite.bitmap = Cache.UI(image)
@width = @sprite.bitmap.width
@height = @sprite.bitmap.height
else
@sprite.bitmap = Bitmap.new([@width, 1].max, [@height, 1].max)
end
end
#------------------------------------------------------------------------------
def draw_text
return unless @image && @show_text
rect = Rect.new(0, 0, @sprite.bitmap.text_size(@name).width, line_height)
rect.y = [@sprite.height - rect.height - 2, 0].max
@sprite.bitmap.draw_text(rect, @name, 1)
end
#------------------------------------------------------------------------------
def moveto(*args)
case args.size
when 1
pos = args[0]
@x = pos.x
@y = pox.y
else
@x, @y = args[0], args[1]
@z = args[2] unless args[2].nil?
end
if sprite_valid?
@sprite.x, @sprite.y = @x, @y
@sprite.z = @z
end
end
#------------------------------------------------------------------------------
def viewport=(vp)
debug_print("Warning: Sprite already has a viewport #{@viewport}") if sprite_valid?(@viewport)
@viewport = vp
end
#------------------------------------------------------------------------------
def z=(nz)
@z = nz
@sprite.z = @z if sprite_valid?
end
#------------------------------------------------------------------------------
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.