repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
willrax/motion-giphy
lib/motion-giphy/client.rb
<reponame>willrax/motion-giphy module MotionGiphy class Client def self.search(query, options = {}, &block) options = { q: query }.merge(options) request.get("search", options) do |response| response.process_data_as_batch if response.success? block.call response end end def self.gif(id, &block) request.get("#{id}") do |response| response.process_data_as_singular if response.success? block.call response end end def self.trending(options = {}, &block) request.get("trending", options) do |response| response.process_data_as_batch if response.success? block.call response end end def self.request MotionGiphy::Request.new end end end
willrax/motion-giphy
lib/motion-giphy/error.rb
module MotionGiphy class Error attr_reader :message, :error def initialize(error) @error = error @message = error.localizedDescription end end end
willrax/motion-giphy
lib/motion-giphy/configuration.rb
<reponame>willrax/motion-giphy<gh_stars>1-10 module MotionGiphy class Configuration class << self attr_writer :api_key def configure(&block) yield self self end def api_key @api_key end end end end
willrax/motion-giphy
lib/motion-giphy/image.rb
<gh_stars>1-10 module MotionGiphy class Image attr_reader :url, :width, :height, :frames, :size, :mp4 def initialize(image_hash) @url = image_hash["url"] @width = image_hash["width"].to_i @height = image_hash["height"].to_i @frames = image_hash["frames"].to_i @size = image_hash["size"].to_i @mp4 = image_hash["mp4"] end end end
willrax/motion-giphy
motion-giphy.gemspec
<filename>motion-giphy.gemspec # -*- encoding: utf-8 -*- VERSION = "1.2.3" Gem::Specification.new do |spec| spec.name = "motion-giphy" spec.version = VERSION spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.description = %q{Giphy API wrapper for RubyMotion} spec.summary = %q{Giphy API wrapper for RubyMotion} spec.homepage = "" spec.license = "" files = [] files << "README.md" files.concat(Dir.glob("lib/**/*.rb")) spec.files = files spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "motion-cocoapods" spec.add_dependency "afmotion" spec.add_development_dependency "rake" end
willrax/motion-giphy
lib/motion-giphy/gif.rb
<reponame>willrax/motion-giphy module MotionGiphy class Gif def self.process_batch(data) data.map { |gif_hash| new(gif_hash) } end attr_reader :hash def initialize(hash) @hash = hash end def id hash["id"] end def giphy_url hash["url"] end def bitly_url hash["bitly_gif_url"] end def embed_url hash["embed_url"] end def original image.new(images["original"]) end def fixed_width image.new(images["fixed_width"]) end def fixed_width_downsampled image.new(images["fixed_width_downsampled"]) end def fixed_height image.new(images["fixed_height"]) end def fixed_height_downsampled image.new(images["fixed_height_downsampled"]) end def fixed_width_still image.new(images["fixed_width_still"]) end def fixed_height_still image.new(images["fixed_height_still"]) end private def images hash["images"] end def image MotionGiphy::Image end end end
willrax/motion-giphy
lib/motion-giphy/request.rb
<filename>lib/motion-giphy/request.rb<gh_stars>1-10 module MotionGiphy class Request def get(path, options = {}, &block) client.get(path, create_options(options)) do |result| block.call response.build_with_result(result) end end private def client AFMotion::SessionClient.build_shared("http://api.giphy.com/v1/gifs/") do session_configuration :default header "Accept", "application/json" response_serializer :json end end def response MotionGiphy::Response end def create_options(options) api_key = MotionGiphy::Configuration.api_key { api_key: api_key }.merge(options) end end end
willrax/motion-giphy
lib/motion-giphy/response.rb
<reponame>willrax/motion-giphy<filename>lib/motion-giphy/response.rb module MotionGiphy class Response def self.build_with_result(result) response = self.new if result.success? response.success = true response.json = result.object else response.success = false response.error = MotionGiphy::Error.new(result.error) end response end attr_accessor :data, :json, :success, :error def process_data_as_singular self.data = gif.new(self.json["data"]) end def process_data_as_batch self.data = gif.process_batch(self.json["data"]) end def pagination @pages ||= MotionGiphy::Pagination.new(json["pagination"]) end def meta @meta ||= MoptionGiphy::Meta.new(json["meta"]) end def success? @success end private def gif MotionGiphy::Gif end end end
XcooBee/payment-sdk-swift
XcooBeePaymentSdk.podspec
Pod::Spec.new do |spec| spec.name = "XcooBeePaymentSdk" spec.version = "1.0.1" spec.summary = "XcooBee Payment SDK for Swift and iOS" spec.description = <<-DESC The XcooBee payment SDK allows you to quickly create contactless payments QR and URL that can be processed in your app. You can use XcooBee to configure accepted payment processors and methods. This simplifies the implementation of payments in apps and makes it safer for your users. DESC spec.homepage = "https://github.com/XcooBee/payment-sdk-swift" spec.license = 'Apache License, Version 2.0' spec.author = { "XcooBee" => "<EMAIL>" } spec.ios.deployment_target = "10.0" spec.source = { :git => "https://github.com/XcooBee/payment-sdk-swift.git", :tag => "#{spec.version}" } spec.source_files = "PaymentSDK/*.swift" end
patrick204nqh/ptk-erp-backend
app/controllers/erp/backend/accounts_controller.rb
module Erp module Backend class AccountsController < Erp::Backend::BackendController before_action :set_profile, only: [:profile, :update_profile] def profile end def gallery end # Update profile of user but not update user table # ==> Because email, password,... is important infor => use another action with permission to update def update_profile if params[:user].present? if @profile.update(user_params) redirect_to erp.profile_backend_accounts_path else redirect_to erp.profile_backend_accounts_path end end end private def set_profile if current_user.present? @profile = current_user.profile end end def user_params params.fetch(:user, {}).permit(:first_name, :last_name, :phone , :address, :birthday, :avatar, :descriptions) end end end end
patrick204nqh/ptk-erp-backend
app/controllers/erp/application_controller.rb
module Erp class ApplicationController < ActionController::Base include Pundit # from 'app/policies' protect_from_forgery with: :exception end end
patrick204nqh/ptk-erp-backend
app/models/erp/user_group.rb
<gh_stars>0 module Erp class UserGroup < ApplicationRecord has_many :rooms, class_name: "Erp::UserRoom", foreign_key: "group_id" has_many :users, through: :rooms, foreign_key: "user_id" end end
patrick204nqh/ptk-erp-backend
app/controllers/erp/backend/backend_controller.rb
module Erp module Backend class BackendController < Erp::ApplicationController layout "erp/backend/index" # When 'url: https://.../backend/...' => accesst to backend include Erp::BackendHelper before_action :set_view # Apply for login/logout layout before_action :authenticate_user!, :backend_authenticate? # Authenticate backend controllers rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized # TODO: remove this statement # if Erp::Backend.available?("frontend") # logger.info "==================================" # logger.info "available" # end ==> true private def set_view session[:current_view] = "backend" end def user_not_authorized redirect_to erp.new_user_session_path end def backend_authenticate? authorize [:erp, :backend, :backend], :backend_access? # From 'app/policies/erp/backend/backend_policy.rb' (parent of 'dashboard_policy.rb') end end end end
patrick204nqh/ptk-erp-backend
app/models/erp/user_profile.rb
<gh_stars>0 module Erp class UserProfile < ApplicationRecord # Relations belongs_to :user, class_name: "Erp::User" # Mount upload mount_uploader :avatar, Erp::AvatarUploader end end
patrick204nqh/ptk-erp-backend
app/helpers/erp/backend_helper.rb
<gh_stars>0 module Erp module BackendHelper def check_controller_action(controller: "", action: "") if params[:controller] == controller && params[:action] == action return true else return false end end def profile_avatar(profile:) if profile.avatar.present? return profile.avatar else return '/backend/assets/img/default/default-user.png' end end end end
patrick204nqh/ptk-erp-backend
app/models/erp/user.rb
module Erp class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable # Validates validates :username, :presence => true validates_format_of :email, :presence => true, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :message => " is invalid (Eg. '<EMAIL>')" # Relations belongs_to :creator, class_name: "Erp::User", optional: true belongs_to :role, class_name: "Erp::UserRole", optional: true # One user just has one role has_many :rooms, class_name: "Erp::UserRoom" has_many :groups, through: :rooms has_one :profile, class_name: "Erp::UserProfile", :foreign_key => 'user_id', :dependent => :destroy # Detroy async when destroy user end end
patrick204nqh/ptk-erp-backend
config/routes.rb
<filename>config/routes.rb Erp::Backend::Engine.routes.draw do devise_for :users, class_name: "Erp::User", module: :devise, :controllers => { :sessions => "erp/users/sessions", :registrations => "erp/users/registrations", :passwords => "erp/users/passwords", :confirmations => "erp/users/confirmations", } namespace :backend do get '/' => 'dashboard#index' resources :accounts do collection do get 'profile' get 'gallery' post 'update_profile' end end end end
patrick204nqh/ptk-erp-backend
app/models/erp/backend/application_record.rb
<filename>app/models/erp/backend/application_record.rb module Erp module Backend class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end end end
patrick204nqh/ptk-erp-backend
lib/erp/backend/engine.rb
<reponame>patrick204nqh/ptk-erp-backend<gh_stars>0 module Erp module Backend class Engine < ::Rails::Engine # require 'jquery-rails' isolate_namespace Erp initializer :append_migrations do |app| unless app.root.to_s.match(root.to_s) config.paths["db/migrate"].expanded.each do |p| app.config.paths["db/migrate"] << p end end end initializer "static assets" do |app| app.middleware.insert_before(::ActionDispatch::Static, ::ActionDispatch::Static, "#{root}/public") end end end end
patrick204nqh/ptk-erp-backend
app/controllers/erp/users/confirmations_controller.rb
<gh_stars>0 module Erp class Users::ConfirmationsController < Devise::ConfirmationsController layout :set_layout # GET /resource/confirmation?confirmation_token=abcdef def show self.resource = resource_class.confirm_by_token(params[:confirmation_token]) yield resource if block_given? if resource.errors.empty? set_flash_message!(:notice, :confirmed) respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) } else # Custom here # respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new } flash[:notice] = "Your account is already confirmed. Please login." redirect_to '/#sign-in' end end private def after_confirmation_path_for(resource_name, resource) '/' end def set_layout return nil if request.xhr? if session[:current_view] == 'frontend' "erp/frontend/auth" else "erp/backend/auth" end end end end
patrick204nqh/ptk-erp-backend
lib/erp/backend/version.rb
module Erp module Backend VERSION = '0.1.0' end end
patrick204nqh/ptk-erp-backend
lib/erp/backend.rb
require 'devise' require 'pundit' require 'carrierwave' # require gem in scope Erp module require "erp/backend/version" require "erp/backend/engine" module Erp module Backend def self.available?(engine_name) Object.const_defined?("Erp::#{engine_name.to_s.camelize}") # Check engine in available? end end end
patrick204nqh/ptk-erp-backend
db/migrate/20210313191529_add_columns_to_erp_users.rb
<gh_stars>0 class AddColumnsToErpUsers < ActiveRecord::Migration[6.1] def change add_column :erp_users, :username, :string add_column :erp_users, :status, :string, default: "ACTIVE" add_reference :erp_users, :creator, index: true, references: :erp_users end end
patrick204nqh/ptk-erp-backend
app/models/erp/user_room.rb
<filename>app/models/erp/user_room.rb module Erp class UserRoom < ApplicationRecord belongs_to :user, class_name: "Erp::User", foreign_key: "user_id" belongs_to :group, class_name: "Erp::UserGroup", foreign_key: "group_id" end end
patrick204nqh/ptk-erp-backend
db/migrate/20210316034137_add_user_role_to_users.rb
<gh_stars>0 class AddUserRoleToUsers < ActiveRecord::Migration[6.1] def change add_reference :erp_users, :role, references: :erp_user_roles, index: true end end
patrick204nqh/ptk-erp-backend
app/controllers/erp/frontend/frontend_controller.rb
module Erp module Frontend class FrontendController < Erp::ApplicationController # include Erp::ApplicationHelper # Used in controllers, views of frontend layout 'erp/frontend/index' # Set frontend layout before_action :set_view # Apply for login/logout layout private def set_view session[:current_view] = "frontend" end end end end
patrick204nqh/ptk-erp-backend
db/migrate/20210316024538_add_user_to_erp_user_profiles.rb
<gh_stars>0 class AddUserToErpUserProfiles < ActiveRecord::Migration[6.1] def change add_reference :erp_user_profiles, :user, references: :erp_users, index: { unique: true } # one user just has one profile end end
patrick204nqh/ptk-erp-backend
lib/erp_backend.rb
require "erp/backend" require "erp/backend/version"
patrick204nqh/ptk-erp-backend
app/policies/erp/backend/dashboard_policy.rb
<reponame>patrick204nqh/ptk-erp-backend module Erp module Backend class DashboardPolicy < Erp::Backend::BackendPolicy end end end
patrick204nqh/ptk-erp-backend
db/migrate/20210313184503_create_erp_user_roles.rb
class CreateErpUserRoles < ActiveRecord::Migration[6.1] def change create_table :erp_user_roles do |t| t.string :name, default: "DEFAULT" t.integer :level, default: 100 t.timestamps end end end
patrick204nqh/ptk-erp-backend
app/policies/erp/backend/backend_policy.rb
module Erp module Backend class BackendPolicy < ApplicationPolicy def index? end def backend_access? # Access to backend if user is super admin or admin if user.role.present? user.role.name == Erp::UserRole::ROLE_AS_SUPER_ADMIN || user.role.name == Erp::UserRole::ROLE_AS_ADMIN else false end end end end end
patrick204nqh/ptk-erp-backend
db/seeds.rb
# Clean database Erp::User.destroy_all Erp::UserRole.destroy_all Erp::UserProfile.destroy_all # Defined roles ROLE_AS_SUPER_ADMIN = "SUPER_ADMIN" ROLE_AS_ADMIN = "ADMIN" ROLE_AS_DEFAULT = "DEFAULT" ROLE_AS_PREMIUM = "PREMIUM" # Create default roles of user Erp::UserRole.create(name: ROLE_AS_DEFAULT, level: 100) Erp::UserRole.create(name: ROLE_AS_PREMIUM, level: 200) Erp::UserRole.create(name: ROLE_AS_ADMIN, level: 300) Erp::UserRole.create(name: ROLE_AS_SUPER_ADMIN, level: 400) role_super = Erp::UserRole.find_by(name: ROLE_AS_SUPER_ADMIN) # Create default user Erp::User.create( email: "<EMAIL>", password: "<PASSWORD>", username: "patrick204nqh", role_id: role_super.id, ) first_user = Erp::User.first Erp::UserProfile.create( user_id: first_user.id, first_name: "patrick", last_name: "nguyen", phone: "0985156089", address: "bao loc", descriptions: "dcf afdslfjl fsdfsdf dfasd", birthday: Time.zone.now )
patrick204nqh/ptk-erp-backend
app/helpers/erp/application_helper.rb
<gh_stars>0 module Erp module ApplicationHelper # Get custom uniquess id def unique_id return [*5000..300000].sample.to_s end # Format date def format_date(date) date.nil? ? '' : date.strftime(t('date_format')) end # Format date def format_datetime(date) date.nil? ? '' : date.strftime(t('datetime_format')) end # Format date def export_partial "erp/elements/export.xlsx.axlsx" end # Test if string is a number def is_number?(object) true if Float(object) rescue false end def format_number(number, vn = false, round = false, precision = nil) prec = (number.to_f.round == number.to_f) ? 0 : 2 prec = 0 if round if !precision.nil? prec = precision end if vn number_to_currency(number, precision: prec, separator: ",", unit: '', delimiter: ".", strip_insignificant_zeros: true) else number_to_currency(number, precision: prec, separator: ".", unit: '', delimiter: ",", strip_insignificant_zeros: true) end end @@mangso = ["không","một","hai","ba","bốn","năm","sáu","bảy","tám","chín"] def dochangchuc(so,daydu) chuoi = "" chuc = (so/10).to_i donvi = so%10 if chuc > 1 chuoi = " " + @@mangso[chuc] + " mươi"; if donvi == 1 chuoi += " mốt" end elsif chuc==1 chuoi = " mười" if donvi==1 chuoi += " một" end elsif daydu && donvi>0 chuoi = " lẻ" end if donvi==5 && chuc>1 chuoi += " lăm" elsif donvi>1 || ($donvi==1 && chuc==0) chuoi += " " + @@mangso[donvi] end return chuoi end def docblock(so,daydu) chuoi = "" tram = (so/100).floor so = so%100 if daydu || tram>0 chuoi = " " + @@mangso[tram] + " trăm" chuoi += dochangchuc(so,true) else chuoi = dochangchuc(so,false) end return chuoi; end def dochangtrieu(so,daydu) chuoi = "" trieu = (so/1000000).floor so = so%1000000 if trieu>0 chuoi = docblock(trieu,daydu) + " triệu" daydu = true end nghin = (so/1000).floor so = so%1000; if nghin>0 chuoi += docblock(nghin,daydu) + " nghìn"; daydu = true; end if so>0 chuoi += docblock(so,daydu) end return chuoi end def docso(so) return @@mangso[0] if so==0 chuoi = "" hauto = "" begin ty = so%1000000000 so = (so/1000000000).floor if so>0 chuoi = dochangtrieu(ty,true) + hauto + chuoi else chuoi = dochangtrieu(ty,false) + hauto + chuoi end hauto = " tỷ" end while so>0 chuoi = chuoi.strip.capitalize chuoi = (chuoi =~ /Triệu/) == 0 ? "Một " + chuoi : chuoi chuoi = (chuoi =~ /Tỷ/) == 0 ? "Một " + chuoi : chuoi chuoi = (chuoi =~ /Nghìn/) == 0 ? "Một " + chuoi : chuoi return chuoi.strip.capitalize + " đồng" end # Status /list page def status_label(status) status.present? ? "<span class=\'label label-sm label-#{status}\'>#{t('.' + status)}</span>".html_safe : '' end # image src def image_src(image, size) !image.nil? ? image.image_url.send(size).url : url_for("/backend/img/placeholder.jpg") end # remove html and reuncate text def short_text(text, length=50) strip_tags(text).split[0..length-1].join(" ").gsub('&amp;','&') end # convert string to url friendly string def url_friendly(string) string.to_ascii.downcase.to_s.gsub(/[^0-9a-z ]/i, '').gsub(/ +/i, '-').strip end # display short name for user def user_short_name(str) str.rpartition(' ').last end # relative time def relative_time(start_time) diff_seconds = (Time.now - start_time).to_i case diff_seconds when 0 .. 59 "Vừa xong" when 60 .. (3600-1) "#{diff_seconds/60} phút trước" when 3600 .. (3600*24-1) "#{diff_seconds/3600} giờ trước" when (3600*24) .. (3600*24*30-1) "#{diff_seconds/(3600*24)} ngày trước" when (3600*24*30) .. (3600*24*30*12-1) "#{diff_seconds/(3600*24*30)} tháng trước" else "#{diff_seconds/(3600*24*30*12)} năm trước" end end # format price def format_price(price) price = (price.to_f/1000).round*1000 if Erp::Backend.available?("online_store") "<span style=\'font-family:sans-serif;\'>#{number_to_currency(price, precision: 0, format: "%n₫", separator: ',', unit: '', delimiter: ".")}</span>".html_safe end # content from editor def format_content_from_editor(text) html_string = CGI.unescapeHTML(text) fragment = Nokogiri::HTML.fragment(html_string) fragment.css('video').each do |video| video_code = video.content # add `.strip` for possible whitespace div = fragment.document.create_element('div', class: 'video-responsive', ) iframe = fragment.document.create_element('iframe', class: 'responsive-iframe', src: "https://www.youtube.com/embed/#{video_code}", frameborder: '0', allowfullscreen: true, ) div << iframe video.swap(div) end return fragment.to_s.html_safe end end end
patrick204nqh/ptk-erp-backend
app/models/erp/user_role.rb
<filename>app/models/erp/user_role.rb<gh_stars>0 module Erp class UserRole < ApplicationRecord # Roles defined ROLE_AS_SUPER_ADMIN = "SUPER_ADMIN" ROLE_AS_ADMIN = "ADMIN" ROLE_AS_PREMIUM = "PREMIUM" ROLE_AS_DEFAULT = "DEFAULT" # Levels defined LEVEL_OF_SUPER_ADMIN = 400 LEVEL_OF_ADMIN = 300 LEVEL_OF_PREMIUM = 200 LEVEL_OF_DEFAULT = 100 end end
patrick204nqh/ptk-erp-backend
app/controllers/erp/backend/dashboard_controller.rb
<filename>app/controllers/erp/backend/dashboard_controller.rb<gh_stars>0 module Erp module Backend class DashboardController < Erp::Backend::BackendController # Extend all mothods from backend controller def index end end end end
analog-analytics/shortener
app/helpers/shortener/shortener_helper.rb
<gh_stars>0 module Shortener::ShortenerHelper # generate a url from a url string def short_url(url, owner=nil, options={}) short_url = Shortener::ShortenedUrl.generate(url, owner) url_for_options = { :controller => :"shortener/shortened_urls", :action => :show, :id => short_url.unique_key, :only_path => false } url_for_options[:host] = options[:host] if options[:host] short_url ? url_for(url_for_options) : url end end
analog-analytics/shortener
spec/helpers/shortener_helper_spec.rb
<reponame>analog-analytics/shortener<gh_stars>0 # -*- coding: utf-8 -*- require 'spec_helper' describe Shortener::ShortenerHelper do before { @short_url = Shortener::ShortenedUrl.generate("www.doorkeeperhq.com") } describe "short_url" do it "should shorten the url" do helper.short_url("www.doorkeeperhq.com").should == "http://test.host/#{@short_url.unique_key}" end it "should allow setting the url host" do helper.short_url("www.doorkeeperhq.com", nil, :host => "customhost.com").should == "http://customhost.com/#{@short_url.unique_key}" end end end
analog-analytics/shortener
spec/models/shortened_url_spec.rb
# -*- coding: utf-8 -*- require 'spec_helper' describe Shortener::ShortenedUrl do it { should belong_to :owner } it { should validate_presence_of :url } shared_examples_for "shortened url" do let(:short_url) { Shortener::ShortenedUrl.generate!(long_url, owner) } it "should be shortened" do short_url.should_not be_nil short_url.url.should == expected_long_url short_url.unique_key.length.should == 5 short_url.owner.should == owner end end context "shortened url" do let(:long_url) { "http://www.doorkeeperhq.com/" } let(:expected_long_url) { long_url } let(:owner) { nil } it_should_behave_like "shortened url" end context "shortened url with partial URL" do let(:long_url) { "www.doorkeeperhq.com" } let(:expected_long_url) { "http://www.doorkeeperhq.com/" } let(:owner) { nil } it_should_behave_like "shortened url" end context "shortened url with i18n path" do let(:long_url) { "http://www.doorkeeper.jp/%E6%97%A5%E6%9C%AC%E8%AA%9E" } let(:expected_long_url) { long_url } let(:owner) { nil } it_should_behave_like "shortened url" end context "shortened url with user" do let(:long_url) { "http://www.doorkeeperhq.com/" } let(:expected_long_url) { long_url } let(:owner) { User.create } it_should_behave_like "shortened url" end context "existing shortened URL" do before { @existing = Shortener::ShortenedUrl.generate!("http://www.doorkeeperhq.com/") } it "should look up exsiting URL" do Shortener::ShortenedUrl.generate!("http://www.doorkeeperhq.com/").should == @existing Shortener::ShortenedUrl.generate!("www.doorkeeperhq.com").should == @existing end it "should generate different one for different" do Shortener::ShortenedUrl.generate!("www.doorkeeper.jp").should_not == @existing end context "duplicate unique key" do before do Shortener::ShortenedUrl.any_instance.stub(:generate_unique_key). and_return(@existing.unique_key, "ABCDEF") end it "should try until it finds a non-dup key" do short_url = Shortener::ShortenedUrl.generate!("client.doorkeeper.jp") short_url.should_not be_nil short_url.unique_key.should == "ABCDEF" end end end end
lanejr/outgain
default_ai.rb
def run(player, world) cx = 10 cy = 10 [-(player.y - cy), (player.x - cx)] end
lingshengjx/LSHtmlLabel
LSHtmlLabel.podspec
Pod::Spec.new do |spec| spec.name = "LSHtmlLabel" spec.version = "1.0.1" spec.summary = "custom UILabel" spec.description = <<-DESC 一个点击文字跳链的UIlabel子类 DESC spec.homepage = "https://github.com/lingshengjx/LSHtmlLabel" #spec.license = "MIT (example)" spec.license = { :type => "MIT", :file => "LICENSE" } spec.author = { "凌胜" => "<EMAIL>" } spec.ios.deployment_target = '9.0' spec.source = { :git => "https://github.com/lingshengjx/LSHtmlLabel.git", :tag => "#{spec.version}" } spec.source_files = "LSHtmlLabel/*.{h,m}" #spec.exclude_files = "LSHtmlLabel/Exclude" #spec.framework = "UIKit" # spec.framework = "SomeFramework" # spec.frameworks = "SomeFramework", "AnotherFramework" # spec.library = "iconv" # spec.libraries = "iconv", "xml2" end
brunoleon/puppet-openvpn
spec/classes/openvpn_init_spec.rb
<gh_stars>0 require 'spec_helper' describe 'openvpn', :type => :class do context 'non-systemd systems' do let(:facts) { { :concat_basedir => '/var/lib/puppet/concat', :osfamily => 'Debian', :lsbdistid => 'Ubuntu', :lsbdistrelease => '12.04', } } it { should create_class('openvpn') } it { should contain_class('openvpn::service') } end context 'systemd systems' do let(:facts) { { :concat_basedir => '/var/lib/puppet/concat', :osfamily => 'RedHat', :operatingsystemrelease => '7.0', } } it { should create_class('openvpn') } it { should_not contain_class('openvpn::service') } end end
kolide/slack_transformer
spec/slack_transformer/slack/quote_spec.rb
require 'slack_transformer/slack/quote' RSpec.describe SlackTransformer::Slack::Quote do let(:transformation) { described_class.new(input) } describe '#to_html' do let(:input) { '>blockquote' } it 'replaces > with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('<blockquote>blockquote</blockquote>') end context "when there's nothing after the >" do let(:input) { '>' } it "doesn't replace the >" do expect(transformation.to_html).to eq('>') end end context "when there's one and only one trailing >" do let(:input) { '>>' } it 'replaces the first > with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('<blockquote>></blockquote>') end end context 'when on adjacent lines' do let(:input) { ">blockquote\n>blockquote" } it 'replaces the > with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('<blockquote>blockquote<br>blockquote</blockquote>') end end context 'when preceded by *' do let(:input) { '*>blockquote' } it "doesn't replace the >" do expect(transformation.to_html).to eq('*>blockquote') end end context 'when surrounded by *' do let(:input) { '*>blockquote*' } it 'replaces the > with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('*<blockquote>blockquote</blockquote>*') end end context 'when preceded by _' do let(:input) { '_>blockquote' } it "doesn't replace the >" do expect(transformation.to_html).to eq('_>blockquote') end end context 'when surrounded by _' do let(:input) { '_>blockquote_' } it 'replaces the > with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('_<blockquote>blockquote</blockquote>_') end end context 'when preceded by ~' do let(:input) { '~>blockquote' } it "doesn't replace the >" do expect(transformation.to_html).to eq('~>blockquote') end end context 'when surrounded by ~' do let(:input) { '~>blockquote~' } it 'replaces the > with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('~<blockquote>blockquote</blockquote>~') end end context 'when preceded by letters' do let(:input) { 'a>blockquote' } it "doesn't replace the >" do expect(transformation.to_html).to eq('a>blockquote') end end context 'when preceded by numbers' do let(:input) { '0>blockquote' } it "doesn't replace the >" do expect(transformation.to_html).to eq('0>blockquote') end end context 'when there are n >= 2 lines of >' do let(:input) { ">\n>" } it 'collapses them into n - 1 lines' do expect(transformation.to_html).to eq('>') end context 'when preceded by *' do let(:input) { "*>\n>" } it 'collapses them into n - 1 lines' do expect(transformation.to_html).to eq('*>') end end context 'when preceded by _' do let(:input) { "_>\n>" } it 'collapses them into n - 1 lines' do expect(transformation.to_html).to eq('_>') end end context 'when preceded by ~' do let(:input) { "~>\n>" } it 'collapses them into n - 1 lines' do expect(transformation.to_html).to eq('~>') end end context 'when preceded by letters' do let(:input) { "a>\n>" } it 'collapses them into n - 1 lines' do expect(transformation.to_html).to eq('a>') end end context 'when preceded by numbers' do let(:input) { "0>\n>" } it 'collapses them into n - 1 lines' do expect(transformation.to_html).to eq('0>') end end end end end
kolide/slack_transformer
spec/slack_transformer/slack_spec.rb
require 'slack_transformer/slack' RSpec.describe SlackTransformer::Slack do let(:transformation) { described_class.new(input) } let(:input) { double('input') } describe '#to_html' do let(:bold_transformation) { instance_double('SlackTransformer::Slack::Bold', to_html: bold) } let(:bold) { double('bold') } let(:italics_transformation) { instance_double('SlackTransformer::Slack::Italics', to_html: italics) } let(:italics) { double('italics') } let(:strikethrough_transformation) { instance_double('SlackTransformer::Slack::Strikethrough', to_html: strikethrough) } let(:strikethrough) { double('strikethrough') } let(:code_transformation) { instance_double('SlackTransformer::Slack::Code', to_html: code) } let(:code) { double('code') } let(:preformatted_transformation) { instance_double('SlackTransformer::Slack::Preformatted', to_html: preformatted) } let(:preformatted) { double('preformatted') } let(:quote_transformation) { instance_double('SlackTransformer::Slack::Quote', to_html: quote) } let(:quote) { double('quote') } let(:blockquote_transformation) { instance_double('SlackTransformer::Slack::Blockquote', to_html: html) } let(:html) { 'output' } before do allow(SlackTransformer::Slack::Bold).to receive(:new).with(input) { bold_transformation } allow(SlackTransformer::Slack::Italics).to receive(:new).with(bold) { italics_transformation } allow(SlackTransformer::Slack::Strikethrough).to receive(:new).with(italics) { strikethrough_transformation } allow(SlackTransformer::Slack::Code).to receive(:new).with(strikethrough) { code_transformation } allow(SlackTransformer::Slack::Preformatted).to receive(:new).with(code) { preformatted_transformation } allow(SlackTransformer::Slack::Quote).to receive(:new).with(preformatted) { quote_transformation } allow(SlackTransformer::Slack::Blockquote).to receive(:new).with(quote) { blockquote_transformation } end it 'returns HTML' do expect(transformation.to_html).to eq('<p>output</p>') end context 'when there are newlines' do let(:html) { "\n" } it 'replaces the newlines with line breaks' do expect(transformation.to_html).to eq('<p><br></p>') end end end end
kolide/slack_transformer
lib/slack_transformer/html.rb
require 'slack_transformer/html/bold' require 'slack_transformer/html/code' require 'slack_transformer/html/italics' require 'slack_transformer/html/lists' require 'slack_transformer/html/paragraph' require 'slack_transformer/html/preformatted' require 'slack_transformer/html/strikethrough' require 'slack_transformer/html/links' module SlackTransformer class Html attr_reader :input TRANSFORMERS = [ SlackTransformer::Html::Bold, SlackTransformer::Html::Italics, SlackTransformer::Html::Strikethrough, SlackTransformer::Html::Code, SlackTransformer::Html::Paragraph, SlackTransformer::Html::Preformatted, SlackTransformer::Html::Lists, SlackTransformer::Html::Links ] def initialize(input) @input = input end def to_slack TRANSFORMERS.reduce(input) do |html, transformer| transformer.new(html).to_slack end end end end
kolide/slack_transformer
spec/slack_transformer/html/code_spec.rb
<reponame>kolide/slack_transformer require 'slack_transformer/html/code' RSpec.describe SlackTransformer::Html::Code do let(:transformation) { described_class.new('<code>code</code>') } describe '#to_slack' do it 'replaces <code> and </code> with `' do expect(transformation.to_slack).to eq('`code`') end end end
kolide/slack_transformer
lib/slack_transformer/html/links.rb
<gh_stars>0 module SlackTransformer class Html class Links attr_reader :input HTML_PATTERN = %r{ <a (?:.*?) href=['"](.+?)['"] (?:.*?)> (.+?) </a> }x def initialize(input) @input = input end def to_slack sub_html_links(@input) end private def sub_html_links(string) string.gsub(HTML_PATTERN) do slack_link Regexp.last_match[1], Regexp.last_match[2] end end def slack_link(link, text=nil) "<#{link}" \ "#{text && !text.empty? ? "|#{text}" : ''}" \ ">" end end end end
kolide/slack_transformer
spec/slack_transformer/html/lists_spec.rb
require 'slack_transformer/html/lists' RSpec.describe SlackTransformer::Html::Lists do let(:transformation) { described_class.new(input) } describe '#to_slack' do context 'when a list is unordered' do let(:input) { '<ul><li>foo</li><li>bar</li><li>baz</li></ul>' } it 'replaces the list' do expect(transformation.to_slack).to eq("• foo\n• bar\n• baz") end end context 'when a list is ordered' do let(:input) { '<ol><li>foo</li><li>bar</li><li>baz</li></ol>' } it 'replaces the list' do expect(transformation.to_slack).to eq("1. foo\n2. bar\n3. baz") end end end end
kolide/slack_transformer
spec/slack_transformer/html/bold_spec.rb
require 'slack_transformer/html/bold' RSpec.describe SlackTransformer::Html::Bold do let(:transformation) { described_class.new('<b>bold</b>') } describe '#to_slack' do it 'replaces <b> and </b> with *' do expect(transformation.to_slack).to eq('*bold*') end end end
kolide/slack_transformer
lib/slack_transformer/slack/italics.rb
module SlackTransformer class Slack class Italics attr_reader :input PATTERN = / (?<=^|\W) # preceded by start of line or non-word character (?<![*~`]) # but not *, ~, or `, which are mrkdwn delimiters # Note: _ is also a mrkdwn delimiter, but it's included in \W because # it's a word character. ([*~]?) # optionally preceded by * or ~ _((?:[^_]|(?<=[a-zA-Z0-9\s])_+(?=[a-zA-Z0-9]))+)_ # one or more of either not _, or one or more _ preceded by letter, # number, or space and followed by letter or number, surrounded by _ \1 # followed by * or ~ if preceded by it (?!```) # not followed by ``` (?=\W|$) # followed by non-word character or end of line /x def initialize(input) @input = input end def to_html input.gsub(PATTERN, '\1<i>\2</i>\1') end end end end
kolide/slack_transformer
lib/slack_transformer/slack/quote.rb
<gh_stars>1-10 module SlackTransformer class Slack class Quote attr_reader :input PATTERN = / ^ # start of line ([*_~]?) # optionally preceded by *, _, or ~ >(.+?) # one or more of anything preceded by > \1 # followed by *, _, or ~ if preceded by it (?:\n|$) # followed by newline or end of line /x def initialize(input) @input = input end def to_html input.gsub(PATTERN, '\1<blockquote>\2</blockquote>\1') .gsub('</blockquote><blockquote>', '<br>') .gsub(/(>(?:\n|$)){2,}/) { |match| match[0...-2] } end end end end
kolide/slack_transformer
spec/slack_transformer/slack/blockquote_spec.rb
require 'slack_transformer/slack/blockquote' RSpec.describe SlackTransformer::Slack::Blockquote do let(:transformation) { described_class.new(input) } describe '#to_html' do let(:input) { ">>>blockquote\nblockquote" } it 'replaces >>> with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('<blockquote>blockquote<br>blockquote</blockquote>') end context "when there's nothing after the >>>" do let(:input) { '>>>' } it "doesn't replace the >" do expect(transformation.to_html).to eq('>>>') end end context 'when there are extra trailing >' do let(:input) { '>>>>' } it 'replaces the first >>> with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('<blockquote>></blockquote>') end end context 'when preceded by *' do let(:input) { '*>>>blockquote' } it "doesn't replace the >>>" do expect(transformation.to_html).to eq('*>>>blockquote') end end context 'when preceded by and contains *' do let(:input) { '*>>>blockquote*blockquote' } it "doesn't replace the >>>" do expect(transformation.to_html).to eq('*>>>blockquote*blockquote') end end context 'when surrounded by *' do let(:input) { '*>>>blockquote*' } it 'replaces the >>> with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('*<blockquote>blockquote</blockquote>*') end end context 'when preceded by _' do let(:input) { '_>>>blockquote' } it "doesn't replace the >>>" do expect(transformation.to_html).to eq('_>>>blockquote') end end context 'when preceded by and contains _' do let(:input) { '_>>>blockquote_blockquote' } it "doesn't replace the >>>" do expect(transformation.to_html).to eq('_>>>blockquote_blockquote') end end context 'when surrounded by _' do let(:input) { '_>>>blockquote_' } it 'replaces the >>> with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('_<blockquote>blockquote</blockquote>_') end end context 'when preceded by ~' do let(:input) { '~>>>blockquote' } it "doesn't replace the >>>" do expect(transformation.to_html).to eq('~>>>blockquote') end end context 'when preceded by and contains ~' do let(:input) { '~>>>blockquote~blockquote' } it "doesn't replace the >>>" do expect(transformation.to_html).to eq('~>>>blockquote~blockquote') end end context 'when surrounded by ~' do let(:input) { '~>>>blockquote~' } it 'replaces the >>> with <blockquote> and </blockquote>' do expect(transformation.to_html).to eq('~<blockquote>blockquote</blockquote>~') end end context 'when preceded by letters' do let(:input) { 'a>>>blockquote' } it "doesn't replace the >>>" do expect(transformation.to_html).to eq('a>>>blockquote') end end context 'when preceded by numbers' do let(:input) { '0>>>blockquote' } it "doesn't replace the >>>" do expect(transformation.to_html).to eq('0>>>blockquote') end end end end
kolide/slack_transformer
lib/slack_transformer/date.rb
require 'set' require 'time' module SlackTransformer class Date attr_reader :input, :format, :link, :fallback class InvalidTokenError < StandardError; end # See https://api.slack.com/docs/message-formatting#formatting_dates DATE_FORMAT_TOKENS = Set.new(%w[ {date_num} {date} {date_short} {date_long} {date_pretty} {date_short_pretty} {date_long_pretty} {time} {time_secs} ]) def initialize(input, format:, link: nil, fallback:) @input = input @format = format @link = link @fallback = fallback end def to_slack tokens = format.scan(/(\{\w+\})/).first if tokens invalid_tokens = tokens.reject { |t| DATE_FORMAT_TOKENS.include?(t) } raise InvalidTokenError, invalid_tokens.join(', ') unless invalid_tokens.empty? end "<!date^#{Time.parse(input.to_s).to_i}^#{format}#{"^#{link}" if link}|#{fallback}>" end end end
kolide/slack_transformer
spec/slack_transformer/slack/preformatted_spec.rb
require 'slack_transformer/slack/preformatted' RSpec.describe SlackTransformer::Slack::Preformatted do let(:transformation) { described_class.new(input) } describe '#to_html' do let(:input) { '```preformatted```' } it 'replaces ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>preformatted</pre>') end context "when there's nothing between the ```" do let(:input) { '``````' } it "doesn't replace the ```" do expect(transformation.to_html).to eq('``````') end end context 'when there are extra leading ```' do let(:input) { '``````preformatted```' } it 'replaces the outer ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>```preformatted</pre>') end end context 'when there are extra trailing ```' do let(:input) { '```preformatted``````' } it 'replaces the outer ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>preformatted```</pre>') end end context 'when there are extra leading and trailing ```' do let(:input) { '``````preformatted``````' } it 'replaces the outer ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>```preformatted```</pre>') end end context 'when preceded by *' do let(:input) { '*```preformatted```' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('*<pre>preformatted</pre>') end end context 'when followed by *' do let(:input) { '```preformatted```*' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>preformatted</pre>*') end end context 'when surrounded by *' do let(:input) { '*```preformatted```*' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('*<pre>preformatted</pre>*') end end context 'when preceded by _' do let(:input) { '_```preformatted```' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('_<pre>preformatted</pre>') end end context 'when followed by _' do let(:input) { '```preformatted```_' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>preformatted</pre>_') end end context 'when surrounded by _' do let(:input) { '_```preformatted```_' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('_<pre>preformatted</pre>_') end end context 'when preceded by ~' do let(:input) { '~```preformatted```' } it "doesn't replace the ```" do expect(transformation.to_html).to eq('~```preformatted```') end end context 'when followed by ~' do let(:input) { '```preformatted```~' } it "doesn't replace the ```" do expect(transformation.to_html).to eq('```preformatted```~') end end context 'when surrounded by ~' do let(:input) { '~```preformatted```~' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('~<pre>preformatted</pre>~') end end context 'when preceded by `' do let(:input) { '````preformatted```' } it 'replaces the outer ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>`preformatted</pre>') end end context 'when followed by `' do let(:input) { '```preformatted````' } it 'replaces the outer ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>preformatted`</pre>') end end context 'when surrounded by `' do let(:input) { '````preformatted````' } it 'replaces the outer ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>`preformatted`</pre>') end end context 'when preceded by >' do let(:input) { '>```preformatted```' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('><pre>preformatted</pre>') end end context 'when preceded by >>>' do let(:input) { '>>>```preformatted```' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('>>><pre>preformatted</pre>') end end context 'when preceded by letters' do let(:input) { 'a```preformatted```' } it "doesn't replace the ```" do expect(transformation.to_html).to eq('a```preformatted```') end end context 'when followed by letters' do let(:input) { '```preformatted```z' } it "doesn't replace the ```" do expect(transformation.to_html).to eq('```preformatted```z') end end context 'when surrounded by letters' do let(:input) { 'a```preformatted```z' } it "doesn't replace the ```" do expect(transformation.to_html).to eq('a```preformatted```z') end end context 'when preceded by numbers' do let(:input) { '0```preformatted```' } it "doesn't replace the ```" do expect(transformation.to_html).to eq('0```preformatted```') end end context 'when followed by numbers' do let(:input) { '```preformatted```9' } it "doesn't replace the ```" do expect(transformation.to_html).to eq('```preformatted```9') end end context 'when surrounded by numbers' do let(:input) { '0```preformatted```9' } it "doesn't replace the ```" do expect(transformation.to_html).to eq('0```preformatted```9') end end context 'when there are internal spaces' do let(:input) { '```preformatted preformatted```' } it 'replaces the ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>preformatted preformatted</pre>') end end context 'when there are internal sequences of ```' do let(:input) { '```preformatted```preformatted```' } it 'replaces the outer ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>preformatted```preformatted</pre>') end end context 'when there are internal sequences of ``` preceded by spaces' do let(:input) { '```preformatted ```preformatted```' } it 'replaces the outer ``` with <pre> and </pre>' do expect(transformation.to_html).to eq('<pre>preformatted ```preformatted</pre>') end end end end
kolide/slack_transformer
spec/slack_transformer/html_spec.rb
<gh_stars>1-10 require 'slack_transformer/html' RSpec.describe SlackTransformer::Html do let(:transformation) { described_class.new(input) } let(:input) { double('input') } describe '#to_slack' do let(:bold_transformation) { instance_double('SlackTransformer::Html::Bold', to_slack: bold) } let(:bold) { double('bold') } let(:italics_transformation) { instance_double('SlackTransformer::Html::Italics', to_slack: italics) } let(:italics) { double('italics') } let(:strikethrough_transformation) { instance_double('SlackTransformer::Html::Strikethrough', to_slack: strikethrough) } let(:strikethrough) { double('strikethrough') } let(:code_transformation) { instance_double('SlackTransformer::Html::Code', to_slack: code) } let(:code) { double('code') } let(:preformatted_transformation) { instance_double('SlackTransformer::Html::Preformatted', to_slack: preformatted) } let(:preformatted) { double('preformatted') } let(:lists_transformation) { instance_double('SlackTransformer::Html::Lists', to_slack: mrkdwn) } let(:mrkdwn) { 'output' } before do allow(SlackTransformer::Html::Bold).to receive(:new).with(input) { bold_transformation } allow(SlackTransformer::Html::Italics).to receive(:new).with(bold) { italics_transformation } allow(SlackTransformer::Html::Strikethrough).to receive(:new).with(italics) { strikethrough_transformation } allow(SlackTransformer::Html::Code).to receive(:new).with(strikethrough) { code_transformation } allow(SlackTransformer::Html::Preformatted).to receive(:new).with(code) { preformatted_transformation } allow(SlackTransformer::Html::Lists).to receive(:new).with(preformatted) { lists_transformation } end it 'returns mrkdwn' do expect(transformation.to_slack).to eq(mrkdwn) end end end
kolide/slack_transformer
lib/slack_transformer/slack/blockquote.rb
module SlackTransformer class Slack class Blockquote attr_reader :input PATTERN = / ^ # start of line ([*_~]?) # optionally preceded by *, _, or ~ >{3}(.+) # one or more of anything preceded by > \1 # followed by *, _, or ~ if preceded by it $ # end of line /mx def initialize(input) @input = input end def to_html input.gsub(PATTERN) do outer = Regexp.last_match(1) inner = Regexp.last_match(2).gsub("\n", '<br>') "#{outer}<blockquote>#{inner}</blockquote>#{outer}" end end end end end
kolide/slack_transformer
lib/slack_transformer/entities.rb
<gh_stars>1-10 module SlackTransformer class Entities attr_reader :input def initialize(input) @input = input end # See https://api.slack.com/docs/message-formatting#how_to_escape_characters # NB: The order matters here. If you were to replace < with &lt; first, for # example, you'd end up with &amp;lt; def to_slack input.gsub('&', '&amp;') .gsub('<', '&lt;') .gsub('>', '&gt;') end end end
kolide/slack_transformer
spec/slack_transformer/entities_spec.rb
<filename>spec/slack_transformer/entities_spec.rb require 'slack_transformer/entities' RSpec.describe SlackTransformer::Entities do describe '#to_slack' do it 'replaces & with &amp;' do expect(described_class.new('&').to_slack).to eq('&amp;') end it 'replaces < with &lt;' do expect(described_class.new('<').to_slack).to eq('&lt;') end it 'replaces > with &gt;' do expect(described_class.new('>').to_slack).to eq('&gt;') end end end
kolide/slack_transformer
lib/slack_transformer/slack.rb
require 'slack_transformer/slack/blockquote' require 'slack_transformer/slack/bold' require 'slack_transformer/slack/code' require 'slack_transformer/slack/italics' require 'slack_transformer/slack/preformatted' require 'slack_transformer/slack/quote' require 'slack_transformer/slack/strikethrough' module SlackTransformer class Slack attr_reader :input TRANSFORMERS = [ SlackTransformer::Slack::Bold, SlackTransformer::Slack::Italics, SlackTransformer::Slack::Strikethrough, SlackTransformer::Slack::Code, SlackTransformer::Slack::Preformatted, SlackTransformer::Slack::Quote, SlackTransformer::Slack::Blockquote ] def initialize(input) @input = input end def to_html html = TRANSFORMERS.reduce(input) do |html, transformer| transformer.new(html).to_html end "<p>#{html.gsub("\n", '<br>')}</p>" end end end
kolide/slack_transformer
lib/slack_transformer/html/paragraph.rb
module SlackTransformer class Html class Paragraph attr_reader :input def initialize(input) @input = input end def to_slack input.gsub(/<\/?p>/, "") end end end end
jomz/radiant-mailer-extension
spec/models/mail_spec.rb
require File.dirname(__FILE__) + "/../spec_helper" describe Mail do dataset :mailer_page before :each do @page = pages(:mail_form) @page.request = ActionController::TestRequest.new @page.last_mail = @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>'}, {'body' => 'Hello, world!'}) ActionMailer::Base.delivery_method = :test ActionMailer::Base.deliveries = [] end describe 'config validation' do it "should have an invalid config when from is absent" do Mail.valid_config?('recipients' => '<EMAIL>').should be_false end it "should have an invalid config when recipients are absent" do Mail.valid_config?('from' => '<EMAIL>').should be_false end it "should have a valid config when recipients and from keys are present" do Mail.valid_config?('recipients' => '<EMAIL>', 'from' => '<EMAIL>').should be_true end it "should have a valid config when recipients_field stands in for recipients" do Mail.valid_config?('recipients_field' => 'to', 'from' => '<EMAIL>').should be_true end it "should have a valid config when from_field stands in for from" do Mail.valid_config?('recipients' => '<EMAIL>', 'from_field' => 'from').should be_true end end describe 'config error messages' do it 'should exist for from' do Mail.config_error_messages('recipients' => '<EMAIL>').should == "'from' is required" end it 'should exist for recipients' do Mail.config_error_messages('from' => '<EMAIL>').should == "'recipients' is required" end end it "should derive the from field from the configuration" do @mail.from.should == '<EMAIL>' end it "should derive the from field from the data when not in the configuration" do @mail.config[:from] = nil @mail.config[:from_field] = 'from' @mail.data['from'] = '<EMAIL>' @mail.from.should == '<EMAIL>' end it "should derive the recipients field from the configuration" do @mail.recipients.should == ['<EMAIL>'] end it "should derive the recipients field from the data when not in the configuration" do @mail.config[:recipients] = nil @mail.config[:recipients_field] = 'to' @mail.data['to'] = '<EMAIL>' @mail.recipients.should == %w(<EMAIL>) end it "should derive the reply_to field from the configuration" do @mail.config[:reply_to] = "<EMAIL>" @mail.reply_to.should == "<EMAIL>" end it "should derive the reply_to field from the data when not in the configuration" do @mail.config[:reply_to_field] = 'reply_to' @mail.data['reply_to'] = '<EMAIL>' @mail.reply_to.should == '<EMAIL>' end it "should derive the sender field from the configuration" do @mail.config[:sender] = "<EMAIL>" @mail.sender.should == "<EMAIL>" end it "should derive the subject field from the data" do @mail.data[:subject] = "My subject" @mail.subject.should == 'My subject' end it "should derive the subject field from the configuration when not present in the data" do @mail.config[:subject] = "My subject" @mail.subject.should == 'My subject' end it "should generate the subject field when not present in data or configuration" do @mail.subject.should == 'Form Mail from test.host' end it "should derive the cc field from the data when configured" do @mail.data['cc'] = "<EMAIL>" @mail.config[:cc_field] = 'cc' @mail.cc.should == "<EMAIL>" end it "should derive the cc field from the configuration when not in the data" do @mail.config[:cc] = "<EMAIL>" @mail.cc.should == "<EMAIL>" end it "should return a blank cc when not in the data or configuration" do @mail.cc.should be_blank end it "should derive the filesize_limit from the configuration" do @mail.config[:filesize_limit] = 1000 @mail.filesize_limit.should == 1000 end it "should return 0 as filesize_limit when not in the configuration" do @mail.filesize_limit.should == 0 end it "should derive the file field from the data when configured" do file1 = StringIO.new("test_data") file2 = Tempfile.new("test2") @mail.data['file1'] = file1 @mail.data['file2'] = file2 @mail.files.include?(file1).should == true @mail.files.include?(file2).should == true end it "should return an empty files array when not in the data" do @mail.files.should == [] end it "should initially have no errors" do @mail.errors.should == {} end it "should be valid when the configuration and fields are correct" do @mail.should be_valid end it "should be invalid when the recipients are empty" do @mail.config[:recipients] = [] @mail.should_not be_valid @mail.errors['form'].should_not be_blank end it "should be invalid when the recipients contains invalid email adresses" do @mail.config[:recipients] = ['sean AT radiant DOT com'] @mail.should_not be_valid @mail.errors['form'].should_not be_blank end it "should be invalid when the from field is empty" do @mail.config[:from] = nil @mail.should_not be_valid @mail.errors['form'].should_not be_blank end it "should be invalid when the from field contains an invalid email address" do @mail.config[:from] = 'sean AT radiant DOT com' @mail.should_not be_valid @mail.errors['form'].should_not be_blank end describe "should be invalid when a required field is missing and a require set to" do ["true", "1", "required", "not_blank"].each do |value| it "should be invalid when " do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>'}, {:required => {'first_name' => value}}) @mail.should_not be_valid @mail.errors['first_name'].should_not be_blank end it "should also be invalid when a field required in the config is missing" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>', :required => {'first_name' => value}}, {}) @mail.should_not be_valid @mail.errors['first_name'].should_not be_blank end end end describe "should be valid when a require set to" do ["true", "1", "required", "not_blank"].each do |value| it "#{value}" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>'}, {:required => {'first_name' => value}, 'first_name' => "Name"}) @mail.should be_valid @mail.errors['first_name'].should be_blank end it "#{value}" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>'}, :required => {'first_name' => value}, 'first_name' => "Name") @mail.should be_valid @mail.errors['first_name'].should be_blank end end end describe "should be invalid when a required field is invalid email" do it "and required is specified in the form" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => 'foo<EMAIL>'}, {:required => {'first_email' => "as_email"}, 'first_email' => "at@.com"}) @mail.should_not be_valid @mail.errors['first_email'].should_not be_blank end it "and required is specified in the config" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>', :required => {'first_email' => "as_email"}}, 'first_email' => "at@.com") @mail.should_not be_valid @mail.errors['first_email'].should_not be_blank end end describe "with regex required" do it "should be invalid when a required field doesn't match regex given on the form" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>'}, {:required => {'birthday' => "/^\\d{2}\\.\\d{2}\\.\\d{4}$/"}, 'birthday' => "11.11.11"}) @mail.should_not be_valid @mail.errors['birthday'].should_not be_blank @mail.errors['birthday'].should == "doesn't match regex (^\\d{2}\\.\\d{2}\\.\\d{4}$)" end it "should be valid when a required field matches regex given on the form" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>'}, {:required => {'birthday' => "/^\\d{2}\\.\\d{2}\\.\\d{4}$/"}, 'birthday' => "12.21.1980"}) @mail.should be_valid @mail.errors['birthday'].should be_blank end it "should be invalid when a required field doesn't match regex given in the config" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>', :required => {'birthday' => "/^\\d{2}\\.\\d{2}\\.\\d{4}$/"}}, 'birthday' => "11.11.11") @mail.should_not be_valid @mail.errors['birthday'].should_not be_blank @mail.errors['birthday'].should == "doesn't match regex (^\\d{2}\\.\\d{2}\\.\\d{4}$)" end it "should be valid when a required field matches regex given in the config" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>', :required => {'birthday' => "/^\\d{2}\\.\\d{2}\\.\\d{4}$/"}}, 'birthday' => "12.21.1980") @mail.should be_valid @mail.errors['birthday'].should be_blank end end describe "should be valid when spam trap field" do it "is not included in config" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>'}, 'spam_trap' => "I'm a spam bot.") @mail.should be_valid @mail.errors['spam_trap'].should be_blank end it "is included in config but not field is given" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>', :leave_blank => ''}, 'spam_trap' => "I'm a spam bot.") @mail.should be_valid @mail.errors['spam_trap'].should be_blank end end it "should be valid when the spam trap field is empty" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>', :leave_blank => 'spam_trap'}, 'spam_trap' => '') @mail.should be_valid @mail.errors['spam_trap'].should be_blank end it "should be invalid when the spam trap field has text in it" do @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>', :leave_blank => 'spam_trap'}, 'spam_trap' => "I'm a spam bot.") @mail.should_not be_valid @mail.errors['spam_trap'].should_not be_blank @mail.errors['spam_trap'].should == 'must be left blank.' end it "should be invalid when a field that disallows links has text that looks like a link" do ['Check out http://example.com', 'Check out www.example.com', 'Check out example.com?a=4&amp;b=5', 'Check out <a href="">Spam site</a>', 'Spam mailto:', 'Spam bcc:', 'Spam cc:', 'Spam multipart', 'Spam [url is', 'Spam Content-Type:'].each do |message| @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>', :disallow_links => ['comments']}, 'comments' => message) @mail.should_not be_valid @mail.errors['comments'].should_not be_blank @mail.errors['comments'].should == 'must not contain the following text: "www", "&amp;amp;", "http:", "mailto:", "bcc:", "href", "multipart", "[url", or "Content-Type:"' end end it "should not send the mail if invalid" do @mail.should_receive(:valid?).and_return(false) @mail.send.should be_false end it "should send an email" do @mail.send.should be_true ActionMailer::Base.deliveries.should_not be_empty end it "should not send and should register an error if the Mailer raised an exception" do Mailer.should_receive(:deliver_generic_mail).and_raise("Boom!") @mail.should be_valid @mail.send.should be_false @mail.errors['base'].should == "Boom!" end it "should set the Reply-To header on the sent mail to the reply_to value given in the configuration" do @mail.config[:reply_to] = "<EMAIL>" @mail.send ActionMailer::Base.deliveries.last.reply_to.should == [@mail.config[:reply_to]] # reply_to on TMail is an Array end it "should set the Reply-To header on the sent mail to the reply_to_field data value given in the configuration" do @mail.config[:reply_to_field] = 'email' @mail.data['email'] = '<EMAIL>' @mail.send ActionMailer::Base.deliveries.last.reply_to.should == [@mail.data['email']] # reply_to on TMail is an Array end it "should set the Reply-To header on the sent mail to the from value when the configuration does not specify a reply_to" do @mail.send ActionMailer::Base.deliveries.last.reply_to.should == ['<EMAIL>'] # reply_to on TMail is an Array end describe "when the page has no email body specified" do it "should render the submitted data as YAML to the plain body" do Mailer.should_receive(:deliver_generic_mail) do |params| params[:plain_body].should == "The following information was posted:\n--- \nbody: Hello, world!\n\n" params[:html_body].should be_blank end @mail.send.should be_true end end describe "when the page has specified a plain email body" do before :each do @page = pages(:plain_mail) @page.request = ActionController::TestRequest.new @page.last_mail = @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>'}, {'body' => 'Hello, world!'}) end it "should send an email with the rendered plain body" do Mailer.should_receive(:deliver_generic_mail) do |params| params[:plain_body].should == 'The body: Hello, world!' params[:html_body].should be_blank end @mail.send.should be_true end end describe "when the page has specified an HTML email body" do before :each do @page = pages(:html_mail) @page.request = ActionController::TestRequest.new @page.last_mail = @mail = Mail.new(@page, {:recipients => ['<EMAIL>'], :from => '<EMAIL>'}, {'body' => 'Hello, world!'}) end it "should send an email with the rendered plain body" do Mailer.should_receive(:deliver_generic_mail) do |params| params[:plain_body].should be_blank params[:html_body].should == '<html><body>Hello, world!</body></html>' end @mail.send.should be_true end end end
karsonhatch/this_is_a_gem
lib/this_is_a_gem.rb
<gh_stars>0 require "this_is_a_gem/version" module ThisIsAGem def self.reversify(str) str.split('').reverse.join('') end def self.casify(str) to_case = [:upcase, :downcase] arr = str.split("") arr.each_with_index do |letter, i| this_case = to_case[rand(2)] arr[i] = letter.send(this_case) end end def self.spacify(str, spaces = 0) new_string = str spaces.times do new_string = new_string.split("").join(" ") end new_string end end
bsxfun/pffdtd
ruby_SU/RoomExporter.rb
# encoding: UTF-8 require 'sketchup.rb' require 'extensions.rb' module RoomExportExtension extension = SketchupExtension.new("Room Exporter", #name "RoomExporter/RoomExport") #import file extension.version = "1.0.0" extension.creator = "<NAME>" extension.copyright = "© <NAME> 2021" extension.description = "Export geometry with materials to JSON." Sketchup.register_extension(extension, true) end
bsxfun/pffdtd
ruby_SU/RoomExporter/RoomExport.rb
# vim: set expandtab # vim: set tabstop=2 ############################################################################## # This file is a part of PFFDTD. # # PFFTD is released under the MIT License. # For details see the LICENSE file. # # Copyright 2021 <NAME>. # # File name: RoomExport.rb # # Description: Functions called by SU plugin (RoomExporter) to export geometry and materials # Exports Sketchup model's non-hidden faces and vertices to JSON # Uses Materials and not Layers (aka Tags in SU2020+) # # Notes: # - model should be exploded prior to export (only exports top level entities) # - internally Sketchup uses inches, this exports in metres.- # - Materials should be one-sided (only one side has material), but can be two-sided if materials match # - This plugin doesn't export/explode components or groups. That should be done beforehand. # - Colors are exported, but textures are not (some average color somehow is exported for textures) # ############################################################################## require 'sketchup.rb' require 'fileutils.rb' require 'csv' require 'json' #$DEBUG = true $DEBUG = false module RoomExporter INCHES2METRES = 0.0254 MAX_SAFE_INTEGER = 9007199254740991 module Export #main class def self.export_entities model = Sketchup.active_model ents = model.entities #initialise arrays mats_hash = {} counts_hash = {} counts_hash['n_groups'] = 0 #number of groups encountered counts_hash['n_comps'] = 0 #number of components encountered counts_hash['n_faces_hidden'] = 0 #number of hidden faces encountered counts_hash['n_faces_nvisible'] = 0 #number of faces not visible encountered counts_hash['n_faces_tofix'] = 0 #number of faces with some error counts_hash['n_faces_rigid'] = 0 #number of faces without materials Sketchup.set_status_text("Processing " + ents.length.to_s + " entities") for i in 0...ents.length ent = ents[i] if ent.is_a?(Sketchup::Group) Sketchup.set_status_text("Encountered Group") counts_hash['n_groups'] += 1 #ignore and notify later elsif ent.is_a?(Sketchup::ComponentInstance) Sketchup.set_status_text("Encountered component: " + ent.definition.name) counts_hash['n_comps'] += 1 #ingore and notify later elsif ent.is_a?(Sketchup::Face) #skip if hidden or visible if (ent.hidden?) counts_hash['n_faces_hidden'] += 1 next end if !(ent.layer.visible?) counts_hash['n_faces_nvisible'] += 1 next end has_fmat = false has_bmat = false bmat_name = '' fmat_name = '' #get material names if ent.back_material bmat_name = ent.back_material.display_name has_bmat = true end if ent.material fmat_name = ent.material.display_name has_fmat = true end #flag faces with two sides different materials if ((has_fmat && has_bmat) && (bmat_name != fmat_name)) #front and back face don't match if !(model.layers['_TOFIX']) layer = model.layers.add('_TOFIX') end puts ent.layer.name ent.layer = model.layers['_TOFIX'] #move to _TOFIX layer (= also assigns via layer.name) counts_hash['n_faces_tofix'] += 1 next #skip to next entity end if (has_bmat) && (!has_fmat) #back-face (other side rigid) mat_name = bmat_name mat = ent.back_material mat_side = 1 elsif (has_fmat) && (!has_bmat) #front-face (other side rigid) mat_name = fmat_name mat = ent.material mat_side = 2 elsif (has_fmat) && (has_bmat) #two-sided mat_name = fmat_name mat = ent.material mat_side = 3 else #no materials - rigid mat_name = '_RIGID' #has no material mat_side = 0 counts_hash['n_faces_rigid'] += 1 end if !mats_hash.has_key?(mat_name) mats_hash[mat_name] = {'tris' => [], 'pts' => [], 'pt_cc' => 0, #point counter 'color' => [0,0,0], 'sides' => [] } #initialise empty array end #rigid has no material if !(mat_name=='_RIGID') mats_hash[mat_name]['color'] = mat.color.to_a[0..2] #save RGB end #get mesh of face mesh = ent.mesh(0) if mesh.points.empty? #skip if empty next end t_pts = mesh.points.to_a.map{|pt| pt.to_a.map{|d| d*INCHES2METRES}} #points for face mesh, convert to arrays #NB mesh.polygons are always triangles (sketchup triangulates for you) for j in 0...mesh.polygons.length vert_array = mesh.polygons[j] if vert_array.length != 3 #make sure is a triangle (and not an edge?) UI.messagebox('Non-triangle poly?' ) next end tri = [vert_array[0].abs(), vert_array[1].abs(), vert_array[2].abs()] tri = tri.map{|t| t + mats_hash[mat_name]['pt_cc'] - 1} #1-indexing in Sketchup mats_hash[mat_name]['tris'] << tri mats_hash[mat_name]['sides'] << mat_side end mats_hash[mat_name]['pt_cc'] += t_pts.length mats_hash[mat_name]['pts'].concat(t_pts) if mats_hash[mat_name]['pt_cc']>MAX_SAFE_INTEGER #JSON uses JS 'Number' type, or double-precision (even for integers) UI.messagebox('Your model have have fewer than %d vertices to export.' % [MAX_SAFE_INTEGER]) fail end end end #unique points for each material for mat_name in mats_hash.keys pts = mats_hash[mat_name]['pts'] tris = mats_hash[mat_name]['tris'] Sketchup.set_status_text("Sort-unique vertices...") unique_pts = Hash[pts.zip((0...pts.length))] #unique vertices ia = pts.map{|v| unique_pts[v]} #maps from pts to unique indices ib = Hash[unique_pts.values.zip((0...unique_pts.length))] #maps from unique indices in pts to indices of unique_pts tris = tris.map{|a| a.map{|i| ib[ia[i]]}} #remaps triangle indices pts = unique_pts.keys #saves smaller list (.keys() returns same order as .values()) mats_hash[mat_name]['pts'] = pts mats_hash[mat_name]['tris'] = tris mats_hash[mat_name].delete('pt_cc') #cleanup end Sketchup.set_status_text("Processed " + ents.length.to_s + " entities") return mats_hash,counts_hash end def self.main #Export main model = Sketchup.active_model if (Sketchup.active_model.path.empty?) UI.messagebox 'Save your model in an appropriate directory first.' return end #go through model Sketchup.set_status_text("Traversing model...") mats_hash, counts_hash = self.export_entities() Sketchup.set_status_text("Done traversing model...") ntris = mats_hash.map{|k,v| v['tris'].length}.inject(0, :+) npts = mats_hash.map{|k,v| v['pts'].length}.inject(0, :+) if $DEBUG puts 'ntris = %d' % [ntris] puts 'npts = %d' % [npts] puts 'nmaterials = %d' % [mats_hash.keys.length] end sources,warning_msg = SourceReceivers::read_CSV('source') if !warning_msg.empty? UI.messagebox(warning_msg) end receivers,warning_msg = SourceReceivers::read_CSV('receiver') if !warning_msg.empty? UI.messagebox(warning_msg) end json_hash = {'mats_hash': mats_hash, 'sources': sources, 'receivers': receivers, 'export_datetime': Time.now} if $DEBUG #p mats_hash #p pts #p tris p json_hash end #write json from here Sketchup.set_status_text("Writing files...") #write in root dir write_dir = File.dirname(Sketchup.active_model.path) filename = 'model_export.json' file = File.new(write_dir + '\\' + filename, 'w') file.write(json_hash.to_json({object_nl: "\n"})) file.close Sketchup.set_status_text("Done.") #print status UI.messagebox('wrote %d points, %d tris, in %d materials to %s' % [npts, ntris, mats_hash.keys.length, write_dir]) #print summary of materials (including any _RIGID) mats_msg = "Summary: \n" mkeys = mats_hash.keys for j in 0...mkeys.length mats_msg << mkeys[j] + ': ' + mats_hash[mkeys[j]]['tris'].length.to_s + " tris \n" end UI.messagebox(mats_msg) #print anything else worth noting if counts_hash['n_faces_hidden']>0 || counts_hash['n_faces_nvisible']>0 UI.messagebox('found %d hidden faces, %d faces not visible' % [counts_hash['n_faces_hidden'],counts_hash['n_faces_nvisible']]) end if counts_hash['n_faces_tofix']>0 UI.messagebox('found %d faces with inconsistent material, moved to _TOFIX layer' % [counts_hash['n_faces_tofix']]) end if counts_hash['n_faces_rigid']>0 UI.messagebox('found %d faces with no material, taken to be rigid' % [counts_hash['n_faces_rigid']]) end if counts_hash['n_groups']>0 || counts_hash['n_comps']>0 UI.messagebox('found %d groups, and %d components' % [counts_hash['n_groups'],counts_hash['n_comps']]) end return end end module SourceReceivers def self.get_bounds_in_metres bmin = Geom::Point3d.new(Float::INFINITY,Float::INFINITY,Float::INFINITY) bmax = Geom::Point3d.new(-Float::INFINITY,-Float::INFINITY,-Float::INFINITY) model = Sketchup.active_model ents = model.entities for i in 0...ents.length ent = ents[i] #only checks faces, not groups or components (only what's exported) if ent.is_a?(Sketchup::Face) #skip if hidden or visible if (ent.hidden?) next end if !(ent.layer.visible?) next end bound = ent.bounds bmax.x = (bound.max.x>bmax.x) ? bound.max.x : bmax.x bmax.y = (bound.max.y>bmax.y) ? bound.max.y : bmax.y bmax.z = (bound.max.z>bmax.z) ? bound.max.z : bmax.z bmin.x = (bound.min.x<bmin.x) ? bound.min.x : bmin.x bmin.y = (bound.min.y<bmin.y) ? bound.min.y : bmin.y bmin.z = (bound.min.z<bmin.z) ? bound.min.z : bmin.z end end bmin_m = [bmin.x,bmin.y,bmin.z].map{|e| e*INCHES2METRES} bmax_m = [bmax.x,bmax.y,bmax.z].map{|e| e*INCHES2METRES} return bmin_m,bmax_m end def self.read_CSV(type) warning_msg = '' srlist = [] if type=='source' file = 'sources.csv' layer_name = '_SOURCES' prefix = 'S' elsif type=='receiver' file = 'receivers.csv' layer_name = '_RECEIVERS' prefix = 'R' end model = Sketchup.active_model root_dir = File.dirname(model.path) filename = root_dir + '\\' + file #puts filename if !(File.exists?(filename)) error_msg = 'Error: \'' + file + '\' not found in SKP model directory' UI.messagebox(error_msg) return srlist,warning_msg end delimiters=[',',';',':','\t'] #will loop through to attempt different delimiters validCSV = false strip_converter = proc{|field| field.strip.upcase } #to strip headers of whitespace for delim in delimiters csv = CSV.read(filename, :headers => true, :col_sep => delim, :header_converters => strip_converter) headers = csv.headers #headers = csv.headers.map{|s| s.strip()} #puts headers if (headers - ['X','Y','Z','NAME']).empty? if csv.length>0 validCSV = true break end end end if !validCSV error_msg = "Error: \'" + file + "\' is not a valid CSV file. \nFirst row needs column names: X,Y,Z,NAME \nDelimiter must be \',\' or \';\' or \':\' or Tab character. Needs at least one entry." UI.messagebox(error_msg) return srlist,warning_msg end for i in 0...csv.length srlist << {} row = csv[i] srlist[i][:xyz] = [row['X'].to_f,row['Y'].to_f,row['Z'].to_f] srlist[i][:name] = '' if row['NAME'] != nil srlist[i][:name] = row['NAME'] end end bmin,bmax = self.get_bounds_in_metres for i in 0...srlist.length xyz = srlist[i][:xyz] for j in 0...3 if xyz[j]>bmax[j] || xyz[j]<bmin[j] warning_msg << 'Warning: ' + type + ' at ' + xyz.map{|e| e.round(3)}.to_s + ' is outside of visible scene' + "\n" break end end end return srlist,warning_msg end def self.plot_positions(type) if type=='source' layer_name = '_SOURCES' prefix = 'S' elsif type=='receiver' layer_name = '_RECEIVERS' prefix = 'R' end srlist,warning_msg = self.read_CSV(type) if !warning_msg.empty? UI.messagebox(warning_msg) end model = Sketchup.active_model if (model.layers[layer_name]) model.layers.remove(layer_name,true) end layer = model.layers.add(layer_name) for i in 0...srlist.length xyz_in = srlist[i][:xyz].map{|e| e/INCHES2METRES} name = srlist[i][:name] pt = model.active_entities.add_cpoint(Geom::Point3d.new(xyz_in)) pt.layer = layer if name == '' label = '―'+prefix+(i+1).to_s else label = '―'+prefix+(i+1).to_s + ':"' + name + '"' end text = model.active_entities.add_text(label,Geom::Point3d.new(xyz_in)) text.layer = layer end return srlist end def self.plot sources = self.plot_positions('source') receivers = self.plot_positions('receiver') UI.messagebox('read %d '% [sources.length] +'sources and %d '% [receivers.length] +' receivers' ) end end end version_required = 17 #this excepts Ruby version from 2017 and up if (Sketchup.version.to_f < version_required) UI.messagebox("You must have Sketchup 20#{version_required} to run this extension. Visit sketchup.com to upgrade.") fail end #load once if (not file_loaded?('RoomExport.rb')) plugins_menu = UI.menu("Plugins") submenu = plugins_menu.add_submenu("Room Exporter") submenu.add_item("Export Geometry") { RoomExporter::Export.main() } submenu.add_item("Plot Sources and Receivers") { RoomExporter::SourceReceivers.plot() } end file_loaded('RoomExport.rb')
armandfardeau/metabase_cli
lib/metabase_cli.rb
<gh_stars>0 # frozen_string_literal: true require_relative "metabase_cli/version" require_relative "metabase_cli/cli" module MetabaseCli class Error < StandardError; end # Your code goes here... end
armandfardeau/metabase_cli
lib/metabase_cli/database_service.rb
<gh_stars>0 # frozen_string_literal: true require "metabase" require "hash_deep_merge" require_relative "api" module MetabaseCli class DatabaseService include MetabaseCli::Api def initialize(client_name:, dbname:, engine:, host:, port:, dbusername:, password:) @client_name = client_name @dbname = dbname @engine = engine @host = host @port = port @dbusername = dbusername @password = password @database_id = nil end def create_database response = MetabaseCli::Api.client.post("/api/database", database_params) @database_id = response.fetch("id") puts "Successfully created database with id: #{@database_id}" self end def set_default_permissions response = MetabaseCli::Api.client.put("/api/permissions/graph", default_permissions) puts "Successfully set default permissions" if permissions_graph[:revision] != response["revision"] end private def database_params { "name": @client_name, "engine": @engine, "details": { "host": @host, "port": @port, "dbname": @dbname, "user": @dbusername, "password": <PASSWORD> } } end def default_permissions MetabaseCli::Api.permissions_graph.dup.deep_merge( { "groups": { "1": { "#{@database_id}": { "native": "none", "schemas": "none" } } } } ) end end end
armandfardeau/metabase_cli
lib/metabase_cli/cli.rb
# frozen_string_literal: true require "thor" require "metabase_cli/database_service" require "metabase_cli/user_service" require "metabase_cli/group_service" module MetabaseCli class CLI < Thor desc "version", "Prints the version" def version puts "MetabaseApi version #{MetabaseCli::VERSION}" end desc "create_database", "Create a database" def create_database client_name = ask("Client name: ") dbname = ask("Database name: ") engine = ask("Database engine: ", default: "postgres") host = ask("Database host: ", default: "localhost") port = ask("Database port: ", default: "5432") dbusername = ask("Database username: ", default: ENV.fetch("DB_USERNAME", nil)) password = ask("Database password: ", default: ENV.fetch("DB_PASSWORD", nil)) MetabaseCli::DatabaseService.new( client_name: client_name, dbname: dbname, engine: engine, host: host, port: port, dbusername: dbusername, password: password ).create_database.set_default_permissions end desc "create_user", "Create a user" def create_user(group_id = nil) first_name = ask("First name: ") last_name = ask("Last name: ") email = ask("Email: ") group_wanted = ask("Group wanted: ", default: (group_id || "1")) MetabaseCli::UserService.new( first_name: first_name, last_name: last_name, email: email, group_wanted: group_wanted ).create_user end desc "create_group", "Create a group" def create_group name = ask("Group name: ") MetabaseCli::GroupService.new( name: name ).create_group end desc "create_grouped_user", "Create a user and a group" def create_grouped_user group_id = create_group create_user(group_id) end desc "create", "Create database, user and a group" def create create_database create_grouped_user end end end
armandfardeau/metabase_cli
lib/metabase_cli/user_service.rb
<gh_stars>0 # frozen_string_literal: true require "metabase" require "hash_deep_merge" require "securerandom" require_relative "api" module MetabaseCli class UserService def initialize(last_name:, first_name:, email:, group_wanted:) @last_name = last_name @first_name = first_name @email = email @group_wanted = group_wanted @user_id = nil end def create_user response = MetabaseCli::Api.client.post("/api/user", user_params) @user_id = response.fetch("id") puts "Successfully created user with id: #{@user_id}" self end private def user_params { "first_name": @first_name, "last_name": @last_name, "email": @email, "password": <PASSWORD>), "group_ids": group_wanted_ids, "login_attributes": nil, "locale": "fr" } end def group_wanted_ids return [1] if @group_wanted.nil? return [1] if @group_wanted == "1" [1, @group_wanted.to_i] end end end
armandfardeau/metabase_cli
lib/metabase_cli/api.rb
# frozen_string_literal: true require "metabase" require "hash_deep_merge" module MetabaseCli module Api def self.client raise "Missing url" unless ENV["METABASE_URL"] raise "Missing username" unless ENV["METABASE_USERNAME"] raise "Missing password" unless ENV["METABASE_PASSWORD"] @client ||= Metabase::Client.new( url: ENV.fetch("METABASE_URL", nil), username: ENV.fetch("METABASE_USERNAME", nil), password: ENV.fetch("<PASSWORD>ABASE_PASSWORD", nil) ).tap(&:login) end def self.permissions_graph # Due to Faraday we need to use a trick to get the string key as symbol @permissions_graph ||= JSON.parse(JSON.dump(client.get("/api/permissions/graph")), symbolize_names: true) end end end
armandfardeau/metabase_cli
lib/metabase_cli/group_service.rb
# frozen_string_literal: true require "metabase" require "hash_deep_merge" require_relative "api" module MetabaseCli class GroupService include MetabaseCli::Api def initialize(name:) @name = name @group_id = nil end def create_group response = MetabaseCli::Api.client.post("/api/permissions/group", { "name": @name }) @group_id = response["id"] puts "Group created with id: #{@group_id}" @group_id end end end
egotter/timeout_job
lib/timeout_job.rb
<reponame>egotter/timeout_job<filename>lib/timeout_job.rb require 'timeout' require 'logger' require "timeout_job/version" module TimeoutJob class Middleware def call(worker, msg, queue, &block) if worker.respond_to?(:timeout_in) result = yield_with_timeout(worker.timeout_in, &block) if timeout? logger.info "TimeoutJob: The job of #{worker.class} timed out timeout_in=#{worker.timeout_in} args=#{truncate(msg['args'].inspect)}" logger.info 'TimeoutJob: ' + @error.backtrace.join("\n") if @error perform_callback(worker, :after_timeout, msg['args']) nil else result end else yield end end def yield_with_timeout(timeout_in, &block) @timeout = false ::Timeout.timeout(timeout_in) do yield end rescue ::Timeout::Error => e @timeout = true @error = e nil end def timeout? @timeout end def perform_callback(worker, callback_name, args) if worker.respond_to?(callback_name) parameters = worker.method(callback_name).parameters begin if parameters.empty? worker.send(callback_name) else worker.send(callback_name, *args) end rescue ArgumentError => e message = "The number of parameters of the callback method (#{parameters.size}) is not the same as the number of arguments (#{args.size})" raise ArgumentError.new("#{self.class}:#{worker.class} #{message} callback_name=#{callback_name} args=#{args.inspect} parameters=#{parameters.inspect}") end end end def truncate(text, length: 100) if text.length > length text.slice(0, length) else text end end def logger if defined?(::Sidekiq) ::Sidekiq.logger elsif defined?(::Rails) ::Rails.logger else ::Logger.new(STDOUT) end end end end
egotter/timeout_job
test/timeout_job_test.rb
<gh_stars>0 require "test_helper" class TimeoutJobTest < Minitest::Test class Worker end class TimeoutWorker def timeout_in(*args) 10 end def after_timeout(*args) 'callback' end end def test_call msg = {'args' => 'args'} result = TimeoutJob::Middleware.new.call(Worker.new, msg, nil) { 'result' } assert result == 'result' result = TimeoutJob::Middleware.new.call(TimeoutWorker.new, msg, nil) { 'result' } assert result == 'result' end def test_yield_with_timeout timeout_in = TimeoutWorker.new.timeout_in result = TimeoutJob::Middleware.new.yield_with_timeout(timeout_in) { 'result' } assert result == 'result' end def test_perform_callback args = 'args' result = TimeoutJob::Middleware.new.perform_callback(Worker.new, :after_timeout, args) assert result.nil? args = 'args' result = TimeoutJob::Middleware.new.perform_callback(TimeoutWorker.new, :after_timeout, args) assert result == 'callback' end def test_truncate result = TimeoutJob::Middleware.new.truncate('a' * 10) assert result == 'a' * 10 result = TimeoutJob::Middleware.new.truncate('a' * 200) assert result == 'a' * 100 end def test_logger end end
egotter/timeout_job
test/test_helper.rb
$LOAD_PATH.unshift File.expand_path("../lib", __dir__) require "timeout_job" require "minitest/autorun"
pankajso/markdown_editor
app/models/page.rb
class Page < ActiveRecord::Base require 'kramdown' def transformed_md Kramdown::Document.new(self.content).to_html end end
wynandpieterse/StickyRay
automation/vagrant/SetUpProvisionLogging.rb
# # The MIT License (MIT) # # Copyright (c) 2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Version 0.1.0 # # Create the log file that provisioning scripts can write out to. def setUpProvisionLogging(vmName) if $vmProvisionLoggingEnabled currentTime = Time.now.strftime("%d-%m-%Y-%H-%M") logDirectoryGuest = "/vagrant/generated/vagrant/provisioning/%s/" % vmName logDirectoryHost = "generated/vagrant/provisioning/%s/" % vmName logFileGuest = "%s%s.log" % [logDirectoryGuest, currentTime] logFileHost = "%s%s.log" % [logDirectoryHost, currentTime] FileUtils.mkdir_p(logDirectoryHost) FileUtils.touch(logFileHost) return logFileGuest else return "/dev/null" end end
wynandpieterse/StickyRay
automation/vagrant/SetUpCoreOSClusterToken.rb
<filename>automation/vagrant/SetUpCoreOSClusterToken.rb # # The MIT License (MIT) # # Copyright (c) 2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Version 0.1.0 # require 'open-uri' require 'yaml' # Regenerate the CoreOS cluster token if the system is brought up on Vagrant. def setUpCoreOSClusterToken generatedCoreFile = "generated/files/LocalUserData.yml" baseCoreFile = "configuration/coreos/LocalUserData.yml" if ARGV[0].eql?('up') token = open('https://discovery.etcd.io/new').read data = YAML.load(IO.readlines(baseCoreFile)[1..-1].join) data['coreos']['etcd']['discovery'] = token yaml = YAML.dump(data) File.open(generatedCoreFile, 'w') { |file| file.write("#{yaml}") } return generatedCoreFile else return baseCoreFile end end
wynandpieterse/StickyRay
automation/vagrant/DefineControlVM.rb
<reponame>wynandpieterse/StickyRay # # The MIT License (MIT) # # Copyright (c) 2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Version 0.1.0 # require $setUpSerialLogging require $setUpProvisionLogging # Defines our control VM, the primary VM for all tasks. def defineControlVM(control, vmName) control.vm.hostname = vmName control.vm.box = "https://cloud-images.ubuntu.com/vagrant/utopic/%s/utopic-server-cloudimg-amd64-vagrant-disk1.box" % $controlRequestImagePath control.vm.network :private_network, ip: "10.10.10.10" # Forward our Docker registry port to the outside world. control.vm.network "forwarded_port", guest: 5000, host: $controlDockerRegistryPort, auto_correct: true # Enabled serial logging if the user asked for it. setUpSerialLogging vmName # Build the log directory where all internal control machines logs will go to. logFile = setUpProvisionLogging vmName # Provision the machines. control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlBase.sh", :privileged => false, :args => "%s" % logFile control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlFiles.sh", :privileged => false, :args => "%s %s" % [logFile, $coreInstances] control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlAnsible.sh", :privileged => false, :args => "%s" % logFile control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlDocker.sh", :privileged => false, :args => "%s" % logFile control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlRegistry.sh", :privileged => false, :args => "%s" % logFile end
wynandpieterse/StickyRay
automation/vagrant/SetUpSerialLogging.rb
# # The MIT License (MIT) # # Copyright (c) 2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Version 0.1.0 # # Enables serial logging on the requested instances. This can be usefull for checking # startup errors on the VM itself. WARNING: Heavy performance intensive, only # user for low-level debugging requirements. def setUpSerialLogging(vmName) if $vmSerialLoggingEnabled currentTime = Time.now.strftime("%d-%m-%Y-%H-%M") serialLogDirectory = "generated/vagrant/serial/%s/" % vmName serialFile = "%s%s.log" % [serialLogDirectory, currentTime] FileUtils.mkdir_p(serialLogDirectory) FileUtils.touch(serialFile) end end
wynandpieterse/StickyRay
configuration/vagrant/Configuration.rb
<gh_stars>0 # # The MIT License (MIT) # # Copyright (c) 2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Version 0.1.0 # # Should the VM provider output debug data about the VM through serial logs. $vmSerialLoggingEnabled = true # Should the VM provisioning process log output $vmProvisionLoggingEnabled = true # Should the VM provider build a headed VM. $vmGUIEnabled = false # How many cores should each VM have. $vmCPUCores = 1 # How much MB memory should each VM have. $vmMemory = 1024 # Which image to use for the control Ubuntu machines. $controlRequestImagePath = "current" # On which port do we expose the Docker registry that is running on the Control # machine. $controlDockerRegistryPort = 5000 # This value needs to be between 1 and 8. The number of CoreOS machines to spin up. $coreInstances = 3 # The updated channel to use for CoreOS images. $coreUpdateChannel = 'stable' # The CoreOS image version requested. $coreRequiredImageVersion = ">= 308.0.1" # The CoreOS image to check for online. $coreRequestImagePath = "current" # Should the CoreOS machines expose their internal Docker socket. $coreExposeDocker = true # If the above is true, on which port should the Docker server listen for requests. $coreExposedDockerPort = 2375
wynandpieterse/StickyRay
automation/vagrant/DefineCommonVM.rb
# # The MIT License (MIT) # # Copyright (c) 2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Version 0.1.0 # # Defines common VM properties that is used by both the CoreOS nodes and the # control node. # Insert the Vagrant public key into the machines. def defineCommonVM(config) config.ssh.insert_key = true # Configure how much memory and CPU cores each VM should have. config.vm.provider :virtualbox do |vb| vb.gui = $vmGUIEnabled vb.memory = $vmMemory vb.cpus = $vmCPUCores end end
wynandpieterse/StickyRay
automation/vagrant/DefineCoreOSVM.rb
# # The MIT License (MIT) # # Copyright (c) 2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Version 0.1.0 # require $setUpSerialLogging require $setUpProvisionLogging require $setUpCoreOSClusterToken # Creates and builds the CoreOS cluster for our testing purposes. These machines # will be controlled by the control VM. def defineCoreOSVM(core, vmName, instanceID) core.vm.hostname = vmName core.vm.box = "coreos-%s" % $coreUpdateChannel core.vm.box_version = $coreRequiredImageVersion core.vm.network :private_network, ip: "10.10.10.#{instanceID + 10}" # Select the image to use for our core VM's. core.vm.provider :virtualbox do |vb, override| override.vm.box_url = "http://%s.release.core-os.net/amd64-usr/%s/coreos_production_vagrant.json" % [$coreUpdateChannel, $coreRequestImagePath] end core.vm.provider :vmware_fusion do |vb, override| override.vm.box_url = "http://%s.release.core-os.net/amd64-usr/%s/coreos_production_vagrant_vmware_fusion.json" % [$coreUpdateChannel, $coreRequestImagePath] end # Expose the internal Docker server port if the user chooses for that. if $coreExposeDocker core.vm.network "forwarded_port", guest: 2375, host: ($coreExposedDockerPort + instanceID - 1), auto_correct: true end # Enable serial logging if the user requested that. setUpSerialLogging vmName # Build the location where log files can output their logs. logFile = setUpProvisionLogging vmName # Provision the machines. core.vm.provision :file, :source => setUpCoreOSClusterToken, :destination => "/tmp/vagrantfile-user-data" core.vm.provision :shell, :inline => "mv /tmp/vagrantfile-user-data /var/lib/coreos-vagrant/", :privileged => true # Disable guest additions as CoreOS has no need for that. core.vm.provider :virtualbox do |v| v.check_guest_additions = false v.functional_vboxsf = false end # Disable guest addition update checks. if Vagrant.has_plugin?("vagrant-vbguest") then core.vbguest.auto_update = false end end
VidAngel/react-native-video-with-ads
react-native-video.podspec
<gh_stars>0 require "json" package = JSON.parse(File.read(File.join(__dir__, "package.json"))) Pod::Spec.new do |s| s.name = 'react-native-video' s.version = package['version'] s.summary = package['description'] s.description = package['description'] s.license = package['license'] s.authors = { '<NAME>' => '<EMAIL>' } s.homepage = 'https://github.com/VidAngel/react-native-video-with-ads' s.source = { :git => "https://github.com/VidAngel/react-native-video-with-ads.git", :tag => "#{s.version}" } s.ios.deployment_target = "8.0" s.tvos.deployment_target = "9.0" s.subspec "Video" do |ss| ss.dependency "GoogleAds-IMA-iOS-SDK", "~> 3.10" ss.source_files = "ios/Video/*.{h,m}" s.static_framework = true end s.subspec "VideoCaching" do |ss| ss.dependency "react-native-video/Video" ss.dependency "SPTPersistentCache", "~> 1.1.0" ss.dependency "DVAssetLoaderDelegate", "~> 0.3.1" ss.dependency "GoogleAds-IMA-iOS-SDK", "~> 3.10" ss.source_files = "ios/VideoCaching/**/*.{h,m}" s.static_framework = true end s.dependency "React" s.default_subspec = "Video" end
dringoen/audited
lib/audited-activerecord.rb
require 'audited' require 'audited/adapters/active_record'
dringoen/audited
spec/support/mongo_mapper/connection.rb
<gh_stars>10-100 require 'mongo_mapper' MongoMapper.connection = Mongo::Connection.new MongoMapper.database = 'audited_test'
dringoen/audited
spec/audited/adapters/mongo_mapper/mongo_mapper_spec_helper.rb
require 'spec_helper' require 'support/mongo_mapper/connection' require 'audited/adapters/mongo_mapper' require 'support/mongo_mapper/models' load "audited/sweeper.rb" # force to reload sweeper
dringoen/audited
lib/audited/active_record/version.rb
module Audited module ActiveRecord VERSION = "4.2.0" end end
dringoen/audited
audited-mongo_mapper.gemspec
# encoding: utf-8 $:.push File.expand_path("../lib", __FILE__) require "audited/version" require "audited/mongo_mapper/version" Gem::Specification.new do |gem| gem.name = 'audited-mongo_mapper' gem.version = Audited::MongoMapper::VERSION gem.authors = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] gem.email = '<EMAIL>' gem.description = 'Log all changes to your MongoMapper models' gem.summary = gem.description gem.homepage = 'https://github.com/collectiveidea/audited' gem.license = 'MIT' gem.add_dependency 'audited', Audited::VERSION gem.add_dependency 'mongo_mapper', '~> 0.12.0' gem.files = `git ls-files lib`.split($\).grep(/mongo_mapper/) gem.files << 'LICENSE' gem.require_paths = ['lib'] end
dringoen/audited
lib/audited-mongo_mapper.rb
require 'audited' require 'audited/adapters/mongo_mapper'
dringoen/audited
spec/support/active_record/schema.rb
require 'active_record' require 'logger' ActiveRecord::Base.establish_connection ActiveRecord::Base.logger = Logger.new(SPEC_ROOT.join('debug.log')) ActiveRecord::Migration.verbose = false ActiveRecord::Schema.define do create_table :users, :force => true do |t| t.column :name, :string t.column :username, :string t.column :password, :string t.column :activated, :boolean t.column :suspended_at, :datetime t.column :logins, :integer, :default => 0 t.column :created_at, :datetime t.column :updated_at, :datetime end create_table :companies, :force => true do |t| t.column :name, :string t.column :owner_id, :integer end create_table :authors, :force => true do |t| t.column :name, :string end create_table :books, :force => true do |t| t.column :authord_id, :integer t.column :title, :string end create_table :audits, :force => true do |t| t.column :auditable_id, :integer t.column :auditable_type, :string t.column :associated_id, :integer t.column :associated_type, :string t.column :user_id, :integer t.column :user_type, :string t.column :username, :string t.column :action, :string t.column :audited_changes, :text t.column :version, :integer, :default => 0 t.column :comment, :string t.column :remote_address, :string t.column :request_uuid, :string t.column :created_at, :datetime end add_index :audits, [:auditable_id, :auditable_type], :name => 'auditable_index' add_index :audits, [:associated_id, :associated_type], :name => 'associated_index' add_index :audits, [:user_id, :user_type], :name => 'user_index' add_index :audits, :request_uuid add_index :audits, :created_at end
dringoen/audited
lib/audited/sweeper.rb
require "rails/observers/activerecord/active_record" require "rails/observers/action_controller/caching" module Audited class Sweeper < ActionController::Caching::Sweeper observe Audited.audit_class attr_accessor :controller def before(controller) self.controller = controller true end def after(controller) self.controller = nil end def before_create(audit) audit.user ||= current_user audit.remote_address = controller.try(:request).try(:remote_ip) audit.request_uuid = request_uuid if request_uuid end def current_user controller.send(Audited.current_user_method) if controller.respond_to?(Audited.current_user_method, true) end def request_uuid controller.try(:request).try(:uuid) end def add_observer!(klass) super define_callback(klass) end def define_callback(klass) observer = self callback_meth = :"_notify_audited_sweeper" klass.send(:define_method, callback_meth) do observer.update(:before_create, self) end klass.send(:before_create, callback_meth) end def controller ::Audited.store[:current_controller] end def controller=(value) ::Audited.store[:current_controller] = value end end end if defined?(ActionController) and defined?(ActionController::Base) # Create dynamic subclass of Audited::Sweeper otherwise rspec will # fail with both ActiveRecord and MongoMapper tests as there will be # around_filter collision sweeper_class = Class.new(Audited::Sweeper) do def self.name "#{Audited.audit_class}::Sweeper" end end ActionController::Base.class_eval do around_filter sweeper_class.instance end end
dringoen/audited
lib/audited/adapters/active_record/audit.rb
require 'set' require 'audited/audit' module Audited module Adapters module ActiveRecord # Audit saves the changes to ActiveRecord models. It has the following attributes: # # * <tt>auditable</tt>: the ActiveRecord model that was changed # * <tt>user</tt>: the user that performed the change; a string or an ActiveRecord model # * <tt>action</tt>: one of create, update, or delete # * <tt>audited_changes</tt>: a serialized hash of all the changes # * <tt>comment</tt>: a comment set with the audit # * <tt>version</tt>: the version of the model # * <tt>request_uuid</tt>: a uuid based that allows audits from the same controller request # * <tt>created_at</tt>: Time that the change was performed # # This version of the Audit model is specific to Club Holdings, to match the legacy version of the table that is in use. Make sure this file is kept up to date with changes in the sunshine version. class Audit < ::ActiveRecord::Base if Rails.version >= "3.2.0" include Audited::Audit include ActiveModel::Observing end # make this Audit model work without all the new columns that the Audit gem is trying to populate attr_accessor :associated_id, :associated_type, :user_id, :comment, :remote_address, :request_uuid # belongs_to :auditable , :polymorphic => true # belongs_to :audit_type belongs_to :membership, :foreign_key => "membership_uid" belongs_to :quintess_user, :class_name => "QuintessUser", :foreign_key => "quintess_editor_uid" belongs_to :member, :class_name => "Member", :foreign_key => "member_editor_uid" # This association screws up the quintess_user association somehow. belongs_to :membership_contract, :class_name => "MembershipContract", :foreign_key => "membership_contract_uid" if Rails.version >= "3.2.0" default_scope ->{ order(:version)} scope :descending, ->{ reorder("version DESC")} scope :creates, ->{ where({:action => 'create'})} scope :updates, ->{ where({:action => 'update'})} scope :destroys, ->{ where({:action => 'destroy'})} scope :up_until, ->(date_or_time){where("created_at <= ?", date_or_time) } scope :from_version, ->(version){where(['version >= ?', version]) } scope :to_version, ->(version){where(['version <= ?', version]) } scope :auditable_finder, ->(auditable_id, auditable_type){where(auditable_id: auditable_id, auditable_type: auditable_type)} # Return all audits older than the current one. def ancestors self.class.where(['auditable_id = ? and auditable_type = ? and version <= ?', auditable_id, auditable_type, version]) end end serialize :change_history before_save :cancel_if_disabled if Rails.version >= "3.2.0" before_save :fill_legacy_columns before_save(:fill_quintess_columns) if Rails.version >= "3.2.0" Rails.version >= "3.2.0" ? (self.table_name = "Audit") : set_table_name('Audit') Rails.version >= "3.2.0" ? (self.primary_key = "audit_uid") : set_primary_key('audit_uid') def user=(user_name) end def user nil end def audited_changes=(changes) self.change_history = changes end def audited_changes change_history end if Rails.version >= "3.2.0" def set_version_number # max = self.class.auditable_finder(auditable_id, auditable_type).maximum(:version) || 0 # self.version = max + 1 # we'll try it without versioning first. self.version = 0 end end def self.these_uids(key_uid_hash = nil) #logger.error "Threading Audit.these_uids, key_uid_hash = #{key_uid_hash.inspect rescue 'rescue'}" @@foreign_keys = key_uid_hash || {} end def self.uids_columns() begin #logger.error "Threading Audit.uids_columns, @@foreign_keys = #{@@foreign_keys.inspect rescue 'rescue'}" logger.error("Threading Audit.uids_columns, member/membership mismatch @@foreign_keys = #{(@@foreign_keys && @@foreign_keys.inspect) rescue 'rescue'}") if @@foreign_keys && @@foreign_keys[:member_uid] && @@foreign_keys[:membership_uid] && MemberMembership.find(:first, :conditions => ['member_uid = ? AND membership_uid = ?', @@foreign_keys[:member_uid], @@foreign_keys[:membership_uid]]) rescue end @@foreign_keys rescue @@foreign_keys = {} end def self.audited_classes @@audited_classes ||= find( :all, :select => "DISTINCT auditable_type", :order => "auditable_type ASC" ).collect {|a| a.auditable_type} end def self.add_audited_class(class_name) unless audited_classes.detect{|ac| ac == class_name} audited_classes << class_name end end def self.disabled=(disabled_flag) @@disabled = disabled_flag end def self.disabled @@disabled rescue @@disabled = false end protected def fill_legacy_columns atu = (self.action || 'nothing').upcase self.audit_type_ucode = atu if %w{CREATE UPDATE DESTROY}.include?(atu) true end if Rails.version >= "3.2.0" def fill_quintess_columns self.member_editor_uid = Logon.current_member, self.quintess_editor_uid = Logon.current_quintess_user true end def cancel_if_disabled return false if Audit.disabled true end end end end end end
dringoen/audited
spec/audited/adapters/active_record/active_record_spec_helper.rb
require 'spec_helper' require 'support/active_record/schema' require 'audited/adapters/active_record' require 'support/active_record/models' load "audited/sweeper.rb" # force to reload sweeper
dringoen/audited
lib/audited/adapters/active_record.rb
<reponame>dringoen/audited<gh_stars>10-100 require 'active_record' require 'audited/auditor' require 'audited/adapters/active_record/audit' module Audited::Auditor::ClassMethods def default_ignored_attributes [self.primary_key, inheritance_column] end end ::ActiveRecord::Base.send :include, Audited::Auditor Audited.audit_class = Audited::Adapters::ActiveRecord::Audit require 'audited/sweeper'
dringoen/audited
lib/audited/mongo_mapper/version.rb
module Audited module MongoMapper VERSION = "4.2.0" end end
dringoen/audited
lib/audited/adapters/mongo_mapper/audited_changes.rb
<gh_stars>10-100 module Audited module Adapters module MongoMapper class AuditedChanges < ::Hash def self.from_mongo(changes) changes.is_a?(Hash) ? new.replace(changes) : changes end def self.to_mongo(changes) if changes.is_a?(Hash) changes.inject({}) do |memo, (key, value)| memo[key] = if value.is_a?(Array) value.map{|v| v.class.to_mongo(v) } else value end memo end else changes end end end end end end
rubrikinc/ruby-delete-relics
lib/parseoptions.rb
<filename>lib/parseoptions.rb require 'optparse' require 'optparse/time' require 'ostruct' class ParseOptions CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary] CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" } def self.parse(args) options = OpenStruct.new opt_parser = OptionParser.new do |opts| opts.banner = "Usage: rubrik.rb [options]" opts.separator "" opts.separator "Specific options:" opts.on('-l', '--login', "Test login to API") do |login| options[:login] = login; end opts.separator "" opts.separator "Common options:" opts.on('-r', '--rubrik FRIENDLYNAME', "Rubrik name in .creds") do |o| options[:r] = o; end opts.on('--relic DAYS', "Number of days to keep snapshots") do |o| options[:relics] = o; end opts.on_tail("-h", "--help", "Show this message") do puts opts exit end end opt_parser.parse!(args) options end end
rubrikinc/ruby-delete-relics
rubrik.rb
<gh_stars>0 $LOAD_PATH.unshift File.expand_path('../lib/', __FILE__) require 'parseoptions.rb' require 'pp' require 'getCreds.rb' require 'json' require 'csv' require 'uri' require 'restCall.rb' require 'getToken.rb' date = DateTime.now.strftime('%Y-%m-%d.%H-%M-%S') # BEGIN Creds = getCreds(); Begintime=Time.now Logtime=Begintime.to_i # Global options Options = ParseOptions.parse(ARGV) r = Options.r v = Options.v if r vers=restCall(r ,"/api/v1/cluster/me",'','get', '')['version'] puts "Rubrik CDM Version #{vers}" end if Options.relics listData = restCall(r,"/api/v1/vmware/vm?limit=9999&is_relic=true&primary_cluster_id=local",'','get','')["data"] listData.each do |vm| if vm['isRelic'] a = [] vmData = restCall(r,"/api/v1/vmware/vm/#{vm['id']}",'','get','')['snapshots'] vmData.each do |ss| age = ((Date.parse Time.now.to_s) - (Date.parse ss['date'])).to_i a.push(age) end if a.min && a.min >= Options.relics.to_i puts "#{vm['name']} (#{vm['id']} is Relic : Newest Snapshot #{a.min} Days ago, DELETING ALL SNAPS" restCall(r,"/api/v1/vmware/vm/#{vm['id']}/snapshot",'','delete','') elsif !a.min puts "#{vm['name']} (#{vm['id']} is Relic : Snapshots have been deleted, pending processing" else puts "#{vm['name']} (#{vm['id']} is Relic : Newest Snapshot #{a.min} Days ago, not deleting" end end end end if Options.login require 'getToken.rb' end
rubrikinc/ruby-delete-relics
lib/restCall.rb
<filename>lib/restCall.rb<gh_stars>0 require 'net/https' require 'getToken.rb' def restCall(server,endpoint,l,type,header) begin endpoint = URI.encode(endpoint) if header.to_s.empty? # Rubrik and Basic Auth (u,pw,sv) = get_token(server) conn = Faraday.new(:url => 'https://' + sv.sample(1)[0], request: { open_timeout: 5, # opening a connection timeout: 360 # waiting for response }) conn.basic_auth u, pw conn.headers['Authorization'] elsif header # vCenter API Auth conn = Faraday.new(:url => 'https://' + server.sample(1)[0], request: { open_timeout: 5, # opening a connection timeout: 360 # waiting for response }) header.each do |k,v| conn.headers[k] = v end end conn.ssl.verify = false response = conn.public_send(type) do |req| req.url endpoint req.headers['Content-Type'] = 'application/json' req.body = l.to_json end if response.status !~ /^20\d$/ begin return JSON.parse(response.body) rescue return "Endpoint #{endpoint} returned #{response.status}" end end rescue Faraday::ConnectionFailed @error = "There was a timeout. Please try again." end end
rubrikinc/ruby-delete-relics
lib/getCreds.rb
# Simple Parser for Credential File, normally ~/.rubrik/creds.json # Format of creds.json : # { # "server": "[cluster_address]", # "username": "[username]", # "password": "[password]" #} # Most routines will accept login info as arguments (arg1 arg2 node username password) require 'json' def getCreds begin return JSON.parse(File.read("#{File.dirname(__FILE__)}/../.creds")) rescue StandardError=>e return e end end
yans67/yanOptionBarController
yanOptionBarController.podspec
<gh_stars>1-10 Pod::Spec.new do |s| s.name = "yanOptionBarController" s.version = "0.0.4" s.summary = "OptionBarController for iOS" s.description = "OptionBarController is iPad and iPhone compatible. Supports landscape and portrait orientations and can be used inside UITabbarController." s.homepage = "https://github.com/yans67/yanOptionBarController" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "yans67" => "<EMAIL>" } s.platform = :ios s.source = { :git => "https://github.com/yans67/yanOptionBarController.git", :tag => s.version.to_s } s.source_files = 'Classes/*.{h,m}' s.requires_arc = true end
ight/bazzar
app/controllers/user_sessions_controller.rb
class UserSessionsController < Devise::SessionsController skip_before_action :verify_authenticity_token, :verify_signed_out_user skip_before_action :authenticate_user!, only: [:create] respond_to :json swagger_controller :user_sessions, "User Login Management" swagger_api :create do summary 'Sign in a user to the application and returns back authentication token' param :form, :'user[email]', :string, :required, 'Email' param :form, :'user[password]', :password, :required, 'Password' response :created response :unauthorized end # Create method # # This method uses devise authentication system # # We are make it return authentication key in returns. def create resource = warden.authenticate!(auth_options) sign_in(resource_name, resource) render json: { api_key: resource.generate_auth_token }, status: :created end end