text stringlengths 10 2.61M |
|---|
require "spec_helper"
describe "Edit schedule", :type => :request, :js => true do
let!(:user) { create(:user, :paul) }
let!(:event) { create(:event, :tasafoconf, :users => [ user ], :owner => user.id) }
let!(:talk) { create(:talk, :users => [ user ], :owner => user.id) }
let!(:another_talk) { create(:another_talk, :users => [ user ], :owner => user.id) }
let!(:activity_lanche) { create(:activity, :lanche) }
let!(:schedule_abertura) { create(:schedule, :abertura, :event => event) }
let!(:schedule_intervalo) { create(:schedule, :intervalo, :event => event) }
let!(:schedule_palestra) { create(:schedule, :palestra, :event => event, :talk => talk) }
let!(:schedule_palestra2) { create(:schedule, :palestra, :event => event, :talk => another_talk) }
context "with valid data" do
before do
login_as(user)
visit root_path
click_link "Eventos"
click_link "Tá Safo Conf"
click_link "schedule_id_#{schedule_palestra.id}"
select "06/06/2012", :from => "schedule_day"
fill_in_inputmask "Horário", :with => "08:00"
fill_in :search_text, :with => "tecnologia"
click_button "Buscar"
click_button another_talk.id
click_button "Atualizar programação"
end
it "redirects to the event page" do
expect(current_path).to match(%r[/events/\w+])
end
it "displays success message" do
expect(page).to have_content("A programação foi atualizada!")
end
end
context "with invalid data" do
before do
login_as(user)
visit root_path
click_link "Eventos"
click_link "Tá Safo Conf"
click_link "schedule_id_#{schedule_palestra2.id}"
fill_in "Horário", :with => "24:00"
click_button "Atualizar programação"
end
it "renders form page" do
expect(current_path).to eql(edit_schedule_path(event, schedule_palestra2))
end
it "displays error messages" do
expect(page).to have_content("Verifique o formulário antes de continuar:")
end
end
end |
# iterate through every number from 0 to n/2
# if n == x, then true
# if it ends the iteration, then it would be false
# 144 / 2 = 72
# (0..72).each do |x|
# if x * x == n
# true
# else
# next
# false
# end
require 'pry'
def power_of_two?(num)
(1..num/2).each do |x|
return if 2*x == num
end
end
puts power_of_two?(144) #== true
puts power_of_two?(2)
puts power_of_two?(4096)
puts power_of_two?(5) |
module NokogiriMiscellaneousMixins
def sentences
self.xpath("//sentences//sentence")
end
def tokens
self.xpath(".//tokens//token")
end
def _words
self.xpath(".//word")
end
def _word
self.at_xpath(".//word")
end
def pos
self.at_xpath(".//POS")
end
def ner
self.at_xpath(".//NER")
end
end
|
module Yito
module Model
module Booking
class ActivityClassifierTerm
include DataMapper::Resource
storage_names[:default] = 'bookds_activity_classifier_terms'
belongs_to :activity, '::Yito::Model::Booking::Activity', :child_key => [:activity_id], :parent_key => [:id], :key => true
belongs_to :classifier_term, '::Yito::Model::Classifier::ClassifierTerm', :child_key => [:classifier_term_id], :parent_key => [:id], :key => true
end
end
end
end |
class AddFaxColumnsToOffices < ActiveRecord::Migration[6.0]
def change
add_column :offices, :fax, :string
add_column :offices, :fax_2, :string
end
end
|
class GifSerializer < ActiveModel::Serializer
# has_many :favorites
# has_many :users, through: :favorites
attributes :title, :img_url
end
# class PizzaSerializer < ActiveModel::Serializer
# # has_many :favorites
# # has_many :users, through: :favorites
# has_many :ingredients
# attributes :name
# end
|
class Api::MessagesController < ApplicationController
before_action :set_group, only:[:index]
def index
respond_to do |format|
format.html
format.json do
@messages=@group.messages.where('id>?',params[:lastMessageId])
end
end
end
def set_group
@group=Group.find(params[:group_id])
end
end
|
ENV["RACK_ENV"] = "test"
require "minitest/autorun"
require "rack/test"
require "erb"
require "fileutils"
require_relative "../app"
class AppTest < Minitest::Test
include Rack::Test::Methods
def app
Sinatra::Application
end
def setup
FileUtils.mkdir_p(data_path)
create_document('about.txt', 'some content')
create_document('test.md', '# headline')
end
def teardown
FileUtils.rm_rf(data_path)
end
def create_document(name, content = "")
File.open(File.join(data_path, name), "w") do |file|
file.write(content)
end
end
def session
last_request.env["rack.session"]
end
def admin_session
{ "rack.session" => { username: "admin" } }
end
# USE LIKE THIS:
# def test_editing_document
# get "/changes.txt/edit", {}, admin_session
# assert_equal 200, last_response.status
# end
def test_root
get '/'
assert_equal 302, last_response.status
get last_response['Location']
assert_equal 200, last_response.status
assert_includes last_response.body, '<ul>'
end
def test_index
get '/index'
assert_equal 200, last_response.status
assert_includes last_response.body, '<ul>'
end
def test_show_a_document
get '/about.txt'
assert_equal 200, last_response.status
assert_equal 'text/plain', last_response['Content-Type']
assert_includes last_response.body, 'some content'
end
def test_create_document
post '/create', { filename: 'second_about.txt' }, admin_session
assert_equal 302, last_response.status
assert_equal "The document 'second_about.txt' has been created.", session["message"]
get last_response['Location']
assert_includes last_response.body, 'second_about.txt'
end
def test_delete_document
post '/about.txt/delete', {}, admin_session
assert_equal 302, last_response.status
assert_equal "The document 'about.txt' has been deleted", session[:message]
get last_response['Location']
assert_includes last_response.body, '>test.md'
refute_includes last_response.body, '>about.txt'
end
def test_sign_in_form
get '/sign-in'
assert_equal 200, last_response.status
assert_includes last_response.body, '<form'
assert_includes last_response.body, '<input'
end
def test_sign_in_form_submission
post '/sign-in', { username: 'admin', password: 'secret' }
assert_equal 302, last_response.status
assert_equal 'Welcome!', session[:message]
assert_equal 'admin', session[:user]
get last_response['Location']
assert_includes last_response.body, 'Signed in as admin'
end
def test_invalid_credentials
post '/sign-in', { username: 'admin', password: 'something stupid' }
assert_equal 422, last_response.status
assert_nil session[:username]
assert_includes last_response.body, '<form'
assert_includes last_response.body, 'Invalid credentials'
end
def test_sign_in_sign_out
post '/sign-in', { username: 'admin', password: 'secret' }
post '/sign-out'
assert_equal 302, last_response.status
assert_nil session[:username]
assert_equal 'Goodbye!', session[:message]
get last_response['Location']
assert_includes last_response.body, 'Sign in'
end
def test_delete_document_while_signed_out
post '/about.txt/delete', {}
assert_equal 302, last_response.status
assert_equal "You have to be signed in to do that.", session[:message]
end
# ^ should write analogous tests for editing document (get and post), creating document (get and post)
end
|
Pod::Spec.new do |s|
s.name = "AASSVC"
s.version = "0.0.1"
s.summary = "Base on LTScrollview create AASScrollView."
s.description = <<-DESC
base on LTScrollView, develop language swift 4.1
DESC
s.homepage = "https://github.com/Nick-chen/AASScrollView"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "458318720@qq.com" => "458318720@qq.com" }
s.ios.deployment_target = '9.0'
s.source = { :git => "https://github.com/Nick-chen/AASScrollView.git", :tag => s.version.to_s }
s.source_files = "AASScrollView", "AASScrollView/AASScrollView/lib/*.swift"
s.requires_arc = true
s.swift_version = '4.1'
end
|
class Recipe < ActiveRecord::Base
has_many :reviews
belongs_to :user
validates :name, :category, :prep_time, :cook_time, :ingredients, :instructions, presence: true
validates :name, :category, :prep_time, :cook_time, format: { with: /\A[a-zA-Z\d\s]+\z/,
message: "only allows letters and numbers" }
def rating_avg
if self.reviews.any?
score = 0
self.reviews.each do |review|
score += review.rating
end
score = score / self.reviews.count.to_f
else
score = 0
end
score
end
end
|
# frozen_string_literal: true
module Mutations
# Offers a non-localized, english only, non configurable way to get error messages. This probably isnt good enough for users as-is.
class CustomErrorMessageCreator < DefaultErrorMessageCreator
MESSAGES = Hash.new("is invalid").tap do |h|
h.merge!(
# General
:nils => "can't be empty",
:required => "is required",
# Datatypes
:string => "isn't a string",
:integer => "isn't an integer",
:boolean => "isn't a boolean",
:hash => "isn't a hash",
:array => "isn't an array",
:model => "isn't the right class",
# Date
:date => "date doesn't exist",
:before => "isn't before given date",
:after => "isn't after given date",
# String
:empty => "can't be blank",
:max_length => "is too long",
:min_length => "is too short",
:matches => "isn't in the right format",
:in => "isn't an option",
# Array
:class => "isn't the right class",
# Integer
:min => "is too small",
:max => "is too big",
# Model
:new_records => "isn't a saved model"
)
end
def message(key, error_symbol, options = {})
if options[:index]
"#{titleize(key || 'array')}[#{options[:index]}] #{MESSAGES[error_symbol]}"
else
"#{titleize(key)} #{MESSAGES[error_symbol]}"
end
end
end
end
Mutations.error_message_creator = Mutations::CustomErrorMessageCreator.new
|
require 'test_helper'
class MollieTest < Test::Unit::TestCase
include OffsitePayments::Integrations
def setup
@token = 'test_8isBjQoJXJoiXRSzjhwKPO1Bo9AkVA'
JSON.stubs(:parse).returns(CREATE_PAYMENT_RESPONSE_JSON)
end
def test_get_request
@request = Mollie::API.new(@token).get_request("payments/#{@payment_id}")
assert_equal 'tr_djsfilasX', @request['id']
assert_equal '500.00', @request['amount']
assert_equal 'https://example.com/return', @request['links']['redirectUrl']
end
def test_post_request
@payment_id ='tr_QkwjRvZBzH'
params = {
:amount => BigDecimal.new('123.45'),
:description => 'My order description',
:redirectUrl => 'https://example.com/return',
:method => 'ideal',
:issuer => 'ideal_TESTNL99',
:metadata => { :my_reference => 'unicorn' }
}
@request = Mollie::API.new(@token).post_request('payments', params)
assert_equal 'tr_djsfilasX', @request['id']
assert_equal '500.00', @request['amount']
assert_equal 'https://example.com/return', @request['links']['redirectUrl']
end
CREATE_PAYMENT_RESPONSE_JSON = JSON.parse(<<-JSON)
{
"id":"tr_djsfilasX",
"mode":"test",
"createdDatetime":"2014-03-03T10:17:05.0Z",
"status":"open",
"amount":"500.00",
"description":"My order description",
"method":"ideal",
"metadata":{
"my_reference":"unicorn"
},
"details":null,
"links":{
"paymentUrl":"https://www.mollie.com/paymentscreen/mistercash/testmode/ca8195a3dc8d5cbf2f7b130654abe5a5",
"redirectUrl":"https://example.com/return"
}
}
JSON
end |
feature "display sandbox warning" do
include EnvVarSpecHelper
context "showing sandbox warning" do
scenario "on homepage" do
with_env_var('DISABLE_SANDBOX_WARNING', 'false') do
visit root_path
expect(page).to have_content("This sandbox site is for testing and training purposes only")
end
end
scenario "on internal pages" do
with_env_var('DISABLE_SANDBOX_WARNING', 'false') do
visit proposals_path
expect(page).to have_content("This sandbox site is for testing and training purposes only")
end
end
end
context "hides sandbox warning in production" do
scenario "on homepage" do
visit root_path
expect(page).not_to have_content("This sandbox site is for testing and training purposes only")
end
scenario "on internal pages" do
visit proposals_path
expect(page).not_to have_content("This sandbox site is for testing and training purposes only")
end
end
end
|
module CartRepresenter
include Roar::JSON
property :id
property :customer_id
property :order_id
property :line_items, getter: ->(*) { self.line_items }, extend: LineItemsRepresenter
property :address, getter: ->(*) { self.address }, extend: AddressRepresenter
end
|
def migrate_up
migrate :bit_many
end
require 'active_record_helper'
require 'troles_spec'
User.troles_strategy :bit_many do |c|
c.valid_roles = [:user, :admin, :blogger]
end.configure!
describe Troles::Storage::BitMany do
let(:kris) { Factory.create :user, :troles => 2}
subject { Troles::Storage::BitMany.new kris }
it 'should set roles' do
subject.set_roles 'blogger'
subject.display_roles.should == [:blogger]
kris.troles.should == 4
end
end
|
class CreatePickupLocations < ActiveRecord::Migration
def change
create_table :pickup_locations do |t|
t.references :user
t.string :name
t.string :address
t.float :latitude
t.float :longitude
t.boolean :gmaps
t.datetime :deleted_at
t.timestamps
end
add_index :pickup_locations, :user_id
end
end
|
require 'test_helper'
class ArtistTest < ActiveSupport::TestCase
def setup
@artist = artists(:one)
@song = Song.create(:artist_id => @artist.id, :title => "Some song")
end
test "could have many songs" do
assert @artist.save
assert_equal [@song], @artist.songs
end
end
|
class SensorsGroup < ApplicationRecord
has_many :sensors
validates :nome,presence: true,length: {minimum: 3,maximum: 25}
validates_uniqueness_of :nome
end
|
# frozen_string_literal: true
resource_name :elasticsearch_bulk_directory
self.class.include ::Ayte::Chef::Cookbook::ElasticSearch::ResourceDefinitionMethods
define_common_attributes(timeout: 32)
attribute :path, name_attribute: true
attribute :pattern, [String, Symbol], default: '**/*.{json,jsons}'
attribute :index, [String, Symbol, NilClass]
attribute :type, [String, Symbol, NilClass]
action_class do
include ::Ayte::Chef::Cookbook::ElasticSearch::ResourceMethods
end
action :execute do
# noinspection RubyResolve
ruby_block "elasticsearch_bulk_directory:#{new_resource.name}" do
block do
::Dir.glob(::File.join(new_resource.path, new_resource.pattern)) do |path|
resource_name = "#{target_name}:#{path}"
# noinspection RubyResolve
target = elasticsearch_bulk_file resource_name do
path path
index new_resource.index
type new_resource.type
end
copy_common_attributes(target)
end
end
end
end
|
# Calculate the mode Pairing Challenge
# I worked on this challenge [with: Kevin Huang ]
# I spent [1.5] hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented.
# 0. Pseudocode
# input: Array of numbers or strings
# output: Array of the most frequent values if only one frequent value returns single array
# Steps:
# Create new hash
# Convert Array elements to Hash Key.
# Assign default hash value to key
# iterate over each hash with an if loop.
# if each hash key is the same as the array element value, add 1 to the hash value.
# Pull biggest hash values out and put hash key into array
# 1. Initial Solution
# def mode(array)
# h = array.each_with_object(Hash.new(0)) do |item, list|
# list[item] += 1
# end
# big_count = 0
# h.each_value do |value|
# if big_count < value
# big_count = value
# end
# end
# a = []
# h.each_pair do |key,value|
# if value == big_count
# a.push(key)
# end
# end
# a
# end
# 3. Refactored Solution
def mode(array)
h = array.each_with_object(Hash.new(0)) do |item, list|
list[item] += 1
end
a = []
h.each {|k, v| a.push(k) if v == h.values.max}
a
end
# 4. Reflection
## Which data structure did you and your pair decide to implement and why?
# We implemented the hash data structure. This allowed us to use the array elements as the key, and the number of times they repeated as the value. We were able to manipulate the data to produce the solution this way.
## Were you more successful breaking this problem down into implementable pseudocode than the last with a pair?
# No. We had better pseudocode for the last assignment. Mainly because it was more detailed. This could also be because the first challenge was easier for us than this challenge.
## What issues/successes did you run into when translating your pseudocode to code?
# Our pseudocode wasn't verbose enough. We had the basic idea, but we didn't know the details. We couldn't figure out how to get the hash value to push the proper key into the array.
# Our initial solution was to create a variable to hold the count and iterate through two loops. We later found the .max method which made things way easier.
## What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement?
# For our initial solution my partner used an interesting .each_with_object method from his GPS grocery list. We also used each_value and each_pair. We found the .max method which seems like it will be really handy in the future while refactoring.
|
require "minitest/autorun"
require_relative "../NeuralNet"
class TestNeuralNet < Minitest::Test
def test_constructor
assert(NeuralNet.new([1], [1]).is_a?(NeuralNet))
end
def test_no_hidden_nodes
net = NeuralNet.new([1], [[[1,1]]])
assert_equal([0.8807970779778823], net.calculate([1, 1]))
end
def test_one_hidden_layer
net = NeuralNet.new([2, 1], [[ [1,1], [1,1]], [[0, 0, 1, 1]]])
assert_equal([0.8534092045709026], net.calculate([1, 1]))
end
end
|
class Bs::Elawa::SegmentSerializer < ActiveModel::Serializer
attributes :id, :name, :event_id, :start_date, :end_date
has_many :performances
belongs_to :event
end
|
require "spec_helper"
describe Notifications do
it "invitation should send to current player of game" do
game = Factory(:game)
game.current_player = game.black_player
mail = Notifications.invitation(game)
mail.subject.should == "[Go vs Go] Invitation from #{game.white_player.username}"
mail.to.should == [game.black_player.email]
mail.from.should == ["noreply@govsgo.com"]
mail.body.encoded.should include("unsubscribe")
end
it "move sends email about move" do
game = Factory(:game)
game.current_player = game.black_player
mail = Notifications.move(game)
mail.subject.should == "[Go vs Go] Move by #{game.white_player.username}"
mail.to.should == [game.black_player.email]
mail.from.should == ["noreply@govsgo.com"]
mail.body.encoded.should include("unsubscribe")
end
end
|
$: << File.dirname(__FILE__)
require 'spec_helper'
module SqlPostgres
describe Translate do
describe '::escape_sql' do
def self.pi
3.1415926535897932384626433832795028841971693993751058209749445923
end
def self.testCases
[
[nil, 'null'],
["", "E''"],
["foo", %q"E'foo'"],
["fred's", %q"E'fred\\047s'"],
['\\', %q"E'\\134'"],
[Time.local(2000, 1, 2, 3, 4, 5, 6),
"timestamp '2000-01-02 03:04:05.000006'"],
[Time.local(1999, 12, 31, 23, 59, 59, 999999),
"timestamp '1999-12-31 23:59:59.999999'"],
[1, '1'],
[-1, '-1'],
[1.0, "1"],
[-1.0, "-1"],
[pi, "3.1415926535898"],
[-pi, "-3.1415926535898"],
[1e100, "1e+100"],
[-1e-100, "-1e-100"],
[true, "true"],
[false, "false"],
[:default, "default"],
[['1 + %s', 1], '1 + 1'],
[[:in, 1, 2], '(1, 2)'],
[[:in, 'foo', 'bar'], "(E'foo', E'bar')"],
[BigDecimal('0'), '0.0'],
[BigDecimal('0.'), '0.0'],
[BigDecimal('1234567890.0987654321'), '1234567890.0987654321'],
[BigDecimal('0.000000000000000000000000000001'), '0.000000000000000000000000000001'],
[PgTime.new(0, 0, 0), "time '00:00:00'"],
[PgTime.new(23, 59, 59), "time '23:59:59'"],
[
PgTimeWithTimeZone.new,
"time with time zone '00:00:00+00:00'"
],
[
PgTimeWithTimeZone.new(12, 0, 0, -8),
"time with time zone '12:00:00-08:00'"
],
[
PgTimeWithTimeZone.new(23, 59, 59, 8),
"time with time zone '23:59:59+08:00'"
],
[
DateTime.civil(2001, 1, 1, 0, 0, 0, Rational(7, 24)),
"timestamp with time zone '2001-01-01 00:00:00.000000000+0700'",
],
[Date.civil(2001, 1, 1), "date '2001-01-01'"],
[
PgTimestamp.new(2001, 1, 2, 12, 0, 1),
"timestamp '2001-01-02 12:00:01.00000'"
],
[PgInterval.new('hours'=>1), "interval '01:00'"],
[PgInterval.new('days'=>1), "interval '1 day'"],
[PgPoint.new(1, 2), "point '(1, 2)'"],
[PgPoint.new(3, 4), "point '(3, 4)'"],
[
PgLineSegment.new(PgPoint.new(1, 2), PgPoint.new(3, 4)),
"lseg '((1, 2), (3, 4))'"
],
[
PgBox.new(PgPoint.new(1, 2), PgPoint.new(3, 4)),
"box '((1, 2), (3, 4))'"
],
[
PgPath.new(true, PgPoint.new(1, 2), PgPoint.new(3, 4)),
"path '((1, 2), (3, 4))'"
],
[
PgPolygon.new(PgPoint.new(1, 2), PgPoint.new(3, 4)),
"polygon '((1, 2), (3, 4))'"
],
[["%s %s", 1, 'Fred'], "1 E'Fred'"],
]
end
testCases.each do |raw, escaped|
context raw.inspect do
it do
Translate.escape_sql(raw).should == escaped
end
end
end
end
describe '::test_escape_array' do
def self.testCases
[
[nil, "null"],
[[], %q"'{}'"],
[[1], %q"ARRAY[1]"],
[[1, 2], %q"ARRAY[1, 2]"],
[['foo'], %q"ARRAY[E'foo']"],
[['\\'], %q"ARRAY[E'\\134']"],
[["a,b,c"], %q"ARRAY[E'a,b,c']"],
[["a", "b", "c"], %q"ARRAY[E'a', E'b', E'c']"],
[["\"Hello\""], %q"ARRAY[E'\"Hello\"']"],
[
[[0, 0], [0, 1], [1, 0], [1, 1]],
"ARRAY[ARRAY[0, 0], ARRAY[0, 1], ARRAY[1, 0], ARRAY[1, 1]]"
],
]
end
testCases.each do |raw, escaped|
context raw.inspect do
it do
Translate.escape_array(raw).should == escaped
end
end
end
end
describe '::escape_bytea_array' do
def self.testCases
[
[[], "'{}'"],
[["", "foo"], "'{\"\",\"foo\"}'"],
["\000\037 ", "'{\"\\\\\\\\000\037 \"}'"],
[["'\\"], "'{\"\\'\\\\\\\\\\\\\\\\\"}'"],
[["~\177\377"], "'{\"~\177\377\"}'"],
[["\""], "'{\"\\\\\"\"}'"],
[nil, "null"],
]
end
testCases.each do |raw, escaped|
context raw.inspect do
it do
Translate.escape_bytea_array(raw).should == escaped
end
end
end
end
describe '::sql_to_array' do
def self.goodTestCases
[
["{}", []],
["{foo}", ["foo"]],
["{foo,bar,\"fool's gold\"}", ["foo", "bar", "fool's gold"]],
["{\"\\\\\"}", ["\\"]],
["{\"\\\\\",fool's}", ["\\", "fool's"]],
["{\"a,b,c\"}", ["a,b,c"]],
["{\"\\\"Hello!\\\"\"}", ["\"Hello!\""]],
["{\"\001\n\037\"}", ["\001\n\037"]],
[
"{{f,f},{f,t},{t,f},{t,t}}",
[["f", "f"], ["f", "t"], ["t", "f"], ["t", "t"]],
],
]
end
def self.badTestCases
[
"",
"{",
"{foo",
"{foo}x",
]
end
goodTestCases.each do |sql, array|
context sql.inspect do
it do
Translate.sql_to_array(sql).should == array
end
end
end
badTestCases.each do |sql|
context sql.inspect do
it do
expect do
Translate.sql_to_array(sql).should == array
end.to raise_error(ArgumentError, sql.inspect)
end
end
end
end
describe '::test_escape_qchar' do
def self.testCases
[
[nil, 'null'],
["\000", %q"E'\\000'"],
["\001", %q"E'\\001'"],
["\377", %q"E'\\377'"],
["a", "E'\\141'"],
]
end
testCases.each do |raw, escaped|
context raw.inspect do
it do
Translate.escape_qchar(raw).should == escaped
end
end
end
end
describe '::escape_bytea' do
def self.testCases
[
[nil, 'null', 'null'],
[:default, "default", "default"],
["", "''", "'\\x'"],
["foo", %q"'foo'", %q"'\\x666f6f'"],
["\000\037 ", %q"'\\000\\037 '", %q"'\\x001f20'"],
["'\\", %q"'''\\\\'", %q"'\\x275c'"],
["~\177\377", "'~\\177\\377'", "'\\x7e7fff'"],
]
end
testCases.each do |raw, escaped_84, escaped_90|
test_connections.each do |test_context, test_connection|
context test_context do
context raw.inspect do
let(:connection) {test_connection}
it do
pgconn = connection.pgconn
escaped = if pgconn.server_version < 9_00_00
escaped_84
else
escaped_90
end
if pgconn.server_version < 9_01_00
escaped = escaped.gsub("\\", "\\\\\\")
escaped = 'E' + escaped if raw.is_a?(String)
end
Translate.escape_bytea(raw, pgconn).should == escaped
end
end
end
end
end
end
describe '::unescape_bytea' do
def self.testCases
[
["", ""],
["abc", "abc"],
["\\\\", "\\"],
["\\001", "\001"],
["\\x01", "\001"],
["\\037", "\037"],
["\\x1f", "\037"],
["\\177", "\177"],
["\\200", "\200"],
["\\377", "\377"],
["\\477", "477"], #DEBUG why had we been testing handling of badly escaped bytea would badly unescape???
["\\387", "387"],
["\\378", "378"],
["\\n", "n"],
["abc\\", "abc"],
["\\x779c", "w\234"]
]
end
testCases.each do |escaped, raw|
test_connections.each do |test_context, test_connection|
context test_context do
context escaped.inspect do
let(:connection) {test_connection}
it do
pgconn = connection.pgconn
Translate.unescape_bytea(escaped, pgconn).should == raw
end
end
end
end
end
end
describe '::unescape_qchar' do
def self.testCases
[
["", "\000"],
["\001", "\001"],
["\037", "\037"],
[" ", " "],
["~", '~'],
["\277", "\277"],
["\300", "\300"],
["\377", "\377"],
]
end
testCases.each do |escaped, raw|
context escaped do
it do
Translate.unescape_qchar(escaped).should == raw
end
end
end
end
describe '::escapeSql' do
context 'Select' do
it do
select = mock(Select, :statement => 'foo')
Translate.escape_sql(select).should == "(foo)"
end
end
context "AllCharValues" do
RANGE = 1..255
test_connections.each do |test_context, test_connection|
context test_context do
let(:connection) {test_connection}
include_context('temporary table',
:table_name => 'escape_sql_test',
:columns => ['i int',
't text'
])
RANGE.each do |i|
context "char: #{i}" do
before(:each) do
insert = "insert into escape_sql_test (i, t) "\
"values (#{i}, #{Translate.escape_sql(i.chr)});"
connection.query(insert)
select = "select i, t, length(t) from escape_sql_test order by i;"
row = connection.query(select).first
@char_number, @text, @length = *row
end
it do
@length.should == '1'
end
it do
@text.should == i.chr
end
end
end
end
end
end
end
describe '::substitute_values' do
def self.testCases
[
["foo", "foo"],
[["bar %s", 1], "bar 1"],
[["bar %s", "O'Malley"], "bar E'O\\047Malley'"],
[["%s %s", nil, 1.23], "null 1.23"],
]
end
testCases.each do |raw, expected|
context raw do
it do
Translate.substitute_values(raw).should == expected
end
end
end
end
describe 'datetime' do
def self.testCases
[
[2003, 10, 18, 11, 30, 24, -7],
[2001, 1, 1, 0, 0, 0, 0],
[1970, 12, 31, 23, 59, 59, -11],
]
end
testCases.each do |time_parts|
context time_parts.inspect do
let(:sql) {"%04d-%02d-%02d %02d:%02d:%02d.000000000%+03d00" % time_parts}
let(:dateTime) do
DateTime.civil(*time_parts[0..5] +
[Rational(time_parts[6], 24)])
end
describe 'sql_to' do
it do
Translate.sql_to_datetime(sql).should == dateTime
end
end
describe "to_sql" do
it do
Translate.datetime_to_sql(dateTime).should == sql
end
end
end
end
end
describe '::sql_to_date' do
def self.testCases
[
[2000, 1, 1],
[1899, 12, 31],
]
end
testCases.each do |time_parts|
context time_parts.inspect do
it do
sql = "%04d-%02d-%02d" % time_parts
date = Date.civil(*time_parts)
Translate.sql_to_date(sql).should == date
end
end
end
end
describe '::deep_collect' do
def self.testCases
[
["1", 1],
[[], []],
[["1"], [1]],
[["1", "2"], [1, 2]],
[["1", ["2", "3"], []], [1, [2, 3], []]],
]
end
testCases.each do |input, output|
context input.inspect do
it do
Translate.deep_collect(input) do |e|
e.to_i
end.should == output
end
end
end
end
end
end
|
class RoomsController < ApplicationController
soap_service namespace: 'urn:WashOut'
soap_action "AddCircle",
:args => { :circle => { :center => { :@x => :integer,
:@y => :integer },
:@radius => :double } },
:return => nil, # [] for wash_out below 0.3.0
:to => :add_circle
def add_circle
circle = params[:circle]
Circle.new(circle[:center][:x], circle[:center][:y], circle[:radius])
render :soap => nil
end
end
|
# frozen_string_literal: true
# Handles player input for moves and pawn promotion
class Player
attr_reader :name, :color, :icon
def initialize(name)
@name = name
@color = nil
@icon = nil
end
def color=(color)
@color = color
@icon = color == :w ? "\u2654" : "\u265A"
end
def make_move
move = gets.chomp
until save_game(move) || /^[a-z]\d\s[a-z]\d$/ =~ move ||
['0-0', '0-0-0'].include?(move)
print 'Please use proper move notation ([a..h][1..8] [a..h][1..8]): '
move = gets.chomp
end
save_game(move) ? move.downcase : move
end
def promote_pawn
print 'Please choose a promotion: 1) Queen, 2) Knight, 3) Rook, ' \
'4) Bishop: '
choice = gets.chomp
until save_game(move) || (/^\d$/ =~ choice && choice.to_i.between?(1, 4))
print 'Please choose only between 1 to 4: '
choice = gets.chomp
end
choice.to_i
end
def save_game(move)
/^save$/i =~ move
end
end
|
require 'highline/import'
namespace :fedbus do
desc "Add an administrative user"
task :admin, :userid, :needs => :environment do |t, args|
userid = args[:userid] || ask("User ID: ") { |uid| uid.validate = /^[a-z\d]+$/ }
admin_role = Role.find_by_name("Administrator")
if admin_role.nil?
say "Administrator role not found. Please seed the database."
say "You can do this by running 'rake db:seed'."
say "This is also done as part of 'rake fedbus:setup' process."
exit
end
user = User.find_by_userid(userid)
if user.nil?
agree("User '#{userid}' not found. Register? ") || exit
user = register_user(userid) || exit
end
user.roles << Role.find_by_name("Administrator")
user.save!
say "User '#{user.userid}' is now an administrator."
end
end
def register_user(userid)
form_info = [
[:first_name, "First Name", /.+/],
[:last_name, "Last Name", /.+/],
[:email, "Email Address", /[a-z0-9!#\$%&'*+\/=?^_`\{|\}~-]+(?:\.[a-z0-9!#\$%&'*+\/=?^_`\{|\}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/],
[:student_number, "Student No. (optional)", /^\d*$/]
]
user_attribs = form_info.inject({}) do |attribs, field|
attribute, question, regex = *field
attribs.merge attribute => ask("#{question}: ".rjust(24)) { |q| q.validate = regex }
end
unless user_attribs[:student_number].blank?
user_attribs[:student_number_confirmation] = ask("Student No. (again): ".rjust(24)) { |q| q.validate = /^\d+$/ }
end
user = User.new(user_attribs)
user.userid = userid
unless user.save
say ""
say "Unable to register user. Errors:"
for error in user.errors
attrib, message = *error
say " * #{attrib.humanize} #{message}."
end
nil
else
say "User '#{userid}' registered."
user
end
end |
Rails.application.routes.draw do
resources :secrets
get 'main/page'
get 'main/new'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: "main#page"
end
|
class FamilyInvitation < ApplicationRecord
enum status: {
pending: 0,
accepted: 1,
declined: 2
}, _prefix: true
belongs_to :inviter_profile, class_name: 'UserProfile'
belongs_to :user_profile, autosave: true
validates :user_profile_id, :inviter_profile_id, :email, presence: true
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }, allow_blank: true
validate :inviter_and_invitee_should_belong_to_same_family
validate :specified_email_should_not_be_within_family
after_create :send_invitation_email
before_update :assign_profile_ownership_if_invitation_accepted
def assign_profile_ownership_if_invitation_accepted
if self.status_accepted?
self.user_profile.update!(user: User.find_by_email(self.email))
end
end
def send_invitation_email
FamilyMailer.invite_to_family(self).deliver_now!
end
def inviter_and_invitee_should_belong_to_same_family
unless inviter_and_invitee_belong_to_same_family?
self.errors.add(:user_profile, " does not belong to same family.")
end
end
def specified_email_should_not_be_within_family
if specified_email_is_within_family?
self.errors.add(:email, " already belongs to a member of this family. Use a different email address.")
end
end
def specified_email_is_within_family?
return false if self.email.blank?
user = User.where(email: self.email).first
return false unless user.present? && user.user_profile.present?
inviter_profile.family_id == user.user_profile.family_id
end
def inviter_and_invitee_belong_to_same_family?
inviter_profile.family_id == user_profile.family_id
end
end
# == Schema Information
#
# Table name: family_invitations
#
# id :integer not null, primary key
# user_profile_id :integer
# inviter_profile_id :integer
# email :string
# status :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_family_invitations_on_inviter_profile_id (inviter_profile_id)
# index_family_invitations_on_user_profile_id (user_profile_id)
#
|
class AssocsController < ApplicationController
swagger_controller :assocs, "Associations management"
before_action :authenticate_volunteer!, except: [:index, :show, :pictures, :main_picture],
unless: :is_swagger_request?
before_action :authenticate_volunteer_if_needed,
only: [:index, :show, :pictures, :main_picture], unless: :is_swagger_request?
before_action :set_assoc, only: [:show, :edit, :update, :notifications, :members, :events, :delete, :pictures, :main_picture, :news, :invitable_volunteers]
before_action :set_link, only: [:update, :delete, :events]
before_action :check_block, only: [:edit, :update, :notifications, :members, :events, :delete, :news]
before_action :check_rights, only: [:update, :delete]
swagger_api :index do
summary "Get a list of all associations"
param :header, 'access-token', :string, :optional, "Access token"
param :header, :client, :string, :optional, "Client token"
param :header, :uid, :string, :optional, "Volunteer's uid (email address)"
response :ok
response 400
end
def index
associations = Assoc.all.map { |assoc|
if current_volunteer.present?
link = assoc.av_links.find_by(volunteer_id: current_volunteer.id)
friends_number = assoc.volunteers.select { |volunteer|
volunteer.volunteers.include?(current_volunteer)
}.count
end
friends_number = 0 if friends_number.blank?
assoc.attributes.merge(rights: link.try(:rights),
nb_members: assoc.volunteers.count,
nb_friends_members: friends_number)
}
render json: create_response(associations)
end
swagger_api :create do
summary "Allow volunteer to create an association"
param :header, 'access-token', :string, :required, "Access token"
param :header, :client, :string, :required, "Client token"
param :header, :uid, :string, :required, "Volunteer's uid (email address)"
param :query, :name, :string, :required, "Association's name"
param :query, :description, :string, :required, "Association's description"
param :query, :birthday, :date, :optional, "Date of creation"
param :query, :city, :string, :optional, "City where the association is located"
param :query, :latitude, :decimal, :optional, "Association latitude position"
param :query, :longitude, :decimal, :optional, "Association longitude position"
response :ok
response 400
end
def create
begin
if Assoc.exist? assoc_params[:name]
render :json => create_error(400, t("assocs.failure.name.unavailable"))
return
end
new_assoc = Assoc.create!(assoc_params)
link = AvLink.create!(assoc_id: new_assoc.id,
volunteer_id: current_volunteer.id, rights: 'owner')
render :json => create_response(new_assoc.as_json.merge('rights' => 'owner'))
rescue ActiveRecord::RecordInvalid => e
render :json => create_error(400, e.to_s)
return
end
end
swagger_api :show do
summary "Get associations information by its id"
param :path, :id, :integer, :required, "Association's id"
param :header, 'access-token', :string, :optional, "Access token"
param :header, :client, :string, :optional, "Client token"
param :header, :uid, :string, :optional, "Volunteer's uid (email address)"
response :ok
response 400
end
def show
p "$$$"
p current_volunteer
p "$$$"
if current_volunteer.blank?
render json: create_response(@assoc) and return
end
link = AvLink.where(assoc_id: @assoc.id).where(volunteer_id: current_volunteer.id).first
if link != nil
render :json => create_response(@assoc.as_json.merge('rights' => link.rights)) and return
end
rights = nil
notif = Notification.where(notif_type: 'InviteMember').where(assoc_id: @assoc.id)
.where(receiver_id: current_volunteer.id).first
if notif != nil
rights = 'invited'
end
notif = Notification.where(notif_type: 'JoinAssoc').where(sender_id: current_volunteer.id)
.where(assoc_id: @assoc.id).first
if notif != nil
rights = 'waiting'
end
render :json => create_response(@assoc.as_json.merge('rights' => rights)) and return
end
swagger_api :members do
summary "Get a list of all members"
param :path, :id, :integer, :required, "Association's id"
param :header, 'access-token', :string, :required, "Access token"
param :header, :client, :string, :required, "Client token"
param :header, :uid, :string, :required, "Volunteer's uid (email address)"
response :ok
response 400
end
def members
query = "volunteers.id, volunteers.firstname, volunteers.lastname, volunteers.email, volunteers.thumb_path, av_links.rights"
render :json => create_response(Volunteer.joins(:av_links)
.where(av_links: { assoc_id: @assoc.id })
.select(query).limit(100))
end
swagger_api :events do
summary "Get a list of all association's events"
param :path, :id, :integer, :required, "Association's id"
param :header, 'access-token', :string, :required, "Access token"
param :header, :client, :string, :required, "Client token"
param :header, :uid, :string, :required, "Volunteer's uid (email address)"
response :ok
response 400
end
def events
privacy = ""
if @link.eql?(nil)
privacy = " AND events.private=false"
end
query = "SELECT events.id, events.title, events.place, events.begin, events.assoc_id, events.assoc_name, events.thumb_path, " +
"(SELECT event_volunteers.rights FROM event_volunteers WHERE event_volunteers.event_id=" +
"events.id AND event_volunteers.volunteer_id=#{current_volunteer.id}) AS rights, " +
"(SELECT COUNT(*) FROM event_volunteers WHERE event_volunteers.event_id=events.id) AS nb_guest, " +
"(SELECT COUNT(*) FROM event_volunteers INNER JOIN v_friends ON " +
"event_volunteers.volunteer_id=v_friends.friend_volunteer_id " +
"WHERE event_id=events.id AND v_friends.volunteer_id=#{current_volunteer.id}) AS nb_friends_members" +
" FROM events WHERE events.assoc_id=#{@assoc.id}" + privacy
render :json => create_response(ActiveRecord::Base.connection.execute(query))
end
swagger_api :update do
summary "Update association"
param :path, :id, :integer, :required, "Association's id"
param :header, 'access-token', :string, :required, "Access token"
param :header, :client, :string, :required, "Client token"
param :header, :uid, :string, :required, "Volunteer's uid (email address)"
param :query, :name, :string, :optional, "Association's name"
param :query, :description, :string, :optional, "Association's description"
param :query, :birthday, :date, :optional, "Date of creation"
param :query, :city, :string, :optional, "City where the association is located"
param :query, :latitude, :decimal, :optional, "Association latitude position"
param :query, :longitude, :decimal, :optional, "Association longitude position"
response :ok
response 400
end
def update
begin
if !Assoc.is_new_name_available?(assoc_params[:name],
@assoc.name)
render :json => create_error(400, t("assocs.failure.name.unavailable"))
elsif @assoc.update!(assoc_params)
render :json => create_response(@assoc.as_json.merge('rights' => @link.rights))
else
render :json => create_error(400, t("assocs.failure.update"))
end
rescue ActiveRecord::RecordInvalid => e
render :json => create_error(400, e.to_s) and return
end
end
swagger_api :delete do
summary "Deletes association (needs to be owner)"
param :path, :id, :integer, :required, "Association's id"
param :header, 'access-token', :string, :required, "Access token"
param :header, :client, :string, :required, "Client token"
param :header, :uid, :string, :required, "Volunteer's uid (email address)"
response :ok
response 400
end
def delete
if @link.rights.eql?('owner')
Notification.where(assoc_id: @assoc.id).destroy_all
AvLink.where(assoc_id: @assoc.id).destroy_all
@assoc.destroy
render :json => create_response(t("assocs.success.deleted")) and return
end
render :json => create_error(400, t("assocs.failure.rights"))
end
swagger_api :invited do
summary "Get all associations where you're invited"
param :header, 'access-token', :string, :required, "Access token"
param :header, :client, :string, :required, "Client token"
param :header, :uid, :string, :required, "Volunteer's uid (email address)"
response :ok
response 400
end
def invited
assocs = Assoc.select(:id, :name, :city, :thumb_path)
.select("(SELECT COUNT(*) FROM av_links WHERE av_links.assoc_id=assocs.id) AS nb_members")
.select("(SELECT COUNT(*) FROM av_links INNER JOIN v_friends ON av_links.volunteer_id=v_friends.friend_volunteer_id WHERE assoc_id=assocs.id AND v_friends.volunteer_id=#{current_volunteer.id}) AS nb_friends_members")
.joins("INNER JOIN notifications ON notifications.assoc_id=assocs.id")
.select("notifications.id AS notif_id")
.where("notifications.receiver_id=#{current_volunteer.id} AND notifications.notif_type='InviteMember'")
render :json => create_response(assocs)
end
swagger_api :joining do
summary "Get all associations you're joining"
param :header, 'access-token', :string, :required, "Access token"
param :header, :client, :string, :required, "Client token"
param :header, :uid, :string, :required, "Volunteer's uid (email address)"
response :ok
response 400
end
def joining
associations = current_volunteer.notifications.select(&:is_join_assoc?).select { |notification|
notification.sender_id == current_volunteer.id
}.map { |notification| Assoc.find(notification.assoc_id) }
render json: create_response(associations)
end
swagger_api :invitable_volunteers do
summary "Get a list of all invitable volunteers"
param :path, :id, :integer, :required, "Association's id"
param :query, :token, :string, :required, "Your token"
response :ok
response 400
end
def invitable_volunteers
volunteers = current_volunteer.volunteers.select { |volunteer| volunteer.assocs.exclude?(@assoc) }
render json: create_response(volunteers)
end
swagger_api :pictures do
summary "Returns a list of all association's pictures paths"
param :path, :id, :integer, :required, "Association's id"
response :ok
response 400
end
def pictures
query = "id, file_size, picture_path, is_main"
pictures = Picture.where(:assoc_id => @assoc.id).select(query).limit(100)
render :json => create_response(pictures)
end
swagger_api :main_picture do
summary "Returns path of main picture"
param :path, :id, :integer, :required, "Association's id"
response :ok
response 400
end
def main_picture
query = "id, file_size, picture_path"
pictures = Picture.where(:assoc_id => @assoc.id).where(:is_main => true).select(query).first
render :json => create_response(pictures)
end
swagger_api :news do
summary "Returns association's news"
param :path, :id, :integer, :required, "Association's id"
param :header, 'access-token', :string, :required, "Access token"
param :header, :client, :string, :required, "Client token"
param :header, :uid, :string, :required, "Volunteer's uid (email address)"
response :ok
response 400
end
def news
rights = current_volunteer.av_links.find_by(assoc_id: @assoc.id).try(:level)
render json: create_response(@assoc.news.select { |new| (new.private and rights.present? and rights >= AvLink.levels["member"]) or new.public })
end
private
def set_assoc
begin
@assoc = Assoc.find(params[:id])
rescue
render :json => create_error(400, t("assocs.failure.id"))
end
end
def set_link
@link = AvLink.where(:volunteer_id => current_volunteer.id).where(:assoc_id => @assoc.id).first
end
def assoc_params
params.permit(:name, :description, :birthday, :city, :latitude, :longitude)
end
def check_block
link = AvLink.where(volunteer_id: current_volunteer.id).where(assoc_id: @assoc.id).first
if !link.eql?(nil) and link.level.eql?(AvLink.levels["block"])
render :json => create_error(400, t("follower.failure.blocked"))
end
end
def check_rights
if @link.eql?(nil) || @link.rights.eql?('member')
render :json => create_error(400, t("assocs.failure.rights"))
return false
end
return true
end
def authenticate_volunteer_if_needed
if request.headers["access-token"].present? and request.headers["client"].present? and request.headers["uid"].present?
authenticate_volunteer!
end
end
end
|
class AddAttachmentToMenus < ActiveRecord::Migration
def change
add_attachment :menus, :game_pic
add_attachment :menus, :game_icon
end
end
|
class AddNameToSchedulators < ActiveRecord::Migration
def change
add_column :schedulators, :name, :string
end
end
|
FactoryBot.define do
factory :school_device_allocation do
std
association :school
association :created_by_user, factory: :dfe_user
association :last_updated_by_user, factory: :dfe_user
trait :std do
device_type { 'std_device' }
end
trait :coms do
device_type { 'coms_device' }
end
trait :with_std_allocation do
allocation { 1 }
cap { 0 }
end
trait :with_coms_allocation do
coms
allocation { 1 }
cap { 0 }
end
trait :with_available_devices do
allocation { 2 }
cap { 1 }
end
trait :fully_ordered do
allocation { 1 }
cap { 1 }
devices_ordered { 1 }
end
trait :partially_ordered do
allocation { 2 }
cap { 2 }
devices_ordered { 1 }
end
end
end
|
rule ".rb" => ".treetop" do |task, args|
# TODO(sissel): Treetop 1.5.x doesn't seem to work well, but I haven't
# investigated what the cause might be. -Jordan
Rake::Task["gem:require"].invoke("treetop", "~> 1.4.0", ENV["GEM_HOME"])
require "treetop"
compiler = Treetop::Compiler::GrammarCompiler.new
compiler.compile(task.source, task.name)
puts "Compiling #{task.source}"
end
namespace "compile" do
desc "Compile the config grammar"
task "grammar" => "lib/logstash/config/grammar.rb"
desc "Build everything"
task "all" => "grammar"
end
|
require 'test_helper'
class SiteLayoutTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
test 'layout links' do
get root_path
assert_template 'static_pages/home'
assert_select 'a[href=?]', root_path, count: 2
assert_select 'a[href=?]', help_path
assert_select 'a[href=?]', about_path
assert_select 'a[href=?]', contact_path # Rails automatically inserts the value of about_path in place of the question mark, thereby checking for an <a> HTML tag with <contact_path> href attribute value
get contact_path
assert_select "title", full_title( "Contact" ) # we can call full_title method because we included ApplicationHelper in test/test_helper.rb
get signup_path
assert_select "select", count: 0
assert_select 'h1', 'Sign up'
end
end
|
require 'spec_helper'
describe Link do
it { should validate_presence_of(:title) }
it { should validate_presence_of(:url) }
it { should validate_presence_of(:user_id) }
it { should have_many(:comments) }
it { should belong_to(:user) }
it { should have_many(:subs) }
it { should allow_mass_assignment_of(:title) }
it { should allow_mass_assignment_of(:url) }
it { should allow_mass_assignment_of(:body) }
it { should allow_mass_assignment_of(:user_id) }
end |
class AddSeasonColumnToSeedBags < ActiveRecord::Migration[5.0]
def change
add_column :seed_bags, :season, :string
end
end
|
class Vote < ActiveRecord::Base
belongs_to :submission
belongs_to :faculty
end
|
class User < ApplicationRecord
validates(:username, presence: true,
uniqueness: true)
validates(:email, presence: true,
uniqueness: true)
validates(:password, presence: true,
length: { minimum: 6 })
has_many :links
has_many :comments
end
|
require 'debugger'
require 'digest/sha1'
enable :sessions
get '/' do
erb :index
end
get '/logout' do
logout!
redirect '/'
end
post '/sign_up' do
@encrypted = Digest::SHA1.hexdigest(params[:password])
@user = User.create(email: params[:email], password: @encrypted)
@user.valid? ? @message = "New user created for #{params[:email]}" : @message = @user.errors.full_messages.first
erb :index
end
post '/login' do
@email = params[:email]
@encrypted = Digest::SHA1.hexdigest(params[:password])
user = User.authenticate(@email,@encrypted)
if user.present?
login! user
redirect '/secret'
else
@message2 = "Invalid login"
erb :index
end
end
get '/secret' do
return "NOT AUTHORIZED" unless logged_in?
erb :secret
end
helpers do
def login! user
session[:current_user_id] = user.id
end
def logout!
session.clear
end
def logged_in?
session[:current_user_id].present?
end
def current_user
return nil unless logged_in?
@current_user ||= User.find(session[:current_user_id])
end
end
|
# Computes factorial of the input number and returns it
def factorial(number)
raise ArgumentError.new if number.class != Integer
return 1 if number <= 1
f = 1
i = 0
while (number-i) > 0 do
f *= (number-i)
i += 1
end
return f
end
|
# ================================================================
# Created: 2015/04/29
# Author: Thomas Nguyen - thomas_ejob@hotmail.com
# Purpose: Keep all filename locations
# ================================================================
module FileNames
CONST_DEFAULT = "../config/constants.rb"
CONST_FILENAMES = "../config/filenames.rb"
LIB_BASE_PAGE = "../lib/base_page.rb"
LIB_COMMON_PAGE = "../lib/common_page.rb"
LIB_MY_CLOCK = "../lib/my_clock.rb"
LIB_MY_EMAIL = "../lib/my_email.rb"
LIB_MY_FILE = "../lib/my_file.rb"
LOCATORS_LOGIN = "../locators/login.yml"
LOCATORS_ACCOUNT = "../locators/account.yml"
LOCATORS_SIGNUP = "../locators/signup.yml"
LOCATORS_SIGNUPTRIAL = "../locators/signuptrial.yml"
PAGES_LOGIN = "../pages/login.rb"
PAGES_ACCOUNT = "../pages/account.rb"
PAGES_SIGNUP = "../pages/signup.rb"
PAGES_SIGNUP_TRIAL = "../pages/signuptrial.rb"
PAGES_TEST = "../pages/test.rb"
HELPER_LOGIN = "../helper/login_helper.rb"
HELPER_SIGNUP = "../helper/signup_helper.rb"
HELPER_SIGNUPTRIAL = "../helper/signuptrial_helper.rb"
#HELPER_UTILS_PROPERTY = "../helper/utils_property_helper.rb" #not used yet
SCREENSHOT_FOLDER = "../screenshot/"
SCREENSHOT_FILENAME = "screen.png"
end |
class Shopper < ActiveRecord::Base
has_many :shopper_assignments
validates :username, presence: true, uniqueness: {case_sensitive: false}, length: {minimum:3, maximum:25}
validates :password, presence: true, length: {minimum: 3, maximum: 25}
before_save {self.username = username.downcase}
has_secure_password
end |
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
# rubocop:disable Layout/LineLength
require_relative('pod_helpers')
def add_flipper_pods!(versions = {})
versions['Flipper'] ||= '~> 0.33.1'
versions['DoubleConversion'] ||= '1.1.7'
versions['Flipper-Folly'] ||= '~> 2.1'
versions['Flipper-Glog'] ||= '0.3.6'
versions['Flipper-PeerTalk'] ||= '~> 0.0.4'
versions['Flipper-RSocket'] ||= '~> 1.0'
pod 'FlipperKit', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/FlipperKitLayoutPlugin', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/SKIOSNetworkPlugin', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/FlipperKitUserDefaultsPlugin', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/FlipperKitReactPlugin', versions['Flipper'], :configuration => 'Debug'
# List all transitive dependencies for FlipperKit pods
# to avoid them being linked in Release builds
pod 'Flipper', versions['Flipper'], :configuration => 'Debug'
pod 'Flipper-DoubleConversion', versions['DoubleConversion'], :configuration => 'Debug'
pod 'Flipper-Folly', versions['Flipper-Folly'], :configuration => 'Debug'
pod 'Flipper-Glog', versions['Flipper-Glog'], :configuration => 'Debug'
pod 'Flipper-PeerTalk', versions['Flipper-PeerTalk'], :configuration => 'Debug'
pod 'Flipper-RSocket', versions['Flipper-RSocket'], :configuration => 'Debug'
pod 'FlipperKit/Core', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/CppBridge', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/FBCxxFollyDynamicConvert', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/FBDefines', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/FKPortForwarding', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/FlipperKitHighlightOverlay', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/FlipperKitLayoutTextSearchable', versions['Flipper'], :configuration => 'Debug'
pod 'FlipperKit/FlipperKitNetworkPlugin', versions['Flipper'], :configuration => 'Debug'
end
def include_react_native!(options)
react_native, flipper_versions, project_root, target_platform = options.values_at(
:path, :rta_flipper_versions, :rta_project_root, :rta_target_platform
)
add_flipper_pods!(flipper_versions) if target_platform == :ios && flipper_versions
pod 'FBLazyVector', :path => "#{react_native}/Libraries/FBLazyVector"
pod 'FBReactNativeSpec', :path => "#{react_native}/Libraries/FBReactNativeSpec"
pod 'RCTRequired', :path => "#{react_native}/Libraries/RCTRequired"
pod 'RCTTypeSafety', :path => "#{react_native}/Libraries/TypeSafety"
pod 'React', :path => "#{react_native}/"
pod 'React-Core', :path => "#{react_native}/", :inhibit_warnings => true
pod 'React-CoreModules', :path => "#{react_native}/React/CoreModules"
pod 'React-Core/DevSupport', :path => "#{react_native}/"
pod 'React-RCTActionSheet', :path => "#{react_native}/Libraries/ActionSheetIOS"
pod 'React-RCTAnimation', :path => "#{react_native}/Libraries/NativeAnimation"
pod 'React-RCTBlob', :path => "#{react_native}/Libraries/Blob"
pod 'React-RCTImage', :path => "#{react_native}/Libraries/Image"
pod 'React-RCTLinking', :path => "#{react_native}/Libraries/LinkingIOS"
pod 'React-RCTNetwork', :path => "#{react_native}/Libraries/Network"
pod 'React-RCTSettings', :path => "#{react_native}/Libraries/Settings"
pod 'React-RCTText', :path => "#{react_native}/Libraries/Text", :inhibit_warnings => true
pod 'React-RCTVibration', :path => "#{react_native}/Libraries/Vibration"
pod 'React-Core/RCTWebSocket', :path => "#{react_native}/"
pod 'React-cxxreact', :path => "#{react_native}/ReactCommon/cxxreact", :inhibit_warnings => true
pod 'React-jsi', :path => "#{react_native}/ReactCommon/jsi"
pod 'React-jsiexecutor', :path => "#{react_native}/ReactCommon/jsiexecutor"
pod 'React-jsinspector', :path => "#{react_native}/ReactCommon/jsinspector"
pod 'ReactCommon/callinvoker', :path => "#{react_native}/ReactCommon"
pod 'ReactCommon/turbomodule/core', :path => "#{react_native}/ReactCommon"
pod 'Yoga', :path => "#{react_native}/ReactCommon/yoga", :modular_headers => true
pod 'DoubleConversion', :podspec => "#{react_native}/third-party-podspecs/DoubleConversion.podspec"
pod 'glog', :podspec => "#{react_native}/third-party-podspecs/glog.podspec"
# `react-native` pods
try_pod('Folly', "#{react_native}/third-party-podspecs/Folly.podspec", project_root)
# `react-native-macos` pods
try_pod('RCT-Folly', "#{react_native}/third-party-podspecs/RCT-Folly.podspec", project_root)
try_pod('boost-for-react-native',
"#{react_native}/third-party-podspecs/boost-for-react-native.podspec",
project_root)
return unless target_platform == :macos
# Hermes
begin
hermes_engine_darwin = resolve_module('hermes-engine-darwin')
pod 'React-Core/Hermes', :path => "#{react_native}/"
pod 'hermes', :path => Pathname.new(hermes_engine_darwin).relative_path_from(project_root).to_s
pod 'libevent', :podspec => "#{react_native}/third-party-podspecs/libevent.podspec"
rescue StandardError
# Use JavaScriptCore
end
end
# rubocop:enable Layout/LineLength
|
class GlobalContext
# In case methods are called on GlobalContext when it has not been set up (such as
# from shell scripts or tests), an instance of this class provides the default
# request data.
attr_accessor :password_reset
class NullRequest
attr_accessor :host
attr_accessor :url
attr_accessor :query_string
attr_accessor :remote_ip
attr_accessor :path
def parameters
@parameters ||= {}
end
def session
@session ||= {}
end
def env
@env ||= {}
end
def url
@url ||= ''
end
end
# Roll-your-own singleton behavior!
private_class_method :new
def self.instance
@instance ||= new
end
def initialize(*params)
set(*params)
end
def self.set(*params)
@instance = new(*params)
end
def set(request)
if request.kind_of?(Hash)
raise ArgumentError, "GlobalContext#set now takes a Request object as its " \
+ "sole argument, but it looks like you are still calling it the " \
+ "old way (with a session hash)."
end
@request = request
end
# Look, this class behaves just like a module with module_method at the top!
def self.method_missing(meth, *args, &block)
instance.send(meth, *args, &block)
end
def authenticated?
user && !user.anonymous?
end
def website
@website ||= Website.find_by_url(http_host)
end
def http_host
@http_host ||= @request.host || 'zaytona.com'
end
def http_host=(hostname)
@http_host = hostname
end
def set_site(site_alias)
@website = Website.find_by_alias(site_alias) || website
end
def location=(location)
session['location'] = location
end
def production_environment?
rails_environment == 'production'
end
def rails_environment
Rails.env || 'production'
end
def request
@request
end
def request_url
@request_url ||= @request.url.gsub('?%s' % @request.query_string, '')
end
def event_log_level
website && website.event_log_level
end
def test_environment?
['test', 'webrat', 'selenium', 'external_webrat', 'external_selenium', 'cucumber'].include?(Rails.env)
end
def session
@request.session
end
def user
@user ||= User.find_by_id(session[:current_user_id]) if session[:current_user_id]
end
def user=( user )
case user
when nil
session[ :current_user_id ] = nil
@user = nil
when User
session[ :current_user_id ] = user.id
@user = user
else
raise 'attempted to assign a value other than a User object to GlobalContext.user'
end
end
end
|
# frozen_string_literal: true
module Api::V1
class ResetPasswordController < ::Api::V1::ApplicationController
skip_before_action :authenticate_user, only: %i[create]
def create
api_action do |m|
m.success do
head 202
end
end
end
end
end
|
# frozen_string_literal: true
require "graphql/query/null_context"
module GraphQL
class Schema
class Object < GraphQL::Schema::Member
extend GraphQL::Schema::Member::HasFields
extend GraphQL::Schema::Member::HasInterfaces
# @return [Object] the application object this type is wrapping
attr_reader :object
# @return [GraphQL::Query::Context] the context instance for this query
attr_reader :context
# @return [GraphQL::Dataloader]
def dataloader
context.dataloader
end
# Call this in a field method to return a value that should be returned to the client
# without any further handling by GraphQL.
def raw_value(obj)
GraphQL::Execution::Interpreter::RawValue.new(obj)
end
class << self
# This is protected so that we can be sure callers use the public method, {.authorized_new}
# @see authorized_new to make instances
protected :new
# This is called by the runtime to return an object to call methods on.
def wrap(object, context)
authorized_new(object, context)
end
# Make a new instance of this type _if_ the auth check passes,
# otherwise, raise an error.
#
# Probably only the framework should call this method.
#
# This might return a {GraphQL::Execution::Lazy} if the user-provided `.authorized?`
# hook returns some lazy value (like a Promise).
#
# The reason that the auth check is in this wrapper method instead of {.new} is because
# of how it might return a Promise. It would be weird if `.new` returned a promise;
# It would be a headache to try to maintain Promise-y state inside a {Schema::Object}
# instance. So, hopefully this wrapper method will do the job.
#
# @param object [Object] The thing wrapped by this object
# @param context [GraphQL::Query::Context]
# @return [GraphQL::Schema::Object, GraphQL::Execution::Lazy]
# @raise [GraphQL::UnauthorizedError] if the user-provided hook returns `false`
def authorized_new(object, context)
maybe_lazy_auth_val = context.query.current_trace.authorized(query: context.query, type: self, object: object) do
begin
authorized?(object, context)
rescue GraphQL::UnauthorizedError => err
context.schema.unauthorized_object(err)
rescue StandardError => err
context.query.handle_or_reraise(err)
end
end
auth_val = if context.schema.lazy?(maybe_lazy_auth_val)
GraphQL::Execution::Lazy.new do
context.query.current_trace.authorized_lazy(query: context.query, type: self, object: object) do
context.schema.sync_lazy(maybe_lazy_auth_val)
end
end
else
maybe_lazy_auth_val
end
context.query.after_lazy(auth_val) do |is_authorized|
if is_authorized
self.new(object, context)
else
# It failed the authorization check, so go to the schema's authorized object hook
err = GraphQL::UnauthorizedError.new(object: object, type: self, context: context)
# If a new value was returned, wrap that instead of the original value
begin
new_obj = context.schema.unauthorized_object(err)
if new_obj
self.new(new_obj, context)
else
nil
end
end
end
end
end
end
def initialize(object, context)
@object = object
@context = context
end
class << self
# Set up a type-specific invalid null error to use when this object's non-null fields wrongly return `nil`.
# It should help with debugging and bug tracker integrations.
def const_missing(name)
if name == :InvalidNullError
custom_err_class = GraphQL::InvalidNullError.subclass_for(self)
const_set(:InvalidNullError, custom_err_class)
custom_err_class
else
super
end
end
def kind
GraphQL::TypeKinds::OBJECT
end
end
end
end
end
|
class CreateStudentAttachmentCategories < ActiveRecord::Migration
def self.up
create_table :student_attachment_categories do |t|
t.string :attachment_category_name
t.boolean :is_deletable, :default => 0
t.integer :creator_id
t.timestamps
end
end
def self.down
drop_table :student_attachment_categories
end
end
|
class StationsController < ApplicationController
def index
@stations = Station.all
respond_to do |format|
format.html
format.json { render json:@stations}
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.provider "virtualbox" do |v|
v.name = "swagger-codegen"
v.memory = 2048
v.cpus = 2
end
config.vm.box_check_update = true
#SSH
config.ssh.forward_agent = true
config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
#Provision
config.vm.provision "shell", inline: <<-SHELL
sudo touch /var/lib/cloud/instance/locale-check.skip
sudo apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
sudo sh -c 'echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" > /etc/apt/sources.list.d/docker.list'
sudo apt-cache policy docker-engine
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install -y docker-engine
sudo usermod -aG docker vagrant
SHELL
end
|
class Api::ArticlesController < ApplicationController
before_action :authenticate_user!, only: [:create, :update]
def index
articles = Article.all
render json: { articles: articles }
end
def show
article = Article.find(params['id'])
render json: { article: article }, status: 200
end
# RecordNotFound is raised when ActiveRecord cannot find record by given id or set of ids
rescue_from ActiveRecord::RecordNotFound, with: :not_found
def not_found
render json: { message: 'Unfortunately we can not find the article you are looking for.' }, status: 404
end
def create
article = Article.create(params[:article].permit(:title, :body))
if article.persisted?
render json: { message: 'Your article was successfully created' }, status: 201
else
render json: { message: article.errors.full_messages.to_sentence }, status: 422
end
end
def update
article = Article.find(params['id'])
article.update(title: params[:article][:title], body: params[:article][:body])
article.persisted?
render json: { article: article, message: 'Your article was successfully updated' }, status:202
end
end
|
class AddUuidToUser < ActiveRecord::Migration
def self.up
add_column :users, :uuid, :string, limit: 36, unique: true
add_index :users, :uuid, unique: true
end
def self.down
remove_index :users, :uuid
remove_column :users, :uuid
end
end
|
class Investment < ApplicationRecord
belongs_to :user
validates :returnRate, :totalExpectedReturn, :totalInvestedAmount, presence: true
validates :timePeriod, presence: true, numericality: {only_integer: true}
with_options if: :mode_is_sip? do |investment|
investment.validates :monthlyInvestment, presence: true
end
with_options if: :mode_is_not_sip? do |investment|
investment.validates :totalInvestment, presence: true
end
def mode_is_sip?
mode == 'sip'
end
def mode_is_not_sip?
mode != 'sip'
end
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :lists
has_many :watches
has_many :watched_lists, :class_name => "List" , :through => :watches, :source => :list
validates :name, :presence => true, :length => { :maximum => 200 }
mount_uploader :avatar, AvatarUploader
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :avatar
def watched_lists_id
watched_lists.map(&:id)
end
def to_s
name
end
end
|
class Todo < ActiveRecord::Base
validates :description, :priority, presence: true
validates :priority, numericality: { only_integer: true, greater_than: 0, less_than: 10 }
belongs_to :user
end
|
module Topographer::Generators
module Helpers
def underscore_name(name)
name.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
end
|
require File.dirname(__FILE__) + '/../test_helper'
require 'login_controller'
# Re-raise errors caught by the controller.
class LoginController; def rescue_action(e) raise e end; end
class LoginControllerTest < Test::Unit::TestCase
fixtures :users
def setup
@controller = LoginController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_valid_login
login
end
def test_invalid_login
post :login, :login => {:username=>"ga", :password=>"drowssap"}
assert_redirected_to :controller => "login", :action => "index"
assert_equal "Login failed. Try again", flash[:error]
assert_nil session[:user_id]
end
end
|
class AddOtherCnNameToWines < ActiveRecord::Migration
def change
add_column :wines, :other_cn_name, :string
end
end
|
class CommentsController < ApplicationController
before_action :comment_owner, only: [:destroy]
def comment_owner
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
unless @comment.user_id == current_user.id||@post.user_id == current_user.id
flash[:notice] = 'Access denied as you are not owner of this comment'
redirect_to posts_path
end
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:comment))
@comment.commentor=current_user.name
@comment.user_id = current_user.id
@comment.save
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
end
|
class Emailer
def initialize
@mandrill = Mandrill::API.new(ENV["MANDRILL_API_KEY"])
end
def voicemail_notification(url, duration)
message = {
"text" => "A new voicemail has arrived!\n\nListen to it here: #{url}\n#{duration} seconds long.",
"subject" => "New Voicemail",
"from_email" => ENV["EMAIL_FROM"],
"from_name" => "No Phone",
"to" => [{"email" => ENV["EMAIL_TO"],
"name" => "Collective Idea",
"type" => "to"}],
"auto_html" => true,
}
@mandrill.messages.send(message)
end
end
|
require 'test_helper'
class NonCampusStateTotalsControllerTest < ActionDispatch::IntegrationTest
setup do
@non_campus_state_total = non_campus_state_totals(:one)
end
test "should get index" do
get non_campus_state_totals_url
assert_response :success
end
test "should get new" do
get new_non_campus_state_total_url
assert_response :success
end
test "should create non_campus_state_total" do
assert_difference('NonCampusStateTotal.count') do
post non_campus_state_totals_url, params: { non_campus_state_total: { } }
end
assert_redirected_to non_campus_state_total_url(NonCampusStateTotal.last)
end
test "should show non_campus_state_total" do
get non_campus_state_total_url(@non_campus_state_total)
assert_response :success
end
test "should get edit" do
get edit_non_campus_state_total_url(@non_campus_state_total)
assert_response :success
end
test "should update non_campus_state_total" do
patch non_campus_state_total_url(@non_campus_state_total), params: { non_campus_state_total: { } }
assert_redirected_to non_campus_state_total_url(@non_campus_state_total)
end
test "should destroy non_campus_state_total" do
assert_difference('NonCampusStateTotal.count', -1) do
delete non_campus_state_total_url(@non_campus_state_total)
end
assert_redirected_to non_campus_state_totals_url
end
end
|
# In this project, you'll visualize the swapping strategy of selection sort, similar to the screenshot on the right.
# To start off with, you'll need to bring in the selection sort algorithm code from the last challenge. Then, come up with an array of data and send that through the algorithm. For each iteration of the algorithm, display the current state of the array on the canvas, and then draw a line or arrow that shows the numbers being swapped.
# Once you've successfully displayed the array being sorted, create 3 more arrays and display them as well, in a quadrant on the canvas. Create one array with reverse sorted values, one array where a few values are the same, and one array where only one value is out of order.
def displayArray(array, firstIndex, secondIndex)
newArray = Array.new
for i in 0..array.length-1 do
if i == firstIndex || i==secondIndex
newArray << "#{array[i]}*"
else
newArray << "#{array[i]}"
end
end
puts "The newArray is #{newArray}"
end
def swap(array, firstIndex, secondIndex)
displayArray(array, firstIndex, secondIndex)
temp = array[firstIndex]
array[firstIndex] = array[secondIndex]
array[secondIndex] = temp
end
def indexOfMinimum(array, startIndex)
minValue = array[startIndex]
minIndex = startIndex
for i in (minIndex + 1)..array.length-1 do
if array[i] < minValue
minIndex = i
minValue = array[i]
end
end
minIndex
end
def selectionSort(array)
for i in 0..array.length-1 do
min = indexOfMinimum(array, i)
swap(array, i, min)
end
end
array = [22, 11, 99, 88, 9, 7, 42]
selectionSort(array)
puts "Array after sorting #{array}"
array2 = [15,12, 33, 1, 8]
selectionSort(array2)
puts "Array2 after sorting #{array2}"
array3 = [25, 1, 13, 77, 9,14]
selectionSort(array3)
puts "Array3 after sorting #{array3}"
array4 = [1, 2, 3, 5, 4]
selectionSort(array4)
puts "Array4 after sorting #{array4}" |
class Piece
attr_accessor :color, :board, :position, :piece_type, :value
def initialize(board, color, position, piece_type)
@color = color
@board = board
@position = position
@piece_type = piece_type
end
def move!(to_position)
if board[to_position].nil?
@position = to_position
else
#capture the enemy piece, and put this piece there
@position = to_position
board[to_position] = self
end
end
def inspect
{ color: @color,
position: @position,
piece_type: @piece_type
}.inspect
end
def available_square?(to_position)
return false unless on_board?(to_position)
board[to_position].nil? || board[to_position].color != self.color
end
def on_board?(position)
position[0].between?(0 , 7) && position[1].between?(0 , 7)
end
def capture(other_piece)
print "This piece captured #{other_piece}."
end
def dup(new_board)
new_piece = self.class.new(new_board, color, position, piece_type)
# p new_piece.position
end
def legal_move?(to_position)
return false unless on_board?(to_position)
return false unless specific_legal_move?(to_position)
return false if board.move_puts_player_in_check?(position, to_position, color)
true
end
end
# [[piece object][nil][nil][piece_object]]
|
class Order < ApplicationRecord
belongs_to :batch, optional: true
enum status: %i[ready production closing sent]
validates :reference, :purchase_channel, :client_name, :address,
:delivery_service, :total_value, :line_items, presence: true
def self.last_by_client(client_name)
where(client_name: client_name)
.order(created_at: :asc)
.last
end
end
|
class User < ActiveRecord::Base
has_many :questions, dependent: :nullify
has_many :answers, dependent: :nullify
has_many :likes, dependent: :destroy
has_many :liked_questions, through: :likes, source: :question
has_many :favourites, dependent: :destroy
has_many :favourite_questions, through: :favourites, source: :question
has_many :votes, dependent: :destroy
has_many :voted_questions, through: :votes, source: :question
# attr_accessor :password
# attr_accessor :password_confirmation
# more info about has_secure_password can be found here:
# http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html
has_secure_password
# This enables us to store a Hash to the twitter_data field and retrieve it
# as a Hash. Rails will take care of encoding/decoding the data of the Hash
# to and from the database. It will be stored as Text in the database.
serialize :twitter_data, Hash
validates :password, length: {minimum: 6}, on: :create
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true,
uniqueness: true,
format: /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i,
unless: :from_oauth?
def from_oauth?
uid.present? && provider.present?
end
def full_name
"#{first_name} #{last_name}".titleize
end
def signed_in_with_twitter?
provider.present? && uid.present? && provider == "twitter"
end
def find_twitter_user(omniauth_data)
where(provider: "twitter", uid: omniauth_data["uid"]).first
end
def self.create_from_twitter(twitter_data)
name = twitter_data["info"]["name"].split(" ")
User.create( provider: "twitter",
uid: twitter_data["uid"],
first_name: name[0],
last_name: name[1],
password: SecureRandom.hex,
twitter_token: twitter_data["credentials"]["token"],
twitter_secret: twitter_data["credentials"]["secret"],
twitter_raw_data: twitter_data
)
end
before_create :generate_api_key
private
def generate_api_key
self.api_key = SecureRandom.hex(32)
while User.exists?(api_key: self.api_key)
self.api_key = SecureRandom.hex(32)
end
# begin
# self.api_key = SecureRandom.hex(32)
# end while User.exists?(api_key: self.api_key)
end
end
|
class Contest < ActiveRecord::Base
validates :title, :start, :end, :visibility, :participation, :presence => true
validates :visibility, :inclusion => { :in => ["public", "unlisted", "invite_only"] }
validates :participation, :inclusion => { :in => ["public", "invite_only"] }
validate :starting_and_ending_time_must_make_sense
scope :invited_but_not_participated_by, ->(user) do
where(:id => user.invited_contests).where.not(:id => user.participated_contests)
end
scope :upcoming, -> { where(arel_table[:start].gt(Time.now)) }
scope :ongoing, -> do
where(arel_table[:end].gt(Time.now).
and(arel_table[:start].lt(Time.now)))
end
scope :ended, -> { where(arel_table[:end].lt(Time.now)) }
scope :not_ended, -> { where(arel_table[:end].gt(Time.now)) }
scope :participated_by, ->(user) { where(:id => user.participated_contests) }
has_one :permalink, :as => :linkable, :dependent => :destroy
has_many :announcements, :validate => false
has_and_belongs_to_many :problems, :validate => false
belongs_to :creator, :class_name => "User", :validate => false
has_and_belongs_to_many :invited_users, :class_name => "User", :validate => false
has_and_belongs_to_many :participants, :class_name => "User", :join_table => "contests_participants", :validate => false
has_many :contest_results
accepts_nested_attributes_for :permalink, :update_only => true, :reject_if => :all_blank, :allow_destroy => true
def starting_and_ending_time_must_make_sense
if self.start && self.end && self.start > self.end
errors.add(:start, "can't happen after end")
end
end
def self.possible_visibilities
{
:public => "Public",
:unlisted => "Unlisted",
:invite_only => "Invite only"
}
end
def self.possible_participations
{
:public => "Public",
:invite_only => "Invite only"
}
end
def listed_to?(user)
if creator == user
true
elsif visibility == "public"
true
elsif visibility == "unlisted"
invited_users.include?(user)
elsif visibility == "invite_only"
invited_users.include?(user)
else
true
end
end
def visible_to?(user)
if creator == user
true
elsif visibility == "public"
true
elsif visibility == "unlisted"
true
elsif visibility == "invite_only"
invited_users.include?(user)
else
true
end
end
def can_access_problems_list?(user)
(user && user.admin?) || (status != :not_started)
end
def can_participate_by?(user)
if participation == "public"
true
elsif participation == "invite_only"
invited_users.include?(user)
else
false
end
end
def status
if Time.now < self.start
:not_started
elsif valid? && Time.now.between?(self.start, self.end)
:in_progress
elsif Time.now > self.end
:ended
end
end
def formatted_status
{
:not_started => "Not started",
:in_progress => "In progress",
:ended => "Ended"
}[status]
end
def num_problems_solved_by(user)
problems.to_a.count do |problem|
problem.solved_between_by?(Time.at(0), self.end, user)
end
end
def total_points_for(user)
problems.inject(0) do |sum, problem|
sum + problem.points_for_between(user, Time.at(0), self.end)
end
end
def leaderboard
contest_results.order(:total_score => :desc).map do |result|
{
:user => result.user,
:problems => Hash[result.scores.map do |problem_id, tasks|
[problem_id.to_i, Task.find(tasks.select { |_, v| v }.keys).inject(0) { |s, t| s + t.point }]
end],
:total_score => result.total_score
}
end
end
end
|
module Concerns::EmergencyInfo::Method
extend ActiveSupport::Concern
included do
scope :publishes, -> {where("display_start_datetime <= ? AND display_end_datetime >= ?", Time.now, Time.now)}
end
module ClassMethods
def stop_public
now_time = DateTime.now
emergency_info = self.first
if emergency_info &&
now_time.between?(emergency_info.display_start_datetime, emergency_info.display_end_datetime)
emergency_info.update(display_end_datetime: now_time)
end
end
#=== 公開中の緊急情報を1件返す。
def public_info
EmergencyInfo.publishes.order("id desc").first
end
end
end
|
# frozen_string_literal: true
module Api::V1::Admin::Users::ResetPassword
CreateSchema = Dry::Validation.Params(BaseSchema) do
required(:user_id).filled(:int?)
end
end
|
class TweetsController < ApplicationController
before_action :set_tweet, only: [:show, :edit, :update, :destroy]
# GET /tweets
# GET /tweets.json
def index
@tweets = Tweet.all
end
# GET /tweet/1
# GET /tweet/1.json
def show
end
# GET /tweet/new
def new
@tweet = Tweet.new
end
# GET /tweet/1/edit
def edit
end
# POST /tweet
# POST /tweet.json
def create
end
# PATCH/PUT /tweet/1
# PATCH/PUT /tweet/1.json
def update
end
# DELETE /tweet/1
# DELETE /tweet/1.json
def destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_tweet
@tweet = Tweet.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def tweet_params
params[:Tweet]
end
end
|
class Addcomment < ActiveRecord::Migration
def up
add_column :staff_admins,:comment,:string
end
def down
end
end
|
# frozen_string_literal: true
class TestPassagesController < ApplicationController
before_action :set_test_passage, only: %i[show update result gist]
def show; end
def result; end
def update
@test_passage.accept!(params[:answer_ids])
@test_passage.abort_test if @test_passage.time_is_up?
if @test_passage.completed?
award_user(@test_passage)
TestsMailer.completed_test(@test_passage).deliver_now
redirect_to result_test_passage_path(@test_passage)
else
render 'show'
end
end
def gist
result = GistQuestionService.new(@test_passage.current_question).call
@gist = Gist.new(question: @test_passage.current_question,
user: @test_passage.user, url: result[:html_url])
if @gist.save!
flash[:notice] = t('.success', url: (helpers.link_to t('.view_gist'), @gist.url,
target: '_blank'))
else
flash[:alert] = t('.failure')
end
redirect_to @test_passage
end
private
def award_user(test_passage)
award = BadgeAwardService.new(test_passage).call
current_user.badges.push(award)
end
def set_test_passage
@test_passage = TestPassage.find(params[:id])
end
end
|
require "student_params"
class StudentsController < ApplicationController
skip_before_action :authenticate_account!, only: [:index, :show]
before_action :profile_completedness!, only: [:new, :create]
before_action :set_student, only: [:show, :edit, :update]
def index
@students = Student.all.includes(:account, :school, :department, :major, :resume_entries)
end
def new
@student = Student.new
end
def create
munged_params = StudentParams.build(student_params)
@student = current_account.build_student(munged_params)
if @student.save && current_account.save
redirect_to profile_path, notice: "Updated profile sucessfully."
else
render :new
end
end
def edit
redirect_to @student unless current_account.username == params[:id]
end
def update
munged_params = StudentParams.build(student_params)
if @student.update_attributes(munged_params)
redirect_to @student, notice: "Profile was sucessfully updated."
else
render :edit
end
end
private
def set_student
@student = Account.friendly.find(params[:id]).student
end
def student_params
params.require(:student)
.permit(:name,
:school_name,
:graduation_year,
:department,
:major_name
)
end
end
|
class PartySerializer < ActiveModel::Serializer
attributes :id, :name, :rsvp
has_many :guests
end
|
class String
def black; "\033[30m#{self}\033[0m" end
def red; "\033[31m#{self}\033[0m" end
def green; "\033[32m#{self}\033[0m" end
def brown; "\033[33m#{self}\033[0m" end
def blue; "\033[34m#{self}\033[0m" end
def magenta; "\033[35m#{self}\033[0m" end
def cyan; "\033[36m#{self}\033[0m" end
def gray; "\033[37m#{self}\033[0m" end
end
class Mastermind
attr_accessor :solution_peg_array, :player_hash, :cpu_hash , :Cpu_player , :player , :coder_input_array
def initialize
@solution_peg_array = 4.times.map{(['red','green','brown','blue','magenta','cyan'].sample)}
@player = Player.new
@coder_input_array = Array.new
end
def compare_guess
if @player.last_guess == @solution_peg_array
puts "\nI win! #{@player.last_guess} is correct! It took me #{13-@player.guesses_left} guesses!"
else
cpu_hash = Hash.new(0)
player_hash = Hash.new(0)
matches = 0
color_only = 0
incorrect = 0
j = 0
while j < 4
if @solution_peg_array[j] == @player.last_guess[j]
matches += 1
@player.saved_guesses[j] = @player.last_guess[j]
end
j += 1
end
@solution_peg_array.each{|color| cpu_hash[color] +=1}
@player.last_guess.each{|color| player_hash[color] +=1}
cpu_hash.each{|key,value| incorrect += [(value - player_hash[key]),0].max}
puts "\n Guess #{13-@player.guesses_left} is wrong... darnit! #{@player.last_guess} is not correct."
puts "Correctly guessed #{matches} pegs!"
color_only = 4-(incorrect+matches)
puts "#{color_only} color-only matches."
puts "#{incorrect} incorrect"
@player.guesses_left -=1
self.play
end
end
def play
incorrect = 0
matches = 0
color_only = 0
if @player.guesses_left > 0
@player.make_guess
self.compare_guess
else
puts "No guesses left!"
end
end
def who_is_playing
puts "Lets Play Mastermind! Would you like to be coder or decoder? (type 'coder' or 'decoder')".red
coder_or_decoder = gets.chomp
if coder_or_decoder == 'decoder'
self.play
else
puts "\nSo you think you can code...huh?"
puts "\nI never lose! Give me 6 guesses...max!"
puts "Enter your 4 colors! You can choose #{'red'.red}, #{'green'.green}, #{'brown'.brown}, #{'blue'.blue}, #{'magenta'.magenta}, or #{'cyan'.cyan} "
puts "\nPeg 1"
@coder_input_array << gets.chomp
puts "\nPeg 2"
@coder_input_array << gets.chomp
puts "\nPeg 3"
@coder_input_array << gets.chomp
puts "\nPeg 4"
@coder_input_array << gets.chomp
@player.player_human = false
@solution_peg_array = @coder_input_array
self.play
end
end
end
class Player
attr_accessor :guesses_left, :last_guess, :player_human , :saved_guesses , :colors , :saved_colors, :slot_one_colors, :slot_two_colors, :slot_three_colors, :slot_four_colors
def initialize
@guesses_left = 12
@last_guess = Array.new
@player_human = true
@saved_guesses = ['','','','']
@colors = ['red','green','brown','blue','magenta','cyan']
@slot_one_colors = ['red','green','brown','blue','magenta','cyan']
@slot_two_colors = ['red','green','brown','blue','magenta','cyan']
@slot_three_colors = ['red','green','brown','blue','magenta','cyan']
@slot_four_colors = ['red','green','brown','blue','magenta','cyan']
end
def make_guess
if @player_human == true
@last_guess = Array.new
puts "Guess peg 1"
@last_guess << gets.chomp
puts "Guess peg 2"
@last_guess << gets.chomp
puts "Guess peg 3"
@last_guess << gets.chomp
puts "Guess peg 4"
@last_guess << gets.chomp
puts "Last guess was #{last_guess} "
end
if @player_human == false
@last_guess = Array.new
i = 0
while i < 4
if @saved_guesses[i] != ''
@last_guess[i] = @saved_guesses[i]
else
if i == 0
samp = @slot_one_colors.sample
@slot_one_colors -= [samp]
@last_guess[i] = samp
elsif i == 1
samp = @slot_two_colors.sample
@slot_two_colors -= [samp]
@last_guess[i] = samp
elsif i == 2
samp = @slot_three_colors.sample
@slot_three_colors -= [samp]
@last_guess[i] = samp
else
samp = @slot_four_colors.sample
@slot_four_colors -= [samp]
@last_guess[i] = samp
end
end
i+=1
end
end
end
end
puts Mastermind.new.who_is_playing
|
class RemoveJobRequestIdFromQuotations < ActiveRecord::Migration[5.1]
def change
remove_reference :quotations, :job_request, foreign_key: true
end
end
|
require 'httparty'
require 'active_support/all'
module SpyFu
class Configuration
attr_accessor :secret_key, :user_id, :base_url
def initialize
self.secret_key = nil
self.user_id = nil
self.base_url = 'http://www.spyfu.com'
end
end
def self.configuration
@configuration ||= Configuration.new
end
def self.configure
yield(configuration) if block_given?
end
def self.core_api
SpyFu::Requests::CoreApi
end
def self.kss_api
SpyFu::Requests::KssApi
end
def self.leads_api
SpyFu::Requests::LeadsApi
end
def self.tracking_api
SpyFu::Requests::TrackingApi
end
def self.url_api
SpyFu::Requests::UrlApi
end
end
require 'spy_fu/version'
require 'spy_fu/build_message'
require 'spy_fu/build_request'
require 'spy_fu/build_signature'
require 'spy_fu/errors'
require 'spy_fu/request'
require 'spy_fu/response'
require 'spy_fu/requests/url_api'
require 'spy_fu/requests/tracking_api'
require 'spy_fu/requests/leads_api'
require 'spy_fu/requests/kss_api'
require 'spy_fu/requests/core_api'
|
require './test/test_helper'
class ViewDetailsTest < FeatureTest
include Rack::Test::Methods
def setup
post '/sources', PayloadSamples.register_users
PayloadSamples.initial_payloads.each do |payload|
post '/sources/jumpstartlab/data', payload
end
end
def test_user_can_view_all_data_at_homepage
visit '/sources/jumpstartlab'
assert page.has_content?("Requested URLs")
assert page.has_content?("http://jumpstartlab.com/index: 4")
assert page.has_content?("Web Browser Breakdown")
assert page.has_content?("Chrome: 7")
assert page.has_content?("OS Breakdown")
assert page.has_content?("OS X 10.8.2")
assert page.has_content?("Screen Resolution")
assert page.has_content?("1920 X 800: 6")
assert page.has_content?("Average URL Response Time")
assert page.has_content?("http://jumpstartlab.com/home: 38")
assert page.has_content?("Links to URL Stats")
assert page.has_content?("jumpstartlab/urls/home")
assert page.has_content?("Links to Event Stats")
assert page.has_content?("Event stats")
end
def test_registered_user_with_no_payload_sees_no_data
visit '/sources/jumpstartlab'
assert page.has_content?("Requested URLs")
assert page.has_content?("Web Browser Breakdown")
assert page.has_content?("OS Breakdown")
assert page.has_content?("Screen Resolution")
assert page.has_content?("Average URL Response Time")
assert page.has_content?("Links to URL Stats")
assert page.has_content?("Links to Event Stats")
end
def test_unregistered_user_returns_error_message
visit '/sources/google'
assert page.has_content? "Identifier does not exist"
end
def test_url_links_redirect_to_individual_stat_pages
visit '/sources/jumpstartlab'
click_link_or_button("/index_link")
assert_equal "/sources/jumpstartlab/urls/index", current_path
end
def test_url_links_redirect_to_event_stats_page
visit '/sources/jumpstartlab'
click_link_or_button("event_link")
assert_equal "/sources/jumpstartlab/events", current_path
end
end
|
##
# La classe qui gére l'affichage de la progression de l'utilisateur dans l'aventure
##
# * +win+ La fenêtre de l'application
# * +boite+ Le layout pour placer tous les boutons et afficher l'image de fond
# * +retourMenu+ Bouton permettant de retourner au menu principal
# * +map+ Nom du fichier de la grille utilisée
# * +chronoLabel+ Label contenant le temps total du joueur sur une grille en cours
# * +penalitesLabel+ Label contenant les pénalités du joueur sur une grille en cours
# * +grille+ La grille de jeu affichée
# * +nbLignes+ Le nombre de lignes du fichier
# * +file_data+ Les données du fichier
# * +i_chap+ Index du chapitre
class Ecran_progression
##
# Constructeur de la classe
##
# * +win+ La fenetre de l'application
def Ecran_progression.creer(win)
new(win)
end
private_class_method :new
##
# Construction de l'instance
##
# * +win+ La fenetre de l'application
def initialize(win)
# init des composants
@win = win
@map = "../Grilles/grille_chapitre1.txt"
@boite = Gtk::Fixed.new()
container = Gtk::Box.new(:vertical)
@retourMenu = Gtk::Button.new(:label => "")
defilerChapitres = Gtk::Button.new(:label => "")
# Création tableau de boutons
btnChapitre = [
Gtk::Button.new(),
Gtk::Button.new(),
Gtk::Button.new(),
Gtk::Button.new(),
Gtk::Button.new()
]
# Création tableau de labels
lblChapitre = [
Gtk::Label.new(""),
Gtk::Label.new(""),
Gtk::Label.new(""),
Gtk::Label.new(""),
Gtk::Label.new("")
]
# Chargement background
@boite.add(Gtk::Image.new(:file => "../maquettes/menu-progression.png"))
container.add(@boite)
# Création css texte labels
cssChapitre = ajouteTexte(3)
# Ajout des boutons dans la sidebar
addChapitre(btnChapitre[0], lblChapitre[0], 13, 20, cssChapitre)
addChapitre(btnChapitre[1], lblChapitre[1], 13, 155, cssChapitre)
addChapitre(btnChapitre[2], lblChapitre[2], 13, 285, cssChapitre)
addChapitre(btnChapitre[3], lblChapitre[3], 13, 420, cssChapitre)
addChapitre(btnChapitre[4], lblChapitre[4], 13, 550, cssChapitre)
# Ajout boutons retour vers menu et défiler chapitres
ajouteBouton(@boite, defilerChapitres, 2, 45, 45, 230, 620, method(:actualiserChapitres), lblChapitre, nil)
ajouteBouton(@boite, @retourMenu, 2, 60, 60, 20, 5, method(:vers_menu), @win, container)
# Ajoute label pour chrono des grilles sauvegardées
@chronoLabel = Gtk::Label.new("")
ajouteTexteProvider(@chronoLabel, cssChapitre)
@boite.put(@chronoLabel, 500, 615)
@penalitesLabel = Gtk::Label.new("")
ajouteTexteProvider(@penalitesLabel, cssChapitre)
@boite.put(@penalitesLabel, 960, 615)
@win.add(container)
# Chargement de la grille 1
if (Grille_jeu_charger.exist?(@map, 'Aventure'))
@grille = Grille_jeu_charger.creer(false, Array.new, @map, nil, 'Aventure')
@chronoLabel.label = @grille.getChrono()
@penalitesLabel.label = @grille.getPenalites()
else
@grille = Grille_jeu.creer(false, nil, @map)
@chronoLabel.label = "0' 0''"
@penalitesLabel.label = "0' 0''"
end
@boite.put(@grille.grille, ($widthEcran *0.37), $heightEcran * 0.16)
file = File.open("chapitres.txt")
lignes = file.readlines
@nbLignes = lignes.size
@file_data = lignes.map(&:chomp)
file.close
@i_chap = 0
# Placement des bons labels de chapitres
actualiserChapitres(lblChapitre)
@win.show_all
Gtk.main
return self
end
##
# Ajoute un chapitre dans la boite
##
# * +bouton+ Le bouton contenant le label
# * +label+ Le label à styliser
# * +css+ Le css a appliquer
# * +x+ Position en abscisse
# * +y+ Postion en ordonnée
def addChapitre(bouton, label, x, y, css)
ajouteBouton(@boite, bouton, 3, 260, 115, x, y, method(:eventChangerChapitre), label, nil)
ajouteTexteProvider(label, css)
bouton.add(label)
return self
end
##
# Change la grille en fonction du chapitre sélectionné
# * +label+ label du chapitre cliqué
def eventChangerChapitre(label)
#Cherche le numéro du chapitre sélectionné dans le label
@boite.remove(@grille.grille)
@map = "../Grilles/grille_chapitre" + label.label.gsub(/[^0-9]/, '') + ".txt"
if (Grille_jeu_charger.exist?(@map, 'Aventure'))
@grille = Grille_jeu_charger.creer(false, Array.new, @map, nil, 'Aventure')
@chronoLabel.label = @grille.getChrono()
@penalitesLabel.label = @grille.getPenalites()
else
@grille = Grille_jeu.creer(false, nil, @map)
@chronoLabel.label = "0' 0''"
@penalitesLabel.label = "0' 0''"
end
if (@grille.nbLignes == 10)
@boite.put(@grille.grille, ($widthEcran *0.37), $heightEcran * 0.16)
elsif (@grille.nbLignes == 15)
@boite.put(@grille.grille, ($widthEcran *0.36), $heightEcran * 0.16)
else
@boite.put(@grille.grille, ($widthEcran *0.35), $heightEcran * 0.11)
end
@win.show_all
return self
end
##
# Permet de changer les chapitres à l'appuie de la flèche
# * +lblChapitre+ Liste des labels à actualiser
def actualiserChapitres(lblChapitre)
lblChapitre.each {|lbl| lbl.label = nextChapitre() }
return self
end
##
# Charge le texte d'un chapitre dans le label
def nextChapitre()
until (@file_data[@i_chap].gsub(" ", "").start_with?("Chapitre"))
@i_chap += 1
if @i_chap == @nbLignes
@i_chap = 0
end
end
str = @file_data[@i_chap].gsub(" ", "").gsub(": ", "\n")
if (str.size > 27)
str = str[0...-9] + "..."
elsif (str.size < 23)
spaces = "";
0.upto((14 - (str.size - 10)) / 2 ) { spaces += " " }
str.insert(12, '♦')
str = str.gsub("♦", spaces)
end
@i_chap += 1
return " " + str
end
end |
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def valid_move?(board, index)
if index.between?(0, 8) && !position_taken?(board, index)
true
else
false
end
end
def position_taken?(board, position)
board[position] == "X" || board[position] == "O"
end
# What does it mean to encapsulate the logic? Hint from the text: Encapsulate the logic to check if a position is occupied in its own method, perhaps #position_taken
def input_to_index(move)
index = move.to_i - 1
end
def move(board, index, value = "X")
#in here, when no 3rd argument is given, value is "O"
#board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
#board[index] == " " but we want to make it whatever value is so:
board[index] = value
#now, board will have a token somewhere and might look like this if value is "X" and index is 0:
#board = ["X", " ", " ", " ", " ", " ", " ", " ", " "]
end
def turn(board)
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(board, index)
move(board, index)
display_board(board)
else
turn(board)
end
end
|
# => Contient la classe FenetreNouvellePartie qui propose le mode aventure ou apprentissage
#
# => Author:: Valentin, DanAurea
# => Version:: 0.1
# => Copyright:: © 2016
# => License:: Distributes under the same terms as Ruby
##
## classe FenetreNouvellePartie
##
class FenetreNouvellePartie < View
# VI box
@boxTop
@boxBottom
# VI bouton
@boutonApprentissage
@boutonJeuLibre
# VI label
@titreLabel
##
## Initialize
##
def initialize()
# VI box
@boxTop = Gtk::Box.new(:vertical,0)
@boxBottom = Fenetre::creerBoxBottom()
# VI bouton
@boutonApprentissage = Gtk::Button.new(:label => "Apprentissage avec aides")
@boutonJeuLibre = Gtk::Button.new(:label => "Jeu libre")
# VI label
@titreLabel = Fenetre::creerLabelType("<u>Nouvelle partie</u>",Fenetre::SIZE_TITRE)
end
##
## Permet de créer et d'ajouter les box au conteneur principal
##
##
def miseEnPlace()
creerBoxTop()
ajoutCss()
Fenetre::box.add(@boxTop)
Fenetre::box.add(@boxBottom)
end
##
## Créer la box verticale contenant les boutons des choix du mode de jeu et le titre
##
##
def creerBoxTop()
#Action des boutons
@boutonApprentissage.signal_connect('clicked'){
Core::changeTo("Apprentissage", "pseudo": @pseudo)
}
@boutonJeuLibre.signal_connect('clicked'){
Core::changeTo("Niveau", "pseudo": @pseudo)
}
#add des boutons à la box
@boxTop.add(@titreLabel)
@boxTop.add(@boutonApprentissage)
@boxTop.add(@boutonJeuLibre)
end
##
## Ajoute les classes css au widget
##
def ajoutCss()
#css label
@titreLabel.override_color(:normal, Fenetre::COULEUR_BLANC)
@titreLabel.set_margin_top(30)
#css bouton
@boutonApprentissage.set_margin_top(100)
@boutonApprentissage.set_margin_bottom(50)
@boutonApprentissage.set_margin_left(100)
@boutonApprentissage.set_margin_right(100)
@boutonJeuLibre.set_margin_bottom(50)
@boutonJeuLibre.set_margin_left(100)
@boutonJeuLibre.set_margin_right(100)
end
##
## Lance la construction du modèle de la vue. Méthode à définir dans tout les cas ! Autrement pas de rendu de la page.
##
## @return self
##
def run()
self.miseEnPlace()
return self
end
end
|
=begin
(Understand the Problem)
Problem:
Write a method that takes an Array of numbers, and returns an Array with the same number of elements, and each element has the running total from the original Array.
Inputs: array of numbers
Outputs: array of numbers
Questions:
1.
Explicit Rules:
1. output array will contain the same number of elements
2. each element should be the running total from original array
Implicit Rules:
1.
2.
Mental Model:
- write a method that takes an array of numbers
- return an array with the same number of elements, but consists of the running total of each element from original array
(Examples/Test Cases)
running_total([2, 5, 13]) == [2, 7, 20]
running_total([14, 11, 7, 15, 20]) == [14, 25, 32, 47, 67]
running_total([3]) == [3]
running_total([]) == []
(Data Structure)
array(consisting of numbers)
(Algorithm)
- create a method that takes an array of numbers
- within the array, create a 'total' variable that contains 0
- using the `map` method, iterate through array and add total to each number to populate new array
(Code)
=end
def running_total(array)
total = 0
new_array = array.map do |num|
total += num
end
new_array
end
p running_total([2, 5, 13]) == [2, 7, 20]
p running_total([14, 11, 7, 15, 20]) == [14, 25, 32, 47, 67]
p running_total([3]) == [3]
p running_total([]) == [] |
execute 'gem install rails' do
only_if { platform_family?('windows') }
end
|
require_relative '../test_case'
module RackRabbit
class TestResponse < TestCase
#--------------------------------------------------------------------------
def test_response
response = build_response(200, BODY, :foo => "bar")
assert_equal(200, response.status)
assert_equal("bar", response.headers[:foo])
assert_equal(BODY, response.body)
assert_equal(true, response.succeeded?)
assert_equal(false, response.failed?)
assert_equal(BODY, response.to_s)
end
#--------------------------------------------------------------------------
def test_succeeded_and_failed
expected_success = [ 200, 201, 202 ]
expected_failure = [ 400, 404, 500 ]
expected_success.each do |status|
response = build_response(status, BODY)
assert_equal(true, response.succeeded?, "status #{status} should be considered a success")
assert_equal(false, response.failed?, "status #{status} should be considered a success")
end
expected_failure.each do |status|
response = build_response(status, BODY)
assert_equal(false, response.succeeded?, "status #{status} should be considered a failure")
assert_equal(true, response.failed?, "status #{status} should be considered a failure")
end
end
#--------------------------------------------------------------------------
def test_to_s
r1 = build_response(200, BODY)
r2 = build_response(400, BODY)
r3 = build_response(404, BODY)
r4 = build_response(500, BODY)
assert_equal(BODY, r1.to_s)
assert_equal("400 Bad Request", r2.to_s)
assert_equal("404 Not Found", r3.to_s)
assert_equal("500 Internal Server Error", r4.to_s)
end
#--------------------------------------------------------------------------
end # class TestResponse
end # module RackRabbit
|
class DataDefinitionsController < ApplicationController
before_action :set_data_definition, only: [:show, :edit, :update, :destroy]
# GET /data_definitions
def index
@table_names=DataDefinition.all.collect{|x|x.table_name}.uniq
@tables=[]
@table_names.each {|name|
@tables << {:name=>name, :columns=>DataDefinition.where('table_name = ?', name)}
}
end
private
# Use callbacks to share common setup or constraints between actions.
def set_data_definition
@data_definition = DataDefinition.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def data_definition_params
params.fetch(:data_definition, {})
end
end
|
require "easy_start/version"
require 'active_support/all'
module EasyStart
def self.add(project)
base_data = {'project_name' => '', 'project_path' => ''}
base_data.each do |key,value|
loop do
base_data[key] = project[key]
unless base_data[key].present?
puts "Enter #{key}"
input = gets.chomp
base_data[key] = input
end
break if base_data[key].present?
end
end
create_script base_data
end
def self.create_script base_data
create_directory_if_not_found
file_path = File.join(File.dirname(__FILE__), "../scripts/#{base_data['project_name']}.sh")
File.open(file_path, 'w') {|f| f.write("ROOT_PATH=\"#{base_data['project_path']}\"\n" + meta_data) }
system "chmod 755 #{file_path}"
end
def self.create_directory_if_not_found
directory_path = File.join(File.dirname(__FILE__), "../scripts")
unless File.directory?(directory_path)
Dir.mkdir directory_path
end
end
def self.launch(name,branch='')
begin
file_path = File.join(File.dirname(__FILE__), "../scripts/#{name}.sh")
a = system "#{file_path}",(branch || '')
rescue SystemExit, Interrupt
exit 0
rescue Exception => e
puts e
end
end
def self.meta_data
['cd "$ROOT_PATH"','if [ -n "$1" ]; then','git checkout $1','git pull','fi','rails s'].join("\n")
end
end
|
require './player'
def read_input
if ARGV.empty?
gets
else
val = ARGV.shift
puts val
val
end
end
class CLI
def self.start
new.start
end
def initialize
@players = []
end
def start
@players << get_player(1)
@players << get_player(2)
@current_player_index = rand(@players.size)
loop do
action = prompt_turn
break if action == "quit"
execute(action)
next_player
end
print "Goodbye"
end
def next_player
@current_player_index = (@current_player_index + 1) % @players.size
end
def get_player(n)
print "Enter name for player ##{n}: "
Player.new read_input.chomp
end
def current_player
@players[@current_player_index]
end
def prompt_turn
dump_boards
print "#{current_player}'s turn: "
read_input.chomp
end
def dump_boards
end
def execute(action)
end
end
CLI.start
|
require 'spec_helper'
describe "solicitacao_tipos/new" do
before(:each) do
assign(:solicitacao_tipo, stub_model(SolicitacaoTipo,
:tipo => "MyString"
).as_new_record)
end
it "renders new solicitacao_tipo form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form[action=?][method=?]", solicitacao_tipos_path, "post" do
assert_select "input#solicitacao_tipo_tipo[name=?]", "solicitacao_tipo[tipo]"
end
end
end
|
require 'spec_helper'
describe "watch_sites/show" do
before(:each) do
@theStubTeam = stub_model(Team, name:"Seahawks", id:1 )
@theStubVenue = stub_model(Venue, name:"Eat At Joes", id:1)
@watch_site = assign(:watch_site, stub_model(WatchSite,
:name => "hawkers site",
:team => @theStubTeam,
:venue => @theStubVenue
))
end
it "renders attributes in <p>" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
rendered.should match(/Name/)
rendered.should match(/Seahawks/)
rendered.should match(/Eat At Joes/)
end
end
|
Rails.application.routes.draw do
get 'comments/create'
get 'comments/distroy'
get 'feed/show'
get 'comments/show_post_comments'
resources :posts
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: redirect('/login')
devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', password: 'secret', confirmation: 'verification', unlock: 'unblock', registration: 'register', sign_up: 'cmon_let_me_in' }
devise_scope :user do
get 'signup' => 'users#signup'
end
resources :users do
member do
put '/admin' => 'users#make_admin', as: :make_admin
end
end
end |
class CreatePeople < ActiveRecord::Migration
def change
create_table :people do |t|
t.string :title
t.string :intro
t.string :cv
t.string :file
t.timestamps
end
end
end
|
# Find the Duplicates
# Sometimes you need to compare lists of number, but sorting each one normally will take too much time. Instead you can use alternative methods to find the differences between each list. Try to find a faster way to do this challenge than sorting two entire lists.
# Challenge
# Numeros The Artist was arranging two identical lists of numbers A and B into specific orders. While it seemed like two random arrangements to everyone else, Numeros was very proud of his arrangements. Unfortunately, some numbers got left out of List A. Can you find the missing numbers from A without messing up his order?
# Details
# There are many duplicates in each list, but you need to find the extra numbers in B that remain once all the AB "matches" have been found. The numbers are all within a range of 100 from each other.
# Guideline
# Don't sort the lists to solve this problem. In fact, you can solve it with one pass through each of the lists.
# Challenge
# Find all the 'extra' numbers that are in B but not in A, and output them in ascending order.
# Example
# p duplicates([203, 204, 205, 206, 207, 208, 203, 204, 205, 206], [203, 204, 204, 205, 206, 207, 205, 208, 203, 206, 204, 205, 206])
# # => [204, 205, 206]
# These numbers are extra in the 2nd list. Note each list can be in any order and the extra numbers
# can appear anywhere in the list.
def duplicates(arr1, arr2)
# write your code here
end
p duplicates([203, 204, 205, 206, 207, 208, 203, 204, 205, 206], [203, 204, 204, 205, 206, 207, 205, 208, 203, 206, 204, 205, 206])
# => [204, 205, 206] |
# Make a dog class
class Dog
attr_accessor :name, :breed
# Shortcut for:
# def name
# @name
# end
# def breed
# @breed
# end
# attr_writer :age
# Shortcut for:
# def age=(new_age)
# @age = new_age
# end
attr_accessor :age, :weight
# Shortcut for:
# attr_reader :age
# attr_writer :age
# attr_reader :weight
# attr_writer :weight
# JavaScript: constructor
def initialize(the_dog_name, the_breed, age)
# This the method that gets called
# whenever we make a new instance
# of Dog
# JavaScript
# this.name = 'Riley'
# Use an idea called instance variables
@name = the_dog_name
@breed = the_breed
@age = age
# this variable goes away when the method is over
# But @name sticks around
# name = 'Riley'
end
def speak
puts "The dog named #{name} that is a #{breed} says: Woof"
end
end
# JavaScript: const riley = new Dog
riley = Dog.new('Riley', "Dachsund", 3)
roscoe = Dog.new('Roscoe', "Dachsund", 7)
p riley
p roscoe
riley.speak
roscoe.speak
p riley.name
p roscoe.name
puts "Riley is #{riley.age} years old"
# riley.age = 4
riley.age = 5
puts "Riley is #{riley.age} years old"
p riley.weight
riley.weight = 12
p riley.weight
# JavaScript: class GoodDog extends Dog
#
# GoodDog is a CHILD class of Dog
# Dog is the PARENT class of GoodDog
#
# GoodDog can do everything a Dog can do
class GoodDog < Dog
def treat
puts "#{name} says: Mmmmmm, thanks!"
end
def speak
puts "I am a good dog!"
end
end
kali = GoodDog.new("Kali", "Pitbull", 9)
p kali
kali.treat
kali.speak
|
gem 'minitest'
require_relative '../lib/player'
require_relative '../lib/scrabble'
require 'minitest/autorun'
require 'minitest/pride'
require 'pry'
class PlayerTest < Minitest::Test
def setup
@player_1 = Player.new(Scrabble.new)
end
def test_total_score_starts_at_0
assert_equal 0, @player_1.total_score
end
def test_total_score_increases
@player_1.play('bear')
assert_equal 6, @player_1.total_score
@player_1.play('quality')
assert_equal 25, @player_1.total_score
@player_1.play('heloooo')
assert_equal 25, @player_1.total_score
end
def test_turns_starts_at_0
assert_equal 0, @player_1.turns
end
def test_turns_increase_when_playing
@player_1.play('bear')
@player_1.play('quality')
@player_1.play('heloooo')
assert_equal 3, @player_1.turns
end
end
|
require_relative "lib/user"
require_relative "model/trivia"
require_relative "model/trivia_session"
require_relative "model/trivia_dao"
require_relative "lib/cdn_upload"
require "yaml"
require_relative "lib/rel_cache"
require_relative "lib/db_factory"
require "bcrypt"
namespace :sample do
desc "Say Hi"
task :hi do
trivia = Trivia.new("Hello World")
trivia.add_question("Do you like bagels?", ["sometimes", "never"])
trivia.add_question("Do you like panera?", "sometimes")
trivia_serial = YAML::dump(trivia)
puts trivia_serial
trivia_load = YAML::load(trivia_serial)
puts trivia_load.questions[1]
end
desc "Push to CDN"
task :push_cdn do
cdn = CDNUpload.new
cdn.post_to_cdn
cdn.write_config
cdn.delete_old_from_cdn
end
desc "Say Kelton"
task :kelton do
puts "Kelton"
end
desc "Say Hi To Kelton"
task :talk => [:hi, :kelton] do
end
desc "List Fake user permissions"
task :perm do
user = User.fake_user("1234")
puts user.roles
end
desc "Save Trivia"
task :save_trivia do
cache = CacheFactory.instance.cache
trivia = Trivia.new(SecureRandom.hex(30))
trivia.name = "My First Trivia"
trivia.add_question("Do you like bagels?", ["sometimes", "never"])
trivia.add_question("Do you like panera?", "sometimes")
#cache.set("trivia", trivia, 60)
TriviaDAO.instance
#puts DBFactory.instance.sql_at("trivia/trivia_delete.sql")
trivia2 = Trivia.new(SecureRandom.hex(30))
trivia2.name = "My Second Trivia"
trivia2.add_question("Do you like bagels?", ["sometimes", "never"])
trivia2.add_question("Do you like panera?", "sometimes")
#TriviaDAO.save(trivia, "kelton")
#TriviaDAO.save(trivia2, "kelton")
#puts TriviaDAO.get_by_member("kelton", 0, 2)[1].name
end
desc "Cache sample"
task :cache_sample do
cache = CacheFactory.instance.cache
#trivia = Trivia.new(SecureRandom.hex(30))
#trivia.name = "My First Trivia"
#cache.set("trivia_" + trivia.trivia_id, trivia)
new_trivia = cache.get("trivia_9d52f81b2e93dfc4065d9b2cd7e43f7549e66b44a5b76237f5e662bf137f")
puts new_trivia.name
end
desc "Get Trivia"
task :get_trivia do
trivia = TriviaDAO.get_by_id_member("a5b318f564694cd6ef2057b0bfb370bfe82def6fdc57fb351ba3cd4b2ca3", "kelton")
TriviaDAO.delete(trivia)
end
desc "Cache Sample"
task :cache_read do
TriviaDAO.get_by_member("kelton", skip = 3, limit = 3)
#cache = RelCache.new
#trivia_session = cache.get("trivia_session_d1acdcf348c8158f4d9e5f39dbfd74e2c5bdbe9a6f5e8ad8edce48ad0ea7")
#puts trivia_session.curr_question
end
end
desc "Default Task (talk)"
task :default => "sample:talk"
desc "Speak"
task :speak do
puts "Speak"
end
|
require 'rails_helper'
RSpec.describe ApplicationHelper, type: :helper do
describe 'full title helper' do
let(:base_title) { 'ピスカティオ' }
context 'case page title is default' do
let(:default_title) { full_title('') }
it 'show title as ピスカティオ' do
expect(default_title).to eq "#{base_title}"
end
end
context 'case page title present' do
let(:title) { full_title('買い物カゴ') }
it 'show title as ピスカティオ | 買い物カゴ' do
expect(title).to eq "#{base_title} | 買い物カゴ"
end
end
end
end
|
class GoodDog
attr_accessor :name, :height, :weight
def initialize(n, h, w)
self.name = n
self.height = h
self.weight = w
end
def change_info(n, h, w)
self.name = n
self.height = h
self.weight = w
end
def info
"#{self.name} weighs #{self.weight} and is #{self.height} tall."
end
def what_is_self
self
end
end
class CoolStuff
def self.this_is_a_class_method
end
end
jimbo = GoodDog.new('Jimbo', '50cm', '15kg')
puts jimbo.info
p jimbo
jimbo.change_info('Leonard', '40cm', '12kg')
puts jimbo.info
puts jimbo.what_is_self
# 'self' is more or less 'this' in JS
# 1. self, inside of an instance method, references the instance (object) that called the method - the calling object. Therefore, self.weight= is the same as sparky.weight=, in our example.
# 2. self, outside of an instance method, references the class and can be used to define class methods. Therefore if we were to define a name class method, def self.name=(n) is the same as def GoodDog.name=(n). |
# frozen_string_literal: true
HealthQuest::Engine.routes.draw do
namespace :v0, defaults: { format: :json } do
resources :appointments, only: %i[index show]
resources :pgd_questionnaires, only: %i[show]
resources :questionnaire_responses, only: %i[index show create]
get 'apidocs', to: 'apidocs#index'
end
end
|
# Customise this file, documentation can be found here:
# https://github.com/fastlane/fastlane/tree/master/fastlane/docs
# All available actions: https://docs.fastlane.tools/actions
# can also be listed using the `fastlane actions` command
# Change the syntax highlighting to Ruby
# All lines starting with a # are ignored when running `fastlane`
# If you want to automatically update fastlane if a new version is available:
# update_fastlane
# This is the minimum version number required.
# Update this, if you use features of a newer version
fastlane_version "2.24.0"
default_platform :ios
platform :ios do
before_all do
# ENV["SLACK_URL"] = "https://hooks.slack.com/services/..."
end
desc "Fix code format in dev or check code format in CI"
lane :format do
Dir.chdir("..") do
sh 'cp ./dotfiles/.clang-format .'
if ENV["CI"] then
cmd = 'find ./ -path .//Example/Pods -prune -o -name "*.[hm]" -exec clang-format -style=file -output-replacements-xml "{}" \; | grep "<replacement " >/dev/null'
system(cmd)
raise "code did not match clang-format" unless $?.exitstatus == 1
next
end
cmd = 'find ./ -path .//Example/Pods -prune -o -name "*.[hm]" -exec clang-format -i -style=file "{}" \;'
sh cmd
end
end
# # fix code format
# sh 'cp ./dotfiles/.clang-format .'
# sh "find #{base_path} -name \"*.[hm]\" -exec clang-format -i -style=file \"{}\" \\;"
# end
# end
after_all do |lane|
# This block is called, only if the executed lane was successful
# slack(
# message: "Successfully deployed new App Update."
# )
end
error do |lane, exception|
# slack(
# message: exception.message,
# success: false
# )
end
end
# More information about multiple platforms in fastlane: https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Platforms.md
# All available actions: https://docs.fastlane.tools/actions
# fastlane reports which actions are used
# No personal data is recorded. Learn more at https://github.com/fastlane/enhancer
|
# frozen_string_literal: true
require "concurrent/map"
module Dry
module Logic
def self.Rule(*args, **options, &block)
if args.any?
Rule.build(*args, **options)
elsif block
Rule.build(block, **options)
end
end
class Rule
include Core::Constants
include Dry::Equalizer(:predicate, :options)
include Operators
attr_reader :predicate
attr_reader :options
attr_reader :args
attr_reader :arity
def self.interfaces
@interfaces ||= ::Concurrent::Map.new
end
def self.specialize(arity, curried, base = Rule)
base.interfaces.fetch_or_store([arity, curried]) do
interface = Interface.new(arity, curried)
klass = Class.new(base) { include interface }
base.const_set("#{base.name.split("::").last}#{interface.name}", klass)
klass
end
end
def self.build(predicate, args: EMPTY_ARRAY, arity: predicate.arity, **options)
specialize(arity, args.size).new(predicate, {args: args, arity: arity, **options})
end
def initialize(predicate, options = EMPTY_HASH)
@predicate = predicate
@options = options
@args = options[:args] || EMPTY_ARRAY
@arity = options[:arity] || predicate.arity
end
def type
:rule
end
def id
options[:id]
end
def curry(*new_args)
with(args: args + new_args)
end
def bind(object)
if predicate.respond_to?(:bind)
self.class.build(predicate.bind(object), **options)
else
self.class.build(
-> *args { object.instance_exec(*args, &predicate) },
**options, arity: arity, parameters: parameters
)
end
end
def eval_args(object)
with(args: args.map { |arg| arg.is_a?(UnboundMethod) ? arg.bind(object).() : arg })
end
def with(new_opts)
self.class.build(predicate, **options, **new_opts)
end
def parameters
options[:parameters] || predicate.parameters
end
def ast(input = Undefined)
[:predicate, [id, args_with_names(input)]]
end
private
def args_with_names(*input)
parameters.map(&:last).zip(args + input)
end
end
end
end
|
Rails.application.routes.draw do
# You can have the root of your site routed with "root"
root 'movies#index'
resources :movies
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.