repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
IIStevowII/Chatter
Server/node_modules/sequelize/index.js
44
module.exports = require("./lib/sequelize")
mit
tihom/dream_blog
spec/controllers/admin/content_controller_spec.rb
23897
require 'spec_helper' describe Admin::ContentController do render_views # Like it's a shared, need call everywhere shared_examples_for 'index action' do it 'should render template index' do get 'index' response.should render_template('index') end it 'should see all published in index' do get :index, :search => {:published => '0', :published_at => '2008-08', :user_id => '2'} response.should render_template('index') response.should be_success end it 'should restrict only by searchstring' do article = FactoryGirl.create(:article, :body => 'once uppon an originally time') get :index, :search => {:searchstring => 'originally'} assigns(:articles).should == [article] response.should render_template('index') response.should be_success end it 'should restrict by searchstring and published_at' do FactoryGirl.create(:article) get :index, :search => {:searchstring => 'originally', :published_at => '2008-08'} assigns(:articles).should be_empty response.should render_template('index') response.should be_success end it 'should restrict to drafts' do article = FactoryGirl.create(:article, :state => 'draft') get :index, :search => {:state => 'drafts'} assigns(:articles).should == [article] response.should render_template('index') response.should be_success end it 'should restrict to publication pending articles' do article = FactoryGirl.create(:article, :state => 'publication_pending', :published_at => '2020-01-01') get :index, :search => {:state => 'pending'} assigns(:articles).should == [article] response.should render_template('index') response.should be_success end it 'should restrict to withdrawn articles' do article = FactoryGirl.create(:article, :state => 'withdrawn', :published_at => '2010-01-01') get :index, :search => {:state => 'withdrawn'} assigns(:articles).should == [article] response.should render_template('index') response.should be_success end it 'should restrict to withdrawn articles' do article = FactoryGirl.create(:article, :state => 'withdrawn', :published_at => '2010-01-01') get :index, :search => {:state => 'withdrawn'} assigns(:articles).should == [article] response.should render_template('index') response.should be_success end it 'should restrict to published articles' do article = FactoryGirl.create(:article, :state => 'published', :published_at => '2010-01-01') get :index, :search => {:state => 'published'} response.should render_template('index') response.should be_success end it 'should fallback to default behavior' do article = FactoryGirl.create(:article, :state => 'draft') get :index, :search => {:state => '3vI1 1337 h4x0r'} response.should render_template('index') assigns(:articles).should_not == [article] response.should be_success end end shared_examples_for 'autosave action' do describe "first time for a new article" do it 'should save new article with draft status and no parent article' do FactoryGirl.create(:none) lambda do lambda do post :autosave, :article => {:allow_comments => '1', :body_and_extended => 'my draft in autosave', :keywords => 'mientag', :permalink => 'big-post', :title => 'big post', :text_filter => 'none', :published => '1', :published_at => 'December 23, 2009 03:20 PM'} end.should change(Article, :count) end.should change(Tag, :count) result = Article.last result.body.should == 'my draft in autosave' result.title.should == 'big post' result.permalink.should == 'big-post' result.parent_id.should be_nil result.redirects.count.should == 0 end end describe "second time for a new article" do it 'should save the same article with draft status and no parent article' do draft = FactoryGirl.create(:article, :published => false, :state => 'draft') lambda do post :autosave, :article => { :id => draft.id, :body_and_extended => 'new body' } end.should_not change(Article, :count) result = Article.find(draft.id) result.body.should == 'new body' result.parent_id.should be_nil result.redirects.count.should == 0 end end describe "for a published article" do before :each do @article = FactoryGirl.create(:article) @data = {:allow_comments => @article.allow_comments, :body_and_extended => 'my draft in autosave', :keywords => '', :permalink => @article.permalink, :title => @article.title, :text_filter => @article.text_filter, :published => '1', :published_at => 'December 23, 2009 03:20 PM'} end it 'should create a draft article with proper attributes and existing article as a parent' do lambda do post :autosave, :id => @article.id, :article => @data end.should change(Article, :count) result = Article.last result.body.should == 'my draft in autosave' result.title.should == @article.title result.permalink.should == @article.permalink result.parent_id.should == @article.id result.redirects.count.should == 0 end it 'should not create another draft article with parent_id if article has already a draft associated' do draft = Article.create!(@article.attributes.merge(:guid => nil, :state => 'draft', :parent_id => @article.id)) lambda do post :autosave, :id => @article.id, :article => @data end.should_not change(Article, :count) Article.last.parent_id.should == @article.id end it 'should create a draft with the same permalink even if the title has changed' do @data[:title] = @article.title + " more stuff" lambda do post :autosave, :id => @article.id, :article => @data end.should change(Article, :count) result = Article.last result.parent_id.should == @article.id result.permalink.should == @article.permalink result.redirects.count.should == 0 end end describe "with an unrelated draft in the database" do before do @draft = FactoryGirl.create(:article, :state => 'draft') end it "leaves the original draft in existence" do post :autosave, 'article' => {} assigns(:article).id.should_not == @draft.id Article.find(@draft.id).should_not be_nil end end end describe 'insert_editor action' do before do FactoryGirl.create(:blog) @user = FactoryGirl.create(:user, :profile => FactoryGirl.create(:profile_admin, :label => Profile::ADMIN)) request.session = { :user => @user.id } end it 'should render _simple_editor' do get(:insert_editor, :editor => 'simple') response.should render_template('_simple_editor') end it 'should render _visual_editor' do get(:insert_editor, :editor => 'visual') response.should render_template('_visual_editor') end it 'should render _visual_editor even if editor param is set to unknow editor' do get(:insert_editor, :editor => 'unknow') response.should render_template('_visual_editor') end end shared_examples_for 'new action' do describe 'GET' do it "renders the 'new' template" do get :new response.should render_template('new') assigns(:article).should_not be_nil assigns(:article).redirects.count.should == 0 end it "correctly converts multi-word tags" do a = FactoryGirl.create(:article, :keywords => '"foo bar", baz') get :new, :id => a.id response.should have_selector("input[id=article_keywords][value='baz, \"foo bar\"']") end end def base_article(options={}) { :title => "posted via tests!", :body => "A good body", :allow_comments => '1', :allow_pings => '1' }.merge(options) end it 'should create article with no comments' do post(:new, 'article' => base_article({:allow_comments => '0'}), 'categories' => [FactoryGirl.create(:category).id]) assigns(:article).should_not be_allow_comments assigns(:article).should be_allow_pings assigns(:article).should be_published end it 'should create a published article with a redirect' do post(:new, 'article' => base_article) assigns(:article).redirects.count.should == 1 end it 'should create a draft article without a redirect' do post(:new, 'article' => base_article({:state => 'draft'})) assigns(:article).redirects.count.should == 0 end it 'should create an unpublished article without a redirect' do post(:new, 'article' => base_article({:published => false})) assigns(:article).redirects.count.should == 0 end it 'should create an article published in the future without a redirect' do post(:new, 'article' => base_article({:published_at => (Time.now + 1.hour).to_s})) assigns(:article).redirects.count.should == 0 end it 'should create article with no pings' do post(:new, 'article' => {:allow_pings => '0', 'title' => 'my Title'}, 'categories' => [FactoryGirl.create(:category).id]) assigns(:article).should be_allow_comments assigns(:article).should_not be_allow_pings assigns(:article).should be_published end it 'should create an article linked to the current user' do post :new, 'article' => base_article new_article = Article.last assert_equal @user, new_article.user end it 'should create new published article' do Article.count.should be == 1 post :new, 'article' => base_article Article.count.should be == 2 end it 'should redirect to show' do post :new, 'article' => base_article assert_response :redirect, :action => 'show' end it 'should send notifications on create' do begin u = FactoryGirl.create(:user, :notify_via_email => true, :notify_on_new_articles => true) u.save! ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries.clear emails = ActionMailer::Base.deliveries post :new, 'article' => base_article assert_equal(1, emails.size) assert_equal(u.email, emails.first.to[0]) ensure ActionMailer::Base.perform_deliveries = false end end it 'should create an article in a category' do category = FactoryGirl.create(:category) post :new, 'article' => base_article, 'categories' => [category.id] new_article = Article.last assert_equal [category], new_article.categories end it 'should create an article with tags' do post :new, 'article' => base_article(:keywords => "foo bar") new_article = Article.last assert_equal 2, new_article.tags.size end it 'should create article in future' do lambda do post(:new, :article => base_article(:published_at => (Time.now + 1.hour).to_s) ) assert_response :redirect, :action => 'show' assigns(:article).should_not be_published end.should_not change(Article.published, :count) assert_equal 1, Trigger.count assigns(:article).redirects.count.should == 0 end it "should correctly interpret time zone in :published_at" do post :new, 'article' => base_article(:published_at => "February 17, 2011 08:47 PM GMT+0100 (CET)") new_article = Article.last assert_equal Time.utc(2011, 2, 17, 19, 47), new_article.published_at end it 'should respect "GMT+0000 (UTC)" in :published_at' do post :new, 'article' => base_article(:published_at => 'August 23, 2011 08:40 PM GMT+0000 (UTC)') new_article = Article.last assert_equal Time.utc(2011, 8, 23, 20, 40), new_article.published_at end it 'should create a filtered article' do Article.delete_all body = "body via *markdown*" extended="*foo*" post :new, 'article' => { :title => "another test", :body => body, :extended => extended} assert_response :redirect, :action => 'index' new_article = Article.find(:first, :order => "created_at DESC") new_article.body.should eq body new_article.extended.should eq extended new_article.text_filter.name.should eq @user.text_filter.name new_article.html(:body).should eq "<p>body via <em>markdown</em></p>" new_article.html(:extended).should eq "<p><em>foo</em></p>" end describe "publishing a published article with an autosaved draft" do before do @orig = FactoryGirl.create(:article) @draft = FactoryGirl.create(:article, :parent_id => @orig.id, :state => 'draft', :published => false) post(:new, :id => @orig.id, :article => {:id => @draft.id, :body => 'update'}) end it "updates the original" do assert_raises ActiveRecord::RecordNotFound do Article.find(@draft.id) end end it "deletes the draft" do Article.find(@orig.id).body.should == 'update' end end describe "publishing a draft copy of a published article" do before do @orig = FactoryGirl.create(:article) @draft = FactoryGirl.create(:article, :parent_id => @orig.id, :state => 'draft', :published => false) post(:new, :id => @draft.id, :article => {:id => @draft.id, :body => 'update'}) end it "updates the original" do assert_raises ActiveRecord::RecordNotFound do Article.find(@draft.id) end end it "deletes the draft" do Article.find(@orig.id).body.should == 'update' end end describe "saving a published article as draft" do before do @orig = FactoryGirl.create(:article) post(:new, :id => @orig.id, :article => {:title => @orig.title, :draft => 'draft', :body => 'update' }) end it "leaves the original published" do @orig.reload @orig.published.should == true end it "leaves the original as is" do @orig.reload @orig.body.should_not == 'update' end it "redirects to the index" do response.should redirect_to(:action => 'index') end it "creates a draft" do draft = Article.child_of(@orig.id).first draft.parent_id.should == @orig.id draft.should_not be_published end end describe "with an unrelated draft in the database" do before do @draft = FactoryGirl.create(:article, :state => 'draft') end describe "saving new article as draft" do it "leaves the original draft in existence" do post( :new, 'article' => base_article({:draft => 'save as draft'})) assigns(:article).id.should_not == @draft.id Article.find(@draft.id).should_not be_nil end end end end shared_examples_for 'destroy action' do it 'should_not destroy article by get' do lambda do art_id = @article.id assert_not_nil Article.find(art_id) get :destroy, 'id' => art_id response.should be_success end.should_not change(Article, :count) end it 'should destroy article by post' do lambda do art_id = @article.id post :destroy, 'id' => art_id response.should redirect_to(:action => 'index') lambda{ article = Article.find(art_id) }.should raise_error(ActiveRecord::RecordNotFound) end.should change(Article, :count).by(-1) end end describe 'with admin connection' do before do FactoryGirl.create(:blog) #TODO delete this after remove fixture Profile.delete_all @user = FactoryGirl.create(:user, :text_filter => FactoryGirl.create(:markdown), :profile => FactoryGirl.create(:profile_admin, :label => Profile::ADMIN)) @user.editor = 'simple' @user.save @article = FactoryGirl.create(:article) request.session = { :user => @user.id } end it_should_behave_like 'index action' it_should_behave_like 'new action' it_should_behave_like 'destroy action' it_should_behave_like 'autosave action' describe 'edit action' do it 'should edit article' do get :edit, 'id' => @article.id response.should render_template('new') assigns(:article).should_not be_nil assigns(:article).should be_valid response.should contain(/body/) response.should contain(/extended content/) end it 'should update article by edit action' do begin ActionMailer::Base.perform_deliveries = true emails = ActionMailer::Base.deliveries emails.clear art_id = @article.id body = "another *textile* test" post :edit, 'id' => art_id, 'article' => {:body => body, :text_filter => 'textile'} assert_response :redirect, :action => 'show', :id => art_id article = @article.reload article.text_filter.name.should == "textile" body.should == article.body emails.size.should == 0 ensure ActionMailer::Base.perform_deliveries = false end end it 'should allow updating body_and_extended' do article = @article post :edit, 'id' => article.id, 'article' => { 'body_and_extended' => 'foo<!--more-->bar<!--more-->baz' } assert_response :redirect article.reload article.body.should == 'foo' article.extended.should == 'bar<!--more-->baz' end it 'should delete draft about this article if update' do article = @article draft = Article.create!(article.attributes.merge(:state => 'draft', :parent_id => article.id, :guid => nil)) lambda do post :edit, 'id' => article.id, 'article' => { 'title' => 'new'} end.should change(Article, :count).by(-1) Article.should_not be_exists({:id => draft.id}) end it 'should delete all draft about this article if update not happen but why not' do article = @article draft = Article.create!(article.attributes.merge(:state => 'draft', :parent_id => article.id, :guid => nil)) draft_2 = Article.create!(article.attributes.merge(:state => 'draft', :parent_id => article.id, :guid => nil)) lambda do post :edit, 'id' => article.id, 'article' => { 'title' => 'new'} end.should change(Article, :count).by(-2) Article.should_not be_exists({:id => draft.id}) Article.should_not be_exists({:id => draft_2.id}) end end describe 'resource_add action' do it 'should add resource' do art_id = @article.id resource = FactoryGirl.create(:resource) get :resource_add, :id => art_id, :resource_id => resource.id response.should render_template('_show_resources') assigns(:article).should be_valid assigns(:resource).should be_valid assert Article.find(art_id).resources.include?(resource) assert_not_nil assigns(:article) assert_not_nil assigns(:resource) assert_not_nil assigns(:resources) end end describe 'resource_remove action' do it 'should remove resource' do art_id = @article.id resource = FactoryGirl.create(:resource) get :resource_remove, :id => art_id, :resource_id => resource.id response.should render_template('_show_resources') assert assigns(:article).valid? assert assigns(:resource).valid? assert !Article.find(art_id).resources.include?(resource) assert_not_nil assigns(:article) assert_not_nil assigns(:resource) assert_not_nil assigns(:resources) end end describe 'auto_complete_for_article_keywords action' do before do FactoryGirl.create(:tag, :name => 'foo', :articles => [FactoryGirl.create(:article)]) FactoryGirl.create(:tag, :name => 'bazz', :articles => [FactoryGirl.create(:article)]) FactoryGirl.create(:tag, :name => 'bar', :articles => [FactoryGirl.create(:article)]) end it 'should return foo for keywords fo' do get :auto_complete_for_article_keywords, :article => {:keywords => 'fo'} response.should be_success response.body.should == '<ul class="unstyled" id="autocomplete"><li>foo</li></ul>' end it 'should return nothing for hello' do get :auto_complete_for_article_keywords, :article => {:keywords => 'hello'} response.should be_success response.body.should == '<ul class="unstyled" id="autocomplete"></ul>' end it 'should return bar and bazz for ba keyword' do get :auto_complete_for_article_keywords, :article => {:keywords => 'ba'} response.should be_success response.body.should == '<ul class="unstyled" id="autocomplete"><li>bar</li><li>bazz</li></ul>' end end end describe 'with publisher connection' do before :each do FactoryGirl.create(:blog) @user = FactoryGirl.create(:user, text_filter: FactoryGirl.create(:markdown), profile: FactoryGirl.create(:profile_publisher)) @user.editor = 'simple' @user.save @article = FactoryGirl.create(:article, :user => @user) request.session = {:user => @user.id} end it_should_behave_like 'index action' it_should_behave_like 'new action' it_should_behave_like 'destroy action' describe 'edit action' do it "should redirect if edit article doesn't his" do get :edit, :id => FactoryGirl.create(:article, :user => FactoryGirl.create(:user, :login => 'another_user')).id response.should redirect_to(:action => 'index') end it 'should edit article' do get :edit, 'id' => @article.id response.should render_template('new') assigns(:article).should_not be_nil assigns(:article).should be_valid end it 'should update article by edit action' do begin ActionMailer::Base.perform_deliveries = true emails = ActionMailer::Base.deliveries emails.clear art_id = @article.id body = "another *textile* test" post :edit, 'id' => art_id, 'article' => {:body => body, :text_filter => 'textile'} response.should redirect_to(:action => 'index') article = @article.reload article.text_filter.name.should == "textile" body.should == article.body emails.size.should == 0 ensure ActionMailer::Base.perform_deliveries = false end end end describe 'destroy action can be access' do it 'should redirect when want destroy article' do article = FactoryGirl.create(:article, :user => FactoryGirl.create(:user, :login => FactoryGirl.create(:user, :login => 'other_user'))) lambda do get :destroy, :id => article.id response.should redirect_to(:action => 'index') end.should_not change(Article, :count) end end end end
mit
susancal/Waitr
vendor/cache/ruby/2.3.0/gems/actionpack-5.0.0/lib/action_dispatch/routing/redirection.rb
6453
require 'action_dispatch/http/request' require 'active_support/core_ext/uri' require 'active_support/core_ext/array/extract_options' require 'rack/utils' require 'action_controller/metal/exceptions' require 'action_dispatch/routing/endpoint' module ActionDispatch module Routing class Redirect < Endpoint # :nodoc: attr_reader :status, :block def initialize(status, block) @status = status @block = block end def redirect?; true; end def call(env) serve Request.new env end def serve(req) req.check_path_parameters! uri = URI.parse(path(req.path_parameters, req)) unless uri.host if relative_path?(uri.path) uri.path = "#{req.script_name}/#{uri.path}" elsif uri.path.empty? uri.path = req.script_name.empty? ? "/" : req.script_name end end uri.scheme ||= req.scheme uri.host ||= req.host uri.port ||= req.port unless req.standard_port? body = %(<html><body>You are being <a href="#{ERB::Util.unwrapped_html_escape(uri.to_s)}">redirected</a>.</body></html>) headers = { 'Location' => uri.to_s, 'Content-Type' => 'text/html', 'Content-Length' => body.length.to_s } [ status, headers, [body] ] end def path(params, request) block.call params, request end def inspect "redirect(#{status})" end private def relative_path?(path) path && !path.empty? && path[0] != '/' end def escape(params) Hash[params.map{ |k,v| [k, Rack::Utils.escape(v)] }] end def escape_fragment(params) Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_fragment(v)] }] end def escape_path(params) Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_path(v)] }] end end class PathRedirect < Redirect URL_PARTS = /\A([^?]+)?(\?[^#]+)?(#.+)?\z/ def path(params, request) if block.match(URL_PARTS) path = interpolation_required?($1, params) ? $1 % escape_path(params) : $1 query = interpolation_required?($2, params) ? $2 % escape(params) : $2 fragment = interpolation_required?($3, params) ? $3 % escape_fragment(params) : $3 "#{path}#{query}#{fragment}" else interpolation_required?(block, params) ? block % escape(params) : block end end def inspect "redirect(#{status}, #{block})" end private def interpolation_required?(string, params) !params.empty? && string && string.match(/%\{\w*\}/) end end class OptionRedirect < Redirect # :nodoc: alias :options :block def path(params, request) url_options = { :protocol => request.protocol, :host => request.host, :port => request.optional_port, :path => request.path, :params => request.query_parameters }.merge! options if !params.empty? && url_options[:path].match(/%\{\w*\}/) url_options[:path] = (url_options[:path] % escape_path(params)) end unless options[:host] || options[:domain] if relative_path?(url_options[:path]) url_options[:path] = "/#{url_options[:path]}" url_options[:script_name] = request.script_name elsif url_options[:path].empty? url_options[:path] = request.script_name.empty? ? "/" : "" url_options[:script_name] = request.script_name end end ActionDispatch::Http::URL.url_for url_options end def inspect "redirect(#{status}, #{options.map{ |k,v| "#{k}: #{v}" }.join(', ')})" end end module Redirection # Redirect any path to another path: # # get "/stories" => redirect("/posts") # # You can also use interpolation in the supplied redirect argument: # # get 'docs/:article', to: redirect('/wiki/%{article}') # # Note that if you return a path without a leading slash then the url is prefixed with the # current SCRIPT_NAME environment variable. This is typically '/' but may be different in # a mounted engine or where the application is deployed to a subdirectory of a website. # # Alternatively you can use one of the other syntaxes: # # The block version of redirect allows for the easy encapsulation of any logic associated with # the redirect in question. Either the params and request are supplied as arguments, or just # params, depending of how many arguments your block accepts. A string is required as a # return value. # # get 'jokes/:number', to: redirect { |params, request| # path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp") # "http://#{request.host_with_port}/#{path}" # } # # Note that the +do end+ syntax for the redirect block wouldn't work, as Ruby would pass # the block to +get+ instead of +redirect+. Use <tt>{ ... }</tt> instead. # # The options version of redirect allows you to supply only the parts of the url which need # to change, it also supports interpolation of the path similar to the first example. # # get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}') # get 'stores/:name(*all)', to: redirect(subdomain: 'stores', path: '/%{name}%{all}') # # Finally, an object which responds to call can be supplied to redirect, allowing you to reuse # common redirect routes. The call method must accept two arguments, params and request, and return # a string. # # get 'accounts/:name' => redirect(SubdomainRedirector.new('api')) # def redirect(*args, &block) options = args.extract_options! status = options.delete(:status) || 301 path = args.shift return OptionRedirect.new(status, options) if options.any? return PathRedirect.new(status, path) if String === path block = path if path.respond_to? :call raise ArgumentError, "redirection argument not supported" unless block Redirect.new status, block end end end end
mit
sf-takaki-umemura/angular-study
Client/app/+examples/stripe-payment/stripe-payment.component.ts
2112
import { Component, OnInit, NgZone } from '@angular/core'; import { UtilityService } from '../../core/services/utility.service'; declare const Stripe: any; @Component({ selector: 'appc-stripe-payment', templateUrl: './stripe-payment.component.html', styleUrls: ['./stripe-payment.component.scss'] }) export class StripePaymentComponent implements OnInit { // Fields public cardNumber = '4242424242424242'; public expiryMonth = '10'; public expiryYear = '18'; public cvc = '222'; public message: string; constructor(private zone: NgZone, private us: UtilityService) { } public ngOnInit() { this.us.loadScript('https://checkout.stripe.com/checkout.js').subscribe(x => { this.us.loadScript('https://js.stripe.com/v2/').subscribe(y => { // here we setup the stripe publish key. // notice that this is a test key for my account so replace with production key(live) Stripe.setPublishableKey('pk_test_1JJKhZ3DycRrYqdE5GWzlbDd'); }); }); } public openCheckout() { // tslint:disable-next-line:whitespace const handler = (<any>window).StripeCheckout.configure({ locale: 'auto', key: 'pk_test_1JJKhZ3DycRrYqdE5GWzlbDd', token: (token: any) => { // You can access the token ID with `token.id`. // Get the token ID to your server-side code for use. } }); handler.open({ name: 'Demo Site', description: '2 widgets', amount: 2000 }); } public getToken() { // set up the card data as an object this.message = 'Loading...'; const dataObj = { number: this.cardNumber, exp_month: this.expiryMonth, exp_year: this.expiryYear, cvc: this.cvc }; // Request a token from Stripe: Stripe.card.createToken(dataObj, (status: number, response: any) => { // Wrapping inside the Angular zone this.zone.run(() => { if (status === 200) { this.message = `Success! Card token ${response.card.id}.`; } else { this.message = response.error.message; } }); } ); } }
mit
wp-plugins/double-click
vendor/zendframework/zendframework/library/Zend/ModuleManager/Feature/DependencyIndicatorInterface.php
583
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\ModuleManager\Feature; interface DependencyIndicatorInterface { /** * Expected to return an array of modules on which the current one depends on * * @return array */ public function getModuleDependencies(); }
mit
benouat/ng-bootstrap
src/dropdown/dropdown.module.ts
624
import {NgModule} from '@angular/core'; import { NgbDropdown, NgbDropdownAnchor, NgbDropdownToggle, NgbDropdownMenu, NgbDropdownItem, NgbNavbar } from './dropdown'; export { NgbDropdown, NgbDropdownAnchor, NgbDropdownToggle, NgbDropdownMenu, NgbDropdownItem, NgbNavbar } from './dropdown'; export {NgbDropdownConfig} from './dropdown-config'; const NGB_DROPDOWN_DIRECTIVES = [NgbDropdown, NgbDropdownAnchor, NgbDropdownToggle, NgbDropdownMenu, NgbDropdownItem, NgbNavbar]; @NgModule({declarations: NGB_DROPDOWN_DIRECTIVES, exports: NGB_DROPDOWN_DIRECTIVES}) export class NgbDropdownModule { }
mit
askl56/smart-answers
test/unit/date_helper_test.rb
360
require_relative "../test_helper" require_relative "../../lib/smart_answer/date_helper" class DateHelperTest < ActiveSupport::TestCase include DateHelper context "next_saturday" do should "return the following saturday for a provided date" do assert_equal Date.parse("2012 Mar 03"), next_saturday(Date.parse("2012 March 01")) end end end
mit
Twi/amaya
amaya/__init__.py
20
from base import *
mit
soltrinox/vator-api-serv
node_modules/loopback-component-storage/node_modules/pkgcloud/node_modules/gcloud/node_modules/protobufjs/node_modules/bytebuffer/src/encodings/hex.js
2392
//? if (HEX) { // encodings/hex /** * Encodes this ByteBuffer's contents to a hex encoded string. * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}. * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}. * @returns {string} Hex encoded string * @expose */ ByteBufferPrototype.toHex = function(begin, end) { begin = typeof begin === 'undefined' ? this.offset : begin; end = typeof end === 'undefined' ? this.limit : end; if (!this.noAssert) { //? ASSERT_RANGE(); } //? if (NODE) return this.buffer.toString("hex", begin, end); //? else { var out = new Array(end - begin), b; while (begin < end) { //? if (DATAVIEW) b = this.view.getUint8(begin++); //? else b = this.view[begin++]; if (b < 0x10) out.push("0", b.toString(16)); else out.push(b.toString(16)); } return out.join(''); //? } }; /** * Decodes a hex encoded string to a ByteBuffer. * @param {string} str String to decode * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to * {@link ByteBuffer.DEFAULT_ENDIAN}. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to * {@link ByteBuffer.DEFAULT_NOASSERT}. * @returns {!ByteBuffer} ByteBuffer * @expose */ ByteBuffer.fromHex = function(str, littleEndian, noAssert) { if (!noAssert) { if (typeof str !== 'string') throw TypeError("Illegal str: Not a string"); if (str.length % 2 !== 0) throw TypeError("Illegal str: Length not a multiple of 2"); } //? if (NODE) { var bb = new ByteBuffer(0, littleEndian, true); bb.buffer = new Buffer(str, "hex"); //? if (BUFFERVIEW) bb.view = new BufferView(bb.buffer); bb.limit = bb.buffer.length; //? } else { var k = str.length, bb = new ByteBuffer((k / 2) | 0, littleEndian), b; for (var i=0, j=0; i<k; i+=2) { b = parseInt(str.substring(i, i+2), 16); if (!noAssert) if (!isFinite(b) || b < 0 || b > 255) throw TypeError("Illegal str: Contains non-hex characters"); //? if (DATAVIEW) bb.view.setUint8(j++, b); //? else bb.view[j++] = b; } bb.limit = j; //? } return bb; }; //? }
mit
hansbonini/cloud9-magento
www/lib/Varien/Image/Adapter/Abstract.php
6678
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Varien * @package Varien_Image * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * @file Abstract.php * @author Magento Core Team <core@magentocommerce.com> */ abstract class Varien_Image_Adapter_Abstract { public $fileName = null; public $imageBackgroundColor = 0; const POSITION_TOP_LEFT = 'top-left'; const POSITION_TOP_RIGHT = 'top-right'; const POSITION_BOTTOM_LEFT = 'bottom-left'; const POSITION_BOTTOM_RIGHT = 'bottom-right'; const POSITION_STRETCH = 'stretch'; const POSITION_TILE = 'tile'; const POSITION_CENTER = 'center'; protected $_fileType = null; protected $_fileName = null; protected $_fileMimeType = null; protected $_fileSrcName = null; protected $_fileSrcPath = null; protected $_imageHandler = null; protected $_imageSrcWidth = null; protected $_imageSrcHeight = null; protected $_requiredExtensions = null; protected $_watermarkPosition = null; protected $_watermarkWidth = null; protected $_watermarkHeigth = null; protected $_watermarkImageOpacity = null; protected $_quality = null; protected $_keepAspectRatio; protected $_keepFrame; protected $_keepTransparency; protected $_backgroundColor; protected $_constrainOnly; abstract public function open($fileName); abstract public function save($destination=null, $newName=null); abstract public function display(); abstract public function resize($width=null, $height=null); abstract public function rotate($angle); abstract public function crop($top=0, $left=0, $right=0, $bottom=0); abstract public function watermark($watermarkImage, $positionX=0, $positionY=0, $watermarkImageOpacity=30, $repeat=false); abstract public function checkDependencies(); public function getMimeType() { if( $this->_fileType ) { return $this->_fileType; } else { list($this->_imageSrcWidth, $this->_imageSrcHeight, $this->_fileType, ) = getimagesize($this->_fileName); $this->_fileMimeType = image_type_to_mime_type($this->_fileType); return $this->_fileMimeType; } } /** * Retrieve Original Image Width * * @return int|null */ public function getOriginalWidth() { $this->getMimeType(); return $this->_imageSrcWidth; } /** * Retrieve Original Image Height * * @return int|null */ public function getOriginalHeight() { $this->getMimeType(); return $this->_imageSrcHeight; } public function setWatermarkPosition($position) { $this->_watermarkPosition = $position; return $this; } public function getWatermarkPosition() { return $this->_watermarkPosition; } public function setWatermarkImageOpacity($imageOpacity) { $this->_watermarkImageOpacity = $imageOpacity; return $this; } public function getWatermarkImageOpacity() { return $this->_watermarkImageOpacity; } public function setWatermarkWidth($width) { $this->_watermarkWidth = $width; return $this; } public function getWatermarkWidth() { return $this->_watermarkWidth; } public function setWatermarkHeigth($heigth) { $this->_watermarkHeigth = $heigth; return $this; } public function getWatermarkHeigth() { return $this->_watermarkHeigth; } /** * Get/set keepAspectRatio * * @param bool $value * @return bool|Varien_Image_Adapter_Abstract */ public function keepAspectRatio($value = null) { if (null !== $value) { $this->_keepAspectRatio = (bool)$value; } return $this->_keepAspectRatio; } /** * Get/set keepFrame * * @param bool $value * @return bool */ public function keepFrame($value = null) { if (null !== $value) { $this->_keepFrame = (bool)$value; } return $this->_keepFrame; } /** * Get/set keepTransparency * * @param bool $value * @return bool */ public function keepTransparency($value = null) { if (null !== $value) { $this->_keepTransparency = (bool)$value; } return $this->_keepTransparency; } /** * Get/set constrainOnly * * @param bool $value * @return bool */ public function constrainOnly($value = null) { if (null !== $value) { $this->_constrainOnly = (bool)$value; } return $this->_constrainOnly; } /** * Get/set quality, values in percentage from 0 to 100 * * @param int $value * @return int */ public function quality($value = null) { if (null !== $value) { $this->_quality = (int)$value; } return $this->_quality; } /** * Get/set keepBackgroundColor * * @param array $value * @return array */ public function backgroundColor($value = null) { if (null !== $value) { if ((!is_array($value)) || (3 !== count($value))) { return; } foreach ($value as $color) { if ((!is_integer($color)) || ($color < 0) || ($color > 255)) { return; } } } $this->_backgroundColor = $value; return $this->_backgroundColor; } protected function _getFileAttributes() { $pathinfo = pathinfo($this->_fileName); $this->_fileSrcPath = $pathinfo['dirname']; $this->_fileSrcName = $pathinfo['basename']; } }
mit
Rafalsky/home-finance
backend/views/article-category/_search.php
779
<?php use yii\helpers\Html; use yii\bootstrap\ActiveForm; /* @var $this yii\web\View */ /* @var $model backend\models\search\ArticleCategorySearch */ /* @var $form yii\bootstrap\ActiveForm */ ?> <div class="article-category-search"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?= $form->field($model, 'id') ?> <?= $form->field($model, 'slug') ?> <?= $form->field($model, 'title') ?> <?= $form->field($model, 'status') ?> <div class="form-group"> <?= Html::submitButton(Yii::t('backend', 'Search'), ['class' => 'btn btn-primary']) ?> <?= Html::resetButton(Yii::t('backend', 'Reset'), ['class' => 'btn btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div>
mit
shutchings/azure-sdk-for-net
src/SDKs/Cdn/Management.Cdn/Generated/Models/ValidateCustomDomainInput.cs
2123
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Cdn; using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// Input of the custom domain to be validated for DNS mapping. /// </summary> public partial class ValidateCustomDomainInput { /// <summary> /// Initializes a new instance of the ValidateCustomDomainInput class. /// </summary> public ValidateCustomDomainInput() { CustomInit(); } /// <summary> /// Initializes a new instance of the ValidateCustomDomainInput class. /// </summary> /// <param name="hostName">The host name of the custom domain. Must be /// a domain name.</param> public ValidateCustomDomainInput(string hostName) { HostName = hostName; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the host name of the custom domain. Must be a domain /// name. /// </summary> [JsonProperty(PropertyName = "hostName")] public string HostName { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (HostName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "HostName"); } } } }
mit
cristianmejia/upmin-admin-ruby
test_seeders/order_seeder.rb
1291
# Dir["#{File.dirname(__FILE__)}/../models/*.rb"].each { |f| require f } class OrderSeeder def OrderSeeder.seed (1..200).each do |i| user = find_helper(User, rand(User.count) + 1) order = Order.new order.user = user order.save! num_products = rand(4) + 1 (1..num_products).each do |k| quantity = rand(4) + 1 product = find_helper(Product, rand(Product.count) + 1) po = ProductOrder.new po.order = order po.product = product po.quantity = quantity po.purchase_price = product.price po.save! end shipment = Shipment.new shipment.order = order shipment.price = (rand(1000) / 100.0) + 10.0 shipment.carrier = [:ups, :usps, :fedex, :dhl][rand(4)] shipment.delivered = [true, true, false][rand(3)] shipment.est_delivery_date = random_date shipment.save! end end def OrderSeeder.random_date(ago = 60, from_now = 20) ago = (0..ago).to_a.map{|i| i.days.ago} from_now = (1..from_now).to_a.map{|i| i.days.ago} all = ago + from_now return all[rand(all.length)] end def OrderSeeder.find_helper(model, id) if defined?(DataMapper) return model.get(id) else return model.find(id) end end end
mit
evansd-archive/kohana-module--ckeditor
vendor/ckeditor/_source/core/editor_basic.js
6171
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ if ( !CKEDITOR.editor ) { /** * No element is linked to the editor instance. * @constant * @example */ CKEDITOR.ELEMENT_MODE_NONE = 0; /** * The element is to be replaced by the editor instance. * @constant * @example */ CKEDITOR.ELEMENT_MODE_REPLACE = 1; /** * The editor is to be created inside the element. * @constant * @example */ CKEDITOR.ELEMENT_MODE_APPENDTO = 2; /** * Creates an editor class instance. This constructor should be rarely * used, in favor of the {@link CKEDITOR} editor creation functions. * @ class Represents an editor instance. * @param {Object} instanceConfig Configuration values for this specific * instance. * @param {CKEDITOR.dom.element} [element] The element linked to this * instance. * @param {Number} [mode] The mode in which the element is linked to this * instance. See {@link #elementMode}. * @param {String} [data] Since 3.3. Initial value for the instance. * @augments CKEDITOR.event * @example */ CKEDITOR.editor = function( instanceConfig, element, mode, data ) { this._ = { // Save the config to be processed later by the full core code. instanceConfig : instanceConfig, element : element, data : data }; /** * The mode in which the {@link #element} is linked to this editor * instance. It can be any of the following values: * <ul> * <li>{@link CKEDITOR.ELEMENT_MODE_NONE}: No element is linked to the * editor instance.</li> * <li>{@link CKEDITOR.ELEMENT_MODE_REPLACE}: The element is to be * replaced by the editor instance.</li> * <li>{@link CKEDITOR.ELEMENT_MODE_APPENDTO}: The editor is to be * created inside the element.</li> * </ul> * @name CKEDITOR.editor.prototype.elementMode * @type Number * @example * var editor = CKEDITOR.replace( 'editor1' ); * alert( <b>editor.elementMode</b> ); "1" */ this.elementMode = mode || CKEDITOR.ELEMENT_MODE_NONE; // Call the CKEDITOR.event constructor to initialize this instance. CKEDITOR.event.call( this ); this._init(); }; /** * Replaces a &lt;textarea&gt; or a DOM element (DIV) with a CKEditor * instance. For textareas, the initial value in the editor will be the * textarea value. For DOM elements, their innerHTML will be used * instead. We recommend using TEXTAREA and DIV elements only. Do not use * this function directly. Use {@link CKEDITOR.replace} instead. * @param {Object|String} elementOrIdOrName The DOM element (textarea), its * ID or name. * @param {Object} [config] The specific configurations to apply to this * editor instance. Configurations set here will override global CKEditor * settings. * @returns {CKEDITOR.editor} The editor instance created. * @example */ CKEDITOR.editor.replace = function( elementOrIdOrName, config ) { var element = elementOrIdOrName; if ( typeof element != 'object' ) { // Look for the element by id. We accept any kind of element here. element = document.getElementById( elementOrIdOrName ); // Elements that should go into head are unacceptable (#6791). if ( element && element.tagName.toLowerCase() in {style:1,script:1,base:1,link:1,meta:1,title:1} ) element = null; // If not found, look for elements by name. In this case we accept only // textareas. if ( !element ) { var i = 0, textareasByName = document.getElementsByName( elementOrIdOrName ); while ( ( element = textareasByName[ i++ ] ) && element.tagName.toLowerCase() != 'textarea' ) { /*jsl:pass*/ } } if ( !element ) throw '[CKEDITOR.editor.replace] The element with id or name "' + elementOrIdOrName + '" was not found.'; } // Do not replace the textarea right now, just hide it. The effective // replacement will be done by the _init function. element.style.visibility = 'hidden'; // Create the editor instance. return new CKEDITOR.editor( config, element, CKEDITOR.ELEMENT_MODE_REPLACE ); }; /** * Creates a new editor instance inside a specific DOM element. Do not use * this function directly. Use {@link CKEDITOR.appendTo} instead. * @param {Object|String} elementOrId The DOM element or its ID. * @param {Object} [config] The specific configurations to apply to this * editor instance. Configurations set here will override global CKEditor * settings. * @param {String} [data] Since 3.3. Initial value for the instance. * @returns {CKEDITOR.editor} The editor instance created. * @example */ CKEDITOR.editor.appendTo = function( elementOrId, config, data ) { var element = elementOrId; if ( typeof element != 'object' ) { element = document.getElementById( elementOrId ); if ( !element ) throw '[CKEDITOR.editor.appendTo] The element with id "' + elementOrId + '" was not found.'; } // Create the editor instance. return new CKEDITOR.editor( config, element, CKEDITOR.ELEMENT_MODE_APPENDTO, data ); }; CKEDITOR.editor.prototype = { /** * Initializes the editor instance. This function will be overriden by the * full CKEDITOR.editor implementation (editor.js). * @private */ _init : function() { var pending = CKEDITOR.editor._pending || ( CKEDITOR.editor._pending = [] ); pending.push( this ); }, // Both fire and fireOnce will always pass this editor instance as the // "editor" param in CKEDITOR.event.fire. So, we override it to do that // automaticaly. /** @ignore */ fire : function( eventName, data ) { return CKEDITOR.event.prototype.fire.call( this, eventName, data, this ); }, /** @ignore */ fireOnce : function( eventName, data ) { return CKEDITOR.event.prototype.fireOnce.call( this, eventName, data, this ); } }; // "Inherit" (copy actually) from CKEDITOR.event. CKEDITOR.event.implementOn( CKEDITOR.editor.prototype, true ); }
mit
erikzhouxin/CSharpSolution
OSS/Alipay/F2FPayDll/Projects/alipay-sdk-NET20161213174056/Response/KoubeiQualityTestCloudacptBatchQueryResponse.cs
811
using System; using System.Xml.Serialization; using System.Collections.Generic; using Aop.Api.Domain; namespace Aop.Api.Response { /// <summary> /// KoubeiQualityTestCloudacptBatchQueryResponse. /// </summary> public class KoubeiQualityTestCloudacptBatchQueryResponse : AopResponse { /// <summary> /// 活动id /// </summary> [XmlElement("activity_id")] public string ActivityId { get; set; } /// <summary> /// 批次列表 /// </summary> [XmlArray("batch_list")] [XmlArrayItem("open_batch")] public List<OpenBatch> BatchList { get; set; } /// <summary> /// 单品批次数 /// </summary> [XmlElement("batch_num")] public string BatchNum { get; set; } } }
mit
mono/referencesource
System.Web/LegacyAspNetSynchronizationContext.cs
8169
//------------------------------------------------------------------------------ // <copyright file="LegacyAspNetSynchronizationContext.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.ComponentModel; using System.Runtime.ExceptionServices; using System.Security.Permissions; using System.Threading; using System.Web; using System.Web.Util; namespace System.Web { // Represents a SynchronizationContext that has legacy behavior (<= FX 4.0) when it comes to asynchronous operations. // Characterized by locking on the HttpApplication to synchronize work, dispatching Posts as Sends. internal sealed class LegacyAspNetSynchronizationContext : AspNetSynchronizationContextBase { private HttpApplication _application; private Action<bool> _appVerifierCallback; private bool _disabled; private bool _syncCaller; private bool _invalidOperationEncountered; private int _pendingCount; private ExceptionDispatchInfo _error; private WaitCallback _lastCompletionCallback; private object _lastCompletionCallbackLock; internal LegacyAspNetSynchronizationContext(HttpApplication app) { _application = app; _appVerifierCallback = AppVerifier.GetSyncContextCheckDelegate(app); _lastCompletionCallbackLock = new object(); } private void CheckForRequestStateIfRequired() { if (_appVerifierCallback != null) { _appVerifierCallback(false); } } private void CallCallback(SendOrPostCallback callback, Object state) { CheckForRequestStateIfRequired(); // don't take app lock for [....] caller to avoid deadlocks in case they poll for result if (_syncCaller) { CallCallbackPossiblyUnderLock(callback, state); } else { lock (_application) { CallCallbackPossiblyUnderLock(callback, state); } } } private void CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state) { ThreadContext threadContext = null; try { threadContext = _application.OnThreadEnter(); try { callback(state); } catch (Exception e) { _error = ExceptionDispatchInfo.Capture(e); } } finally { if (threadContext != null) { threadContext.DisassociateFromCurrentThread(); } } } // this property no-ops using the legacy [....] context internal override bool AllowAsyncDuringSyncStages { get; set; } internal override int PendingOperationsCount { get { return _pendingCount; } } internal override ExceptionDispatchInfo ExceptionDispatchInfo { get { return _error; } } internal override void ClearError() { _error = null; } // Dev11 Bug 70908: Race condition involving SynchronizationContext allows ASP.NET requests to be abandoned in the pipeline // // When the last completion occurs, the _pendingCount is decremented and then the _lastCompletionCallbackLock is acquired to get // the _lastCompletionCallback. If the _lastCompletionCallback is non-null, then the last completion will invoke the callback; // otherwise, the caller of PendingCompletion will handle the completion. internal override bool PendingCompletion(WaitCallback callback) { Debug.Assert(_lastCompletionCallback == null); // only one at a time bool pending = false; if (_pendingCount != 0) { lock (_lastCompletionCallbackLock) { if (_pendingCount != 0) { pending = true; _lastCompletionCallback = callback; } } } return pending; } public override void Send(SendOrPostCallback callback, Object state) { #if DBG Debug.Trace("Async", "Send"); Debug.Trace("AsyncStack", "Send from:\r\n" + GetDebugStackTrace()); #endif CallCallback(callback, state); } public override void Post(SendOrPostCallback callback, Object state) { #if DBG Debug.Trace("Async", "Post"); Debug.Trace("AsyncStack", "Post from:\r\n" + GetDebugStackTrace()); #endif CallCallback(callback, state); } #if DBG [EnvironmentPermission(SecurityAction.Assert, Unrestricted=true)] private void CreateCopyDumpStack() { Debug.Trace("Async", "CreateCopy"); Debug.Trace("AsyncStack", "CreateCopy from:\r\n" + GetDebugStackTrace()); } #endif public override SynchronizationContext CreateCopy() { #if DBG CreateCopyDumpStack(); #endif LegacyAspNetSynchronizationContext context = new LegacyAspNetSynchronizationContext(_application); context._disabled = _disabled; context._syncCaller = _syncCaller; context.AllowAsyncDuringSyncStages = AllowAsyncDuringSyncStages; return context; } public override void OperationStarted() { if (_invalidOperationEncountered || (_disabled && _pendingCount == 0)) { _invalidOperationEncountered = true; throw new InvalidOperationException(SR.GetString(SR.Async_operation_disabled)); } Interlocked.Increment(ref _pendingCount); #if DBG Debug.Trace("Async", "OperationStarted(count=" + _pendingCount + ")"); Debug.Trace("AsyncStack", "OperationStarted(count=" + _pendingCount + ") from:\r\n" + GetDebugStackTrace()); #endif } public override void OperationCompleted() { if (_invalidOperationEncountered || (_disabled && _pendingCount == 0)) { // throw from operation started could cause extra operation completed return; } int pendingCount = Interlocked.Decrement(ref _pendingCount); #if DBG Debug.Trace("Async", "OperationCompleted(pendingCount=" + pendingCount + ")"); Debug.Trace("AsyncStack", "OperationCompleted(pendingCount=" + pendingCount + ") from:\r\n" + GetDebugStackTrace()); #endif // notify (once) about the last completion to resume the async work if (pendingCount == 0) { WaitCallback callback = null; lock (_lastCompletionCallbackLock) { callback = _lastCompletionCallback; _lastCompletionCallback = null; } if (callback != null) { Debug.Trace("Async", "Queueing LastCompletionWorkItemCallback"); ThreadPool.QueueUserWorkItem(callback); } } } internal override bool Enabled { get { return !_disabled; } } internal override void Enable() { _disabled = false; } internal override void Disable() { _disabled = true; } internal override void SetSyncCaller() { _syncCaller = true; } internal override void ResetSyncCaller() { _syncCaller = false; } internal override void AssociateWithCurrentThread() { Monitor.Enter(_application); } internal override void DisassociateFromCurrentThread() { Monitor.Exit(_application); } #if DBG [EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)] private static string GetDebugStackTrace() { return Environment.StackTrace; } #endif } }
mit
redbubble/rollbar-gem
lib/rollbar/delay/thread.rb
596
module Rollbar module Delay class Thread def self.call(payload) new.call(payload) end def call(payload) ::Thread.new do begin Rollbar.process_from_async_handler(payload) rescue # Here we swallow the exception: # 1. The original report wasn't sent. # 2. An internal error was sent and logged # # If users want to handle this in some way they # can provide a more custom Thread based implementation end end end end end end
mit
isislovecruft/globe
app.js
792
/** * Module dependencies. */ var express = require('express') , http = require('http') , path = require('path'); var app = express(); var distDir = '/build/dist/'; // all express settings app.set('port', process.env.PORT || 3000); app.use(express.favicon(__dirname + distDir +'favicon.ico')); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, distDir))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', function(req, res){ res.sendfile('build/dist/index.html'); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
mit
1974kpkpkp/merb
merb-core/experimentation/simple_benches/cookie.rb
577
require "rubygems" require "rbench" def original(name, value, options) (@_headers['Set-Cookie'] ||=[]) << "#{name}=#{value}; " + options.map{|k, v| "#{k}=#{v};"}.sort.join(' ') end def new_impl(name, value, options) cookie = @_headers["Set-Cookie"] ||= [] cookie << ("#{name}=#{value}" << options.map do |k,v| "#{k}=#{v};" end.join(" ")) end RBench.run(10_000) do report("original") do @_headers = {} original("foo", "bar", :foo => "bar") end report("new_impl") do @_headers = {} new_impl("foo", "bar", :foo => "bar") end end
mit
ermshiperete/web-languageforge
src/angular-app/bellows/core/input-systems/input-systems.scripts.ts
7150
// THIS FILE IS AUTOMATICALLY GENERATED by build-json-language-data.py // Do not make changes to this file; they will be overwritten. // Input Systems Scripts data export const inputSystemsScripts = { "Adlm": [ "Adlam" ], "Afak": [ "Afaka" ], "Aghb": [ "Caucasian Albanian" ], "Ahom": [ "Ahom", "Tai Ahom" ], "Arab": [ "Arabic" ], "Aran": [ "Arabic (Nastaliq variant)" ], "Armi": [ "Imperial Aramaic" ], "Armn": [ "Armenian" ], "Avst": [ "Avestan" ], "Bali": [ "Balinese" ], "Bamu": [ "Bamum" ], "Bass": [ "Bassa Vah" ], "Batk": [ "Batak" ], "Beng": [ "Bengali" ], "Blis": [ "Blissymbols" ], "Bopo": [ "Bopomofo" ], "Brah": [ "Brahmi" ], "Brai": [ "Braille" ], "Bugi": [ "Buginese" ], "Buhd": [ "Buhid" ], "Cakm": [ "Chakma" ], "Cans": [ "Unified Canadian Aboriginal Syllabics" ], "Cari": [ "Carian" ], "Cham": [ "Cham" ], "Cher": [ "Cherokee" ], "Cirt": [ "Cirth" ], "Copt": [ "Coptic" ], "Cprt": [ "Cypriot" ], "Cyrl": [ "Cyrillic" ], "Cyrs": [ "Cyrillic (Old Church Slavonic variant)" ], "Deva": [ "Devanagari", "Nagari" ], "Dsrt": [ "Deseret", "Mormon" ], "Dupl": [ "Duployan shorthand", "Duployan stenography" ], "Egyd": [ "Egyptian demotic" ], "Egyh": [ "Egyptian hieratic" ], "Egyp": [ "Egyptian hieroglyphs" ], "Elba": [ "Elbasan" ], "Ethi": [ "Ethiopic", "Geʻez", "Ge'ez" ], "Geok": [ "Khutsuri (Asomtavruli and Nuskhuri)" ], "Geor": [ "Georgian (Mkhedruli)" ], "Glag": [ "Glagolitic" ], "Goth": [ "Gothic" ], "Gran": [ "Grantha" ], "Grek": [ "Greek" ], "Gujr": [ "Gujarati" ], "Guru": [ "Gurmukhi" ], "Hang": [ "Hangul", "Hangŭl", "Hangeul" ], "Hani": [ "Han", "Hanzi", "Kanji", "Hanja" ], "Hano": [ "Hanunoo", "Hanunóo" ], "Hans": [ "Han (Simplified variant)" ], "Hant": [ "Han (Traditional variant)" ], "Hatr": [ "Hatran" ], "Hebr": [ "Hebrew" ], "Hira": [ "Hiragana" ], "Hluw": [ "Anatolian Hieroglyphs", "Luwian Hieroglyphs", "Hittite Hieroglyphs" ], "Hmng": [ "Pahawh Hmong" ], "Hrkt": [ "Japanese syllabaries (alias for Hiragana + Katakana)" ], "Hung": [ "Old Hungarian", "Hungarian Runic" ], "Inds": [ "Indus", "Harappan" ], "Ital": [ "Old Italic (Etruscan, Oscan, etc.)" ], "Java": [ "Javanese" ], "Jpan": [ "Japanese (alias for Han + Hiragana + Katakana)" ], "Jurc": [ "Jurchen" ], "Kali": [ "Kayah Li" ], "Kana": [ "Katakana" ], "Khar": [ "Kharoshthi" ], "Khmr": [ "Khmer" ], "Khoj": [ "Khojki" ], "Kitl": [ "Khitan large script" ], "Kits": [ "Khitan small script" ], "Knda": [ "Kannada" ], "Kore": [ "Korean (alias for Hangul + Han)" ], "Kpel": [ "Kpelle" ], "Kthi": [ "Kaithi" ], "Lana": [ "Tai Tham", "Lanna" ], "Laoo": [ "Lao" ], "Latf": [ "Latin (Fraktur variant)" ], "Latg": [ "Latin (Gaelic variant)" ], "Latn": [ "Latin" ], "Lepc": [ "Lepcha", "Róng" ], "Limb": [ "Limbu" ], "Lina": [ "Linear A" ], "Linb": [ "Linear B" ], "Lisu": [ "Lisu", "Fraser" ], "Loma": [ "Loma" ], "Lyci": [ "Lycian" ], "Lydi": [ "Lydian" ], "Mahj": [ "Mahajani" ], "Mand": [ "Mandaic", "Mandaean" ], "Mani": [ "Manichaean" ], "Marc": [ "Marchen" ], "Maya": [ "Mayan hieroglyphs" ], "Mend": [ "Mende Kikakui" ], "Merc": [ "Meroitic Cursive" ], "Mero": [ "Meroitic Hieroglyphs" ], "Mlym": [ "Malayalam" ], "Modi": [ "Modi", "Moḍī" ], "Mong": [ "Mongolian" ], "Moon": [ "Moon", "Moon code", "Moon script", "Moon type" ], "Mroo": [ "Mro", "Mru" ], "Mtei": [ "Meitei Mayek", "Meithei", "Meetei" ], "Mult": [ "Multani" ], "Mymr": [ "Myanmar", "Burmese" ], "Narb": [ "Old North Arabian", "Ancient North Arabian" ], "Nbat": [ "Nabataean" ], "Nkgb": [ "Nakhi Geba", "'Na-'Khi ²Ggŏ-¹baw", "Naxi Geba" ], "Nkoo": [ "N’Ko", "N'Ko" ], "Nshu": [ "Nüshu" ], "Ogam": [ "Ogham" ], "Olck": [ "Ol Chiki", "Ol Cemet'", "Ol", "Santali" ], "Orkh": [ "Old Turkic", "Orkhon Runic" ], "Orya": [ "Oriya" ], "Osge": [ "Osage" ], "Osma": [ "Osmanya" ], "Palm": [ "Palmyrene" ], "Pauc": [ "Pau Cin Hau" ], "Perm": [ "Old Permic" ], "Phag": [ "Phags-pa" ], "Phli": [ "Inscriptional Pahlavi" ], "Phlp": [ "Psalter Pahlavi" ], "Phlv": [ "Book Pahlavi" ], "Phnx": [ "Phoenician" ], "Plrd": [ "Miao", "Pollard" ], "Prti": [ "Inscriptional Parthian" ], "Qaaa..Qabx": [ "Private use" ], "Rjng": [ "Rejang", "Redjang", "Kaganga" ], "Roro": [ "Rongorongo" ], "Runr": [ "Runic" ], "Samr": [ "Samaritan" ], "Sara": [ "Sarati" ], "Sarb": [ "Old South Arabian" ], "Saur": [ "Saurashtra" ], "Sgnw": [ "SignWriting" ], "Shaw": [ "Shavian", "Shaw" ], "Shrd": [ "Sharada", "Śāradā" ], "Sidd": [ "Siddham", "Siddhaṃ", "Siddhamātṛkā" ], "Sind": [ "Khudawadi", "Sindhi" ], "Sinh": [ "Sinhala" ], "Sora": [ "Sora Sompeng" ], "Sund": [ "Sundanese" ], "Sylo": [ "Syloti Nagri" ], "Syrc": [ "Syriac" ], "Syre": [ "Syriac (Estrangelo variant)" ], "Syrj": [ "Syriac (Western variant)" ], "Syrn": [ "Syriac (Eastern variant)" ], "Tagb": [ "Tagbanwa" ], "Takr": [ "Takri", "Ṭākrī", "Ṭāṅkrī" ], "Tale": [ "Tai Le" ], "Talu": [ "New Tai Lue" ], "Taml": [ "Tamil" ], "Tang": [ "Tangut" ], "Tavt": [ "Tai Viet" ], "Telu": [ "Telugu" ], "Teng": [ "Tengwar" ], "Tfng": [ "Tifinagh", "Berber" ], "Tglg": [ "Tagalog", "Baybayin", "Alibata" ], "Thaa": [ "Thaana" ], "Thai": [ "Thai" ], "Tibt": [ "Tibetan" ], "Tirh": [ "Tirhuta" ], "Ugar": [ "Ugaritic" ], "Vaii": [ "Vai" ], "Visp": [ "Visible Speech" ], "Wara": [ "Warang Citi", "Varang Kshiti" ], "Wole": [ "Woleai" ], "Xpeo": [ "Old Persian" ], "Xsux": [ "Sumero-Akkadian cuneiform" ], "Yiii": [ "Yi" ], "Zinh": [ "Code for inherited script" ], "Zmth": [ "Mathematical notation" ], "Zsym": [ "Symbols" ], "Zxxx": [ "Code for unwritten documents" ], "Zyyy": [ "Code for undetermined script" ], "Zzzz": [ "Code for uncoded script" ] };
mit
Autodrop3d/autodrop3dServer
public/js/scaffold-interface-js/social.js
425
window.twttr = (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], t = window.twttr || {}; if (d.getElementById(id)) return t; js = d.createElement(s); js.id = id; js.src = "https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); t._e = []; t.ready = function(f) { t._e.push(f); }; return t; }(document, "script", "twitter-wjs"));
mit
stof/dbal
lib/Doctrine/DBAL/Event/Listeners/SQLSessionInit.php
1959
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\DBAL\Event\Listeners; use Doctrine\DBAL\Event\ConnectionEventArgs; use Doctrine\DBAL\Events; use Doctrine\Common\EventSubscriber; /** * Session init listener for executing a single SQL statement right after a connection is opened. * * @link www.doctrine-project.org * @since 2.2 * @author Benjamin Eberlei <kontakt@beberlei.de> */ class SQLSessionInit implements EventSubscriber { /** * @var string */ protected $sql; /** * @param string $sql */ public function __construct($sql) { $this->sql = $sql; } /** * @param \Doctrine\DBAL\Event\ConnectionEventArgs $args * * @return void */ public function postConnect(ConnectionEventArgs $args) { $conn = $args->getConnection(); $conn->exec($this->sql); } /** * {@inheritdoc} */ public function getSubscribedEvents() { return [Events::postConnect]; } }
mit
ybarghane/AnnuaireResteaux
web/bundles/sonataadmin/vendor/jqueryui/ui/minified/i18n/jquery.ui.datepicker-tj.min.js
995
/*! jQuery UI - v1.10.4 - 2014-02-16 * http://jqueryui.com * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.tj={closeText:"Идома",prevText:"&#x3c;Қафо",nextText:"Пеш&#x3e;",currentText:"Имрӯз",monthNames:["Январ","Феврал","Март","Апрел","Май","Июн","Июл","Август","Сентябр","Октябр","Ноябр","Декабр"],monthNamesShort:["Янв","Фев","Мар","Апр","Май","Июн","Июл","Авг","Сен","Окт","Ноя","Дек"],dayNames:["якшанбе","душанбе","сешанбе","чоршанбе","панҷшанбе","ҷумъа","шанбе"],dayNamesShort:["якш","душ","сеш","чор","пан","ҷум","шан"],dayNamesMin:["Як","Дш","Сш","Чш","Пш","Ҷм","Шн"],weekHeader:"Хф",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.tj)});
mit
Admin-Kaf/Tinyboard
templates/themes/recent/theme.php
4518
<?php require 'info.php'; function recentposts_build($action, $settings, $board) { // Possible values for $action: // - all (rebuild everything, initialization) // - news (news has been updated) // - boards (board list changed) // - post (a post has been made) // - post-thread (a thread has been made) $b = new RecentPosts(); $b->build($action, $settings); } // Wrap functions in a class so they don't interfere with normal Tinyboard operations class RecentPosts { public function build($action, $settings) { global $config, $_theme; if ($action == 'all') { copy('templates/themes/recent/' . $settings['basecss'], $config['dir']['home'] . $settings['css']); } $this->excluded = explode(' ', $settings['exclude']); if ($action == 'all' || $action == 'post' || $action == 'post-thread' || $action == 'post-delete') file_write($config['dir']['home'] . $settings['html'], $this->homepage($settings)); } // Build news page public function homepage($settings) { global $config, $board; $recent_images = Array(); $recent_posts = Array(); $stats = Array(); $boards = listBoards(); $query = ''; foreach ($boards as &$_board) { if (in_array($_board['uri'], $this->excluded)) continue; $query .= sprintf("SELECT *, '%s' AS `board` FROM ``posts_%s`` WHERE `file` IS NOT NULL AND `file` != 'deleted' AND `thumb` != 'spoiler' UNION ALL ", $_board['uri'], $_board['uri']); } $query = preg_replace('/UNION ALL $/', 'ORDER BY `time` DESC LIMIT ' . (int)$settings['limit_images'], $query); $query = query($query) or error(db_error()); while ($post = $query->fetch(PDO::FETCH_ASSOC)) { openBoard($post['board']); // board settings won't be available in the template file, so generate links now $post['link'] = $config['root'] . $board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], ($post['thread'] ? $post['thread'] : $post['id'])) . '#' . $post['id']; $post['src'] = $config['uri_thumb'] . $post['thumb']; $recent_images[] = $post; } $query = ''; foreach ($boards as &$_board) { if (in_array($_board['uri'], $this->excluded)) continue; $query .= sprintf("SELECT *, '%s' AS `board` FROM ``posts_%s`` UNION ALL ", $_board['uri'], $_board['uri']); } $query = preg_replace('/UNION ALL $/', 'ORDER BY `time` DESC LIMIT ' . (int)$settings['limit_posts'], $query); $query = query($query) or error(db_error()); while ($post = $query->fetch(PDO::FETCH_ASSOC)) { openBoard($post['board']); $post['link'] = $config['root'] . $board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], ($post['thread'] ? $post['thread'] : $post['id'])) . '#' . $post['id']; $post['snippet'] = pm_snippet($post['body'], 30); $post['board_name'] = $board['name']; $recent_posts[] = $post; } // Total posts $query = 'SELECT SUM(`top`) FROM ('; foreach ($boards as &$_board) { if (in_array($_board['uri'], $this->excluded)) continue; $query .= sprintf("SELECT MAX(`id`) AS `top` FROM ``posts_%s`` UNION ALL ", $_board['uri']); } $query = preg_replace('/UNION ALL $/', ') AS `posts_all`', $query); $query = query($query) or error(db_error()); $stats['total_posts'] = number_format($query->fetchColumn()); // Unique IPs $query = 'SELECT COUNT(DISTINCT(`ip`)) FROM ('; foreach ($boards as &$_board) { if (in_array($_board['uri'], $this->excluded)) continue; $query .= sprintf("SELECT `ip` FROM ``posts_%s`` UNION ALL ", $_board['uri']); } $query = preg_replace('/UNION ALL $/', ') AS `posts_all`', $query); $query = query($query) or error(db_error()); $stats['unique_posters'] = number_format($query->fetchColumn()); // Active content $query = 'SELECT SUM(`filesize`) FROM ('; foreach ($boards as &$_board) { if (in_array($_board['uri'], $this->excluded)) continue; $query .= sprintf("SELECT `filesize` FROM ``posts_%s`` UNION ALL ", $_board['uri']); } $query = preg_replace('/UNION ALL $/', ') AS `posts_all`', $query); $query = query($query) or error(db_error()); $stats['active_content'] = $query->fetchColumn(); return Element('themes/recent/recent.html', Array( 'settings' => $settings, 'config' => $config, 'boardlist' => createBoardlist(), 'recent_images' => $recent_images, 'recent_posts' => $recent_posts, 'stats' => $stats )); } }; ?>
mit
konopacki/seattleusedbikes-site
concrete/core/controllers/single_pages/dashboard/system/backup_restore/update.php
4901
<?php defined('C5_EXECUTE') or die("Access Denied."); Loader::library('update'); Loader::library('archive'); class UpdateArchive extends Archive { public function __construct() { parent::__construct(); $this->targetDirectory = DIR_APP_UPDATES; } public function install($file) { parent::install($file, true); } } if (!ini_get('safe_mode')) { @set_time_limit(0); ini_set('max_execution_time', 0); } class Concrete5_Controller_Dashboard_System_BackupRestore_Update extends DashboardBaseController { function view() { $upd = new Update(); $updates = $upd->getLocalAvailableUpdates(); $remote = $upd->getApplicationUpdateInformation(); $this->set('updates', $updates); if (MULTI_SITE == 0) { $this->set('showDownloadBox', true); } else { $this->set('showDownloadBox', false); } if (is_object($remote) && version_compare($remote->version, APP_VERSION, '>')) { // loop through local updates $downloadableUpgradeAvailable = true; foreach($updates as $upd) { if ($upd->getUpdateVersion() == $remote->version) { // we have a LOCAL version ready to install that is the same, so we abort $downloadableUpgradeAvailable = false; $this->set('showDownloadBox', false); break; } } $this->set('downloadableUpgradeAvailable', $downloadableUpgradeAvailable); $this->set('update', $remote); } else { $this->set('downloadableUpgradeAvailable', false); } } public function check_for_updates() { Config::clear('APP_VERSION_LATEST', false); Update::getLatestAvailableVersionNumber(); $this->redirect('/dashboard/system/backup_restore/update'); } public function on_start() { $this->error = Loader::helper('validation/error'); $this->secCheck(); } public function on_before_render() { $this->set('error', $this->error); } public function download_update() { if (MULTI_SITE == 1) { return false; } $vt = Loader::helper('validation/token'); if (!$vt->validate('download_update')) { $this->error->add($vt->getErrorMessage()); } if (!is_dir(DIR_APP_UPDATES)) { $this->error->add(t('The directory %s does not exist.', DIR_APP_UPDATES)); } else if (!is_writable(DIR_APP_UPDATES)) { $this->error->add(t('The directory %s must be writable by the web server.', DIR_APP_UPDATES)); } if (!$this->error->has()) { $remote = Update::getApplicationUpdateInformation(); if (is_object($remote)) { // try to download Loader::library("marketplace"); $r = Marketplace::downloadRemoteFile($remote->url); if (empty($r) || $r == Package::E_PACKAGE_DOWNLOAD) { $response = array(Package::E_PACKAGE_DOWNLOAD); } else if ($r == Package::E_PACKAGE_SAVE) { $response = array($r); } if (isset($response)) { $errors = Package::mapError($response); foreach($errors as $e) { $this->error->add($e); } } if (!$this->error->has()) { // the file exists in the right spot Loader::library('archive'); $ar = new UpdateArchive(); try { $ar->install($r); } catch(Exception $e) { $this->error->add($e->getMessage()); } } } else { $this->error->add(t('Unable to retrieve software from update server.')); } } $this->view(); } public function secCheck() { $fh = Loader::helper('file'); $updates = $fh->getDirectoryContents(DIR_APP_UPDATES); foreach($updates as $upd) { if (is_dir(DIR_APP_UPDATES . '/' . $upd) && is_writable(DIR_APP_UPDATES . '/' . $upd)) { if (file_exists(DIR_APP_UPDATES . '/' . $upd . '/' . DISPATCHER_FILENAME) && is_writable(DIR_APP_UPDATES . '/' . $upd . '/' . DISPATCHER_FILENAME)) { unlink(DIR_APP_UPDATES . '/' . $upd . '/' . DISPATCHER_FILENAME); } if (!file_exists(DIR_APP_UPDATES . '/' . $upd . '/index.html')) { touch(DIR_APP_UPDATES . '/' . $upd . '/index.html'); } } } } public function do_update() { $updateVersion = $this->post('updateVersion'); if (!$updateVersion) { $this->error->add(t('Invalid version')); } else { $upd = ApplicationUpdate::getByVersionNumber($updateVersion); } if (!is_object($upd)) { $this->error->add(t('Invalid version')); } else { if (version_compare($upd->getUpdateVersion(), APP_VERSION, '<=')) { $this->error->add(t('You may only apply updates with a greater version number than the version you are currently running.')); } } if (!$this->error->has()) { $resp = $upd->apply(); if ($resp !== true) { switch($resp) { case ApplicationUpdate::E_UPDATE_WRITE_CONFIG: $this->error->add(t('Unable to write to config/site.php. You must make config/site.php writable in order to upgrade in this manner.')); break; } } else { header('Location: ' . BASE_URL . REL_DIR_FILES_TOOLS_REQUIRED . '/upgrade?source=dashboard_update'); exit; } } $this->view(); } }
mit
okazia/XChange
xchange-btcchina/src/main/java/com/xeiam/xchange/btcchina/BTCChina.java
14863
package com.xeiam.xchange.btcchina; import java.io.IOException; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import si.mazi.rescu.ParamsDigest; import si.mazi.rescu.SynchronizedValueFactory; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetAccountInfoRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetDepositsRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetWithdrawalRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetWithdrawalsRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaRequestWithdrawalRequest; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetAccountInfoResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetDepositsResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetWithdrawalResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetWithdrawalsResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaRequestWithdrawalResponse; import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaDepth; import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTicker; import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTrade; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetIcebergOrdersRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetMarketDepthRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrdersRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetStopOrdersRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaTransactionsRequest; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaBooleanResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetIcebergOrderResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetIcebergOrdersResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetMarketDepthResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrderResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrdersResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetStopOrderResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetStopOrdersResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaIntegerResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaTransactionsResponse; @Path("/") @Produces(MediaType.APPLICATION_JSON) public interface BTCChina { @GET @Path("data/ticker") BTCChinaTicker getTicker(@QueryParam("market") String market) throws IOException; /** * Returns all the open orders from the specified {@code market}. * * @param market the market could be {@code btccny}, {@code ltccny}, {@code ltcbtc}. * @return the order book. * @throws IOException indicates I/O exception. * @see #getOrderBook(String, int) */ @GET @Path("data/orderbook") BTCChinaDepth getFullDepth(@QueryParam("market") String market) throws IOException; /** * Order book default contains all open ask and bid orders. Set 'limit' parameter to specify the number of records fetched per request. * <p> * Bid orders are {@code limit} orders with highest price while ask with lowest, and orders are descendingly sorted by price. * </p> * * @param market market could be {@code btccny}, {@code ltccny}, {@code ltcbtc}. * @param limit number of records fetched per request. * @return the order book. * @throws IOException indicates I/O exception. * @see #getFullDepth(String) */ @GET @Path("data/orderbook") BTCChinaDepth getOrderBook(@QueryParam("market") String market, @QueryParam("limit") int limit) throws IOException; /** * Returns last 100 trade records. */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market) throws IOException; /** * Returns last {@code limit} trade records. * * @param market * @param limit the range of limit is [0,5000]. * @throws IOException */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("limit") int limit) throws IOException; /** * Returns 100 trade records starting from id {@code since}. * * @param market * @param since the starting trade ID(exclusive). * @throws IOException */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since) throws IOException; /** * Returns {@code limit} trades starting from id {@code since} * * @param market * @param since the starting trade ID(exclusive). * @param limit the range of limit is [0,5000]. * @throws IOException */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since, @QueryParam("limit") int limit) throws IOException; @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since, @QueryParam("limit") int limit, @QueryParam("sincetype") @DefaultValue("id") String sincetype) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetAccountInfoResponse getAccountInfo(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetAccountInfoRequest getAccountInfoRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetDepositsResponse getDeposits(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetDepositsRequest getDepositsRequest) throws IOException; /** * Get the complete market depth. Returns all open bid and ask orders. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetMarketDepthResponse getMarketDepth(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetMarketDepthRequest request) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetWithdrawalResponse getWithdrawal(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetWithdrawalRequest request) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetWithdrawalsResponse getWithdrawals(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetWithdrawalsRequest request) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaRequestWithdrawalResponse requestWithdrawal(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaRequestWithdrawalRequest requestWithdrawalRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetOrderResponse getOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetOrderRequest getOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetOrdersResponse getOrders(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetOrdersRequest getOrdersRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaBooleanResponse cancelOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelOrderRequest cancelOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse buyOrder2(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyOrderRequest buyOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse sellOrder2(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellOrderRequest sellOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaTransactionsResponse getTransactions(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaTransactionsRequest transactionRequest) throws IOException; /** * Place a buy iceberg order. This method will return an iceberg order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse buyIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyIcebergOrderRequest request) throws IOException; /** * Place a sell iceberg order. This method will return an iceberg order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse sellIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellIcebergOrderRequest request) throws IOException; /** * Get an iceberg order, including the orders placed. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetIcebergOrderResponse getIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetIcebergOrderRequest request) throws IOException; /** * Get iceberg orders, including the orders placed inside each iceberg order. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetIcebergOrdersResponse getIcebergOrders(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetIcebergOrdersRequest request) throws IOException; /** * Cancels an open iceberg order. Fails if iceberg order is already cancelled or closed. The related order with the iceberg order will also be * cancelled. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaBooleanResponse cancelIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelIcebergOrderRequest request) throws IOException; /** * Place a buy stop order. This method will return a stop order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse buyStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyStopOrderRequest request) throws IOException; /** * Place a sell stop order. This method will return an stop order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse sellStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellStopOrderRequest request) throws IOException; /** * Get a stop order. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetStopOrderResponse getStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetStopOrderRequest request) throws IOException; /** * Get stop orders. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetStopOrdersResponse getStopOrders(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetStopOrdersRequest request) throws IOException; /** * Cancels an open stop order. Fails if stop order is already cancelled or closed. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaBooleanResponse cancelStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelStopOrderRequest request) throws IOException; }
mit
magnusnordlander/symfony-micro
web/app.php
749
<?php use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Use APC for autoloading to improve performance. // Change 'sf2' to a unique prefix in order to prevent cache key conflicts // with other applications also using APC. /* $loader = new ApcClassLoader('sf2', $loader); $loader->register(true); */ require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
mit
oxaudo/force
src/v2/__generated__/redirects_order.graphql.ts
5491
/* tslint:disable */ import { ReaderFragment } from "relay-runtime"; export type CommerceOrderModeEnum = "BUY" | "OFFER" | "%future added value"; export type CommerceOrderParticipantEnum = "BUYER" | "SELLER" | "%future added value"; export type CommerceOrderStateEnum = "ABANDONED" | "APPROVED" | "CANCELED" | "FULFILLED" | "PENDING" | "REFUNDED" | "SUBMITTED" | "%future added value"; import { FragmentRefs } from "relay-runtime"; export type redirects_order = { readonly internalID: string; readonly mode: CommerceOrderModeEnum | null; readonly state: CommerceOrderStateEnum; readonly lastTransactionFailed: boolean | null; readonly requestedFulfillment: { readonly __typename: string; } | null; readonly lineItems: { readonly edges: ReadonlyArray<{ readonly node: { readonly artwork: { readonly slug: string; } | null; } | null; } | null> | null; } | null; readonly creditCard: { readonly internalID: string; } | null; readonly myLastOffer?: { readonly internalID: string; readonly createdAt: string; } | null; readonly lastOffer?: { readonly internalID: string; readonly createdAt: string; } | null; readonly awaitingResponseFrom?: CommerceOrderParticipantEnum | null; readonly " $refType": "redirects_order"; }; export type redirects_order$data = redirects_order; export type redirects_order$key = { readonly " $data"?: redirects_order$data; readonly " $fragmentRefs": FragmentRefs<"redirects_order">; }; const node: ReaderFragment = (function(){ var v0 = { "kind": "ScalarField", "alias": null, "name": "internalID", "args": null, "storageKey": null }, v1 = [ (v0/*: any*/), { "kind": "ScalarField", "alias": null, "name": "createdAt", "args": null, "storageKey": null } ]; return { "kind": "Fragment", "name": "redirects_order", "type": "CommerceOrder", "metadata": null, "argumentDefinitions": [], "selections": [ (v0/*: any*/), { "kind": "ScalarField", "alias": null, "name": "mode", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "state", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "lastTransactionFailed", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "requestedFulfillment", "storageKey": null, "args": null, "concreteType": null, "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "__typename", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": null, "name": "lineItems", "storageKey": null, "args": null, "concreteType": "CommerceLineItemConnection", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "edges", "storageKey": null, "args": null, "concreteType": "CommerceLineItemEdge", "plural": true, "selections": [ { "kind": "LinkedField", "alias": null, "name": "node", "storageKey": null, "args": null, "concreteType": "CommerceLineItem", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "artwork", "storageKey": null, "args": null, "concreteType": "Artwork", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "slug", "args": null, "storageKey": null } ] } ] } ] } ] }, { "kind": "LinkedField", "alias": null, "name": "creditCard", "storageKey": null, "args": null, "concreteType": "CreditCard", "plural": false, "selections": [ (v0/*: any*/) ] }, { "kind": "InlineFragment", "type": "CommerceOfferOrder", "selections": [ { "kind": "LinkedField", "alias": null, "name": "myLastOffer", "storageKey": null, "args": null, "concreteType": "CommerceOffer", "plural": false, "selections": (v1/*: any*/) }, { "kind": "LinkedField", "alias": null, "name": "lastOffer", "storageKey": null, "args": null, "concreteType": "CommerceOffer", "plural": false, "selections": (v1/*: any*/) }, { "kind": "ScalarField", "alias": null, "name": "awaitingResponseFrom", "args": null, "storageKey": null } ] } ] }; })(); (node as any).hash = '45b06150d1e7184360e9c945ed0660bf'; export default node;
mit
shelsonjava/datawrapper
vendor/propel/generator/lib/task/PropelSQLDiffTask.php
6178
<?php /** * This file is part of the Propel package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT License */ require_once dirname(__FILE__) . '/AbstractPropelDataModelTask.php'; require_once dirname(__FILE__) . '/../builder/om/ClassTools.php'; require_once dirname(__FILE__) . '/../builder/om/OMBuilder.php'; require_once dirname(__FILE__) . '/../model/diff/PropelDatabaseComparator.php'; require_once dirname(__FILE__) . '/../util/PropelMigrationManager.php'; /** * This Task creates the OM classes based on the XML schema file. * * @author Hans Lellelid <hans@xmpl.org> * @package propel.generator.task */ class PropelSQLDiffTask extends AbstractPropelDataModelTask { protected $databaseName; protected $editorCmd; protected $isCaseInsensitive = false; /** * Sets the datasource name. * * This will be used as the <database name=""> value in the generated schema.xml * * @param string $v */ public function setDatabaseName($v) { $this->databaseName = $v; } /** * Gets the datasource name. * * @return string */ public function getDatabaseName() { return $this->databaseName; } /** * Setter for the editorCmd property * * @param string $editorCmd */ public function setEditorCmd($editorCmd) { $this->editorCmd = $editorCmd; } /** * Getter for the editorCmd property * * @return string */ public function getEditorCmd() { return $this->editorCmd; } /** * Defines whether the comparison is case insensitive * * @param boolean $isCaseInsensitive */ public function setCaseInsensitive($isCaseInsensitive) { $this->isCaseInsensitive = (boolean) $isCaseInsensitive; } /** * Checks whether the comparison is case insensitive * * @return boolean */ public function isCaseInsensitive() { return $this->isCaseInsensitive; } /** * Main method builds all the targets for a typical propel project. */ public function main() { // check to make sure task received all correct params $this->validate(); $generatorConfig = $this->getGeneratorConfig(); // loading model from database $this->log('Reading databases structure...'); $connections = $generatorConfig->getBuildConnections(); if (!$connections) { throw new Exception('You must define database connection settings in a buildtime-conf.xml file to use diff'); } $manager = new PropelMigrationManager(); $manager->setConnections($connections); $manager->setMigrationDir($this->getOutputDirectory()); $manager->setMigrationTable($this->getGeneratorConfig()->getBuildProperty('migrationTable')); if ($manager->hasPendingMigrations()) { throw new Exception('Uncommitted migrations have been found ; you should either execute or delete them before rerunning the \'diff\' task'); } $totalNbTables = 0; $ad = new AppData(); foreach ($connections as $name => $params) { $this->log(sprintf('Connecting to database "%s" using DSN "%s"', $name, $params['dsn']), Project::MSG_VERBOSE); $pdo = $generatorConfig->getBuildPDO($name); $database = new Database($name); $platform = $generatorConfig->getConfiguredPlatform($pdo); if (!$platform->supportsMigrations()) { $this->log(sprintf('Skipping database "%s" since vendor "%s" does not support migrations', $name, $platform->getDatabaseType())); continue; } $database->setPlatform($platform); $database->setDefaultIdMethod(IDMethod::NATIVE); $parser = $generatorConfig->getConfiguredSchemaParser($pdo); $nbTables = $parser->parse($database, $this); $ad->addDatabase($database); $totalNbTables += $nbTables; $this->log(sprintf('%d tables found in database "%s"', $nbTables, $name), Project::MSG_VERBOSE); } if ($totalNbTables) { $this->log(sprintf('%d tables found in all databases.', $totalNbTables)); } else { $this->log('No table found in all databases'); } // loading model from XML $this->packageObjectModel = true; $appDatasFromXml = $this->getDataModels(); $appDataFromXml = array_pop($appDatasFromXml); // comparing models $this->log('Comparing models...'); $migrationsUp = array(); $migrationsDown = array(); foreach ($ad->getDatabases() as $database) { $name = $database->getName(); $this->log(sprintf('Comparing database "%s"', $name), Project::MSG_VERBOSE); if (!$appDataFromXml->hasDatabase($name)) { // FIXME: tables present in database but not in XML continue; } $databaseDiff = PropelDatabaseComparator::computeDiff($database, $appDataFromXml->getDatabase($name), $this->isCaseInsensitive()); if (!$databaseDiff) { $this->log(sprintf('Same XML and database structures for datasource "%s" - no diff to generate', $name), Project::MSG_VERBOSE); continue; } $this->log(sprintf('Structure of database was modified in datasource "%s": %s', $name, $databaseDiff->getDescription())); $platform = $generatorConfig->getConfiguredPlatform(null, $name); $migrationsUp[$name] = $platform->getModifyDatabaseDDL($databaseDiff); $migrationsDown[$name] = $platform->getModifyDatabaseDDL($databaseDiff->getReverseDiff()); } if (!$migrationsUp) { $this->log('Same XML and database structures for all datasource - no diff to generate'); return; } $timestamp = time(); $migrationFileName = $manager->getMigrationFileName($timestamp); $migrationClassBody = $manager->getMigrationClassBody($migrationsUp, $migrationsDown, $timestamp); $_f = new PhingFile($this->getOutputDirectory(), $migrationFileName); file_put_contents($_f->getAbsolutePath(), $migrationClassBody); $this->log(sprintf('"%s" file successfully created in %s', $_f->getName(), $_f->getParent())); if ($editorCmd = $this->getEditorCmd()) { $this->log(sprintf('Using "%s" as text editor', $editorCmd)); shell_exec($editorCmd . ' ' . escapeshellarg($_f->getAbsolutePath())); } else { $this->log(' Please review the generated SQL statements, and add data migration code if necessary.'); $this->log(' Once the migration class is valid, call the "migrate" task to execute it.'); } } }
mit
TheNetStriker/openhab
bundles/binding/org.openhab.binding.maxcube/src/main/java/org/openhab/binding/maxcube/internal/message/Device.java
9525
/** * Copyright (c) 2010-2019 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.maxcube.internal.message; import java.util.Date; import java.util.List; import org.openhab.binding.maxcube.internal.Utils; import org.openhab.binding.maxcube.internal.message.Battery.Charge; import org.openhab.core.library.types.OpenClosedType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for devices provided by the MAX!Cube protocol. * * @author Andreas Heil (info@aheil.de) * @author Bernd Michael Helm (bernd.helm at helmundwalter.de) * @since 1.4.0 */ public abstract class Device { protected final static Logger logger = LoggerFactory.getLogger(Device.class); private final String serialNumber; private final String rfAddress; private final int roomId; private final Battery battery = new Battery(); private boolean initialized; private boolean answer; private Boolean error = null; private boolean errorUpdated; private boolean valid; private boolean DstSettingsActive; private boolean gatewayKnown; private boolean panelLocked; private boolean linkStatusError; public Device(Configuration c) { this.serialNumber = c.getSerialNumber(); this.rfAddress = c.getRFAddress(); this.roomId = c.getRoomId(); } public abstract DeviceType getType(); private static Device create(String rfAddress, List<Configuration> configurations) { Device returnValue = null; for (Configuration c : configurations) { if (c.getRFAddress().toUpperCase().equals(rfAddress.toUpperCase())) { switch (c.getDeviceType()) { case HeatingThermostatPlus: case HeatingThermostat: HeatingThermostat thermostat = new HeatingThermostat(c); thermostat.setType(c.getDeviceType()); return thermostat; case EcoSwitch: return new EcoSwitch(c); case ShutterContact: return new ShutterContact(c); case WallMountedThermostat: return new WallMountedThermostat(c); default: return new UnsupportedDevice(c); } } } return returnValue; } public static Device create(byte[] raw, List<Configuration> configurations) { if (raw.length == 0) { return null; } String rfAddress = Utils.toHex(raw[0] & 0xFF, raw[1] & 0xFF, raw[2] & 0xFF); // Based on the RF address and the corresponding configuration, // create the device based on the type specified in its configuration Device device = Device.create(rfAddress, configurations); if (device == null) { logger.warn("Can't create device from received message, returning NULL."); return null; } return Device.update(raw, configurations, device); } public static Device update(byte[] raw, List<Configuration> configurations, Device device) { String rfAddress = device.getRFAddress(); // byte 4 is skipped // multiple device information are encoded in those particular bytes boolean[] bits1 = Utils.getBits(Utils.fromByte(raw[4])); boolean[] bits2 = Utils.getBits(Utils.fromByte(raw[5])); device.setInitialized(bits1[1]); device.setAnswer(bits1[2]); device.setError(bits1[3]); device.setValid(bits1[4]); device.setDstSettingActive(bits2[3]); device.setGatewayKnown(bits2[4]); device.setPanelLocked(bits2[5]); device.setLinkStatusError(bits2[6]); device.battery().setCharge(bits2[7] ? Charge.LOW : Charge.OK); logger.trace("Device {} L Message length: {} content: {}", rfAddress, raw.length, Utils.getHex(raw)); // TODO move the device specific readings into the sub classes switch (device.getType()) { case WallMountedThermostat: case HeatingThermostat: case HeatingThermostatPlus: HeatingThermostat heatingThermostat = (HeatingThermostat) device; // "xxxx xx00 = automatic, xxxx xx01 = manual, xxxx xx10 = vacation, xxxx xx11 = boost": if (bits2[1] == false && bits2[0] == false) { heatingThermostat.setMode(ThermostatModeType.AUTOMATIC); } else if (bits2[1] == false && bits2[0] == true) { heatingThermostat.setMode(ThermostatModeType.MANUAL); } else if (bits2[1] == true && bits2[0] == false) { heatingThermostat.setMode(ThermostatModeType.VACATION); } else if (bits2[1] == true && bits2[0] == true) { heatingThermostat.setMode(ThermostatModeType.BOOST); } else { // TODO: handel malformed message } heatingThermostat.setValvePosition(raw[6] & 0xFF); heatingThermostat.setTemperatureSetpoint(raw[7] & 0x7F); // 9 2 858B Date until (05-09-2011) (see Encoding/Decoding // date/time) // B 1 2E Time until (23:00) (see Encoding/Decoding date/time) String hexDate = Utils.toHex(raw[8] & 0xFF, raw[9] & 0xFF); int dateValue = Utils.fromHex(hexDate); int timeValue = raw[10] & 0xFF; Date date = Utils.resolveDateTime(dateValue, timeValue); heatingThermostat.setDateSetpoint(date); int actualTemp = 0; if (device.getType() == DeviceType.WallMountedThermostat) { actualTemp = (raw[11] & 0xFF) + (raw[7] & 0x80) * 2; } else { if (heatingThermostat.getMode() != ThermostatModeType.VACATION && heatingThermostat.getMode() != ThermostatModeType.BOOST) { actualTemp = (raw[8] & 0xFF) * 256 + (raw[9] & 0xFF); } else { logger.debug("No temperature reading in {} mode", heatingThermostat.getMode()); } } if (actualTemp != 0) { logger.debug("Actual Temperature : {}", (double) actualTemp / 10); heatingThermostat.setTemperatureActual((double) actualTemp / 10); } break; case EcoSwitch: String eCoSwitchData = Utils.toHex(raw[3] & 0xFF, raw[4] & 0xFF, raw[5] & 0xFF); logger.trace("EcoSwitch Device {} status bytes : {}", rfAddress, eCoSwitchData); case ShutterContact: ShutterContact shutterContact = (ShutterContact) device; // xxxx xx10 = shutter open, xxxx xx00 = shutter closed if (bits2[1] == true && bits2[0] == false) { shutterContact.setShutterState(OpenClosedType.OPEN); logger.trace("Device {} status: Open", rfAddress); } else if (bits2[1] == false && bits2[0] == false) { shutterContact.setShutterState(OpenClosedType.CLOSED); logger.trace("Device {} status: Closed", rfAddress); } else { logger.trace("Device {} status switch status Unknown (true-true)", rfAddress); } break; default: logger.debug("Unhandled Device. DataBytes: " + Utils.getHex(raw)); break; } return device; } public Battery battery() { return battery; } public final String getRFAddress() { return this.rfAddress; } public final int getRoomId() { return roomId; } private void setLinkStatusError(boolean linkStatusError) { this.linkStatusError = linkStatusError; } private void setPanelLocked(boolean panelLocked) { this.panelLocked = panelLocked; } private void setGatewayKnown(boolean gatewayKnown) { this.gatewayKnown = gatewayKnown; } private void setDstSettingActive(boolean dstSettingsActive) { this.DstSettingsActive = dstSettingsActive; } private void setValid(boolean valid) { this.valid = valid; } protected void setError(boolean newError) { errorUpdated = (this.error == null) || (this.error != newError); this.error = newError; if (newError) { logger.warn("Connection error occurred between cube and device '{}'", this.toString()); } } public boolean isError() { return Boolean.TRUE.equals(error); } public boolean isErrorUpdated() { return errorUpdated; } public String getSerialNumber() { return serialNumber; } private void setInitialized(boolean initialized) { this.initialized = initialized; } private void setAnswer(boolean answer) { this.answer = answer; } @Override public String toString() { return rfAddress + " - " + serialNumber; } }
epl-1.0
PatrickSHYee/idecore
com.salesforce.ide.core/src/com/salesforce/ide/core/internal/components/letterhead/LetterheadComponentController.java
1338
/******************************************************************************* * Copyright (c) 2014 Salesforce.com, inc.. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Salesforce.com, inc. - initial API and implementation ******************************************************************************/ package com.salesforce.ide.core.internal.components.letterhead; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IProgressMonitor; import com.salesforce.ide.core.internal.components.ComponentController; import com.salesforce.ide.core.internal.components.ComponentModel; import com.salesforce.ide.core.project.ForceProjectException; public class LetterheadComponentController extends ComponentController { public LetterheadComponentController() throws ForceProjectException { super(new LetterheadModel()); } @Override protected void preSaveProcess(ComponentModel componentWizardModel, IProgressMonitor monitor) throws InterruptedException, InvocationTargetException { // TODO Auto-generated method stub } }
epl-1.0
echoes-tech/eclipse.jsdt.core
org.eclipse.wst.jsdt.core.tests.model/workspace/JavaSearchBugs/src/b163984/B.js
83
package b163984; public class B { public static void main(String[] args) {} }
epl-1.0
greenlion/mysql-server
storage/ndb/src/kernel/blocks/dbtux/DbtuxMaint.cpp
5745
/* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define DBTUX_MAINT_CPP #include "Dbtux.hpp" #define JAM_FILE_ID 369 /* * Maintain index. */ void Dbtux::execTUX_MAINT_REQ(Signal* signal) { jamEntry(); TuxMaintReq* const sig = (TuxMaintReq*)signal->getDataPtrSend(); // ignore requests from redo log IndexPtr indexPtr; c_indexPool.getPtr(indexPtr, sig->indexId); if (unlikely(! (indexPtr.p->m_state == Index::Online || indexPtr.p->m_state == Index::Building))) { jam(); #ifdef VM_TRACE if (debugFlags & DebugMaint) { TupLoc tupLoc(sig->pageId, sig->pageIndex); debugOut << "opInfo=" << hex << sig->opInfo; debugOut << " tableId=" << dec << sig->tableId; debugOut << " indexId=" << dec << sig->indexId; debugOut << " fragId=" << dec << sig->fragId; debugOut << " tupLoc=" << tupLoc; debugOut << " tupVersion=" << dec << sig->tupVersion; debugOut << " -- ignored at ISP=" << dec << c_internalStartPhase; debugOut << " TOS=" << dec << c_typeOfStart; debugOut << endl; } #endif sig->errorCode = 0; return; } TuxMaintReq reqCopy = *sig; TuxMaintReq* const req = &reqCopy; const Uint32 opCode = req->opInfo & 0xFF; // get the index ndbrequire(indexPtr.p->m_tableId == req->tableId); // get base fragment id and extra bits const Uint32 fragId = req->fragId; // get the fragment FragPtr fragPtr; findFrag(jamBuffer(), *indexPtr.p, fragId, fragPtr); ndbrequire(fragPtr.i != RNIL); Frag& frag = *fragPtr.p; // set up search entry TreeEnt ent; ent.m_tupLoc = TupLoc(req->pageId, req->pageIndex); ent.m_tupVersion = req->tupVersion; // set up and read search key KeyData searchKey(indexPtr.p->m_keySpec, false, 0); searchKey.set_buf(c_ctx.c_searchKey, MaxAttrDataSize << 2); readKeyAttrs(c_ctx, frag, ent, searchKey, indexPtr.p->m_numAttrs); if (unlikely(! indexPtr.p->m_storeNullKey) && searchKey.get_null_cnt() == indexPtr.p->m_numAttrs) { jam(); return; } #ifdef VM_TRACE if (debugFlags & DebugMaint) { const Uint32 opFlag = req->opInfo >> 8; debugOut << "opCode=" << dec << opCode; debugOut << " opFlag=" << dec << opFlag; debugOut << " tableId=" << dec << req->tableId; debugOut << " indexId=" << dec << req->indexId; debugOut << " fragId=" << dec << req->fragId; debugOut << " entry=" << ent; debugOut << endl; } #endif // do the operation req->errorCode = 0; TreePos treePos; bool ok; switch (opCode) { case TuxMaintReq::OpAdd: jam(); ok = searchToAdd(c_ctx, frag, searchKey, ent, treePos); #ifdef VM_TRACE if (debugFlags & DebugMaint) { debugOut << treePos << (! ok ? " - error" : "") << endl; } #endif if (! ok) { jam(); // there is no "Building" state so this will have to do if (indexPtr.p->m_state == Index::Online) { jam(); req->errorCode = TuxMaintReq::SearchError; } break; } /* * At most one new node is inserted in the operation. Pre-allocate * it so that the operation cannot fail. */ if (frag.m_freeLoc == NullTupLoc) { jam(); NodeHandle node(frag); req->errorCode = allocNode(c_ctx, node); if (req->errorCode != 0) { jam(); break; } frag.m_freeLoc = node.m_loc; ndbrequire(frag.m_freeLoc != NullTupLoc); } treeAdd(c_ctx, frag, treePos, ent); frag.m_entryCount++; frag.m_entryBytes += searchKey.get_data_len(); frag.m_entryOps++; break; case TuxMaintReq::OpRemove: jam(); ok = searchToRemove(c_ctx, frag, searchKey, ent, treePos); #ifdef VM_TRACE if (debugFlags & DebugMaint) { debugOut << treePos << (! ok ? " - error" : "") << endl; } #endif if (! ok) { jam(); // there is no "Building" state so this will have to do if (indexPtr.p->m_state == Index::Online) { jam(); req->errorCode = TuxMaintReq::SearchError; } break; } treeRemove(frag, treePos); ndbrequire(frag.m_entryCount != 0); frag.m_entryCount--; frag.m_entryBytes -= searchKey.get_data_len(); frag.m_entryOps++; break; default: ndbrequire(false); break; } #ifdef VM_TRACE if (debugFlags & DebugTree) { printTree(signal, frag, debugOut); } #endif // copy back *sig = *req; //ndbrequire(c_keyAttrs[0] == c_keyAttrs[1]); //ndbrequire(c_sqlCmp[0] == c_sqlCmp[1]); //ndbrequire(c_searchKey[0] == c_searchKey[1]); //ndbrequire(c_entryKey[0] == c_entryKey[1]); //ndbrequire(c_dataBuffer[0] == c_dataBuffer[1]); }
gpl-2.0
BetterBetterBetter/B3App
modules/mod_easysocial_register/helper.php
2091
<?php /** * @package EasySocial * @copyright Copyright (C) 2010 - 2014 Stack Ideas Sdn Bhd. All rights reserved. * @license GNU/GPL, see LICENSE.php * EasySocial is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ defined( '_JEXEC' ) or die( 'Unauthorized Access' ); class EasySocialModRegisterHelper { /** * Returns the login url * * @since 1.0 * @access public * @param string * @return */ public static function getReturnURL( &$params ) { $app = JFactory::getApplication(); $router = $app->getRouter(); $url = null; $itemid = $params->get( 'return' ); if( $itemid ) { $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select($db->quoteName('link')) ->from($db->quoteName('#__menu')) ->where($db->quoteName('published') . '=1') ->where($db->quoteName('id') . '=' . $db->quote($itemid)); $db->setQuery($query); if ($link = $db->loadResult()) { if ($router->getMode() == JROUTER_MODE_SEF) { $url = 'index.php?Itemid='.$itemid; } else { $url = $link.'&Itemid='.$itemid; } } } if (!$url) { // Stay on the same page $uri = clone JUri::getInstance(); $vars = $router->parse($uri); unset($vars['lang']); if ($router->getMode() == JROUTER_MODE_SEF) { if (isset($vars['Itemid'])) { $itemid = $vars['Itemid']; $menu = $app->getMenu(); $item = $menu->getItem($itemid); unset($vars['Itemid']); if (isset($item) && $vars == $item->query) { $url = 'index.php?Itemid='.$itemid; } else { $url = 'index.php?'.JUri::buildQuery($vars).'&Itemid='.$itemid; } } else { $url = 'index.php?'.JUri::buildQuery($vars); } } else { $url = 'index.php?'.JUri::buildQuery($vars); } } return base64_encode($url); } }
gpl-2.0
altrobot/love_spreading
vendors/social/javascripts/socialShare.js
6374
/* Plugin Name: socialShare Version: 1.0 Plugin URI: https://github.com/tolgaergin/social Description: To share any page with 46 icons Author: Tolga Ergin Author URI: http://tolgaergin.com Designer: Gökhun Güneyhan Designer URI: http://gokhunguneyhan.com */ /* PLUGIN USAGE */ /* $('#clickable').socialShare({ social: 'blogger,delicious,digg,facebook,friendfeed,google,linkedin,myspace,pinterest,reddit,stumbleupon,tumblr,twitter,windows,yahoo' }); */ (function($){ $.fn.extend({ socialShare: function(options) { var defaults = { social: '', title: document.title, shareUrl: window.location.href, description: $('meta[name="description"]').attr('content'), animation: 'launchpad', // launchpad, launchpadReverse, slideTop, slideRight, slideBottom, slideLeft, chain chainAnimationSpeed: 100, whenSelect: false, selectContainer: 'body', blur: false }; var options = $.extend(true,defaults, options); var beforeDivs = '<div class="arthref arthrefSocialShare"><div class="overlay '+options.animation+'"><div class="icon-container"><div class="centered"><ul>'; var afterDivs = '</ul></div></div></div></div>'; return this.each(function() { var o = options; var obj = $(this); if(o.whenSelect) { $(o.selectContainer).mouseup(function(e) { var selection = getSelected(); if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) { options.title = selection; } }); } obj.click(function() { createContainer(); if(o.blur) { $('.arthrefSocialShare').find('.overlay').addClass('opaque'); $('body').children().not('.arthref, script').addClass('blurred'); } $('.arthrefSocialShare').find('.overlay').css('display','block'); setTimeout(function(){ $('.arthrefSocialShare').find('.overlay').addClass('active'); $('.arthrefSocialShare').find('ul').addClass('active'); if(o.animation=='chain') chainAnimation($('.arthrefSocialShare').find('li'),o.chainAnimationSpeed,'1'); },0); }); $( document ).on( "click touchstart", ".arthrefSocialShare .overlay", function( e ) { destroyContainer(o); }); $( document ).on( "keydown", function( e ) { if( e.keyCode == 27 ) destroyContainer(o); }); $( document ).on( "click touchstart", ".arthrefSocialShare li", function( e ) { e.stopPropagation(); }); }); function getSelected() { if(window.getSelection) { return window.getSelection(); } else if(document.getSelection) { return document.getSelection(); } else { var selection = document.selection && document.selection.createRange(); if(selection.text) { return selection.text; } return false; } return false; }; function chainAnimation(e,s,o) { var $fade = $(e); $fade.each(function( i ){ $(this).delay(i * s).fadeTo(s,o); }); }; function createContainer(){ var siteSettings = { 'blogger': { text: 'Blogger', className: 'aBlogger', url: 'http://www.blogger.com/blog_this.pyra?t=&amp;u={u}&amp;n={t}' }, 'delicious': { text: 'Delicious', className: 'aDelicious', url: 'http://del.icio.us/post?url={u}&amp;title={t}' }, 'digg': { text: 'Digg', className: 'aDigg', url: 'http://digg.com/submit?phase=2&amp;url={u}&amp;title={t}' }, 'facebook': { text: 'Facebook', className: 'aFacebook', url: 'http://www.facebook.com/sharer.php?u={u}&amp;t={t}' }, 'friendfeed': { text: 'FriendFeed', className: 'aFriendFeed', url: 'http://friendfeed.com/share?url={u}&amp;title={t}' }, 'google': { text: 'Google+', className: 'aGooglePlus', url: 'https://plus.google.com/share?url={u}' }, 'linkedin': { text: 'LinkedIn', className: 'aLinkedIn', url: 'http://www.linkedin.com/shareArticle?mini=true&amp;url={u}&amp;title={t}&amp;ro=false&amp;summary={d}&amp;source=' }, 'myspace': { text: 'MySpace', className: 'aMySpace', url: 'http://www.myspace.com/Modules/PostTo/Pages/?u={u}&amp;t={t}' }, 'pinterest': { text: 'Pinterest', className: 'aPinterest', url: 'http://pinterest.com/pin/create/button/?url={u}&amp;description={d}' }, 'reddit': { text: 'Reddit', className: 'aReddit', url: 'http://reddit.com/submit?url={u}&amp;title={t}' }, 'stumbleupon': { text: 'StumbleUpon', className: 'aStumbleUpon', url: 'http://www.stumbleupon.com/submit?url={u}&amp;title={t}' }, 'tumblr': { text: 'Tumblr', className: 'aTumblr', url: 'http://www.tumblr.com/share/link?url={u}&name={t}&description={d}' }, 'twitter': { text: 'Twitter', className: 'aTwitter', url: 'http://twitter.com/home?status={t}%20{u}' }, 'windows': { text: 'Windows', className: 'aWindows', url: 'http://profile.live.com/badge?url={u}' }, 'yahoo': { text: 'Yahoo', className: 'aYahoo', url: 'http://bookmarks.yahoo.com/toolbar/savebm?opener=tb&amp;u={u}&amp;t={t}' } }; var sites = options.social.split(','); var listItem = ''; for (var i = 0; i <= sites.length-1; i++) { siteSettings[ sites[i] ]['url'] = siteSettings[ sites[i] ]['url'].replace('{t}',encodeURIComponent(options.title)).replace('{u}',encodeURI(options.shareUrl)).replace('{d}',encodeURIComponent(options.description)); listItem += '<li><a href="'+siteSettings[ sites[i] ]['url'] +'" target="_blank" rel="nofollow" class="'+siteSettings[ sites[i] ]['className'] +'"><span></span></a><span>'+siteSettings[ sites[i] ]['text'] +'</span></li>'; }; $('body').append(beforeDivs+listItem+afterDivs); } function destroyContainer(o) { if(o.blur) $('body').children().removeClass('blurred'); $('.arthrefSocialShare').find('.overlay').removeClass('active'); $('.arthrefSocialShare').find('ul').removeClass('active'); setTimeout(function(){ $('.arthrefSocialShare').find('.overlay').css('display','none'); $('.arthrefSocialShare').remove(); },300); } } }); })(jQuery);
gpl-2.0
HUDBT/HUDBT
lang/chs/lang_getusertorrentlistajax.php
531
<?php $lang_getusertorrentlistajax = array ( 'col_type' => "类型", 'col_name' => "标题", 'title_size' => "大小", 'title_seeders' => "种子数", 'title_leechers' => "下载数", 'col_uploaded' => "上传", 'col_downloaded' => "下载", 'col_ratio' => "分享率", 'col_anonymous' => "匿名", 'col_time_completed' => "完成时间", 'col_se_time' => "做种时间", 'col_le_time' => "下载时间", 'text_record' => "条记录", 'text_no_record' => "没有记录", 'col_time_storing' => "保种时间", ); ?>
gpl-2.0
manateelazycat/deepin-gnome-shell-3.4.1
js/ui/runDialog.js
14355
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const Clutter = imports.gi.Clutter; const Gio = imports.gi.Gio; const GLib = imports.gi.GLib; const Lang = imports.lang; const Meta = imports.gi.Meta; const St = imports.gi.St; const Shell = imports.gi.Shell; const Signals = imports.signals; const FileUtils = imports.misc.fileUtils; const Main = imports.ui.main; const ModalDialog = imports.ui.modalDialog; const ShellEntry = imports.ui.shellEntry; const Tweener = imports.ui.tweener; const Util = imports.misc.util; const History = imports.misc.history; const MAX_FILE_DELETED_BEFORE_INVALID = 10; const HISTORY_KEY = 'command-history'; const LOCKDOWN_SCHEMA = 'org.gnome.desktop.lockdown'; const DISABLE_COMMAND_LINE_KEY = 'disable-command-line'; const TERMINAL_SCHEMA = 'org.gnome.desktop.default-applications.terminal'; const EXEC_KEY = 'exec'; const EXEC_ARG_KEY = 'exec-arg'; const DIALOG_GROW_TIME = 0.1; const CommandCompleter = new Lang.Class({ Name: 'CommandCompleter', _init : function() { this._changedCount = 0; this._paths = GLib.getenv('PATH').split(':'); this._paths.push(GLib.get_home_dir()); this._valid = false; this._updateInProgress = false; this._childs = new Array(this._paths.length); this._monitors = new Array(this._paths.length); for (let i = 0; i < this._paths.length; i++) { this._childs[i] = []; let file = Gio.file_new_for_path(this._paths[i]); let info; try { info = file.query_info(Gio.FILE_ATTRIBUTE_STANDARD_TYPE, Gio.FileQueryInfoFlags.NONE, null); } catch (e) { // FIXME catchall this._paths[i] = null; continue; } if (info.get_attribute_uint32(Gio.FILE_ATTRIBUTE_STANDARD_TYPE) != Gio.FileType.DIRECTORY) continue; this._paths[i] = file.get_path(); this._monitors[i] = file.monitor_directory(Gio.FileMonitorFlags.NONE, null); if (this._monitors[i] != null) { this._monitors[i].connect('changed', Lang.bind(this, this._onChanged)); } } this._paths = this._paths.filter(function(a) { return a != null; }); this._update(0); }, update : function() { if (this._valid) return; this._update(0); }, _update : function(i) { if (i == 0 && this._updateInProgress) return; this._updateInProgress = true; this._changedCount = 0; this._i = i; if (i >= this._paths.length) { this._valid = true; this._updateInProgress = false; return; } let file = Gio.file_new_for_path(this._paths[i]); this._childs[this._i] = []; FileUtils.listDirAsync(file, Lang.bind(this, function (files) { for (let i = 0; i < files.length; i++) { this._childs[this._i].push(files[i].get_name()); } this._update(this._i + 1); })); }, _onChanged : function(m, f, of, type) { if (!this._valid) return; let path = f.get_parent().get_path(); let k = undefined; for (let i = 0; i < this._paths.length; i++) { if (this._paths[i] == path) k = i; } if (k === undefined) { return; } if (type == Gio.FileMonitorEvent.CREATED) { this._childs[k].push(f.get_basename()); } if (type == Gio.FileMonitorEvent.DELETED) { this._changedCount++; if (this._changedCount > MAX_FILE_DELETED_BEFORE_INVALID) { this._valid = false; } let name = f.get_basename(); this._childs[k] = this._childs[k].filter(function(e) { return e != name; }); } if (type == Gio.FileMonitorEvent.UNMOUNTED) { this._childs[k] = []; } }, getCompletion: function(text) { let common = ''; let notInit = true; if (!this._valid) { this._update(0); return common; } function _getCommon(s1, s2) { let k = 0; for (; k < s1.length && k < s2.length; k++) { if (s1[k] != s2[k]) break; } if (k == 0) return ''; return s1.substr(0, k); } function _hasPrefix(s1, prefix) { return s1.indexOf(prefix) == 0; } for (let i = 0; i < this._childs.length; i++) { for (let k = 0; k < this._childs[i].length; k++) { if (!_hasPrefix(this._childs[i][k], text)) continue; if (notInit) { common = this._childs[i][k]; notInit = false; } common = _getCommon(common, this._childs[i][k]); } } if (common.length) return common.substr(text.length); return common; } }); const RunDialog = new Lang.Class({ Name: 'RunDialog', Extends: ModalDialog.ModalDialog, _init : function() { this.parent({ styleClass: 'run-dialog' }); this._lockdownSettings = new Gio.Settings({ schema: LOCKDOWN_SCHEMA }); this._terminalSettings = new Gio.Settings({ schema: TERMINAL_SCHEMA }); global.settings.connect('changed::development-tools', Lang.bind(this, function () { this._enableInternalCommands = global.settings.get_boolean('development-tools'); })); this._enableInternalCommands = global.settings.get_boolean('development-tools'); this._internalCommands = { 'lg': Lang.bind(this, function() { Main.createLookingGlass().open(); }), 'r': Lang.bind(this, function() { global.reexec_self(); }), // Developer brain backwards compatibility 'restart': Lang.bind(this, function() { global.reexec_self(); }), 'debugexit': Lang.bind(this, function() { Meta.quit(Meta.ExitCode.ERROR); }), // rt is short for "reload theme" 'rt': Lang.bind(this, function() { Main.loadTheme(); }) }; let label = new St.Label({ style_class: 'run-dialog-label', text: _("Please enter a command:") }); this.contentLayout.add(label, { y_align: St.Align.START }); let entry = new St.Entry({ style_class: 'run-dialog-entry' }); ShellEntry.addContextMenu(entry); entry.label_actor = label; this._entryText = entry.clutter_text; this.contentLayout.add(entry, { y_align: St.Align.START }); this.setInitialKeyFocus(this._entryText); this._errorBox = new St.BoxLayout({ style_class: 'run-dialog-error-box' }); this.contentLayout.add(this._errorBox, { expand: true }); let errorIcon = new St.Icon({ icon_name: 'dialog-error', icon_size: 24, style_class: 'run-dialog-error-icon' }); this._errorBox.add(errorIcon, { y_align: St.Align.MIDDLE }); this._commandError = false; this._errorMessage = new St.Label({ style_class: 'run-dialog-error-label' }); this._errorMessage.clutter_text.line_wrap = true; this._errorBox.add(this._errorMessage, { expand: true, y_align: St.Align.MIDDLE, y_fill: false }); this._errorBox.hide(); this._pathCompleter = new Gio.FilenameCompleter(); this._commandCompleter = new CommandCompleter(); this._group.connect('notify::visible', Lang.bind(this._commandCompleter, this._commandCompleter.update)); this._history = new History.HistoryManager({ gsettingsKey: HISTORY_KEY, entry: this._entryText }); this._entryText.connect('key-press-event', Lang.bind(this, function(o, e) { let symbol = e.get_key_symbol(); if (symbol == Clutter.Return || symbol == Clutter.KP_Enter) { this.popModal(); if (e.get_state() & Clutter.ModifierType.CONTROL_MASK) this._run(o.get_text(), true); else this._run(o.get_text(), false); if (!this._commandError) this.close(); else { if (!this.pushModal()) this.close(); } return true; } if (symbol == Clutter.Escape) { this.close(); return true; } if (symbol == Clutter.slash) { // Need preload data before get completion. GFilenameCompleter load content of parent directory. // Parent directory for /usr/include/ is /usr/. So need to add fake name('a'). let text = o.get_text().concat('/a'); let prefix; if (text.lastIndexOf(' ') == -1) prefix = text; else prefix = text.substr(text.lastIndexOf(' ') + 1); this._getCompletion(prefix); return false; } if (symbol == Clutter.Tab) { let text = o.get_text(); let prefix; if (text.lastIndexOf(' ') == -1) prefix = text; else prefix = text.substr(text.lastIndexOf(' ') + 1); let postfix = this._getCompletion(prefix); if (postfix != null && postfix.length > 0) { o.insert_text(postfix, -1); o.set_cursor_position(text.length + postfix.length); if (postfix[postfix.length - 1] == '/') this._getCompletion(text + postfix + 'a'); } return true; } return false; })); }, _getCompletion : function(text) { if (text.indexOf('/') != -1) { return this._pathCompleter.get_completion_suffix(text); } else { return this._commandCompleter.getCompletion(text); } }, _run : function(input, inTerminal) { let command = input; this._history.addItem(input); this._commandError = false; let f; if (this._enableInternalCommands) f = this._internalCommands[input]; else f = null; if (f) { f(); } else if (input) { try { if (inTerminal) { let exec = this._terminalSettings.get_string(EXEC_KEY); let exec_arg = this._terminalSettings.get_string(EXEC_ARG_KEY); command = exec + ' ' + exec_arg + ' ' + input; } Util.trySpawnCommandLine(command); } catch (e) { // Mmmh, that failed - see if @input matches an existing file let path = null; if (input.charAt(0) == '/') { path = input; } else { if (input.charAt(0) == '~') input = input.slice(1); path = GLib.get_home_dir() + '/' + input; } if (GLib.file_test(path, GLib.FileTest.EXISTS)) { let file = Gio.file_new_for_path(path); try { Gio.app_info_launch_default_for_uri(file.get_uri(), global.create_app_launch_context()); } catch (e) { // The exception from gjs contains an error string like: // Error invoking Gio.app_info_launch_default_for_uri: No application // is registered as handling this file // We are only interested in the part after the first colon. let message = e.message.replace(/[^:]*: *(.+)/, '$1'); this._showError(message); } } else { this._showError(e.message); } } } }, _showError : function(message) { this._commandError = true; this._errorMessage.set_text(message); if (!this._errorBox.visible) { let [errorBoxMinHeight, errorBoxNaturalHeight] = this._errorBox.get_preferred_height(-1); let parentActor = this._errorBox.get_parent(); Tweener.addTween(parentActor, { height: parentActor.height + errorBoxNaturalHeight, time: DIALOG_GROW_TIME, transition: 'easeOutQuad', onComplete: Lang.bind(this, function() { parentActor.set_height(-1); this._errorBox.show(); }) }); } }, open: function() { this._history.lastItem(); this._errorBox.hide(); this._entryText.set_text(''); this._commandError = false; if (this._lockdownSettings.get_boolean(DISABLE_COMMAND_LINE_KEY)) return; this.parent(); }, }); Signals.addSignalMethods(RunDialog.prototype);
gpl-2.0
RGray1959/MyParish
CmsWeb/Areas/Search/Models/RegistrationSearch/RegistrationSearchInfo.cs
980
using System; using CmsWeb.Code; namespace CmsWeb.Areas.Search.Models { [Serializable] public class RegistrationSearchInfo { public string Registrant { get; set; } public string User { get; set; } public string Organization { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public CodeInfo Active { get; set; } public CodeInfo Expired { get; set; } public CodeInfo Complete { get; set; } public CodeInfo Abandoned { get; set; } public bool FromMobileAppOnly { get; set; } public string Count { get; set; } public RegistrationSearchInfo() { var yna = CodeValueModel.YesNoAll().ToSelect("Value"); Active = new CodeInfo("All", yna); Complete = new CodeInfo("All", yna); Abandoned = new CodeInfo("All", yna); Expired = new CodeInfo("All", yna); } } }
gpl-2.0
mdaniel/svn-caucho-com-resin
modules/resin/src/com/caucho/ejb/message/JmsActivationSpec.java
1456
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.ejb.message; import javax.resource.spi.ActivationSpec; import javax.resource.spi.ResourceAdapter; public class JmsActivationSpec implements ActivationSpec { private JmsResourceAdapter _ra; public void setResourceAdapter(ResourceAdapter ra) { _ra = (JmsResourceAdapter) ra; } public ResourceAdapter getResourceAdapter() { return _ra; } public void validate() { } }
gpl-2.0
mdaniel/svn-caucho-com-resin
modules/jcr/src/javax/jcr/MergeException.java
1400
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package javax.jcr; public class MergeException extends RepositoryException { public MergeException() { } public MergeException(String message) { super(message); } public MergeException(String message, Throwable rootCause) { super(message, rootCause); } public MergeException(Throwable rootCause) { super(rootCause); } }
gpl-2.0
mitchellzen/DLAMP-MAX
magento/downloader/pearlib/php/PEAR/Task/Windowseol.php
2619
<?php /** * <tasks:windowseol> * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_0.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category pear * @package PEAR * @author Greg Beaver <cellog@php.net> * @copyright 1997-2008 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: Windowseol.php,v 1.8 2008/01/03 20:26:37 cellog Exp $ * @link http://pear.php.net/package/PEAR * @since File available since Release 1.4.0a1 */ /** * Base class */ require_once 'PEAR/Task/Common.php'; /** * Implements the windows line endsings file task. * @category pear * @package PEAR * @author Greg Beaver <cellog@php.net> * @copyright 1997-2008 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: 1.7.1 * @link http://pear.php.net/package/PEAR * @since Class available since Release 1.4.0a1 */ class PEAR_Task_Windowseol extends PEAR_Task_Common { var $type = 'simple'; var $phase = PEAR_TASK_PACKAGE; var $_replacements; /** * Validate the raw xml at parsing-time. * @param PEAR_PackageFile_v2 * @param array raw, parsed xml * @param PEAR_Config * @static */ function validateXml($pkg, $xml, &$config, $fileXml) { if ($xml != '') { return array(PEAR_TASK_ERROR_INVALID, 'no attributes allowed'); } return true; } /** * Initialize a task instance with the parameters * @param array raw, parsed xml * @param unused */ function init($xml, $attribs) { } /** * Replace all line endings with windows line endings * * See validateXml() source for the complete list of allowed fields * @param PEAR_PackageFile_v1|PEAR_PackageFile_v2 * @param string file contents * @param string the eventual final file location (informational only) * @return string|false|PEAR_Error false to skip this file, PEAR_Error to fail * (use $this->throwError), otherwise return the new contents */ function startSession($pkg, $contents, $dest) { $this->logger->log(3, "replacing all line endings with \\r\\n in $dest"); return preg_replace("/\r\n|\n\r|\r|\n/", "\r\n", $contents); } } ?>
gpl-2.0
Melanie27/2014
wp-content/plugins/subscribe2/subscribe2.php
3157
<?php /* Plugin Name: Subscribe2 Plugin URI: http://subscribe2.wordpress.com Description: Notifies an email list when new entries are posted. Version: 8.9.1 Author: Matthew Robinson Author URI: http://subscribe2.wordpress.com Licence: GPL3 Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=2387904 */ /* Copyright (C) 2006-13 Matthew Robinson Based on the Original Subscribe2 plugin by Copyright (C) 2005 Scott Merrill (skippy@skippy.net) This file is part of Subscribe2. Subscribe2 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Subscribe2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Subscribe2. If not, see <http://www.gnu.org/licenses/>. */ if ( version_compare($GLOBALS['wp_version'], '3.1', '<') || !function_exists( 'add_action' ) ) { if ( !function_exists( 'add_action' ) ) { $exit_msg = __("I'm just a plugin, please don't call me directly", 'subscribe2'); } else { // Subscribe2 needs WordPress 3.1 or above, exit if not on a compatible version $exit_msg = sprintf(__('This version of Subscribe2 requires WordPress 3.1 or greater. Please update %1$s or use an older version of %2$s.', 'subscribe2'), '<a href="http://codex.wordpress.org/Updating_WordPress">Wordpress</a>', '<a href="http://wordpress.org/extend/plugins/subscribe2/download/">Subscribe2</a>'); } exit($exit_msg); } // stop Subscribe2 being activated site wide on Multisite installs if ( !function_exists( 'is_plugin_active_for_network' ) ) { require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); } if ( is_plugin_active_for_network(plugin_basename(__FILE__)) ) { deactivate_plugins( plugin_basename(__FILE__) ); $exit_msg = __('Subscribe2 cannot be activated as a network plugin. Please activate it at on a site level', 'subscribe2'); exit($exit_msg); } // our version number. Don't touch this or any line below // unless you know exactly what you are doing define( 'S2VERSION', '8.9' ); define( 'S2PATH', trailingslashit(dirname(__FILE__)) ); define( 'S2DIR', trailingslashit(dirname(plugin_basename(__FILE__))) ); define( 'S2URL', plugin_dir_url(dirname(__FILE__)) . S2DIR ); // Set maximum execution time to 5 minutes - won't affect safe mode $safe_mode = array('On', 'ON', 'on', 1); if ( !in_array(ini_get('safe_mode'), $safe_mode) && ini_get('max_execution_time') < 300 ) { @ini_set('max_execution_time', 300); } require_once( S2PATH . 'classes/class-s2-core.php' ); if ( is_admin() ) { require_once( S2PATH . 'classes/class-s2-admin.php' ); global $mysubscribe2; $mysubscribe2 = new s2_admin; $mysubscribe2->s2init(); } else { require_once( S2PATH . 'classes/class-s2-frontend.php' ); global $mysubscribe2; $mysubscribe2 = new s2_frontend; $mysubscribe2->s2init(); } ?>
gpl-2.0
cphillipp/deepwood
wp-content/themes/nevada/javascripts/nonverblaster.js
849
window.PlayerOnLoad = window.onload; PlayerOnLoad = init; var jsReady = false; var flashMovie = ""; var nonverblasterClicked = false; function init(){ jsReady = true; } function getFlashMovie(movieName) { if (navigator.appName.indexOf("Microsoft") != -1) { return window[movieName]; } else { return document[movieName]; } } // broadcasts the actions to the player function sendToNonverBlaster(value) { getFlashMovie(flashMovie).sendToActionScript(value); } function registerForJavaScriptCommunication(_flashMovie){ flashMovie = _flashMovie; } // Called if the Player was clicked function nonverBlasterClickHandler(){ nonverblasterClicked = true; //alert("nonverblasterClicked: " + nonverblasterClicked) } function quelltext() { window.open('view-source:' + window.location.href); }
gpl-2.0
dlinknctu/OpenADM
webui/js/config.js
533
var coreIP = "localhost"; var corePort = "5567"; function getFeatureUrl(){ return "http://"+coreIP+":"+corePort+"/feature"; } function getStatUrl(){ return "http://"+coreIP+":"+corePort+"/stat"; } function getTopologyUrl(){ return "http://"+coreIP+":"+corePort+"/info/topology"; } function getFlowModUrl(){ return "http://"+coreIP+":"+corePort+"/flowmod"; } function getUdsUrl(){ return "http://"+coreIP+":"+corePort+"/uds"; } function getSubscribeUrl(){ return "http://"+coreIP+":"+corePort+"/subscribe"; }
gpl-2.0
falbrechtskirchinger/kde-workspace
plasma/netbook/shell/data/layouts/org.kde.plasma-netbook.defaultPage/contents/layout.js
291
var page = new Activity("newspaper") page.screen = -1 page.wallpaperPlugin = 'image' page.wallpaperMode = 'SingleImage' page.name = templateName page.addWidgetAt("news", 0, 0) page.addWidgetAt("weather", 1, 0) page.addWidgetAt("opendesktop", 0, 1) page.addWidgetAt("knowledgebase", 1, 1)
gpl-2.0
VelocityRa/scummvm
engines/bladerunner/audio_player.cpp
5704
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "audio_player.h" #include "bladerunner/archive.h" #include "bladerunner/aud_stream.h" #include "bladerunner/bladerunner.h" #include "audio/audiostream.h" #include "audio/mixer.h" #include "common/debug.h" #include "common/stream.h" namespace Common { class MemoryReadStream; } namespace BladeRunner { AudioCache::~AudioCache() { for (uint i = 0; i != _cacheItems.size(); ++i) { free(_cacheItems[i].data); } } bool AudioCache::canAllocate(uint32 size) { Common::StackLock lock(_mutex); return _maxSize - _totalSize >= size; } bool AudioCache::dropOldest() { Common::StackLock lock(_mutex); if (_cacheItems.size() == 0) return false; uint oldest = 0; for (uint i = 1; i != _cacheItems.size(); ++i) { if (_cacheItems[i].refs == 0 && _cacheItems[i].lastAccess < _cacheItems[oldest].lastAccess) oldest = i; } free(_cacheItems[oldest].data); _totalSize -= _cacheItems[oldest].size; _cacheItems.remove_at(oldest); return true; } byte *AudioCache::findByHash(int32 hash) { Common::StackLock lock(_mutex); for (uint i = 0; i != _cacheItems.size(); ++i) { if (_cacheItems[i].hash == hash) { _cacheItems[i].lastAccess = _accessCounter++; return _cacheItems[i].data; } } return NULL; } void AudioCache::storeByHash(int32 hash, Common::SeekableReadStream *stream) { Common::StackLock lock(_mutex); uint32 size = stream->size(); byte *data = (byte*)malloc(size); stream->read(data, size); cacheItem item = { hash, 0, _accessCounter++, data, size }; _cacheItems.push_back(item); _totalSize += size; } void AudioCache::incRef(int32 hash) { Common::StackLock lock(_mutex); for (uint i = 0; i != _cacheItems.size(); ++i) { if (_cacheItems[i].hash == hash) { _cacheItems[i].refs++; return; } } assert(0 && "AudioCache::incRef: hash not found"); } void AudioCache::decRef(int32 hash) { Common::StackLock lock(_mutex); for (uint i = 0; i != _cacheItems.size(); ++i) { if (_cacheItems[i].hash == hash) { assert(_cacheItems[i].refs > 0); _cacheItems[i].refs--; return; } } assert(0 && "AudioCache::decRef: hash not found"); } AudioPlayer::AudioPlayer(BladeRunnerEngine *vm) : _vm(vm) { _cache = new AudioCache(); for (int i = 0; i != 6; ++i) { _tracks[i].hash = 0; _tracks[i].priority = 0; } } AudioPlayer::~AudioPlayer() { delete _cache; } bool AudioPlayer::isTrackActive(Track *track) { if (!track->isMaybeActive) return false; return track->isMaybeActive = _vm->_mixer->isSoundHandleActive(track->soundHandle); } void AudioPlayer::stopAll() { for (int i = 0; i != TRACKS; ++i) { _vm->_mixer->stopHandle(_tracks[i].soundHandle); } } void AudioPlayer::fadeAndStopTrack(Track *track, int time) { (void)time; _vm->_mixer->stopHandle(track->soundHandle); } int AudioPlayer::playAud(const Common::String &name, int volume, int panFrom, int panTo, int priority, byte flags) { /* Find first available track or, alternatively, the lowest priority playing track */ Track *track = NULL; int lowestPriority = 1000000; Track *lowestPriorityTrack = NULL; for (int i = 0; i != 6; ++i) { Track *ti = &_tracks[i]; if (!isTrackActive(ti)) { track = ti; break; } if (lowestPriorityTrack == NULL || ti->priority < lowestPriority) { lowestPriority = ti->priority; lowestPriorityTrack = ti; } } /* If there's no available track, stop the lowest priority track if it's lower than * the new priority */ if (track == NULL && lowestPriority < priority) { fadeAndStopTrack(lowestPriorityTrack, 1); track = lowestPriorityTrack; } /* If there's still no available track, give up */ if (track == NULL) return -1; /* Load audio resource and store in cache. Playback will happen directly from there. */ int32 hash = mix_id(name); if (!_cache->findByHash(hash)) { Common::SeekableReadStream *r = _vm->getResourceStream(name); if (!r) return -1; int32 size = r->size(); while (!_cache->canAllocate(size)) { if (!_cache->dropOldest()) { delete r; return -1; } } _cache->storeByHash(hash, r); delete r; } AudStream *audStream = new AudStream(_cache, hash); Audio::AudioStream *audioStream = audStream; if (flags & LOOP) { audioStream = new Audio::LoopingAudioStream(audStream, 0, DisposeAfterUse::YES); } Audio::SoundHandle soundHandle; // debug("PlayStream: %s", name.c_str()); int balance = panFrom; _vm->_mixer->playStream( Audio::Mixer::kPlainSoundType, &soundHandle, audioStream, -1, volume * 255 / 100, balance); track->isMaybeActive = true; track->soundHandle = soundHandle; track->priority = priority; track->hash = hash; track->volume = volume; return track - &_tracks[0]; } } // End of namespace BladeRunner
gpl-2.0
rschatz/graal-core
graal/com.oracle.graal.compiler.test/src/com/oracle/graal/compiler/test/TypeWriterTest.java
6478
/* * Copyright (c) 2015, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.test; import org.junit.Assert; import org.junit.Test; import com.oracle.graal.compiler.common.util.TypeConversion; import com.oracle.graal.compiler.common.util.TypeReader; import com.oracle.graal.compiler.common.util.TypeWriter; import com.oracle.graal.compiler.common.util.UnsafeArrayTypeReader; import com.oracle.graal.compiler.common.util.UnsafeArrayTypeWriter; public class TypeWriterTest extends GraalCompilerTest { private static void putValue(TypeWriter writer, long value) { if (TypeConversion.isS1(value)) { writer.putS1(value); } if (TypeConversion.isU1(value)) { writer.putU1(value); } if (TypeConversion.isS2(value)) { writer.putS2(value); } if (TypeConversion.isU2(value)) { writer.putU2(value); } if (TypeConversion.isS4(value)) { writer.putS4(value); } if (TypeConversion.isU4(value)) { writer.putU4(value); } writer.putS8(value); writer.putSV(value); if (value >= 0) { writer.putUV(value); } } private static void checkValue(TypeReader reader, long value) { if (TypeConversion.isS1(value)) { Assert.assertEquals(value, reader.getS1()); } if (TypeConversion.isU1(value)) { Assert.assertEquals(value, reader.getU1()); } if (TypeConversion.isS2(value)) { Assert.assertEquals(value, reader.getS2()); } if (TypeConversion.isU2(value)) { Assert.assertEquals(value, reader.getU2()); } if (TypeConversion.isS4(value)) { Assert.assertEquals(value, reader.getS4()); } if (TypeConversion.isU4(value)) { Assert.assertEquals(value, reader.getU4()); } Assert.assertEquals(value, reader.getS8()); Assert.assertEquals(value, reader.getSV()); if (value >= 0) { Assert.assertEquals(value, reader.getUV()); } } private static void putValues(TypeWriter writer) { for (int i = 0; i < 64; i++) { long value = 1L << i; putValue(writer, value - 2); putValue(writer, value - 1); putValue(writer, value); putValue(writer, value + 1); putValue(writer, value + 2); putValue(writer, -value - 2); putValue(writer, -value - 1); putValue(writer, -value); putValue(writer, -value + 1); putValue(writer, -value + 2); } } private static void checkValues(TypeReader reader) { for (int i = 0; i < 64; i++) { long value = 1L << i; checkValue(reader, value - 2); checkValue(reader, value - 1); checkValue(reader, value); checkValue(reader, value + 1); checkValue(reader, value + 2); checkValue(reader, -value - 2); checkValue(reader, -value - 1); checkValue(reader, -value); checkValue(reader, -value + 1); checkValue(reader, -value + 2); } } private static void test01(boolean supportsUnalignedMemoryAccess) { UnsafeArrayTypeWriter writer = UnsafeArrayTypeWriter.create(supportsUnalignedMemoryAccess); putValues(writer); byte[] array = new byte[(int) writer.getBytesWritten()]; writer.toArray(array); UnsafeArrayTypeReader reader = UnsafeArrayTypeReader.create(array, 0, supportsUnalignedMemoryAccess); checkValues(reader); } @Test public void test01a() { test01(getTarget().arch.supportsUnalignedMemoryAccess()); } @Test public void test01b() { test01(false); } private static void checkSignedSize(TypeWriter writer, long value, int expectedSize) { long sizeBefore = writer.getBytesWritten(); writer.putSV(value); Assert.assertEquals(expectedSize, writer.getBytesWritten() - sizeBefore); } private static void checkUnsignedSize(TypeWriter writer, long value, int expectedSize) { long sizeBefore = writer.getBytesWritten(); writer.putUV(value); Assert.assertEquals(expectedSize, writer.getBytesWritten() - sizeBefore); } private static void checkSizes(TypeWriter writer) { checkSignedSize(writer, 0, 1); checkSignedSize(writer, 63, 1); checkSignedSize(writer, -64, 1); checkSignedSize(writer, 64, 2); checkSignedSize(writer, -65, 2); checkSignedSize(writer, 8191, 2); checkSignedSize(writer, -8192, 2); checkSignedSize(writer, 8192, 3); checkSignedSize(writer, -8193, 3); checkSignedSize(writer, Long.MAX_VALUE, 10); checkSignedSize(writer, Long.MIN_VALUE, 10); checkUnsignedSize(writer, 0, 1); checkUnsignedSize(writer, 127, 1); checkUnsignedSize(writer, 128, 2); checkUnsignedSize(writer, 16383, 2); checkUnsignedSize(writer, 16384, 3); checkUnsignedSize(writer, Long.MAX_VALUE, 9); } @Test public void test02a() { checkSizes(UnsafeArrayTypeWriter.create(getTarget().arch.supportsUnalignedMemoryAccess())); } @Test public void test02b() { checkSizes(UnsafeArrayTypeWriter.create(false)); } }
gpl-2.0
werwurm/sunxi-fiasco
tool/preprocess/test/template.cpp
3774
INTERFACE: template<class T> class stack_t; template<class T> class stack_top_t { private: friend class stack_t<T>; // Dont change the layout !!, comp_and_swap2 expects // version and _next next to each other, in that order int _version; T *_next; }; template<class T> class stack_t { private: stack_top_t<T> _head; }; IMPLEMENTATION: // // atomic-manipulation functions // // typesafe variants template <class I> inline bool compare_and_swap(I *ptr, I oldval, I newval) { return compare_and_swap(reinterpret_cast<unsigned*>(ptr), *reinterpret_cast<unsigned*>(&oldval), *reinterpret_cast<unsigned*>(&newval)); } template <class I> inline bool test_and_set(I *l) { return test_and_set(reinterpret_cast<unsigned*>(l)); } // // stack_top_t // // template<class T> // stack_top_t<T> & // stack_top_t<T>::operator=(const stack_top_t& _copy){ // _version = _copy._version; // _next = _copy._next; // return *this; // } PUBLIC inline template<class T> stack_top_t<T>::stack_top_t (int version, T *next) : _version (version), _next (next) {} PUBLIC inline template<class T> stack_top_t<T>::stack_top_t () : _version (0), _next (0) {} // // stack_t // PUBLIC template<class T> stack_t<T>::stack_t() : _head (0, 0) {} PUBLIC template<class T> int stack_t<T>::insert(T *e) { stack_top_t<T> old_head, new_head; do { e->set_next(_head._next); old_head = _head; new_head._version = _head._version+1; new_head._next = e; } while (! compare_and_swap2((int *) &_head, (int *) &old_head, (int *) &new_head)); return new_head._version; } PUBLIC template<class T> T* stack_t<T>::dequeue() { stack_top_t<T> old_head, new_head; T *first; do { old_head = _head; first = _head._next; if(! first){ break; } new_head._next = first->get_next(); new_head._version = _head._version + 1; } while (! compare_and_swap2((int *) &_head, (int *) &old_head, (int *) &new_head)); // XXX Why did the old implementation test on e ? // while (e && ! compare_and_swap(&_first, e, e->list_property.next)); // This is necessary to handle the case of a empty stack. // return old_head._next; return first; } // This version of dequeue only returns a value // if it is equal to the one passed as top PUBLIC template<class T> T* stack_t<T>::dequeue(T *top) { stack_top_t<T> old_head, new_head; // stack_elem_t *first; old_head._version = _head._version; // version doesnt matter old_head._next = top; // cas will fail, if top aint at top if(!_head._next){ // empty stack return 0; } new_head._version = _head._version + 1; new_head._next = top->get_next(); if(! compare_and_swap2((int *) &_head, (int *) &old_head, (int *) &new_head)) // we didnt succeed return 0; else // top was on top , so we dequeued it return top; } PUBLIC template<class T> T* stack_t<T>::first() { return _head._next; } PUBLIC template<class T> void stack_t<T>::reset() { _head._version = 0; _head._next = 0; } template<class T> stack_t<T>* create_stack() { return new stack_t<T>(); } template <> stack_t<int>* create_stack<int>() { return new stack<int>(); } template <> inline stack_t<bool>* create_stack<bool>() { return new stack<bool>(); } // // Member templates // class Foo { template <typename T> T* goo(T* t); }; template <class Bar> class TFoo { }; PUBLIC template <typename T> T* Foo::bar (T* t) { } IMPLEMENT template <typename T> T* Foo::goo (T* t) { } PUBLIC template <class Bar> template <typename T> T* TFoo::baz (T* t) { }
gpl-2.0
Dovedesign/WoodsDev
wp-content/plugins/soliloquy/assets/js/lib/bxslider.js
51856
;(function($){ var plugin = {}; var defaults = { // Added by Thomas keyboard: false, // GENERAL mode: 'horizontal', slideSelector: '', infiniteLoop: true, hideControlOnEnd: false, speed: 500, captionSpeed: 0, easing: null, slideMargin: 0, startSlide: 0, randomStart: false, captions: false, ticker: false, tickerHover: false, adaptiveHeight: false, adaptiveHeightSpeed: 500, video: false, useCSS: true, preloadImages: 'visible', responsive: true, slideZIndex: 50, wrapperClass: 'soliloquy-wrapper', // TOUCH touchEnabled: true, swipeThreshold: 50, oneToOneTouch: true, preventDefaultSwipeX: true, preventDefaultSwipeY: false, // PAGER pager: true, pagerType: 'full', pagerShortSeparator: ' / ', pagerSelector: null, buildPager: null, pagerCustom: null, // CONTROLS controls: true, nextText: 'Next', prevText: 'Prev', nextSelector: null, prevSelector: null, autoControls: false, startText: 'Start', stopText: 'Stop', autoControlsCombine: false, autoControlsSelector: null, // AUTO auto: false, pause: 4000, autoStart: true, autoDirection: 'next', autoHover: false, autoDelay: 0, autoSlideForOnePage: false, // CAROUSEL minSlides: 1, maxSlides: 1, moveSlides: 0, slideWidth: 0, // CALLBACKS onSliderLoad: function() {}, onSlideBefore: function() {}, onSlideAfter: function() {}, onSlideNext: function() {}, onSlidePrev: function() {}, onSliderResize: function() {} } $.fn.soliloquy = function(options){ if(this.length == 0) return this; // support mutltiple elements if(this.length > 1){ this.each(function(){$(this).soliloquy(options)}); return this; } // create a namespace to be used throughout the plugin var slider = {}; // set a reference to our slider element var el = this; plugin.el = this; /** * Makes slideshow responsive */ // first get the original window dimens (thanks alot IE) var windowWidth = $(window).width(); var windowHeight = $(window).height(); /** * =================================================================================== * = PRIVATE FUNCTIONS * =================================================================================== */ /** * Initializes namespace settings to be used throughout plugin */ var init = function(){ // merge user-supplied options with the defaults slider.settings = $.extend({}, defaults, options); // parse slideWidth setting slider.settings.slideWidth = parseInt(slider.settings.slideWidth); // store the original children slider.children = el.children(slider.settings.slideSelector); // check if actual number of slides is less than minSlides / maxSlides if(slider.children.length < slider.settings.minSlides) slider.settings.minSlides = slider.children.length; if(slider.children.length < slider.settings.maxSlides) slider.settings.maxSlides = slider.children.length; // if random start, set the startSlide setting to random number if(slider.settings.randomStart) slider.settings.startSlide = Math.floor(Math.random() * slider.children.length); // store active slide information slider.active = { index: slider.settings.startSlide } // store if the slider is in carousel mode (displaying / moving multiple slides) slider.carousel = slider.settings.minSlides > 1 || slider.settings.maxSlides > 1; // if carousel, force preloadImages = 'all' if(slider.carousel) slider.settings.preloadImages = 'all'; // calculate the min / max width thresholds based on min / max number of slides // used to setup and update carousel slides dimensions slider.minThreshold = (slider.settings.minSlides * slider.settings.slideWidth) + ((slider.settings.minSlides - 1) * slider.settings.slideMargin); slider.maxThreshold = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin); // store the current state of the slider (if currently animating, working is true) slider.working = false; // initialize the controls object slider.controls = {}; // initialize an auto interval slider.interval = null; // determine which property to use for transitions slider.animProp = slider.settings.mode == 'vertical' ? 'top' : 'left'; // determine if hardware acceleration can be used slider.usingCSS = slider.settings.useCSS && slider.settings.mode != 'fade' && (function(){ // create our test div element var div = document.createElement('div'); // css transition properties var props = ['WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective']; // test for each property for(var i in props){ if(div.style[props[i]] !== undefined){ slider.cssPrefix = props[i].replace('Perspective', '').toLowerCase(); slider.animProp = '-' + slider.cssPrefix + '-transform'; return true; } } return false; }()); // if vertical mode always make maxSlides and minSlides equal if(slider.settings.mode == 'vertical') slider.settings.maxSlides = slider.settings.minSlides; // save original style data el.data("origStyle", el.attr("style")); el.children(slider.settings.slideSelector).each(function() { $(this).data("origStyle", $(this).attr("style")); }); // perform all DOM / CSS modifications setup(); } /** * Performs all DOM and CSS modifications */ var setup = function(){ // wrap el in a wrapper el.wrap('<div class="' + slider.settings.wrapperClass + '"><div class="soliloquy-viewport"></div></div>'); // store a namspace reference to .soliloquy-viewport slider.viewport = el.parent(); // add a loading div to display while images are loading slider.loader = $('<div class="soliloquy-loading" />'); slider.viewport.prepend(slider.loader); // set el to a massive width, to hold any needed slides // also strip any margin and padding from el el.css({ width: slider.settings.mode == 'horizontal' ? (slider.children.length * 100 + 215) + '%' : 'auto', position: 'relative' }); // if using CSS, add the easing property if(slider.usingCSS && slider.settings.easing){ el.css('-' + slider.cssPrefix + '-transition-timing-function', slider.settings.easing); // if not using CSS and no easing value was supplied, use the default JS animation easing (swing) }else if(!slider.settings.easing){ slider.settings.easing = 'swing'; } var slidesShowing = getNumberSlidesShowing(); // make modifications to the viewport (.soliloquy-viewport) slider.viewport.css({ width: '100%', position: 'relative' }); if(slider.settings.mode != 'fade'){ slider.viewport.css({overflow:'hidden'}); } slider.viewport.parent().css({ maxWidth: getViewportMaxWidth() }); // make modification to the wrapper (.soliloquy-wrapper) if(!slider.settings.pager) { slider.viewport.parent().css({ margin: '0 auto 0px' }); } // apply css to all slider children slider.children.css({ 'float': 'left', listStyle: 'none', position: 'relative' }); // apply the calculated width after the float is applied to prevent scrollbar interference slider.children.css('width', getSlideWidth()); // if slideMargin is supplied, add the css if(slider.settings.mode == 'horizontal' && slider.settings.slideMargin > 0) slider.children.css('marginRight', slider.settings.slideMargin); if(slider.settings.mode == 'vertical' && slider.settings.slideMargin > 0) slider.children.css('marginBottom', slider.settings.slideMargin); // if "fade" mode, add positioning and z-index CSS if(slider.settings.mode == 'fade'){ slider.children.css({ zIndex: 0, display: 'none', marginRight: '-100%', width: '100%' }); // prepare the z-index on the showing element slider.children.eq(slider.settings.startSlide).css({zIndex: slider.settings.slideZIndex, display: 'block'}); } // create an element to contain all slider controls (pager, start / stop, etc) slider.controls.el = $('<div class="soliloquy-controls" />'); // if captions are requested, add them if(slider.settings.captions) appendCaptions(); // check if startSlide is last slide slider.active.last = slider.settings.startSlide == getPagerQty() - 1; // Added by Thomas - removed fitVids support, no need. // set the default preload selector (visible) var preloadSelector = slider.children.eq(slider.settings.startSlide); if (slider.settings.preloadImages == "all") preloadSelector = slider.children; // only check for control addition if not in "ticker" mode if(!slider.settings.ticker){ // if pager is requested, add it if(slider.settings.pager) appendPager(); // if controls are requested, add them if(slider.settings.controls) appendControls(); // if auto is true, and auto controls are requested, add them if(slider.settings.auto && slider.settings.autoControls) appendControlsAuto(); // if any control option is requested, add the controls wrapper if(slider.settings.controls || slider.settings.autoControls || slider.settings.pager) slider.viewport.after(slider.controls.el); // if ticker mode, do not allow a pager }else{ slider.settings.pager = false; } // preload all images, then perform final DOM / CSS modifications that depend on images being loaded loadElements(preloadSelector, start); } var loadElements = function(selector, callback){ var total = selector.find('img, iframe').length; if (total == 0){ callback(); return; } var count = 0; selector.find('img, iframe').each(function(){ $(this).one('load', function() { if(++count == total) callback(); }).each(function() { if(this.complete) $(this).load(); }); }); } /** * Start the slider */ var start = function(){ // if infinite loop, prepare additional slides if(slider.settings.infiniteLoop && slider.settings.mode != 'fade' && !slider.settings.ticker){ var slice = slider.settings.mode == 'vertical' ? slider.settings.minSlides : slider.settings.maxSlides; var sliceAppend = slider.children.slice(0, slice).clone().addClass('soliloquy-clone'); var slicePrepend = slider.children.slice(-slice).clone().addClass('soliloquy-clone'); el.append(sliceAppend).prepend(slicePrepend); } // remove the loading DOM element slider.loader.remove(); // set the left / top position of "el" setSlidePosition(); // if "vertical" mode, always use adaptiveHeight to prevent odd behavior if (slider.settings.mode == 'vertical') slider.settings.adaptiveHeight = true; // set the viewport height slider.viewport.height(getViewportHeight()); // make sure everything is positioned just right (same as a window resize) el.redrawSlider(); // onSliderLoad callback slider.settings.onSliderLoad(slider.active.index); // slider has been fully initialized slider.initialized = true; // bind the resize call to the window if (slider.settings.responsive) $(window).bind('resize', resizeWindow); // if auto is true and has more than 1 page, start the show if (slider.settings.auto && slider.settings.autoStart && (getPagerQty() > 1 || slider.settings.autoSlideForOnePage)) initAuto(); // if ticker is true, start the ticker if (slider.settings.ticker) initTicker(); // if pager is requested, make the appropriate pager link active if (slider.settings.pager) updatePagerActive(slider.settings.startSlide); // check for any updates to the controls (like hideControlOnEnd updates) if (slider.settings.controls) updateDirectionControls(); // if touchEnabled is true, setup the touch events if (slider.settings.touchEnabled && !slider.settings.ticker) initTouch(); // Added by Thomas if (slider.settings.keyboard && !slider.settings.ticker) { $(document).on('keydown', function(e){ if (e.keyCode == 39) { clickNextBind(e); return false; } else if (e.keyCode == 37) { clickPrevBind(e); return false; } }); } } /** * Returns the calculated height of the viewport, used to determine either adaptiveHeight or the maxHeight value */ var getViewportHeight = function(){ var height = 0; // first determine which children (slides) should be used in our height calculation var children = $(); // if mode is not "vertical" and adaptiveHeight is false, include all children if(slider.settings.mode != 'vertical' && !slider.settings.adaptiveHeight){ children = slider.children; }else{ // if not carousel, return the single active child if(!slider.carousel){ children = slider.children.eq(slider.active.index); // if carousel, return a slice of children }else{ // get the individual slide index var currentIndex = slider.settings.moveSlides == 1 ? slider.active.index : slider.active.index * getMoveBy(); // add the current slide to the children children = slider.children.eq(currentIndex); // cycle through the remaining "showing" slides for (i = 1; i <= slider.settings.maxSlides - 1; i++){ // if looped back to the start if(currentIndex + i >= slider.children.length){ children = children.add(slider.children.eq(i - 1)); }else{ children = children.add(slider.children.eq(currentIndex + i)); } } } } // if "vertical" mode, calculate the sum of the heights of the children if(slider.settings.mode == 'vertical'){ children.each(function(index) { height += $(this).outerHeight(); }); // add user-supplied margins if(slider.settings.slideMargin > 0){ height += slider.settings.slideMargin * (slider.settings.minSlides - 1); } // if not "vertical" mode, calculate the max height of the children }else{ height = Math.max.apply(Math, children.map(function(){ return $(this).outerHeight(false); }).get()); } if(slider.viewport.css('box-sizing') == 'border-box'){ height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom')) + parseFloat(slider.viewport.css('border-top-width')) + parseFloat(slider.viewport.css('border-bottom-width')); }else if(slider.viewport.css('box-sizing') == 'padding-box'){ height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom')); } return height; } /** * Returns the calculated width to be used for the outer wrapper / viewport */ var getViewportMaxWidth = function(){ var width = '100%'; if(slider.settings.slideWidth > 0){ if(slider.settings.mode == 'horizontal'){ width = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin); }else{ width = slider.settings.slideWidth; } } return (slider.settings.mode == 'fade') ? '100%' : width; } /** * Returns the calculated width to be applied to each slide */ var getSlideWidth = function(){ // start with any user-supplied slide width var newElWidth = slider.settings.slideWidth; // get the current viewport width var wrapWidth = slider.viewport.width(); // if slide width was not supplied, or is larger than the viewport use the viewport width if(slider.settings.slideWidth == 0 || (slider.settings.slideWidth > wrapWidth && !slider.carousel) || slider.settings.mode == 'vertical'){ newElWidth = wrapWidth; // if carousel, use the thresholds to determine the width }else if(slider.settings.maxSlides > 1 && slider.settings.mode == 'horizontal'){ if(wrapWidth > slider.maxThreshold){ // newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.maxSlides - 1))) / slider.settings.maxSlides; }else if(wrapWidth < slider.minThreshold){ newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.minSlides - 1))) / slider.settings.minSlides; } } return (slider.settings.mode == 'fade') ? '100%' : newElWidth; } /** * Returns the number of slides currently visible in the viewport (includes partially visible slides) */ var getNumberSlidesShowing = function(){ var slidesShowing = 1; if(slider.settings.mode == 'horizontal' && slider.settings.slideWidth > 0){ // if viewport is smaller than minThreshold, return minSlides if(slider.viewport.width() < slider.minThreshold){ slidesShowing = slider.settings.minSlides; // if viewport is larger than minThreshold, return maxSlides }else if(slider.viewport.width() > slider.maxThreshold){ slidesShowing = slider.settings.maxSlides; // if viewport is between min / max thresholds, divide viewport width by first child width }else{ var childWidth = slider.children.first().width() + slider.settings.slideMargin; slidesShowing = Math.floor((slider.viewport.width() + slider.settings.slideMargin) / childWidth); } // if "vertical" mode, slides showing will always be minSlides }else if(slider.settings.mode == 'vertical'){ slidesShowing = slider.settings.minSlides; } return slidesShowing; } /** * Returns the number of pages (one full viewport of slides is one "page") */ var getPagerQty = function(){ var pagerQty = 0; // if moveSlides is specified by the user if(slider.settings.moveSlides > 0){ if(slider.settings.infiniteLoop){ pagerQty = Math.ceil(slider.children.length / getMoveBy()); }else{ // use a while loop to determine pages var breakPoint = 0; var counter = 0 // when breakpoint goes above children length, counter is the number of pages while (breakPoint < slider.children.length){ ++pagerQty; breakPoint = counter + getNumberSlidesShowing(); counter += slider.settings.moveSlides <= getNumberSlidesShowing() ? slider.settings.moveSlides : getNumberSlidesShowing(); } } // if moveSlides is 0 (auto) divide children length by sides showing, then round up }else{ pagerQty = Math.ceil(slider.children.length / getNumberSlidesShowing()); } return pagerQty; } /** * Returns the number of indivual slides by which to shift the slider */ var getMoveBy = function(){ // if moveSlides was set by the user and moveSlides is less than number of slides showing if(slider.settings.moveSlides > 0 && slider.settings.moveSlides <= getNumberSlidesShowing()){ return slider.settings.moveSlides; } // if moveSlides is 0 (auto) return getNumberSlidesShowing(); } /** * Sets the slider's (el) left or top position */ var setSlidePosition = function(){ // if last slide, not infinite loop, and number of children is larger than specified maxSlides if(slider.children.length > slider.settings.maxSlides && slider.active.last && !slider.settings.infiniteLoop){ if (slider.settings.mode == 'horizontal'){ // get the last child's position var lastChild = slider.children.last(); var position = lastChild.position(); // set the left position setPositionProperty(-(position.left - (slider.viewport.width() - lastChild.outerWidth())), 'reset', 0); }else if(slider.settings.mode == 'vertical'){ // get the last showing index's position var lastShowingIndex = slider.children.length - slider.settings.minSlides; var position = slider.children.eq(lastShowingIndex).position(); // set the top position setPositionProperty(-position.top, 'reset', 0); } // if not last slide }else{ // get the position of the first showing slide var position = slider.children.eq(slider.active.index * getMoveBy()).position(); // check for last slide if (slider.active.index == getPagerQty() - 1) slider.active.last = true; // set the repective position if (position != undefined){ if (slider.settings.mode == 'horizontal') setPositionProperty(-position.left, 'reset', 0); else if (slider.settings.mode == 'vertical') setPositionProperty(-position.top, 'reset', 0); } } } /** * Sets the el's animating property position (which in turn will sometimes animate el). * If using CSS, sets the transform property. If not using CSS, sets the top / left property. * * @param value (int) * - the animating property's value * * @param type (string) 'slider', 'reset', 'ticker' * - the type of instance for which the function is being * * @param duration (int) * - the amount of time (in ms) the transition should occupy * * @param params (array) optional * - an optional parameter containing any variables that need to be passed in */ var setPositionProperty = function(value, type, duration, params){ // use CSS transform if(slider.usingCSS){ // determine the translate3d value var propValue = slider.settings.mode == 'vertical' ? 'translate3d(0, ' + value + 'px, 0)' : 'translate3d(' + value + 'px, 0, 0)'; // add the CSS transition-duration el.css('-' + slider.cssPrefix + '-transition-duration', duration / 1000 + 's'); if(type == 'slide'){ // set the property value el.css(slider.animProp, propValue); // bind a callback method - executes when CSS transition completes el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(){ // unbind the callback el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'); updateAfterSlideTransition(); }); }else if(type == 'reset'){ el.css(slider.animProp, propValue); }else if(type == 'ticker'){ // make the transition use 'linear' el.css('-' + slider.cssPrefix + '-transition-timing-function', 'linear'); el.css(slider.animProp, propValue); // bind a callback method - executes when CSS transition completes el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(){ // unbind the callback el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'); // reset the position setPositionProperty(params['resetValue'], 'reset', 0); // start the loop again tickerLoop(); }); } // use JS animate }else{ var animateObj = {}; animateObj[slider.animProp] = value; if(type == 'slide'){ el.animate(animateObj, duration, slider.settings.easing, function(){ updateAfterSlideTransition(); }); }else if(type == 'reset'){ el.css(slider.animProp, value) }else if(type == 'ticker'){ el.animate(animateObj, speed, 'linear', function(){ setPositionProperty(params['resetValue'], 'reset', 0); // run the recursive loop after animation tickerLoop(); }); } } } /** * Populates the pager with proper amount of pages */ var populatePager = function(){ var pagerHtml = ''; var pagerQty = getPagerQty(); // loop through each pager item for(var i=0; i < pagerQty; i++){ var linkContent = ''; // if a buildPager function is supplied, use it to get pager link value, else use index + 1 if(slider.settings.buildPager && $.isFunction(slider.settings.buildPager)){ linkContent = slider.settings.buildPager(i); slider.pagerEl.addClass('soliloquy-custom-pager'); }else{ linkContent = i + 1; slider.pagerEl.addClass('soliloquy-default-pager'); } // var linkContent = slider.settings.buildPager && $.isFunction(slider.settings.buildPager) ? slider.settings.buildPager(i) : i + 1; // add the markup to the string pagerHtml += '<div class="soliloquy-pager-item"><a href="" data-slide-index="' + i + '" class="soliloquy-pager-link" tabindex="0"><span>' + linkContent + '</span></a></div>'; }; // populate the pager element with pager links slider.pagerEl.html(pagerHtml); } /** * Appends the pager to the controls element */ var appendPager = function(){ // Create container for pager if (!slider.settings.pagerCustom) { // Auto generated pager - create container slider.pagerEl = $('<div class="soliloquy-pager" />'); } else { // Manually specified pager - insert slider.pagerEl = $(slider.settings.pagerCustom); } // If a pager selector was supplied, populate it with the pager if (slider.settings.pagerSelector) { $(slider.settings.pagerSelector).html(slider.pagerEl); } else { slider.controls.el.addClass('soliloquy-has-pager').append(slider.pagerEl); } // If we are not using a custom pager, automatically populated slider.pagerEl if (!slider.settings.pagerCustom) { populatePager(); } // Assign the clickPagerBind event slider.pagerEl.on('click', 'a', clickPagerBind); } /** * Appends prev / next controls to the controls element */ var appendControls = function(){ slider.controls.next = $('<a class="soliloquy-next" href="" tabindex="0"><span>' + slider.settings.nextText + '</span></a>'); slider.controls.prev = $('<a class="soliloquy-prev" href="" tabindex="0"><span>' + slider.settings.prevText + '</span></a>'); // bind click actions to the controls slider.controls.next.bind('click', clickNextBind); slider.controls.prev.bind('click', clickPrevBind); // if nextSlector was supplied, populate it if(slider.settings.nextSelector){ $(slider.settings.nextSelector).append(slider.controls.next); } // if prevSlector was supplied, populate it if(slider.settings.prevSelector){ $(slider.settings.prevSelector).append(slider.controls.prev); } // if no custom selectors were supplied if(!slider.settings.nextSelector && !slider.settings.prevSelector){ // add the controls to the DOM slider.controls.directionEl = $('<div class="soliloquy-controls-direction" />'); // add the control elements to the directionEl slider.controls.directionEl.append(slider.controls.prev).append(slider.controls.next); // slider.viewport.append(slider.controls.directionEl); slider.controls.el.addClass('soliloquy-has-controls-direction').append(slider.controls.directionEl); } } /** * Appends start / stop auto controls to the controls element */ var appendControlsAuto = function(){ slider.controls.start = $('<div class="soliloquy-controls-auto-item"><a class="soliloquy-start" href="" aria-label="play" tabindex="0"><span>' + slider.settings.startText + '</span></a></div>'); slider.controls.stop = $('<div class="soliloquy-controls-auto-item"><a class="soliloquy-stop" href="" aria-label="pause" tabindex="0"><span>' + slider.settings.stopText + '</span></a></div>'); // add the controls to the DOM slider.controls.autoEl = $('<div class="soliloquy-controls-auto" />'); // bind click actions to the controls slider.controls.autoEl.on('click', '.soliloquy-start', clickStartBind); slider.controls.autoEl.on('click', '.soliloquy-stop', clickStopBind); // if autoControlsCombine, insert only the "start" control if(slider.settings.autoControlsCombine){ slider.controls.autoEl.append(slider.controls.start); // if autoControlsCombine is false, insert both controls }else{ slider.controls.autoEl.append(slider.controls.start).append(slider.controls.stop); } // if auto controls selector was supplied, populate it with the controls if(slider.settings.autoControlsSelector){ $(slider.settings.autoControlsSelector).html(slider.controls.autoEl); // if auto controls selector was not supplied, add it after the wrapper }else{ slider.controls.el.addClass('soliloquy-has-controls-auto').append(slider.controls.autoEl); } // update the auto controls updateAutoControls(slider.settings.autoStart ? 'stop' : 'start'); } /** * Appends image captions to the DOM */ var appendCaptions = function(){ // cycle through each child slider.children.each(function(index){ // get the image title attribute var title = $(this).find('img:first').attr('title'); // append the caption if (title != undefined && ('' + title).length) { $(this).append('<div class="soliloquy-caption"><span>' + title + '</span></div>'); } }); } /** * Click next binding * * @param e (event) * - DOM event object */ var clickNextBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); el.goToNextSlide(); e.preventDefault(); } /** * Click prev binding * * @param e (event) * - DOM event object */ var clickPrevBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); el.goToPrevSlide(); e.preventDefault(); } /** * Click start binding * * @param e (event) * - DOM event object */ var clickStartBind = function(e){ el.startAuto(); e.preventDefault(); } /** * Click stop binding * * @param e (event) * - DOM event object */ var clickStopBind = function(e){ el.stopAuto(); e.preventDefault(); } /** * Click pager binding * * @param e (event) * - DOM event object */ var clickPagerBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); var pagerLink = $(e.currentTarget); if(pagerLink.attr('data-slide-index') !== undefined){ var pagerIndex = parseInt(pagerLink.attr('data-slide-index')); // if clicked pager link is not active, continue with the goToSlide call if(pagerIndex != slider.active.index) el.goToSlide(pagerIndex); e.preventDefault(); } } /** * Updates the pager links with an active class * * @param slideIndex (int) * - index of slide to make active */ var updatePagerActive = function(slideIndex){ // if "short" pager type var len = slider.children.length; // nb of children if(slider.settings.pagerType == 'short'){ if(slider.settings.maxSlides > 1) { len = Math.ceil(slider.children.length/slider.settings.maxSlides); } slider.pagerEl.html( (slideIndex + 1) + slider.settings.pagerShortSeparator + len); return; } // remove all pager active classes slider.pagerEl.find('a').removeClass('active'); // apply the active class for all pagers slider.pagerEl.each(function(i, el) { $(el).find('a').eq(slideIndex).addClass('active'); }); } /** * Performs needed actions after a slide transition */ var updateAfterSlideTransition = function(){ // if infinte loop is true if(slider.settings.infiniteLoop){ var position = ''; // first slide if(slider.active.index == 0){ // set the new position position = slider.children.eq(0).position(); // carousel, last slide }else if(slider.active.index == getPagerQty() - 1 && slider.carousel){ position = slider.children.eq((getPagerQty() - 1) * getMoveBy()).position(); // last slide }else if(slider.active.index == slider.children.length - 1){ position = slider.children.eq(slider.children.length - 1).position(); } if(position){ if (slider.settings.mode == 'horizontal') { setPositionProperty(-position.left, 'reset', 0); } else if (slider.settings.mode == 'vertical') { setPositionProperty(-position.top, 'reset', 0); } } } // declare that the transition is complete slider.working = false; // Added by Thomas if(slider.settings.mode == 'fade'){ slider.viewport.css({overflow:''}); } // onSlideAfter callback slider.settings.onSlideAfter(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); } /** * Updates the auto controls state (either active, or combined switch) * * @param state (string) "start", "stop" * - the new state of the auto show */ var updateAutoControls = function(state){ // if autoControlsCombine is true, replace the current control with the new state if(slider.settings.autoControlsCombine){ if ( slider.controls.autoEl ) { slider.controls.autoEl.html(slider.controls[state]); } // if autoControlsCombine is false, apply the "active" class to the appropriate control }else{ slider.controls.autoEl.find('a').removeClass('active'); slider.controls.autoEl.find('a:not(.soliloquy-' + state + ')').addClass('active'); } } /** * Updates the direction controls (checks if either should be hidden) */ var updateDirectionControls = function(){ if(getPagerQty() == 1){ slider.controls.prev.addClass('disabled'); slider.controls.next.addClass('disabled'); }else if(!slider.settings.infiniteLoop && slider.settings.hideControlOnEnd){ // if first slide if (slider.active.index == 0){ slider.controls.prev.addClass('disabled'); slider.controls.next.removeClass('disabled'); // if last slide }else if(slider.active.index == getPagerQty() - 1){ slider.controls.next.addClass('disabled'); slider.controls.prev.removeClass('disabled'); // if any slide in the middle }else{ slider.controls.prev.removeClass('disabled'); slider.controls.next.removeClass('disabled'); } } } /** * Initialzes the auto process */ var initAuto = function(){ // if autoDelay was supplied, launch the auto show using a setTimeout() call if(slider.settings.autoDelay > 0){ var timeout = setTimeout(el.startAuto, slider.settings.autoDelay); // if autoDelay was not supplied, start the auto show normally }else{ el.startAuto(); } // if autoHover is requested if(slider.settings.autoHover){ // on el hover el.hover(function(){ // if the auto show is currently playing (has an active interval) if(slider.interval){ // stop the auto show and pass true agument which will prevent control update el.stopAuto(true); // create a new autoPaused value which will be used by the relative "mouseout" event slider.autoPaused = true; } }, function(){ // if the autoPaused value was created be the prior "mouseover" event if(slider.autoPaused){ // start the auto show and pass true agument which will prevent control update el.startAuto(true); // reset the autoPaused value slider.autoPaused = null; } }); } } /** * Initialzes the ticker process */ var initTicker = function(){ var startPosition = 0; // if autoDirection is "next", append a clone of the entire slider if(slider.settings.autoDirection == 'next'){ el.append(slider.children.clone().addClass('soliloquy-clone')); // if autoDirection is "prev", prepend a clone of the entire slider, and set the left position }else{ el.prepend(slider.children.clone().addClass('soliloquy-clone')); var position = slider.children.first().position(); startPosition = slider.settings.mode == 'horizontal' ? -position.left : -position.top; } setPositionProperty(startPosition, 'reset', 0); // do not allow controls in ticker mode slider.settings.pager = false; slider.settings.controls = false; slider.settings.autoControls = false; // if autoHover is requested if(slider.settings.tickerHover && !slider.usingCSS){ // on el hover slider.viewport.hover(function(){ el.stop(); }, function(){ // calculate the total width of children (used to calculate the speed ratio) var totalDimens = 0; slider.children.each(function(index){ totalDimens += slider.settings.mode == 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true); }); // calculate the speed ratio (used to determine the new speed to finish the paused animation) var ratio = slider.settings.speed / totalDimens; // determine which property to use var property = slider.settings.mode == 'horizontal' ? 'left' : 'top'; // calculate the new speed var newSpeed = ratio * (totalDimens - (Math.abs(parseInt(el.css(property))))); tickerLoop(newSpeed); }); } // start the ticker loop tickerLoop(); } /** * Runs a continuous loop, news ticker-style */ var tickerLoop = function(resumeSpeed){ speed = resumeSpeed ? resumeSpeed : slider.settings.speed; var position = {left: 0, top: 0}; var reset = {left: 0, top: 0}; // if "next" animate left position to last child, then reset left to 0 if(slider.settings.autoDirection == 'next'){ position = el.find('.soliloquy-clone').first().position(); // if "prev" animate left position to 0, then reset left to first non-clone child }else{ reset = slider.children.first().position(); } var animateProperty = slider.settings.mode == 'horizontal' ? -position.left : -position.top; var resetValue = slider.settings.mode == 'horizontal' ? -reset.left : -reset.top; var params = {resetValue: resetValue}; setPositionProperty(animateProperty, 'ticker', speed, params); } /** * Initializes touch events */ var initTouch = function(){ // initialize object to contain all touch values slider.touch = { start: {x: 0, y: 0}, end: {x: 0, y: 0} } slider.viewport.bind('touchstart', onTouchStart); } /** * Event handler for "touchstart" * * @param e (event) * - DOM event object */ var onTouchStart = function(e){ if(slider.working){ e.preventDefault(); }else{ // record the original position when touch starts slider.touch.originalPos = el.position(); var orig = e.originalEvent; // record the starting touch x, y coordinates slider.touch.start.x = orig.changedTouches[0].pageX; slider.touch.start.y = orig.changedTouches[0].pageY; // bind a "touchmove" event to the viewport slider.viewport.bind('touchmove', onTouchMove); // bind a "touchend" event to the viewport slider.viewport.bind('touchend', onTouchEnd); } } /** * Event handler for "touchmove" * * @param e (event) * - DOM event object */ var onTouchMove = function(e){ var orig = e.originalEvent; // if scrolling on y axis, do not prevent default var xMovement = Math.abs(orig.changedTouches[0].pageX - slider.touch.start.x); var yMovement = Math.abs(orig.changedTouches[0].pageY - slider.touch.start.y); // x axis swipe if((xMovement * 3) > yMovement && slider.settings.preventDefaultSwipeX){ e.preventDefault(); // y axis swipe }else if((yMovement * 3) > xMovement && slider.settings.preventDefaultSwipeY){ e.preventDefault(); } if(slider.settings.mode != 'fade' && slider.settings.oneToOneTouch){ var value = 0; // if horizontal, drag along x axis if(slider.settings.mode == 'horizontal'){ var change = orig.changedTouches[0].pageX - slider.touch.start.x; value = slider.touch.originalPos.left + change; // if vertical, drag along y axis }else{ var change = orig.changedTouches[0].pageY - slider.touch.start.y; value = slider.touch.originalPos.top + change; } setPositionProperty(value, 'reset', 0); } } /** * Event handler for "touchend" * * @param e (event) * - DOM event object */ var onTouchEnd = function(e){ slider.viewport.unbind('touchmove', onTouchMove); var orig = e.originalEvent; var value = 0; // record end x, y positions slider.touch.end.x = orig.changedTouches[0].pageX; slider.touch.end.y = orig.changedTouches[0].pageY; // if fade mode, check if absolute x distance clears the threshold if(slider.settings.mode == 'fade'){ var distance = Math.abs(slider.touch.start.x - slider.touch.end.x); if(distance >= slider.settings.swipeThreshold){ slider.touch.start.x > slider.touch.end.x ? el.goToNextSlide() : el.goToPrevSlide(); el.stopAuto(); } // not fade mode }else{ var distance = 0; // calculate distance and el's animate property if(slider.settings.mode == 'horizontal'){ distance = slider.touch.end.x - slider.touch.start.x; value = slider.touch.originalPos.left; }else{ distance = slider.touch.end.y - slider.touch.start.y; value = slider.touch.originalPos.top; } // if not infinite loop and first / last slide, do not attempt a slide transition if(!slider.settings.infiniteLoop && ((slider.active.index == 0 && distance > 0) || (slider.active.last && distance < 0))){ setPositionProperty(value, 'reset', 200); }else{ // check if distance clears threshold if(Math.abs(distance) >= slider.settings.swipeThreshold){ distance < 0 ? el.goToNextSlide() : el.goToPrevSlide(); el.stopAuto(); }else{ // el.animate(property, 200); setPositionProperty(value, 'reset', 200); } } } slider.viewport.unbind('touchend', onTouchEnd); } /** * Window resize event callback */ var resizeWindow = function(e){ // don't do anything if slider isn't initialized. if(!slider.initialized) return; // get the new window dimens (again, thank you IE) var windowWidthNew = $(window).width(); var windowHeightNew = $(window).height(); // make sure that it is a true window resize // *we must check this because our dinosaur friend IE fires a window resize event when certain DOM elements // are resized. Can you just die already?* if(windowWidth != windowWidthNew || windowHeight != windowHeightNew){ // set the new window dimens windowWidth = windowWidthNew; windowHeight = windowHeightNew; // update all dynamic elements el.redrawSlider(); // Call user resize handler slider.settings.onSliderResize.call(el, slider.active.index); } } /** * =================================================================================== * = PUBLIC FUNCTIONS * =================================================================================== */ /** * Performs slide transition to the specified slide * * @param slideIndex (int) * - the destination slide's index (zero-based) * * @param direction (string) * - INTERNAL USE ONLY - the direction of travel ("prev" / "next") */ el.goToSlide = function(slideIndex, direction){ // if plugin is currently in motion, ignore request if(slider.working || slider.active.index == slideIndex) return; // declare that plugin is in motion slider.working = true; // store the old index slider.oldIndex = slider.active.index; // if slideIndex is less than zero, set active index to last child (this happens during infinite loop) if(slideIndex < 0){ slider.active.index = getPagerQty() - 1; // if slideIndex is greater than children length, set active index to 0 (this happens during infinite loop) }else if(slideIndex >= getPagerQty()){ slider.active.index = 0; // set active index to requested slide }else{ slider.active.index = slideIndex; } // onSlideBefore, onSlideNext, onSlidePrev callbacks slider.settings.onSlideBefore(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); if(direction == 'next'){ slider.settings.onSlideNext(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); }else if(direction == 'prev'){ slider.settings.onSlidePrev(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); } // check if last slide slider.active.last = slider.active.index >= getPagerQty() - 1; // update the pager with active class if(slider.settings.pager) updatePagerActive(slider.active.index); // // check for direction control update if(slider.settings.controls) updateDirectionControls(); // if slider is set to mode: "fade" if(slider.settings.mode == 'fade'){ // Added by Thomas slider.viewport.css({overflow:'hidden'}); // if adaptiveHeight is true and next height is different from current height, animate to the new height if(slider.settings.adaptiveHeight && slider.viewport.height() != getViewportHeight()){ slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed); } // fade out the visible child and reset its z-index value slider.children.filter(':visible').fadeOut(slider.settings.speed).css({zIndex: 0}); // fade in the newly requested slide slider.children.eq(slider.active.index).css('zIndex', slider.settings.slideZIndex+1).fadeIn(slider.settings.speed, function(){ $(this).css('zIndex', slider.settings.slideZIndex); updateAfterSlideTransition(); }); // slider mode is not "fade" }else{ // if adaptiveHeight is true and next height is different from current height, animate to the new height if(slider.settings.adaptiveHeight && slider.viewport.height() != getViewportHeight()){ slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed); } var moveBy = 0; var position = {left: 0, top: 0}; // if carousel and not infinite loop if(!slider.settings.infiniteLoop && slider.carousel && slider.active.last){ if(slider.settings.mode == 'horizontal'){ // get the last child position var lastChild = slider.children.eq(slider.children.length - 1); position = lastChild.position(); // calculate the position of the last slide moveBy = slider.viewport.width() - lastChild.outerWidth(); }else{ // get last showing index position var lastShowingIndex = slider.children.length - slider.settings.minSlides; position = slider.children.eq(lastShowingIndex).position(); } // horizontal carousel, going previous while on first slide (infiniteLoop mode) }else if(slider.carousel && slider.active.last && direction == 'prev'){ // get the last child position var eq = slider.settings.moveSlides == 1 ? slider.settings.maxSlides - getMoveBy() : ((getPagerQty() - 1) * getMoveBy()) - (slider.children.length - slider.settings.maxSlides); var lastChild = el.children('.soliloquy-clone').eq(eq); position = lastChild.position(); // if infinite loop and "Next" is clicked on the last slide }else if(direction == 'next' && slider.active.index == 0){ // get the last clone position position = el.find('> .soliloquy-clone').eq(slider.settings.maxSlides).position(); slider.active.last = false; // normal non-zero requests }else if(slideIndex >= 0){ var requestEl = slideIndex * getMoveBy(); position = slider.children.eq(requestEl).position(); } /* If the position doesn't exist * (e.g. if you destroy the slider on a next click), * it doesn't throw an error. */ if ("undefined" !== typeof(position)) { var value = slider.settings.mode == 'horizontal' ? -(position.left - moveBy) : -position.top; // plugin values to be animated setPositionProperty(value, 'slide', slider.settings.speed); } } } /** * Transitions to the next slide in the show */ el.goToNextSlide = function(){ // if infiniteLoop is false and last page is showing, disregard call if (!slider.settings.infiniteLoop && slider.active.last) return; var pagerIndex = parseInt(slider.active.index) + 1; el.goToSlide(pagerIndex, 'next'); } /** * Transitions to the prev slide in the show */ el.goToPrevSlide = function(){ // if infiniteLoop is false and last page is showing, disregard call if (!slider.settings.infiniteLoop && slider.active.index == 0) return; var pagerIndex = parseInt(slider.active.index) - 1; el.goToSlide(pagerIndex, 'prev'); } /** * Starts the auto show * * @param preventControlUpdate (boolean) * - if true, auto controls state will not be updated */ el.startAuto = function(preventControlUpdate){ // if an interval already exists, disregard call if(slider.interval) return; // create an interval slider.interval = setInterval(function(){ slider.settings.autoDirection == 'next' ? el.goToNextSlide() : el.goToPrevSlide(); }, slider.settings.pause); // if auto controls are displayed and preventControlUpdate is not true if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('stop'); } /** * Stops the auto show * * @param preventControlUpdate (boolean) * - if true, auto controls state will not be updated */ el.stopAuto = function(preventControlUpdate){ // if no interval exists, disregard call if(!slider.interval) return; // clear the interval clearInterval(slider.interval); slider.interval = null; // if auto controls are displayed and preventControlUpdate is not true if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('start'); } /** * Returns current slide index (zero-based) */ el.getCurrentSlide = function(){ return slider.active.index; } /** * Returns current slide element */ el.getCurrentSlideElement = function(){ return slider.children.eq(slider.active.index); } /** * Returns number of slides in show */ el.getSlideCount = function(){ return slider.children.length; } /** * Update all dynamic slider elements */ el.redrawSlider = function(){ // resize all children in ratio to new screen size slider.children.add(el.find('.soliloquy-clone')).width(getSlideWidth()); // adjust the height slider.viewport.css('height', getViewportHeight()); // update the slide position if(!slider.settings.ticker) setSlidePosition(); // if active.last was true before the screen resize, we want // to keep it last no matter what screen size we end on if (slider.active.last) slider.active.index = getPagerQty() - 1; // if the active index (page) no longer exists due to the resize, simply set the index as last if (slider.active.index >= getPagerQty()) slider.active.last = true; // if a pager is being displayed and a custom pager is not being used, update it if(slider.settings.pager && !slider.settings.pagerCustom){ populatePager(); updatePagerActive(slider.active.index); } } /** * Destroy the current instance of the slider (revert everything back to original state) */ el.destroySlider = function(){ // don't do anything if slider has already been destroyed if(!slider.initialized) return; slider.initialized = false; $('.soliloquy-clone', this).remove(); slider.children.each(function() { $(this).data("origStyle") != undefined ? $(this).attr("style", $(this).data("origStyle")) : $(this).removeAttr('style'); }); $(this).data("origStyle") != undefined ? this.attr("style", $(this).data("origStyle")) : $(this).removeAttr('style'); $(this).unwrap().unwrap(); if(slider.controls.el) slider.controls.el.remove(); if(slider.controls.next) slider.controls.next.remove(); if(slider.controls.prev) slider.controls.prev.remove(); if(slider.pagerEl && slider.settings.controls) slider.pagerEl.remove(); $('.soliloquy-caption', this).remove(); if(slider.controls.autoEl) slider.controls.autoEl.remove(); clearInterval(slider.interval); if(slider.settings.responsive) $(window).unbind('resize', resizeWindow); } /** * Reload the slider (revert all DOM changes, and re-initialize) */ el.reloadSlider = function(settings){ if (settings != undefined) options = settings; el.destroySlider(); init(); } el.getSetting = function(setting){ if ( slider.settings[setting] ) { return slider.settings[setting]; } else { return false; } } init(); // returns the current jQuery object return this; } })(jQuery);
gpl-2.0
benetech/Secure-App-Generator
SecureAppGenerator/src/main/resources/static/Vellum/bower_components/jquery/src/var/indexOf.js
55
define(["./deletedIds"],function(a){return a.indexOf});
gpl-2.0
am-immanuel/quercus
modules/resin/src/com/caucho/jsp/JspPrecompileResource.java
7435
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.jsp; import com.caucho.config.ConfigException; import com.caucho.config.types.*; import com.caucho.env.thread.ThreadPool; import com.caucho.java.JavaCompilerUtil; import com.caucho.java.LineMap; import com.caucho.lifecycle.Lifecycle; import com.caucho.server.webapp.WebApp; import com.caucho.util.Alarm; import com.caucho.util.CompileException; import com.caucho.util.CurrentTime; import com.caucho.util.L10N; import com.caucho.vfs.Path; import com.caucho.vfs.Vfs; import javax.annotation.PostConstruct; import javax.servlet.jsp.JspFactory; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * Resource for precompiling all the *.jsp files on startup. */ public class JspPrecompileResource { private static final Logger log = Logger.getLogger(JspPrecompileResource.class.getName()); private static final L10N L = new L10N(JspPrecompileResource.class); private FileSetType _fileSet; private WebApp _webApp; private final Lifecycle _lifecycle = new Lifecycle(); private int _threadCount = 2; private int _completeCount; private long _timeout = 60000L; /** * Sets the webApp. */ public void setWebApp(WebApp app) { _webApp = app; } /** * Add a pattern. */ public FileSetType createFileset() { if (_fileSet == null) { _fileSet = new FileSetType(); _fileSet.setDir(Vfs.lookup()); } return _fileSet; } /** * @deprecated */ public FileSetType createFileSet() { return createFileset(); } /** * Sets the number of threads to spawn. */ public void setThreadCount(int count) { if (count < 1) count = 1; _threadCount = count; } /** * Set the time to wait for compilation to complete */ public void setTimeoutMs(long timeout) { _timeout = timeout; } /** * Initialize the resource. */ @PostConstruct public void init() throws ConfigException { Path pwd = Vfs.lookup(); if (_fileSet == null) { createFileset().addInclude(new PathPatternType("**/*.jsp")); } if (_webApp == null) { _webApp = WebApp.getLocal(); } if (_webApp == null) throw new ConfigException(L.l("JspPrecompileResource must be used in a web-app context.")); start(); } /** * Starts the resource. */ public void start() { if (! _lifecycle.toActive()) return; // JspManager manager = new JspManager(_webApp); if (JspFactory.getDefaultFactory() == null) JspFactory.setDefaultFactory(new QJspFactory()); ArrayList<Path> paths = _fileSet.getPaths(); ArrayList<String> classes = new ArrayList<String>(); for (int i = 0; i < _threadCount; i++) { CompileTask task = new CompileTask(paths, classes); ThreadPool.getThreadPool().schedule(task); } long expire = CurrentTime.getCurrentTime() + _timeout; synchronized (this) { while (_completeCount < _threadCount) { try { long timeout = expire - CurrentTime.getCurrentTime(); if (timeout <= 0) { log.fine(this.getClass().getSimpleName() + " timeout occured"); return; } wait(timeout); } catch (Exception e) { } } } } class CompileTask implements Runnable { private int _chunkCount; private ArrayList<Path> _paths; private ArrayList<String> _classes; private JspCompiler _compiler; CompileTask(ArrayList<Path> paths, ArrayList<String> classes) { _paths = paths; _classes = classes; synchronized (_paths) { _chunkCount = (_paths.size() + _threadCount) / _threadCount; } _compiler = new JspCompiler(); _compiler.setWebApp(_webApp); } public void run() { try { while (compilePath()) { } while (compileClasses()) { } } finally { synchronized (JspPrecompileResource.this) { _completeCount++; JspPrecompileResource.this.notifyAll(); } } } private boolean compilePath() { String contextPath = _webApp.getContextPath(); if (! contextPath.endsWith("/")) contextPath = contextPath + "/"; Path pwd = Vfs.lookup(); Path path = null; synchronized (_paths) { if (_paths.size() == 0) return false; path = _paths.remove(0); } String uri = path.getPath().substring(pwd.getPath().length()); if (_webApp.getContext(contextPath + uri) != _webApp) return true; String className = JspCompiler.urlToClassName(uri); try { CauchoPage page = (CauchoPage) _compiler.loadClass(className, true); page.init(pwd); if (! page._caucho_isModified()) { log.fine("pre-loaded " + uri); return true; } } catch (ClassNotFoundException e) { } catch (Throwable e) { log.log(Level.FINER, e.toString(), e); } log.fine("compiling " + uri); try { JspCompilerInstance compilerInst; compilerInst = _compiler.getCompilerInstance(path, uri, className); JspGenerator generator = compilerInst.generate(); if (generator.isStatic()) return true; LineMap lineMap = generator.getLineMap(); synchronized (_classes) { _classes.add(className.replace('.', '/') + ".java"); } } catch (Exception e) { if (e instanceof CompileException) log.warning(e.getMessage()); else log.log(Level.WARNING, e.toString(), e); } return true; } private boolean compileClasses() { String []files; synchronized (_classes) { if (_classes.size() == 0) return false; files = new String[_classes.size()]; _classes.toArray(files); _classes.clear(); } try { JavaCompilerUtil javaCompiler = JavaCompilerUtil.create(null); javaCompiler.setClassDir(_compiler.getClassDir()); javaCompiler.compileBatch(files); } catch (Exception e) { if (e instanceof CompileException) log.warning(e.getMessage()); else log.log(Level.WARNING, e.toString(), e); } return true; } } }
gpl-2.0
lian88jian/Mycat-Server
src/main/java/io/mycat/backend/mysql/nio/handler/CommitNodeHandler.java
5326
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.backend.mysql.nio.handler; import java.util.List; import io.mycat.backend.mysql.xa.TxState; import io.mycat.config.ErrorCode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.mycat.backend.BackendConnection; import io.mycat.backend.mysql.nio.MySQLConnection; import io.mycat.net.mysql.ErrorPacket; import io.mycat.server.NonBlockingSession; import io.mycat.server.ServerConnection; /** * @author mycat */ public class CommitNodeHandler implements ResponseHandler { private static final Logger LOGGER = LoggerFactory .getLogger(CommitNodeHandler.class); private final NonBlockingSession session; public CommitNodeHandler(NonBlockingSession session) { this.session = session; } public void commit(BackendConnection conn) { conn.setResponseHandler(CommitNodeHandler.this); boolean isClosed=conn.isClosedOrQuit(); if(isClosed) { session.getSource().writeErrMessage(ErrorCode.ER_UNKNOWN_ERROR, "receive commit,but find backend con is closed or quit"); LOGGER.error( conn+"receive commit,but fond backend con is closed or quit"); } if(conn instanceof MySQLConnection) { MySQLConnection mysqlCon = (MySQLConnection) conn; if (mysqlCon.getXaStatus() == 1) { String xaTxId = session.getXaTXID()+",'"+mysqlCon.getSchema()+"'"; String[] cmds = new String[]{"XA END " + xaTxId, "XA PREPARE " + xaTxId}; mysqlCon.execBatchCmd(cmds); } else { conn.commit(); } }else { conn.commit(); } } @Override public void connectionAcquired(BackendConnection conn) { LOGGER.error("unexpected invocation: connectionAcquired from commit"); } @Override public void okResponse(byte[] ok, BackendConnection conn) { if(conn instanceof MySQLConnection) { MySQLConnection mysqlCon = (MySQLConnection) conn; switch (mysqlCon.getXaStatus()) { case TxState.TX_STARTED_STATE: if (mysqlCon.batchCmdFinished()) { String xaTxId = session.getXaTXID()+",'"+mysqlCon.getSchema()+"'"; mysqlCon.execCmd("XA COMMIT " + xaTxId); mysqlCon.setXaStatus(TxState.TX_PREPARED_STATE); } return; case TxState.TX_PREPARED_STATE: { mysqlCon.setXaStatus(TxState.TX_INITIALIZE_STATE); break; } default: // LOGGER.error("Wrong XA status flag!"); } /* 1. 事务提交后,xa 事务结束 */ if(TxState.TX_INITIALIZE_STATE==mysqlCon.getXaStatus()){ if(session.getXaTXID()!=null){ session.setXATXEnabled(false); } } } /* 2. preAcStates 为true,事务结束后,需要设置为true。preAcStates 为ac上一个状态 */ if(session.getSource().isPreAcStates()&&!session.getSource().isAutocommit()){ session.getSource().setAutocommit(true); } session.clearResources(false); ServerConnection source = session.getSource(); source.write(ok); } @Override public void errorResponse(byte[] err, BackendConnection conn) { ErrorPacket errPkg = new ErrorPacket(); errPkg.read(err); String errInfo = new String(errPkg.message); session.getSource().setTxInterrupt(errInfo); errPkg.write(session.getSource()); } @Override public void rowEofResponse(byte[] eof, BackendConnection conn) { LOGGER.error(new StringBuilder().append("unexpected packet for ") .append(conn).append(" bound by ").append(session.getSource()) .append(": field's eof").toString()); } @Override public void fieldEofResponse(byte[] header, List<byte[]> fields, byte[] eof, BackendConnection conn) { LOGGER.error(new StringBuilder().append("unexpected packet for ") .append(conn).append(" bound by ").append(session.getSource()) .append(": field's eof").toString()); } @Override public void rowResponse(byte[] row, BackendConnection conn) { LOGGER.warn(new StringBuilder().append("unexpected packet for ") .append(conn).append(" bound by ").append(session.getSource()) .append(": row data packet").toString()); } @Override public void writeQueueAvailable() { } @Override public void connectionError(Throwable e, BackendConnection conn) { } @Override public void connectionClose(BackendConnection conn, String reason) { } }
gpl-2.0
Lsty/ygopro-scripts
c56804361.lua
1204
--魔装聖龍 イーサルウェポン function c56804361.initial_effect(c) --tohand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(56804361,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCountLimit(1,56804361) e1:SetCondition(c56804361.condition) e1:SetTarget(c56804361.target) e1:SetOperation(c56804361.operation) c:RegisterEffect(e1) end function c56804361.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetSummonType()==SUMMON_TYPE_PENDULUM end function c56804361.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and chkc:IsAbleToHand() end if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToHand,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND) local g=Duel.SelectTarget(tp,Card.IsAbleToHand,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c56804361.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) end end
gpl-2.0
yarwalker/ecobyt
wp-content/plugins/woocommerce-jetpack/includes/price-by-country/class-wcj-price-by-country-group-generator.php
4511
<?php /** * WooCommerce Jetpack Price By Country Group Generator * * The WooCommerce Jetpack Price By Country Group Generator class. * * @version 2.3.9 * @author Algoritmika Ltd. */ if ( ! defined( 'ABSPATH' ) ) exit; if ( ! class_exists( 'WCJ_Price_By_Country_Group_Generator' ) ) : class WCJ_Price_By_Country_Group_Generator { /** * Constructor. * * @version 2.3.9 */ function __construct() { require_once( 'wcj-country-currency.php' ); add_action( 'woocommerce_init', array( $this, 'create_all_countries_groups' ) ); } /** * get_currency_countries. * * @version 2.3.9 */ function get_currency_countries( $limit_currencies = '' ) { $country_currency = wcj_get_country_currency(); if ( '' != $limit_currencies ) { $default_currency = get_woocommerce_currency(); if ( 'paypal_only' === $limit_currencies || 'paypal_and_yahoo_exchange_rates_only' === $limit_currencies ) { $paypal_supported_currencies = wcj_get_paypal_supported_currencies(); } if ( 'yahoo_exchange_rates_only' === $limit_currencies || 'paypal_and_yahoo_exchange_rates_only' === $limit_currencies ) { $yahoo_exchange_rates_supported_currencies = wcj_get_yahoo_exchange_rates_supported_currency(); } } $currencies = array(); foreach ( $country_currency as $country => $currency ) { if ( 'paypal_only' === $limit_currencies ) { if ( ! isset( $paypal_supported_currencies[ $currency ] ) ) { $currency = $default_currency; } } elseif ( 'yahoo_exchange_rates_only' === $limit_currencies ) { if ( ! isset( $yahoo_exchange_rates_supported_currencies[ $currency ] ) ) { $currency = $default_currency; } } elseif ( 'paypal_and_yahoo_exchange_rates_only' === $limit_currencies ) { if ( ! isset( $paypal_supported_currencies[ $currency ] ) || ! isset( $yahoo_exchange_rates_supported_currencies[ $currency ] ) ) { $currency = $default_currency; } } $currencies[ $currency ][] = $country; } return $currencies; } /** * create_all_countries_groups. * * @version 2.3.9 */ function create_all_countries_groups() { global $wcj_notice; if ( ! isset( $_GET['wcj_generate_country_groups'] ) ) { return; } if ( isset( $_POST['save'] ) ) { return; } if ( /* ! is_admin() || */ ! is_super_admin() || 1 === apply_filters( 'wcj_get_option_filter', 1, '' ) ) { $wcj_notice = __( 'Create All Country Groups Failed.', 'woocommerce-jetpack' ); return; } switch ( $_GET['wcj_generate_country_groups'] ) { case 'all': case 'paypal_only': case 'yahoo_exchange_rates_only': case 'paypal_and_yahoo_exchange_rates_only': $currencies = $this->get_currency_countries( $_GET['wcj_generate_country_groups'] ); break; default: $wcj_notice = __( 'Create All Country Groups Failed. Wrong parameter.', 'woocommerce-jetpack' ); return; } $number_of_groups = count( $currencies ); if ( ! isset( $_GET['wcj_generate_country_groups_confirm'] ) ) { $wcj_notice .= sprintf( __( 'All existing country groups will be deleted and %s new groups will be created. Are you sure?', 'woocommerce-jetpack' ), $number_of_groups ); $wcj_notice .= ' ' . '<a style="color: red !important;" href="' . add_query_arg( 'wcj_generate_country_groups_confirm', 'yes' ) . '">' . __( 'Confirm', 'woocommerce-jetpack' ) . '</a>.'; //$_GET['wc_message'] = __( 'Are you sure? Confirm.', 'woocommerce-jetpack' ); /* $wcj_notice .= '<p>'; $wcj_notice .= __( 'Preview', 'woocommerce-jetpack' ) . '<br>'; foreach ( $currencies as $group_currency => $countries ) { $wcj_notice .= $group_currency . ' - ' . implode( ',', $countries ) . '<br>'; } $wcj_notice .= '</p>'; */ } else { update_option( 'wcj_price_by_country_total_groups_number', $number_of_groups ); $i = 0; foreach ( $currencies as $group_currency => $countries ) { $i++; update_option( 'wcj_price_by_country_exchange_rate_countries_group_' . $i, implode( ',', $countries ) ); update_option( 'wcj_price_by_country_exchange_rate_currency_group_' . $i, $group_currency ); update_option( 'wcj_price_by_country_exchange_rate_group_' . $i, 1 ); update_option( 'wcj_price_by_country_make_empty_price_group_' . $i, 'no' ); } $wcj_notice = __( 'Country Groups Generated.', 'woocommerce-jetpack' ); } } } endif; return new WCJ_Price_By_Country_Group_Generator();
gpl-2.0
SparklingSoftware/dokuwiki_almlib_ready_legacy
lib/plugins/swiftmail/admin.php
1996
<?php /** * Swiftmail Plugin * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> */ // must be run within Dokuwiki if(!defined('DOKU_INC')) die(); class admin_plugin_swiftmail extends DokuWiki_Admin_Plugin { /** * return sort order for position in admin menu */ function getMenuSort() { return 200; } /** * handle user request */ function handle() { global $INPUT; global $conf; if(!$INPUT->bool('send')) return; // make sure debugging is on; $conf['plugin']['swiftmail']['debug'] = 1; // send a mail $mail = new Mailer(); if($INPUT->str('to')) $mail->to($INPUT->str('to')); if($INPUT->str('cc')) $mail->to($INPUT->str('cc')); if($INPUT->str('bcc')) $mail->to($INPUT->str('bcc')); $mail->subject('SwiftMail Plugin says hello'); $mail->setBody("Hi @USER@\n\nThis is a test from @DOKUWIKIURL@"); $ok = $mail->send(); // check result if($ok){ msg('Message was sent. Swiftmail seems to work.',1); }else{ msg('Message wasn\'t sent. Swiftmail seems not to work properly.',-1); } } /** * Output HTML form */ function html() { global $INPUT; global $conf; echo $this->locale_xhtml('intro'); if(!$conf['mailfrom']) msg($this->getLang('nofrom'),-1); $form = new Doku_Form(array()); $form->startFieldset('Testmail'); $form->addHidden('send', 1); $form->addElement(form_makeField('text', 'to', $INPUT->str('to'), 'To:', '', 'block')); $form->addElement(form_makeField('text', 'cc', $INPUT->str('cc'), 'Cc:', '', 'block')); $form->addElement(form_makeField('text', 'bcc', $INPUT->str('bcc'), 'Bcc:', '', 'block')); $form->addElement(form_makeButton('submit', '', 'Send Email')); $form->printForm(); } }
gpl-2.0
quanghung0404/it2tech
media/com_easysocial/apps/user/photos/themes/default/emails/html/like.album.involved.php
3086
<?php /** * @package EasySocial * @copyright Copyright (C) 2010 - 2014 Stack Ideas Sdn Bhd. All rights reserved. * @license GNU/GPL, see LICENSE.php * EasySocial is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ defined( '_JEXEC' ) or die( 'Unauthorized Access' ); ?> <tr> <td style="text-align: center;padding: 40px 10px 0;"> <div style="margin-bottom:15px;"> <div style="font-family:Arial;font-size:32px;font-weight:normal;color:#333;display:block; margin: 4px 0"> <?php echo JText::sprintf('APP_USER_PHOTOS_EMAILS_LIKE_ALBUM_INVOLVED_HEADING', $actor); ?> </div> </div> </td> </tr> <tr> <td style="text-align: center;font-size:12px;color:#888"> <div style="margin:30px auto;text-align:center;display:block"> <img src="<?php echo rtrim( JURI::root() , '/' );?>/components/com_easysocial/themes/wireframe/images/emails/divider.png" alt="<?php echo JText::_( 'divider' );?>" /> </div> <table width="540" cellspacing="0" cellpadding="0" border="0" align="center"> <tr> <td> <p style="text-align:left;"> <?php echo JText::_('COM_EASYSOCIAL_EMAILS_HELLO'); ?> <?php echo $recipientName; ?>, </p> <p style="text-align:left;"> <?php echo JText::sprintf('APP_USER_PHOTOS_EMAILS_LIKE_ALBUM_INVOLVED_CONTENT' , $actor);?> </p> </td> </tr> </table> <table width="540" cellspacing="0" cellpadding="0" border="0" align="center" style="margin: 20px auto 0;background-color:#f8f9fb;padding:15px 20px;"> <tbody> <tr> <td valign="top" align="left" width="30%"> <a href="<?php echo $albumPermalink;?>"><img src="<?php echo $albumCover;?>" alt="<?php echo $this->html( 'string.escape' , $albumTitle );?>" style="" width="128" /></a> </td> <td valign="top" style="color:#888;background-color:#f8f9fb;text-align:left;"> <p style="margin:0 0 5px;font-weight:bold;font-size:13px;"> <a href="<?php echo $albumPermalink;?>" style="color:#888;text-decoration:none;"><?php echo $albumTitle;?></a> </p> </td> </tr> </tbody> </table> <a style=" display:inline-block; text-decoration:none; font-weight:bold; margin-top: 20px; padding:10px 15px; line-height:20px; color:#fff;font-size: 12px; background-color: #83B3DD; background-image: linear-gradient(to bottom, #91C2EA, #6D9CCA); background-repeat: repeat-x; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); border-style: solid; border-width: 1px; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05); border-radius:2px; -moz-border-radius:2px; -webkit-border-radius:2px; " href="<?php echo $albumPermalink;?>"><?php echo JText::_('COM_EASYSOCIAL_EMAILS_VIEW_ALBUM');?></a> </td> </tr>
gpl-2.0
PlanetAPL/a-plus
src/MSGUI/MSKeyPress.C
2587
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 1998-2008 Morgan Stanley All rights reserved. // See .../src/LICENSE for terms of distribution // // /////////////////////////////////////////////////////////////////////////////// #include <MSGUI/MSKeyPress.H> #include <string.h> static char *keyTokens[]={"None","Shift","Lock","Ctrl","Meta","NumLck"}; static int keyMasks[]={MSKeyPress::NoneKeyMask, MSKeyPress::ShiftKeyMask, MSKeyPress::LockKeyMask, MSKeyPress::ControlKeyMask, MSKeyPress::MetaKeyMask, MSKeyPress::NumLockMask}; static const int NumTokens=6; static char *tokenString="<Key>"; MSKeyPress::MSKeyPress(const char* pString_) { unsigned int mask; translate(pString_,_keysym,mask,_state); } MSKeyPress::MSKeyPress(KeySym keysym_,unsigned int state_): _state(state_), _keysym(keysym_){} MSKeyPress::~MSKeyPress(){} MSBoolean MSKeyPress::isMatch(KeySym keysym_, unsigned int state_) const { return ( keysym_ == _keysym && state_ == _state)? MSTrue:MSFalse;} MSBoolean MSKeyPress::isMatch(const char* pString_) const { KeySym keySym; unsigned int mask, flag; translate(pString_,keySym,mask,flag); return isMatch(keysym(),state(),keySym,mask,flag); } void MSKeyPress::translate(const char *pString_,KeySym &keysym_, unsigned int &mask_, unsigned int &flag_) { mask_=0; flag_=0; keysym_=0; if (pString_!=0) { char *pString; for (int i=0;i<NumTokens;i++) { // cast is for bug in Borland if ((pString=strstr((char*)(void*)pString_,keyTokens[i]))!= 0) { mask_+=keyMasks[i]; if (pString==pString_) flag_+=keyMasks[i]; // check for beginning of string else if (*(pString-1)!='~') flag_+=keyMasks[i]; // check for negation character } } if (pString_[0]=='!') mask_=ExactMask; // require an exact match // cast is for bug in Borland if ((pString=strstr((char*)(void*)pString_,tokenString))!=0) { keysym_=XStringToKeysym(pString+5); if (keysym_>=0x61&&keysym_<=0x7a&&(mask_&ShiftKeyMask)==ShiftKeyMask) { keysym_-=0x20; // uppercase-X will send 'Q' not 'q' with Shift down } } else mask_+=ALL; } } MSBoolean MSKeyPress::isMatch(KeySym keysym1_,unsigned int state_, KeySym keysym2_,unsigned int mask_, unsigned int flag_) { if (mask_&ExactMask) return (state_==( flag_ & ~(ALL)) && ((ALL&mask_)||keysym1_==keysym2_))?MSTrue:MSFalse; else return ((state_&mask_)==flag_&& ((ALL&mask_)||keysym1_==keysym2_))?MSTrue:MSFalse; }
gpl-2.0
Seanhunt/letmrack.com
wp-content/themes/Marina/twitter.php
11269
<?php /* Plugin Name: Twitter for Wordpress Version: 1.9.7 Plugin URI: http://rick.jinlabs.com/code/twitter Description: Displays your public Twitter messages for all to read. Based on <a href="http://cavemonkey50.com/code/pownce/">Pownce for Wordpress</a> by <a href="http://cavemonkey50.com/">Cavemonkey50</a>. Author: Ricardo Gonz&aacute;lez Author URI: http://rick.jinlabs.com/ */ /* Copyright 2007 Ricardo González Castro (rick[in]jinlabs.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ define('MAGPIE_CACHE_ON', 1); //2.7 Cache Bug define('MAGPIE_CACHE_AGE', 180); define('MAGPIE_INPUT_ENCODING', 'UTF-8'); define('MAGPIE_OUTPUT_ENCODING', 'UTF-8'); $twitter_options['widget_fields']['title'] = array('label'=>'Title:', 'type'=>'text', 'default'=>''); $twitter_options['widget_fields']['username'] = array('label'=>'Username:', 'type'=>'text', 'default'=>''); $twitter_options['widget_fields']['num'] = array('label'=>'Number of links:', 'type'=>'text', 'default'=>'5'); $twitter_options['widget_fields']['update'] = array('label'=>'Show timestamps:', 'type'=>'checkbox', 'default'=>true); $twitter_options['widget_fields']['linked'] = array('label'=>'Linked:', 'type'=>'text', 'default'=>'#'); $twitter_options['widget_fields']['hyperlinks'] = array('label'=>'Discover Hyperlinks:', 'type'=>'checkbox', 'default'=>true); $twitter_options['widget_fields']['twitter_users'] = array('label'=>'Discover @replies:', 'type'=>'checkbox', 'default'=>true); $twitter_options['widget_fields']['encode_utf8'] = array('label'=>'UTF8 Encode:', 'type'=>'checkbox', 'default'=>false); $twitter_options['prefix'] = 'twitter'; // Display Twitter messages function twitter_messages($username = '', $num = 5, $list = false, $update = true, $linked = '#', $hyperlinks = true, $twitter_users = true, $encode_utf8 = false) { global $twitter_options; include_once(ABSPATH . WPINC . '/rss.php'); $messages = fetch_rss('http://twitter.com/statuses/user_timeline/'.$username.'.rss'); if ($list) echo '<ul class="twitter">'; if ($username == '') { if ($list) echo '<li>'; echo 'RSS not configured'; if ($list) echo '</li>'; } else { if ( empty($messages->items) ) { if ($list) echo '<li>'; echo 'No public Twitter messages.'; if ($list) echo '</li>'; } else { $i = 0; foreach ( $messages->items as $message ) { $msg = " ".substr(strstr($message['description'],': '), 2, strlen($message['description']))." "; if($encode_utf8) $msg = utf8_encode($msg); $link = $message['link']; if ($list) echo '<li class="twitter-item">'; elseif ($num != 1) echo '<p class="twitter-message">'; if ($hyperlinks) { $msg = hyperlinks($msg); } if ($twitter_users) { $msg = twitter_users($msg); } if ($linked != '' || $linked != false) { if($linked == 'all') { $msg = '<a href="'.$link.'" class="twitter-link">'.$msg.'</a>'; // Puts a link to the status of each tweet } else { $msg = $msg . '<a href="'.$link.'" class="twitter-link">'.$linked.'</a>'; // Puts a link to the status of each tweet } } echo $msg; if($update) { $time = strtotime($message['pubdate']); if ( ( abs( time() - $time) ) < 86400 ) $h_time = sprintf( __('%s ago'), human_time_diff( $time ) ); else $h_time = date(__('Y/m/d'), $time); echo sprintf( __('%s', 'twitter-for-wordpress'),' <span class="twitter-timestamp"><abbr title="' . date(__('Y/m/d H:i:s'), $time) . '">' . $h_time . '</abbr></span>' ); } if ($list) echo '</li>'; elseif ($num != 1) echo '</p>'; $i++; if ( $i >= $num ) break; } } } if ($list) echo '</ul>'; } // Link discover stuff function hyperlinks($text) { // Props to Allen Shaw & webmancers.com // match protocol://address/path/file.extension?some=variable&another=asf% //$text = preg_replace("/\b([a-zA-Z]+:\/\/[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)\b/i","<a href=\"$1\" class=\"twitter-link\">$1</a>", $text); $text = preg_replace('/\b([a-zA-Z]+:\/\/[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"<a href=\"$1\" class=\"twitter-link\">$1</a>", $text); // match www.something.domain/path/file.extension?some=variable&another=asf% //$text = preg_replace("/\b(www\.[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)\b/i","<a href=\"http://$1\" class=\"twitter-link\">$1</a>", $text); $text = preg_replace('/\b(?<!:\/\/)(www\.[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"<a href=\"http://$1\" class=\"twitter-link\">$1</a>", $text); // match name@address $text = preg_replace("/\b([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})\b/i","<a href=\"mailto://$1\" class=\"twitter-link\">$1</a>", $text); //mach #trendingtopics. Props to Michael Voigt $text = preg_replace('/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)#{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i', "$1<a href=\"http://twitter.com/#search?q=$2\" class=\"twitter-link\">#$2</a>$3 ", $text); return $text; } function twitter_users($text) { $text = preg_replace('/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)@{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i', "$1<a href=\"http://twitter.com/$2\" class=\"twitter-user\">@$2</a>$3 ", $text); return $text; } // Twitter widget stuff function widget_twitter_init() { if ( !function_exists('register_sidebar_widget') ) return; $check_options = get_option('widget_twitter'); if ($check_options['number']=='') { $check_options['number'] = 1; update_option('widget_twitter', $check_options); } function widget_twitter($args, $number = 1) { global $twitter_options; // $args is an array of strings that help widgets to conform to // the active theme: before_widget, before_title, after_widget, // and after_title are the array keys. Default tags: li and h2. extract($args); // Each widget can store its own options. We keep strings here. include_once(ABSPATH . WPINC . '/rss.php'); $options = get_option('widget_twitter'); // fill options with default values if value is not set $item = $options[$number]; foreach($twitter_options['widget_fields'] as $key => $field) { if (! isset($item[$key])) { $item[$key] = $field['default']; } } $messages = fetch_rss('http://twitter.com/statuses/user_timeline/'.$item['username'].'.rss'); // These lines generate our output. echo $before_widget . $before_title . '<a href="http://twitter.com/' . $item['username'] . '" class="twitter_title_link">'. $item['title'] . '</a>' . $after_title; twitter_messages($item['username'], $item['num'], true, $item['update'], $item['linked'], $item['hyperlinks'], $item['twitter_users'], $item['encode_utf8']); echo $after_widget; } // This is the function that outputs the form to let the users edit // the widget's title. It's an optional feature that users cry for. function widget_twitter_control($number) { global $twitter_options; // Get our options and see if we're handling a form submission. $options = get_option('widget_twitter'); if ( isset($_POST['twitter-submit']) ) { foreach($twitter_options['widget_fields'] as $key => $field) { $options[$number][$key] = $field['default']; $field_name = sprintf('%s_%s_%s', $twitter_options['prefix'], $key, $number); if ($field['type'] == 'text') { $options[$number][$key] = strip_tags(stripslashes($_POST[$field_name])); } elseif ($field['type'] == 'checkbox') { $options[$number][$key] = isset($_POST[$field_name]); } } update_option('widget_twitter', $options); } foreach($twitter_options['widget_fields'] as $key => $field) { $field_name = sprintf('%s_%s_%s', $twitter_options['prefix'], $key, $number); $field_checked = ''; if ($field['type'] == 'text') { $field_value = htmlspecialchars($options[$number][$key], ENT_QUOTES); } elseif ($field['type'] == 'checkbox') { $field_value = 1; if (! empty($options[$number][$key])) { $field_checked = 'checked="checked"'; } } printf('<p style="text-align:right;" class="twitter_field"><label for="%s">%s <input id="%s" name="%s" type="%s" value="%s" class="%s" %s /></label></p>', $field_name, __($field['label']), $field_name, $field_name, $field['type'], $field_value, $field['type'], $field_checked); } echo '<input type="hidden" id="twitter-submit" name="twitter-submit" value="1" />'; } function widget_twitter_setup() { $options = $newoptions = get_option('widget_twitter'); if ( isset($_POST['twitter-number-submit']) ) { $number = (int) $_POST['twitter-number']; $newoptions['number'] = $number; } if ( $options != $newoptions ) { update_option('widget_twitter', $newoptions); widget_twitter_register(); } } function widget_twitter_page() { $options = $newoptions = get_option('widget_twitter'); ?> <div class="wrap"> <form method="POST"> <h2><?php _e('Twitter Widgets'); ?></h2> <p style="line-height: 30px;"><?php _e('How many Twitter widgets would you like?'); ?> <select id="twitter-number" name="twitter-number" value="<?php echo $options['number']; ?>"> <?php for ( $i = 1; $i < 10; ++$i ) echo "<option value='$i' ".($options['number']==$i ? "selected='selected'" : '').">$i</option>"; ?> </select> <span class="submit"><input type="submit" name="twitter-number-submit" id="twitter-number-submit" value="<?php echo attribute_escape(__('Save')); ?>" /></span></p> </form> </div> <?php } function widget_twitter_register() { $options = get_option('widget_twitter'); $dims = array('width' => 300, 'height' => 300); $class = array('classname' => 'widget_twitter'); for ($i = 1; $i <= 9; $i++) { $name = sprintf(__('Twitter #%d'), $i); $id = "twitter-$i"; // Never never never translate an id wp_register_sidebar_widget($id, $name, $i <= $options['number'] ? 'widget_twitter' : /* unregister */ '', $class, $i); wp_register_widget_control($id, $name, $i <= $options['number'] ? 'widget_twitter_control' : /* unregister */ '', $dims, $i); } add_action('sidebar_admin_setup', 'widget_twitter_setup'); add_action('sidebar_admin_page', 'widget_twitter_page'); } widget_twitter_register(); } // Run our code later in case this loads prior to any required plugins. add_action('widgets_init', 'widget_twitter_init'); ?>
gpl-2.0
VikaCep/mediawiki-nodos
extensions/SemanticMediaWiki/tests/phpunit/Unit/ParserParameterProcessorTest.php
5803
<?php namespace SMW\Tests; use SMW\ParserParameterProcessor; /** * @covers \SMW\ParserParameterProcessor * @group semantic-mediawiki * * @license GNU GPL v2+ * @since 1.9 * * @author mwjames */ class ParserParameterProcessorTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider parametersDataProvider */ public function testCanConstruct( array $parameters ) { $this->assertInstanceOf( 'SMW\ParserParameterProcessor', new ParserParameterProcessor( $parameters ) ); } /** * @dataProvider parametersDataProvider */ public function testGetRaw( array $parameters ) { $instance = new ParserParameterProcessor( $parameters ); $this->assertEquals( $parameters, $instance->getRaw() ); } public function testSetParameters() { $instance = new ParserParameterProcessor(); $parameters = array( 'Foo' => 'Bar' ); $instance->setParameters( $parameters ); $this->assertEquals( $parameters, $instance->toArray() ); } public function testAddParameter() { $instance = new ParserParameterProcessor(); $instance->addParameter( 'Foo', 'Bar' ); $this->assertEquals( array( 'Foo' => array( 'Bar' ) ), $instance->toArray() ); } public function testSetParameter() { $instance = new ParserParameterProcessor(); $instance->setParameter( 'Foo', array() ); $this->assertEmpty( $instance->toArray() ); $instance->setParameter( 'Foo', array( 'Bar' ) ); $this->assertEquals( array( 'Foo' => array( 'Bar' ) ), $instance->toArray() ); } /** * @dataProvider parametersDataProvider */ public function testToArray( array $parameters, array $expected ) { $instance = new ParserParameterProcessor( $parameters ); $this->assertEquals( $expected, $instance->toArray() ); } /** * @dataProvider firstParameterDataProvider */ public function testGetFirst( array $parameters, array $expected ) { $instance = new ParserParameterProcessor( $parameters ); $this->assertEquals( $expected['identifier'], $instance->getFirst() ); } public function parametersDataProvider() { return array( // {{#...: // |Has test 1=One // }} array( array( 'Has test 1=One' ), array( 'Has test 1' => array( 'One' ) ) ), // {{#...: // |Has test 1=One // }} array( array( array( 'Foo' ), 'Has test 1=One', ), array( 'Has test 1' => array( 'One' ) ), array( 'msg' => 'Failed to recognize that only strings can be processed' ) ), // {{#...: // |Has test 2=Two // |Has test 2=Three;Four|+sep=; // }} array( array( 'Has test 2=Two', 'Has test 2=Three;Four', '+sep=;' ), array( 'Has test 2' => array( 'Two', 'Three', 'Four' ) ) ), // {{#...: // |Has test 3=One,Two,Three|+sep // |Has test 4=Four // }} array( array( 'Has test 3=One,Two,Three', '+sep', 'Has test 4=Four' ), array( 'Has test 3' => array( 'One', 'Two', 'Three' ), 'Has test 4' => array( 'Four' ) ) ), // {{#...: // |Has test 5=Test 5-1|Test 5-2|Test 5-3|Test 5-4 // |Has test 5=Test 5-5 // }} array( array( 'Has test 5=Test 5-1', 'Test 5-2', 'Test 5-3', 'Test 5-4', 'Has test 5=Test 5-5' ), array( 'Has test 5' => array( 'Test 5-1', 'Test 5-2', 'Test 5-3', 'Test 5-4', 'Test 5-5' ) ) ), // {{#...: // |Has test 6=1+2+3|+sep=+ // |Has test 7=7 // |Has test 8=9,10,11,|+sep= // }} array( array( 'Has test 6=1+2+3', '+sep=+', 'Has test 7=7', 'Has test 8=9,10,11,', '+sep=' ), array( 'Has test 6' => array( '1', '2', '3'), 'Has test 7' => array( '7' ), 'Has test 8' => array( '9', '10', '11' ) ) ), // {{#...: // |Has test 9=One,Two,Three|+sep=; // |Has test 10=Four // }} array( array( 'Has test 9=One,Two,Three', '+sep=;', 'Has test 10=Four' ), array( 'Has test 9' => array( 'One,Two,Three' ), 'Has test 10' => array( 'Four' ) ) ), // {{#...: // |Has test 11=Test 5-1|Test 5-2|Test 5-3|Test 5-4 // |Has test 12=Test 5-5 // |Has test 11=9,10,11,|+sep= // }} array( array( 'Has test 11=Test 5-1', 'Test 5-2', 'Test 5-3', 'Test 5-4', 'Has test 12=Test 5-5', 'Has test 11=9,10,11,', '+sep=' ), array( 'Has test 11' => array( 'Test 5-1', 'Test 5-2', 'Test 5-3', 'Test 5-4', '9', '10', '11' ), 'Has test 12' => array( 'Test 5-5' ) ) ), // {{#...: // |Has test url=http://www.semantic-mediawiki.org/w/index.php?title=Subobject;http://www.semantic-mediawiki.org/w/index.php?title=Set|+sep=; // }} array( array( 'Has test url=http://www.semantic-mediawiki.org/w/index.php?title=Subobject;http://www.semantic-mediawiki.org/w/index.php?title=Set', '+sep=;' ), array( 'Has test url' => array( 'http://www.semantic-mediawiki.org/w/index.php?title=Subobject', 'http://www.semantic-mediawiki.org/w/index.php?title=Set' ) ) ), ); } public function firstParameterDataProvider() { return array( // {{#subobject: // |Has test 1=One // }} array( array( '', 'Has test 1=One'), array( 'identifier' => null ) ), // {{#set_recurring_event:Foo // |Has test 2=Two // |Has test 2=Three;Four|+sep=; // }} array( array( 'Foo' , 'Has test 2=Two', 'Has test 2=Three;Four', '+sep=;' ), array( 'identifier' => 'Foo' ) ), // {{#subobject:- // |Has test 2=Two // |Has test 2=Three;Four|+sep=; // }} array( array( '-', 'Has test 2=Two', 'Has test 2=Three;Four', '+sep=;' ), array( 'identifier' => '-' ) ), ); } }
gpl-2.0
josmarsm/openwonderland
core/src/classes/org/jdesktop/wonderland/server/cell/CellDescription.java
2911
/** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.server.cell; import org.jdesktop.wonderland.common.InternalAPI; import org.jdesktop.wonderland.common.cell.CellID; /** * A light weight container for perfomance sensiteive cell data. Used to provide in memory access to * some portion of cell data without requiring a Darkstar database access. * * @author paulby */ @InternalAPI public interface CellDescription { /** * Returns the cell ID * @return */ public CellID getCellID(); /** * Returns the time stamp for when the contents was last modified * @return */ // public long getContentsTimestamp(); /** * Returns the time stamp for when the transform was last modified * @return */ // public long getTransformTimestamp(); /** * Returns a copy of the cell's local bounds * @return the cells bounds. */ // public BoundingVolume getLocalBounds(); /** * Returns a copy of the cell's world bounds * @return */ // public BoundingVolume getWorldBounds(); /** * Set the world bounds * @param worldBounds */ // public void setWorldBounds(BoundingVolume worldBounds); /** * Returns a copy of the cell's current transform * @return the cells transform. */ // public CellTransform getLocalTransform(); // // void setLocalTransform(CellTransform localTransform, long timestamp); /** * Mark the given objectClass as dirty storing the updated Object and * the timestamp of the change, should ObjectClass be a class or an * integer ID or an enum ? */ // void markDirty(Class objectClass, Object object, long timestamp); /** * Return all dirty object since the given timestamp. This call will * mark all objects returned as clean. */ // public HashSet<Class, Object> getDirty(long timestamp) /** * Return the cells priority * @return */ // public short getPriority(); /** * Return the class of the cell represented by this mirror * @return */ // public Class getCellClass(); /** * Return true if this is a movable cell, false if its static * @return */ // public boolean isMovable(); }
gpl-2.0
mwmarkland/plucid
manual/contents.C
1341
.SP 1 .DS CONTENTS Abstract Contents 1 Introduction 2 Lucid Expressions 2.1 The @where clause 2.2 The operators @next, @fby and @first 2.3 User Defined Functions 2.4 The operators @asa, @whenever and @upon 2.5 The @@is current& declaration 3 p-Lucid Data Types 3.1 Numeric Expressions 3.2 Non-Numeric Data Processing 3.2.1 Word Processing 3.2.2 Boolean Expressions and Predefined Variables 3.2.3 String Processing 3.2.4 List Processing 3.3 The objects @eod and @error 3.4 pLucid Conditional Expressions 4 Scope Rules 5 Running pLucid under UNIX 5.1 The Basics 5.2 The @filter and @arg operators 5.3 Runtime errors 5.4 The @include facility 5.5 A UNIX manual entry for pLucid 6 Tables and Rules 6.1 Tables of Operators 6.2 Associativity and Precedence Rules 6.3 Reserved Words 7 Miscellaneous 7.1 pLucid Grammar 7.2 Syntax Diagrams 7.3 Programming examples .DE
gpl-2.0
drgr33n/norfolk-lights-website
includes/templates/template_default/templates/tpl_product_free_shipping_info_display.php
9610
<?php /** * Page Template * * Loaded automatically by index.php?main_page=product_free_shipping_info.<br /> * Displays details of a "free-shipping" product (provided it is assigned to the product-free-shipping product type) * * @package templateSystem * @copyright Copyright 2003-2011 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: tpl_product_free_shipping_info_display.php 19690 2011-10-04 16:41:45Z drbyte $ */ ?> <div class="centerColumn" id="productFreeShipdisplay"> <!--bof Form start--> <?php echo zen_draw_form('cart_quantity', zen_href_link(zen_get_info_page($_GET['products_id']), zen_get_all_get_params(array('action')) . 'action=add_product', $request_type), 'post', 'enctype="multipart/form-data"') . "\n"; ?> <!--eof Form start--> <?php if ($messageStack->size('product_info') > 0) echo $messageStack->output('product_info'); ?> <!--bof Category Icon --> <?php if ($module_show_categories != 0) {?> <?php /** * display the category icons */ require($template->get_template_dir('/tpl_modules_category_icon_display.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_modules_category_icon_display.php'); ?> <?php } ?> <!--eof Category Icon --> <!--bof Prev/Next top position --> <?php if (PRODUCT_INFO_PREVIOUS_NEXT == 1 or PRODUCT_INFO_PREVIOUS_NEXT == 3) { ?> <?php /** * display the product previous/next helper */ require($template->get_template_dir('/tpl_products_next_previous.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_products_next_previous.php'); ?> <?php } ?> <!--eof Prev/Next top position--> <!--bof Main Product Image --> <?php if (zen_not_null($products_image)) { ?> <?php /** * display the main product image */ require($template->get_template_dir('/tpl_modules_main_product_image.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_modules_main_product_image.php'); ?> <?php } ?> <!--eof Main Product Image--> <!--bof Product Name--> <h1 id="productName" class="freeShip"><?php echo $products_name; ?></h1> <!--eof Product Name--> <!--bof Product Price block --> <h2 id="productPrices" class="freeShip"> <?php // base price if ($show_onetime_charges_description == 'true') { $one_time = '<span >' . TEXT_ONETIME_CHARGE_SYMBOL . TEXT_ONETIME_CHARGE_DESCRIPTION . '</span><br />'; } else { $one_time = ''; } echo $one_time . ((zen_has_product_attributes_values((int)$_GET['products_id']) and $flag_show_product_info_starting_at == 1) ? TEXT_BASE_PRICE : '') . zen_get_products_display_price((int)$_GET['products_id']); ?></h2> <!--eof Product Price block --> <!--bof free ship icon --> <?php if(zen_get_product_is_always_free_shipping($products_id_current) && $flag_show_product_info_free_shipping) { ?> <div id="freeShippingIcon"><?php echo TEXT_PRODUCT_FREE_SHIPPING_ICON; ?></div> <?php } ?> <!--eof free ship icon --> <!--bof Product description --> <?php if ($products_description != '') { ?> <div id="productDescription" class="freeShip biggerText"><?php echo stripslashes($products_description); ?></div> <?php } ?> <!--eof Product description --> <br class="clearBoth" /> <!--bof Add to Cart Box --> <?php if (CUSTOMERS_APPROVAL == 3 and TEXT_LOGIN_FOR_PRICE_BUTTON_REPLACE_SHOWROOM == '') { // do nothing } else { ?> <?php $display_qty = (($flag_show_product_info_in_cart_qty == 1 and $_SESSION['cart']->in_cart($_GET['products_id'])) ? '<p>' . PRODUCTS_ORDER_QTY_TEXT_IN_CART . $_SESSION['cart']->get_quantity($_GET['products_id']) . '</p>' : ''); if ($products_qty_box_status == 0 or $products_quantity_order_max== 1) { // hide the quantity box and default to 1 $the_button = '<input type="hidden" name="cart_quantity" value="1" />' . zen_draw_hidden_field('products_id', (int)$_GET['products_id']) . zen_image_submit(BUTTON_IMAGE_IN_CART, BUTTON_IN_CART_ALT); } else { // show the quantity box $the_button = PRODUCTS_ORDER_QTY_TEXT . '<input type="text" name="cart_quantity" value="' . (zen_get_buy_now_qty($_GET['products_id'])) . '" maxlength="6" size="4" /><br />' . zen_get_products_quantity_min_units_display((int)$_GET['products_id']) . '<br />' . zen_draw_hidden_field('products_id', (int)$_GET['products_id']) . zen_image_submit(BUTTON_IMAGE_IN_CART, BUTTON_IN_CART_ALT); } $display_button = zen_get_buy_now_button($_GET['products_id'], $the_button); ?> <?php if ($display_qty != '' or $display_button != '') { ?> <div id="cartAdd"> <?php echo $display_qty; echo $display_button; ?> </div> <?php } // display qty and button ?> <?php } // CUSTOMERS_APPROVAL == 3 ?> <!--eof Add to Cart Box--> <!--bof Product details list --> <?php if ( (($flag_show_product_info_model == 1 and $products_model != '') or ($flag_show_product_info_weight == 1 and $products_weight !=0) or ($flag_show_product_info_quantity == 1) or ($flag_show_product_info_manufacturer == 1 and !empty($manufacturers_name))) ) { ?> <ul id="productDetailsList" class="floatingBox back"> <?php echo (($flag_show_product_info_model == 1 and $products_model !='') ? '<li>' . TEXT_PRODUCT_MODEL . $products_model . '</li>' : '') . "\n"; ?> <?php echo (($flag_show_product_info_weight == 1 and $products_weight !=0) ? '<li>' . TEXT_PRODUCT_WEIGHT . $products_weight . TEXT_PRODUCT_WEIGHT_UNIT . '</li>' : '') . "\n"; ?> <?php echo (($flag_show_product_info_quantity == 1) ? '<li>' . $products_quantity . TEXT_PRODUCT_QUANTITY . '</li>' : '') . "\n"; ?> <?php echo (($flag_show_product_info_manufacturer == 1 and !empty($manufacturers_name)) ? '<li>' . TEXT_PRODUCT_MANUFACTURER . $manufacturers_name . '</li>' : '') . "\n"; ?> </ul> <br class="clearBoth" /> <?php } ?> <!--eof Product details list --> <!--bof Attributes Module --> <?php if ($pr_attr->fields['total'] > 0) { ?> <?php /** * display the product atributes */ require($template->get_template_dir('/tpl_modules_attributes.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_modules_attributes.php'); ?> <?php } ?> <!--eof Attributes Module --> <!--bof Quantity Discounts table --> <?php if ($products_discount_type != 0) { ?> <?php /** * display the products quantity discount */ require($template->get_template_dir('/tpl_modules_products_quantity_discounts.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_modules_products_quantity_discounts.php'); ?> <?php } ?> <!--eof Quantity Discounts table --> <!--bof Additional Product Images --> <?php /** * display the products additional images */ require($template->get_template_dir('/tpl_modules_additional_images.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_modules_additional_images.php'); ?> <!--eof Additional Product Images --> <!--bof Prev/Next bottom position --> <?php if (PRODUCT_INFO_PREVIOUS_NEXT == 2 or PRODUCT_INFO_PREVIOUS_NEXT == 3) { ?> <?php /** * display the product previous/next helper */ require($template->get_template_dir('/tpl_products_next_previous.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_products_next_previous.php'); ?> <?php } ?> <!--eof Prev/Next bottom position --> <!--bof Reviews button and count--> <?php if ($flag_show_product_info_reviews == 1) { // if more than 0 reviews, then show reviews button; otherwise, show the "write review" button if ($reviews->fields['count'] > 0 ) { ?> <div id="productReviewLink" class="buttonRow back"><?php echo '<a href="' . zen_href_link(FILENAME_PRODUCT_REVIEWS, zen_get_all_get_params()) . '">' . zen_image_button(BUTTON_IMAGE_REVIEWS, BUTTON_REVIEWS_ALT) . '</a>'; ?></div> <br class="clearBoth" /> <p class="reviewCount"><?php echo ($flag_show_product_info_reviews_count == 1 ? TEXT_CURRENT_REVIEWS . ' ' . $reviews->fields['count'] : ''); ?></p> <?php } else { ?> <div id="productReviewLink" class="buttonRow back"><?php echo '<a href="' . zen_href_link(FILENAME_PRODUCT_REVIEWS_WRITE, zen_get_all_get_params(array())) . '">' . zen_image_button(BUTTON_IMAGE_WRITE_REVIEW, BUTTON_WRITE_REVIEW_ALT) . '</a>'; ?></div> <br class="clearBoth" /> <?php } } ?> <!--eof Reviews button and count --> <!--bof Product date added/available--> <?php if ($products_date_available > date('Y-m-d H:i:s')) { if ($flag_show_product_info_date_available == 1) { ?> <p id="productDateAvailable" class="freeShip centeredContent"><?php echo sprintf(TEXT_DATE_AVAILABLE, zen_date_long($products_date_available)); ?></p> <?php } } else { if ($flag_show_product_info_date_added == 1) { ?> <p id="productDateAdded" class="freeShip centeredContent"><?php echo sprintf(TEXT_DATE_ADDED, zen_date_long($products_date_added)); ?></p> <?php } // $flag_show_product_info_date_added } ?> <!--eof Product date added/available --> <!--bof Product URL --> <?php if (zen_not_null($products_url)) { if ($flag_show_product_info_url == 1) { ?> <p id="productInfoLink" class="freeShip centeredContent"><?php echo sprintf(TEXT_MORE_INFORMATION, zen_href_link(FILENAME_REDIRECT, 'action=url&goto=' . urlencode($products_url), 'NONSSL', true, false)); ?></p> <?php } // $flag_show_product_info_url } ?> <!--eof Product URL --> <!--bof also purchased products module--> <?php require($template->get_template_dir('tpl_modules_also_purchased_products.php', DIR_WS_TEMPLATE, $current_page_base,'templates'). '/' . 'tpl_modules_also_purchased_products.php');?> <!--eof also purchased products module--> <!--bof Form close--> </form> <!--bof Form close--> </div>
gpl-2.0
chauhansaurabhb/IoTSuite-TemplateV7
AndroidDeviceDrivers/src/framework/IHeater.java
196
package framework; public abstract interface IHeater { public abstract void Off(); public abstract void SetTemp(TempStruct arg ); }
gpl-2.0
geosolutions-it/geoserver-exts
mapmeter/src/main/java/org/geoserver/web/HomePageMapmeterJsContribution.java
801
package org.geoserver.web; import java.util.Set; import org.apache.wicket.markup.html.WebPage; import org.geoserver.security.GeoServerSecurityManager; public class HomePageMapmeterJsContribution extends ClassLimitingHeaderContribution { private final GeoServerSecurityManager geoServerSecurityManager; public HomePageMapmeterJsContribution(GeoServerSecurityManager geoServerSecurityManager, Set<Class<?>> pagesToApplyTo) { super(pagesToApplyTo); this.geoServerSecurityManager = geoServerSecurityManager; } @Override public boolean appliesTo(WebPage page) { // we only want to apply this to the home page if we have the admin role return super.appliesTo(page) && geoServerSecurityManager.checkAuthenticationForAdminRole(); } }
gpl-2.0
dinhkk/viking_vietnam
wp-content/plugins/qtranslate-x/qtranslate_utils.php
18387
<?php // encoding: utf-8 /* Copyright 2014 qTranslate Team (email : qTranslateTeam@gmail.com ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ // Exit if accessed directly if ( !defined( 'ABSPATH' ) ) exit; /* qTranslate-X Utilities */ // /* if(WP_DEBUG){ if(!function_exists('qtranxf_dbg_log')){ function qtranxf_dbg_log($msg,$var='novar',$bt=false,$exit=false){ //$d=ABSPATH.'/wp-logs'; //if(!file_exists($d)) mkdir($d); //$f=$d.'/qtranslate.log'; $f=WP_CONTENT_DIR.'/debug-qtranslate.log'; if( $var !== 'novar' ) $msg .= var_export($var,true); if($bt){ $msg .= PHP_EOL.'backtrace:'.PHP_EOL.var_export(debug_backtrace(),true); } error_log($msg.PHP_EOL,3,$f); if($exit) exit(); } } if(!function_exists('qtranxf_dbg_echo')){ function qtranxf_dbg_echo($msg,$var='novar',$bt=false,$exit=false){ if( $var !== 'novar' ) $msg .= var_export($var,true); echo $msg."<br>\n"; if($bt){ debug_print_backtrace(); } if($exit) exit(); } } if(!function_exists('qtranxf_dbg_log_if')){ function qtranxf_dbg_log_if($condition,$msg,$var='novar',$bt=false,$exit=false){ if($condition)qtranxf_dbg_log($msg,$var,$bt,$exit); } } if(!function_exists('qtranxf_dbg_echo_if')){ function qtranxf_dbg_echo_if($condition,$msg,$var='novar',$bt=false,$exit=false){ if($condition)qtranxf_dbg_echo($msg,$var,$bt,$exit); } } assert_options(ASSERT_BAIL,true); function qtranxf_do_tests(){ if(file_exists(dirname(__FILE__).'/dev/qtx-tests.php')) require_once(dirname(__FILE__).'/dev/qtx-tests.php'); } //add_action('qtranslate_init_language','qtranxf_do_tests'); }else{ if(!function_exists('qtranxf_dbg_log')){ function qtranxf_dbg_log($msg,$var=null,$bt=false,$exit=false){} } if(!function_exists('qtranxf_dbg_echo')){ function qtranxf_dbg_echo($msg,$var=null,$bt=false,$exit=false){} } if(!function_exists('qtranxf_dbg_log_if')){ function qtranxf_dbg_log_if($condition,$msg,$var=null,$bt=false,$exit=false){} } if(!function_exists('qtranxf_dbg_echo_if')){ function qtranxf_dbg_echo_if($condition,$msg,$var=null,$bt=false,$exit=false){} } //assert_options(ASSERT_ACTIVE,false); //assert_options(ASSERT_WARNING,false); //assert_options(ASSERT_QUIET_EVAL,true); }// */ function qtranxf_parseURL($url) { //this is not the same as native parse_url and so it is in use //it should also work quicker than native parse_url, so we should keep it? //preg_match('!(?:(\w+)://)?(?:(\w+)\:(\w+)@)?([^/:]+)?(?:\:(\d*))?([^#?]+)?(?:\?([^#]+))?(?:#(.+$))?!',$url,$out); preg_match('!(?:(\w+)://)?(?:(\w+)\:(\w+)@)?([^/:?#]+)?(?:\:(\d*))?([^#?]+)?(?:\?([^#]+))?(?:#(.+$))?!',$url,$out); //qtranxf_dbg_log('qtranxf_parseURL('.$url.'): out:',$out); //new code since 3.2.8 - performance improvement $result = array(); if(!empty($out[1])) $result['scheme'] = $out[1]; if(!empty($out[2])) $result['user'] = $out[2]; if(!empty($out[3])) $result['pass'] = $out[3]; if(!empty($out[4])) $result['host'] = $out[4]; if(!empty($out[6])) $result['path'] = $out[6]; if(!empty($out[7])) $result['query'] = $out[7]; if(!empty($out[8])) $result['fragment'] = $out[8]; /* //new code since 3.2-b2, older version produces warnings in the debugger $result = @array( 'scheme' => isset($out[1]) ? $out[1] : '', 'user' => isset($out[2]) ? $out[2] : '', 'pass' => isset($out[3]) ? $out[3] : '', 'host' => isset($out[4]) ? $out[4] : '', 'path' => isset($out[6]) ? $out[6] : '', 'query' => isset($out[7]) ? $out[7] : '', 'fragment' => isset($out[8]) ? $out[8] : '' ); */ if(!empty($out[5])) $result['host'] .= ':'.$out[5]; /* //this older version produce warnings in the debugger $result = @array( "scheme" => $out[1], "host" => $out[4].(($out[5]=='')?'':':'.$out[5]), "user" => $out[2], "pass" => $out[3], "path" => $out[6], "query" => $out[7], "fragment" => $out[8] ); */ /* not the same as above for relative url without host like 'path/1/2/3' $result = parse_url($url) + array( 'scheme' => '', 'host' => '', 'user' => '', 'pass' => '', 'path' => '', 'query' => '', 'fragment' => '' ); isset($result['port']) and $result['host'] .= ':'. $result['port']; */ return $result; } /** * @since 3.2.8 */ function qtranxf_buildURL($urlinfo,$homeinfo) { //qtranxf_dbg_log('qtranxf_buildURL: $urlinfo:',$urlinfo); //qtranxf_dbg_log('qtranxf_buildURL: $homeinfo:',$homeinfo); $url = (empty($urlinfo['scheme']) ? $homeinfo['scheme'] : $urlinfo['scheme']).'://'; if(!empty($urlinfo['user'])){ $url .= $urlinfo['user']; if(!empty($urlinfo['pass'])) $url .= ':'.$urlinfo['pass']; $url .= '@'; }elseif(!empty($homeinfo['user'])){ $url .= $homeinfo['user']; if(!empty($homeinfo['pass'])) $url .= ':'.$homeinfo['pass']; $url .= '@'; } $url .= empty($urlinfo['host']) ? $homeinfo['host'] : $urlinfo['host']; if(!empty($urlinfo['path-base'])) $url .= $urlinfo['path-base']; if(!empty($urlinfo['wp-path'])) $url .= $urlinfo['wp-path']; if(!empty($urlinfo['query'])) $url .= '?'.$urlinfo['query']; if(!empty($urlinfo['fragment'])) $url .= '#'.$urlinfo['fragment']; //qtranxf_dbg_log('qtranxf_buildURL: $url:',$url); return $url; } /** * @since 3.2.8 Copies the data needed for qtranxf_buildURL and qtranxf_url_set_language */ function qtranxf_copy_url_info($urlinfo) { $r = array(); if(isset($urlinfo['scheme'])) $r['scheme'] = $urlinfo['scheme']; if(isset($urlinfo['user'])) $r['user'] = $urlinfo['user']; if(isset($urlinfo['pass'])) $r['pass'] = $urlinfo['pass']; if(isset($urlinfo['host'])) $r['host'] = $urlinfo['host']; if(isset($urlinfo['path-base'])) $r['path-base'] = $urlinfo['path-base']; if(isset($urlinfo['wp-path'])) $r['wp-path'] = $urlinfo['wp-path']; if(isset($urlinfo['query'])) $r['query'] = $urlinfo['query']; if(isset($urlinfo['fragment'])) $r['fragment'] = $urlinfo['fragment']; if(isset($urlinfo['query_amp'])) $r['query_amp'] = $urlinfo['query_amp']; return $r; } function qtranxf_get_address_info($option_name) { $info = qtranxf_parseURL( get_option($option_name) ); if(isset($info['path'])){ $info['path-length'] = strlen($info['path']); }else{ $info['path'] = ''; $info['path-length'] = 0; } return $info; } function qtranxf_get_home_info() { static $home_info; if(!$home_info) $home_info = qtranxf_get_address_info('home'); return $home_info; } function qtranxf_get_site_info() { static $site_info; if(!$site_info) $site_info = qtranxf_get_address_info('siteurl'); return $site_info; } function qtranxf_get_url_info($url){ $urlinfo = qtranxf_parseURL($url); qtranxf_complete_url_info($urlinfo); qtranxf_complete_url_info_path($urlinfo); return $urlinfo; } function qtranxf_complete_url_info(&$urlinfo){ if(!isset($urlinfo['path'])) $urlinfo['path'] = ''; $path = &$urlinfo['path']; $home_info = qtranxf_get_home_info(); $site_info = qtranxf_get_site_info(); $home_path = $home_info['path']; $site_path = $site_info['path']; $home_path_len = $home_info['path-length']; $site_path_len = $site_info['path-length']; if($home_path_len > $site_path_len){ if(qtranxf_startsWith($path,$home_path)){ $urlinfo['path-base'] = $home_path; $urlinfo['path-base-length'] = $home_path_len; $urlinfo['doing_front_end'] = true; }elseif(qtranxf_startsWith($path,$site_path)){ $urlinfo['path-base'] = $site_path; $urlinfo['path-base-length'] = $site_path_len; $urlinfo['doing_front_end'] = false; } }elseif($home_path_len < $site_path_len){ if(qtranxf_startsWith($path,$site_path)){ $urlinfo['path-base'] = $site_path; $urlinfo['path-base-length'] = $site_path_len; $urlinfo['doing_front_end'] = false; }elseif(qtranxf_startsWith($path,$home_path)){ $urlinfo['path-base'] = $home_path; $urlinfo['path-base-length'] = $home_path_len; $urlinfo['doing_front_end'] = true; } }elseif($home_path != $site_path){ if(qtranxf_startsWith($path,$home_path)){ $urlinfo['path-base'] = $home_path; $urlinfo['path-base-length'] = $home_path_len; $urlinfo['doing_front_end'] = true; }elseif(qtranxf_startsWith($path,$site_path)){ $urlinfo['path-base'] = $site_path; $urlinfo['path-base-length'] = $site_path_len; $urlinfo['doing_front_end'] = false; } }else{//$home_path == $site_path if(qtranxf_startsWith($path,$home_path)){ $urlinfo['path-base'] = $home_path; $urlinfo['path-base-length'] = $home_path_len; } } } /** * @since 3.2.8 */ function qtranxf_complete_url_info_path(&$urlinfo){ if(isset($urlinfo['path-base'])){ if( empty($urlinfo['path-base']) ){ $urlinfo['wp-path'] = $urlinfo['path']; }elseif( !empty($urlinfo['path']) && qtranxf_startsWith($urlinfo['path'],$urlinfo['path-base']) ){ //qtranxf_dbg_log('qtranxf_complete_url_info_path: urlinfo: ',$urlinfo); if(isset($urlinfo['path'][$urlinfo['path-base-length']])){ if($urlinfo['path'][$urlinfo['path-base-length']] == '/'){ $urlinfo['wp-path'] = substr($urlinfo['path'],$urlinfo['path-base-length']); } }else{ $urlinfo['wp-path'] = ''; } } } //$urlinfo['wp-path'] is not set, means url does not belong to this WP installation } /** * Simplified version of WP's add_query_arg * @since 3.2.8 */ function qtranxf_add_query_arg(&$query, $key_value){ if(empty($query)) $query = $key_value; else $query .= '&'.$key_value; } /** * Simplified version of WP's remove_query_arg * @since 3.2.8 */ function qtranxf_del_query_arg(&$query, $key){ //$key_value; $match; while(preg_match('/(&|&amp;|&#038;|^)('.$key.'=[^&]+)(&|&amp;|&#038;|$)/i',$query,$match)){ //$key_value = $match[2]; $p = strpos($query,$match[2]); $n = strlen($match[2]); if(!empty($match[1])) { $l = strlen($match[1]); $p -= $l; $n += $l; } elseif(!empty($match[3])) { $l = strlen($match[3]); $n += $l; } //qtranxf_dbg_log('qtranxf_del_query_arg: query: '.$query.'; p='.$p.'; n=',$n); $query = substr_replace($query,'',$p,$n); //qtranxf_dbg_log('qtranxf_del_query_arg: query: ',$query); } //return $key_value; } /* * @since 2.3.8 simplified version of esc_url */ function qtranxf_sanitize_url($url) { $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url); $strip = array('%0d', '%0a', '%0D', '%0A'); $count; do{ $url = str_replace( $strip, '', $url, $count ); } while($count); return $url; } function qtranxf_stripSlashesIfNecessary($str) { if(1==get_magic_quotes_gpc()) { $str = stripslashes($str); } return $str; } function qtranxf_insertDropDownElement($language, $url, $id){ global $q_config; $html =" var sb = document.getElementById('qtranxs_select_".$id."'); var o = document.createElement('option'); var l = document.createTextNode('".$q_config['language_name'][$language]."'); "; if($q_config['language']==$language) $html .= "o.selected = 'selected';"; $html .= " o.value = '".addslashes(htmlspecialchars_decode($url, ENT_NOQUOTES))."'; o.appendChild(l); sb.appendChild(o); "; return $html; } function qtranxf_get_domain_language($host){ global $q_config; //todo should have hash host->lang //foreach($q_config['enabled_languages'] as $lang){ // if(!isset($q_config['domains'][$lang])) continue; // if($q_config['domains'][$lang] != $host) continue; // return $lang; //} foreach($q_config['domains'] as $lang => $h){ if($h == $host) return $lang; } } function qtranxf_external_host_ex($host,$homeinfo){ global $q_config; //$homehost = qtranxf_get_home_info()['host']; switch($q_config['url_mode']){ case QTX_URL_QUERY: return $homeinfo['host'] != $host; case QTX_URL_PATH: case QTX_URL_DOMAIN: return !qtranxf_endsWith($host,$homeinfo['host']); case QTX_URL_DOMAINS: foreach($q_config['domains'] as $lang => $h){ if($h == $host) return false; } if($homeinfo['host'] == $host) return false; default: return true; } } function qtranxf_external_host($host){ $homeinfo=qtranxf_get_home_info(); return qtranxf_external_host_ex($host,$homeinfo); } function qtranxf_isMultilingual($str){ return preg_match('/(<!--:[a-z]{2}-->|\[:[a-z]{2}\])/im',$str); } if (!function_exists('qtranxf_getLanguage')){ function qtranxf_getLanguage() { global $q_config; return $q_config['language']; } } function qtranxf_getLanguageName($lang = '') { global $q_config; if($lang=='' || !qtranxf_isEnabled($lang)) $lang = $q_config['language']; return $q_config['language_name'][$lang]; } function qtranxf_isEnabled($lang) { global $q_config; return in_array($lang, $q_config['enabled_languages']); } /** * @since 3.2.8 - change code to improve performance */ function qtranxf_startsWith($s, $n) { $l = strlen($n); if($l>strlen($s)) return false; for($i=0;$i<$l;++$i){ if($s[$i] != $n[$i]) return false; } //if($n == substr($s,0,strlen($n))) return true; return true; } /** * @since 3.2.8 */ function qtranxf_endsWith($s, $n) { $l = strlen($n); $b = strlen($s) - $l; if($b < 0) return false; for($i=0;$i<$l;++$i){ if($s[$b+$i] != $n[$i]) return false; } return true; } function qtranxf_getAvailableLanguages($text) { global $q_config; $result = array(); $content = qtranxf_split($text); foreach($content as $language => $lang_text) { $lang_text = trim($lang_text); if(!empty($lang_text)) $result[] = $language; } if(sizeof($result)==0) { // add default language to keep default URL $result[] = $q_config['language']; } return $result; } function qtranxf_isAvailableIn($post_id, $language='') { global $q_config; if($language == '') $language = $q_config['default_language']; $p = get_post($post_id); $post = &$p; $languages = qtranxf_getAvailableLanguages($post->post_content); return in_array($language,$languages); } function qtranxf_convertDateFormatToStrftimeFormat($format) { $mappings = array( 'd' => '%d', 'D' => '%a', 'j' => '%E', 'l' => '%A', 'N' => '%u', 'S' => '%q', 'w' => '%f', 'z' => '%F', 'W' => '%V', 'F' => '%B', 'm' => '%m', 'M' => '%b', 'n' => '%i', 't' => '%J', 'L' => '%k', 'o' => '%G', 'Y' => '%Y', 'y' => '%y', 'a' => '%P', 'A' => '%p', 'B' => '%K', 'g' => '%l', 'G' => '%L', 'h' => '%I', 'H' => '%H', 'i' => '%M', 's' => '%S', 'u' => '%N', 'e' => '%Q', 'I' => '%o', 'O' => '%O', 'P' => '%s', 'T' => '%v', 'Z' => '%1', 'c' => '%2', 'r' => '%3', 'U' => '%4' ); $date_parameters = array(); $strftime_parameters = array(); $date_parameters[] = '#%#'; $strftime_parameters[] = '%'; foreach($mappings as $df => $sf) { $date_parameters[] = '#(([^%\\\\])'.$df.'|^'.$df.')#'; $strftime_parameters[] = '${2}'.$sf; } // convert everything $format = preg_replace($date_parameters, $strftime_parameters, $format); // remove single backslashes from dates $format = preg_replace('#\\\\([^\\\\]{1})#','${1}',$format); // remove double backslashes from dates $format = preg_replace('#\\\\\\\\#','\\\\',$format); return $format; } function qtranxf_convertFormat($format, $default_format) { global $q_config; // if one of special language-neutral formats are requested, don't replace it switch($format){ case 'Z': case 'c': case 'r': case 'U': return qtranxf_convertDateFormatToStrftimeFormat($format); default: break; } // check for multilang formats $format = qtranxf_useCurrentLanguageIfNotFoundUseDefaultLanguage($format); $default_format = qtranxf_useCurrentLanguageIfNotFoundUseDefaultLanguage($default_format); switch($q_config['use_strftime']) { case QTX_DATE: if($format=='') $format = $default_format; return qtranxf_convertDateFormatToStrftimeFormat($format); case QTX_DATE_OVERRIDE: return qtranxf_convertDateFormatToStrftimeFormat($default_format); case QTX_STRFTIME: return $format; case QTX_STRFTIME_OVERRIDE: default: return $default_format; } } function qtranxf_convertDateFormat($format) { global $q_config; if(isset($q_config['date_format'][$q_config['language']])) { $default_format = $q_config['date_format'][$q_config['language']]; } elseif(isset($q_config['date_format'][$q_config['default_language']])) { $default_format = $q_config['date_format'][$q_config['default_language']]; } else { $default_format = ''; } return qtranxf_convertFormat($format, $default_format); } function qtranxf_convertTimeFormat($format) { global $q_config; if(isset($q_config['time_format'][$q_config['language']])) { $default_format = $q_config['time_format'][$q_config['language']]; } elseif(isset($q_config['time_format'][$q_config['default_language']])) { $default_format = $q_config['time_format'][$q_config['default_language']]; } else { $default_format = ''; } return qtranxf_convertFormat($format, $default_format); } function qtranxf_formatCommentDateTime($format) { global $comment; return qtranxf_strftime(qtranxf_convertFormat($format, $format), mysql2date('U',$comment->comment_date), ''); } function qtranxf_formatPostDateTime($format) { global $post; return qtranxf_strftime(qtranxf_convertFormat($format, $format), mysql2date('U',$post->post_date), ''); } function qtranxf_formatPostModifiedDateTime($format) { global $post; return qtranxf_strftime(qtranxf_convertFormat($format, $format), mysql2date('U',$post->post_modified), ''); } //not in use //function qtranxf_realURL($url = '') { // global $q_config; // return $q_config['url_info']['original_url']; //} function qtranxf_getSortedLanguages($reverse = false) { global $q_config; $languages = $q_config['enabled_languages']; ksort($languages); // fix broken order $clean_languages = array(); foreach($languages as $lang) { $clean_languages[] = $lang; } if($reverse) krsort($clean_languages); return $clean_languages; } function qtranxf_can_redirect() { return !defined('WP_ADMIN') && !defined('DOING_AJAX') && !defined('WP_CLI') && !defined('DOING_CRON') && empty($_POST); }
gpl-2.0
boudewijnrempt/HyvesDesktop
3rdparty/google-breakpad-read-only/src/client/linux/handler/linux_thread_test.cc
9059
// Copyright (c) 2006, Google Inc. // All rights reserved. // // Author: Li Liu // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <pthread.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <cstdio> #include <cstdlib> #include <cstring> #include "client/linux/handler/linux_thread.h" using namespace google_breakpad; // Thread use this to see if it should stop working. static bool should_exit = false; static void foo2(int *a) { // Stack variable, used for debugging stack dumps. int c = 0xcccccccc; c = c; while (!should_exit) sleep(1); } static void foo() { // Stack variable, used for debugging stack dumps. int a = 0xaaaaaaaa; foo2(&a); } static void *thread_main(void *) { // Stack variable, used for debugging stack dumps. int b = 0xbbbbbbbb; b = b; while (!should_exit) { foo(); } return NULL; } static void CreateThreads(int num) { pthread_t handle; for (int i = 0; i < num; i++) { if (0 != pthread_create(&handle, NULL, thread_main, NULL)) fprintf(stderr, "Failed to create thread.\n"); else pthread_detach(handle); } } static bool ProcessOneModule(const struct ModuleInfo &module_info, void *context) { printf("0x%x[%8d] %s\n", module_info.start_addr, module_info.size, module_info.name); return true; } static bool ProcessOneThread(const struct ThreadInfo &thread_info, void *context) { printf("\n\nPID: %d, TGID: %d, PPID: %d\n", thread_info.pid, thread_info.tgid, thread_info.ppid); struct user_regs_struct regs; struct user_fpregs_struct fp_regs; struct user_fpxregs_struct fpx_regs; struct DebugRegs dbg_regs; LinuxThread *threads = reinterpret_cast<LinuxThread *>(context); memset(&regs, 0, sizeof(regs)); if (threads->GetRegisters(thread_info.pid, &regs)) { printf(" gs = 0x%lx\n", regs.xgs); printf(" fs = 0x%lx\n", regs.xfs); printf(" es = 0x%lx\n", regs.xes); printf(" ds = 0x%lx\n", regs.xds); printf(" edi = 0x%lx\n", regs.edi); printf(" esi = 0x%lx\n", regs.esi); printf(" ebx = 0x%lx\n", regs.ebx); printf(" edx = 0x%lx\n", regs.edx); printf(" ecx = 0x%lx\n", regs.ecx); printf(" eax = 0x%lx\n", regs.eax); printf(" ebp = 0x%lx\n", regs.ebp); printf(" eip = 0x%lx\n", regs.eip); printf(" cs = 0x%lx\n", regs.xcs); printf(" eflags = 0x%lx\n", regs.eflags); printf(" esp = 0x%lx\n", regs.esp); printf(" ss = 0x%lx\n", regs.xss); } else { fprintf(stderr, "ERROR: Failed to get general purpose registers\n"); } memset(&fp_regs, 0, sizeof(fp_regs)); if (threads->GetFPRegisters(thread_info.pid, &fp_regs)) { printf("\n Floating point registers:\n"); printf(" fctl = 0x%lx\n", fp_regs.cwd); printf(" fstat = 0x%lx\n", fp_regs.swd); printf(" ftag = 0x%lx\n", fp_regs.twd); printf(" fioff = 0x%lx\n", fp_regs.fip); printf(" fiseg = 0x%lx\n", fp_regs.fcs); printf(" fooff = 0x%lx\n", fp_regs.foo); printf(" foseg = 0x%lx\n", fp_regs.fos); int st_space_size = sizeof(fp_regs.st_space) / sizeof(fp_regs.st_space[0]); printf(" st_space[%2d] = 0x", st_space_size); for (int i = 0; i < st_space_size; ++i) printf("%02lx", fp_regs.st_space[i]); printf("\n"); } else { fprintf(stderr, "ERROR: Failed to get floating-point registers\n"); } memset(&fpx_regs, 0, sizeof(fpx_regs)); if (threads->GetFPXRegisters(thread_info.pid, &fpx_regs)) { printf("\n Extended floating point registers:\n"); printf(" fctl = 0x%x\n", fpx_regs.cwd); printf(" fstat = 0x%x\n", fpx_regs.swd); printf(" ftag = 0x%x\n", fpx_regs.twd); printf(" fioff = 0x%lx\n", fpx_regs.fip); printf(" fiseg = 0x%lx\n", fpx_regs.fcs); printf(" fooff = 0x%lx\n", fpx_regs.foo); printf(" foseg = 0x%lx\n", fpx_regs.fos); printf(" fop = 0x%x\n", fpx_regs.fop); printf(" mxcsr = 0x%lx\n", fpx_regs.mxcsr); int space_size = sizeof(fpx_regs.st_space) / sizeof(fpx_regs.st_space[0]); printf(" st_space[%2d] = 0x", space_size); for (int i = 0; i < space_size; ++i) printf("%02lx", fpx_regs.st_space[i]); printf("\n"); space_size = sizeof(fpx_regs.xmm_space) / sizeof(fpx_regs.xmm_space[0]); printf(" xmm_space[%2d] = 0x", space_size); for (int i = 0; i < space_size; ++i) printf("%02lx", fpx_regs.xmm_space[i]); printf("\n"); } if (threads->GetDebugRegisters(thread_info.pid, &dbg_regs)) { printf("\n Debug registers:\n"); printf(" dr0 = 0x%x\n", dbg_regs.dr0); printf(" dr1 = 0x%x\n", dbg_regs.dr1); printf(" dr2 = 0x%x\n", dbg_regs.dr2); printf(" dr3 = 0x%x\n", dbg_regs.dr3); printf(" dr4 = 0x%x\n", dbg_regs.dr4); printf(" dr5 = 0x%x\n", dbg_regs.dr5); printf(" dr6 = 0x%x\n", dbg_regs.dr6); printf(" dr7 = 0x%x\n", dbg_regs.dr7); printf("\n"); } if (regs.esp != 0) { // Print the stack content. int size = 1024 * 2; char *buf = new char[size]; size = threads->GetThreadStackDump(regs.ebp, regs.esp, (void*)buf, size); printf(" Stack content: = 0x"); size /= sizeof(unsigned long); unsigned long *p_buf = (unsigned long *)(buf); for (int i = 0; i < size; i += 1) printf("%.8lx ", p_buf[i]); delete []buf; printf("\n"); } return true; } static int PrintAllThreads(void *argument) { int pid = (int)argument; LinuxThread threads(pid); int total_thread = threads.SuspendAllThreads(); printf("There are %d threads in the process: %d\n", total_thread, pid); int total_module = threads.GetModuleCount(); printf("There are %d modules in the process: %d\n", total_module, pid); CallbackParam<ModuleCallback> module_callback(ProcessOneModule, &threads); threads.ListModules(&module_callback); CallbackParam<ThreadCallback> thread_callback(ProcessOneThread, &threads); threads.ListThreads(&thread_callback); return 0; } int main(int argc, char **argv) { int pid = getpid(); printf("Main thread is %d\n", pid); CreateThreads(1); // Create stack for the process. char *stack = new char[1024 * 100]; int cloned_pid = clone(PrintAllThreads, stack + 1024 * 100, CLONE_VM | CLONE_FILES | CLONE_FS | CLONE_UNTRACED, (void*)getpid()); waitpid(cloned_pid, NULL, __WALL); should_exit = true; printf("Test finished.\n"); delete []stack; return 0; }
gpl-2.0
transcend3nt/windows-privesc-check
windows-privesc-check.py
136275
# Licence # ======= # # windows-privesc-check - Security Auditing Tool For Windows # Copyright (C) 2010 pentestmonkey@pentestmonkey.net # http://pentestmonkey.net/windows-privesc-check # # This tool may be used for legal purposes only. Users take full responsibility # for any actions performed using this tool. The author accepts no liability for # damage caused by this tool. If these terms are not acceptable to you, then you # may not use this tool. # # In all other respects the GPL version 2 applies. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # TODO List # ========= # # TODO review "read" perms. should probably ignore these. # TODO explaination of what various permissions mean # TODO Audit: Process listing, full paths and perms of all processes # TODO dlls used by programs (for all checks) # TODO find web roots and check for write access # TODO support remote server (remote file, reg keys, unc paths for file, remote resolving of sids) # TODO task scheduler # TODO alert if lanman hashes are being stored (for post-exploitation) # TODO alert if named local/domain service accounts are being used (for post-exploitation) # TODO Alert if really important patches are missing. These are metasploitable: # MS10_015 977165 Vulnerabilities in Windows Kernel Could Allow Elevation of Privilege (kitrap0d - meterpreter "getsystem") # MS03_049 828749 Microsoft Workstation Service NetAddAlternateComputerName Overflow (netapi) # MS04_007 828028 Microsoft ASN.1 Library Bitstring Heap Overflow (killbill) # MS04_011 835732 Microsoft LSASS Service DsRolerUpgradeDownlevelServer Overflow (lsass) # MS04_031 841533 Microsoft NetDDE Service Overflow (netdde) # MS05_039 899588 Microsoft Plug and Play Service Overflow (pnp) # MS06_025 911280 Microsoft RRAS Service RASMAN Registry Overflow (rasmans_reg) # MS06_025 911280 Microsoft RRAS Service Overflow (rras) # MS06_040 921883 Microsoft Server Service NetpwPathCanonicalize Overflow (netapi) # MS06_066 923980 Microsoft Services MS06-066 nwapi32.dll (nwapi) # MS06_066 923980 Microsoft Services MS06-066 nwwks.dll (nwwks) # MS06_070 924270 Microsoft Workstation Service NetpManageIPCConnect Overflow (wkssvc) # MS07_029 935966 Microsoft DNS RPC Service extractQuotedChar() Overflow (SMB) (msdns_zonename) # MS08_067 958644 Microsoft Server Service Relative Path Stack Corruption (netapi) # MS09_050 975517 Microsoft SRV2.SYS SMB Negotiate ProcessID Function Table Dereference (smb2_negotiate_func_index) # MS03_026 823980 Microsoft RPC DCOM Interface Overflow # MS05_017 892944 Microsoft Message Queueing Service Path Overflow # MS07_065 937894 Microsoft Message Queueing Service DNS Name Path Overflow # TODO registry key checks for windows services # TODO per-user checks including perms on home dirs and startup folders + default user and all users # TODO need to be able to order issues more logically. Maybe group by section? # Building an Executable # ====================== # # This script should be converted to an exe before it is used for # auditing - otherwise you'd have to install loads of dependencies # on the target system. # # Download pyinstaller: http://www.pyinstaller.org/changeset/latest/trunk?old_path=%2F&format=zip # Read the docs: http://www.pyinstaller.org/export/latest/tags/1.4/doc/Manual.html?format=raw # # Unzip to c:\pyinstaller (say) # cd c:\pyinstaller # python Configure.py # python Makespec.py --onefile c:\somepath\wpc.py # python Build.py wpc\wpc.spec # wpc\dist\wpc.exe # # Alternative to pyinstaller is cxfreeze. This doesn't always work, though: # \Python26\Scripts\cxfreeze wpc.py --target-dir dist # zip -r wpc.zip dist # # You then need to copy wpc.zip to the target and unzip it. The exe therein # should then run because all the dependencies are in the current (dist) directory. # 64-bit vs 32-bit # ================ # # If we run a 32-bit version of this script on a 64-bit box we have (at least) the # following problems: # * Registry: We CAN'T see the whole 64-bit registry. This seems insurmountable. # * Files: It's harder to see in system32. This can be worked round. # What types of object have permissions? # ====================================== # # Files, directories and registry keys are the obvious candidates. There are several others too... # # This provides a good summary: http://msdn.microsoft.com/en-us/library/aa379557%28v=VS.85%29.aspx # # Files or directories on an NTFS file system GetNamedSecurityInfo, SetNamedSecurityInfo, GetSecurityInfo, SetSecurityInfo # Named pipes # Anonymous pipes # Processes # Threads # File-mapping objects # Access tokens # Window-management objects (window stations and desktops) # Registry keys # Windows services # Local or remote printers # Network shares # Interprocess synchronization objects # Directory service objects # # This provides a good description of how Access Tokens interact with the Security Descriptors on Securable Objects: http://msdn.microsoft.com/en-us/library/aa374876%28v=VS.85%29.aspx # # http://msdn.microsoft.com/en-us/library/aa379593(VS.85).aspx # win32security.SE_UNKNOWN_OBJECT_TYPE - n/a # win32security.SE_FILE_OBJECT - poc working # win32security.SE_SERVICE - poc working # win32security.SE_PRINTER - TODO Indicates a printer. A printer object can be a local printer, such as PrinterName, or a remote printer, such as # \\ComputerName\PrinterName. # win32security.SE_REGISTRY_KEY - TODO # Indicates a registry key. A registry key object can be in the local registry, such as CLASSES_ROOT\SomePath or in a remote registry, # such as \\ComputerName\CLASSES_ROOT\SomePath. # The names of registry keys must use the following literal strings to identify the predefined registry keys: # "CLASSES_ROOT", "CURRENT_USER", "MACHINE", and "USERS". # perms: http://msdn.microsoft.com/en-us/library/ms724878(VS.85).aspx # win32security.SE_LMSHARE - TODO Indicates a network share. A share object can be local, such as ShareName, or remote, such as \\ComputerName\ShareName. # win32security.SE_KERNEL_OBJECT - TODO # Indicates a local kernel object. # The GetSecurityInfo and SetSecurityInfo functions support all types of kernel objects. # The GetNamedSecurityInfo and SetNamedSecurityInfo functions work only with the following kernel objects: # semaphore, event, mutex, waitable timer, and file mapping. # win32security.SE_WINDOW_OBJECT - TODO Indicates a window station or desktop object on the local computer. # You cannot use GetNamedSecurityInfo and SetNamedSecurityInfo with these objects because the names of window stations or desktops are not unique. # win32security.SE_DS_OBJECT - TODO - Active Directory object # Indicates a directory service object or a property set or property of a directory service object. # The name string for a directory service object must be in X.500 form, for example: # CN=SomeObject,OU=ou2,OU=ou1,DC=DomainName,DC=CompanyName,DC=com,O=internet # perm list: http://msdn.microsoft.com/en-us/library/aa772285(VS.85).aspx # win32security.SE_DS_OBJECT_ALL - TODO # Indicates a directory service object and all of its property sets and properties. # win32security.SE_PROVIDER_DEFINED_OBJECT - TODO Indicates a provider-defined object. # win32security.SE_WMIGUID_OBJECT - TODO Indicates a WMI object. # win32security.SE_REGISTRY_WOW64_32KEY - TODO Indicates an object for a registry entry under WOW64. # What sort of privileges can be granted on Windows? # ================================================== # # These are bit like Capabilities on Linux. # http://msdn.microsoft.com/en-us/library/bb530716(VS.85).aspx # http://msdn.microsoft.com/en-us/library/bb545671(VS.85).aspx # # These privs sound like they might allow the holder to gain admin rights: # # SE_ASSIGNPRIMARYTOKEN_NAME TEXT("SeAssignPrimaryTokenPrivilege") Required to assign the primary token of a process. User Right: Replace a process-level token. # SE_BACKUP_NAME TEXT("SeBackupPrivilege") Required to perform backup operations. This privilege causes the system to grant all read access control to any file, regardless of the access control list (ACL) specified for the file. Any access request other than read is still evaluated with the ACL. This privilege is required by the RegSaveKey and RegSaveKeyExfunctions. The following access rights are granted if this privilege is held: READ_CONTROL ACCESS_SYSTEM_SECURITY FILE_GENERIC_READ FILE_TRAVERSE User Right: Back up files and directories. # SE_CREATE_PAGEFILE_NAME TEXT("SeCreatePagefilePrivilege") Required to create a paging file. User Right: Create a pagefile. # SE_CREATE_TOKEN_NAME TEXT("SeCreateTokenPrivilege") Required to create a primary token. User Right: Create a token object. # SE_DEBUG_NAME TEXT("SeDebugPrivilege") Required to debug and adjust the memory of a process owned by another account. User Right: Debug programs. # SE_ENABLE_DELEGATION_NAME TEXT("SeEnableDelegationPrivilege") Required to mark user and computer accounts as trusted for delegation. User Right: Enable computer and user accounts to be trusted for delegation. # SE_LOAD_DRIVER_NAME TEXT("SeLoadDriverPrivilege") Required to load or unload a device driver. User Right: Load and unload device drivers. # SE_MACHINE_ACCOUNT_NAME TEXT("SeMachineAccountPrivilege") Required to create a computer account. User Right: Add workstations to domain. # SE_MANAGE_VOLUME_NAME TEXT("SeManageVolumePrivilege") Required to enable volume management privileges. User Right: Manage the files on a volume. # SE_RELABEL_NAME TEXT("SeRelabelPrivilege") Required to modify the mandatory integrity level of an object. User Right: Modify an object label. # SE_RESTORE_NAME TEXT("SeRestorePrivilege") Required to perform restore operations. This privilege causes the system to grant all write access control to any file, regardless of the ACL specified for the file. Any access request other than write is still evaluated with the ACL. Additionally, this privilege enables you to set any valid user or group SID as the owner of a file. This privilege is required by the RegLoadKey function. The following access rights are granted if this privilege is held: WRITE_DAC WRITE_OWNER ACCESS_SYSTEM_SECURITY FILE_GENERIC_WRITE FILE_ADD_FILE FILE_ADD_SUBDIRECTORY DELETE User Right: Restore files and directories. # SE_SHUTDOWN_NAME TEXT("SeShutdownPrivilege") Required to shut down a local system. User Right: Shut down the system. # SE_SYNC_AGENT_NAME TEXT("SeSyncAgentPrivilege") Required for a domain controller to use the LDAP directory synchronization services. This privilege enables the holder to read all objects and properties in the directory, regardless of the protection on the objects and properties. By default, it is assigned to the Administrator and LocalSystem accounts on domain controllers. User Right: Synchronize directory service data. # SE_TAKE_OWNERSHIP_NAME TEXT("SeTakeOwnershipPrivilege") Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be set only to those values that the holder may legitimately assign as the owner of an object. User Right: Take ownership of files or other objects. # SE_TCB_NAME TEXT("SeTcbPrivilege") This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this privilege. User Right: Act as part of the operating system. # SE_TRUSTED_CREDMAN_ACCESS_NAME TEXT("SeTrustedCredManAccessPrivilege") Required to access Credential Manager as a trusted caller. User Right: Access Credential Manager as a trusted caller. # # These sound like they could be troublesome in the wrong hands: # # SE_SECURITY_NAME TEXT("SeSecurityPrivilege") Required to perform a number of security-related functions, such as controlling and viewing audit messages. This privilege identifies its holder as a security operator. User Right: Manage auditing and security log. # SE_REMOTE_SHUTDOWN_NAME TEXT("SeRemoteShutdownPrivilege") Required to shut down a system using a network request. User Right: Force shutdown from a remote system. # SE_PROF_SINGLE_PROCESS_NAME TEXT("SeProfileSingleProcessPrivilege") Required to gather profiling information for a single process. User Right: Profile single process. # SE_AUDIT_NAME TEXT("SeAuditPrivilege") Required to generate audit-log entries. Give this privilege to secure servers.User Right: Generate security audits. # SE_INC_BASE_PRIORITY_NAME TEXT("SeIncreaseBasePriorityPrivilege") Required to increase the base priority of a process. User Right: Increase scheduling priority. # SE_INC_WORKING_SET_NAME TEXT("SeIncreaseWorkingSetPrivilege") Required to allocate more memory for applications that run in the context of users. User Right: Increase a process working set. # SE_INCREASE_QUOTA_NAME TEXT("SeIncreaseQuotaPrivilege") Required to increase the quota assigned to a process. User Right: Adjust memory quotas for a process. # SE_LOCK_MEMORY_NAME TEXT("SeLockMemoryPrivilege") Required to lock physical pages in memory. User Right: Lock pages in memory. # SE_SYSTEM_ENVIRONMENT_NAME TEXT("SeSystemEnvironmentPrivilege") Required to modify the nonvolatile RAM of systems that use this type of memory to store configuration information. User Right: Modify firmware environment values. # # These sound less interesting: # # SE_CHANGE_NOTIFY_NAME TEXT("SeChangeNotifyPrivilege") Required to receive notifications of changes to files or directories. This privilege also causes the system to skip all traversal access checks. It is enabled by default for all users. User Right: Bypass traverse checking. # SE_CREATE_GLOBAL_NAME TEXT("SeCreateGlobalPrivilege") Required to create named file mapping objects in the global namespace during Terminal Services sessions. This privilege is enabled by default for administrators, services, and the local system account.User Right: Create global objects. Windows XP/2000: This privilege is not supported. Note that this value is supported starting with Windows Server 2003, Windows XP with SP2, and Windows 2000 with SP4. # SE_CREATE_PERMANENT_NAME TEXT("SeCreatePermanentPrivilege") Required to create a permanent object. User Right: Create permanent shared objects. # SE_CREATE_SYMBOLIC_LINK_NAME TEXT("SeCreateSymbolicLinkPrivilege") Required to create a symbolic link. User Right: Create symbolic links. # SE_IMPERSONATE_NAME TEXT("SeImpersonatePrivilege") Required to impersonate. User Right: Impersonate a client after authentication. Windows XP/2000: This privilege is not supported. Note that this value is supported starting with Windows Server 2003, Windows XP with SP2, and Windows 2000 with SP4. # SE_SYSTEM_PROFILE_NAME TEXT("SeSystemProfilePrivilege") Required to gather profiling information for the entire system. User Right: Profile system performance. # SE_SYSTEMTIME_NAME TEXT("SeSystemtimePrivilege") Required to modify the system time. User Right: Change the system time. # SE_TIME_ZONE_NAME TEXT("SeTimeZonePrivilege") Required to adjust the time zone associated with the computer's internal clock. User Right: Change the time zone. # SE_UNDOCK_NAME TEXT("SeUndockPrivilege") Required to undock a laptop. User Right: Remove computer from docking station. # SE_UNSOLICITED_INPUT_NAME TEXT("SeUnsolicitedInputPrivilege") Required to read unsolicited input from a terminal device. User Right: Not applicable. # These are from ntsecapi.h: # # SE_BATCH_LOGON_NAME TEXT("SeBatchLogonRight") Required for an account to log on using the batch logon type. # SE_DENY_BATCH_LOGON_NAME TEXT("SeDenyBatchLogonRight") Explicitly denies an account the right to log on using the batch logon type. # SE_DENY_INTERACTIVE_LOGON_NAME TEXT("SeDenyInteractiveLogonRight") Explicitly denies an account the right to log on using the interactive logon type. # SE_DENY_NETWORK_LOGON_NAME TEXT("SeDenyNetworkLogonRight") Explicitly denies an account the right to log on using the network logon type. # SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME TEXT("SeDenyRemoteInteractiveLogonRight") Explicitly denies an account the right to log on remotely using the interactive logon type. # SE_DENY_SERVICE_LOGON_NAME TEXT("SeDenyServiceLogonRight") Explicitly denies an account the right to log on using the service logon type. # SE_INTERACTIVE_LOGON_NAME TEXT("SeInteractiveLogonRight") Required for an account to log on using the interactive logon type. # SE_NETWORK_LOGON_NAME TEXT("SeNetworkLogonRight") Required for an account to log on using the network logon type. # SE_REMOTE_INTERACTIVE_LOGON_NAME TEXT("SeRemoteInteractiveLogonRight") Required for an account to log on remotely using the interactive logon type. # SE_SERVICE_LOGON_NAME TEXT("SeServiceLogonRight") Required for an account to log on using the service logon type. #import pythoncom, sys, os, time, win32api #from win32com.taskscheduler import taskscheduler import glob import datetime import socket import os, sys import win32process import re import win32security, ntsecuritycon, win32api, win32con, win32file import win32service import pywintypes # doesn't play well with molebox pro - why did we need this anyway? import win32net import ctypes import getopt import _winreg import win32netcon from subprocess import Popen, PIPE, STDOUT # from winapi import * from ntsecuritycon import TokenSessionId, TokenSandBoxInert, TokenType, TokenImpersonationLevel, TokenVirtualizationEnabled, TokenVirtualizationAllowed, TokenHasRestrictions, TokenElevationType, TokenUIAccess, TokenUser, TokenOwner, TokenGroups, TokenRestrictedSids, TokenPrivileges, TokenPrimaryGroup, TokenSource, TokenDefaultDacl, TokenStatistics, TokenOrigin, TokenLinkedToken, TokenLogonSid, TokenElevation, TokenIntegrityLevel, TokenMandatoryPolicy, SE_ASSIGNPRIMARYTOKEN_NAME, SE_BACKUP_NAME, SE_CREATE_PAGEFILE_NAME, SE_CREATE_TOKEN_NAME, SE_DEBUG_NAME, SE_LOAD_DRIVER_NAME, SE_MACHINE_ACCOUNT_NAME, SE_RESTORE_NAME, SE_SHUTDOWN_NAME, SE_TAKE_OWNERSHIP_NAME, SE_TCB_NAME # Need: SE_ENABLE_DELEGATION_NAME, SE_MANAGE_VOLUME_NAME, SE_RELABEL_NAME, SE_SYNC_AGENT_NAME, SE_TRUSTED_CREDMAN_ACCESS_NAME k32 = ctypes.windll.kernel32 wow64 = ctypes.c_long( 0 ) on64bitwindows = 1 remote_server = None remote_username = None remote_password = None remote_domain = None local_ips = socket.gethostbyname_ex(socket.gethostname())[2] # have to do this before Wow64DisableWow64FsRedirection version = "1.0" svnversion="$Revision$" # Don't change this line. Auto-updated. svnnum=re.sub('[^0-9]', '', svnversion) if svnnum: version = version + "svn" + svnnum all_checks = 0 registry_checks = 0 path_checks = 0 service_checks = 0 service_audit = 0 drive_checks = 0 eventlog_checks = 0 progfiles_checks = 0 process_checks = 0 share_checks = 0 passpol_audit = 0 user_group_audit = 0 logged_in_audit = 0 process_audit = 0 admin_users_audit= 0 host_info_audit = 0 ignore_trusted = 0 owner_info = 0 weak_perms_only = 0 host_info_audit = 0 patch_checks = 0 verbose = 0 report_file_name = None kb_nos = { '977165': 'MS10_015 Vulnerabilities in Windows Kernel Could Allow Elevation of Privilege (kitrap0d - meterpreter "getsystem")', '828749': 'MS03_049 Microsoft Workstation Service NetAddAlternateComputerName Overflow (netapi) ', '828028': 'MS04_007 Microsoft ASN.1 Library Bitstring Heap Overflow (killbill) ', '835732': 'MS04_011 Microsoft LSASS Service DsRolerUpgradeDownlevelServer Overflow (lsass) ', '841533': 'MS04_031 Microsoft NetDDE Service Overflow (netdde)', '899588': 'MS05_039 Microsoft Plug and Play Service Overflow (pnp)', '911280': 'MS06_025 Microsoft RRAS Service RASMAN Registry Overflow (rasmans_reg)', '911280': 'MS06_025 Microsoft RRAS Service Overflow (rras)', '921883': 'MS06_040 Microsoft Server Service NetpwPathCanonicalize Overflow (netapi)', '923980': 'MS06_066 Microsoft Services MS06-066 nwapi32.dll (nwapi)', '923980': 'MS06_066 Microsoft Services MS06-066 nwwks.dll (nwwks)', '924270': 'MS06_070 Microsoft Workstation Service NetpManageIPCConnect Overflow (wkssvc)', '935966': 'MS07_029 Microsoft DNS RPC Service extractQuotedChar() Overflow (SMB) (msdns_zonename)', '958644': 'MS08_067 Microsoft Server Service Relative Path Stack Corruption (netapi)', '975517': 'MS09_050 Microsoft SRV2.SYS SMB Negotiate ProcessID Function Table Dereference (smb2_negotiate_func_index)', '823980': 'MS03_026 Microsoft RPC DCOM Interface Overflow', '892944': 'MS05_017 Microsoft Message Queueing Service Path Overflow', '937894': 'MS07_065 Microsoft Message Queueing Service DNS Name Path Overflow' } reg_paths = ( 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services', 'HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run', 'HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run', 'HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce', 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell', 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit', 'HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce', 'HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce', 'HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices', 'HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce', 'HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices', 'HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce', 'HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows', ) # We don't care if some users / groups hold dangerous permission because they're trusted # These have fully qualified names: trusted_principles_fq = ( "BUILTIN\\Administrators", "NT SERVICE\\TrustedInstaller", "NT AUTHORITY\\SYSTEM" ) # We may temporarily regard a user as trusted (e.g. if we're looking for writable # files in a user's path, we do not care that he can write to his own path) tmp_trusted_principles_fq = ( ) eventlog_key_hklm = 'SYSTEM\CurrentControlSet\Services\Eventlog' # We don't care if members of these groups hold dangerous permission because they're trusted # These have names without a domain: trusted_principles = ( "Administrators", "Domain Admins", "Enterprise Admins", ) # Windows privileges from windows_privileges = ( "SeAssignPrimaryTokenPrivilege", "SeBackupPrivilege", "SeCreatePagefilePrivilege", "SeCreateTokenPrivilege", "SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeLoadDriverPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege", "SeRelabelPrivilege", "SeRestorePrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege", "SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTrustedCredManAccessPrivilege", "SeSecurityPrivilege", "SeRemoteShutdownPrivilege", "SeProfileSingleProcessPrivilege", "SeAuditPrivilege", "SeIncreaseBasePriorityPrivilege", "SeIncreaseWorkingSetPrivilege", "SeIncreaseQuotaPrivilege", "SeLockMemoryPrivilege", "SeSystemEnvironmentPrivilege", "SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeImpersonatePrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege", "SeTimeZonePrivilege", "SeUndockPrivilege", "SeUnsolicitedInputPrivilege", "SeBatchLogonRight", "SeDenyBatchLogonRight", "SeDenyInteractiveLogonRight", "SeDenyNetworkLogonRight", "SeDenyRemoteInteractiveLogonRight", "SeDenyServiceLogonRight", "SeInteractiveLogonRight", "SeNetworkLogonRight", "SeRemoteInteractiveLogonRight", "SeServiceLogonRight" ) share_types = ( "STYPE_IPC", "STYPE_DISKTREE", "STYPE_PRINTQ", "STYPE_DEVICE", ) sv_types = ( "SV_TYPE_WORKSTATION", "SV_TYPE_SERVER", "SV_TYPE_SQLSERVER", "SV_TYPE_DOMAIN_CTRL", "SV_TYPE_DOMAIN_BAKCTRL", "SV_TYPE_TIME_SOURCE", "SV_TYPE_AFP", "SV_TYPE_NOVELL", "SV_TYPE_DOMAIN_MEMBER", "SV_TYPE_PRINTQ_SERVER", "SV_TYPE_DIALIN_SERVER", "SV_TYPE_XENIX_SERVER", "SV_TYPE_NT", "SV_TYPE_WFW", "SV_TYPE_SERVER_MFPN", "SV_TYPE_SERVER_NT", "SV_TYPE_POTENTIAL_BROWSER", "SV_TYPE_BACKUP_BROWSER", "SV_TYPE_MASTER_BROWSER", "SV_TYPE_DOMAIN_MASTER", "SV_TYPE_SERVER_OSF", "SV_TYPE_SERVER_VMS", "SV_TYPE_WINDOWS", "SV_TYPE_DFS", "SV_TYPE_CLUSTER_NT", "SV_TYPE_TERMINALSERVER", # missing from win32netcon.py #"SV_TYPE_CLUSTER_VS_NT", # missing from win32netcon.py "SV_TYPE_DCE", "SV_TYPE_ALTERNATE_XPORT", "SV_TYPE_LOCAL_LIST_ONLY", "SV_TYPE_DOMAIN_ENUM" ) win32netcon.SV_TYPE_TERMINALSERVER = 0x2000000 dangerous_perms_write = { # http://www.tek-tips.com/faqs.cfm?fid 'share': { ntsecuritycon: ( "FILE_READ_DATA", # "FILE_WRITE_DATA", "FILE_APPEND_DATA", "FILE_READ_EA", # "FILE_WRITE_EA", "FILE_EXECUTE", # "FILE_READ_ATTRIBUTES", # "FILE_WRITE_ATTRIBUTES", "DELETE", "READ_CONTROL", # "WRITE_DAC", "WRITE_OWNER", "SYNCHRONIZE", # ) }, 'file': { ntsecuritycon: ( #"FILE_READ_DATA", "FILE_WRITE_DATA", "FILE_APPEND_DATA", #"FILE_READ_EA", "FILE_WRITE_EA", #"FILE_EXECUTE", #"FILE_READ_ATTRIBUTES", "FILE_WRITE_ATTRIBUTES", "DELETE", #"READ_CONTROL", "WRITE_DAC", "WRITE_OWNER", #"SYNCHRONIZE", ) }, # http://msdn.microsoft.com/en-us/library/ms724878(VS.85).aspx # KEY_ALL_ACCESS: STANDARD_RIGHTS_REQUIRED KEY_QUERY_VALUE KEY_SET_VALUE KEY_CREATE_SUB_KEY KEY_ENUMERATE_SUB_KEYS KEY_NOTIFY KEY_CREATE_LINK # KEY_CREATE_LINK (0x0020) Reserved for system use. # KEY_CREATE_SUB_KEY (0x0004) Required to create a subkey of a registry key. # KEY_ENUMERATE_SUB_KEYS (0x0008) Required to enumerate the subkeys of a registry key. # KEY_EXECUTE (0x20019) Equivalent to KEY_READ. # KEY_NOTIFY (0x0010) Required to request change notifications for a registry key or for subkeys of a registry key. # KEY_QUERY_VALUE (0x0001) Required to query the values of a registry key. # KEY_READ (0x20019) Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values. # KEY_SET_VALUE (0x0002) Required to create, delete, or set a registry value. # KEY_WOW64_32KEY (0x0200) Indicates that an application on 64-bit Windows should operate on the 32-bit registry view. For more information, see Accessing an Alternate Registry View. This flag must be combined using the OR operator with the other flags in this table that either query or access registry values. # Windows 2000: This flag is not supported. # KEY_WOW64_64KEY (0x0100) Indicates that an application on 64-bit Windows should operate on the 64-bit registry view. For more information, see Accessing an Alternate Registry View. # This flag must be combined using the OR operator with the other flags in this table that either query or access registry values. # Windows 2000: This flag is not supported. # KEY_WRITE (0x20006) Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights. # "STANDARD_RIGHTS_REQUIRED", # "STANDARD_RIGHTS_WRITE", # "STANDARD_RIGHTS_READ", # "DELETE", # "READ_CONTROL", # "WRITE_DAC", #"WRITE_OWNER", 'reg': { _winreg: ( #"KEY_ALL_ACCESS", # Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, and KEY_CREATE_LINK access rights. #"KEY_QUERY_VALUE", # GUI "Query Value" "KEY_SET_VALUE", # GUI "Set Value". Required to create, delete, or set a registry value. "KEY_CREATE_LINK", # GUI "Create Link". Reserved for system use. "KEY_CREATE_SUB_KEY", # GUI "Create subkey" # "KEY_ENUMERATE_SUB_KEYS", # GUI "Create subkeys" # "KEY_NOTIFY", # GUI "Notify" #"KEY_EXECUTE", # same as KEY_READ #"KEY_READ", #"KEY_WOW64_32KEY", #"KEY_WOW64_64KEY", # "KEY_WRITE", # Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights. ), ntsecuritycon: ( "DELETE", # GUI "Delete" # "READ_CONTROL", # GUI "Read Control" - read security descriptor "WRITE_DAC", # GUI "Write DAC" "WRITE_OWNER", # GUI "Write Owner" #"STANDARD_RIGHTS_REQUIRED", #"STANDARD_RIGHTS_WRITE", #"STANDARD_RIGHTS_READ", ) }, 'directory': { ntsecuritycon: ( #"FILE_LIST_DIRECTORY", "FILE_ADD_FILE", "FILE_ADD_SUBDIRECTORY", #"FILE_READ_EA", "FILE_WRITE_EA", #"FILE_TRAVERSE", "FILE_DELETE_CHILD", #"FILE_READ_ATTRIBUTES", "FILE_WRITE_ATTRIBUTES", "DELETE", #"READ_CONTROL", "WRITE_DAC", "WRITE_OWNER", #"SYNCHRONIZE", ) }, 'service_manager': { # For service manager # http://msdn.microsoft.com/en-us/library/ms685981(VS.85).aspx # SC_MANAGER_ALL_ACCESS (0xF003F) Includes STANDARD_RIGHTS_REQUIRED, in addition to all access rights in this table. # SC_MANAGER_CREATE_SERVICE (0x0002) Required to call the CreateService function to create a service object and add it to the database. # SC_MANAGER_CONNECT (0x0001) Required to connect to the service control manager. # SC_MANAGER_ENUMERATE_SERVICE (0x0004) Required to call the EnumServicesStatusEx function to list the services that are in the database. # SC_MANAGER_LOCK (0x0008) Required to call the LockServiceDatabase function to acquire a lock on the database. # SC_MANAGER_MODIFY_BOOT_CONFIG (0x0020) Required to call the NotifyBootConfigStatus function. # SC_MANAGER_QUERY_LOCK_STATUS (0x0010)Required to call the QueryServiceLockStatus function to retrieve the lock status information for the database. win32service: ( "SC_MANAGER_ALL_ACCESS", "SC_MANAGER_CREATE_SERVICE", "SC_MANAGER_CONNECT", "SC_MANAGER_ENUMERATE_SERVICE", "SC_MANAGER_LOCK", "SC_MANAGER_MODIFY_BOOT_CONFIG", "SC_MANAGER_QUERY_LOCK_STATUS", ) }, 'service': { # For services: # http://msdn.microsoft.com/en-us/library/ms685981(VS.85).aspx # SERVICE_ALL_ACCESS (0xF01FF) Includes STANDARD_RIGHTS_REQUIRED in addition to all access rights in this table. # SERVICE_CHANGE_CONFIG (0x0002) Required to call the ChangeServiceConfig or ChangeServiceConfig2 function to change the service configuration. Because this grants the caller the right to change the executable file that the system runs, it should be granted only to administrators. # SERVICE_ENUMERATE_DEPENDENTS (0x0008) Required to call the EnumDependentServices function to enumerate all the services dependent on the service. # SERVICE_INTERROGATE (0x0080) Required to call the ControlService function to ask the service to report its status immediately. # SERVICE_PAUSE_CONTINUE (0x0040) Required to call the ControlService function to pause or continue the service. # SERVICE_QUERY_CONFIG (0x0001) Required to call the QueryServiceConfig and QueryServiceConfig2 functions to query the service configuration. # SERVICE_QUERY_STATUS (0x0004) Required to call the QueryServiceStatusEx function to ask the service control manager about the status of the service. # SERVICE_START (0x0010) Required to call the StartService function to start the service. # SERVICE_STOP (0x0020) Required to call the ControlService function to stop the service. # SERVICE_USER_DEFINED_CONTROL(0x0100) Required to call the ControlService function to specify a user-defined control code. win32service: ( # "SERVICE_INTERROGATE", # "SERVICE_QUERY_STATUS", # "SERVICE_ENUMERATE_DEPENDENTS", "SERVICE_ALL_ACCESS", "SERVICE_CHANGE_CONFIG", "SERVICE_PAUSE_CONTINUE", # "SERVICE_QUERY_CONFIG", "SERVICE_START", "SERVICE_STOP", # "SERVICE_USER_DEFINED_CONTROL", # TODO this is granted most of the time. Double check that's not a bad thing. ) }, } all_perms = { 'share': { ntsecuritycon: ( "FILE_READ_DATA", # "FILE_WRITE_DATA", "FILE_APPEND_DATA", "FILE_READ_EA", # "FILE_WRITE_EA", "FILE_EXECUTE", # "FILE_READ_ATTRIBUTES", # "FILE_WRITE_ATTRIBUTES", "DELETE", "READ_CONTROL", # "WRITE_DAC", "WRITE_OWNER", "SYNCHRONIZE", # ) }, 'file': { ntsecuritycon: ( "FILE_READ_DATA", "FILE_WRITE_DATA", "FILE_APPEND_DATA", "FILE_READ_EA", "FILE_WRITE_EA", "FILE_EXECUTE", "FILE_READ_ATTRIBUTES", "FILE_WRITE_ATTRIBUTES", "DELETE", "READ_CONTROL", "WRITE_DAC", "WRITE_OWNER", "SYNCHRONIZE", ) }, 'reg': { _winreg: ( "KEY_ALL_ACCESS", "KEY_CREATE_LINK", "KEY_CREATE_SUB_KEY", "KEY_ENUMERATE_SUB_KEYS", "KEY_EXECUTE", "KEY_NOTIFY", "KEY_QUERY_VALUE", "KEY_READ", "KEY_SET_VALUE", "KEY_WOW64_32KEY", "KEY_WOW64_64KEY", "KEY_WRITE", ), ntsecuritycon: ( "DELETE", "READ_CONTROL", "WRITE_DAC", "WRITE_OWNER", "STANDARD_RIGHTS_REQUIRED", "STANDARD_RIGHTS_WRITE", "STANDARD_RIGHTS_READ", "SYNCHRONIZE", ) }, 'directory': { ntsecuritycon: ( "FILE_LIST_DIRECTORY", "FILE_ADD_FILE", "FILE_ADD_SUBDIRECTORY", "FILE_READ_EA", "FILE_WRITE_EA", "FILE_TRAVERSE", "FILE_DELETE_CHILD", "FILE_READ_ATTRIBUTES", "FILE_WRITE_ATTRIBUTES", "DELETE", "READ_CONTROL", "WRITE_DAC", "WRITE_OWNER", "SYNCHRONIZE", ) }, 'service_manager': { win32service: ( "SC_MANAGER_ALL_ACCESS", "SC_MANAGER_CREATE_SERVICE", "SC_MANAGER_CONNECT", "SC_MANAGER_ENUMERATE_SERVICE", "SC_MANAGER_LOCK", "SC_MANAGER_MODIFY_BOOT_CONFIG", "SC_MANAGER_QUERY_LOCK_STATUS", ) }, 'service': { win32service: ( "SERVICE_INTERROGATE", "SERVICE_QUERY_STATUS", "SERVICE_ENUMERATE_DEPENDENTS", "SERVICE_ALL_ACCESS", "SERVICE_CHANGE_CONFIG", "SERVICE_PAUSE_CONTINUE", "SERVICE_QUERY_CONFIG", "SERVICE_START", "SERVICE_STOP", "SERVICE_USER_DEFINED_CONTROL", # TODO this is granted most of the time. Double check that's not a bad thing. ) }, 'process': { win32con: ( "PROCESS_TERMINATE", "PROCESS_CREATE_THREAD", "PROCESS_VM_OPERATION", "PROCESS_VM_READ", "PROCESS_VM_WRITE", "PROCESS_DUP_HANDLE", "PROCESS_CREATE_PROCESS", "PROCESS_SET_QUOTA", "PROCESS_SET_INFORMATION", "PROCESS_QUERY_INFORMATION", "PROCESS_ALL_ACCESS" ), ntsecuritycon: ( "DELETE", "READ_CONTROL", "WRITE_DAC", "WRITE_OWNER", "SYNCHRONIZE", "STANDARD_RIGHTS_REQUIRED", "STANDARD_RIGHTS_READ", "STANDARD_RIGHTS_WRITE", "STANDARD_RIGHTS_EXECUTE", "STANDARD_RIGHTS_ALL", "SPECIFIC_RIGHTS_ALL", "ACCESS_SYSTEM_SECURITY", "MAXIMUM_ALLOWED", "GENERIC_READ", "GENERIC_WRITE", "GENERIC_EXECUTE", "GENERIC_ALL" ) }, 'thread': { win32con: ( "THREAD_TERMINATE", "THREAD_SUSPEND_RESUME", "THREAD_GET_CONTEXT", "THREAD_SET_CONTEXT", "THREAD_SET_INFORMATION", "THREAD_QUERY_INFORMATION", "THREAD_SET_THREAD_TOKEN", "THREAD_IMPERSONATE", "THREAD_DIRECT_IMPERSONATION", "THREAD_ALL_ACCESS", "THREAD_QUERY_LIMITED_INFORMATION", "THREAD_SET_LIMITED_INFORMATION" ), ntsecuritycon: ( "DELETE", "READ_CONTROL", "WRITE_DAC", "WRITE_OWNER", "SYNCHRONIZE", ) }, } # Used to store a data structure representing the issues we've found # We use this to generate the report issues = {} issue_template = { 'WPC001': { 'title': "Insecure Permissions on Program Files", 'description': '''Some of the programs in %ProgramFiles% and/or %ProgramFiles(x86)% could be changed by non-administrative users. This could allow certain users on the system to place malicious code into certain key directories, or to replace programs with malicious ones. A malicious local user could use this technique to hijack the privileges of other local users, running commands with their privileges. ''', 'recommendation': '''Programs run by multiple users should only be changable only by administrative users. The directories containing these programs should only be changable only by administrators too. Revoke write privileges for non-administrative users from the above programs and directories.''', 'supporting_data': { 'writable_progs': { 'section': "description", 'preamble': "The programs below can be modified by non-administrative users:", }, 'writable_dirs': { 'section': "description", 'preamble': "The directories below can be changed by non-administrative users:", }, } }, 'WPC002': { 'title': "Insecure Permissions on Files and Directories in Path (OBSELETE ISSUE)", 'description': '''Some of the programs and directories in the %PATH% variable could be changed by non-administrative users. This could allow certain users on the system to place malicious code into certain key directories, or to replace programs with malicious ones. A malicious local user could use this technique to hijack the privileges of other local users, running commands with their privileges. ''', 'recommendation': '''Programs run by multiple users should only be changable only by administrative users. The directories containing these programs should only be changable only by administrators too. Revoke write privileges for non-administrative users from the above programs and directories.''', 'supporting_data': { 'writable_progs': { 'section': "description", 'preamble': "The programs below are in the path of the user used to carry out this audit. Each one can be changed by non-administrative users:", }, 'writable_dirs': { 'section': "description", 'preamble': "The directories below are in the path of the user used to carry out this audit. Each one can be changed by non-administrative users:", } } }, 'WPC003': { 'title': "Insecure Permissions In Windows Registry", 'description': '''Some registry keys that hold the names of programs run by other users were checked and found to have insecure permissions. It would be possible for non-administrative users to modify the registry to cause a different programs to be run. This weakness could be abused by low-privileged users to run commands of their choosing with higher privileges.''', 'recommendation': '''Modify the permissions on the above registry keys to allow only administrators write access. Revoke write access from low-privileged users.''', 'supporting_data': { 'writable_reg_paths': { 'section': "description", 'preamble': "The registry keys below could be changed by non-administrative users:", }, } }, 'WPC004': { 'title': "Insecure Permissions On Windows Service Executables", 'description': '''Some of the programs that are run when Windows Services start were found to have weak file permissions. It is possible for non-administrative local users to replace some of the Windows Service executables with malicious programs.''', 'recommendation': '''Modify the permissions on the above programs to allow only administrators write access. Revoke write access from low-privileged users.''', 'supporting_data': { 'writable_progs': { 'section': "description", 'preamble': "The programs below could be changed by non-administrative users:", }, } }, 'WPC005': { 'title': "Insecure Permissions On Windows Service Registry Keys (NOT IMPLEMENTED YET)", 'description': '''Some registry keys that hold the names of programs that are run when Windows Services start were found to have weak file permissions. They could be changed by non-administrative users to cause malicious programs to be run instead of the intended Windows Service Executable.''', 'recommendation': '''Modify the permissions on the above programs to allow only administrators write access. Revoke write access from low-privileged users.''', 'supporting_data': { 'writable_reg_paths': { 'section': "description", 'preamble': "The registry keys below could be changed by non-administrative users:", }, } }, 'WPC007': { 'title': "Insecure Permissions On Event Log File", 'description': '''Some of the Event Log files could be changed by non-administrative users. This may allow attackers to cover their tracks.''', 'recommendation': '''Modify the permissions on the above files to allow only administrators write access. Revoke write access from low-privileged users.''', 'supporting_data': { 'writable_eventlog_file': { 'section': "description", 'preamble': "The files below could be changed by non-administrative users:", }, } }, 'WPC008': { 'title': "Insecure Permissions On Event Log DLL", 'description': '''Some DLL files used by Event Viewer to display logs could be changed by non-administrative users. It may be possible to replace these with a view to having code run when an administrative user next views log files.''', 'recommendation': '''Modify the permissions on the above DLLs to allow only administrators write access. Revoke write access from low-privileged users.''', 'supporting_data': { 'writable_eventlog_dll': { 'section': "description", 'preamble': "The DLL files below could be changed by non-administrative users:", }, } }, 'WPC009': { 'title': "Insecure Permissions On Event Log Registry Key (NOT IMPLMENTED YET)", 'description': '''Some registry keys that hold the names of DLLs used by Event Viewer and the location of Log Files are writable by non-administrative users. It may be possible to maliciouly alter the registry to change the location of log files or run malicious code.''', 'recommendation': '''Modify the permissions on the above programs to allow only administrators write access. Revoke write access from low-privileged users.''', 'supporting_data': { 'writable_eventlog_key': { 'section': "description", 'preamble': "The registry keys below could be changed by non-administrative users:", }, } }, 'WPC010': { 'title': "Insecure Permissions On Drive Root", 'description': '''Some of the local drive roots allow non-administrative users to create files and folders. This could allow malicious files to be placed in on the server in the hope that they'll allow a local user to escalate privileges (e.g. create program.exe which might get accidentally launched by another user).''', 'recommendation': '''Modify the permissions on the drive roots to only allow administrators write access. Revoke write access from low-privileged users.''', 'supporting_data': { 'writable_drive_root': { 'section': "description", 'preamble': "The following drives allow non-administrative users to write to their root directory:", }, } }, 'WPC011': { 'title': "Insecure (Non-NTFS) File System Used", 'description': '''Some local drives use Non-NTFS file systems. These drive therefore don't allow secure file permissions to be used. Any local user can change any data on these drives.''', 'recommendation': '''Use NTFS filesystems instead of FAT. Ensure that strong file permissions are set - NTFS file permissions are insecure by default after FAT file systems are converted.''', 'supporting_data': { 'fat_fs_drives': { 'section': "description", 'preamble': "The following drives use Non-NTFS file systems:", }, } }, 'WPC012': { 'title': "Insecure Permissions On Windows Services", 'description': '''Some of the Windows Services installed have weak permissions. This could allow non-administrators to manipulate services to their own advantage. The impact depends on the permissions granted, but can include starting services, stopping service or even reconfiguring them to run a different program. This can lead to denial of service or even privilege escalation if the service is running as a user with more privilege than a malicious local user.''', 'recommendation': '''Review the permissions that have been granted to non-administrative users and revoke access where possible.''', 'supporting_data': { 'weak_service_perms': { 'section': "description", 'preamble': "Some Windows Services can be manipulated by non-administrator users:", }, } }, 'WPC013': { 'title': "Insecure Permissions On Files / Directories In System PATH", 'description': '''Some programs/directories in the system path have weak permissions. TODO which user are affected by this issue?''', 'recommendation': '''Review the permissions that have been granted to non-administrative users and revoke access where possible.''', 'supporting_data': { 'weak_perms_exe': { 'section': "description", 'preamble': "The following programs/DLLs in the system PATH can be manipulated by non-administrator users:", }, 'weak_perms_dir': { 'section': "description", 'preamble': "The following directories in the system PATH can be manipulated by non-administrator users:", }, } }, 'WPC014': { 'title': "Insecure Permissions On Files / Directories In Current User's PATH", 'description': '''Some programs/directories in the path of the user used to perform this audit have weak permissions. TODO which user was used to perform this audit?''', 'recommendation': '''Review the permissions that have been granted to non-administrative users and revoke access where possible.''', 'supporting_data': { 'weak_perms_exe': { 'section': "description", 'preamble': "The following programs/DLLs in current user's PATH can be manipulated by non-administrator users:", }, 'weak_perms_dir': { 'section': "description", 'preamble': "The following directories in the current user's PATH can be manipulated by non-administrator users:", }, } }, 'WPC015': { 'title': "Insecure Permissions On Files / Directories In Users' PATHs (NEED TO CHECK THIS WORKS)", 'description': '''Some programs/directories in the paths of users on this system have weak permissions.''', 'recommendation': '''Review the permissions that have been granted to non-administrative users and revoke access where possible.''', 'supporting_data': { 'weak_perms_exe': { 'section': "description", 'preamble': "The following programs/DLLs in users' PATHs can be manipulated by non-administrator users:", }, 'weak_perms_dir': { 'section': "description", 'preamble': "The following directories in users' PATHs can be manipulated by non-administrator users:", }, } }, 'WPC016': { 'title': "Insecure Permissions On Running Programs", 'description': '''Some programs running at the time of the audit have weak file permissions. The corresponding programs could be altered by non-administrator users.''', 'recommendation': '''Review the permissions that have been granted to non-administrative users and revoke access where possible.''', 'supporting_data': { 'weak_perms_exes': { 'section': "description", 'preamble': "The following programs were running at the time of the audit, but could be changed on-disk by non-administrator users:", }, 'weak_perms_dlls': { 'section': "description", 'preamble': "The following DLLs are used by program which were running at the time of the audit. These DLLs can be changed on-disk by non-administrator users:", }, } }, 'WPC017': { 'title': "Shares Accessible By Non-Admin Users", 'description': '''The share-level permissions on some Windows file shares allows access by non-administrative users. This can often be desirable, in which case this issue can be ignored. However, sometimes it can allow data to be stolen or programs to be malciously modified. NB: Setting strong NTFS permissions can sometimes mean that data which seems to be exposed on a share actually isn't accessible.''', 'recommendation': '''Review the share-level permissions that have been granted to non-administrative users and revoke access where possible. Share-level permissions can be viewed in Windows Explorer: Right-click folder | Sharing and Security | "Sharing" tab | "Permissions" button (for XP - other OSs may vary slightly).''', 'supporting_data': { 'non_admin_shares': { 'section': "description", 'preamble': "The following shares are accessible by non-administrative users:", }, } }, } issue_template_html = ''' <h3>REPLACE_TITLE</h3> <table> <tr> <td> <b>Description</b> </td> <td> REPLACE_DESCRIPTION REPLACE_DESCRIPTION_DATA </td> </tr> <tr> <td> <b>Recommendation</b> </td> <td> REPLACE_RECOMMENDATION REPLACE_RECOMMENDATION_DATA </td> </tr> </table> ''' issue_list_html =''' REPLACE_PREAMBLE <ul> REPLACE_ITEM </ul> ''' # TODO nice looking css, internal links, risk ratings # TODO record group members for audit user, separate date and time; os and sp overview_template_html = ''' <html> <head> <style type="text/css"> body {color:black} td { vertical-align:top; } h1 {font-size: 300%; text-align:center} h2 {font-size: 200%; margin-top: 25px; margin-bottom: 0px; padding: 5px; background-color: #CCCCCC;} h3 {font-size: 150%; font-weight: normal; padding: 5px; background-color: #EEEEEE; margin-top: 10px;} #frontpage {height: 270px; background-color: #F3F3F3;} p.ex {color:rgb(0,0,255)} #customers { font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; /* width:100%; */ padding:10px 0px 0px 0px; border-collapse:collapse; } #customers td, #customers th { font-size:1em; border:1px solid #989898; padding:3px 7px 2px 7px; } #customers th { font-size:1.1em; text-align:left; padding-top:5px; padding-bottom:4px; background-color:#A7C942; color:#ffffff; } #customers tr.alt td { color:#000000; background-color:#EAF2D3; } </style> </head> <div id="frontpage"> <h1><p>windows-privesc-check</p> <p>Audit of Host: </p><p>REPLACE_HOSTNAME</p></h1> </div> <h2>Contents</h2> REPLACE_CONTENTS <h2>Information about this Audit</h2> <p>This report was generated on REPLACE_DATETIME by vREPLACE_VERSION of <a href="http://pentestmonkey.net/windows-privesc-check">windows-privesc-check</a>.</p> <p>The audit was run as the user REPLACE_AUDIT_USER.</p> <p>The following table provides information about this audit:</p> <table id="customers" border="1"> <tr> <td>Hostname</td> <td>REPLACE_HOSTNAME</td> </tr> <tr class="alt"> <td>Domain/Workgroup</td> <td>REPLACE_DOMWKG</td> </tr> <tr> <td>Operating System</td> <td>REPLACE_OS</td> </tr> <tr class="alt"> <td>IP Addresses</td> <td><ul>REPLACE_IPS</ul></td> </tr> </table> <h2>Escalation Vectors</h2> REPLACE_ISSUES <h2>Scan Parameters</h2> For the purposes of the audit the following users were considered to be trusted. Any privileges assigned to them have not been considered as potential attack vectors: <ul> REPLACE_TRUSTED_USERS </ul> Additionally members of the following groups were considered trusted: <ul> REPLACE_TRUSTED_GROUPS </ul> The following file/directory/registry permissions were considered to be potentially dangerous. This audit exclusively searched for instances of these permissions: <ul> REPLACE_DANGEROUS_PERMS </ul> </html> ''' def usage(): print "Usage: windows-privesc-check [options] checks" print "" print "checks must be at least one of:" print " -a|--all_checks Run all security checks (see below)" print " -r|--registry_checks Check RunOnce and other critical keys" print " -t|--path_checks Check %PATH% for insecure permissions" print " -S|--service_checks Check Windows services for insecure permissions" print " -d|--drive_checks Check for FAT filesystems and weak perms in root dir" print " -E|--eventlog_checks Check Event Logs for insecure permissions" print " -F|--progfiles_checks Check Program Files directories for insecure perms" print " -R|--process_checks Check Running Processes for insecure permissions" print " -H|--share_checks Check shares for insecure permissions" #print " -T|--patch_checks Check some important patches" print " -U|--user_groups Dump users, groups and privileges (no HTML yet)" print " -A|--admin_users Dump admin users / high priv users (no HTML yet)" print " -O|--processes Dump process info (no HTML yet)" print " -P|--passpol Dump password policy (no HTML yet)" print " -i|--host_info Dump host info - OS, domain controller, ... (no HTML yet)" print " -e|--services Dump service info (no HTML yet)" # TODO options to flag a user/group as trusted print "" print "options are:" print " -h|--help This help message" print " -w|--write_perms_only Only list write perms (dump opts only)" print " -I|--ignore_trusted Ignore trusted users, empty groups (dump opts only)" print " -W|--owner_info Owner, Group info (dump opts only)" print " -v|--verbose More detail output (use with -U)" print " -o|--report_file file Report filename. Default privesc-report-[host].html" print " -s|--server host Remote server name. Only works with -u!" print " -u|--username arg Remote username. Only works with -u!" print " -p|--password arg Remote password. Only works with -u!" print " -d|--domain arg Remote domain. Only works with -u!" print "" sys.exit(0) # # Reporting functions # def format_issues(format, issue_template, issue_data): report = "" toc = "" overview = overview_template_html overview = overview.replace('REPLACE_HOSTNAME', audit_data['hostname']) overview = overview.replace('REPLACE_DOMWKG', audit_data['domwkg']) # overview = overview.replace('REPLACE_IPS', "<li>" + "</li><li>".join(audit_data['ips']) + "</li>") for item in audit_data['ips']: overview = overview.replace('REPLACE_IPS', list_item("REPLACE_IPS", item)) overview = overview.replace('REPLACE_IPS', '') overview = overview.replace('REPLACE_OS', audit_data['os_name'] + " (" + audit_data['os_version'] + ")") overview = overview.replace('REPLACE_VERSION', audit_data['version']) overview = overview.replace('REPLACE_DATETIME', audit_data['datetime']) overview = overview.replace('REPLACE_AUDIT_USER', audit_data['audit_user']) for item in audit_data['trusted_users']: overview = overview.replace('REPLACE_TRUSTED_USERS', list_item("REPLACE_TRUSTED_USERS", item)) overview = overview.replace('REPLACE_TRUSTED_USERS', '') for item in audit_data['trusted_groups']: overview = overview.replace('REPLACE_TRUSTED_GROUPS', list_item("REPLACE_TRUSTED_GROUPS", item)) overview = overview.replace('REPLACE_TRUSTED_GROUPS', '') permlist = '' for permtype in dangerous_perms_write.keys(): permlist += "Permission type '" + permtype + "'<p>" permlist += "<ul>" for location in dangerous_perms_write[permtype].keys(): for item in dangerous_perms_write[permtype][location]: permlist += "\t<li>" + item + "</li>" permlist += "</ul>" #for item in audit_data['dangerous_privs']: # overview = overview.replace('REPLACE_DANGEROUS_PERM', list_item("REPLACE_DANGEROUS_PERM", item)) #overview = overview.replace('REPLACE_DANGEROUS_PERM', '') overview = overview.replace('REPLACE_DANGEROUS_PERMS', permlist) for item in audit_data['ips']: overview = overview.replace('REPLACE_IP', list_item("REPLACE_IPS", item)) overview = overview.replace('REPLACE_IP', '') for issue_no in issue_data: # print "[V] Processing issue issue_no\n" report = report + format_issue(format, issue_no, issue_data, issue_template) toc = toc + '<a href="#' + issue_template[issue_no]['title'] + '">' + issue_template[issue_no]['title'] + "</a><p>" if report: overview = overview.replace('REPLACE_ISSUES', report) overview = overview.replace('REPLACE_CONTENTS', toc) else: overview = overview.replace('REPLACE_ISSUES', "No issues found") overview = overview.replace('REPLACE_CONTENTS', "No issues found") return overview def list_item(tag, item): return "<li>" + item + "</li>\n" + tag def format_issue(format, issue_no, issue_data, issue_template): # $format is xml, html, or text if not issue_no in issue_template: print "[E] Can't find an issue template for issue number issue_no. Bug!" sys.exit(1) issue = issue_template_html issue = issue.replace('REPLACE_TITLE', '<a name="' + issue_template[issue_no]['title'] + '">' + issue_template[issue_no]['title'] + '</a>') description = issue_template[issue_no]['description'] description = description.replace('\n\n+', "<p>\n") for key in issue_data[issue_no]: #print "[D] Processing data for %s" % key # print "[D] $key has type issue_data[issue_no]['$key']['type']\n" #if issue_data[issue_no][key]['type'] == "list": # TODO alter data structre to include type #section = issue_template[issue_no]['supporting_data'][key]['section'] # print "[D] Data belongs to section section\n" #if (section == "description"): preamble = issue_template[issue_no]['supporting_data'][key]['preamble'] data = issue_list_html data = data.replace('REPLACE_PREAMBLE', preamble) for item in issue_data[issue_no][key]: # TODO alter data structure to include data # print "Processing item " + item perm_string = " ".join(issue_data[issue_no][key][item]) data = data.replace('REPLACE_ITEM', list_item("REPLACE_ITEM", item + ": " + perm_string)) data = data.replace('REPLACE_ITEM', '') issue = issue.replace('REPLACE_DESCRIPTION_DATA', data + "\nREPLACE_DESCRIPTION_DATA") #elif section == "recommendation": # pass #issue = issue.replace('REPLACE_RECOMMENDATION_DATA', "data\nREPLACE_DESCRIPTION_DATA', issue = issue.replace('REPLACE_RECOMMENDATION_DATA', '') issue = issue.replace('REPLACE_DESCRIPTION_DATA', '') issue = issue.replace('REPLACE_DESCRIPTION', description + "<p>\n") recommendation = issue_template[issue_no]['recommendation'] issue = issue.replace('REPLACE_RECOMMENDATION', recommendation + "<p>\n") recommendation = recommendation.replace('\n\n+', '<p>\n') return issue def format_audit_data(format, audit_data): # $format is xml, html, or text print "format_audit_data not implemented yet" # Inputs: # string: issue_name # array: weak_perms def save_issue(issue_name, data_type, weak_perms): #print weak_perms global issues if not issue_name in issues: issues[issue_name] = {} #if not 'supporting_data' in issues[issue_name]: # issues[issue_name]['supporting_data'] = {} for weak_perm in weak_perms: object = weak_perm[0] domain = weak_perm[1] name = weak_perm[2] permission = weak_perm[3] key = object + " has the following permissions granted for " + domain + "\\" + name if not data_type in issues[issue_name]: issues[issue_name][data_type]= {} if not key in issues[issue_name][data_type]: issues[issue_name][data_type][key] = [] issues[issue_name][data_type][key].append(permission) issues[issue_name][data_type][key] = list(set(issues[issue_name][data_type][key])) # dedup def save_issue_string(issue_name, data_type, issue_string): #print weak_perms global issues if not issue_name in issues: issues[issue_name] = {} if not data_type in issues[issue_name]: issues[issue_name][data_type]= {} if not issue_string in issues[issue_name][data_type]: issues[issue_name][data_type][issue_string] = [] # args: string, string # Returns 1 if the principle provided is trusted (admin / system / user-definted trusted principle) # Returns 0 otherwise def principle_is_trusted(principle, domain): if domain + "\\" + principle in trusted_principles_fq: return 1 if principle in trusted_principles: return 1 global tmp_trusted_principles_fq if domain + "\\" + principle in tmp_trusted_principles_fq: return 1 # Consider groups with zero members to be trusted too try: memberdict, total, rh = win32net.NetLocalGroupGetMembers(remote_server, principle , 1 , 0 , 100000 ) if len(memberdict) == 0: return 1 except: # If a user is a member of a trusted group (like administrators), then they are trusted try: group_attrs = win32net.NetUserGetLocalGroups(remote_server, principle) if set(group_attrs).intersection(set(trusted_principles)): return 1 except: pass return 0 # for memberinfo in memberdict: # print "\t" + memberinfo['name'] + " (" + win32security.ConvertSidToStringSid(memberinfo['sid']) + ")" # TODO ignore groups that only contain administrators # There are all possible objects. SE_OBJECT_TYPE (http://msdn.microsoft.com/en-us/library/aa379593(VS.85).aspx): # win32security.SE_UNKNOWN_OBJECT_TYPE # win32security.SE_FILE_OBJECT # win32security.SE_SERVICE # win32security.SE_PRINTER # win32security.SE_REGISTRY_KEY # win32security.SE_LMSHARE # win32security.SE_KERNEL_OBJECT # win32security.SE_WINDOW_OBJECT # win32security.SE_DS_OBJECT # win32security.SE_DS_OBJECT_ALL # win32security.SE_PROVIDER_DEFINED_OBJECT # win32security.SE_WMIGUID_OBJECT # win32security.SE_REGISTRY_WOW64_32KEY # object_type_s is one of # service # file # dir def check_weak_perms(object_name, object_type_s, perms): object_type = None if object_type_s == 'file': object_type = win32security.SE_FILE_OBJECT if object_type_s == 'directory': object_type = win32security.SE_FILE_OBJECT if object_type_s == 'service': object_type = win32security.SE_SERVICE if object_type == win32security.SE_FILE_OBJECT: # if not os.path.exists(object_name): # print "WARNING: %s doesn't exist" % object_name if os.path.isfile(object_name): object_type_s = 'file' else: object_type_s = 'directory' if object_type == None: print "ERROR: Unknown object type %s" % object_type_s exit(1) try: sd = win32security.GetNamedSecurityInfo ( object_name, object_type, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION ) except: # print "WARNING: Can't get security descriptor for " + object_name + ". skipping. (" + details[2] + ")" return [] return check_weak_perms_sd(object_name, object_type_s, sd, perms) def check_weak_write_perms_by_sd(object_name, object_type_s, sd): return check_weak_perms_sd(object_name, object_type_s, sd, dangerous_perms_write) def check_weak_perms_sd(object_name, object_type_s, sd, perms): dacl= sd.GetSecurityDescriptorDacl() if dacl == None: print "No Discretionary ACL" return [] owner_sid = sd.GetSecurityDescriptorOwner() try: owner_name, owner_domain, type = win32security.LookupAccountSid(remote_server, owner_sid) owner_fq = owner_domain + "\\" + owner_name except: try: owner_fq = owner_name = win32security.ConvertSidToStringSid(owner_sid) owner_domain = "" except: owner_domain = "" owner_fq = owner_name = "INVALIDSID!" weak_perms = [] for ace_no in range(0, dacl.GetAceCount()): #print "[D] ACE #%d" % ace_no ace = dacl.GetAce(ace_no) flags = ace[0][1] try: principle, domain, type = win32security.LookupAccountSid(remote_server, ace[2]) except: principle = win32security.ConvertSidToStringSid(ace[2]) domain = "" #print "[D] ACE is for %s\\%s" % (principle, domain) #print "[D] ACE Perm mask: " + int2bin(ace[1]) #print "[D] ace_type: " + str(ace[0][0]) #print "[D] DACL: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION) if principle_is_trusted(principle, domain): #print "[D] Ignoring trusted principle %s\\%s" % (principle, domain) continue if principle == "CREATOR OWNER": if principle_is_trusted(owner_name, owner_domain): continue else: principle = "CREATOR OWNER [%s]" % owner_fq for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"): if getattr(ntsecuritycon, i) == ace[0][0]: ace_type_s = i if not ace_type_s == "ACCESS_ALLOWED_ACE_TYPE": vprint("WARNING: Unimplmented ACE type encountered: " + ace_type_s + ". skipping.") continue for mod, perms_tuple in perms[object_type_s].iteritems(): for perm in perms_tuple: if getattr(mod, perm) & ace[1] == getattr(mod, perm): weak_perms.append([object_name, domain, principle, perm]) return weak_perms def dump_perms(object_name, object_type_s, options={}): object_type = None if object_type_s == 'file': object_type = win32security.SE_FILE_OBJECT if object_type_s == 'directory': object_type = win32security.SE_FILE_OBJECT if object_type_s == 'service': object_type = win32security.SE_SERVICE if object_type == win32security.SE_FILE_OBJECT: # if not os.path.exists(object_name): # print "WARNING: %s doesn't exist" % object_name if os.path.isfile(object_name): object_type_s = 'file' else: object_type_s = 'directory' if object_type == None: print "ERROR: Unknown object type %s" % object_type_s exit(1) try: sd = win32security.GetNamedSecurityInfo ( object_name, object_type, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION ) except: # print "WARNING: Can't get security descriptor for " + object_name + ". skipping. (" + details[2] + ")" return [] return dump_sd(object_name, object_type_s, sd, options) def dump_sd(object_name, object_type_s, sd, options={}): perms = all_perms if not sd: return dacl = sd.GetSecurityDescriptorDacl() if dacl == None: print "No Discretionary ACL" return [] owner_sid = sd.GetSecurityDescriptorOwner() try: owner_name, owner_domain, type = win32security.LookupAccountSid(remote_server, owner_sid) owner_fq = owner_domain + "\\" + owner_name except: try: owner_fq = owner_name = win32security.ConvertSidToStringSid(owner_sid) owner_domain = "" except: owner_domain = "" owner_fq = owner_name = None group_sid = sd.GetSecurityDescriptorGroup() try: group_name, group_domain, type = win32security.LookupAccountSid(remote_server, group_sid) group_fq = group_domain + "\\" + group_name except: try: group_fq = group_name = win32security.ConvertSidToStringSid(group_sid) group_domain = "" except: group_domain = "" group_fq = group_name = "[none]" if owner_info: print "\tOwner: " + str(owner_fq) print "\tGroup: " + str(group_fq) weak_perms = [] dump_acl(object_name, object_type_s, dacl, options) return def dump_acl(object_name, object_type_s, sd, options={}): dacl = sd if dacl == None: print "No Discretionary ACL" return [] weak_perms = [] for ace_no in range(0, dacl.GetAceCount()): # print "[D] ACE #%d" % ace_no ace = dacl.GetAce(ace_no) flags = ace[0][1] try: principle, domain, type = win32security.LookupAccountSid(remote_server, ace[2]) except: principle = win32security.ConvertSidToStringSid(ace[2]) domain = "" mask = ace[1] if ace[1] < 0: mask = ace[1] + 2**32 if ignore_trusted and principle_is_trusted(principle, domain): # print "[D] Ignoring trusted principle %s\\%s" % (principle, domain) continue if principle == "CREATOR OWNER": if ignore_trusted and principle_is_trusted(owner_name, owner_domain): #print "[D] Ignoring trusted principle (creator owner) %s\\%s" % (principle, domain) continue else: principle = "CREATOR OWNER [%s\%s]" % (domain, principle) for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"): if getattr(ntsecuritycon, i) == ace[0][0]: ace_type_s = i ace_type_short = ace_type_s if ace_type_s == "ACCESS_DENIED_ACE_TYPE": ace_type_short = "DENY" if ace_type_s == "ACCESS_ALLOWED_ACE_TYPE": ace_type_short = "ALLOW" if weak_perms_only: perms = dangerous_perms_write else: perms = all_perms for mod, perms_tuple in perms[object_type_s].iteritems(): for perm in perms_tuple: #print "Checking for perm %s in ACE %s" % (perm, mask) if getattr(mod, perm) & mask == getattr(mod, perm): weak_perms.append([object_name, domain, principle, perm, ace_type_short]) print_weak_perms(object_type_s, weak_perms, options) def check_weak_write_perms(object_name, object_type_s): return check_weak_perms(object_name, object_type_s, dangerous_perms_write) def check_registry(): for key_string in reg_paths: parts = key_string.split("\\") hive = parts[0] key_string = "\\".join(parts[1:]) try: keyh = win32api.RegOpenKeyEx(getattr(win32con, hive), key_string, 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: #print "Can't open: " + hive + "\\" + key_string continue sd = win32api.RegGetKeySecurity(keyh, win32security.DACL_SECURITY_INFORMATION | win32security.OWNER_SECURITY_INFORMATION) weak_perms = check_weak_write_perms_by_sd(hive + "\\" + key_string, 'reg', sd) if weak_perms: vprint(hive + "\\" + key_string) #print weak_perms if verbose == 0: sys.stdout.write(".") save_issue("WPC003", "writable_reg_paths", weak_perms) # print_weak_perms("x", weak_perms) print # TODO save_issue("WPC009", "writable_eventlog_key", weak_perms) # weak perms on event log reg key def check_event_logs(): key_string = "HKEY_LOCAL_MACHINE\\" + eventlog_key_hklm try: keyh = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, eventlog_key_hklm , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: print "Can't open: " + key_string return 0 subkeys = win32api.RegEnumKeyEx(keyh) for subkey in subkeys: # print key_string + "\\" + subkey[0] sys.stdout.write(".") try: subkeyh = win32api.RegOpenKeyEx(keyh, subkey[0] , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: print "Can't open: " + key_string else: subkey_count, value_count, mod_time = win32api.RegQueryInfoKey(subkeyh) # print "\tChild Nodes: %s subkeys, %s values" % (subkey_count, value_count) try: filename, type = win32api.RegQueryValueEx(subkeyh, "DisplayNameFile") except: pass else: weak_perms = check_weak_write_perms(os.path.expandvars(filename), 'file') if weak_perms: # print "------------------------------------------------" # print "Weak permissions found on event log display DLL:" # print_weak_perms("File", weak_perms) sys.stdout.write("!") save_issue("WPC008", "writable_eventlog_dll", weak_perms) try: filename, type = win32api.RegQueryValueEx(subkeyh, "File") except: pass else: weak_perms = check_weak_write_perms(os.path.expandvars(filename), 'file') if weak_perms: # print "------------------------------------------------" # print "Weak permissions found on event log file:" # print_weak_perms("File", weak_perms) sys.stdout.write("!") save_issue("WPC007", "writable_eventlog_file", weak_perms) print #sd = win32api.RegGetKeySecurity(subkeyh, win32security.DACL_SECURITY_INFORMATION) # TODO: get owner too? #print "\tDACL: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION) def get_extra_privs(): # Try to give ourselves some extra privs (only works if we're admin): # SeBackupPrivilege - so we can read anything # SeDebugPrivilege - so we can find out about other processes (otherwise OpenProcess will fail for some) # SeSecurityPrivilege - ??? what does this do? # Problem: Vista+ support "Protected" processes, e.g. audiodg.exe. We can't see info about these. # Interesting post on why Protected Process aren't really secure anyway: http://www.alex-ionescu.com/?p=34 th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY) privs = win32security.GetTokenInformation(th, TokenPrivileges) newprivs = [] for privtuple in privs: if privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeBackupPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeDebugPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeSecurityPrivilege"): print "Added privilege " + str(privtuple[0]) # privtuple[1] = 2 # tuples are immutable. WHY?! newprivs.append((privtuple[0], 2)) # SE_PRIVILEGE_ENABLED else: newprivs.append((privtuple[0], privtuple[1])) # Adjust privs privs = tuple(newprivs) str(win32security.AdjustTokenPrivileges(th, False , privs)) def audit_processes(): get_extra_privs() # Things we might want to know about a process: # TCP/UDP/Local sockets # Treads - and the tokens of each (API doesn't support getting a thread handle!) # Shared memory pids = win32process.EnumProcesses() for pid in sorted(pids): print "---------------------------------------------------------" print "PID: %s" % pid # TODO there's a security descriptor for each process accessible via GetSecurityInfo according to http://msdn.microsoft.com/en-us/library/ms684880%28VS.85%29.aspx ph = 0 gotph = 0 try: # PROCESS_VM_READ is required to list modules (DLLs, EXE) ph = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, pid) gotph = 1 vprint("OpenProcess with VM_READ and PROCESS_QUERY_INFORMATION: Success") except: print("OpenProcess with VM_READ and PROCESS_QUERY_INFORMATION: Failed") try: # We can still get some info without PROCESS_VM_READ ph = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION , False, pid) gotph = 1 vprint("OpenProcess with PROCESS_QUERY_INFORMATION: Success") except: print "OpenProcess with PROCESS_QUERY_INFORMATION: Failed" try: # If we have to resort to using PROCESS_QUERY_LIMITED_INFORMATION, the process is protected. # There's no point trying PROCESS_VM_READ ph = win32api.OpenProcess(win32con.PROCESS_QUERY_LIMITED_INFORMATION , False, pid) gotph = 1 vprint("OpenProcess with PROCESS_QUERY_LIMITED_INFORMATION: Success") except: print "OpenProcess with PROCESS_QUERY_LIMITED_INFORMATION: Failed" # Move onto the next process. We don't have a process handle! exe = "[unknown]" gotexe = 0 mhs = 0 try: mhs = win32process.EnumProcessModules(ph) mhs = list(mhs) exe = win32process.GetModuleFileNameEx(ph, mhs.pop(0)) gotexe = 1 except: pass print "Filename: %s" % exe gottokenh = 0 try: tokenh = win32security.OpenProcessToken(ph, win32con.TOKEN_QUERY) gottokenh = 1 sidObj, intVal = win32security.GetTokenInformation(tokenh, TokenUser) if sidObj: accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj) print "TokenUser: %s\%s (type %s)" % (domainName, accountName, accountTypeInt) sidObj = win32security.GetTokenInformation(tokenh, TokenOwner) if sidObj: accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj) print "TokenOwner: %s\%s (type %s)" % (domainName, accountName, accountTypeInt) sidObj = win32security.GetTokenInformation(tokenh, TokenPrimaryGroup) if sidObj: accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj) print "TokenPrimaryGroup: %s\%s (type %s)" % (domainName, accountName, accountTypeInt) except: print "OpenProcessToken with TOKEN_QUERY: Failed" print "TokenUser: Unknown" print "TokenOwner: Unknown" print "TokenPrimaryGroup: Unknown" pass user = "unknown\\unknown" # TODO I'm not sure how to interogate threads. # There's no OpenThread() in win32api. I need a thread handle before I can get Thread Tokens. # The code below lists threadid's, be we can't use the handle (it's not a PyHandle) # # hThreadSnap = CreateToolhelp32Snapshot (TH32CS_SNAPTHREAD, pid) # if hThreadSnap == INVALID_HANDLE_VALUE: # print "Failed to get Thread snapshot" # else: # te32 = Thread32First (hThreadSnap) # if te32: # while True: # if te32.th32OwnerProcessID == pid: # hThread = OpenThread (win32con.THREAD_QUERY_INFORMATION, FALSE, te32.th32ThreadID) # print "PID %s, ThreadID %s" % (pid, te32.th32ThreadID) # print "Priority: " + str(win32process.GetThreadPriority(hThread)) # CloseHandle (hThread) # te32 = Thread32Next (hThreadSnap) # if not te32: # break # CloseHandle (hThreadSnap) # except: # print "EnumProcessModules: Failed" # continue # print "EnumProcessModules: Success" if ph: print "IsWow64 Process: %s" % win32process.IsWow64Process(ph) if gottokenh: vprint("OpenProcessToken with TOKEN_QUERY: Success") imp_levels = { "SecurityAnonymous": 0, "SecurityIdentification": 1, "SecurityImpersonation": 2, "SecurityDelegation": 3 } #for ilevel in imp_levels.keys(): #sys.stdout.write("Trying DuplicateToken with " + ilevel) #try: #win32security.DuplicateToken(tokenh, imp_levels[ilevel]) #print "success" #except: #print "failed" tokentype = win32security.GetTokenInformation(tokenh, TokenType) tokentype_str = "TokenImpersonation" if tokentype == 1: tokentype_str = "TokenPrimary" print "Token Type: " + tokentype_str print "Logon Session ID: " + str(win32security.GetTokenInformation(tokenh, TokenOrigin)) try: source = win32security.GetTokenInformation(tokenh, TokenSource) print "Token Source: " + source except: print "Token Source: Unknown (Access Denied)" try: print "TokenImpersonationLevel: %s" % win32security.GetTokenInformation(tokenh, TokenImpersonationLevel) # doesn't work on xp except: pass try: r = win32security.GetTokenInformation(tokenh, TokenHasRestrictions) # doesn't work on xp if r == 0: print "TokenHasRestrictions: 0 (not filtered)" else: print "TokenHasRestrictions: %s (token has been filtered)" % r except: pass try: e = win32security.GetTokenInformation(tokenh, TokenElevationType) # vista if e == 1: print "TokenElevationType: TokenElevationTypeDefault" elif e == 2: print "TokenElevationType: TokenElevationTypeFull" elif e == 3: print "TokenElevationType: TokenElevationTypeLimited" else: print "TokenElevationType: Unknown (%s)" % e except: pass try: print "TokenUIAccess: %s" % win32security.GetTokenInformation(tokenh, TokenUIAccess) # doesn't work on xp except: pass try: print "TokenLinkedToken: %s" % win32security.GetTokenInformation(tokenh, TokenLinkedToken) # vista except: pass try: print "TokenLogonSid: %s" % win32security.GetTokenInformation(tokenh, TokenLogonSid) # doesn't work on xp print "TokenElevation: %s" % win32security.GetTokenInformation(tokenh, TokenElevation) # vista except: pass try: sid, i = win32security.GetTokenInformation(tokenh, TokenIntegrityLevel) # vista try: accountName, domainName, accountTypeInt = win32security.LookupAccountSid(None, sid) user = domainName + "\\" + accountName + " (" + win32security.ConvertSidToStringSid(sid) + ")" except: user = win32security.ConvertSidToStringSid(sid) print "TokenIntegrityLevel: %s %s" % (user, i) except: pass try: m = win32security.GetTokenInformation(tokenh, TokenMandatoryPolicy) # vista if m == 0: print "TokenMandatoryPolicy: OFF" elif m == 1: print "TokenMandatoryPolicy: NO_WRITE_UP" elif m == 2: print "TokenMandatoryPolicy: NEW_PROCESS_MIN" elif m == 3: print "TokenMandatoryPolicy: POLICY_VALID_MASK" else: print "TokenMandatoryPolicy: %s" % m except: pass print "Token Resitrcted Sids: " + str(win32security.GetTokenInformation(tokenh, TokenRestrictedSids)) print "IsTokenRestricted: " + str(win32security.IsTokenRestricted(tokenh)) print "\nToken Groups: " for tup in win32security.GetTokenInformation(tokenh, TokenGroups): sid = tup[0] attr = tup[1] attr_str = attr if attr < 0: attr = 2**32 + attr attr_str_a = [] if attr & 1: # attr_str_a.append("SE_GROUP_MANDATORY") attr_str_a.append("MANDATORY") if attr & 2: # attr_str_a.append("SE_GROUP_ENABLED_BY_DEFAULT") attr_str_a.append("ENABLED_BY_DEFAULT") if attr & 4: # attr_str_a.append("SE_GROUP_ENABLED") attr_str_a.append("ENABLED") if attr & 8: # attr_str_a.append("SE_GROUP_OWNER") attr_str_a.append("OWNER") if attr & 0x40000000: # attr_str_a.append("SE_GROUP_LOGON_ID") attr_str_a.append("LOGON_ID") attr_str = ("|".join(attr_str_a)) try: accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sid) user = domainName + "\\" + accountName + " (" + win32security.ConvertSidToStringSid(sid) + ")" except: user = win32security.ConvertSidToStringSid(sid) print "\t%s: %s" % (user, attr_str) # Link that explains how privs are added / removed from tokens: # http://support.microsoft.com/kb/326256 print "\nToken Privileges:" privs = win32security.GetTokenInformation(tokenh, TokenPrivileges) for priv_tuple in privs: priv_val = priv_tuple[0] attr = priv_tuple[1] attr_str = "unknown_attr(" + str(attr) + ")" attr_str_a = [] if attr == 0: attr_str_a.append("[disabled but not removed]") if attr & 1: # attr_str_a.append("SE_PRIVILEGE_ENABLED_BY_DEFAULT") attr_str_a.append("ENABLED_BY_DEFAULT") if attr & 2: # attr_str_a.append("SE_PRIVILEGE_ENABLED") attr_str_a.append("ENABLED") if attr & 0x80000000: # attr_str_a.append("SE_PRIVILEGE_USED_FOR_ACCESS") attr_str_a.append("USED_FOR_ACCESS") if attr & 4: # attr_str_a.append("SE_PRIVILEGE_REMOVED") attr_str_a.append("REMOVED") if attr_str_a: attr_str = ("|").join(attr_str_a) print "\t%s: %s" % (win32security.LookupPrivilegeName(remote_server, priv_val), attr_str) #print "\nProcess ACL (buggy - probably wrong):" #dump_acl(pid, 'process', win32security.GetTokenInformation(tokenh, TokenDefaultDacl), {'brief': 1}) # TODO can't understand ACL # sidObj = win32security.GetTokenInformation(tokenh, TokenOwner) # Owner returns "Administrators" instead of SYSTEM. It's not what we want. # if sidObj: # accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj) # print "User: %s\%s (type %s)" % (domainName, accountName, accountTypeInt) if gotexe: print "\nFile permissions on %s:" % exe dump_perms(exe, 'file', {'brief': 1}) print if mhs and ph: for mh in mhs: dll = win32process.GetModuleFileNameEx(ph, mh) print "Loaded module: %s" % dll dump_perms(dll, 'file', {'brief': 1}) print def check_processes(): pids = win32process.EnumProcesses() # TODO also check out WMI. It might not be running, but it could help if it is: # http://groups.google.com/group/comp.lang.python/browse_thread/thread/1f50065064173ccb # TODO process explorer can find quite a lot more information than this script. This script has several problems: # TODO I can't open 64-bit processes for a 32-bit app. I get this error: # ERROR: can't open 6100: 299 EnumProcessModules, Only part of a ReadProcessMemory # or WriteProcessMemory request was completed. # TODO I can't seem to get the name of elevated processes (user running as me, but with admin privs) # TODO I can't get details of certain processes runnign as SYSTEM on xp (e.g. pid 4 "system", csrss.exe) # TODO should be able to find name (and threads?) for all processes. Not necessarily path. for pid in sorted(pids): # TODO there's a security descriptor for each process accessible via GetSecurityInfo according to http://msdn.microsoft.com/en-us/library/ms684880%28VS.85%29.aspx # TODO could we connect with PROCESS_QUERY_LIMITED_INFORMATION instead on Vista+ try: ph = win32api.OpenProcess(win32con.PROCESS_VM_READ | win32con.PROCESS_QUERY_INFORMATION , False, pid) except: # print "ERROR: can't connected to PID " + str(pid) sys.stdout.write("?") continue else: user = "unknown\\unknown" try: tokenh = win32security.OpenProcessToken(ph, win32con.TOKEN_QUERY) except: pass else: sidObj, intVal = win32security.GetTokenInformation(tokenh, TokenUser) #source = win32security.GetTokenInformation(tokenh, TokenSource) if sidObj: accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj) # print "pid=%d accountname=%s domainname=%s wow64=%s" % (pid, accountName, domainName, win32process.IsWow64Process(ph)) user = domainName + "\\" + accountName # print "PID %d is running as %s" % (pid, user) sys.stdout.write(".") try: mhs = win32process.EnumProcessModules(ph) # print mhs except: continue mhs = list(mhs) exe = win32process.GetModuleFileNameEx(ph, mhs.pop(0)) weak_perms = check_weak_write_perms(exe, 'file') # print_weak_perms("PID " + str(pid) + " running as " + user + ":", weak_perms) if weak_perms: save_issue("WPC016", "weak_perms_exes", weak_perms) sys.stdout.write("!") for mh in mhs: # print "PID %d (%s) has loaded module: %s" % (pid, exe, win32process.GetModuleFileNameEx(ph, mh)) dll = win32process.GetModuleFileNameEx(ph, mh) weak_perms = check_weak_write_perms(dll, 'file') # print_weak_perms("DLL used by PID " + str(pid) + " running as " + user + " (" + exe + "):", weak_perms) if weak_perms: save_issue("WPC016", "weak_perms_dlls", weak_perms) sys.stdout.write("!") print def check_services(): sch = win32service.OpenSCManager(remote_server, None, win32service.SC_MANAGER_ENUMERATE_SERVICE ) try: # TODO Haven't seen this work - even when running as SYSTEM sd = win32service.QueryServiceObjectSecurity(sch, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION) print check_weak_write_perms_by_sd("Service Manager", 'service_manager', sd) except: pass # Need to connect to service (OpenService) with minimum privs to read DACL. Here are our options: # # http://www.pinvoke.net/default.aspx/advapi32/OpenSCManager.html?diff=y # SC_MANAGER_ALL_ACCESS (0xF003F) Includes STANDARD_RIGHTS_REQUIRED, in addition to all access rights in this table. # SC_MANAGER_CREATE_SERVICE (0x0002) Required to call the CreateService function to create a service object and add it to the database. # SC_MANAGER_CONNECT (0x0001) Required to connect to the service control manager. # SC_MANAGER_ENUMERATE_SERVICE (0x0004) Required to call the EnumServicesStatusEx function to list the services that are in the database. # SC_MANAGER_LOCK (0x0008) Required to call the LockServiceDatabase function to acquire a lock on the database. # SC_MANAGER_MODIFY_BOOT_CONFIG (0x0020) Required to call the NotifyBootConfigStatus function. # SC_MANAGER_QUERY_LOCK_STATUS (0x0010)Required to call the QueryServiceLockStatus function to retrieve the lock status information for the database. # GENERIC_READ # GENERIC_WRITE # GENERIC_EXECUTE # GENERIC_ALL services = win32service.EnumServicesStatus(sch, win32service.SERVICE_WIN32, win32service.SERVICE_STATE_ALL ) for service in services: try: sh = win32service.OpenService(sch, service[0] , win32service.SC_MANAGER_CONNECT ) service_info = win32service.QueryServiceConfig(sh) except: print "WARNING: Can't open service " + service[0] continue try: sh = win32service.OpenService(sch, service[0] , win32con.GENERIC_READ ) sd = win32service.QueryServiceObjectSecurity(sh, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION) except: # print "Service Perms: Unknown (Access Denied)" continue weak_perms = check_weak_write_perms_by_sd("Service \"" + service[1] + "\" (" + service[0] + ") which runs as user \"" + service_info[7] + "\"", 'service', sd) binary = None weak_perms_binary = [] if not remote_server: binary = get_binary(service_info[3]) if binary: weak_perms_binary = check_weak_write_perms(binary, 'file') if weak_perms or weak_perms_binary: vprint("---------------------------------------") vprint("Service: " + service[0]) vprint("Description: " + service[1]) vprint("Binary: " + service_info[3]) if binary: vprint("Binary (clean): " + binary) else: vprint("Binary (clean): [Missing Binary]") vprint("Run as: " + service_info[7]) vprint("Weak Perms: ") # service_info = win32service.QueryServiceConfig2(sh, win32service.SERVICE_CONFIG_DESCRIPTION) # long description of service. not interesting. # print "Service Perms: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION) print_weak_perms("file", weak_perms_binary) if weak_perms_binary: save_issue("WPC004", "writable_progs", weak_perms_binary) print_weak_perms("service", weak_perms) if weak_perms: save_issue("WPC012", "weak_service_perms", weak_perms) if verbose == 0: sys.stdout.write("!") else: if verbose == 0: sys.stdout.write(".") print def audit_services(): print sch = win32service.OpenSCManager(remote_server, None, win32service.SC_MANAGER_ENUMERATE_SERVICE ) try: # TODO Haven't seen this work - even when running as SYSTEM sd = win32service.QueryServiceObjectSecurity(sch, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION) print check_weak_write_perms_by_sd("Service Manager", 'service_manager', sd) except: #print "ERROR: Can't get security descriptor for service manager" pass # Need to connect to service (OpenService) with minimum privs to read DACL. Here are our options: # # http://www.pinvoke.net/default.aspx/advapi32/OpenSCManager.html?diff=y # SC_MANAGER_ALL_ACCESS (0xF003F) Includes STANDARD_RIGHTS_REQUIRED, in addition to all access rights in this table. # SC_MANAGER_CREATE_SERVICE (0x0002) Required to call the CreateService function to create a service object and add it to the database. # SC_MANAGER_CONNECT (0x0001) Required to connect to the service control manager. # SC_MANAGER_ENUMERATE_SERVICE (0x0004) Required to call the EnumServicesStatusEx function to list the services that are in the database. # SC_MANAGER_LOCK (0x0008) Required to call the LockServiceDatabase function to acquire a lock on the database. # SC_MANAGER_MODIFY_BOOT_CONFIG (0x0020) Required to call the NotifyBootConfigStatus function. # SC_MANAGER_QUERY_LOCK_STATUS (0x0010)Required to call the QueryServiceLockStatus function to retrieve the lock status information for the database. # GENERIC_READ # GENERIC_WRITE # GENERIC_EXECUTE # GENERIC_ALL services = win32service.EnumServicesStatus(sch, win32service.SERVICE_WIN32, win32service.SERVICE_STATE_ALL ) for service in services: sh = win32service.OpenService(sch, service[0] , win32service.SC_MANAGER_CONNECT ) service_info = win32service.QueryServiceConfig(sh) binary = None if remote_server: print "WARNING: Running agianst remote server. Checking perms of .exe not implemented." else: binary = get_binary(service_info[3]) print "---------------------------------------------------------------" print("Service: " + service[0]) print("Description: " + service[1]) print("Binary: " + service_info[3]) if binary: print("Binary (clean): " + binary) else: if remote_server: print("Binary (clean): [N/A Running remotely]") else: print("Binary (clean): [Missing Binary/Remote]") print("Run as: " + service_info[7]) print "\nFile Permissions on executable %s:" % binary if binary: dump_perms(binary, 'file', {'brief': 1}) else: print "WARNING: Can't get full path of binary. Skipping." print "\nPermissions on service:" try: sh = win32service.OpenService(sch, service[0] , win32con.GENERIC_READ ) except: print "ERROR: OpenService failed" try: sd = win32service.QueryServiceObjectSecurity(sh, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION) except: print "ERROR: QueryServiceObjectSecurity didn't get security descriptor for service" dump_sd("Service \"" + service[1] + "\" (" + service[0] + ") which runs as user \"" + service_info[7] + "\"", 'service', sd, {'brief': 1}) print "\nPermissions on registry data:" print "WARNING: Not implmented yet" # service_info = win32service.QueryServiceConfig2(sh, win32service.SERVICE_CONFIG_DESCRIPTION) # long description of service. not interesting. # print "Service Perms: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION) print def vprint(string): if (verbose): print string def get_binary(binary_dirty): m = re.search('^[\s]*?"([^"]+)"', binary_dirty) if m and os.path.exists(m.group(1)): return m.group(1) else: if m: binary_dirty = m.group(1) chunks = binary_dirty.split(" ") candidate = "" for chunk in chunks: if candidate: candidate = candidate + " " candidate = candidate + chunk if os.path.exists(candidate) and os.path.isfile(candidate): return candidate if os.path.exists(candidate + ".exe") and os.path.isfile(candidate + ".exe"): return candidate + ".exe" global on64bitwindows if on64bitwindows: candidate2 = candidate.replace("system32", "syswow64") if os.path.exists(candidate2) and os.path.isfile(candidate2): return candidate2 if os.path.exists(candidate2 + ".exe") and os.path.isfile(candidate2 + ".exe"): return candidate2 + ".exe" return None def print_weak_perms(type, weak_perms, options={}): brief = 0 if options: if options['brief']: brief = 1 for perms in weak_perms: object_name = perms[0] domain = perms[1] principle = perms[2] perm = perms[3] if len(perms) == 5: acl_type = perms[4] if acl_type == "ALLOW": acl_type = "" else: acl_type = acl_type + " " else: acl_type = "" slash = "\\" if domain == "": slash = "" if brief: print "\t%s%s%s%s: %s" % (acl_type, domain, slash, principle, perm) else: print "\t%s%s%s%s has permission %s on %s %s" % (acl_type, domain, slash, principle, perm, type, object_name) def check_path(path, issue_no): dirs = set(path.split(';')) exts = ('exe', 'com', 'bat', 'dll') # TODO pl, rb, py, php, inc, asp, aspx, ocx, vbs, more? for dir in dirs: weak_flag = 0 weak_perms = check_weak_write_perms(dir, 'directory') if weak_perms: save_issue(issue_no, "weak_perms_dir", weak_perms) print_weak_perms("Directory", weak_perms) weak_flag = 1 for ext in exts: for file in glob.glob(dir + '\*.' + ext): #print "Processing " + file weak_perms = check_weak_write_perms(file, 'file') if weak_perms: save_issue(issue_no, "weak_perms_exe", weak_perms) print_weak_perms("File", weak_perms) weak_flag = 1 if weak_flag == 1: sys.stdout.write("!") else: sys.stdout.write(".") def get_user_paths(): try: keyh = win32api.RegOpenKeyEx(win32con.HKEY_USERS, None , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: return 0 paths = [] subkeys = win32api.RegEnumKeyEx(keyh) for subkey in subkeys: try: subkeyh = win32api.RegOpenKeyEx(keyh, subkey[0] + "\\Environment" , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: pass else: subkey_count, value_count, mod_time = win32api.RegQueryInfoKey(subkeyh) try: path, type = win32api.RegQueryValueEx(subkeyh, "PATH") paths.append((subkey[0], path)) except: pass return paths def get_system_path(): # HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment key_string = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' try: keyh = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, key_string , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: return None try: path, type = win32api.RegQueryValueEx(keyh, "PATH") return path except: return None #name=sys.argv[1] #if not os.path.exists(name): #print name, "does not exist!" #sys.exit() def check_user_paths(): for user_path in get_user_paths(): user_sid_s = user_path[0] try: user_sid = win32security.ConvertStringSidToSid(user_sid_s) principle, domain, type = win32security.LookupAccountSid(remote_server, user_sid) user_fq = domain + "\\" + principle except: print "WARNING: Can't convert sid %s to name. Skipping." % user_sid_s continue path = user_path[1] vprint("Checking path of %s" % user_fq) global tmp_trusted_principles_fq tmp_trusted_principles_fq = (user_fq) check_path(path, "WPC015") tmp_trusted_principles_fq = () def check_current_path(): vprint("Checking current user's PATH") global tmp_trusted_principles_fq tmp_trusted_principles_fq = (os.environ['userdomain'] + "\\" + os.environ['username']) check_path(os.environ['path'], "WPC014") tmp_trusted_principles_fq = () def check_system_path(): vprint("Checking system PATH") check_path(get_system_path(), "WPC013") def check_paths(): check_system_path() check_current_path() check_user_paths() print def check_drives(): for drive in win32api.GetLogicalDriveStrings().split("\x00"): sys.stdout.write(".") type = win32file.GetDriveType(drive) if type == win32con.DRIVE_FIXED: fs = win32api.GetVolumeInformation(drive)[4] if fs == 'NTFS': warning = "" weak_perms = check_weak_write_perms(drive, 'directory') if weak_perms: # print "Weak permissions on drive root %s:" % drive # print_weak_perms('directory', weak_perms) sys.stdout.write(".") save_issue("WPC010", "writable_drive_root", weak_perms) elif fs == 'FAT': save_issue_string("WPC011", "fat_fs_drives", "Fixed drive " + drive + ": has " + fs + " filesystem (FAT does not support file permissions)" ) sys.stdout.write("!") elif fs == 'FAT32': save_issue_string("WPC011", "fat_fs_drives", "Fixed drive " + drive + ": has " + fs + " filesystem (FAT32 does not support file permissions)" ) sys.stdout.write("!") else: warning = " (not NTFS - might be insecure)" save_issue_string("WPC011", "fat_fs_drives", "Fixed drive " + drive + ": has " + fs + " filesystem (Not NTFS - might not be secure)" ) sys.stdout.write("!") # print "Fixed drive %s has %s filesystem%s" % (drive, fs, warning) print def check_shares(): resume = 0; try: (sharelist, total, resume) = win32net.NetShareEnum(None, 502, resume, 9999) for share in sharelist: sys.stdout.write(".") sd = share['security_descriptor'] # print "%s (%s) %s type=%s" % (share['netname'], share['path'], share['remark'], share['type']) if sd: weak_perms = check_weak_write_perms_by_sd("Share \"" + share['netname'] + "\" (" + share['path'] + ") ", 'share', sd) if weak_perms: save_issue("WPC017", "non_admin_shares", weak_perms) sys.stdout.write("!") except: print "[E] Can't check shares - not enough privs?" # TODO not option to call this yet def audit_shares(): print print "[+] Shares" print resume = 0; try: (sharelist, total, resume) = win32net.NetShareEnum(remote_server, 502, resume, 999999) #print win32net.NetShareGetInfo(remote_server, ?, 0) # do we need this? for share in sharelist: # Determine type of share types = [] if share['type'] & getattr(win32netcon, "STYPE_SPECIAL"): # print "Share type: " types.append("STYPE_SPECIAL") share['type'] = share['type'] & 3 # mask off "special" #print share['type'] for stype in share_types: if share['type'] == getattr(win32netcon, stype): types.append(stype) #print "Share type: " + stype break print "---------------" print "Share: " + share['netname'] print "Path: " + share['path'] print "Remark: " + share['remark'] print "Type(s): " + "|".join(types) print "Reserved: %s" % share['reserved'] print "Passwd: %s" % share['passwd'] print "Current Uses: %s" % share['current_uses'] print "Max Uses: %s" % share['max_uses'] print "Permissions: %s" % share['permissions'] print "Sec. Desc.: " dump_sd(share['netname'], 'share', share['security_descriptor']) except: print "[E] Couldn't get share information" print print "[+] Server Info (NetServerGetInfo 102)" print def check_progfiles(): # %ProgramFiles% # %ProgramFiles(x86)% prog_dirs = [] # re_exe = re.compile('\.exe$|\.com$|\.bat$|\.dll$', re.IGNORECASE) exts = ('exe', 'com', 'bat', 'dll') # TODO pl, rb, py, php, inc, asp, aspx, ocx, vbs, more? if os.getenv('ProgramFiles'): prog_dirs.append(os.environ['ProgramFiles']) if os.getenv('ProgramFiles(x86)'): prog_dirs.append(os.environ['ProgramFiles(x86)']) dot_count = 0 weak_flag = 0 for prog_dir in prog_dirs: # print "Looking for programs under %s..." % prog_dir for root, dirs, files in os.walk(prog_dir): #print "root=%s, dirs=%s, files=%s" % (root, dirs, files) # for file in files: # m = re_exe.search(file) # if m is None: # continue # #print "Checking file %s" % os.path.join(root, file) # weak_perms = check_weak_write_perms(os.path.join(root, file), 'file') # if weak_perms: # print_weak_perms("File", weak_perms) for file in dirs: #print "Checking dir %s" % os.path.join(root, file) weak_perms = check_weak_write_perms(os.path.join(root, file), 'file') if weak_perms: #print_weak_perms("Directory", weak_perms) save_issue("WPC001", "writable_dirs", weak_perms) weak_flag = 1 dir = file for ext in exts: for f in glob.glob(root + "\\" + dir + '\*.' + ext): #print "Processing " + f weak_perms = check_weak_write_perms(f, 'file') if weak_perms: print_weak_perms("File", weak_perms) save_issue("WPC001", "writable_progs", weak_perms) weak_flag = 1 dot_count = dot_count + 1; # Don't print out all the dots. There are too many! if dot_count > 10: if weak_flag == 1: sys.stdout.write("!") else: sys.stdout.write(".") dot_count = 0; weak_flag = 0; print def check_patches(): # TODO: This is more difficult than I'd hoped. You can't just search for the KB number: XP will appear to be vulnerable to dcom. Need to search for KB number or SP2 in this case. # from subprocess import Popen, PIPE patchlist = Popen(["systeminfo"], stdout=PIPE).communicate()[0] # for kb_no in kb_nos: # print "Searching for " + kb_no # if re.search(kb_no, patchlist): # print "found" def print_section(title): if (verbose != 0): print "=================================" print title print "=================================" print else: sys.stdout.write(title + ": ") # http://www.daniweb.com/code/snippet216539.html def int2bin(n): bStr = '' if n < 0: n = n + 2^32 if n == 0: return '0' while n > 0: bStr = str(n % 2) + bStr n = n >> 1 return bStr def impersonate(username, password, domain): if username: print "Using alternative credentials:" print "Username: " + str(username) print "Password: " + str(password) print "Domain: " + str(domain) handle = win32security.LogonUser( username, domain, password, win32security.LOGON32_LOGON_NEW_CREDENTIALS, win32security.LOGON32_PROVIDER_WINNT50 ) win32security.ImpersonateLoggedOnUser( handle ) else: print "Running as current user. No logon creds supplied (-u, -d, -p)." print def audit_passpol(): print print "[+] NetUserModalsGet 0,1,2,3" print try: data = win32net.NetUserModalsGet(remote_server, 0) for key in data.keys(): print "%s: %s" % (key, data[key]) data = win32net.NetUserModalsGet(remote_server, 1) for key in data.keys(): print "%s: %s" % (key, data[key]) data = win32net.NetUserModalsGet(remote_server, 2) for key in data.keys(): if key == 'domain_id': print "%s: %s" % (key, win32security.ConvertSidToStringSid(data[key])) elif key == 'lockout_threshold' and data[key] == '0': print "%s: %s (accounts aren't locked out)" % (key, data[key]) else: print "%s: %s" % (key, data[key]) data = win32net.NetUserModalsGet(remote_server, 3) for key in data.keys(): if key == 'lockout_threshold' and data[key] == 0: print "%s: %s (accounts aren't locked out)" % (key, data[key]) else: print "%s: %s" % (key, data[key]) except: print "[E] Couldn't get NetUserModals data" # Recursive function to find group members (and the member of any groups in those groups...) def get_group_members(server, group, depth): resume = 0 indent = "\t" * depth members = [] while True: try: m, total, resume = win32net.NetLocalGroupGetMembers(server, group, 2, resume, 999999) except: break for member in m: if member['sidusage'] == 4: type = "local group" g = member['domainandname'].split("\\") print indent + member['domainandname'] + " (" + str(type) + ")" get_group_members(server, g[1], depth + 1) elif member['sidusage'] == 2: type = "domain group" print indent + member['domainandname'] + " (" + str(type) + ")" elif member['sidusage'] == 1: type = "user" print indent + member['domainandname'] + " (" + str(type) + ")" else: type = "type " + str(member['sidusage']) print indent + member['domainandname'] + " (" + str(type) + ")" if resume == 0: break def audit_admin_users(): print for group in ("administrators", "domain admins", "enterprise admins"): print "\n[+] Members of " + group + ":" get_group_members(remote_server, group, 0) print # It might be interesting to look up who has powerful privs, but LsaEnumerateAccountsWithUserRight doesn't seem to work as a low priv user # SE_ASSIGNPRIMARYTOKEN_NAME TEXT("SeAssignPrimaryTokenPrivilege") Required to assign the primary token of a process. User Right: Replace a process-level token. # SE_BACKUP_NAME TEXT("SeBackupPrivilege") Required to perform backup operations. This privilege causes the system to grant all read access control to any file, regardless of the access control list (ACL) specified for the file. Any access request other than read is still evaluated with the ACL. This privilege is required by the RegSaveKey and RegSaveKeyExfunctions. The following access rights are granted if this privilege is held: READ_CONTROL ACCESS_SYSTEM_SECURITY FILE_GENERIC_READ FILE_TRAVERSE User Right: Back up files and directories. # SE_CREATE_PAGEFILE_NAME TEXT("SeCreatePagefilePrivilege") Required to create a paging file. User Right: Create a pagefile. # SE_CREATE_TOKEN_NAME TEXT("SeCreateTokenPrivilege") Required to create a primary token. User Right: Create a token object. # SE_DEBUG_NAME TEXT("SeDebugPrivilege") Required to debug and adjust the memory of a process owned by another account. User Right: Debug programs. # SE_ENABLE_DELEGATION_NAME TEXT("SeEnableDelegationPrivilege") Required to mark user and computer accounts as trusted for delegation. User Right: Enable computer and user accounts to be trusted for delegation. # SE_LOAD_DRIVER_NAME TEXT("SeLoadDriverPrivilege") Required to load or unload a device driver. User Right: Load and unload device drivers. # SE_MACHINE_ACCOUNT_NAME TEXT("SeMachineAccountPrivilege") Required to create a computer account. User Right: Add workstations to domain. # SE_MANAGE_VOLUME_NAME TEXT("SeManageVolumePrivilege") Required to enable volume management privileges. User Right: Manage the files on a volume. # SE_RELABEL_NAME TEXT("SeRelabelPrivilege") Required to modify the mandatory integrity level of an object. User Right: Modify an object label. # SE_RESTORE_NAME TEXT("SeRestorePrivilege") Required to perform restore operations. This privilege causes the system to grant all write access control to any file, regardless of the ACL specified for the file. Any access request other than write is still evaluated with the ACL. Additionally, this privilege enables you to set any valid user or group SID as the owner of a file. This privilege is required by the RegLoadKey function. The following access rights are granted if this privilege is held: WRITE_DAC WRITE_OWNER ACCESS_SYSTEM_SECURITY FILE_GENERIC_WRITE FILE_ADD_FILE FILE_ADD_SUBDIRECTORY DELETE User Right: Restore files and directories. # SE_SHUTDOWN_NAME TEXT("SeShutdownPrivilege") Required to shut down a local system. User Right: Shut down the system. # SE_SYNC_AGENT_NAME TEXT("SeSyncAgentPrivilege") Required for a domain controller to use the LDAP directory synchronization services. This privilege enables the holder to read all objects and properties in the directory, regardless of the protection on the objects and properties. By default, it is assigned to the Administrator and LocalSystem accounts on domain controllers. User Right: Synchronize directory service data. # SE_TAKE_OWNERSHIP_NAME TEXT("SeTakeOwnershipPrivilege") Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be set only to those values that the holder may legitimately assign as the owner of an object. User Right: Take ownership of files or other objects. # SE_TCB_NAME TEXT("SeTcbPrivilege") This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this privilege. User Right: Act as part of the operating system. # SE_TRUSTED_CREDMAN_ACCESS_NAME TEXT("SeTrustedCredManAccessPrivilege") Required to access Credential Manager as a trusted caller. User Right: Access Credential Manager as a trusted caller. # Need: SE_ENABLE_DELEGATION_NAME, SE_MANAGE_VOLUME_NAME, SE_RELABEL_NAME, SE_SYNC_AGENT_NAME, SE_TRUSTED_CREDMAN_ACCESS_NAME # ph = win32security.LsaOpenPolicy(remote_server, win32security.POLICY_VIEW_LOCAL_INFORMATION | win32security.POLICY_LOOKUP_NAMES) # for priv in (SE_ASSIGNPRIMARYTOKEN_NAME, SE_BACKUP_NAME, SE_CREATE_PAGEFILE_NAME, SE_CREATE_TOKEN_NAME, SE_DEBUG_NAME, SE_LOAD_DRIVER_NAME, SE_MACHINE_ACCOUNT_NAME, SE_RESTORE_NAME, SE_SHUTDOWN_NAME, SE_TAKE_OWNERSHIP_NAME, SE_TCB_NAME): # print "Looking up who has " + priv + "priv" # try: # sids = win32security.LsaEnumerateAccountsWithUserRight(ph, priv) # print sids # except: # print "[E] Lookup failed" def audit_logged_in(): resume = 0 print "\n[+] Logged in users:" try: while True: users, total, resume = win32net.NetWkstaUserEnum(remote_server, 1 , resume , 999999 ) for user in users: print "User logged in: Logon Server=\"%s\" Logon Domain=\"%s\" Username=\"%s\"" % (user['logon_server'], user['logon_domain'], user['username']) if resume == 0: break except: print "[E] Failed" def audit_host_info(): print "\n" if remote_server: print "Querying remote server: " + remote_server # Only works on local host #win32net.NetGetJoinInformation() # This looks interesting, but doesn't seem to work. Maybe unsupported legacy api. #pywintypes.error: (50, 'NetUseEnum', 'The request is not supported.') #print #print "[+] Getting Net Use info" #print #resume = 0 #use, total, resume = win32net.NetUseEnum(remote_server, 2, resume , 999999 ) #print use print print "[+] Workstation Info (NetWkstaGetInfo 102)" print try: #print win32net.NetWkstaGetInfo(remote_server, 100) #print win32net.NetWkstaGetInfo(remote_server, 101) serverinfo = win32net.NetWkstaGetInfo(remote_server, 102) print "Computer Name: %s" % serverinfo['computername'] print "Langroup: %s" % serverinfo['langroup'] print "OS: %s.%s" % (serverinfo['ver_major'], serverinfo['ver_minor']) print "Logged On Users: %s" % serverinfo['logged_on_users'] print "Lanroot: %s" % serverinfo['lanroot'] if serverinfo['platform_id'] & win32netcon.PLATFORM_ID_NT: print "Platform: PLATFORM_ID_NT (means NT family, not NT4)" if serverinfo['platform_id'] == win32netcon.PLATFORM_ID_OS2: print "Platform: PLATFORM_ID_OS2" if serverinfo['platform_id'] == win32netcon.PLATFORM_ID_DOS: print "Platform: PLATFORM_ID_DOS" if serverinfo['platform_id'] == win32netcon.PLATFORM_ID_OSF: print "Platform: PLATFORM_ID_OSF" if serverinfo['platform_id'] == win32netcon.PLATFORM_ID_VMS: print "Platform: PLATFORM_ID_VMS" except: print "[E] Couldn't get Workstation Info" print print "[+] Server Info (NetServerGetInfo 102)" print try: #print "NetServerGetInfo 100" + str(win32net.NetServerGetInfo(remote_server, 100)) #print "NetServerGetInfo 101" + str(win32net.NetServerGetInfo(remote_server, 101)) serverinfo = win32net.NetServerGetInfo(remote_server, 102) print "Name: %s" % serverinfo['name'] print "Comment: %s" % serverinfo['comment'] print "OS: %s.%s" % (serverinfo['version_major'], serverinfo['version_minor']) print "Userpath: %s" % serverinfo['userpath'] print "Hidden: %s" % serverinfo['hidden'] if serverinfo['platform_id'] & win32netcon.PLATFORM_ID_NT: print "Platform: PLATFORM_ID_NT (means NT family, not NT4)" if serverinfo['platform_id'] == win32netcon.PLATFORM_ID_OS2: print "Platform: PLATFORM_ID_OS2" if serverinfo['platform_id'] == win32netcon.PLATFORM_ID_DOS: print "Platform: PLATFORM_ID_DOS" if serverinfo['platform_id'] == win32netcon.PLATFORM_ID_OSF: print "Platform: PLATFORM_ID_OSF" if serverinfo['platform_id'] == win32netcon.PLATFORM_ID_VMS: print "Platform: PLATFORM_ID_VMS" for sv_type in sv_types: if serverinfo['type'] & getattr(win32netcon, sv_type): print "Type: " + sv_type except: print "[E] Couldn't get Server Info" print print "[+] LsaQueryInformationPolicy" print try: ph = win32security.LsaOpenPolicy(remote_server, win32security.POLICY_VIEW_LOCAL_INFORMATION | win32security.POLICY_LOOKUP_NAMES) print "PolicyDnsDomainInformation:" print win32security.LsaQueryInformationPolicy(ph, win32security.PolicyDnsDomainInformation) print "PolicyDnsDomainInformation:" print win32security.LsaQueryInformationPolicy(ph, win32security.PolicyPrimaryDomainInformation) print "PolicyPrimaryDomainInformation:" print win32security.LsaQueryInformationPolicy(ph, win32security.PolicyAccountDomainInformation) print "PolicyLsaServerRoleInformation:" print win32security.LsaQueryInformationPolicy(ph, win32security.PolicyLsaServerRoleInformation) except: print "[E] Couldn't LsaOpenPolicy" # DsBindWithCred isn't available from python! # IADsComputer looks useful, but also isn't implemented: # http://msdn.microsoft.com/en-us/library/aa705980%28v=VS.85%29.aspx # The following always seems to fail: # need a dc hostname as remote_server # and domain #try: # hds = win32security.DsBind(remote_server, remote_domain) # print "hds: " + hds # print "DsListDomainsInSite: "+ str(win32security.DsListDomainsInSite(hds)) #except: # pass # domain can be null. i think domainguid can be null. sitename null. flags = 0. # lists roles recognised by the server (fsmo roles?) # win32security.DsListRoles(hds) # list misc info for a server # win32security.DsListInfoForServer(hds, server) # but how to get a list of sites? # win32security.DsListServersInSite(hds, site ) # win32security.DsCrackNames(hds, flags , formatOffered , formatDesired , names ) # ...For example, user objects can be identified by SAM account names (Domain\UserName), user principal name (UserName@Domain.com), or distinguished name. print print "[+] Getting domain controller info" print try: domain = None # TODO: could call of each domain if we had a list print "PDC: " + win32net.NetGetDCName(remote_server, domain) # Try to list some domain controllers for the remote host # There are better ways of doing this, but they don't seem to be available via python! dc_seen = {} for filter in (0, 0x00004000, 0x00000080, 0x00001000, 0x00000400, 0x00000040, 0x00000010): dc_info = win32security.DsGetDcName(remote_server, None, None, None, filter) if not dc_info['DomainControllerAddress'] in dc_seen: print "\n[+] Found DC\n" for k in dc_info: print k + ": " + str(dc_info[k]) dc_seen[dc_info['DomainControllerAddress']] = 1 print "\nWARNING: Above is not necessarily a complete list of DCs\n" #print "Domain controller: " + str(win32security.DsGetDcName(remote_server, None, None, None, 0)) # any dc #print "Domain controller: " + str(win32security.DsGetDcName(remote_server, None, None, None, 0x00004000)) # not the system we connect to #print "Domain controller: " + str(win32security.DsGetDcName(remote_server, None, None, None, 0x00000080)) # pdc #print "Domain controller: " + str(win32security.DsGetDcName(remote_server, None, None, None, 0x00001000)) # writeable #print "Domain controller: " + str(win32security.DsGetDcName(remote_server, None, None, None, 0x00000400)) # kerberos #print "Domain controller: " + str(win32security.DsGetDcName(remote_server, None, None, None, 0x00000040)) # gc #print "Domain controller: " + str(win32security.DsGetDcName(remote_server, None, None, None, 0x00000010)) # directory service except: print "[E] Couldn't get DC info" # This function sounds very much like what lservers.exe does, but the server name must be None # according to http://msdn.microsoft.com/en-us/library/aa370623%28VS.85%29.aspx. No use to us. # print win32net.NetServerEnum(remote_server, 100 or 101, win32netcon.SV_TYPE_ALL, "SOMEDOMAIN.COM", 0, 999999) def audit_user_group(): try: ph = win32security.LsaOpenPolicy(remote_server, win32security.POLICY_VIEW_LOCAL_INFORMATION | win32security.POLICY_LOOKUP_NAMES) except: pass print print "[+] Local Groups" print resume = 0 groups = [] while True: try: g, total, resume = win32net.NetLocalGroupEnum(remote_server, 0, resume, 999999) groups = groups + g if resume == 0: break except: print "[E] NetLocalGroupEnum failed" break for group in groups: members = [] while True: m, total, resume = win32net.NetLocalGroupGetMembers(remote_server, group['name'], 1, resume, 999999) for member in m: members.append(member['name']) if resume == 0: break sid, s, i = win32security.LookupAccountName(remote_server, group['name']) sid_string = win32security.ConvertSidToStringSid(sid) print "Group %s has sid %s" % (group['name'], sid_string) for m in members: print "Group %s has member: %s" % (group['name'], m) if verbose: try: privs = win32security.LsaEnumerateAccountRights(ph, sid) for priv in privs: print "Group %s has privilege: %s" % (group['name'], priv) except: print "Group %s: privilege lookup failed " % (group['name']) print print "[+] Non-local Groups" print resume = 0 groups = [] while True: try: g, total, resume = win32net.NetGroupEnum(remote_server, 0, resume, 999999) groups = groups + g if resume == 0: break except: print "[E] NetGroupEnum failed" break for group in groups: members = [] while True: try: m, total, resume = win32net.NetGroupGetUsers(remote_server, group['name'], 0, resume, 999999) for member in m: members.append(member['name']) if resume == 0: break except: print "[E] NetGroupEnum failed" break sid, s, i = win32security.LookupAccountName(remote_server, group['name']) sid_string = win32security.ConvertSidToStringSid(sid) print "Group %s has sid %s" % (group['name'], sid_string) for m in members: print "Group %s has member: %s" % (group['name'], m) if verbose: try: privs = win32security.LsaEnumerateAccountRights(ph, sid) for priv in privs: print "Group %s has privilege: %s" % (group['name'], priv) except: print "Group %s has no privileges" % (group['name']) print print "[+] Users" print resume = 0 users = [] if verbose: level = 11 else: level = 0 while True: try: # u, total, resume = win32net.NetUserEnum(remote_server, 11, 0, resume, 999999) # lots of user detail # u, total, resume = win32net.NetUserEnum(remote_server, 0, 0, resume, 999999) # just the username u, total, resume = win32net.NetUserEnum(remote_server, level, 0, resume, 999999) for user in u: if verbose: for k in user: if k != 'parms': print k + "\t: " + str(user[k]) print users.append(user['name']) if resume == 0: break except: print "[E] NetUserEnum failed" break for user in users: gprivs = [] sid, s, i = win32security.LookupAccountName(remote_server, user) sid_string = win32security.ConvertSidToStringSid(sid) print "User %s has sid %s" % (user, sid_string) groups = win32net.NetUserGetLocalGroups(remote_server, user, 0) for group in groups: gsid, s, i = win32security.LookupAccountName(remote_server, group) try: privs = win32security.LsaEnumerateAccountRights(ph, gsid) gprivs = list(list(gprivs) + list(privs)) except: pass print "User %s is in this local group: %s" % (user, group) group_list = win32net.NetUserGetGroups(remote_server, user) groups = [] for g in group_list: groups.append(g[0]) for group in groups: print "User %s is in this non-local group: %s" % (user, group) if verbose: privs = [] try: privs = win32security.LsaEnumerateAccountRights(ph, sid) except: pass for priv in list(set(list(gprivs) + list(privs))): print "User %s has privilege %s" % (user, priv) if verbose: print print "[+] Privileges" print for priv in windows_privileges: try: for s in win32security.LsaEnumerateAccountsWithUserRight(ph, priv): priv_desc = "NoDesc!" try: priv_desc = win32security.LookupPrivilegeDisplayName(remote_server, priv) except: pass name, domain, type = win32security.LookupAccountSid(remote_server, s) type_string = "unknown_type" if type == 4: type_string = "group" if type == 5: type_string = "user" print "Privilege %s (%s) is held by %s\%s (%s)" % (priv, priv_desc, domain, name, type_string) # print "Privilege %s is held by %s\%s (%s)" % (priv, domain, name, type_string) except: #print "Skipping %s - doesn't exist for this platform" % priv pass print "windows-privesc-check v%s (http://pentestmonkey.net/windows-privesc-check)\n" % version # Process Command Line Options try: opts, args = getopt.getopt(sys.argv[1:], "artSDEPRHUOMAFILIehwiWvo:s:u:p:d:", ["help", "verbose", "all_checks", "registry_checks", "path_checks", "service_checks", "services", "drive_checks", "eventlog_checks", "progfiles_checks", "passpol", "process_checks", "share_checks", "user_groups", "processes", "ignore_trusted", "owner_info", "write_perms_only", "domain", "patch_checks", "admin_users", "host_info", "logged_in", "report_file=", "username=", "password=", "domain=", "server="]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) output = None for o, a in opts: if o in ("-a", "--all_checks"): all_checks = 1 elif o in ("-r", "--registry_checks"): registry_checks = 1 elif o in ("-t", "--path_checks"): path_checks = 1 elif o in ("-S", "--service_checks"): service_checks = 1 elif o in ("-D", "--drive_checks"): drive_checks = 1 elif o in ("-E", "--eventlog_checks"): eventlog_checks = 1 elif o in ("-F", "--progfiles_checks"): progfiles_checks = 1 elif o in ("-R", "--process_checks"): process_checks = 1 elif o in ("-H", "--share_checks"): share_checks = 1 # elif o in ("-T", "--patch_checks"): # patch_checks = 1 elif o in ("-L", "--logged_in_audit"): logged_in_audit = 1 elif o in ("-U", "--user_group_audit"): user_group_audit = 1 elif o in ("-P", "--passpol"): passpol_audit = 1 elif o in ("-A", "--admin_users_audit"): admin_users_audit = 1 elif o in ("-O", "--process_audit"): process_audit = 1 elif o in ("-i", "--host_info"): host_info_audit = 1 elif o in ("-e", "--services"): service_audit = 1 elif o in ("-h", "--help"): usage() sys.exit() elif o in ("-w", "--write_perms_only"): weak_perms_only = 1 elif o in ("-I", "--ignore_trusted"): ignore_trusted = 1 elif o in ("-W", "--owner_info"): owner_info = 1 elif o in ("-v", "--verbose"): verbose = verbose + 1 elif o in ("-o", "--report_file"): report_file_name = a elif o in ("-s", "--server"): remote_server = a print "Remote server selected: " + a elif o in ("-u", "--username"): remote_username = a elif o in ("-p", "--password"): remote_password = a elif o in ("-d", "--domain"): remote_domain = a else: assert False, "unhandled option" if all_checks: registry_checks = 1 path_checks = 1 service_checks = 1 service_audit = 1 drive_checks = 1 eventlog_checks = 1 progfiles_checks = 1 process_checks = 1 share_checks = 1 user_group_audit = 1 passpol_audit = 1 logged_in_audit = 1 admin_users_audit= 1 host_info_audit = 1 patch_checks = 1 process_audit = 1 # Print usage message unless at least on type of check is selected if not ( registry_checks or path_checks or service_checks or service_audit or drive_checks or eventlog_checks or progfiles_checks or process_checks or share_checks or logged_in_audit or user_group_audit or passpol_audit or admin_users_audit or host_info_audit or process_audit or patch_checks ): usage() if report_file_name == None: report_file_name = "privesc-report-" + socket.gethostname() + ".html" # Better open the report file now in case there's a permissions problem REPORT = open(report_file_name,"w") # Print out scan parameters print "Audit parameters:" print "Registry Checks: ....... " + str(registry_checks) print "PATH Checks: ........... " + str(path_checks) print "Service Checks: ........ " + str(service_checks) print "Eventlog Checks: ....... " + str(drive_checks) print "Program Files Checks: .. " + str(eventlog_checks) print "Process Checks: ........ " + str(progfiles_checks) print "Patch Checks: ..........." + str(patch_checks) print "User/Group Audit: ...... " + str(user_group_audit) print "Password Policy Audit .. " + str(passpol_audit) print "Logged-in User Audit ... " + str(logged_in_audit) print "Admin Users Audit: ..... " + str(admin_users_audit) print "Host Info Audit: ....... " + str(host_info_audit) print "Process Audit: ......... " + str(process_audit) print "Service Audit .......... " + str(service_audit) print "Ignore Trusted ......... " + str(ignore_trusted) print "Owner Info ............. " + str(owner_info) print "Weak Perms Only ........ " + str(weak_perms_only) print "Verbosity .............. " + str(verbose) print "Output File: ........... " + report_file_name print impersonate(remote_username, remote_password, remote_domain) # Load win32security # # Try to open file and ingore the result. This gets win32security loaded and working. # We can then turn off WOW64 and call repeatedly. If we turn off WOW64 first, # win32security will fail to work properly. try: sd = win32security.GetNamedSecurityInfo ( ".", win32security.SE_FILE_OBJECT, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION ) except: # nothing pass # Load win32net # # NetLocalGroupEnum fails with like under Windows 7 64-bit, but not XP 32-bit: # pywintypes.error: (127, 'NetLocalGroupEnum', 'The specified procedure could not be found.') dummy = win32net.NetLocalGroupEnum(None, 0, 0, 1000) # Disable WOW64 - we WANT to see 32-bit areas of the filesystem # # Need to wrap in a try because the following call will error on 32-bit windows try: k32.Wow64DisableWow64FsRedirection( ctypes.byref(wow64) ) except: on64bitwindows = 0 # WOW64 is now disabled, so we can read file permissions without Windows redirecting us from system32 to syswow64 # Run checks if registry_checks: print_section("Registry Checks") check_registry() if path_checks: print_section("PATH Checks") check_paths() if service_checks: print_section("Service Checks") check_services() if service_audit: print_section("Service Audit") audit_services() if drive_checks: print_section("Drive Checks") check_drives() if eventlog_checks: print_section("Event Log Checks") check_event_logs() if progfiles_checks: print_section("Program Files Checks") check_progfiles() if process_checks: print_section("Process Checks") check_processes() if share_checks: print_section("Share Checks") check_shares() if logged_in_audit: print_section("Logged-in User Audit") audit_logged_in() if user_group_audit: print_section("User/Group Audit") audit_user_group() if passpol_audit: print_section("Password Policy") audit_passpol() if admin_users_audit: print_section("Admin Users Audit") audit_admin_users() if host_info_audit: print_section("Host Info Audit") audit_host_info() if process_audit: print_section("Process Audit") audit_processes() if patch_checks: print_section("Patch Checks") check_patches() # task_name='test_addtask.job' # ts=pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None,pythoncom.CLSCTX_INPROC_SERVER,taskscheduler.IID_ITaskScheduler) # tasks=ts.Enum() # for task in tasks: # print task # print issues # Generate report audit_data = {} audit_data['hostname'] = socket.gethostname() ver_list = win32api.GetVersionEx(1) os_ver = str(ver_list[0]) + "." + str(ver_list[1]) # version numbers from http://msdn.microsoft.com/en-us/library/ms724832(VS.85).aspx if os_ver == "4.0": os_str = "Windows NT" if os_ver == "5.0": os_str = "Windows 2000" if os_ver == "5.1": os_str = "Windows XP" if os_ver == "5.2": os_str = "Windows 2003" if os_ver == "6.0": os_str = "Windows Vista" if os_ver == "6.0": os_str = "Windows 2008" if os_ver == "6.1": os_str = "Windows 2008 R2" if os_ver == "6.1": os_str = "Windows 7" audit_data['os_name'] = os_str # print ver_list # audit_data['os_version'] = str(ver_list[0]) + "." + str(ver_list[1]) + "." + str(ver_list[2]) + " SP" + str(ver_list[5])+ "." + str(ver_list[6]) audit_data['os_version'] = str(ver_list[0]) + "." + str(ver_list[1]) + "." + str(ver_list[2]) + " SP" + str(ver_list[5]) # http://msdn.microsoft.com/en-us/library/ms724429(VS.85).aspx audit_data['ips'] = local_ips audit_data['domwkg'] = win32api.GetDomainName() audit_data['version'] = version audit_data['datetime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") audit_data['audit_user'] = os.environ['USERDOMAIN'] + "\\" + os.environ['USERNAME'] audit_data['trusted_users'] = trusted_principles_fq audit_data['trusted_groups'] = trusted_principles audit_data['dangerous_privs'] = 'somedangerous_privs' REPORT.write(format_issues("html", issue_template, issues)) REPORT.close print print print "Report saved to " + report_file_name print
gpl-2.0
diZturbio/lara42x-sbe
vendor/edvinaskrucas/notification/tests/SubscriberTest.php
6006
<?php use Mockery as m; require_once 'Mocks/SubscriberMock.php'; class SubscriberTest extends PHPUnit_Framework_TestCase { public function tearDown() { m::close(); } public function testIsConstructed() { $subscriber = $this->getSubscriber(); $this->assertInstanceOf('Illuminate\Session\SessionManager', $subscriber->getSession()); $this->assertInstanceOf('Illuminate\Config\Repository', $subscriber->getConfig()); } public function testSubscribe() { $subscriber = $this->getSubscriber(); $events = m::mock('Illuminate\Events\Dispatcher'); $events->shouldReceive('listen')->once()->with('notification.flash: *', 'Krucas\Notification\Subscriber@onFlash'); $events->shouldReceive('listen')->once()->with('notification.booted', 'Krucas\Notification\Subscriber@onBoot'); $this->assertNull($subscriber->subscribe($events)); } public function testFlashContainerNames() { $subscriber = $this->getSubscriber(); $subscriber->getSession()->shouldReceive('flash')->once()->with('notifications_containers', array('test')); $subscriber->getConfig()->shouldReceive('get')->once()->with('notification::session_prefix')->andReturn('notifications_'); $notification = $this->getNotification(); $notificationsBag = $this->getNotificationsBag(); $notification->shouldReceive('getContainers')->once()->andReturn(array($notificationsBag)); $notificationsBag->shouldReceive('getName')->once()->andReturn('test'); $this->assertNull($subscriber->flashContainerNames($notification)); } public function testGenerateMessageKey() { $subscriber = $this->getSubscriber(); $message = $this->getMessage(); $message->shouldReceive('toJson')->andReturn('test'); $this->assertNotNull($subscriber->generateMessageKey($message)); } public function testGenerateDifferentKeysForDifferentMessages() { $subscriber = $this->getSubscriber(); $message1 = $this->getMessage(); $message2 = $this->getMessage(); $message1->shouldReceive('toJson')->andReturn('test1'); $message2->shouldReceive('toJson')->andReturn('test2'); $this->assertNotSame($subscriber->generateMessageKey($message1), $subscriber->generateMessageKey($message2)); } public function testGenerateDifferentKeysForSameMessages() { $subscriber = $this->getSubscriber(); $message = $this->getMessage(); $message->shouldReceive('toJson')->andReturn('test'); $this->assertNotSame($subscriber->generateMessageKey($message), $subscriber->generateMessageKey($message)); } public function testOnFlash() { $session = $this->getSessionManager(); $config = $this->getConfigRepository(); $subscriber = m::mock('SubscriberMock[flashContainerNames,generateMessageKey,getSession,getConfig]'); $subscriber->shouldReceive('getSession')->andReturn($session); $subscriber->shouldReceive('getConfig')->andReturn($config); $notification = $this->getNotification(); $notificationsBag = $this->getNotificationsBag(); $message = $this->getMessage(); $subscriber->shouldReceive('flashContainerNames')->once()->with($notification); $config->shouldReceive('get')->once()->with('notification::session_prefix')->andReturn('notifications_'); $notificationsBag->shouldReceive('getName')->once()->andReturn('test'); $subscriber->shouldReceive('generateMessageKey')->once()->with($message)->andReturn('test_key'); $message->shouldReceive('toJson')->once()->andReturn('test_message'); $session->shouldReceive('flash')->once()->with('notifications_test_test_key', 'test_message'); $this->assertTrue($subscriber->onFlash($notification, $notificationsBag, $message)); } public function testOnBoot() { $subscriber = $this->getSubscriber(); $subscriber->getConfig()->shouldReceive('get')->once()->with('notification::session_prefix')->andReturn('notifications_'); $subscriber->getSession()->shouldReceive('get')->once()->with('notifications_containers', array())->andReturn(array('test')); $flasedMessages = array( 'notifications_test_1' => '{"message":"test message","format":":type: :message","type":"info","flashable":false,"alias":null,"position":null}', 'notifications_test_2' => '{"message":"test message","format":":type: :message","type":"error","flashable":false,"alias":null,"position":null}', ); $subscriber->getSession()->shouldReceive('all')->once()->andReturn($flasedMessages); $notificationsBag = $this->getNotificationsBag(); $notificationsBag->shouldReceive('add')->once()->with('info', m::type('Krucas\Notification\Message'), false); $notificationsBag->shouldReceive('add')->once()->with('error', m::type('Krucas\Notification\Message'), false); $notification = $this->getNotification(); $notification->shouldReceive('container')->twice()->with('test')->andReturn($notificationsBag); $this->assertTrue($subscriber->onBoot($notification)); } protected function getSubscriber() { $subscriber = new SubscriberMock($this->getSessionManager(), $this->getConfigRepository()); return $subscriber; } protected function getSessionManager() { return m::mock('Illuminate\Session\SessionManager'); } protected function getConfigRepository() { return m::mock('Illuminate\Config\Repository'); } protected function getNotification() { return m::mock('Krucas\Notification\Notification'); } protected function getNotificationsBag() { return m::mock('Krucas\Notification\NotificationsBag'); } protected function getMessage() { return m::mock('Krucas\Notification\Message'); } }
gpl-2.0
JunkyBulgaria/5.4.1
src/server/scripts/EasternKingdoms/zone_silverpine_forest.cpp
4042
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Silverpine_Forest SD%Complete: 100 SDComment: Quest support: 435 SDCategory: Silverpine Forest EndScriptData */ /* ContentData npc_deathstalker_erland EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedEscortAI.h" #include "Player.h" /*###### ## npc_deathstalker_erland ######*/ enum eErland { SAY_QUESTACCEPT = 0, SAY_START = 1, SAY_AGGRO = 2, SAY_PROGRESS = 3, SAY_LAST = 4, SAY_RANE = 0, SAY_RANE_ANSWER = 5, SAY_MOVE_QUINN = 6, SAY_QUINN = 7, SAY_QUINN_ANSWER = 0, SAY_BYE = 8, QUEST_ESCORTING = 435, NPC_RANE = 1950, NPC_QUINN = 1951 }; class npc_deathstalker_erland : public CreatureScript { public: npc_deathstalker_erland() : CreatureScript("npc_deathstalker_erland") { } struct npc_deathstalker_erlandAI : public npc_escortAI { npc_deathstalker_erlandAI(Creature* creature) : npc_escortAI(creature) { } void WaypointReached(uint32 waypointId) { Player* player = GetPlayerForEscort(); if (!player) return; switch (waypointId) { case 1: Talk(SAY_START, player->GetGUID()); break; case 10: Talk(SAY_PROGRESS); break; case 13: Talk(SAY_LAST, player->GetGUID()); player->GroupEventHappens(QUEST_ESCORTING, me); break; case 15: if (Creature* rane = me->FindNearestCreature(NPC_RANE, 20.0f)) rane->AI()->Talk(SAY_RANE); break; case 16: Talk(SAY_RANE_ANSWER); break; case 17: Talk(SAY_MOVE_QUINN); break; case 24: Talk(SAY_QUINN); break; case 25: if (Creature* quinn = me->FindNearestCreature(NPC_QUINN, 20.0f)) quinn->AI()->Talk(SAY_QUINN_ANSWER); break; case 26: Talk(SAY_BYE); break; } } void Reset() OVERRIDE { } void EnterCombat(Unit* who) { Talk(SAY_AGGRO, who->GetGUID()); } }; bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) { if (quest->GetQuestId() == QUEST_ESCORTING) { creature->AI()->Talk(SAY_QUESTACCEPT, player->GetGUID()); if (npc_escortAI* pEscortAI = CAST_AI(npc_deathstalker_erland::npc_deathstalker_erlandAI, creature->AI())) pEscortAI->Start(true, false, player->GetGUID()); } return true; } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_deathstalker_erlandAI(creature); } }; /*###### ## AddSC ######*/ void AddSC_silverpine_forest() { new npc_deathstalker_erland(); }
gpl-2.0
gwenaelCF/eveGCF
apps/stats/modules/tickets/templates/indexSuccess.php
736
<?php include_partial('attendance/filters',array('form' => $form)) ?> <div class="ui-widget ui-corner-all ui-widget-content"> <a name="chart-title"></a> <div class="ui-widget-header ui-corner-all fg-toolbar"> <?php include_partial('attendance/filters_buttons') ?> <h1><?php echo __('Global stats on ticketting') ?></h1> </div> <?php include_partial('stats_all',array('contacts' => $contacts, 'professionals' => $professionals)) ?> <?php include_partial('stats_legend', array('dates' => $criterias['dates'])) ?> <div class="clear"></div> <?php include_partial('stats_perso', array('contacts' => $contacts)) ?> <?php include_partial('stats_pro', array('professionals' => $professionals)) ?> <div class="clear"></div> </div>
gpl-2.0
iRGBit/QGIS
python/plugins/processing/algs/qgis/FieldsMapper.py
5632
# -*- coding: utf-8 -*- """ *************************************************************************** FieldsMapper.py --------------------- Date : October 2014 Copyright : (C) 2014 by Arnaud Morvan Email : arnaud dot morvan at camptocamp dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Arnaud Morvan' __date__ = 'October 2014' __copyright__ = '(C) 2014, Arnaud Morvan' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from qgis.core import QgsField, QgsExpression, QgsFeature from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.core.parameters import ParameterVector from processing.core.outputs import OutputVector from processing.tools import dataobjects, vector from .fieldsmapping import ParameterFieldsMapping from .ui.FieldsMapperDialogs import (FieldsMapperParametersDialog, FieldsMapperModelerParametersDialog) class FieldsMapper(GeoAlgorithm): INPUT_LAYER = 'INPUT_LAYER' FIELDS_MAPPING = 'FIELDS_MAPPING' OUTPUT_LAYER = 'OUTPUT_LAYER' def __init__(self): GeoAlgorithm.__init__(self) self.mapping = None def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Refactor fields') self.group, self.i18n_group = self.trAlgorithm('Vector table tools') self.addParameter(ParameterVector(self.INPUT_LAYER, self.tr('Input layer'), [ParameterVector.VECTOR_TYPE_ANY], False)) self.addParameter(ParameterFieldsMapping(self.FIELDS_MAPPING, self.tr('Fields mapping'), self.INPUT_LAYER)) self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Refactored'))) def getCustomParametersDialog(self): return FieldsMapperParametersDialog(self) def getCustomModelerParametersDialog(self, modelAlg, algIndex=None): return FieldsMapperModelerParametersDialog(self, modelAlg, algIndex) def processAlgorithm(self, progress): layer = self.getParameterValue(self.INPUT_LAYER) mapping = self.getParameterValue(self.FIELDS_MAPPING) output = self.getOutputFromName(self.OUTPUT_LAYER) layer = dataobjects.getObjectFromUri(layer) provider = layer.dataProvider() fields = [] expressions = [] for field_def in mapping: fields.append(QgsField(name=field_def['name'], type=field_def['type'], len=field_def['length'], prec=field_def['precision'])) expression = QgsExpression(field_def['expression']) if expression.hasParserError(): raise GeoAlgorithmExecutionException( self.tr(u'Parser error in expression "{}": {}') .format(unicode(field_def['expression']), unicode(expression.parserErrorString()))) expression.prepare(provider.fields()) if expression.hasEvalError(): raise GeoAlgorithmExecutionException( self.tr(u'Evaluation error in expression "{}": {}') .format(unicode(field_def['expression']), unicode(expression.evalErrorString()))) expressions.append(expression) writer = output.getVectorWriter(fields, provider.geometryType(), layer.crs()) # Create output vector layer with new attributes error = '' calculationSuccess = True inFeat = QgsFeature() outFeat = QgsFeature() features = vector.features(layer) count = len(features) for current, inFeat in enumerate(features): rownum = current + 1 outFeat.setGeometry(inFeat.geometry()) attrs = [] for i in xrange(0, len(mapping)): field_def = mapping[i] expression = expressions[i] expression.setCurrentRowNumber(rownum) value = expression.evaluate(inFeat) if expression.hasEvalError(): calculationSuccess = False error = expression.evalErrorString() break attrs.append(value) outFeat.setAttributes(attrs) writer.addFeature(outFeat) current += 1 progress.setPercentage(100 * current / float(count)) del writer if not calculationSuccess: raise GeoAlgorithmExecutionException( self.tr('An error occurred while evaluating the calculation' ' string:\n') + error)
gpl-2.0
am-immanuel/quercus
modules/resin/src/com/caucho/message/DistributionMode.java
1841
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.message; import com.caucho.util.L10N; /** * Selects how a message should be treated when it's acquired from the node. * "MOVE" is like a queue, it deletes the node. * "COPY" is like a topic, it copies the node. */ public enum DistributionMode { MOVE("move"), COPY("copy"); private static final L10N L = new L10N(DistributionMode.class); private String _name; DistributionMode(String name) { _name = name; } public String getName() { return _name; } public static DistributionMode find(String name) { if (name == null) return null; else if ("move".equals(name)) return MOVE; else if ("copy".equals(name)) return COPY; else throw new IllegalArgumentException(L.l("unknown type: " + name)); } }
gpl-2.0
ovidiugabriel/joomla-platform
tests/suites/unit/joomla/database/JDatabaseDriverTest.php
11406
<?php /** * @package Joomla.UnitTest * @subpackage Database * * @copyright Copyright (C) 2005 - 2013 Open Source Matters. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ require_once __DIR__ . '/stubs/nosqldriver.php'; /** * Test class for JDatabaseDriver. * Generated by PHPUnit on 2009-10-08 at 22:00:38. * * @package Joomla.UnitTest * @subpackage Database * * @since 11.1 */ class JDatabaseDriverTest extends TestCaseDatabase { /** * @var JDatabaseDriver * @since 11.4 */ protected $db; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @return void */ protected function setUp() { $this->db = JDatabaseDriver::getInstance( array( 'driver' => 'nosql', 'database' => 'europa', 'prefix' => '&', ) ); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void */ protected function tearDown() { } /** * Test for the JDatabaseDriver::__call method. * * @return void * * @since 12.1 */ public function test__callQuote() { $this->assertThat( $this->db->q('foo'), $this->equalTo($this->db->quote('foo')), 'Tests the q alias of quote.' ); } /** * Test for the JDatabaseDriver::__call method. * * @return void * * @since 12.1 */ public function test__callQuoteName() { $this->assertThat( $this->db->qn('foo'), $this->equalTo($this->db->quoteName('foo')), 'Tests the qn alias of quoteName.' ); } /** * Test for the JDatabaseDriver::__call method. * * @return void * * @since 12.1 */ public function test__callUnknown() { $this->assertThat( $this->db->foo(), $this->isNull(), 'Tests for an unknown method.' ); } /** * Test... * * @todo Implement test__construct(). * * @return void */ public function test__construct() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testGetInstance(). * * @return void */ public function testGetInstance() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement test__destruct(). * * @return void */ public function test__destruct() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Tests the JDatabaseDriver::getConnection method. * * @return void * * @since 11.4 */ public function testGetConnection() { TestReflection::setValue($this->db, 'connection', 'foo'); $this->assertThat( $this->db->getConnection(), $this->equalTo('foo') ); } /** * Test... * * @todo Implement testGetConnectors(). * * @return void */ public function testGetConnectors() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Tests the JDatabaseDriver::getCount method. * * @return void * * @since 11.4 */ public function testGetCount() { TestReflection::setValue($this->db, 'count', 42); $this->assertThat( $this->db->getCount(), $this->equalTo(42) ); } /** * Tests the JDatabaseDriver::getDatabase method. * * @return void * * @since 11.4 */ public function testGetDatabase() { $this->assertThat( TestReflection::invoke($this->db, 'getDatabase'), $this->equalTo('europa') ); } /** * Tests the JDatabaseDriver::getDateFormat method. * * @return void * * @since 11.4 */ public function testGetDateFormat() { $this->assertThat( $this->db->getDateFormat(), $this->equalTo('Y-m-d H:i:s') ); } /** * Tests the JDatabaseDriver::splitSql method. * * @return void * * @since 12.1 */ public function testSplitSql() { $this->assertThat( $this->db->splitSql('SELECT * FROM #__foo;SELECT * FROM #__bar;'), $this->equalTo( array( 'SELECT * FROM #__foo;', 'SELECT * FROM #__bar;' ) ), 'splitSql method should split a string of multiple queries into an array.' ); } /** * Test... * * @todo Implement testGetErrorNum(). * * @return void */ public function testGetErrorNum() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testGetErrorMsg(). * * @return void */ public function testGetErrorMsg() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Tests the JDatabaseDriver::getLog method. * * @return void * * @since 11.4 */ public function testGetLog() { TestReflection::setValue($this->db, 'log', 'foo'); $this->assertThat( $this->db->getLog(), $this->equalTo('foo') ); } /** * Tests the JDatabaseDriver::getPrefix method. * * @return void * * @since 11.4 */ public function testGetPrefix() { $this->assertThat( $this->db->getPrefix(), $this->equalTo('&') ); } /** * Tests the JDatabaseDriver::getNullDate method. * * @return void * * @since 11.4 */ public function testGetNullDate() { $this->assertThat( $this->db->getNullDate(), $this->equalTo('1BC') ); } /** * Tests the JDatabaseDriver::getMinimum method. * * @return void * * @since 12.1 */ public function testGetMinimum() { $this->assertThat( $this->db->getMinimum(), $this->equalTo('12.1'), 'getMinimum should return a string with the minimum supported database version number' ); } /** * Tests the JDatabaseDriver::isMinimumVersion method. * * @return void * * @since 12.1 */ public function testIsMinimumVersion() { $this->assertThat( $this->db->isMinimumVersion(), $this->isTrue(), 'isMinimumVersion should return a boolean true if the database version is supported by the driver' ); } /** * Tests the JDatabaseDriver::setDebug method. * * @return void * * @since 12.1 */ public function testSetDebug() { $this->assertThat( $this->db->setDebug(true), $this->isType('boolean'), 'setDebug should return a boolean value containing the previous debug state.' ); } /** * Tests the JDatabaseDriver::setQuery method. * * @return void * * @since 12.1 */ public function testSetQuery() { $this->assertThat( $this->db->setQuery('SELECT * FROM #__dbtest'), $this->isInstanceOf('JDatabaseDriver'), 'setQuery method should return an instance of JDatabaseDriver.' ); } /** * Tests the JDatabaseDriver::replacePrefix method. * * @return void * * @since 12.1 */ public function testReplacePrefix() { $this->assertThat( $this->db->replacePrefix('SELECT * FROM #__dbtest'), $this->equalTo('SELECT * FROM &dbtest'), 'replacePrefix method should return the query string with the #__ prefix replaced by the actual table prefix.' ); } /** * Test... * * @todo Implement testStderr(). * * @return void */ public function testStderr() { // Remove the following lines when you implement this test. $this->markTestSkipped('Deprecated method'); } /** * Tests the JDatabaseDriver::quote method. * * @return void * * @covers JDatabaseDriver::quote * @since 11.4 */ public function testQuote() { $this->assertThat( $this->db->quote('test', false), $this->equalTo("'test'"), 'Tests the without escaping.' ); $this->assertThat( $this->db->quote('test'), $this->equalTo("'-test-'"), 'Tests the with escaping (default).' ); $this->assertEquals( array("'-test1-'", "'-test2-'"), $this->db->quote(array('test1', 'test2')), 'Check that the array is quoted.' ); } /** * Tests the JDatabaseDriver::quote method. * * @return void * * @since 11.4 */ public function testQuoteBooleanTrue() { $this->assertThat( $this->db->quote(true), $this->equalTo("'-1-'"), 'Tests handling of boolean true with escaping (default).' ); } /** * Tests the JDatabaseDriver::quote method. * * @return void * * @since 11.4 */ public function testQuoteBooleanFalse() { $this->assertThat( $this->db->quote(false), $this->equalTo("'--'"), 'Tests handling of boolean false with escaping (default).' ); } /** * Tests the JDatabaseDriver::quote method. * * @return void * * @since 11.4 */ public function testQuoteNull() { $this->assertThat( $this->db->quote(null), $this->equalTo("'--'"), 'Tests handling of null with escaping (default).' ); } /** * Tests the JDatabaseDriver::quote method. * * @return void * * @since 11.4 */ public function testQuoteInteger() { $this->assertThat( $this->db->quote(42), $this->equalTo("'-42-'"), 'Tests handling of integer with escaping (default).' ); } /** * Tests the JDatabaseDriver::quote method. * * @return void * * @since 11.4 */ public function testQuoteFloat() { $this->assertThat( $this->db->quote(3.14), $this->equalTo("'-3.14-'"), 'Tests handling of float with escaping (default).' ); } /** * Tests the JDatabaseDriver::quoteName method. * * @return void * * @since 11.4 */ public function testQuoteName() { $this->assertThat( $this->db->quoteName('test'), $this->equalTo('[test]'), 'Tests the left-right quotes on a string.' ); $this->assertThat( $this->db->quoteName('a.test'), $this->equalTo('[a].[test]'), 'Tests the left-right quotes on a dotted string.' ); $this->assertThat( $this->db->quoteName(array('a', 'test')), $this->equalTo(array('[a]', '[test]')), 'Tests the left-right quotes on an array.' ); $this->assertThat( $this->db->quoteName(array('a.b', 'test.quote')), $this->equalTo(array('[a].[b]', '[test].[quote]')), 'Tests the left-right quotes on an array.' ); $this->assertThat( $this->db->quoteName(array('a.b', 'test.quote'), array(null, 'alias')), $this->equalTo(array('[a].[b]', '[test].[quote] AS [alias]')), 'Tests the left-right quotes on an array.' ); $this->assertThat( $this->db->quoteName(array('a.b', 'test.quote'), array('alias1', 'alias2')), $this->equalTo(array('[a].[b] AS [alias1]', '[test].[quote] AS [alias2]')), 'Tests the left-right quotes on an array.' ); $this->assertThat( $this->db->quoteName((object) array('a', 'test')), $this->equalTo(array('[a]', '[test]')), 'Tests the left-right quotes on an object.' ); TestReflection::setValue($this->db, 'nameQuote', '/'); $this->assertThat( $this->db->quoteName('test'), $this->equalTo('/test/'), 'Tests the uni-quotes on a string.' ); } /** * Tests the JDatabaseDriver::truncateTable method. * * @return void * * @since 12.1 */ public function testTruncateTable() { $this->assertNull( $this->db->truncateTable('#__dbtest'), 'truncateTable should not return anything if successful.' ); } }
gpl-2.0
BryanQuigley/sos
sos/report/plugins/tuned.py
1112
# Copyright (C) 2014 Red Hat, Inc., Peter Portante <peter.portante@redhat.com> # This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distribution for further information. from sos.report.plugins import Plugin, RedHatPlugin class Tuned(Plugin, RedHatPlugin): short_desc = 'Tuned system tuning daemon' packages = ('tuned',) profiles = ('system', 'performance') plugin_name = 'tuned' def setup(self): self.add_cmd_output([ "tuned-adm list", "tuned-adm active", "tuned-adm recommend", "tuned-adm verify" ]) self.add_copy_spec([ "/etc/tuned.conf", "/etc/tune-profiles" ]) self.add_copy_spec([ "/etc/tuned", "/usr/lib/tuned", "/var/log/tuned/tuned.log" ]) # vim: set et ts=4 sw=4 :
gpl-2.0
ezecosystem/ezpublish-kernel
eZ/Publish/Core/Base/Container/ApiLoader/RepositoryFactory.php
4789
<?php /** * File containing the RepositoryFactory class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\Core\Base\Container\ApiLoader; use eZ\Publish\Core\Repository\Helper\RelationProcessor; use eZ\Publish\Core\Repository\Values\User\UserReference; use eZ\Publish\Core\Search\Common\BackgroundIndexer; use eZ\Publish\SPI\Persistence\Handler as PersistenceHandler; use eZ\Publish\SPI\Search\Handler as SearchHandler; use eZ\Publish\SPI\Limitation\Type as SPILimitationType; use eZ\Publish\API\Repository\Repository; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareTrait; use eZ\Publish\Core\Base\Exceptions\InvalidArgumentException; class RepositoryFactory implements ContainerAwareInterface { use ContainerAwareTrait; /** * @var string */ private $repositoryClass; /** * Collection of fieldTypes, lazy loaded via a closure. * * @var \eZ\Publish\Core\Base\Container\ApiLoader\FieldTypeCollectionFactory */ protected $fieldTypeCollectionFactory; /** * Collection of fieldTypes, lazy loaded via a closure. * * @var \eZ\Publish\Core\Base\Container\ApiLoader\FieldTypeNameableCollectionFactory */ protected $fieldTypeNameableCollectionFactory; /** * Collection of limitation types for the RoleService. * * @var \eZ\Publish\SPI\Limitation\Type[] */ protected $roleLimitations = array(); /** * Policies map. * * @var array */ protected $policyMap = array(); public function __construct( $repositoryClass, FieldTypeCollectionFactory $fieldTypeCollectionFactory, FieldTypeNameableCollectionFactory $fieldTypeNameableCollectionFactory, array $policyMap ) { $this->repositoryClass = $repositoryClass; $this->fieldTypeCollectionFactory = $fieldTypeCollectionFactory; $this->fieldTypeNameableCollectionFactory = $fieldTypeNameableCollectionFactory; $this->policyMap = $policyMap; } /** * Builds the main repository, heart of eZ Publish API. * * This always returns the true inner Repository, please depend on ezpublish.api.repository and not this method * directly to make sure you get an instance wrapped inside Signal / Cache / * functionality. * * @param \eZ\Publish\SPI\Persistence\Handler $persistenceHandler * @param \eZ\Publish\SPI\Search\Handler $searchHandler * @param \eZ\Publish\Core\Search\Common\BackgroundIndexer $backgroundIndexer * * @return \eZ\Publish\API\Repository\Repository */ public function buildRepository( PersistenceHandler $persistenceHandler, SearchHandler $searchHandler, BackgroundIndexer $backgroundIndexer, RelationProcessor $relationProcessor ) { $repository = new $this->repositoryClass( $persistenceHandler, $searchHandler, $backgroundIndexer, $relationProcessor, array( 'fieldType' => $this->fieldTypeCollectionFactory->getFieldTypes(), 'nameableFieldTypes' => $this->fieldTypeNameableCollectionFactory->getNameableFieldTypes(), 'role' => array( 'limitationTypes' => $this->roleLimitations, 'policyMap' => $this->policyMap, ), 'languages' => $this->container->getParameter('languages'), ), new UserReference($this->container->getParameter('anonymous_user_id')) ); return $repository; } /** * Registers a limitation type for the RoleService. * * @param string $limitationName * @param \eZ\Publish\SPI\Limitation\Type $limitationType */ public function registerLimitationType($limitationName, SPILimitationType $limitationType) { $this->roleLimitations[$limitationName] = $limitationType; } /** * Returns a service based on a name string (content => contentService, etc). * * @param \eZ\Publish\API\Repository\Repository $repository * @param string $serviceName * * @throws \eZ\Publish\Core\Base\Exceptions\InvalidArgumentException * * @return mixed */ public function buildService(Repository $repository, $serviceName) { $methodName = 'get' . $serviceName . 'Service'; if (!method_exists($repository, $methodName)) { throw new InvalidArgumentException($serviceName, 'No such service'); } return $repository->$methodName(); } }
gpl-2.0
NaturalGIS/naturalgis_qgis
src/app/decorations/qgsdecorationtitledialog.cpp
5811
/*************************************************************************** qgsdecorationtitledialog.cpp -------------------------------------- Date : November 2018 Copyright : (C) 2018 by Mathieu Pellerin Email : nirvn dot asia at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsdecorationtitledialog.h" #include "qgsdecorationtitle.h" #include "qgisapp.h" #include "qgsexpression.h" #include "qgsexpressionbuilderdialog.h" #include "qgsexpressioncontext.h" #include "qgshelp.h" #include "qgsmapcanvas.h" #include "qgsgui.h" #include <QColorDialog> #include <QColor> #include <QFont> #include <QDialogButtonBox> #include <QPushButton> QgsDecorationTitleDialog::QgsDecorationTitleDialog( QgsDecorationTitle &deco, QWidget *parent ) : QDialog( parent ) , mDeco( deco ) { setupUi( this ); QgsGui::enableAutoGeometryRestore( this ); connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsDecorationTitleDialog::buttonBox_accepted ); connect( buttonBox, &QDialogButtonBox::rejected, this, &QgsDecorationTitleDialog::buttonBox_rejected ); connect( mInsertExpressionButton, &QPushButton::clicked, this, &QgsDecorationTitleDialog::mInsertExpressionButton_clicked ); connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsDecorationTitleDialog::showHelp ); QPushButton *applyButton = buttonBox->button( QDialogButtonBox::Apply ); connect( applyButton, &QAbstractButton::clicked, this, &QgsDecorationTitleDialog::apply ); grpEnable->setChecked( mDeco.enabled() ); // label text txtTitleText->setAcceptRichText( false ); if ( !mDeco.enabled() && mDeco.mLabelText.isEmpty() ) { QString defaultString = QgsProject::instance()->metadata().title(); txtTitleText->setPlainText( defaultString ); } else { txtTitleText->setPlainText( mDeco.mLabelText ); } // background bar color pbnBackgroundColor->setAllowOpacity( true ); pbnBackgroundColor->setColor( mDeco.mBackgroundColor ); pbnBackgroundColor->setContext( QStringLiteral( "gui" ) ); pbnBackgroundColor->setColorDialogTitle( tr( "Select Background Bar Color" ) ); // placement cboPlacement->addItem( tr( "Top Left" ), QgsDecorationItem::TopLeft ); cboPlacement->addItem( tr( "Top Center" ), QgsDecorationItem::TopCenter ); cboPlacement->addItem( tr( "Top Right" ), QgsDecorationItem::TopRight ); cboPlacement->addItem( tr( "Bottom Left" ), QgsDecorationItem::BottomLeft ); cboPlacement->addItem( tr( "Bottom Center" ), QgsDecorationItem::BottomCenter ); cboPlacement->addItem( tr( "Bottom Right" ), QgsDecorationItem::BottomRight ); connect( cboPlacement, qOverload<int>( &QComboBox::currentIndexChanged ), this, [ = ]( int ) { spnHorizontal->setMinimum( cboPlacement->currentData() == QgsDecorationItem::TopCenter || cboPlacement->currentData() == QgsDecorationItem::BottomCenter ? -100 : 0 ); } ); cboPlacement->setCurrentIndex( cboPlacement->findData( mDeco.placement() ) ); spnHorizontal->setClearValue( 0 ); spnHorizontal->setValue( mDeco.mMarginHorizontal ); spnVertical->setValue( mDeco.mMarginVertical ); wgtUnitSelection->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderPercentage << QgsUnitTypes::RenderPixels ); wgtUnitSelection->setUnit( mDeco.mMarginUnit ); // font settings mButtonFontStyle->setDialogTitle( tr( "Title Label Text Format" ) ); mButtonFontStyle->setMapCanvas( QgisApp::instance()->mapCanvas() ); mButtonFontStyle->setTextFormat( mDeco.textFormat() ); } void QgsDecorationTitleDialog::buttonBox_accepted() { apply(); accept(); } void QgsDecorationTitleDialog::buttonBox_rejected() { reject(); } void QgsDecorationTitleDialog::mInsertExpressionButton_clicked() { QString selText = txtTitleText->textCursor().selectedText(); // edit the selected expression if there's one if ( selText.startsWith( QLatin1String( "[%" ) ) && selText.endsWith( QLatin1String( "%]" ) ) ) selText = selText.mid( 2, selText.size() - 4 ); selText = selText.replace( QChar( 0x2029 ), QChar( '\n' ) ); QgsExpressionBuilderDialog exprDlg( nullptr, selText, this, QStringLiteral( "generic" ), QgisApp::instance()->mapCanvas()->mapSettings().expressionContext() ); exprDlg.setWindowTitle( QObject::tr( "Insert Expression" ) ); if ( exprDlg.exec() == QDialog::Accepted ) { QString expression = exprDlg.expressionText(); if ( !expression.isEmpty() ) { txtTitleText->insertPlainText( "[%" + expression + "%]" ); } } } void QgsDecorationTitleDialog::apply() { mDeco.setTextFormat( mButtonFontStyle->textFormat() ); mDeco.mLabelText = txtTitleText->toPlainText(); mDeco.mBackgroundColor = pbnBackgroundColor->color(); mDeco.setPlacement( static_cast< QgsDecorationItem::Placement>( cboPlacement->currentData().toInt() ) ); mDeco.mMarginUnit = wgtUnitSelection->unit(); mDeco.mMarginHorizontal = spnHorizontal->value(); mDeco.mMarginVertical = spnVertical->value(); mDeco.setEnabled( grpEnable->isChecked() ); mDeco.update(); } void QgsDecorationTitleDialog::showHelp() { QgsHelp::openHelp( QStringLiteral( "introduction/general_tools.html#title_label_decoration" ) ); }
gpl-2.0
JBonsink/GSOC-2013
tools/ns-allinone-3.14.1/ns-3.14.1/build/.conf_check_d6c8946949ece91ce43c989711393fec/test.cpp
206
#include <Python.h> #ifdef __cplusplus extern "C" { #endif void Py_Initialize(void); void Py_Finalize(void); #ifdef __cplusplus } #endif int main() { Py_Initialize(); Py_Finalize(); return 0; }
gpl-3.0
SilenceIM/Silence
src/org/smssecure/smssecure/util/Trimmer.java
2043
package org.smssecure.smssecure.util; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; import org.smssecure.smssecure.R; import org.smssecure.smssecure.database.DatabaseFactory; import org.smssecure.smssecure.database.ThreadDatabase; public class Trimmer { public static void trimAllThreads(Context context, int threadLengthLimit) { new TrimmingProgressTask(context).execute(threadLengthLimit); } private static class TrimmingProgressTask extends AsyncTask<Integer, Integer, Void> implements ThreadDatabase.ProgressListener { private ProgressDialog progressDialog; private Context context; public TrimmingProgressTask(Context context) { this.context = context; } @Override protected void onPreExecute() { progressDialog = new ProgressDialog(context); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setCancelable(false); progressDialog.setIndeterminate(false); progressDialog.setTitle(R.string.trimmer__deleting); progressDialog.setMessage(context.getString(R.string.trimmer__deleting_old_messages)); progressDialog.setMax(100); progressDialog.show(); } @Override protected Void doInBackground(Integer... params) { DatabaseFactory.getThreadDatabase(context).trimAllThreads(params[0], this); return null; } @Override protected void onProgressUpdate(Integer... progress) { double count = progress[1]; double index = progress[0]; progressDialog.setProgress((int)Math.round((index / count) * 100.0)); } @Override protected void onPostExecute(Void result) { progressDialog.dismiss(); Toast.makeText(context, R.string.trimmer__old_messages_successfully_deleted, Toast.LENGTH_LONG).show(); } @Override public void onProgress(int complete, int total) { this.publishProgress(complete, total); } } }
gpl-3.0
wiki2014/Learning-Summary
alps/cts/tests/tests/drm/src/android/drm/cts/DRMTest.java
9247
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.drm.cts; import android.content.ContentValues; import android.test.AndroidTestCase; import android.util.Log; import java.io.IOException; import java.io.File; import java.util.HashMap; import java.util.ArrayList; import java.util.Iterator; import android.drm.DrmManagerClient; import android.drm.DrmConvertedStatus; import android.drm.DrmEvent; import android.drm.DrmInfo; import android.drm.DrmInfoRequest; import android.drm.DrmInfoStatus; import android.drm.DrmRights; import android.drm.DrmStore; import android.drm.DrmUtils; public class DRMTest extends AndroidTestCase { private static String TAG = "CtsDRMTest"; private static final int WAIT_TIME = 60000; // 1 min max private Object mLock = new Object(); private ArrayList<Config> mConfigs = new ArrayList<Config>(); private DrmRights mDrmRights; private DrmManagerClient mDrmManagerClient; @Override protected void setUp() throws Exception { super.setUp(); mDrmManagerClient = new DrmManagerClient(getContext()); String[] plugins = mDrmManagerClient.getAvailableDrmEngines(); mConfigs.clear(); for(String plugInName : plugins) { Config config = ConfigFactory.getConfig(plugInName); if (null != config) { mConfigs.add(config); } } } private void register(Config config) throws Exception { DrmInfo drmInfo = executeAcquireDrmInfo(DrmInfoRequest.TYPE_REGISTRATION_INFO, config.getInfoOfRegistration(), config.getMimeType()); executeProcessDrmInfo(drmInfo, config); } private void acquireRights(Config config) throws Exception { DrmInfo drmInfo = executeAcquireDrmInfo(DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO, config.getInfoOfRightsAcquisition(), config.getMimeType()); executeProcessDrmInfo(drmInfo, config); } private void deregister(Config config) throws Exception { DrmInfo drmInfo = executeAcquireDrmInfo(DrmInfoRequest.TYPE_UNREGISTRATION_INFO, config.getInfoOfRegistration(), config.getMimeType()); executeProcessDrmInfo(drmInfo, config); } public void testIsDrmDirectoryExist() { assertTrue("/data/drm/ does not exist", new File("/data/drm/").exists()); } public void testRegisterAndDeregister() throws Exception { for (Config config : mConfigs) { register(config); deregister(config); } } public void testAcquireRights() throws Exception { for (Config config : mConfigs) { register(config); acquireRights(config); deregister(config); } } public void testGetConstraints() throws Exception { for (Config config : mConfigs) { register(config); acquireRights(config); ContentValues constraints = mDrmManagerClient.getConstraints( config.getContentPath(), DrmStore.Action.DEFAULT); assertNotNull("Failed on plugin: " + config.getPluginName(), constraints); deregister(config); } } public void testCanHandle() throws Exception { for (Config config : mConfigs) { assertTrue("Failed on plugin: " + config.getPluginName(), mDrmManagerClient.canHandle(config.getContentPath(), config.getMimeType())); } } public void testGetOriginalMimeType() throws Exception { for (Config config : mConfigs) { assertNotNull("Failed on plugin: " + config.getPluginName(), mDrmManagerClient.getOriginalMimeType(config.getContentPath())); } } public void testCheckRightsStatus() throws Exception { for (Config config : mConfigs) { register(config); acquireRights(config); int rightsStatus = mDrmManagerClient.checkRightsStatus( config.getContentPath(), DrmStore.Action.PLAY); assertEquals("Failed on plugin: " + config.getPluginName(), DrmStore.RightsStatus.RIGHTS_VALID, rightsStatus); deregister(config); } } public void testRemoveRights() throws Exception { for (Config config : mConfigs) { assertEquals("Failed on plugin: " + config.getPluginName(), DrmManagerClient.ERROR_NONE, mDrmManagerClient.removeRights(config.getContentPath())); } } public void testRemoveAllRights() throws Exception { for (Config config : mConfigs) { assertEquals("Failed on plugin: " + config.getPluginName(), mDrmManagerClient.removeAllRights(), DrmManagerClient.ERROR_NONE); } } public void testConvertData() throws Exception { for (Config config : mConfigs) { byte[] inputData = new byte[]{'T','E','S','T'}; int convertId = mDrmManagerClient.openConvertSession(config.getMimeType()); DrmConvertedStatus drmConvertStatus = mDrmManagerClient.convertData(convertId, inputData); mDrmManagerClient.closeConvertSession(convertId); } } private DrmInfo executeAcquireDrmInfo( int type, HashMap<String, String> request, String mimeType) throws Exception { DrmInfoRequest infoRequest = new DrmInfoRequest(type, mimeType); for (Iterator it = request.keySet().iterator(); it.hasNext(); ) { String key = (String) it.next(); String value = request.get(key); infoRequest.put(key, value); } return mDrmManagerClient.acquireDrmInfo(infoRequest); } private void executeProcessDrmInfo(DrmInfo drmInfo, Config config) throws Exception { if (drmInfo == null) { return; } mDrmManagerClient.setOnEventListener(new OnEventListenerImpl(config)); drmInfo.put(DrmInfoRequest.ACCOUNT_ID, config.getAccountId()); assertEquals("Failed on plugin: " + config.getPluginName(), DrmManagerClient.ERROR_NONE, mDrmManagerClient.processDrmInfo(drmInfo)); synchronized(mLock) { try { mLock.wait(WAIT_TIME); } catch(Exception e) { Log.v(TAG, "ProcessDrmInfo: wait was interrupted."); } } } private class OnEventListenerImpl implements DrmManagerClient.OnEventListener { private Config mConfig; public OnEventListenerImpl(Config config) { mConfig = config; } @Override public void onEvent(DrmManagerClient client, DrmEvent event) { switch (event.getType()) { case DrmEvent.TYPE_DRM_INFO_PROCESSED: Log.d(TAG, "processDrmInfo() completed"); DrmInfoStatus infoStatus = (DrmInfoStatus) event.getAttribute(DrmEvent.DRM_INFO_STATUS_OBJECT); switch (infoStatus.infoType) { case DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO: mDrmRights = new DrmRights(infoStatus.data, infoStatus.mimeType); assertNotNull(mDrmRights); try { assertEquals(DrmManagerClient.ERROR_NONE, mDrmManagerClient.saveRights( mDrmRights, mConfig.getRightsPath(), mConfig.getContentPath())); Log.d(TAG, "Rights saved"); } catch (IOException e) { Log.e(TAG, "Save Rights failed"); e.printStackTrace(); } break; case DrmInfoRequest.TYPE_REGISTRATION_INFO: Log.d(TAG, "Registration completed"); break; case DrmInfoRequest.TYPE_UNREGISTRATION_INFO: Log.d(TAG, "Deregistration completed"); break; default: break; } break; default: break; } synchronized (mLock) { mLock.notify(); } } } }
gpl-3.0
SchulichUAV/ardupilot
libraries/AP_HAL_ChibiOS/hwdef/scripts/dma_resolver.py
8674
#!/usr/bin/env python import sys, fnmatch import importlib # peripheral types that can be shared, wildcard patterns SHARED_MAP = ["I2C*", "USART*_TX", "UART*_TX", "SPI*", "TIM*_UP"] ignore_list = [] dma_map = None debug = False def check_possibility(periph, dma_stream, curr_dict, dma_map, check_list): for other_periph in curr_dict: if other_periph != periph: if curr_dict[other_periph] == dma_stream: ignore_list.append(periph) check_str = "%s(%d,%d) %s(%d,%d)" % ( other_periph, curr_dict[other_periph][0], curr_dict[other_periph][1], periph, dma_stream[0], dma_stream[1]) #check if we did this before if check_str in check_list: return False check_list.append(check_str) if debug: print("Trying to Resolve Conflict: ", check_str) #check if we can resolve by swapping with other periphs for streamchan in dma_map[other_periph]: stream = (streamchan[0], streamchan[1]) if stream != curr_dict[other_periph] and \ check_possibility(other_periph, stream, curr_dict, dma_map, check_list): curr_dict[other_periph] = stream return True return False return True def can_share(periph, noshare_list): '''check if a peripheral is in the SHARED_MAP list''' for noshare in noshare_list: if fnmatch.fnmatch(periph, noshare): return False for f in SHARED_MAP: if fnmatch.fnmatch(periph, f): return True if debug: print("%s can't share" % periph) return False def chibios_dma_define_name(key): '''return define name needed for board.h for ChibiOS''' if key.startswith('ADC'): return 'STM32_ADC_%s_DMA_' % key elif key.startswith('SPI'): return 'STM32_SPI_%s_DMA_' % key elif key.startswith('I2C'): return 'STM32_I2C_%s_DMA_' % key elif key.startswith('USART'): return 'STM32_UART_%s_DMA_' % key elif key.startswith('UART'): return 'STM32_UART_%s_DMA_' % key elif key.startswith('SDIO') or key.startswith('SDMMC'): return 'STM32_SDC_%s_DMA_' % key elif key.startswith('TIM'): return 'STM32_TIM_%s_DMA_' % key else: print("Error: Unknown key type %s" % key) sys.exit(1) def get_list_index(peripheral, priority_list): '''return index into priority_list for a peripheral''' for i in range(len(priority_list)): str = priority_list[i] if fnmatch.fnmatch(peripheral, str): return i # default to max priority return len(priority_list) def get_sharing_priority(periph_list, priority_list): '''get priority of a list of peripherals we could share with''' highest = len(priority_list) for p in periph_list: prio = get_list_index(p, priority_list) if prio < highest: highest = prio return highest def write_dma_header(f, peripheral_list, mcu_type, dma_exclude=[], dma_priority='', dma_noshare=''): '''write out a DMA resolver header file''' global dma_map # form a list of DMA priorities priority_list = dma_priority.split() # sort by priority peripheral_list = sorted(peripheral_list, key=lambda x: get_list_index(x, priority_list)) # form a list of peripherals that can't share noshare_list = dma_noshare.split() try: lib = importlib.import_module(mcu_type) if hasattr(lib, "DMA_Map"): dma_map = lib.DMA_Map else: return except ImportError: print("Unable to find module for MCU %s" % mcu_type) sys.exit(1) print("Writing DMA map") unassigned = [] curr_dict = {} for periph in peripheral_list: if periph in dma_exclude: continue assigned = False check_list = [] if not periph in dma_map: print("Unknown peripheral function %s in DMA map for %s" % (periph, mcu_type)) sys.exit(1) for streamchan in dma_map[periph]: stream = (streamchan[0], streamchan[1]) if check_possibility(periph, stream, curr_dict, dma_map, check_list): curr_dict[periph] = stream assigned = True break if assigned == False: unassigned.append(periph) # now look for shared DMA possibilities stream_assign = {} for k in curr_dict.keys(): stream_assign[curr_dict[k]] = [k] unassigned_new = unassigned[:] for periph in unassigned: share_possibility = [] for streamchan in dma_map[periph]: stream = (streamchan[0], streamchan[1]) share_ok = True for periph2 in stream_assign[stream]: if not can_share(periph, noshare_list) or not can_share(periph2, noshare_list): share_ok = False if share_ok: share_possibility.append(stream) if share_possibility: # sort the possible sharings so minimise impact on high priority streams share_possibility = sorted(share_possibility, key=lambda x: get_sharing_priority(stream_assign[x], priority_list)) # and take the one with the least impact (lowest value for highest priority stream share) stream = share_possibility[-1] if debug: print("Sharing %s on %s with %s" % (periph, stream, stream_assign[stream])) curr_dict[periph] = stream stream_assign[stream].append(periph) unassigned_new.remove(periph) unassigned = unassigned_new f.write("\n\n// auto-generated DMA mapping from dma_resolver.py\n") if unassigned: f.write( "\n// Note: The following peripherals can't be resolved for DMA: %s\n\n" % unassigned) for key in sorted(curr_dict.keys()): stream = curr_dict[key] shared = '' if len(stream_assign[stream]) > 1: shared = ' // shared %s' % ','.join(stream_assign[stream]) f.write("#define %-30s STM32_DMA_STREAM_ID(%u, %u)%s\n" % (chibios_dma_define_name(key)+'STREAM', curr_dict[key][0], curr_dict[key][1], shared)) for streamchan in dma_map[key]: if stream == (streamchan[0], streamchan[1]): f.write("#define %-30s %u\n" % (chibios_dma_define_name(key)+'CHAN', streamchan[2])) break # now generate UARTDriver.cpp DMA config lines f.write("\n\n// generated UART DMA configuration lines\n") for u in range(1, 9): key = None if 'USART%u_TX' % u in peripheral_list: key = 'USART%u' % u if 'UART%u_TX' % u in peripheral_list: key = 'UART%u' % u if 'USART%u_RX' % u in peripheral_list: key = 'USART%u' % u if 'UART%u_RX' % u in peripheral_list: key = 'UART%u' % u if key is None: continue f.write("#define STM32_%s_RX_DMA_CONFIG " % key) if key + "_RX" in curr_dict: f.write( "true, STM32_UART_%s_RX_DMA_STREAM, STM32_%s_RX_DMA_CHN\n" % (key, key)) else: f.write("false, 0, 0\n") f.write("#define STM32_%s_TX_DMA_CONFIG " % key) if key + "_TX" in curr_dict: f.write( "true, STM32_UART_%s_TX_DMA_STREAM, STM32_%s_TX_DMA_CHN\n" % (key, key)) else: f.write("false, 0, 0\n") if __name__ == '__main__': import optparse parser = optparse.OptionParser("dma_resolver.py") parser.add_option("-M", "--mcu", default=None, help='MCU type') parser.add_option( "-D", "--debug", action='store_true', help='enable debug') parser.add_option( "-P", "--peripherals", default=None, help='peripheral list (comma separated)') opts, args = parser.parse_args() if opts.peripherals is None: print("Please provide a peripheral list with -P") sys.exit(1) if opts.mcu is None: print("Please provide a MCU type with -<") sys.exit(1) debug = opts.debug plist = opts.peripherals.split(',') mcu_type = opts.mcu f = open("dma.h", "w") write_dma_header(f, plist, mcu_type)
gpl-3.0
micaelbatista/neeist_wiki
wiki/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/PrefixTest.php
4529
<?php namespace Elastica\Test\Filter; use Elastica\Document; use Elastica\Filter\Prefix; use Elastica\Test\DeprecatedClassBase as BaseTest; use Elastica\Type\Mapping; class PrefixTest extends BaseTest { /** * @group unit */ public function testDeprecated() { $reflection = new \ReflectionClass(new Prefix()); $this->assertFileDeprecated($reflection->getFileName(), 'Deprecated: Filters are deprecated. Use queries in filter context. See https://www.elastic.co/guide/en/elasticsearch/reference/2.0/query-dsl-filters.html'); } /** * @group unit */ public function testToArray() { $field = 'name'; $prefix = 'ruf'; $filter = new Prefix($field, $prefix); $expectedArray = array( 'prefix' => array( $field => $prefix, ), ); $this->assertequals($expectedArray, $filter->toArray()); } /** * @group functional */ public function testDifferentPrefixes() { $client = $this->_getClient(); $index = $client->getIndex('test'); $index->create(array(), true); $type = $index->getType('test'); $mapping = new Mapping($type, array( 'name' => array('type' => 'string', 'store' => 'no', 'index' => 'not_analyzed'), ) ); $type->setMapping($mapping); $type->addDocuments(array( new Document(1, array('name' => 'Basel-Stadt')), new Document(2, array('name' => 'New York')), new Document(3, array('name' => 'Baden')), new Document(4, array('name' => 'Baden Baden')), new Document(5, array('name' => 'New Orleans')), )); $index->refresh(); $query = new Prefix('name', 'Ba'); $resultSet = $index->search($query); $this->assertEquals(3, $resultSet->count()); // Lower case should not return a result $query = new Prefix('name', 'ba'); $resultSet = $index->search($query); $this->assertEquals(0, $resultSet->count()); $query = new Prefix('name', 'Baden'); $resultSet = $index->search($query); $this->assertEquals(2, $resultSet->count()); $query = new Prefix('name', 'Baden B'); $resultSet = $index->search($query); $this->assertEquals(1, $resultSet->count()); $query = new Prefix('name', 'Baden Bas'); $resultSet = $index->search($query); $this->assertEquals(0, $resultSet->count()); } /** * @group functional */ public function testDifferentPrefixesLowercase() { $client = $this->_getClient(); $index = $client->getIndex('test'); $indexParams = array( 'analysis' => array( 'analyzer' => array( 'lw' => array( 'type' => 'custom', 'tokenizer' => 'keyword', 'filter' => array('lowercase'), ), ), ), ); $index->create($indexParams, true); $type = $index->getType('test'); $mapping = new Mapping($type, array( 'name' => array('type' => 'string', 'store' => 'no', 'analyzer' => 'lw'), ) ); $type->setMapping($mapping); $type->addDocuments(array( new Document(1, array('name' => 'Basel-Stadt')), new Document(2, array('name' => 'New York')), new Document(3, array('name' => 'Baden')), new Document(4, array('name' => 'Baden Baden')), new Document(5, array('name' => 'New Orleans')), )); $index->refresh(); $query = new Prefix('name', 'ba'); $resultSet = $index->search($query); $this->assertEquals(3, $resultSet->count()); // Upper case should not return a result $query = new Prefix('name', 'Ba'); $resultSet = $index->search($query); $this->assertEquals(0, $resultSet->count()); $query = new Prefix('name', 'baden'); $resultSet = $index->search($query); $this->assertEquals(2, $resultSet->count()); $query = new Prefix('name', 'baden b'); $resultSet = $index->search($query); $this->assertEquals(1, $resultSet->count()); $query = new Prefix('name', 'baden bas'); $resultSet = $index->search($query); $this->assertEquals(0, $resultSet->count()); } }
gpl-3.0
lyy289065406/expcodes
java/01-framework/dubbo-admin/incubator-dubbo-ops/dubbo-admin-frontend/node_modules/vuetify/src/components/VPagination/index.ts
91
import VPagination from './VPagination' export { VPagination } export default VPagination
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Source/core/input/InputDeviceCapabilities.cpp
1008
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/input/InputDeviceCapabilities.h" namespace blink { InputDeviceCapabilities::InputDeviceCapabilities(bool firesTouchEvents) { m_firesTouchEvents = firesTouchEvents; } InputDeviceCapabilities::InputDeviceCapabilities( const InputDeviceCapabilitiesInit& initializer) { m_firesTouchEvents = initializer.firesTouchEvents(); } InputDeviceCapabilities* InputDeviceCapabilities::firesTouchEventsSourceCapabilities() { DEFINE_STATIC_LOCAL(InputDeviceCapabilities, instance, (InputDeviceCapabilities::create(true))); return &instance; } InputDeviceCapabilities* InputDeviceCapabilities::doesntFireTouchEventsSourceCapabilities() { DEFINE_STATIC_LOCAL(InputDeviceCapabilities, instance, (InputDeviceCapabilities::create(false))); return &instance; } } // namespace blink
gpl-3.0
vineodd/PIMSim
GEM5Simulation/gem5/src/gpu-compute/scheduler.cc
2369
/* * Copyright (c) 2014-2017 Advanced Micro Devices, Inc. * All rights reserved. * * For use for simulation and test purposes only * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Authors: Sooraj Puthoor, * Anthony Gutierrez */ #include "gpu-compute/scheduler.hh" #include "gpu-compute/of_scheduling_policy.hh" #include "gpu-compute/rr_scheduling_policy.hh" #include "params/ComputeUnit.hh" Scheduler::Scheduler(const ComputeUnitParams *p) { if (p->execPolicy == "OLDEST-FIRST") { schedPolicy = new OFSchedulingPolicy(); } else if (p->execPolicy == "ROUND-ROBIN") { schedPolicy = new RRSchedulingPolicy(); } else { fatal("Unimplemented scheduling policy.\n"); } } Wavefront* Scheduler::chooseWave() { return schedPolicy->chooseWave(scheduleList); } void Scheduler::bindList(std::vector<Wavefront*> *sched_list) { scheduleList = sched_list; }
gpl-3.0
vbjay/gitextensions
GitUI/CommandsDialogs/FormRenameBranch.cs
2724
using System; using System.Diagnostics; using System.Linq; using System.Windows.Forms; using GitCommands; using GitCommands.Git; using ResourceManager; namespace GitUI.CommandsDialogs { public sealed partial class FormRenameBranch : GitModuleForm { private readonly TranslationString _branchRenameFailed = new TranslationString("Rename failed."); private readonly IGitBranchNameNormaliser _branchNameNormaliser; private readonly GitBranchNameOptions _gitBranchNameOptions = new GitBranchNameOptions(AppSettings.AutoNormaliseSymbol); private readonly string _oldName; [Obsolete("For VS designer and translation test only. Do not remove.")] private FormRenameBranch() { InitializeComponent(); } public FormRenameBranch(GitUICommands commands, string defaultBranch) : base(commands) { _branchNameNormaliser = new GitBranchNameNormaliser(); InitializeComponent(); InitializeComplete(); BranchNameTextBox.Text = defaultBranch; _oldName = defaultBranch; } private void BranchNameTextBox_Leave(object sender, EventArgs e) { if (!AppSettings.AutoNormaliseBranchName || !BranchNameTextBox.Text.Any(GitBranchNameNormaliser.IsValidChar)) { return; } var caretPosition = BranchNameTextBox.SelectionStart; var branchName = _branchNameNormaliser.Normalise(BranchNameTextBox.Text, _gitBranchNameOptions); BranchNameTextBox.Text = branchName; BranchNameTextBox.SelectionStart = caretPosition; } private void OkClick(object sender, EventArgs e) { // Ok button set as the "AcceptButton" for the form // if the user hits [Enter] at any point, we need to trigger BranchNameTextBox Leave event Ok.Focus(); var newName = BranchNameTextBox.Text; if (newName == _oldName) { DialogResult = DialogResult.Cancel; return; } try { var renameBranchResult = Module.RenameBranch(_oldName, newName); if (!string.IsNullOrEmpty(renameBranchResult)) { MessageBox.Show(this, _branchRenameFailed.Text + Environment.NewLine + renameBranchResult, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { Trace.WriteLine(ex.Message); } DialogResult = DialogResult.OK; } } }
gpl-3.0
jenarroyo/moodle-repo
mod/feedback/item/textarea/lib.php
10063
<?php defined('MOODLE_INTERNAL') OR die('not allowed'); require_once($CFG->dirroot.'/mod/feedback/item/feedback_item_class.php'); class feedback_item_textarea extends feedback_item_base { var $type = "textarea"; var $commonparams; var $item_form; var $item; function init() { } function build_editform($item, $feedback, $cm) { global $DB, $CFG; require_once('textarea_form.php'); //get the lastposition number of the feedback_items $position = $item->position; $lastposition = $DB->count_records('feedback_item', array('feedback'=>$feedback->id)); if($position == -1){ $i_formselect_last = $lastposition + 1; $i_formselect_value = $lastposition + 1; $item->position = $lastposition + 1; }else { $i_formselect_last = $lastposition; $i_formselect_value = $item->position; } //the elements for position dropdownlist $positionlist = array_slice(range(0,$i_formselect_last),1,$i_formselect_last,true); $item->presentation = empty($item->presentation) ? '' : $item->presentation; $widthAndHeight = explode('|',$item->presentation); $itemwidth = (isset($widthAndHeight[0]) AND $widthAndHeight[0] >= 5) ? $widthAndHeight[0] : 30; $itemheight = isset($widthAndHeight[1]) ? $widthAndHeight[1] : 5; $item->itemwidth = $itemwidth; $item->itemheight = $itemheight; //all items for dependitem $feedbackitems = feedback_get_depend_candidates_for_item($feedback, $item); $commonparams = array('cmid'=>$cm->id, 'id'=>isset($item->id) ? $item->id : NULL, 'typ'=>$item->typ, 'items'=>$feedbackitems, 'feedback'=>$feedback->id); //build the form $this->item_form = new feedback_textarea_form('edit_item.php', array('item'=>$item, 'common'=>$commonparams, 'positionlist'=>$positionlist, 'position'=>$position)); } //this function only can used after the call of build_editform() function show_editform() { $this->item_form->display(); } function is_cancelled() { return $this->item_form->is_cancelled(); } function get_data() { if($this->item = $this->item_form->get_data()) { return true; } return false; } function save_item() { global $DB; if(!$item = $this->item_form->get_data()) { return false; } if(isset($item->clone_item) AND $item->clone_item) { $item->id = ''; //to clone this item $item->position++; } $item->hasvalue = $this->get_hasvalue(); if(!$item->id) { $item->id = $DB->insert_record('feedback_item', $item); }else { $DB->update_record('feedback_item', $item); } return $DB->get_record('feedback_item', array('id'=>$item->id)); } //liefert eine Struktur ->name, ->data = array(mit Antworten) function get_analysed($item, $groupid = false, $courseid = false) { global $DB; $aVal = null; $aVal->data = array(); $aVal->name = $item->name; //$values = $DB->get_records('feedback_value', array('item'=>$item->id)); $values = feedback_get_group_values($item, $groupid, $courseid); if($values) { $data = array(); foreach($values as $value) { $data[] = str_replace("\n", '<br />', $value->value); } $aVal->data = $data; } return $aVal; } function get_printval($item, $value) { if(!isset($value->value)) return ''; return $value->value; } function print_analysed($item, $itemnr = '', $groupid = false, $courseid = false) { $values = feedback_get_group_values($item, $groupid, $courseid); if($values) { //echo '<table>';2 // $itemnr++; echo '<tr><th colspan="2" align="left">'. $itemnr . '&nbsp;('. $item->label .') ' . $item->name .'</th></tr>'; foreach($values as $value) { echo '<tr><td valign="top" align="left">-&nbsp;&nbsp;</td><td align="left" valign="top">' . str_replace("\n", '<br />', $value->value) . '</td></tr>'; } //echo '</table>'; } // return $itemnr; } function excelprint_item(&$worksheet, $rowOffset, $xlsFormats, $item, $groupid, $courseid = false) { $analysed_item = $this->get_analysed($item, $groupid, $courseid); // $worksheet->setFormat("<l><f><ro2><vo><c:green>"); $worksheet->write_string($rowOffset, 0, $item->label, $xlsFormats->head2); $worksheet->write_string($rowOffset, 1, $item->name, $xlsFormats->head2); $data = $analysed_item->data; if(is_array($data)) { // $worksheet->setFormat("<l><ro2><vo>"); if(isset($data[0])) { $worksheet->write_string($rowOffset, 2, $data[0], $xlsFormats->value_bold); } $rowOffset++; $sizeofdata = sizeof($data); for($i = 1; $i < $sizeofdata; $i++) { // $worksheet->setFormat("<l><vo>"); $worksheet->write_string($rowOffset, 2, $data[$i], $xlsFormats->default); $rowOffset++; } } $rowOffset++; return $rowOffset; } /** * print the item at the edit-page of feedback * * @global object * @param object $item * @return void */ function print_item_preview($item) { global $OUTPUT, $DB; $align = right_to_left() ? 'right' : 'left'; $presentation = explode ("|", $item->presentation); $requiredmark = ($item->required == 1)?'<span class="feedback_required_mark">*</span>':''; //print the question and label echo '<div class="feedback_item_label_'.$align.'">'; echo '('.$item->label.') '; echo format_text($item->name.$requiredmark, true, false, false); if($item->dependitem) { if($dependitem = $DB->get_record('feedback_item', array('id'=>$item->dependitem))) { echo ' <span class="feedback_depend">('.$dependitem->label.'-&gt;'.$item->dependvalue.')</span>'; } } echo '</div>'; //print the presentation echo '<div class="feedback_item_presentation_'.$align.'">'; echo '<span class="feedback_item_textarea">'; echo '<textarea name="'.$item->typ.'_'.$item->id.'" cols="'.$presentation[0].'" rows="'.$presentation[1].'"></textarea>'; echo '</span>'; echo '</div>'; } /** * print the item at the complete-page of feedback * * @global object * @param object $item * @param string $value * @param bool $highlightrequire * @return void */ function print_item_complete($item, $value = '', $highlightrequire = false) { global $OUTPUT; $align = right_to_left() ? 'right' : 'left'; $presentation = explode ("|", $item->presentation); if($highlightrequire AND $item->required AND strval($value) == '') { $highlight = ' missingrequire'; }else { $highlight = ''; } $requiredmark = ($item->required == 1)?'<span class="feedback_required_mark">*</span>':''; //print the question and label echo '<div class="feedback_item_label_'.$align.$highlight.'">'; echo format_text($item->name . $requiredmark, true, false, false); echo '</div>'; //print the presentation echo '<div class="feedback_item_presentation_'.$align.$highlight.'">'; echo '<span class="feedback_item_textarea">'; echo '<textarea name="'.$item->typ.'_'.$item->id.'" cols="'.$presentation[0].'" rows="'.$presentation[1].'">'.$value.'</textarea>'; echo '</span>'; echo '</div>'; } /** * print the item at the complete-page of feedback * * @global object * @param object $item * @param string $value * @return void */ function print_item_show_value($item, $value = '') { global $OUTPUT; $align = right_to_left() ? 'right' : 'left'; $presentation = explode ("|", $item->presentation); $requiredmark = ($item->required == 1)?'<span class="feedback_required_mark">*</span>':''; //print the question and label echo '<div class="feedback_item_label_'.$align.'">'; echo '('.$item->label.') '; echo format_text($item->name . $requiredmark, true, false, false); echo '</div>'; //print the presentation echo $OUTPUT->box_start('generalbox boxalign'.$align); echo $value?str_replace("\n",'<br />',$value):'&nbsp;'; echo $OUTPUT->box_end(); } function check_value($value, $item) { //if the item is not required, so the check is true if no value is given if((!isset($value) OR $value == '') AND $item->required != 1) return true; if($value == "")return false; return true; } function create_value($data) { $data = s($data); return $data; } //compares the dbvalue with the dependvalue //dbvalue is the value put in by the user //dependvalue is the value that is compared function compare_value($item, $dbvalue, $dependvalue) { if($dbvalue == $dependvalue) { return true; } return false; } function get_presentation($data) { return $data->itemwidth . '|'. $data->itemheight; } function get_hasvalue() { return 1; } function can_switch_require() { return true; } function clean_input_value($value) { return s($value); } }
gpl-3.0
krharrison/cilib
library/src/main/java/net/sourceforge/cilib/niching/merging/detection/MergeDetection.java
569
/** __ __ * _____ _/ /_/ /_ Computational Intelligence Library (CIlib) * / ___/ / / / __ \ (c) CIRG @ UP * / /__/ / / / /_/ / http://cilib.net * \___/_/_/_/_.___/ */ package net.sourceforge.cilib.niching.merging.detection; import net.sourceforge.cilib.algorithm.population.SinglePopulationBasedAlgorithm; import fj.F2; /** * Merge detection strategies for Niching. * * Used to merge two swarms into one. */ public abstract class MergeDetection extends F2<SinglePopulationBasedAlgorithm, SinglePopulationBasedAlgorithm, Boolean> { }
gpl-3.0
erikriver/eduIntelligent-cynin
src/ubify.cyninv2theme/ubify/cyninv2theme/browser/itemdetails.py
6590
############################################################################### #cyn.in is an open source Collaborative Knowledge Management Appliance that #enables teams to seamlessly work together on files, documents and content in #a secure central environment. # #cyn.in v2 an open source appliance is distributed under the GPL v3 license #along with commercial support options. # #cyn.in is a Cynapse Invention. # #Copyright (C) 2008 Cynapse India Pvt. Ltd. # #This program is free software: you can redistribute it and/or modify it under #the terms of the GNU General Public License as published by the Free Software #Foundation, either version 3 of the License, or any later version and observe #the Additional Terms applicable to this program and must display appropriate #legal notices. In accordance with Section 7(b) of the GNU General Public #License version 3, these Appropriate Legal Notices must retain the display of #the "Powered by cyn.in" AND "A Cynapse Invention" logos. You should have #received a copy of the detailed Additional Terms License with this program. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General #Public License for more details. # #You should have received a copy of the GNU General Public License along with #this program. If not, see <http://www.gnu.org/licenses/>. # #You can contact Cynapse at support@cynapse.com with any problems with cyn.in. #For any queries regarding the licensing, please send your mails to # legal@cynapse.com # #You can also contact Cynapse at: #802, Building No. 1, #Dheeraj Sagar, Malad(W) #Mumbai-400064, India ############################################################################### from Products.CMFCore.utils import getToolByName from Products.Five import BrowserView from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from zope.publisher.interfaces import NotFound from AccessControl import getSecurityManager from Acquisition import aq_inner, aq_parent from DateTime import DateTime from ubify.viewlets.browser.custommethods import get_displaycountforlist,canreply,getjsondata from ubify.cyninv2theme import getListingTemplateForContextParent class ItemDetails(BrowserView): """Contains backend code for expanded item """ template = ViewPageTemplateFile('itemdetails.pt') def __call__(self): uid = None itemindex = 0 if self.request.form.has_key('uid'): uid = self.request.form['uid'] if self.request.form.has_key('itemindex'): itemindex = self.request.form['itemindex'] if uid is not None: query = {'UID':uid} pdt = getToolByName(self.context,'portal_discussion') cat = getToolByName(self.context, 'uid_catalog') resbrains = cat.searchResults(query) if len(resbrains) == 1: item = resbrains[0] contobj = item.getObject() fullpath = item.getPath() splitpath = fullpath.split('/')[:-1] prettypath = '/' + '/'.join(splitpath) URLsuffix = getListingTemplateForContextParent(item) pathlink = self.context.portal_url() + prettypath + '/' + URLsuffix pathtitle = prettypath lasttimestamp = DateTime().timeTime() lastcommentid = '0' showxmorelink = True commentscount = 0 xmorecomments = 0 replydict = [] isDiscussable = contobj.isDiscussable() canReply = canreply(contobj) jsondata = getjsondata(self.context,replydict,self.context.portal_url(),contobj.absolute_url()) if isDiscussable: dobj = pdt.getDiscussionFor(contobj) alldiscussions = dobj.objectValues() alldiscussions.sort(lambda x,y:cmp(x.modified(),y.modified()),reverse=True) maxdispcomments = get_displaycountforlist() lastxdiscussions = alldiscussions[:maxdispcomments] commentscount = dobj.replyCount(contobj) if commentscount > maxdispcomments: showxmorelink = True xmorecomments = commentscount - maxdispcomments elif commentscount > 0 and commentscount <= maxdispcomments: showxmorelink = False xmorecomments = 0 else: showxmorelink = True commentscount = 0 xmorecomments = 0 if len(alldiscussions) > 0: lasttimestamp = alldiscussions[0].modified().timeTime() lastcommentid = alldiscussions[0].id lastxdiscussions.sort(lambda x,y:cmp(x.modified(),y.modified())) for eachdisc in lastxdiscussions: reply = dobj.getReply(eachdisc.id) if reply <> None: replydict.append({'depth': 0,'object':reply,'showoutput':True}) other_data = {'view_type':'listview','canreply': str(canReply)} jsondata = getjsondata(self.context,replydict,self.context.portal_url(),contobj.absolute_url(),other_data) return self.template(item_type=contobj.portal_type,item_type_title=contobj.Type(),item=item,pathlink=pathlink,pathtitle=pathtitle,contobj=contobj,showxmorelink = showxmorelink, xmorecomments = xmorecomments,allowdiscussion = isDiscussable,usercanreply = canReply,uid=uid,reply_dict=jsondata,title=contobj.Title(),commentcount=commentscount,lasttimestamp = lasttimestamp,lastcommentid = lastcommentid,itemindex=itemindex,view_type='listview') else: raise NotFound('Object not found for request','Not found',self.request) else: raise NotFound('uid is not passed','Not found',self.request)
gpl-3.0
alexvandesande/cpp-ethereum
libtestutils/BlockChainLoader.cpp
1453
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file BlockChainLoader.cpp * @author Marek Kotewicz <marek@ethdev.com> * @date 2015 */ #include "BlockChainLoader.h" #include "StateLoader.h" #include "Common.h" using namespace std; using namespace dev; using namespace dev::test; using namespace dev::eth; BlockChainLoader::BlockChainLoader(Json::Value const& _json) { // load pre state StateLoader sl(_json["pre"], m_dir.path()); m_state = sl.state(); // load genesisBlock m_bc.reset(new BlockChain(fromHex(_json["genesisRLP"].asString()), m_dir.path(), WithExisting::Kill)); assert(m_state.rootHash() == m_bc->info().stateRoot); // load blocks for (auto const& block: _json["blocks"]) { bytes rlp = fromHex(block["rlp"].asString()); m_bc->import(rlp, m_state.db()); } // sync state m_state.sync(*m_bc); }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Source/core/layout/line/TrailingObjects.cpp
3665
/* * Copyright (C) 2000 Lars Knoll (knoll@kde.org) * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. * All right reserved. * Copyright (C) 2010 Google Inc. All rights reserved. * Copyright (C) 2014 Adobe Systems Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "core/layout/line/TrailingObjects.h" #include "core/layout/api/LineLayoutItem.h" #include "core/layout/line/BreakingContextInlineHeaders.h" #include "core/layout/line/InlineIterator.h" namespace blink { void TrailingObjects::updateMidpointsForTrailingObjects( LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace) { if (!m_whitespace) return; // This object is either going to be part of the last midpoint, or it is going // to be the actual endpoint. In both cases we just decrease our pos by 1 // level to exclude the space, allowing it to - in effect - collapse into the // newline. if (lineMidpointState.numMidpoints() % 2) { // Find the trailing space object's midpoint. int trailingSpaceMidpoint = lineMidpointState.numMidpoints() - 1; for (; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints()[trailingSpaceMidpoint] .getLineLayoutItem() != m_whitespace; --trailingSpaceMidpoint) { } ASSERT(trailingSpaceMidpoint >= 0); if (collapseFirstSpace == CollapseFirstSpace) lineMidpointState.midpoints()[trailingSpaceMidpoint].setOffset( lineMidpointState.midpoints()[trailingSpaceMidpoint].offset() - 1); // Now make sure every single trailingPositionedBox following the // trailingSpaceMidpoint properly stops and starts ignoring spaces. size_t currentMidpoint = trailingSpaceMidpoint + 1; for (size_t i = 0; i < m_objects.size(); ++i) { if (currentMidpoint >= lineMidpointState.numMidpoints()) { // We don't have a midpoint for this box yet. ensureLineBoxInsideIgnoredSpaces(&lineMidpointState, LineLayoutItem(m_objects[i])); } else { ASSERT(lineMidpointState.midpoints()[currentMidpoint] .getLineLayoutItem() == m_objects[i]); ASSERT(lineMidpointState.midpoints()[currentMidpoint + 1] .getLineLayoutItem() == m_objects[i]); } currentMidpoint += 2; } } else if (!lBreak.getLineLayoutItem()) { ASSERT(collapseFirstSpace == CollapseFirstSpace); // Add a new end midpoint that stops right at the very end. unsigned length = m_whitespace.textLength(); unsigned pos = length >= 2 ? length - 2 : UINT_MAX; InlineIterator endMid(0, m_whitespace, pos); lineMidpointState.startIgnoringSpaces(endMid); for (size_t i = 0; i < m_objects.size(); ++i) { ensureLineBoxInsideIgnoredSpaces(&lineMidpointState, m_objects[i]); } } } } // namespace blink
gpl-3.0
sergiocazzolato/snapd
store/errors.go
8838
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2014-2018 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package store import ( "errors" "fmt" "net/url" "sort" "strings" "github.com/snapcore/snapd/snap/channel" "github.com/snapcore/snapd/strutil" ) var ( // ErrBadQuery is returned from Find when the query has special characters in strange places. ErrBadQuery = errors.New("bad query") // ErrInvalidScope is returned from Find when an invalid scope is requested. ErrInvalidScope = errors.New("invalid scope") // ErrSnapNotFound is returned when a snap can not be found ErrSnapNotFound = errors.New("snap not found") // ErrUnauthenticated is returned when authentication is needed to complete the query ErrUnauthenticated = errors.New("you need to log in first") // ErrAuthenticationNeeds2fa is returned if the authentication needs 2factor ErrAuthenticationNeeds2fa = errors.New("two factor authentication required") // Err2faFailed is returned when 2fa failed (e.g., a bad token was given) Err2faFailed = errors.New("two factor authentication failed") // ErrInvalidCredentials is returned on login error // It can also be returned when refreshing the discharge // macaroon if the user has changed their password. ErrInvalidCredentials = errors.New("invalid credentials") // ErrTOSNotAccepted is returned when the user has not accepted the store's terms of service. ErrTOSNotAccepted = errors.New("terms of service not accepted") // ErrNoPaymentMethods is returned when the user has no valid payment methods associated with their account. ErrNoPaymentMethods = errors.New("no payment methods") // ErrPaymentDeclined is returned when the user's payment method was declined by the upstream payment provider. ErrPaymentDeclined = errors.New("payment declined") // ErrLocalSnap is returned when an operation that only applies to snaps that come from a store was attempted on a local snap. ErrLocalSnap = errors.New("cannot perform operation on local snap") // ErrNoUpdateAvailable is returned when an update is attempetd for a snap that has no update available. ErrNoUpdateAvailable = errors.New("snap has no updates available") ) // RevisionNotAvailableError is returned when an install is attempted for a snap but the/a revision is not available (given install constraints). type RevisionNotAvailableError struct { Action string Channel string Releases []channel.Channel } func (e *RevisionNotAvailableError) Error() string { return "no snap revision available as specified" } // DownloadError represents a download error type DownloadError struct { Code int URL *url.URL } func (e *DownloadError) Error() string { return fmt.Sprintf("received an unexpected http response code (%v) when trying to download %s", e.Code, e.URL) } // PasswordPolicyError is returned in a few corner cases, most notably // when the password has been force-reset. type PasswordPolicyError map[string]stringList func (e PasswordPolicyError) Error() string { var msg string if reason, ok := e["reason"]; ok && len(reason) == 1 { msg = reason[0] if location, ok := e["location"]; ok && len(location) == 1 { msg += "\nTo address this, go to: " + location[0] + "\n" } } else { for k, vs := range e { msg += fmt.Sprintf("%s: %s\n", k, strings.Join(vs, " ")) } } return msg } // InvalidAuthDataError signals that the authentication data didn't pass validation. type InvalidAuthDataError map[string]stringList func (e InvalidAuthDataError) Error() string { var es []string for _, v := range e { es = append(es, v...) } // XXX: confirm with server people that extra args are all // full sentences (with periods and capitalization) // (empirically this checks out) return strings.Join(es, " ") } // SnapActionError conveys errors that were reported on otherwise overall successful snap action (install/refresh) request. type SnapActionError struct { // NoResults is set if there were no results in the response NoResults bool // Refresh errors by snap name. Refresh map[string]error // Install errors by snap name. Install map[string]error // Download errors by snap name. Download map[string]error // Other errors. Other []error } // SingleOpError returns the single operation, snap name, and error if // e represents a single error of a single operation on a single snap // (i.e. if e.Other is empty, and e.Refresh, e.Install and e.Download // have a single error in total). // In any other case, the error returned will be nil. func (e SnapActionError) SingleOpError() (op, name string, err error) { if len(e.Other) > 0 { return "", "", nil } nRefresh := len(e.Refresh) nInstall := len(e.Install) nDownload := len(e.Download) if nRefresh+nInstall+nDownload != 1 { return "", "", nil } var errs map[string]error switch { case nRefresh > 0: op = "refresh" errs = e.Refresh case nInstall > 0: op = "install" errs = e.Install case nDownload > 0: op = "download" errs = e.Download } for name, err = range errs { return op, name, err } // can't happen return "", "", nil } func (e SnapActionError) Error() string { nRefresh := len(e.Refresh) nInstall := len(e.Install) nDownload := len(e.Download) nOther := len(e.Other) // single error switch nRefresh + nInstall + nDownload + nOther { case 0: if e.NoResults { // this is an atypical result return "no install/refresh information results from the store" } case 1: if nOther == 0 { op, name, err := e.SingleOpError() return fmt.Sprintf("cannot %s snap %q: %v", op, name, err) } else { return fmt.Sprintf("cannot refresh, install, or download: %v", e.Other[0]) } } header := "cannot refresh, install, or download:" if nOther == 0 { // at least one of nDownload, nInstall, or nRefresh is > 0 switch { case nDownload == 0 && nRefresh == 0: header = "cannot install:" case nDownload == 0 && nInstall == 0: header = "cannot refresh:" case nRefresh == 0 && nInstall == 0: header = "cannot download:" case nDownload == 0: header = "cannot refresh or install:" case nInstall == 0: header = "cannot refresh or download:" case nRefresh == 0: header = "cannot install or download:" } } // reverse the "snap->error" map to "error->snap", as the // common case is that all snaps fail with the same error // (e.g. "no refresh available") errToSnaps := map[string][]string{} errKeys := []string{} // poorman's ordered map for _, m := range []map[string]error{e.Refresh, e.Install, e.Download} { for snapName, err := range m { k := err.Error() v, ok := errToSnaps[k] if !ok { errKeys = append(errKeys, k) } errToSnaps[k] = append(v, snapName) } } es := make([]string, 1, 1+len(errToSnaps)+nOther) es[0] = header for _, k := range errKeys { sort.Strings(errToSnaps[k]) es = append(es, fmt.Sprintf("%s: %s", k, strutil.Quoted(errToSnaps[k]))) } for _, e := range e.Other { es = append(es, e.Error()) } if len(es) == 2 { // header + 1 reason return strings.Join(es, " ") } return strings.Join(es, "\n") } // Authorization soft-expiry errors that get handled automatically. var ( errUserAuthorizationNeedsRefresh = errors.New("soft-expired user authorization needs refresh") errDeviceAuthorizationNeedsRefresh = errors.New("soft-expired device authorization needs refresh") ) func translateSnapActionError(action, snapChannel, code, message string, releases []snapRelease) error { switch code { case "revision-not-found": e := &RevisionNotAvailableError{ Action: action, Channel: snapChannel, } if len(releases) != 0 { parsedReleases := make([]channel.Channel, len(releases)) for i := 0; i < len(releases); i++ { var err error parsedReleases[i], err = channel.Parse(releases[i].Channel, releases[i].Architecture) if err != nil { // shouldn't happen, return error without Releases return e } } e.Releases = parsedReleases } return e case "id-not-found", "name-not-found": return ErrSnapNotFound case "user-authorization-needs-refresh": return errUserAuthorizationNeedsRefresh case "device-authorization-needs-refresh": return errDeviceAuthorizationNeedsRefresh default: return fmt.Errorf("%v", message) } }
gpl-3.0
dioptre/rasdaman
applications/raswct/lib/jsclass/min/forwardable.js
347
JS.Forwardable=new JS.Module('Forwardable',{defineDelegator:function(b,e,d,f){d=d||e;this.define(d,function(){var a=this[b],c=a[e];return(typeof c==='function')?c.apply(a,arguments):c},{_0:f!==false})},defineDelegators:function(){var a=JS.array(arguments),c=a.shift(),b=a.length;while(b--)this.defineDelegator(c,a[b],a[b],false);this.resolve()}});
gpl-3.0
chris-steele/sliderMatchingTestPackage
src/extensions/adapt-contrib-pageLevelProgress/js/adapt-contrib-pageLevelProgress.js
2860
define(function(require) { var Adapt = require('coreJS/adapt'); var Backbone = require('backbone'); var completionCalculations = require('./completionCalculations'); var PageLevelProgressMenuView = require('extensions/adapt-contrib-pageLevelProgress/js/PageLevelProgressMenuView'); var PageLevelProgressNavigationView = require('extensions/adapt-contrib-pageLevelProgress/js/PageLevelProgressNavigationView'); function setupPageLevelProgress(pageModel, enabledProgressComponents) { new PageLevelProgressNavigationView({model: pageModel, collection: new Backbone.Collection(enabledProgressComponents) }); } // This should add/update progress on menuView Adapt.on('menuView:postRender', function(view) { if (view.model.get('_id') == Adapt.location._currentId) return; // do not proceed until pageLevelProgress enabled on course.json if (!Adapt.course.get('_pageLevelProgress') || !Adapt.course.get('_pageLevelProgress')._isEnabled) { return; } var pageLevelProgress = view.model.get('_pageLevelProgress'); var viewType = view.model.get('_type'); // Progress bar should not render for course viewType if (viewType == 'course') return; if (pageLevelProgress && pageLevelProgress._isEnabled) { var completionObject = completionCalculations.calculateCompletion(view.model); //take all non-assessment components and subprogress info into the percentage //this allows the user to see if the assessments are passed (subprogress) and all other components are complete var completed = completionObject.nonAssessmentCompleted + completionObject.subProgressCompleted; var total = completionObject.nonAssessmentTotal + completionObject.subProgressTotal; var percentageComplete = Math.floor((completed / total)*100); view.model.set('completedChildrenAsPercentage', percentageComplete); view.$el.find('.menu-item-inner').append(new PageLevelProgressMenuView({model: view.model}).$el); } }); // This should add/update progress on page navigation bar Adapt.on('router:page', function(pageModel) { // do not proceed until pageLevelProgress enabled on course.json if (!Adapt.course.get('_pageLevelProgress') || !Adapt.course.get('_pageLevelProgress')._isEnabled) { return; } var currentPageComponents = pageModel.findDescendants('components').where({'_isAvailable': true}); var enabledProgressComponents = completionCalculations.getPageLevelProgressEnabledModels(currentPageComponents); if (enabledProgressComponents.length > 0) { setupPageLevelProgress(pageModel, enabledProgressComponents); } }); });
gpl-3.0
NSAMR/journal.nsamr.ac.uk
jsamr/js/plugins/citationFormats.js
1697
/** * @file js/plugins/citationFormats.js * * Copyright (c) 2014-2016 Simon Fraser University Library * Copyright (c) 2000-2016 John Willinsky * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @brief Frontend script to fetch citation formats on demand. * * This script is designed to be compatible with any themes that follow these * steps. First, you need a target element that will display the citation in * the requested format. This should have an id of `citationOutput`: * * <div id="citationOutput"></div> * * You can create a link to retrieve a citation and display it in this div by * assigning the link a `data-load-citation` attribute: * * <a href="{url ...}" data-load-citation="true">View citation in ABNT format</a> * * Downloadable citations should leave the `data-load-citation` attribute out * to allow normal browser download handling. * * This script requires jQuery. The format you specify should match * a format provided by a CitationFormat plugin. */ (function($) { // Require jQuery if (typeof $ === 'undefined') { return; } var citationOutput = $('#citationOutput'), citationFormatLinks = $('[data-load-citation]'); if (!citationOutput.length || !citationFormatLinks.length) { return; } citationFormatLinks.click(function(e) { e.preventDefault(); e.stopPropagation(); var url = $(this).attr('href') + '/json'; citationOutput.css('opacity', 0.5); $.ajax({url: url, dataType: 'json'}) .done(function(r) { citationOutput.html(r.content) .hide() .css('opacity', 1) .fadeIn(); }) .fail(function(r) { citationOutput.css('opacity', 1); }); }); })(jQuery);
gpl-3.0
abcdefg30/OpenRA
mods/ra/maps/soviet-06a/soviet06a.lua
5846
--[[ Copyright 2007-2021 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] ArmorAttack = { } AttackPaths = { { AttackWaypoint1 }, { AttackWaypoint2 } } BaseAttackers = { BaseAttacker1, BaseAttacker2 } InfAttack = { } IntroAttackers = { IntroEnemy1, IntroEnemy2, IntroEnemy3 } Trucks = { Truck1, Truck2 } AlliedInfantryTypes = { "e1", "e1", "e3" } AlliedArmorTypes = { "jeep", "jeep", "1tnk", "1tnk", "2tnk", "2tnk", "arty" } SovietReinforcements1 = { "e6", "e6", "e6", "e6", "e6" } SovietReinforcements2 = { "e4", "e4", "e2", "e2", "e2" } SovietReinforcements1Waypoints = { McvWaypoint.Location, APCWaypoint1.Location } SovietReinforcements2Waypoints = { McvWaypoint.Location, APCWaypoint2.Location } TruckGoalTrigger = { CPos.New(83, 7), CPos.New(83, 8), CPos.New(83, 9), CPos.New(83, 10), CPos.New(84, 10), CPos.New(84, 11), CPos.New(84, 12), CPos.New(85, 12), CPos.New(86, 12), CPos.New(87, 12), CPos.New(87, 13), CPos.New(88, 13), CPos.New(89, 13), CPos.New(90, 13), CPos.New(90, 14), CPos.New(90, 15), CPos.New(91, 15), CPos.New(92, 15), CPos.New(93, 15), CPos.New(94, 15) } CameraBarrierTrigger = { CPos.New(65, 39), CPos.New(65, 40), CPos.New(66, 40), CPos.New(66, 41), CPos.New(67, 41), CPos.New(67, 42), CPos.New(68, 42), CPos.New(68, 43), CPos.New(68, 44) } CameraBaseTrigger = { CPos.New(53, 42), CPos.New(54, 42), CPos.New(54, 41), CPos.New(55, 41), CPos.New(56, 41), CPos.New(56, 40), CPos.New(57, 40), CPos.New(57, 39), CPos.New(58, 39), CPos.New(59, 39), CPos.New(59, 38), CPos.New(60, 38), CPos.New(61, 38) } Trigger.OnEnteredFootprint(TruckGoalTrigger, function(a, id) if not truckGoalTrigger and a.Owner == player and a.Type == "truk" then truckGoalTrigger = true player.MarkCompletedObjective(sovietObjective) player.MarkCompletedObjective(SaveAllTrucks) end end) Trigger.OnEnteredFootprint(CameraBarrierTrigger, function(a, id) if not cameraBarrierTrigger and a.Owner == player then cameraBarrierTrigger = true local cameraBarrier = Actor.Create("camera", true, { Owner = player, Location = CameraBarrier.Location }) Trigger.AfterDelay(DateTime.Seconds(15), function() cameraBarrier.Destroy() end) end end) Trigger.OnEnteredFootprint(CameraBaseTrigger, function(a, id) if not cameraBaseTrigger and a.Owner == player then cameraBaseTrigger = true local cameraBase1 = Actor.Create("camera", true, { Owner = player, Location = CameraBase1.Location }) local cameraBase2 = Actor.Create("camera", true, { Owner = player, Location = CameraBase2.Location }) local cameraBase3 = Actor.Create("camera", true, { Owner = player, Location = CameraBase3.Location }) local cameraBase4 = Actor.Create("camera", true, { Owner = player, Location = CameraBase4.Location }) Trigger.AfterDelay(DateTime.Minutes(1), function() cameraBase1.Destroy() cameraBase2.Destroy() cameraBase3.Destroy() cameraBase4.Destroy() end) end end) Trigger.OnAllKilled(Trucks, function() enemy.MarkCompletedObjective(alliedObjective) end) Trigger.OnAnyKilled(Trucks, function() player.MarkFailedObjective(SaveAllTrucks) end) Trigger.OnKilled(Apwr, function(building) BaseApwr.exists = false end) Trigger.OnKilled(Barr, function(building) BaseTent.exists = false end) Trigger.OnKilled(Proc, function(building) BaseProc.exists = false end) Trigger.OnKilled(Weap, function(building) BaseWeap.exists = false end) Trigger.OnKilled(Apwr2, function(building) BaseApwr2.exists = false end) Trigger.OnKilledOrCaptured(Dome, function() Trigger.AfterDelay(DateTime.Seconds(2), function() player.MarkCompletedObjective(sovietObjective2) Media.PlaySpeechNotification(player, "ObjectiveMet") end) end) -- Activate the AI once the player deployed the Mcv Trigger.OnRemovedFromWorld(Mcv, function() if not mcvDeployed then mcvDeployed = true BuildBase() SendEnemies() Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry) Trigger.AfterDelay(DateTime.Minutes(2), ProduceArmor) Trigger.AfterDelay(DateTime.Minutes(2), function() Utils.Do(BaseAttackers, function(actor) IdleHunt(actor) end) end) end end) WorldLoaded = function() player = Player.GetPlayer("USSR") enemy = Player.GetPlayer("Greece") Camera.Position = CameraStart.CenterPosition Mcv.Move(McvWaypoint.Location) Harvester.FindResources() Utils.Do(IntroAttackers, function(actor) IdleHunt(actor) end) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == enemy and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < 3/4 * building.MaxHealth then building.StartBuildingRepairs() end end) end end) Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements1, SovietReinforcements1Waypoints) Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements2, SovietReinforcements2Waypoints) InitObjectives(player) alliedObjective = enemy.AddObjective("Destroy all Soviet troops.") sovietObjective = player.AddObjective("Escort the Convoy.") sovietObjective2 = player.AddObjective("Destroy or capture the Allied radar dome to stop\nenemy reinforcements.", "Secondary", false) SaveAllTrucks = player.AddObjective("Keep all trucks alive.", "Secondary", false) end Tick = function() if player.HasNoRequiredUnits() then enemy.MarkCompletedObjective(alliedObjective) end if enemy.Resources >= enemy.ResourceCapacity * 0.75 then enemy.Cash = enemy.Cash + enemy.Resources - enemy.ResourceCapacity * 0.25 enemy.Resources = enemy.ResourceCapacity * 0.25 end end
gpl-3.0
Jorge-Rodriguez/ansible
lib/ansible/modules/cloud/azure/azure_rm_devtestlabvirtualnetwork.py
9917
#!/usr/bin/python # # Copyright (c) 2019 Zim Kalinowski, <zikalino@microsoft.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_devtestlabvirtualnetwork version_added: "2.8" short_description: Manage Azure DevTest Lab Virtual Network instance. description: - Create, update and delete instance of Azure DevTest Lab Virtual Network. options: resource_group: description: - The name of the resource group. required: True lab_name: description: - The name of the lab. required: True name: description: - The name of the virtual network. required: True location: description: - The location of the resource. description: description: - The description of the virtual network. state: description: - Assert the state of the Virtual Network. - Use 'present' to create or update an Virtual Network and 'absent' to delete it. default: present choices: - absent - present extends_documentation_fragment: - azure - azure_tags author: - "Zim Kalinowski (@zikalino)" ''' EXAMPLES = ''' - name: Create (or update) Virtual Network azure_rm_devtestlabvirtualnetwork: resource_group: testrg lab_name: mylab name: myvn description: My Lab Virtual Network ''' RETURN = ''' id: description: - The identifier of the resource. returned: always type: str sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/testrg/providers/microsoft.devtestlab/ mylab/mylab/virtualnetworks/myvn" external_provider_resource_id: description: - The identifier of external virtual network. returned: always type: str sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/testrg/providers/Microsoft.Network/vi rtualNetworks/myvn" ''' import time from ansible.module_utils.azure_rm_common import AzureRMModuleBase from ansible.module_utils.common.dict_transformations import _snake_to_camel try: from msrestazure.azure_exceptions import CloudError from msrest.polling import LROPoller from msrestazure.azure_operation import AzureOperationPoller from azure.mgmt.devtestlabs import DevTestLabsClient from msrest.serialization import Model except ImportError: # This is handled in azure_rm_common pass class Actions: NoAction, Create, Update, Delete = range(4) class AzureRMDevTestLabVirtualNetwork(AzureRMModuleBase): """Configuration class for an Azure RM Virtual Network resource""" def __init__(self): self.module_arg_spec = dict( resource_group=dict( type='str', required=True ), lab_name=dict( type='str', required=True ), name=dict( type='str', required=True ), location=dict( type='str' ), description=dict( type='str' ), state=dict( type='str', default='present', choices=['present', 'absent'] ) ) self.resource_group = None self.lab_name = None self.name = None self.virtual_network = {} self.results = dict(changed=False) self.mgmt_client = None self.state = None self.to_do = Actions.NoAction super(AzureRMDevTestLabVirtualNetwork, self).__init__(derived_arg_spec=self.module_arg_spec, supports_check_mode=True, supports_tags=True) def exec_module(self, **kwargs): """Main module execution method""" for key in list(self.module_arg_spec.keys()) + ['tags']: if hasattr(self, key): setattr(self, key, kwargs[key]) elif kwargs[key] is not None: self.virtual_network[key] = kwargs[key] response = None self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, base_url=self._cloud_environment.endpoints.resource_manager, api_version='2018-10-15') resource_group = self.get_resource_group(self.resource_group) if self.virtual_network.get('location') is None: self.virtual_network['location'] = resource_group.location old_response = self.get_virtualnetwork() if not old_response: self.log("Virtual Network instance doesn't exist") if self.state == 'absent': self.log("Old instance didn't exist") else: self.to_do = Actions.Create else: self.log("Virtual Network instance already exists") if self.state == 'absent': self.to_do = Actions.Delete elif self.state == 'present': if self.virtual_network.get('description') is not None and self.virtual_network.get('description') != old_response.get('description'): self.to_do = Actions.Update if (self.to_do == Actions.Create) or (self.to_do == Actions.Update): self.log("Need to Create / Update the Virtual Network instance") self.results['changed'] = True if self.check_mode: return self.results response = self.create_update_virtualnetwork() self.log("Creation / Update done") elif self.to_do == Actions.Delete: self.log("Virtual Network instance deleted") self.results['changed'] = True if self.check_mode: return self.results self.delete_virtualnetwork() # This currently doesnt' work as there is a bug in SDK / Service if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller): response = self.get_poller_result(response) else: self.log("Virtual Network instance unchanged") self.results['changed'] = False response = old_response if self.state == 'present': self.results.update({ 'id': response.get('id', None), 'external_provider_resource_id': response.get('external_provider_resource_id', None) }) return self.results def create_update_virtualnetwork(self): ''' Creates or updates Virtual Network with the specified configuration. :return: deserialized Virtual Network instance state dictionary ''' self.log("Creating / Updating the Virtual Network instance {0}".format(self.name)) try: response = self.mgmt_client.virtual_networks.create_or_update(resource_group_name=self.resource_group, lab_name=self.lab_name, name=self.name, virtual_network=self.virtual_network) if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller): response = self.get_poller_result(response) except CloudError as exc: self.log('Error attempting to create the Virtual Network instance.') self.fail("Error creating the Virtual Network instance: {0}".format(str(exc))) return response.as_dict() def delete_virtualnetwork(self): ''' Deletes specified Virtual Network instance in the specified subscription and resource group. :return: True ''' self.log("Deleting the Virtual Network instance {0}".format(self.name)) try: response = self.mgmt_client.virtual_networks.delete(resource_group_name=self.resource_group, lab_name=self.lab_name, name=self.name) except CloudError as e: self.log('Error attempting to delete the Virtual Network instance.') self.fail("Error deleting the Virtual Network instance: {0}".format(str(e))) return True def get_virtualnetwork(self): ''' Gets the properties of the specified Virtual Network. :return: deserialized Virtual Network instance state dictionary ''' self.log("Checking if the Virtual Network instance {0} is present".format(self.name)) found = False try: response = self.mgmt_client.virtual_networks.get(resource_group_name=self.resource_group, lab_name=self.lab_name, name=self.name) found = True self.log("Response : {0}".format(response)) self.log("Virtual Network instance : {0} found".format(response.name)) except CloudError as e: self.log('Did not find the Virtual Network instance.') if found is True: return response.as_dict() return False def main(): """Main execution""" AzureRMDevTestLabVirtualNetwork() if __name__ == '__main__': main()
gpl-3.0
simonwydooghe/ansible
lib/ansible/module_utils/vultr.py
12136
# -*- coding: utf-8 -*- # (c) 2017, René Moser <mail@renemoser.net> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import absolute_import, division, print_function __metaclass__ = type import os import time import random import urllib from ansible.module_utils.six.moves import configparser from ansible.module_utils._text import to_text, to_native from ansible.module_utils.urls import fetch_url VULTR_API_ENDPOINT = "https://api.vultr.com" VULTR_USER_AGENT = 'Ansible Vultr' def vultr_argument_spec(): return dict( api_key=dict(type='str', default=os.environ.get('VULTR_API_KEY'), no_log=True), api_timeout=dict(type='int', default=os.environ.get('VULTR_API_TIMEOUT')), api_retries=dict(type='int', default=os.environ.get('VULTR_API_RETRIES')), api_retry_max_delay=dict(type='int', default=os.environ.get('VULTR_API_RETRY_MAX_DELAY')), api_account=dict(type='str', default=os.environ.get('VULTR_API_ACCOUNT') or 'default'), api_endpoint=dict(type='str', default=os.environ.get('VULTR_API_ENDPOINT')), validate_certs=dict(type='bool', default=True), ) class Vultr: def __init__(self, module, namespace): if module._name.startswith('vr_'): module.deprecate("The Vultr modules were renamed. The prefix of the modules changed from vr_ to vultr_", version='2.11') self.module = module # Namespace use for returns self.namespace = namespace self.result = { 'changed': False, namespace: dict(), 'diff': dict(before=dict(), after=dict()) } # For caching HTTP API responses self.api_cache = dict() try: config = self.read_env_variables() config.update(Vultr.read_ini_config(self.module.params.get('api_account'))) except KeyError: config = {} try: self.api_config = { 'api_key': self.module.params.get('api_key') or config.get('key'), 'api_timeout': self.module.params.get('api_timeout') or int(config.get('timeout') or 60), 'api_retries': self.module.params.get('api_retries') or int(config.get('retries') or 5), 'api_retry_max_delay': self.module.params.get('api_retry_max_delay') or int(config.get('retry_max_delay') or 12), 'api_endpoint': self.module.params.get('api_endpoint') or config.get('endpoint') or VULTR_API_ENDPOINT, } except ValueError as e: self.fail_json(msg="One of the following settings, " "in section '%s' in the ini config file has not an int value: timeout, retries. " "Error was %s" % (self.module.params.get('api_account'), to_native(e))) if not self.api_config.get('api_key'): self.module.fail_json(msg="The API key is not speicied. Please refer to the documentation.") # Common vultr returns self.result['vultr_api'] = { 'api_account': self.module.params.get('api_account'), 'api_timeout': self.api_config['api_timeout'], 'api_retries': self.api_config['api_retries'], 'api_retry_max_delay': self.api_config['api_retry_max_delay'], 'api_endpoint': self.api_config['api_endpoint'], } # Headers to be passed to the API self.headers = { 'API-Key': "%s" % self.api_config['api_key'], 'User-Agent': VULTR_USER_AGENT, 'Accept': 'application/json', } def read_env_variables(self): keys = ['key', 'timeout', 'retries', 'retry_max_delay', 'endpoint'] env_conf = {} for key in keys: if 'VULTR_API_%s' % key.upper() not in os.environ: continue env_conf[key] = os.environ['VULTR_API_%s' % key.upper()] return env_conf @staticmethod def read_ini_config(ini_group): paths = ( os.path.join(os.path.expanduser('~'), '.vultr.ini'), os.path.join(os.getcwd(), 'vultr.ini'), ) if 'VULTR_API_CONFIG' in os.environ: paths += (os.path.expanduser(os.environ['VULTR_API_CONFIG']),) conf = configparser.ConfigParser() conf.read(paths) if not conf._sections.get(ini_group): return dict() return dict(conf.items(ini_group)) def fail_json(self, **kwargs): self.result.update(kwargs) self.module.fail_json(**self.result) def get_yes_or_no(self, key): if self.module.params.get(key) is not None: return 'yes' if self.module.params.get(key) is True else 'no' def switch_enable_disable(self, resource, param_key, resource_key=None): if resource_key is None: resource_key = param_key param = self.module.params.get(param_key) if param is None: return r_value = resource.get(resource_key) if r_value in ['yes', 'no']: if param and r_value != 'yes': return "enable" elif not param and r_value != 'no': return "disable" else: if param and not r_value: return "enable" elif not param and r_value: return "disable" def api_query(self, path="/", method="GET", data=None): url = self.api_config['api_endpoint'] + path if data: data_encoded = dict() data_list = "" for k, v in data.items(): if isinstance(v, list): for s in v: try: data_list += '&%s[]=%s' % (k, urllib.quote(s)) except AttributeError: data_list += '&%s[]=%s' % (k, urllib.parse.quote(s)) elif v is not None: data_encoded[k] = v try: data = urllib.urlencode(data_encoded) + data_list except AttributeError: data = urllib.parse.urlencode(data_encoded) + data_list retry_max_delay = self.api_config['api_retry_max_delay'] randomness = random.randint(0, 1000) / 1000.0 for retry in range(0, self.api_config['api_retries']): response, info = fetch_url( module=self.module, url=url, data=data, method=method, headers=self.headers, timeout=self.api_config['api_timeout'], ) if info.get('status') == 200: break # Vultr has a rate limiting requests per second, try to be polite # Use exponential backoff plus a little bit of randomness delay = 2 ** retry + randomness if delay > retry_max_delay: delay = retry_max_delay + randomness time.sleep(delay) else: self.fail_json(msg="Reached API retries limit %s for URL %s, method %s with data %s. Returned %s, with body: %s %s" % ( self.api_config['api_retries'], url, method, data, info['status'], info['msg'], info.get('body') )) if info.get('status') != 200: self.fail_json(msg="URL %s, method %s with data %s. Returned %s, with body: %s %s" % ( url, method, data, info['status'], info['msg'], info.get('body') )) res = response.read() if not res: return {} try: return self.module.from_json(to_native(res)) or {} except ValueError as e: self.module.fail_json(msg="Could not process response into json: %s" % e) def query_resource_by_key(self, key, value, resource='regions', query_by='list', params=None, use_cache=False, id_key=None, optional=False): if not value: return {} r_list = None if use_cache: r_list = self.api_cache.get(resource) if not r_list: r_list = self.api_query(path="/v1/%s/%s" % (resource, query_by), data=params) if use_cache: self.api_cache.update({ resource: r_list }) if not r_list: return {} elif isinstance(r_list, list): for r_data in r_list: if str(r_data[key]) == str(value): return r_data if id_key is not None and to_text(r_data[id_key]) == to_text(value): return r_data elif isinstance(r_list, dict): for r_id, r_data in r_list.items(): if str(r_data[key]) == str(value): return r_data if id_key is not None and to_text(r_data[id_key]) == to_text(value): return r_data if not optional: if id_key: msg = "Could not find %s with ID or %s: %s" % (resource, key, value) else: msg = "Could not find %s with %s: %s" % (resource, key, value) self.module.fail_json(msg=msg) return {} @staticmethod def normalize_result(resource, schema, remove_missing_keys=True): if remove_missing_keys: fields_to_remove = set(resource.keys()) - set(schema.keys()) for field in fields_to_remove: resource.pop(field) for search_key, config in schema.items(): if search_key in resource: if 'convert_to' in config: if config['convert_to'] == 'int': resource[search_key] = int(resource[search_key]) elif config['convert_to'] == 'float': resource[search_key] = float(resource[search_key]) elif config['convert_to'] == 'bool': resource[search_key] = True if resource[search_key] == 'yes' else False if 'transform' in config: resource[search_key] = config['transform'](resource[search_key]) if 'key' in config: resource[config['key']] = resource[search_key] del resource[search_key] return resource def get_result(self, resource): if resource: if isinstance(resource, list): self.result[self.namespace] = [Vultr.normalize_result(item, self.returns) for item in resource] else: self.result[self.namespace] = Vultr.normalize_result(resource, self.returns) return self.result def get_plan(self, plan=None, key='name', optional=False): value = plan or self.module.params.get('plan') return self.query_resource_by_key( key=key, value=value, resource='plans', use_cache=True, id_key='VPSPLANID', optional=optional, ) def get_firewallgroup(self, firewallgroup=None, key='description'): value = firewallgroup or self.module.params.get('firewallgroup') return self.query_resource_by_key( key=key, value=value, resource='firewall', query_by='group_list', use_cache=True ) def get_application(self, application=None, key='name'): value = application or self.module.params.get('application') return self.query_resource_by_key( key=key, value=value, resource='app', use_cache=True ) def get_region(self, region=None, key='name'): value = region or self.module.params.get('region') return self.query_resource_by_key( key=key, value=value, resource='regions', use_cache=True )
gpl-3.0
jmcPereira/overture
ide/debug/src/main/java/org/overture/ide/debug/ui/launching/AbstractVdmLaunchConfigurationTabGroup.java
2297
/* * #%~ * org.overture.ide.debug * %% * Copyright (C) 2008 - 2014 Overture * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #~% */ package org.overture.ide.debug.ui.launching; import java.util.List; import java.util.Vector; import org.eclipse.debug.ui.CommonTab; import org.eclipse.debug.ui.ILaunchConfigurationDialog; import org.eclipse.debug.ui.ILaunchConfigurationTab; import org.eclipse.debug.ui.sourcelookup.SourceLookupTab; public abstract class AbstractVdmLaunchConfigurationTabGroup extends org.eclipse.debug.ui.AbstractLaunchConfigurationTabGroup { public void createTabs(ILaunchConfigurationDialog dialog, String mode) { List<ILaunchConfigurationTab> tabs = new Vector<ILaunchConfigurationTab>(); tabs.add(getMainTab()); tabs.add(getRuntimeTab()); tabs.add(new VmArgumentsLaunchConfigurationTab()); tabs.add(new VdmDevelopLaunchConfigurationTab()); tabs.addAll(getAdditionalTabs()); tabs.add(new SourceLookupTab()); tabs.add(new CommonTab()); setTabs(tabs.toArray(new ILaunchConfigurationTab[tabs.size()])); } /** * Provides the main launch tab as an implementation of VdmMainLaunchConfigurationTab */ protected abstract AbstractVdmMainLaunchConfigurationTab getMainTab(); /** * Provides the runtime launch tab * * @return must return an instance of VdmRuntimeChecksLaunchConfigurationTab or a subclass */ protected VdmRuntimeChecksLaunchConfigurationTab getRuntimeTab() { return new VdmRuntimeChecksLaunchConfigurationTab(); } /** * Provides additional tab pages to the tab group */ protected List<ILaunchConfigurationTab> getAdditionalTabs() { return new Vector<ILaunchConfigurationTab>(); } }
gpl-3.0
chriskmanx/qmole
QMOLEDEV/boost_1_49_0/libs/wave/test/testwave/testfiles/t_5_021.cpp
2754
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2011 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) The tests included in this file were initially taken from the mcpp V2.5 preprocessor validation suite and were modified to fit into the Boost.Wave unit test requirements. The original files of the mcpp preprocessor are distributed under the license reproduced at the end of this file. =============================================================================*/ // Tests #define directive. // Excerpts from ISO C 6.8.3 "Examples". #define OBJ_LIKE (1-1) #define FTN_LIKE(a) ( a ) // 18.1: Definition of an object-like macro. //R #line 24 "t_5_021.cpp" OBJ_LIKE //R (1-1) //R #line 32 "t_5_021.cpp" //R true #define ZERO_TOKEN #ifndef ZERO_TOKEN "Can't define macro to 0-token." #else true #endif // 18.2: Definition of a function-like macro. //R #line 37 "t_5_021.cpp" FTN_LIKE(3) //R ( 3 ) // 18.3: Spelling in string identical to parameter is not a parameter. //R #line 42 "t_5_021.cpp" #define STR(n1, n2) "n1:n2" STR(1, 2) //R "n1:n2" /*- * Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <kmatsui@t3.rim.or.jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */
gpl-3.0
phenix-factory/Veille-et-protege
plugins/auto/yaml/v1.5.2/inc/yaml.php
3047
<?php if (!defined("_ECRIRE_INC_VERSION")) return; # textwheel fournit yaml_decode() aussi... # include_spip('inc/yaml-mini'); # wrapper de la class sfYAML pour SPIP # # fournit deux fonctions pour YAML, # analogues a json_encode() et json_decode # # Regle de dev: ne pas se rendre dependant de la lib sous-jacente // Si on est en PHP4 if (version_compare(PHP_VERSION, '5.0.0', '<')) define('_LIB_YAML','spyc-php4'); else { // temporaire le temps de tester spyc define('_LIB_YAML','sfyaml'); #define('_LIB_YAML','spyc'); } /* * Encode n'importe quelle structure en yaml * @param $struct * @return string */ function yaml_encode($struct, $opt = array()) { // Si PHP4 if (_LIB_YAML == 'spyc-php4') { require_once _DIR_PLUGIN_YAML.'spyc/spyc-php4.php'; return Spyc::YAMLDump($struct); } // test temporaire if (_LIB_YAML == 'spyc') { require_once _DIR_PLUGIN_YAML.'spyc/spyc.php'; return Spyc::YAMLDump($struct); } require_once _DIR_PLUGIN_YAML.'inc/yaml_sfyaml.php'; return yaml_sfyaml_encode($struct, $opt); } /* * Decode un texte yaml, renvoie la structure * @param string $input * boolean $show_error true: arrete le parsing et retourne erreur en cas d'echec - false: retourne un simple false en cas d'erreur de parsing */ if (!function_exists('yaml_decode')) { function yaml_decode($input,$show_error=true) { // Si PHP4 if (_LIB_YAML == 'spyc-php4') { require_once _DIR_PLUGIN_YAML.'spyc/spyc-php4.php'; return Spyc::YAMLLoad($input); } // test temporaire if (_LIB_YAML == 'spyc') { require_once _DIR_PLUGIN_YAML.'spyc/spyc.php'; return Spyc::YAMLLoad($input); } require_once _DIR_PLUGIN_YAML.'inc/yaml_sfyaml.php'; return yaml_sfyaml_decode($input,$show_error); } } /* * Decode un fichier en utilisant yaml_decode * @param string $fichier */ function yaml_decode_file($fichier){ $yaml = ''; $retour = false; lire_fichier($fichier, $yaml); // Si on recupere bien quelque chose if ($yaml){ $retour = yaml_decode($yaml); } return $retour; } /* * Charge les inclusions de YAML dans un tableau * Les inclusions sont indiquees dans le tableau via la valeur 'inclure:rep/fichier.yaml' ou rep indique le chemin relatif. * On passe donc par find_in_path() pour trouver le fichier * @param array $tableau */ function yaml_charger_inclusions($tableau){ if (is_array($tableau)){ $retour = array(); foreach($tableau as $cle => $valeur) { if (is_string($valeur) && substr($valeur,0,8)=='inclure:' && substr($valeur,-5)=='.yaml') $retour = array_merge($retour,yaml_charger_inclusions(yaml_decode_file(find_in_path(substr($valeur,8))))); elseif (is_array($valeur)) $retour = array_merge($retour,array($cle => yaml_charger_inclusions($valeur))); else $retour = array_merge($retour,array($cle => $valeur)); } return $retour; } elseif (is_string($tableau) && substr($tableau,0,8)=='inclure:' && substr($tableau,-5)=='.yaml') return yaml_charger_inclusions(yaml_decode_file(find_in_path(substr($tableau,8)))); else return $tableau; } ?>
gpl-3.0