text
stringlengths
2
1.04M
meta
dict
title: Try.flatMap - Kotlin utility classes based on Scala --- [Kotlin utility classes based on Scala](../../index.html) / [it.czerwinski.kotlin.util](../index.html) / [Try](index.html) / [flatMap](./flat-map.html) # flatMap `abstract fun <R> flatMap(transform: (`[`T`](index.html#T)`) -> `[`Try`](index.html)`<`[`R`](flat-map.html#R)`>): `[`Try`](index.html)`<`[`R`](flat-map.html#R)`>` Maps value of a [Success](../-success/index.html) to a new [Try](index.html) using [transform](flat-map.html#it.czerwinski.kotlin.util.Try$flatMap(kotlin.Function1((it.czerwinski.kotlin.util.Try.T, it.czerwinski.kotlin.util.Try((it.czerwinski.kotlin.util.Try.flatMap.R)))))/transform) or returns the same [Try](index.html) if this is a [Failure](../-failure/index.html). ### Parameters `transform` - Function transforming value of a [Success](../-success/index.html) to a [Try](index.html). **Return** [Try](index.html) returned by [transform](flat-map.html#it.czerwinski.kotlin.util.Try$flatMap(kotlin.Function1((it.czerwinski.kotlin.util.Try.T, it.czerwinski.kotlin.util.Try((it.czerwinski.kotlin.util.Try.flatMap.R)))))/transform) or this object if this is a [Failure](../-failure/index.html).
{ "content_hash": "cb6ab238611e5db3d6f0f97757dfb345", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 370, "avg_line_length": 66.27777777777777, "alnum_prop": 0.7041072925398156, "repo_name": "sczerwinski/sczerwinski.github.io", "id": "de941544b0cd5581b09c40b22e9bfab79e2f02cb", "size": "1197", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "projects/kotlin-util/1.0/docs/it.czerwinski.kotlin.util/-try/flat-map.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "23044" }, { "name": "JavaScript", "bytes": "641" }, { "name": "Ruby", "bytes": "71" }, { "name": "SCSS", "bytes": "214419" } ], "symlink_target": "" }
require "spec_helper" describe "Assets" do subject(:asset) { page.body } it "serves images, eg the crown header" do visit "/assets/govuk_admin_template/header-crown.png" expect(asset).not_to be_empty end describe "Compiling javascript" do it "compiles library code" do visit "/assets/govuk-admin-template.js" expect(asset).to include("Bootstrap") expect(asset).to include("jQuery") end it "compiles IE shims" do visit "/assets/lte-ie8.js" expect(asset).to include("respond") expect(asset).to include("html5") end end end
{ "content_hash": "e9987d6b2750cf8c0994921d97cf41de", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 57, "avg_line_length": 24.791666666666668, "alnum_prop": 0.6621848739495798, "repo_name": "alphagov/govuk_admin_template", "id": "72a92eaa60c08d1491692fc212fe6e9f8f7868b7", "size": "595", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spec/assets/assets_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "37975" }, { "name": "JavaScript", "bytes": "39500" }, { "name": "Ruby", "bytes": "25661" }, { "name": "SCSS", "bytes": "31931" } ], "symlink_target": "" }
using namespace std; #include <map> #include <vector> #include <string> #include <algorithm> typedef struct tagStudentInfo { int nID; string strName; bool operator < (tagStudentInfo const& _A) const { //这个函数指定排序策略,按nID排序,如果nID相等的话,按strName排序 if(nID < _A.nID) return true; if(nID == _A.nID) return strName.compare(_A.strName) < 0; return false; } }StudentInfo, *PStudentInfo; //学生信息 int main() { vector<StudentInfo> vc; StudentInfo studentInfo; studentInfo.nID = 1; studentInfo.strName = "student_one"; vc.push_back(studentInfo); StudentInfo studentInfo1; studentInfo1.nID = 2; studentInfo1.strName = "student_two"; vc.push_back(studentInfo1); StudentInfo studentInfo2; studentInfo2.nID = 2; studentInfo2.strName = "student_two"; vc.push_back(studentInfo2); //排序 sort(vc.begin(),vc.end()); //输出 vector<StudentInfo>::iterator iter; for (iter=vc.begin(); iter!=vc.end(); iter++) cout<<iter->nID<<" "<<iter->strName <<endl; return 0; }
{ "content_hash": "743bd60077816d12d357cc629cbe3ba5", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 71, "avg_line_length": 27.975, "alnum_prop": 0.610366398570152, "repo_name": "echoorchid/hua-wei-shang-ji-ti-hui-zong", "id": "1a3439ae0d8197407b5be4e03b858bfe73f13cb0", "size": "1206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "结构体排序.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "2412" } ], "symlink_target": "" }
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/segmentation_platform/internal/service_proxy_impl.h" #include <inttypes.h> #include <memory> #include <sstream> #include "base/observer_list.h" #include "base/strings/stringprintf.h" #include "base/time/default_clock.h" #include "base/time/time.h" #include "components/segmentation_platform/internal/database/segment_info_database.h" #include "components/segmentation_platform/internal/database/signal_storage_config.h" #include "components/segmentation_platform/internal/database/storage_service.h" #include "components/segmentation_platform/internal/execution/default_model_manager.h" #include "components/segmentation_platform/internal/metadata/metadata_utils.h" #include "components/segmentation_platform/internal/scheduler/execution_service.h" #include "components/segmentation_platform/internal/selection/segment_result_provider.h" #include "components/segmentation_platform/internal/selection/segment_selector_impl.h" #include "components/segmentation_platform/public/config.h" namespace segmentation_platform { namespace { std::string SegmentMetadataToString(const proto::SegmentInfo& segment_info) { if (!segment_info.has_model_metadata()) return std::string(); return "model_metadata: { " + metadata_utils::SegmetationModelMetadataToString( segment_info.model_metadata()) + " }"; } std::string PredictionResultToString(const proto::SegmentInfo& segment_info) { if (!segment_info.has_prediction_result()) return std::string(); const auto prediction_result = segment_info.prediction_result(); base::Time time; if (prediction_result.has_timestamp_us()) { time = base::Time::FromDeltaSinceWindowsEpoch( base::Microseconds(prediction_result.timestamp_us())); } std::ostringstream time_string; time_string << time; return base::StringPrintf( "result: %f, time: %s", prediction_result.has_result() ? prediction_result.result() : 0, time_string.str().c_str()); } base::flat_set<proto::SegmentId> GetAllSegemntIds( const std::vector<std::unique_ptr<Config>>& configs) { base::flat_set<proto::SegmentId> all_segment_ids; for (const auto& config : configs) { for (const auto& segment : config->segments) { all_segment_ids.insert(segment.first); } } return all_segment_ids; } } // namespace ServiceProxyImpl::ServiceProxyImpl( SegmentInfoDatabase* segment_db, DefaultModelManager* default_manager, SignalStorageConfig* signal_storage_config, std::vector<std::unique_ptr<Config>>* configs, const PlatformOptions& platform_options, base::flat_map<std::string, std::unique_ptr<SegmentSelectorImpl>>* segment_selectors) : force_refresh_results_(platform_options.force_refresh_results), segment_db_(segment_db), default_manager_(default_manager), signal_storage_config_(signal_storage_config), configs_(configs), segment_selectors_(segment_selectors) {} ServiceProxyImpl::~ServiceProxyImpl() = default; void ServiceProxyImpl::AddObserver(ServiceProxy::Observer* observer) { observers_.AddObserver(observer); } void ServiceProxyImpl::RemoveObserver(ServiceProxy::Observer* observer) { observers_.RemoveObserver(observer); } void ServiceProxyImpl::OnServiceStatusChanged(bool is_initialized, int status_flag) { bool changed = (is_service_initialized_ != is_initialized) || (service_status_flag_ != status_flag); is_service_initialized_ = is_initialized; service_status_flag_ = status_flag; UpdateObservers(changed); } void ServiceProxyImpl::UpdateObservers(bool update_service_status) { if (observers_.empty()) return; if (update_service_status) { for (auto& obs : observers_) obs.OnServiceStatusChanged(is_service_initialized_, service_status_flag_); } if (default_manager_ && (static_cast<int>(ServiceStatus::kSegmentationInfoDbInitialized) & service_status_flag_)) { default_manager_->GetAllSegmentInfoFromBothModels( GetAllSegemntIds(*configs_), segment_db_, base::BindOnce(&ServiceProxyImpl::OnGetAllSegmentationInfo, weak_ptr_factory_.GetWeakPtr())); } } void ServiceProxyImpl::SetExecutionService( ExecutionService* model_execution_scheduler) { execution_service_ = model_execution_scheduler; segment_result_provider_ = SegmentResultProvider::Create( segment_db_, signal_storage_config_, default_manager_, execution_service_, base::DefaultClock::GetInstance(), /*force_refresh_results=*/true); } void ServiceProxyImpl::GetServiceStatus() { UpdateObservers(true /* update_service_status */); } void ServiceProxyImpl::ExecuteModel(SegmentId segment_id) { if (!execution_service_ || segment_id == SegmentId::OPTIMIZATION_TARGET_UNKNOWN) { return; } auto request = std::make_unique<SegmentResultProvider::GetResultOptions>(); request->save_results_to_db = true; request->segment_id = segment_id; request->ignore_db_scores = true; segment_result_provider_->GetSegmentResult(std::move(request)); } void ServiceProxyImpl::OverwriteResult(SegmentId segment_id, float result) { if (!execution_service_) return; if (segment_id != SegmentId::OPTIMIZATION_TARGET_UNKNOWN) { execution_service_->OverwriteModelExecutionResult( segment_id, std::make_pair(result, ModelExecutionStatus::kSuccess)); } } void ServiceProxyImpl::SetSelectedSegment(const std::string& segmentation_key, SegmentId segment_id) { if (!segment_selectors_ || segment_selectors_->find(segmentation_key) == segment_selectors_->end()) { return; } if (segment_id != SegmentId::OPTIMIZATION_TARGET_UNKNOWN) { auto& selector = segment_selectors_->at(segmentation_key); selector->UpdateSelectedSegment(segment_id, 0); } } void ServiceProxyImpl::OnGetAllSegmentationInfo( DefaultModelManager::SegmentInfoList segment_info) { if (!configs_) return; // Convert the |segment_info| vector to a map for quick lookup. base::flat_map<SegmentId, proto::SegmentInfo> segment_ids; for (const auto& info : segment_info) { const SegmentId segment_id = info->segment_info.segment_id(); switch (info->segment_source) { case DefaultModelManager::SegmentSource::DATABASE: // If database info is available, then overwrite the existing entry. segment_ids[segment_id] = std::move(info->segment_info); break; case DefaultModelManager::SegmentSource::DEFAULT_MODEL: // If database info is not available then use default model info. if (segment_ids.count(segment_id) == 0) { segment_ids[segment_id] = std::move(info->segment_info); } break; } } std::vector<ServiceProxy::ClientInfo> result; for (const auto& config : *configs_) { SegmentId selected = SegmentId::OPTIMIZATION_TARGET_UNKNOWN; if (segment_selectors_ && segment_selectors_->find(config->segmentation_key) != segment_selectors_->end()) { absl::optional<proto::SegmentId> target = segment_selectors_->at(config->segmentation_key) ->GetCachedSegmentResult() .segment; if (target.has_value()) { selected = *target; } } result.emplace_back(config->segmentation_key, selected); for (const auto& segment_id : config->segments) { if (!segment_ids.contains(segment_id.first)) continue; const auto& info = segment_ids[segment_id.first]; bool can_execute_segment = force_refresh_results_ || (signal_storage_config_ && signal_storage_config_->MeetsSignalCollectionRequirement( info.model_metadata())); result.back().segment_status.emplace_back( segment_id.first, SegmentMetadataToString(info), PredictionResultToString(info), can_execute_segment); } } for (auto& obs : observers_) obs.OnClientInfoAvailable(result); } void ServiceProxyImpl::OnModelExecutionCompleted(SegmentId segment_id) { // Update the observers with the new execution results. UpdateObservers(false); } } // namespace segmentation_platform
{ "content_hash": "961a6c5c15c98f42d5b0ea307e745599", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 88, "avg_line_length": 36.60698689956332, "alnum_prop": 0.700942383394966, "repo_name": "nwjs/chromium.src", "id": "3d12b87fa0cbf5d59eb694b91e9b99cce9af7d44", "size": "8383", "binary": false, "copies": "1", "ref": "refs/heads/nw70", "path": "components/segmentation_platform/internal/service_proxy_impl.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
GTFCreator::Application.routes.draw do devise_for :users mount RailsAdmin::Engine => '/admin', :as => 'rails_admin' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
{ "content_hash": "c6fe4df2bcff720c400fdaaff8bdb4ba", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 84, "avg_line_length": 29.103448275862068, "alnum_prop": 0.6463270142180095, "repo_name": "teriiehina/GTFSCreator", "id": "6be1373f7c16ef58ca93c083c5ec12e64edd2d96", "size": "1688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/routes.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "546" }, { "name": "JavaScript", "bytes": "664" }, { "name": "Ruby", "bytes": "43881" } ], "symlink_target": "" }
 /** * @ignore * File overview: Clipboard support. */ // // COPY & PASTE EXECUTION FLOWS: // -- CTRL+C // * if ( isCustomCopyCutSupported ) // * dataTransfer.setData( 'text/html', getSelectedHtml ) // * else // * browser's default behavior // -- CTRL+X // * listen onKey (onkeydown) // * fire 'saveSnapshot' on editor // * if ( isCustomCopyCutSupported ) // * dataTransfer.setData( 'text/html', getSelectedHtml ) // * extractSelectedHtml // remove selected contents // * else // * browser's default behavior // * deferred second 'saveSnapshot' event // -- CTRL+V // * listen onKey (onkeydown) // * simulate 'beforepaste' for non-IEs on editable // * listen 'onpaste' on editable ('onbeforepaste' for IE) // * fire 'beforePaste' on editor // * if ( !canceled && ( htmlInDataTransfer || !external paste) && dataTransfer is not empty ) getClipboardDataByPastebin // * fire 'paste' on editor // * !canceled && fire 'afterPaste' on editor // -- Copy command // * tryToCutCopy // * execCommand // * !success && notification // -- Cut command // * fixCut // * tryToCutCopy // * execCommand // * !success && notification // -- Paste command // * fire 'paste' on editable ('beforepaste' for IE) // * !canceled && execCommand 'paste' // -- Paste from native context menu & menubar // (Fx & Webkits are handled in 'paste' default listener. // Opera cannot be handled at all because it doesn't fire any events // Special treatment is needed for IE, for which is this part of doc) // * listen 'onpaste' // * cancel native event // * fire 'beforePaste' on editor // * if ( !canceled && ( htmlInDataTransfer || !external paste) && dataTransfer is not empty ) getClipboardDataByPastebin // * execIECommand( 'paste' ) -> this fires another 'paste' event, so cancel it // * fire 'paste' on editor // * !canceled && fire 'afterPaste' on editor // // // PASTE EVENT - PREPROCESSING: // -- Possible dataValue types: auto, text, html. // -- Possible dataValue contents: // * text (possible \n\r) // * htmlified text (text + br,div,p - no presentational markup & attrs - depends on browser) // * html // -- Possible flags: // * htmlified - if true then content is a HTML even if no markup inside. This flag is set // for content from editable pastebins, because they 'htmlify' pasted content. // // -- Type: auto: // * content: htmlified text -> filter, unify text markup (brs, ps, divs), set type: text // * content: html -> filter, set type: html // -- Type: text: // * content: htmlified text -> filter, unify text markup // * content: html -> filter, strip presentational markup, unify text markup // -- Type: html: // * content: htmlified text -> filter, unify text markup // * content: html -> filter // // -- Phases: // * if dataValue is empty copy data from dataTransfer to dataValue (priority 1) // * filtering (priorities 3-5) - e.g. pastefromword filters // * content type sniffing (priority 6) // * markup transformations for text (priority 6) // // DRAG & DROP EXECUTION FLOWS: // -- Drag // * save to the global object: // * drag timestamp (with 'cke-' prefix), // * selected html, // * drag range, // * editor instance. // * put drag timestamp into event.dataTransfer.text // -- Drop // * if events text == saved timestamp && editor == saved editor // internal drag & drop occurred // * getRangeAtDropPosition // * create bookmarks for drag and drop ranges starting from the end of the document // * dragRange.deleteContents() // * fire 'paste' with saved html and drop range // * if events text == saved timestamp && editor != saved editor // cross editor drag & drop occurred // * getRangeAtDropPosition // * fire 'paste' with saved html // * dragRange.deleteContents() // * FF: refreshCursor on afterPaste // * if events text != saved timestamp // drop form external source occurred // * getRangeAtDropPosition // * if event contains html data then fire 'paste' with html // * else if event contains text data then fire 'paste' with encoded text // * FF: refreshCursor on afterPaste 'use strict'; ( function() { // Register the plugin. CKEDITOR.plugins.add( 'clipboard', { requires: 'notification,toolbar', // jscs:disable maximumLineLength lang: 'af,ar,az,bg,bn,bs,ca,cs,cy,da,de,de-ch,el,en,en-au,en-ca,en-gb,eo,es,es-mx,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,oc,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE% // jscs:enable maximumLineLength icons: 'copy,copy-rtl,cut,cut-rtl,paste,paste-rtl', // %REMOVE_LINE_CORE% hidpi: true, // %REMOVE_LINE_CORE% init: function( editor ) { var filterType, filtersFactory = filtersFactoryFactory(); if ( editor.config.forcePasteAsPlainText ) { filterType = 'plain-text'; } else if ( editor.config.pasteFilter ) { filterType = editor.config.pasteFilter; } // On Webkit the pasteFilter defaults 'semantic-content' because pasted data is so terrible // that it must be always filtered. else if ( CKEDITOR.env.webkit && !( 'pasteFilter' in editor.config ) ) { filterType = 'semantic-content'; } editor.pasteFilter = filtersFactory.get( filterType ); initPasteClipboard( editor ); initDragDrop( editor ); // Convert image file (if present) to base64 string for Firefox. Do it as the first // step as the conversion is asynchronous and should hold all further paste processing. if ( CKEDITOR.env.gecko ) { var supportedImageTypes = [ 'image/png', 'image/jpeg', 'image/gif' ], latestId; editor.on( 'paste', function( evt ) { var dataObj = evt.data, data = dataObj.dataValue, dataTransfer = dataObj.dataTransfer; // If data empty check for image content inside data transfer. http://dev.ckeditor.com/ticket/16705 if ( !data && dataObj.method == 'paste' && dataTransfer && dataTransfer.getFilesCount() == 1 && latestId != dataTransfer.id ) { var file = dataTransfer.getFile( 0 ); if ( CKEDITOR.tools.indexOf( supportedImageTypes, file.type ) != -1 ) { var fileReader = new FileReader(); // Convert image file to img tag with base64 image. fileReader.addEventListener( 'load', function() { evt.data.dataValue = '<img src="' + fileReader.result + '" />'; editor.fire( 'paste', evt.data ); }, false ); // Proceed with normal flow if reading file was aborted. fileReader.addEventListener( 'abort', function() { editor.fire( 'paste', evt.data ); }, false ); // Proceed with normal flow if reading file failed. fileReader.addEventListener( 'error', function() { editor.fire( 'paste', evt.data ); }, false ); fileReader.readAsDataURL( file ); latestId = dataObj.dataTransfer.id; evt.stop(); } } }, null, null, 1 ); } editor.on( 'paste', function( evt ) { // Init `dataTransfer` if `paste` event was fired without it, so it will be always available. if ( !evt.data.dataTransfer ) { evt.data.dataTransfer = new CKEDITOR.plugins.clipboard.dataTransfer(); } // If dataValue is already set (manually or by paste bin), so do not override it. if ( evt.data.dataValue ) { return; } var dataTransfer = evt.data.dataTransfer, // IE support only text data and throws exception if we try to get html data. // This html data object may also be empty if we drag content of the textarea. value = dataTransfer.getData( 'text/html' ); if ( value ) { evt.data.dataValue = value; evt.data.type = 'html'; } else { // Try to get text data otherwise. value = dataTransfer.getData( 'text/plain' ); if ( value ) { evt.data.dataValue = editor.editable().transformPlainTextToHtml( value ); evt.data.type = 'text'; } } }, null, null, 1 ); editor.on( 'paste', function( evt ) { var data = evt.data.dataValue, blockElements = CKEDITOR.dtd.$block; // Filter webkit garbage. if ( data.indexOf( 'Apple-' ) > -1 ) { // Replace special webkit's &nbsp; with simple space, because webkit // produces them even for normal spaces. data = data.replace( /<span class="Apple-converted-space">&nbsp;<\/span>/gi, ' ' ); // Strip <span> around white-spaces when not in forced 'html' content type. // This spans are created only when pasting plain text into Webkit, // but for safety reasons remove them always. if ( evt.data.type != 'html' ) { data = data.replace( /<span class="Apple-tab-span"[^>]*>([^<]*)<\/span>/gi, function( all, spaces ) { // Replace tabs with 4 spaces like Fx does. return spaces.replace( /\t/g, '&nbsp;&nbsp; &nbsp;' ); } ); } // This br is produced only when copying & pasting HTML content. if ( data.indexOf( '<br class="Apple-interchange-newline">' ) > -1 ) { evt.data.startsWithEOL = 1; evt.data.preSniffing = 'html'; // Mark as not text. data = data.replace( /<br class="Apple-interchange-newline">/, '' ); } // Remove all other classes. data = data.replace( /(<[^>]+) class="Apple-[^"]*"/gi, '$1' ); } // Strip editable that was copied from inside. (http://dev.ckeditor.com/ticket/9534) if ( data.match( /^<[^<]+cke_(editable|contents)/i ) ) { var tmp, editable_wrapper, wrapper = new CKEDITOR.dom.element( 'div' ); wrapper.setHtml( data ); // Verify for sure and check for nested editor UI parts. (http://dev.ckeditor.com/ticket/9675) while ( wrapper.getChildCount() == 1 && ( tmp = wrapper.getFirst() ) && tmp.type == CKEDITOR.NODE_ELEMENT && // Make sure first-child is element. ( tmp.hasClass( 'cke_editable' ) || tmp.hasClass( 'cke_contents' ) ) ) { wrapper = editable_wrapper = tmp; } // If editable wrapper was found strip it and bogus <br> (added on FF). if ( editable_wrapper ) data = editable_wrapper.getHtml().replace( /<br>$/i, '' ); } if ( CKEDITOR.env.ie ) { // &nbsp; <p> -> <p> (br.cke-pasted-remove will be removed later) data = data.replace( /^&nbsp;(?: |\r\n)?<(\w+)/g, function( match, elementName ) { if ( elementName.toLowerCase() in blockElements ) { evt.data.preSniffing = 'html'; // Mark as not a text. return '<' + elementName; } return match; } ); } else if ( CKEDITOR.env.webkit ) { // </p><div><br></div> -> </p><br> // We don't mark br, because this situation can happen for htmlified text too. data = data.replace( /<\/(\w+)><div><br><\/div>$/, function( match, elementName ) { if ( elementName in blockElements ) { evt.data.endsWithEOL = 1; return '</' + elementName + '>'; } return match; } ); } else if ( CKEDITOR.env.gecko ) { // Firefox adds bogus <br> when user pasted text followed by space(s). data = data.replace( /(\s)<br>$/, '$1' ); } evt.data.dataValue = data; }, null, null, 3 ); editor.on( 'paste', function( evt ) { var dataObj = evt.data, type = editor._.nextPasteType || dataObj.type, data = dataObj.dataValue, trueType, // Default is 'html'. defaultType = editor.config.clipboard_defaultContentType || 'html', transferType = dataObj.dataTransfer.getTransferType( editor ); // If forced type is 'html' we don't need to know true data type. if ( type == 'html' || dataObj.preSniffing == 'html' ) { trueType = 'html'; } else { trueType = recogniseContentType( data ); } delete editor._.nextPasteType; // Unify text markup. if ( trueType == 'htmlifiedtext' ) { data = htmlifiedTextHtmlification( editor.config, data ); } // Strip presentational markup & unify text markup. // Forced plain text. // Note: we do not check dontFilter option in this case, because forcePAPT was implemented // before pasteFilter and pasteFilter is automatically used on Webkit&Blink since 4.5, so // forcePAPT should have priority as it had before 4.5. if ( type == 'text' && trueType == 'html' ) { data = filterContent( editor, data, filtersFactory.get( 'plain-text' ) ); } // External paste and pasteFilter exists and filtering isn't disabled. else if ( transferType == CKEDITOR.DATA_TRANSFER_EXTERNAL && editor.pasteFilter && !dataObj.dontFilter ) { data = filterContent( editor, data, editor.pasteFilter ); } if ( dataObj.startsWithEOL ) { data = '<br data-cke-eol="1">' + data; } if ( dataObj.endsWithEOL ) { data += '<br data-cke-eol="1">'; } if ( type == 'auto' ) { type = ( trueType == 'html' || defaultType == 'html' ) ? 'html' : 'text'; } dataObj.type = type; dataObj.dataValue = data; delete dataObj.preSniffing; delete dataObj.startsWithEOL; delete dataObj.endsWithEOL; }, null, null, 6 ); // Inserts processed data into the editor at the end of the // events chain. editor.on( 'paste', function( evt ) { var data = evt.data; if ( data.dataValue ) { editor.insertHtml( data.dataValue, data.type, data.range ); // Defer 'afterPaste' so all other listeners for 'paste' will be fired first. // Fire afterPaste only if paste inserted some HTML. setTimeout( function() { editor.fire( 'afterPaste' ); }, 0 ); } }, null, null, 1000 ); } } ); function firePasteEvents( editor, data, withBeforePaste ) { if ( !data.type ) { data.type = 'auto'; } if ( withBeforePaste ) { // Fire 'beforePaste' event so clipboard flavor get customized // by other plugins. if ( editor.fire( 'beforePaste', data ) === false ) return false; // Event canceled } // Do not fire paste if there is no data (dataValue and dataTranfser are empty). // This check should be done after firing 'beforePaste' because for native paste // 'beforePaste' is by default fired even for empty clipboard. if ( !data.dataValue && data.dataTransfer.isEmpty() ) { return false; } if ( !data.dataValue ) { data.dataValue = ''; } // Because of FF bug we need to use this hack, otherwise cursor is hidden // or it is not possible to move it (http://dev.ckeditor.com/ticket/12420). // Also, check that editor.toolbox exists, because the toolbar plugin might not be loaded (http://dev.ckeditor.com/ticket/13305). if ( CKEDITOR.env.gecko && data.method == 'drop' && editor.toolbox ) { editor.once( 'afterPaste', function() { editor.toolbox.focus(); } ); } return editor.fire( 'paste', data ); } function initPasteClipboard( editor ) { var clipboard = CKEDITOR.plugins.clipboard, preventBeforePasteEvent = 0, preventPasteEvent = 0, inReadOnly = 0; addListeners(); addButtonsCommands(); /** * Gets clipboard data by directly accessing the clipboard (IE only). * * editor.getClipboardData( function( data ) { * if ( data ) * alert( data.type + ' ' + data.dataValue ); * } ); * * @member CKEDITOR.editor * @param {Function/Object} callbackOrOptions For function, see the `callback` parameter documentation. The object was used before 4.7.0 with the `title` property, to set the paste dialog's title. * @param {Function} callback A function that will be executed with the `data` property of the * {@link CKEDITOR.editor#event-paste paste event} or `null` if none of the capturing methods succeeded. * Since 4.7.0 the `callback` should be provided as a first argument, just like in the example above. This parameter will be removed in * an upcoming major release. */ editor.getClipboardData = function( callbackOrOptions, callback ) { // Options are optional - args shift. if ( !callback ) { callback = callbackOrOptions; callbackOrOptions = null; } // Listen with maximum priority to handle content before everyone else. // This callback will handle paste event that will be fired if direct // access to the clipboard succeed in IE. editor.on( 'paste', onPaste, null, null, 0 ); // If command didn't succeed (only IE allows to access clipboard and only if // user agrees) invoke callback with null, meaning that paste is not blocked. if ( getClipboardDataDirectly() === false ) { // Direct access to the clipboard wasn't successful so remove listener. editor.removeListener( 'paste', onPaste ); callback( null ); } function onPaste( evt ) { evt.removeListener(); evt.cancel(); callback( evt.data ); } }; function addButtonsCommands() { addButtonCommand( 'Cut', 'cut', createCutCopyCmd( 'cut' ), 10, 1 ); addButtonCommand( 'Copy', 'copy', createCutCopyCmd( 'copy' ), 20, 4 ); addButtonCommand( 'Paste', 'paste', createPasteCmd(), 30, 8 ); function addButtonCommand( buttonName, commandName, command, toolbarOrder, ctxMenuOrder ) { var lang = editor.lang.clipboard[ commandName ]; editor.addCommand( commandName, command ); editor.ui.addButton && editor.ui.addButton( buttonName, { label: lang, command: commandName, toolbar: 'clipboard,' + toolbarOrder } ); // If the "menu" plugin is loaded, register the menu item. if ( editor.addMenuItems ) { editor.addMenuItem( commandName, { label: lang, command: commandName, group: 'clipboard', order: ctxMenuOrder } ); } } } function addListeners() { editor.on( 'key', onKey ); editor.on( 'contentDom', addPasteListenersToEditable ); // For improved performance, we're checking the readOnly state on selectionChange instead of hooking a key event for that. editor.on( 'selectionChange', function( evt ) { inReadOnly = evt.data.selection.getRanges()[ 0 ].checkReadOnly(); setToolbarStates(); } ); // If the "contextmenu" plugin is loaded, register the listeners. if ( editor.contextMenu ) { editor.contextMenu.addListener( function( element, selection ) { inReadOnly = selection.getRanges()[ 0 ].checkReadOnly(); return { cut: stateFromNamedCommand( 'cut' ), copy: stateFromNamedCommand( 'copy' ), paste: stateFromNamedCommand( 'paste' ) }; } ); } } // Add events listeners to editable. function addPasteListenersToEditable() { var editable = editor.editable(); if ( CKEDITOR.plugins.clipboard.isCustomCopyCutSupported ) { var initOnCopyCut = function( evt ) { // If user tries to cut in read-only editor, we must prevent default action. (http://dev.ckeditor.com/ticket/13872) if ( !editor.readOnly || evt.name != 'cut' ) { clipboard.initPasteDataTransfer( evt, editor ); } evt.data.preventDefault(); }; editable.on( 'copy', initOnCopyCut ); editable.on( 'cut', initOnCopyCut ); // Delete content with the low priority so one can overwrite cut data. editable.on( 'cut', function() { // If user tries to cut in read-only editor, we must prevent default action. (http://dev.ckeditor.com/ticket/13872) if ( !editor.readOnly ) { editor.extractSelectedHtml(); } }, null, null, 999 ); } // We'll be catching all pasted content in one line, regardless of whether // it's introduced by a document command execution (e.g. toolbar buttons) or // user paste behaviors (e.g. CTRL+V). editable.on( clipboard.mainPasteEvent, function( evt ) { if ( clipboard.mainPasteEvent == 'beforepaste' && preventBeforePasteEvent ) { return; } // If you've just asked yourself why preventPasteEventNow() is not here, but // in listener for CTRL+V and exec method of 'paste' command // you've asked the same question we did. // // THE ANSWER: // // First thing to notice - this answer makes sense only for IE, // because other browsers don't listen for 'paste' event. // // What would happen if we move preventPasteEventNow() here? // For: // * CTRL+V - IE fires 'beforepaste', so we prevent 'paste' and pasteDataFromClipboard(). OK. // * editor.execCommand( 'paste' ) - we fire 'beforepaste', so we prevent // 'paste' and pasteDataFromClipboard() and doc.execCommand( 'Paste' ). OK. // * native context menu - IE fires 'beforepaste', so we prevent 'paste', but unfortunately // on IE we fail with pasteDataFromClipboard() here, because of... we don't know why, but // we just fail, so... we paste nothing. FAIL. // * native menu bar - the same as for native context menu. // // But don't you know any way to distinguish first two cases from last two? // Only one - special flag set in CTRL+V handler and exec method of 'paste' // command. And that's what we did using preventPasteEventNow(). pasteDataFromClipboard( evt ); } ); // It's not possible to clearly handle all four paste methods (ctrl+v, native menu bar // native context menu, editor's command) in one 'paste/beforepaste' event in IE. // // For ctrl+v & editor's command it's easy to handle pasting in 'beforepaste' listener, // so we do this. For another two methods it's better to use 'paste' event. // // 'paste' is always being fired after 'beforepaste' (except of weird one on opening native // context menu), so for two methods handled in 'beforepaste' we're canceling 'paste' // using preventPasteEvent state. // // 'paste' event in IE is being fired before getClipboardDataByPastebin executes its callback. // // QUESTION: Why didn't you handle all 4 paste methods in handler for 'paste'? // Wouldn't this just be simpler? // ANSWER: Then we would have to evt.data.preventDefault() only for native // context menu and menu bar pastes. The same with execIECommand(). // That would force us to mark CTRL+V and editor's paste command with // special flag, other than preventPasteEvent. But we still would have to // have preventPasteEvent for the second event fired by execIECommand. // Code would be longer and not cleaner. if ( clipboard.mainPasteEvent == 'beforepaste' ) { editable.on( 'paste', function( evt ) { if ( preventPasteEvent ) { return; } // Cancel next 'paste' event fired by execIECommand( 'paste' ) // at the end of this callback. preventPasteEventNow(); // Prevent native paste. evt.data.preventDefault(); pasteDataFromClipboard( evt ); // Force IE to paste content into pastebin so pasteDataFromClipboard will work. execIECommand( 'paste' ); } ); // If mainPasteEvent is 'beforePaste' (IE before Edge), // dismiss the (wrong) 'beforepaste' event fired on context/toolbar menu open. (http://dev.ckeditor.com/ticket/7953) editable.on( 'contextmenu', preventBeforePasteEventNow, null, null, 0 ); editable.on( 'beforepaste', function( evt ) { // Do not prevent event on CTRL+V and SHIFT+INS because it blocks paste (http://dev.ckeditor.com/ticket/11970). if ( evt.data && !evt.data.$.ctrlKey && !evt.data.$.shiftKey ) preventBeforePasteEventNow(); }, null, null, 0 ); } editable.on( 'beforecut', function() { !preventBeforePasteEvent && fixCut( editor ); } ); var mouseupTimeout; // Use editor.document instead of editable in non-IEs for observing mouseup // since editable won't fire the event if selection process started within // iframe and ended out of the editor (http://dev.ckeditor.com/ticket/9851). editable.attachListener( CKEDITOR.env.ie ? editable : editor.document.getDocumentElement(), 'mouseup', function() { mouseupTimeout = setTimeout( function() { setToolbarStates(); }, 0 ); } ); // Make sure that deferred mouseup callback isn't executed after editor instance // had been destroyed. This may happen when editor.destroy() is called in parallel // with mouseup event (i.e. a button with onclick callback) (http://dev.ckeditor.com/ticket/10219). editor.on( 'destroy', function() { clearTimeout( mouseupTimeout ); } ); editable.on( 'keyup', setToolbarStates ); } // Create object representing Cut or Copy commands. function createCutCopyCmd( type ) { return { type: type, canUndo: type == 'cut', // We can't undo copy to clipboard. startDisabled: true, fakeKeystroke: type == 'cut' ? CKEDITOR.CTRL + 88 /*X*/ : CKEDITOR.CTRL + 67 /*C*/, exec: function() { // Attempts to execute the Cut and Copy operations. function tryToCutCopy( type ) { if ( CKEDITOR.env.ie ) return execIECommand( type ); // non-IEs part try { // Other browsers throw an error if the command is disabled. return editor.document.$.execCommand( type, false, null ); } catch ( e ) { return false; } } this.type == 'cut' && fixCut(); var success = tryToCutCopy( this.type ); if ( !success ) { // Show cutError or copyError. editor.showNotification( editor.lang.clipboard[ this.type + 'Error' ] ); // jshint ignore:line } return success; } }; } function createPasteCmd() { return { // Snapshots are done manually by editable.insertXXX methods. canUndo: false, async: true, fakeKeystroke: CKEDITOR.CTRL + 86 /*V*/, /** * The default implementation of the paste command. * * @private * @param {CKEDITOR.editor} editor An instance of the editor where the command is being executed. * @param {Object/String} data If `data` is a string, then it is considered content that is being pasted. * Otherwise it is treated as an object with options. * @param {Boolean/String} [data.notification=true] Content for a notification shown after an unsuccessful * paste attempt. If `false`, the notification will not be displayed. This parameter was added in 4.7.0. * @param {String} [data.type='html'] The type of pasted content. There are two allowed values: * * 'html' * * 'text' * @param {String/Object} data.dataValue Content being pasted. If this parameter is an object, it * is supposed to be a `data` property of the {@link CKEDITOR.editor#paste} event. * @param {CKEDITOR.plugins.clipboard.dataTransfer} data.dataTransfer Data transfer instance connected * with the current paste action. * @member CKEDITOR.editor.commands.paste */ exec: function( editor, data ) { data = typeof data !== 'undefined' && data !== null ? data : {}; var cmd = this, notification = typeof data.notification !== 'undefined' ? data.notification : true, forcedType = data.type, keystroke = CKEDITOR.tools.keystrokeToString( editor.lang.common.keyboard, editor.getCommandKeystroke( this ) ), msg = typeof notification === 'string' ? notification : editor.lang.clipboard.pasteNotification .replace( /%1/, '<kbd aria-label="' + keystroke.aria + '">' + keystroke.display + '</kbd>' ), pastedContent = typeof data === 'string' ? data : data.dataValue; function callback( data, withBeforePaste ) { withBeforePaste = typeof withBeforePaste !== 'undefined' ? withBeforePaste : true; if ( data ) { data.method = 'paste'; if ( !data.dataTransfer ) { data.dataTransfer = clipboard.initPasteDataTransfer(); } firePasteEvents( editor, data, withBeforePaste ); } else if ( notification ) { editor.showNotification( msg, 'info', editor.config.clipboard_notificationDuration ); } editor.fire( 'afterCommandExec', { name: 'paste', command: cmd, returnValue: !!data } ); } // Force type for the next paste. if ( forcedType ) { editor._.nextPasteType = forcedType; } else { delete editor._.nextPasteType; } if ( typeof pastedContent === 'string' ) { callback( { dataValue: pastedContent } ); } else { editor.getClipboardData( callback ); } } }; } function preventPasteEventNow() { preventPasteEvent = 1; // For safety reason we should wait longer than 0/1ms. // We don't know how long execution of quite complex getClipboardData will take // and in for example 'paste' listener execCommand() (which fires 'paste') is called // after getClipboardData finishes. // Luckily, it's impossible to immediately fire another 'paste' event we want to handle, // because we only handle there native context menu and menu bar. setTimeout( function() { preventPasteEvent = 0; }, 100 ); } function preventBeforePasteEventNow() { preventBeforePasteEvent = 1; setTimeout( function() { preventBeforePasteEvent = 0; }, 10 ); } // Tries to execute any of the paste, cut or copy commands in IE. Returns a // boolean indicating that the operation succeeded. // @param {String} command *LOWER CASED* name of command ('paste', 'cut', 'copy'). function execIECommand( command ) { var doc = editor.document, body = doc.getBody(), enabled = false, onExec = function() { enabled = true; }; // The following seems to be the only reliable way to detect that // clipboard commands are enabled in IE. It will fire the // onpaste/oncut/oncopy events only if the security settings allowed // the command to execute. body.on( command, onExec ); // IE7: document.execCommand has problem to paste into positioned element. if ( CKEDITOR.env.version > 7 ) { doc.$.execCommand( command ); } else { doc.$.selection.createRange().execCommand( command ); } body.removeListener( command, onExec ); return enabled; } // Cutting off control type element in IE standards breaks the selection entirely. (http://dev.ckeditor.com/ticket/4881) function fixCut() { if ( !CKEDITOR.env.ie || CKEDITOR.env.quirks ) return; var sel = editor.getSelection(), control, range, dummy; if ( ( sel.getType() == CKEDITOR.SELECTION_ELEMENT ) && ( control = sel.getSelectedElement() ) ) { range = sel.getRanges()[ 0 ]; dummy = editor.document.createText( '' ); dummy.insertBefore( control ); range.setStartBefore( dummy ); range.setEndAfter( control ); sel.selectRanges( [ range ] ); // Clear up the fix if the paste wasn't succeeded. setTimeout( function() { // Element still online? if ( control.getParent() ) { dummy.remove(); sel.selectElement( control ); } }, 0 ); } } // Allow to peek clipboard content by redirecting the // pasting content into a temporary bin and grab the content of it. function getClipboardDataByPastebin( evt, callback ) { var doc = editor.document, editable = editor.editable(), cancel = function( evt ) { evt.cancel(); }, blurListener; // Avoid recursions on 'paste' event or consequent paste too fast. (http://dev.ckeditor.com/ticket/5730) if ( doc.getById( 'cke_pastebin' ) ) return; var sel = editor.getSelection(); var bms = sel.createBookmarks(); // http://dev.ckeditor.com/ticket/11384. On IE9+ we use native selectionchange (i.e. editor#selectionCheck) to cache the most // recent selection which we then lock on editable blur. See selection.js for more info. // selectionchange fired before getClipboardDataByPastebin() cached selection // before creating bookmark (cached selection will be invalid, because bookmarks modified the DOM), // so we need to fire selectionchange one more time, to store current seleciton. // Selection will be locked when we focus pastebin. if ( CKEDITOR.env.ie ) sel.root.fire( 'selectionchange' ); // Create container to paste into. // For rich content we prefer to use "body" since it holds // the least possibility to be splitted by pasted content, while this may // breaks the text selection on a frame-less editable, "div" would be // the best one in that case. // In another case on old IEs moving the selection into a "body" paste bin causes error panic. // Body can't be also used for Opera which fills it with <br> // what is indistinguishable from pasted <br> (copying <br> in Opera isn't possible, // but it can be copied from other browser). var pastebin = new CKEDITOR.dom.element( ( CKEDITOR.env.webkit || editable.is( 'body' ) ) && !CKEDITOR.env.ie ? 'body' : 'div', doc ); pastebin.setAttributes( { id: 'cke_pastebin', 'data-cke-temp': '1' } ); var containerOffset = 0, offsetParent, win = doc.getWindow(); if ( CKEDITOR.env.webkit ) { // It's better to paste close to the real paste destination, so inherited styles // (which Webkits will try to compensate by styling span) differs less from the destination's one. editable.append( pastebin ); // Style pastebin like .cke_editable, to minimize differences between origin and destination. (http://dev.ckeditor.com/ticket/9754) pastebin.addClass( 'cke_editable' ); // Compensate position of offsetParent. if ( !editable.is( 'body' ) ) { // We're not able to get offsetParent from pastebin (body element), so check whether // its parent (editable) is positioned. if ( editable.getComputedStyle( 'position' ) != 'static' ) offsetParent = editable; // And if not - safely get offsetParent from editable. else offsetParent = CKEDITOR.dom.element.get( editable.$.offsetParent ); containerOffset = offsetParent.getDocumentPosition().y; } } else { // Opera and IE doesn't allow to append to html element. editable.getAscendant( CKEDITOR.env.ie ? 'body' : 'html', 1 ).append( pastebin ); } pastebin.setStyles( { position: 'absolute', // Position the bin at the top (+10 for safety) of viewport to avoid any subsequent document scroll. top: ( win.getScrollPosition().y - containerOffset + 10 ) + 'px', width: '1px', // Caret has to fit in that height, otherwise browsers like Chrome & Opera will scroll window to show it. // Set height equal to viewport's height - 20px (safety gaps), minimum 1px. height: Math.max( 1, win.getViewPaneSize().height - 20 ) + 'px', overflow: 'hidden', // Reset styles that can mess up pastebin position. margin: 0, padding: 0 } ); // Paste fails in Safari when the body tag has 'user-select: none'. (http://dev.ckeditor.com/ticket/12506) if ( CKEDITOR.env.safari ) pastebin.setStyles( CKEDITOR.tools.cssVendorPrefix( 'user-select', 'text' ) ); // Check if the paste bin now establishes new editing host. var isEditingHost = pastebin.getParent().isReadOnly(); if ( isEditingHost ) { // Hide the paste bin. pastebin.setOpacity( 0 ); // And make it editable. pastebin.setAttribute( 'contenteditable', true ); } // Transparency is not enough since positioned non-editing host always shows // resize handler, pull it off the screen instead. else { pastebin.setStyle( editor.config.contentsLangDirection == 'ltr' ? 'left' : 'right', '-10000px' ); } editor.on( 'selectionChange', cancel, null, null, 0 ); // Webkit fill fire blur on editable when moving selection to // pastebin (if body is used). Cancel it because it causes incorrect // selection lock in case of inline editor (http://dev.ckeditor.com/ticket/10644). // The same seems to apply to Firefox (http://dev.ckeditor.com/ticket/10787). if ( CKEDITOR.env.webkit || CKEDITOR.env.gecko ) blurListener = editable.once( 'blur', cancel, null, null, -100 ); // Temporarily move selection to the pastebin. isEditingHost && pastebin.focus(); var range = new CKEDITOR.dom.range( pastebin ); range.selectNodeContents( pastebin ); var selPastebin = range.select(); // If non-native paste is executed, IE will open security alert and blur editable. // Editable will then lock selection inside itself and after accepting security alert // this selection will be restored. We overwrite stored selection, so it's restored // in pastebin. (http://dev.ckeditor.com/ticket/9552) if ( CKEDITOR.env.ie ) { blurListener = editable.once( 'blur', function() { editor.lockSelection( selPastebin ); } ); } var scrollTop = CKEDITOR.document.getWindow().getScrollPosition().y; // Wait a while and grab the pasted contents. setTimeout( function() { // Restore main window's scroll position which could have been changed // by browser in cases described in http://dev.ckeditor.com/ticket/9771. if ( CKEDITOR.env.webkit ) CKEDITOR.document.getBody().$.scrollTop = scrollTop; // Blur will be fired only on non-native paste. In other case manually remove listener. blurListener && blurListener.removeListener(); // Restore properly the document focus. (http://dev.ckeditor.com/ticket/8849) if ( CKEDITOR.env.ie ) editable.focus(); // IE7: selection must go before removing pastebin. (http://dev.ckeditor.com/ticket/8691) sel.selectBookmarks( bms ); pastebin.remove(); // Grab the HTML contents. // We need to look for a apple style wrapper on webkit it also adds // a div wrapper if you copy/paste the body of the editor. // Remove hidden div and restore selection. var bogusSpan; if ( CKEDITOR.env.webkit && ( bogusSpan = pastebin.getFirst() ) && ( bogusSpan.is && bogusSpan.hasClass( 'Apple-style-span' ) ) ) pastebin = bogusSpan; editor.removeListener( 'selectionChange', cancel ); callback( pastebin.getHtml() ); }, 0 ); } // Try to get content directly on IE from clipboard, without native event // being fired before. In other words - synthetically get clipboard data, if it's possible. // mainPasteEvent will be fired, so if forced native paste: // * worked, getClipboardDataByPastebin will grab it, // * didn't work, dataValue and dataTransfer will be empty and editor#paste won't be fired. // Clipboard data can be accessed directly only on IEs older than Edge. // On other browsers we should fire beforePaste event and return false. function getClipboardDataDirectly() { if ( clipboard.mainPasteEvent == 'paste' ) { editor.fire( 'beforePaste', { type: 'auto', method: 'paste' } ); return false; } // Prevent IE from pasting at the begining of the document. editor.focus(); // Command will be handled by 'beforepaste', but as // execIECommand( 'paste' ) will fire also 'paste' event // we're canceling it. preventPasteEventNow(); // http://dev.ckeditor.com/ticket/9247: Lock focus to prevent IE from hiding toolbar for inline editor. var focusManager = editor.focusManager; focusManager.lock(); if ( editor.editable().fire( clipboard.mainPasteEvent ) && !execIECommand( 'paste' ) ) { focusManager.unlock(); return false; } focusManager.unlock(); return true; } // Listens for some clipboard related keystrokes, so they get customized. // Needs to be bind to keydown event. function onKey( event ) { if ( editor.mode != 'wysiwyg' ) return; switch ( event.data.keyCode ) { // Paste case CKEDITOR.CTRL + 86: // CTRL+V case CKEDITOR.SHIFT + 45: // SHIFT+INS var editable = editor.editable(); // Cancel 'paste' event because ctrl+v is for IE handled // by 'beforepaste'. preventPasteEventNow(); // Simulate 'beforepaste' event for all browsers using 'paste' as main event. if ( clipboard.mainPasteEvent == 'paste' ) { editable.fire( 'beforepaste' ); } return; // Cut case CKEDITOR.CTRL + 88: // CTRL+X case CKEDITOR.SHIFT + 46: // SHIFT+DEL // Save Undo snapshot. editor.fire( 'saveSnapshot' ); // Save before cut setTimeout( function() { editor.fire( 'saveSnapshot' ); // Save after cut }, 50 ); // OSX is slow (http://dev.ckeditor.com/ticket/11416). } } function pasteDataFromClipboard( evt ) { // Default type is 'auto', but can be changed by beforePaste listeners. var eventData = { type: 'auto', method: 'paste', dataTransfer: clipboard.initPasteDataTransfer( evt ) }; eventData.dataTransfer.cacheData(); // Fire 'beforePaste' event so clipboard flavor get customized by other plugins. // If 'beforePaste' is canceled continue executing getClipboardDataByPastebin and then do nothing // (do not fire 'paste', 'afterPaste' events). This way we can grab all - synthetically // and natively pasted content and prevent its insertion into editor // after canceling 'beforePaste' event. var beforePasteNotCanceled = editor.fire( 'beforePaste', eventData ) !== false; // Do not use paste bin if the browser let us get HTML or files from dataTranfer. if ( beforePasteNotCanceled && clipboard.canClipboardApiBeTrusted( eventData.dataTransfer, editor ) ) { evt.data.preventDefault(); setTimeout( function() { firePasteEvents( editor, eventData ); }, 0 ); } else { getClipboardDataByPastebin( evt, function( data ) { // Clean up. eventData.dataValue = data.replace( /<span[^>]+data-cke-bookmark[^<]*?<\/span>/ig, '' ); // Fire remaining events (without beforePaste) beforePasteNotCanceled && firePasteEvents( editor, eventData ); } ); } } function setToolbarStates() { if ( editor.mode != 'wysiwyg' ) return; var pasteState = stateFromNamedCommand( 'paste' ); editor.getCommand( 'cut' ).setState( stateFromNamedCommand( 'cut' ) ); editor.getCommand( 'copy' ).setState( stateFromNamedCommand( 'copy' ) ); editor.getCommand( 'paste' ).setState( pasteState ); editor.fire( 'pasteState', pasteState ); } function stateFromNamedCommand( command ) { if ( inReadOnly && command in { paste: 1, cut: 1 } ) return CKEDITOR.TRISTATE_DISABLED; if ( command == 'paste' ) return CKEDITOR.TRISTATE_OFF; // Cut, copy - check if the selection is not empty. var sel = editor.getSelection(), ranges = sel.getRanges(), selectionIsEmpty = sel.getType() == CKEDITOR.SELECTION_NONE || ( ranges.length == 1 && ranges[ 0 ].collapsed ); return selectionIsEmpty ? CKEDITOR.TRISTATE_DISABLED : CKEDITOR.TRISTATE_OFF; } } // Returns: // * 'htmlifiedtext' if content looks like transformed by browser from plain text. // See clipboard/paste.html TCs for more info. // * 'html' if it is not 'htmlifiedtext'. function recogniseContentType( data ) { if ( CKEDITOR.env.webkit ) { // Plain text or ( <div><br></div> and text inside <div> ). if ( !data.match( /^[^<]*$/g ) && !data.match( /^(<div><br( ?\/)?><\/div>|<div>[^<]*<\/div>)*$/gi ) ) return 'html'; } else if ( CKEDITOR.env.ie ) { // Text and <br> or ( text and <br> in <p> - paragraphs can be separated by new \r\n ). if ( !data.match( /^([^<]|<br( ?\/)?>)*$/gi ) && !data.match( /^(<p>([^<]|<br( ?\/)?>)*<\/p>|(\r\n))*$/gi ) ) return 'html'; } else if ( CKEDITOR.env.gecko ) { // Text or <br>. if ( !data.match( /^([^<]|<br( ?\/)?>)*$/gi ) ) return 'html'; } else { return 'html'; } return 'htmlifiedtext'; } // This function transforms what browsers produce when // pasting plain text into editable element (see clipboard/paste.html TCs // for more info) into correct HTML (similar to that produced by text2Html). function htmlifiedTextHtmlification( config, data ) { function repeatParagraphs( repeats ) { // Repeat blocks floor((n+1)/2) times. // Even number of repeats - add <br> at the beginning of last <p>. return CKEDITOR.tools.repeat( '</p><p>', ~~( repeats / 2 ) ) + ( repeats % 2 == 1 ? '<br>' : '' ); } // Replace adjacent white-spaces (EOLs too - Fx sometimes keeps them) with one space. data = data.replace( /\s+/g, ' ' ) // Remove spaces from between tags. .replace( /> +</g, '><' ) // Normalize XHTML syntax and upper cased <br> tags. .replace( /<br ?\/>/gi, '<br>' ); // IE - lower cased tags. data = data.replace( /<\/?[A-Z]+>/g, function( match ) { return match.toLowerCase(); } ); // Don't touch single lines (no <br|p|div>) - nothing to do here. if ( data.match( /^[^<]$/ ) ) return data; // Webkit. if ( CKEDITOR.env.webkit && data.indexOf( '<div>' ) > -1 ) { // One line break at the beginning - insert <br> data = data.replace( /^(<div>(<br>|)<\/div>)(?!$|(<div>(<br>|)<\/div>))/g, '<br>' ) // Two or more - reduce number of new lines by one. .replace( /^(<div>(<br>|)<\/div>){2}(?!$)/g, '<div></div>' ); // Two line breaks create one paragraph in Webkit. if ( data.match( /<div>(<br>|)<\/div>/ ) ) { data = '<p>' + data.replace( /(<div>(<br>|)<\/div>)+/g, function( match ) { return repeatParagraphs( match.split( '</div><div>' ).length + 1 ); } ) + '</p>'; } // One line break create br. data = data.replace( /<\/div><div>/g, '<br>' ); // Remove remaining divs. data = data.replace( /<\/?div>/g, '' ); } // Opera and Firefox and enterMode != BR. if ( CKEDITOR.env.gecko && config.enterMode != CKEDITOR.ENTER_BR ) { // Remove bogus <br> - Fx generates two <brs> for one line break. // For two line breaks it still produces two <brs>, but it's better to ignore this case than the first one. if ( CKEDITOR.env.gecko ) data = data.replace( /^<br><br>$/, '<br>' ); // This line satisfy edge case when for Opera we have two line breaks //data = data.replace( /) if ( data.indexOf( '<br><br>' ) > -1 ) { // Two line breaks create one paragraph, three - 2, four - 3, etc. data = '<p>' + data.replace( /(<br>){2,}/g, function( match ) { return repeatParagraphs( match.length / 4 ); } ) + '</p>'; } } return switchEnterMode( config, data ); } function filtersFactoryFactory() { var filters = {}; function setUpTags() { var tags = {}; for ( var tag in CKEDITOR.dtd ) { if ( tag.charAt( 0 ) != '$' && tag != 'div' && tag != 'span' ) { tags[ tag ] = 1; } } return tags; } function createSemanticContentFilter() { var filter = new CKEDITOR.filter(); filter.allow( { $1: { elements: setUpTags(), attributes: true, styles: false, classes: false } } ); return filter; } return { get: function( type ) { if ( type == 'plain-text' ) { // Does this look confusing to you? Did we forget about enter mode? // It is a trick that let's us creating one filter for edidtor, regardless of its // activeEnterMode (which as the name indicates can change during runtime). // // How does it work? // The active enter mode is passed to the filter.applyTo method. // The filter first marks all elements except <br> as disallowed and then tries to remove // them. However, it cannot remove e.g. a <p> element completely, because it's a basic structural element, // so it tries to replace it with an element created based on the active enter mode, eventually doing nothing. // // Now you can sleep well. return filters.plainText || ( filters.plainText = new CKEDITOR.filter( 'br' ) ); } else if ( type == 'semantic-content' ) { return filters.semanticContent || ( filters.semanticContent = createSemanticContentFilter() ); } else if ( type ) { // Create filter based on rules (string or object). return new CKEDITOR.filter( type ); } return null; } }; } function filterContent( editor, data, filter ) { var fragment = CKEDITOR.htmlParser.fragment.fromHtml( data ), writer = new CKEDITOR.htmlParser.basicWriter(); filter.applyTo( fragment, true, false, editor.activeEnterMode ); fragment.writeHtml( writer ); return writer.getHtml(); } function switchEnterMode( config, data ) { if ( config.enterMode == CKEDITOR.ENTER_BR ) { data = data.replace( /(<\/p><p>)+/g, function( match ) { return CKEDITOR.tools.repeat( '<br>', match.length / 7 * 2 ); } ).replace( /<\/?p>/g, '' ); } else if ( config.enterMode == CKEDITOR.ENTER_DIV ) { data = data.replace( /<(\/)?p>/g, '<$1div>' ); } return data; } function preventDefaultSetDropEffectToNone( evt ) { evt.data.preventDefault(); evt.data.$.dataTransfer.dropEffect = 'none'; } function initDragDrop( editor ) { var clipboard = CKEDITOR.plugins.clipboard; editor.on( 'contentDom', function() { var editable = editor.editable(), dropTarget = CKEDITOR.plugins.clipboard.getDropTarget( editor ), top = editor.ui.space( 'top' ), bottom = editor.ui.space( 'bottom' ); // -------------- DRAGOVER TOP & BOTTOM -------------- // Not allowing dragging on toolbar and bottom (http://dev.ckeditor.com/ticket/12613). clipboard.preventDefaultDropOnElement( top ); clipboard.preventDefaultDropOnElement( bottom ); // -------------- DRAGSTART -------------- // Listed on dragstart to mark internal and cross-editor drag & drop // and save range and selected HTML. editable.attachListener( dropTarget, 'dragstart', fireDragEvent ); // Make sure to reset data transfer (in case dragend was not called or was canceled). editable.attachListener( editor, 'dragstart', clipboard.resetDragDataTransfer, clipboard, null, 1 ); // Create a dataTransfer object and save it globally. editable.attachListener( editor, 'dragstart', function( evt ) { clipboard.initDragDataTransfer( evt, editor ); }, null, null, 2 ); editable.attachListener( editor, 'dragstart', function() { // Save drag range globally for cross editor D&D. var dragRange = clipboard.dragRange = editor.getSelection().getRanges()[ 0 ]; // Store number of children, so we can later tell if any text node was split on drop. (http://dev.ckeditor.com/ticket/13011, http://dev.ckeditor.com/ticket/13447) if ( CKEDITOR.env.ie && CKEDITOR.env.version < 10 ) { clipboard.dragStartContainerChildCount = dragRange ? getContainerChildCount( dragRange.startContainer ) : null; clipboard.dragEndContainerChildCount = dragRange ? getContainerChildCount( dragRange.endContainer ) : null; } }, null, null, 100 ); // -------------- DRAGEND -------------- // Clean up on dragend. editable.attachListener( dropTarget, 'dragend', fireDragEvent ); // Init data transfer if someone wants to use it in dragend. editable.attachListener( editor, 'dragend', clipboard.initDragDataTransfer, clipboard, null, 1 ); // When drag & drop is done we need to reset dataTransfer so the future // external drop will be not recognize as internal. editable.attachListener( editor, 'dragend', clipboard.resetDragDataTransfer, clipboard, null, 100 ); // -------------- DRAGOVER -------------- // We need to call preventDefault on dragover because otherwise if // we drop image it will overwrite document. editable.attachListener( dropTarget, 'dragover', function( evt ) { // Edge requires this handler to have `preventDefault()` regardless of the situation. if ( CKEDITOR.env.edge ) { evt.data.preventDefault(); return; } var target = evt.data.getTarget(); // Prevent reloading page when dragging image on empty document (http://dev.ckeditor.com/ticket/12619). if ( target && target.is && target.is( 'html' ) ) { evt.data.preventDefault(); return; } // If we do not prevent default dragover on IE the file path // will be loaded and we will lose content. On the other hand // if we prevent it the cursor will not we shown, so we prevent // dragover only on IE, on versions which support file API and only // if the event contains files. if ( CKEDITOR.env.ie && CKEDITOR.plugins.clipboard.isFileApiSupported && evt.data.$.dataTransfer.types.contains( 'Files' ) ) { evt.data.preventDefault(); } } ); // -------------- DROP -------------- editable.attachListener( dropTarget, 'drop', function( evt ) { // Do nothing if event was already prevented. (http://dev.ckeditor.com/ticket/13879) if ( evt.data.$.defaultPrevented ) { return; } // Cancel native drop. evt.data.preventDefault(); var target = evt.data.getTarget(), readOnly = target.isReadOnly(); // Do nothing if drop on non editable element (http://dev.ckeditor.com/ticket/13015). // The <html> tag isn't editable (body is), but we want to allow drop on it // (so it is possible to drop below editor contents). if ( readOnly && !( target.type == CKEDITOR.NODE_ELEMENT && target.is( 'html' ) ) ) { return; } // Getting drop position is one of the most complex parts. var dropRange = clipboard.getRangeAtDropPosition( evt, editor ), dragRange = clipboard.dragRange; // Do nothing if it was not possible to get drop range. if ( !dropRange ) { return; } // Fire drop. fireDragEvent( evt, dragRange, dropRange ); }, null, null, 9999 ); // Create dataTransfer or get it, if it was created before. editable.attachListener( editor, 'drop', clipboard.initDragDataTransfer, clipboard, null, 1 ); // Execute drop action, fire paste. editable.attachListener( editor, 'drop', function( evt ) { var data = evt.data; if ( !data ) { return; } // Let user modify drag and drop range. var dropRange = data.dropRange, dragRange = data.dragRange, dataTransfer = data.dataTransfer; if ( dataTransfer.getTransferType( editor ) == CKEDITOR.DATA_TRANSFER_INTERNAL ) { // Execute drop with a timeout because otherwise selection, after drop, // on IE is in the drag position, instead of drop position. setTimeout( function() { clipboard.internalDrop( dragRange, dropRange, dataTransfer, editor ); }, 0 ); } else if ( dataTransfer.getTransferType( editor ) == CKEDITOR.DATA_TRANSFER_CROSS_EDITORS ) { crossEditorDrop( dragRange, dropRange, dataTransfer ); } else { externalDrop( dropRange, dataTransfer ); } }, null, null, 9999 ); // Cross editor drag and drop (drag in one Editor and drop in the other). function crossEditorDrop( dragRange, dropRange, dataTransfer ) { // Paste event should be fired before delete contents because otherwise // Chrome have a problem with drop range (Chrome split the drop // range container so the offset is bigger then container length). dropRange.select(); firePasteEvents( editor, { dataTransfer: dataTransfer, method: 'drop' }, 1 ); // Remove dragged content and make a snapshot. dataTransfer.sourceEditor.fire( 'saveSnapshot' ); dataTransfer.sourceEditor.editable().extractHtmlFromRange( dragRange ); // Make some selection before saving snapshot, otherwise error will be thrown, because // there will be no valid selection after content is removed. dataTransfer.sourceEditor.getSelection().selectRanges( [ dragRange ] ); dataTransfer.sourceEditor.fire( 'saveSnapshot' ); } // Drop from external source. function externalDrop( dropRange, dataTransfer ) { // Paste content into the drop position. dropRange.select(); firePasteEvents( editor, { dataTransfer: dataTransfer, method: 'drop' }, 1 ); // Usually we reset DataTranfer on dragend, // but dragend is called on the same element as dragstart // so it will not be called on on external drop. clipboard.resetDragDataTransfer(); } // Fire drag/drop events (dragstart, dragend, drop). function fireDragEvent( evt, dragRange, dropRange ) { var eventData = { $: evt.data.$, target: evt.data.getTarget() }; if ( dragRange ) { eventData.dragRange = dragRange; } if ( dropRange ) { eventData.dropRange = dropRange; } if ( editor.fire( evt.name, eventData ) === false ) { evt.data.preventDefault(); } } function getContainerChildCount( container ) { if ( container.type != CKEDITOR.NODE_ELEMENT ) { container = container.getParent(); } return container.getChildCount(); } } ); } /** * @singleton * @class CKEDITOR.plugins.clipboard */ CKEDITOR.plugins.clipboard = { /** * True if the environment allows to set data on copy or cut manually. This value is false in IE, because this browser * shows the security dialog window when the script tries to set clipboard data and on iOS, because custom data is * not saved to clipboard there. * * @since 4.5 * @readonly * @property {Boolean} */ isCustomCopyCutSupported: !CKEDITOR.env.ie && !CKEDITOR.env.iOS, /** * True if the environment supports MIME types and custom data types in dataTransfer/cliboardData getData/setData methods. * * @since 4.5 * @readonly * @property {Boolean} */ isCustomDataTypesSupported: !CKEDITOR.env.ie, /** * True if the environment supports File API. * * @since 4.5 * @readonly * @property {Boolean} */ isFileApiSupported: !CKEDITOR.env.ie || CKEDITOR.env.version > 9, /** * Main native paste event editable should listen to. * * **Note:** Safari does not like the {@link CKEDITOR.editor#beforePaste} event &mdash; it sometimes does not * handle <kbd>Ctrl+C</kbd> properly. This is probably caused by some race condition between events. * Chrome, Firefox and Edge work well with both events, so it is better to use {@link CKEDITOR.editor#paste} * which will handle pasting from e.g. browsers' menu bars. * IE7/8 does not like the {@link CKEDITOR.editor#paste} event for which it is throwing random errors. * * @since 4.5 * @readonly * @property {String} */ mainPasteEvent: ( CKEDITOR.env.ie && !CKEDITOR.env.edge ) ? 'beforepaste' : 'paste', /** * Returns `true` if it is expected that a browser provides HTML data through the Clipboard API. * If not, this method returns `false` and as a result CKEditor will use the paste bin. Read more in * the [Clipboard Integration](http://docs.ckeditor.com/#!/guide/dev_clipboard-section-clipboard-api) guide. * * @since 4.5.2 * @returns {Boolean} */ canClipboardApiBeTrusted: function( dataTransfer, editor ) { // If it's an internal or cross-editor data transfer, then it means that custom cut/copy/paste support works // and that the data were put manually on the data transfer so we can be sure that it's available. if ( dataTransfer.getTransferType( editor ) != CKEDITOR.DATA_TRANSFER_EXTERNAL ) { return true; } // In Chrome we can trust Clipboard API, with the exception of Chrome on Android (in both - mobile and desktop modes), where // clipboard API is not available so we need to check it (http://dev.ckeditor.com/ticket/13187). if ( CKEDITOR.env.chrome && !dataTransfer.isEmpty() ) { return true; } // Because of a Firefox bug HTML data are not available in some cases (e.g. paste from Word), in such cases we // need to use the pastebin (http://dev.ckeditor.com/ticket/13528, https://bugzilla.mozilla.org/show_bug.cgi?id=1183686). if ( CKEDITOR.env.gecko && ( dataTransfer.getData( 'text/html' ) || dataTransfer.getFilesCount() ) ) { return true; } // Safari fixed clipboard in 10.1 (https://bugs.webkit.org/show_bug.cgi?id=19893) (http://dev.ckeditor.com/ticket/16982). // However iOS version still doesn't work well enough (https://bugs.webkit.org/show_bug.cgi?id=19893#c34). if ( CKEDITOR.env.safari && CKEDITOR.env.version >= 603 && !CKEDITOR.env.iOS ) { return true; } // In older Safari and IE HTML data is not available though the Clipboard API. // In Edge things are a bit messy at the moment - // https://connect.microsoft.com/IE/feedback/details/1572456/edge-clipboard-api-text-html-content-messed-up-in-event-clipboarddata // It is safer to use the paste bin in unknown cases. return false; }, /** * Returns the element that should be used as the target for the drop event. * * @since 4.5 * @param {CKEDITOR.editor} editor The editor instance. * @returns {CKEDITOR.dom.domObject} the element that should be used as the target for the drop event. */ getDropTarget: function( editor ) { var editable = editor.editable(); // http://dev.ckeditor.com/ticket/11123 Firefox needs to listen on document, because otherwise event won't be fired. // http://dev.ckeditor.com/ticket/11086 IE8 cannot listen on document. if ( ( CKEDITOR.env.ie && CKEDITOR.env.version < 9 ) || editable.isInline() ) { return editable; } else { return editor.document; } }, /** * IE 8 & 9 split text node on drop so the first node contains the * text before the drop position and the second contains the rest. If you * drag the content from the same node you will be not be able to get * it (the range becomes invalid), so you need to join them back. * * Note that the first node in IE 8 & 9 is the original node object * but with shortened content. * * Before: * --- Text Node A ---------------------------------- * /\ * Drag position * * After (IE 8 & 9): * --- Text Node A ----- --- Text Node B ----------- * /\ /\ * Drop position Drag position * (invalid) * * After (other browsers): * --- Text Node A ---------------------------------- * /\ /\ * Drop position Drag position * * **Note:** This function is in the public scope for tests usage only. * * @since 4.5 * @private * @param {CKEDITOR.dom.range} dragRange The drag range. * @param {CKEDITOR.dom.range} dropRange The drop range. * @param {Number} preDragStartContainerChildCount The number of children of the drag range start container before the drop. * @param {Number} preDragEndContainerChildCount The number of children of the drag range end container before the drop. */ fixSplitNodesAfterDrop: function( dragRange, dropRange, preDragStartContainerChildCount, preDragEndContainerChildCount ) { var dropContainer = dropRange.startContainer; if ( typeof preDragEndContainerChildCount != 'number' || typeof preDragStartContainerChildCount != 'number' ) { return; } // We are only concerned about ranges anchored in elements. if ( dropContainer.type != CKEDITOR.NODE_ELEMENT ) { return; } if ( handleContainer( dragRange.startContainer, dropContainer, preDragStartContainerChildCount ) ) { return; } if ( handleContainer( dragRange.endContainer, dropContainer, preDragEndContainerChildCount ) ) { return; } function handleContainer( dragContainer, dropContainer, preChildCount ) { var dragElement = dragContainer; if ( dragElement.type == CKEDITOR.NODE_TEXT ) { dragElement = dragContainer.getParent(); } if ( dragElement.equals( dropContainer ) && preChildCount != dropContainer.getChildCount() ) { applyFix( dropRange ); return true; } } function applyFix( dropRange ) { var nodeBefore = dropRange.startContainer.getChild( dropRange.startOffset - 1 ), nodeAfter = dropRange.startContainer.getChild( dropRange.startOffset ); if ( nodeBefore && nodeBefore.type == CKEDITOR.NODE_TEXT && nodeAfter && nodeAfter.type == CKEDITOR.NODE_TEXT ) { var offset = nodeBefore.getLength(); nodeBefore.setText( nodeBefore.getText() + nodeAfter.getText() ); nodeAfter.remove(); dropRange.setStart( nodeBefore, offset ); dropRange.collapse( true ); } } }, /** * Checks whether turning the drag range into bookmarks will invalidate the drop range. * This usually happens when the drop range shares the container with the drag range and is * located after the drag range, but there are countless edge cases. * * This function is stricly related to {@link #internalDrop} which toggles * order in which it creates bookmarks for both ranges based on a value returned * by this method. In some cases this method returns a value which is not necessarily * true in terms of what it was meant to check, but it is convenient, because * we know how it is interpreted in {@link #internalDrop}, so the correct * behavior of the entire algorithm is assured. * * **Note:** This function is in the public scope for tests usage only. * * @since 4.5 * @private * @param {CKEDITOR.dom.range} dragRange The first range to compare. * @param {CKEDITOR.dom.range} dropRange The second range to compare. * @returns {Boolean} `true` if the first range is before the second range. */ isDropRangeAffectedByDragRange: function( dragRange, dropRange ) { var dropContainer = dropRange.startContainer, dropOffset = dropRange.endOffset; // Both containers are the same and drop offset is at the same position or later. // " A L] A " " M A " // ^ ^ if ( dragRange.endContainer.equals( dropContainer ) && dragRange.endOffset <= dropOffset ) { return true; } // Bookmark for drag start container will mess up with offsets. // " O [L A " " M A " // ^ ^ if ( dragRange.startContainer.getParent().equals( dropContainer ) && dragRange.startContainer.getIndex() < dropOffset ) { return true; } // Bookmark for drag end container will mess up with offsets. // " O] L A " " M A " // ^ ^ if ( dragRange.endContainer.getParent().equals( dropContainer ) && dragRange.endContainer.getIndex() < dropOffset ) { return true; } return false; }, /** * Internal drag and drop (drag and drop in the same editor instance). * * **Note:** This function is in the public scope for tests usage only. * * @since 4.5 * @private * @param {CKEDITOR.dom.range} dragRange The first range to compare. * @param {CKEDITOR.dom.range} dropRange The second range to compare. * @param {CKEDITOR.plugins.clipboard.dataTransfer} dataTransfer * @param {CKEDITOR.editor} editor */ internalDrop: function( dragRange, dropRange, dataTransfer, editor ) { var clipboard = CKEDITOR.plugins.clipboard, editable = editor.editable(), dragBookmark, dropBookmark, isDropRangeAffected; // Save and lock snapshot so there will be only // one snapshot for both remove and insert content. editor.fire( 'saveSnapshot' ); editor.fire( 'lockSnapshot', { dontUpdate: 1 } ); if ( CKEDITOR.env.ie && CKEDITOR.env.version < 10 ) { this.fixSplitNodesAfterDrop( dragRange, dropRange, clipboard.dragStartContainerChildCount, clipboard.dragEndContainerChildCount ); } // Because we manipulate multiple ranges we need to do it carefully, // changing one range (event creating a bookmark) may make other invalid. // We need to change ranges into bookmarks so we can manipulate them easily in the future. // We can change the range which is later in the text before we change the preceding range. // We call isDropRangeAffectedByDragRange to test the order of ranges. isDropRangeAffected = this.isDropRangeAffectedByDragRange( dragRange, dropRange ); if ( !isDropRangeAffected ) { dragBookmark = dragRange.createBookmark( false ); } dropBookmark = dropRange.clone().createBookmark( false ); if ( isDropRangeAffected ) { dragBookmark = dragRange.createBookmark( false ); } // Check if drop range is inside range. // This is an edge case when we drop something on editable's margin/padding. // That space is not treated as a part of the range we drag, so it is possible to drop there. // When we drop, browser tries to find closest drop position and it finds it inside drag range. (http://dev.ckeditor.com/ticket/13453) var startNode = dragBookmark.startNode, endNode = dragBookmark.endNode, dropNode = dropBookmark.startNode, dropInsideDragRange = // Must check endNode because dragRange could be collapsed in some edge cases (simulated DnD). endNode && ( startNode.getPosition( dropNode ) & CKEDITOR.POSITION_PRECEDING ) && ( endNode.getPosition( dropNode ) & CKEDITOR.POSITION_FOLLOWING ); // If the drop range happens to be inside drag range change it's position to the beginning of the drag range. if ( dropInsideDragRange ) { // We only change position of bookmark span that is connected with dropBookmark. // dropRange will be overwritten and set to the dropBookmark later. dropNode.insertBefore( startNode ); } // No we can safely delete content for the drag range... dragRange = editor.createRange(); dragRange.moveToBookmark( dragBookmark ); editable.extractHtmlFromRange( dragRange, 1 ); // ...and paste content into the drop position. dropRange = editor.createRange(); dropRange.moveToBookmark( dropBookmark ); // We do not select drop range, because of may be in the place we can not set the selection // (e.g. between blocks, in case of block widget D&D). We put range to the paste event instead. firePasteEvents( editor, { dataTransfer: dataTransfer, method: 'drop', range: dropRange }, 1 ); editor.fire( 'unlockSnapshot' ); }, /** * Gets the range from the `drop` event. * * @since 4.5 * @param {Object} domEvent A native DOM drop event object. * @param {CKEDITOR.editor} editor The source editor instance. * @returns {CKEDITOR.dom.range} range at drop position. */ getRangeAtDropPosition: function( dropEvt, editor ) { var $evt = dropEvt.data.$, x = $evt.clientX, y = $evt.clientY, $range, defaultRange = editor.getSelection( true ).getRanges()[ 0 ], range = editor.createRange(); // Make testing possible. if ( dropEvt.data.testRange ) return dropEvt.data.testRange; // Webkits. if ( document.caretRangeFromPoint && editor.document.$.caretRangeFromPoint( x, y ) ) { $range = editor.document.$.caretRangeFromPoint( x, y ); range.setStart( CKEDITOR.dom.node( $range.startContainer ), $range.startOffset ); range.collapse( true ); } // FF. else if ( $evt.rangeParent ) { range.setStart( CKEDITOR.dom.node( $evt.rangeParent ), $evt.rangeOffset ); range.collapse( true ); } // IEs 9+. // We check if editable is focused to make sure that it's an internal DnD. External DnD must use the second // mechanism because of http://dev.ckeditor.com/ticket/13472#comment:6. else if ( CKEDITOR.env.ie && CKEDITOR.env.version > 8 && defaultRange && editor.editable().hasFocus ) { // On IE 9+ range by default is where we expected it. // defaultRange may be undefined if dragover was canceled (file drop). return defaultRange; } // IE 8 and all IEs if !defaultRange or external DnD. else if ( document.body.createTextRange ) { // To use this method we need a focus (which may be somewhere else in case of external drop). editor.focus(); $range = editor.document.getBody().$.createTextRange(); try { var sucess = false; // If user drop between text line IEs moveToPoint throws exception: // // Lorem ipsum pulvinar purus et euismod // // dolor sit amet,| consectetur adipiscing // * // vestibulum tincidunt augue eget tempus. // // * - drop position // | - expected cursor position // // So we try to call moveToPoint with +-1px up to +-20px above or // below original drop position to find nearest good drop position. for ( var i = 0; i < 20 && !sucess; i++ ) { if ( !sucess ) { try { $range.moveToPoint( x, y - i ); sucess = true; } catch ( err ) { } } if ( !sucess ) { try { $range.moveToPoint( x, y + i ); sucess = true; } catch ( err ) { } } } if ( sucess ) { var id = 'cke-temp-' + ( new Date() ).getTime(); $range.pasteHTML( '<span id="' + id + '">\u200b</span>' ); var span = editor.document.getById( id ); range.moveToPosition( span, CKEDITOR.POSITION_BEFORE_START ); span.remove(); } else { // If the fist method does not succeed we might be next to // the short element (like header): // // Lorem ipsum pulvinar purus et euismod. // // // SOME HEADER| * // // // vestibulum tincidunt augue eget tempus. // // * - drop position // | - expected cursor position // // In such situation elementFromPoint returns proper element. Using getClientRect // it is possible to check if the cursor should be at the beginning or at the end // of paragraph. var $element = editor.document.$.elementFromPoint( x, y ), element = new CKEDITOR.dom.element( $element ), rect; if ( !element.equals( editor.editable() ) && element.getName() != 'html' ) { rect = element.getClientRect(); if ( x < rect.left ) { range.setStartAt( element, CKEDITOR.POSITION_AFTER_START ); range.collapse( true ); } else { range.setStartAt( element, CKEDITOR.POSITION_BEFORE_END ); range.collapse( true ); } } // If drop happens on no element elementFromPoint returns html or body. // // * |Lorem ipsum pulvinar purus et euismod. // // vestibulum tincidunt augue eget tempus. // // * - drop position // | - expected cursor position // // In such case we can try to use default selection. If startContainer is not // 'editable' element it is probably proper selection. else if ( defaultRange && defaultRange.startContainer && !defaultRange.startContainer.equals( editor.editable() ) ) { return defaultRange; // Otherwise we can not find any drop position and we have to return null // and cancel drop event. } else { return null; } } } catch ( err ) { return null; } } else { return null; } return range; }, /** * This function tries to link the `evt.data.dataTransfer` property of the {@link CKEDITOR.editor#dragstart}, * {@link CKEDITOR.editor#dragend} and {@link CKEDITOR.editor#drop} events to a single * {@link CKEDITOR.plugins.clipboard.dataTransfer} object. * * This method is automatically used by the core of the drag and drop functionality and * usually does not have to be called manually when using the drag and drop events. * * This method behaves differently depending on whether the drag and drop events were fired * artificially (to represent a non-native drag and drop) or whether they were caused by the native drag and drop. * * If the native event is not available, then it will create a new {@link CKEDITOR.plugins.clipboard.dataTransfer} * instance (if it does not exist already) and will link it to this and all following event objects until * the {@link #resetDragDataTransfer} method is called. It means that all three drag and drop events must be fired * in order to ensure that the data transfer is bound correctly. * * If the native event is available, then the {@link CKEDITOR.plugins.clipboard.dataTransfer} is identified * by its ID and a new instance is assigned to the `evt.data.dataTransfer` only if the ID changed or * the {@link #resetDragDataTransfer} method was called. * * @since 4.5 * @param {CKEDITOR.dom.event} [evt] A drop event object. * @param {CKEDITOR.editor} [sourceEditor] The source editor instance. */ initDragDataTransfer: function( evt, sourceEditor ) { // Create a new dataTransfer object based on the drop event. // If this event was used on dragstart to create dataTransfer // both dataTransfer objects will have the same id. var nativeDataTransfer = evt.data.$ ? evt.data.$.dataTransfer : null, dataTransfer = new this.dataTransfer( nativeDataTransfer, sourceEditor ); if ( !nativeDataTransfer ) { // No native event. if ( this.dragData ) { dataTransfer = this.dragData; } else { this.dragData = dataTransfer; } } else { // Native event. If there is the same id we will replace dataTransfer with the one // created on drag, because it contains drag editor, drag content and so on. // Otherwise (in case of drag from external source) we save new object to // the global clipboard.dragData. if ( this.dragData && dataTransfer.id == this.dragData.id ) { dataTransfer = this.dragData; } else { this.dragData = dataTransfer; } } evt.data.dataTransfer = dataTransfer; }, /** * Removes the global {@link #dragData} so the next call to {@link #initDragDataTransfer} * always creates a new instance of {@link CKEDITOR.plugins.clipboard.dataTransfer}. * * @since 4.5 */ resetDragDataTransfer: function() { this.dragData = null; }, /** * Global object storing the data transfer of the current drag and drop operation. * Do not use it directly, use {@link #initDragDataTransfer} and {@link #resetDragDataTransfer}. * * Note: This object is global (meaning that it is not related to a single editor instance) * in order to handle drag and drop from one editor into another. * * @since 4.5 * @private * @property {CKEDITOR.plugins.clipboard.dataTransfer} dragData */ /** * Range object to save the drag range and remove its content after the drop. * * @since 4.5 * @private * @property {CKEDITOR.dom.range} dragRange */ /** * Initializes and links data transfer objects based on the paste event. If the data * transfer object was already initialized on this event, the function will * return that object. In IE it is not possible to link copy/cut and paste events * so the method always returns a new object. The same happens if there is no paste event * passed to the method. * * @since 4.5 * @param {CKEDITOR.dom.event} [evt] A paste event object. * @param {CKEDITOR.editor} [sourceEditor] The source editor instance. * @returns {CKEDITOR.plugins.clipboard.dataTransfer} The data transfer object. */ initPasteDataTransfer: function( evt, sourceEditor ) { if ( !this.isCustomCopyCutSupported ) { // Edge does not support custom copy/cut, but it have some useful data in the clipboardData (http://dev.ckeditor.com/ticket/13755). return new this.dataTransfer( ( CKEDITOR.env.edge && evt && evt.data.$ && evt.data.$.clipboardData ) || null, sourceEditor ); } else if ( evt && evt.data && evt.data.$ ) { var dataTransfer = new this.dataTransfer( evt.data.$.clipboardData, sourceEditor ); if ( this.copyCutData && dataTransfer.id == this.copyCutData.id ) { dataTransfer = this.copyCutData; dataTransfer.$ = evt.data.$.clipboardData; } else { this.copyCutData = dataTransfer; } return dataTransfer; } else { return new this.dataTransfer( null, sourceEditor ); } }, /** * Prevents dropping on the specified element. * * @since 4.5 * @param {CKEDITOR.dom.element} element The element on which dropping should be disabled. */ preventDefaultDropOnElement: function( element ) { element && element.on( 'dragover', preventDefaultSetDropEffectToNone ); } }; // Data type used to link drag and drop events. // // In IE URL data type is buggie and there is no way to mark drag & drop without // modifying text data (which would be displayed if user drop content to the textarea) // so we just read dragged text. // // In Chrome and Firefox we can use custom data types. var clipboardIdDataType = CKEDITOR.plugins.clipboard.isCustomDataTypesSupported ? 'cke/id' : 'Text'; /** * Facade for the native `dataTransfer`/`clipboadData` object to hide all differences * between browsers. * * @since 4.5 * @class CKEDITOR.plugins.clipboard.dataTransfer * @constructor Creates a class instance. * @param {Object} [nativeDataTransfer] A native data transfer object. * @param {CKEDITOR.editor} [editor] The source editor instance. If the editor is defined, dataValue will * be created based on the editor content and the type will be 'html'. */ CKEDITOR.plugins.clipboard.dataTransfer = function( nativeDataTransfer, editor ) { if ( nativeDataTransfer ) { this.$ = nativeDataTransfer; } this._ = { metaRegExp: /^<meta.*?>/i, bodyRegExp: /<body(?:[\s\S]*?)>([\s\S]*)<\/body>/i, fragmentRegExp: /<!--(?:Start|End)Fragment-->/g, data: {}, files: [], normalizeType: function( type ) { type = type.toLowerCase(); if ( type == 'text' || type == 'text/plain' ) { return 'Text'; // IE support only Text and URL; } else if ( type == 'url' ) { return 'URL'; // IE support only Text and URL; } else { return type; } } }; // Check if ID is already created. this.id = this.getData( clipboardIdDataType ); // If there is no ID we need to create it. Different browsers needs different ID. if ( !this.id ) { if ( clipboardIdDataType == 'Text' ) { // For IE10+ only Text data type is supported and we have to compare dragged // and dropped text. If the ID is not set it means that empty string was dragged // (ex. image with no alt). We change null to empty string. this.id = ''; } else { // String for custom data type. this.id = 'cke-' + CKEDITOR.tools.getUniqueId(); } } // In IE10+ we can not use any data type besides text, so we do not call setData. if ( clipboardIdDataType != 'Text' ) { // Try to set ID so it will be passed from the drag to the drop event. // On some browsers with some event it is not possible to setData so we // need to catch exceptions. try { this.$.setData( clipboardIdDataType, this.id ); } catch ( err ) {} } if ( editor ) { this.sourceEditor = editor; this.setData( 'text/html', editor.getSelectedHtml( 1 ) ); // Without setData( 'text', ... ) on dragstart there is no drop event in Safari. // Also 'text' data is empty as drop to the textarea does not work if we do not put there text. if ( clipboardIdDataType != 'Text' && !this.getData( 'text/plain' ) ) { this.setData( 'text/plain', editor.getSelection().getSelectedText() ); } } /** * Data transfer ID used to bind all dataTransfer * objects based on the same event (e.g. in drag and drop events). * * @readonly * @property {String} id */ /** * A native DOM event object. * * @readonly * @property {Object} $ */ /** * Source editor &mdash; the editor where the drag starts. * Might be undefined if the drag starts outside the editor (e.g. when dropping files to the editor). * * @readonly * @property {CKEDITOR.editor} sourceEditor */ /** * Private properties and methods. * * @private * @property {Object} _ */ }; /** * Data transfer operation (drag and drop or copy and paste) started and ended in the same * editor instance. * * @since 4.5 * @readonly * @property {Number} [=1] * @member CKEDITOR */ CKEDITOR.DATA_TRANSFER_INTERNAL = 1; /** * Data transfer operation (drag and drop or copy and paste) started in one editor * instance and ended in another. * * @since 4.5 * @readonly * @property {Number} [=2] * @member CKEDITOR */ CKEDITOR.DATA_TRANSFER_CROSS_EDITORS = 2; /** * Data transfer operation (drag and drop or copy and paste) started outside of the editor. * The source of the data may be a textarea, HTML, another application, etc. * * @since 4.5 * @readonly * @property {Number} [=3] * @member CKEDITOR */ CKEDITOR.DATA_TRANSFER_EXTERNAL = 3; CKEDITOR.plugins.clipboard.dataTransfer.prototype = { /** * Facade for the native `getData` method. * * @param {String} type The type of data to retrieve. * @param {Boolean} [getNative=false] Indicates if the whole, original content of the dataTransfer should be returned. * Introduced in CKEditor 4.7.0. * @returns {String} type Stored data for the given type or an empty string if the data for that type does not exist. */ getData: function( type, getNative ) { function isEmpty( data ) { return data === undefined || data === null || data === ''; } function filterUnwantedCharacters( data ) { if ( typeof data !== 'string' ) { return data; } var htmlEnd = data.indexOf( '</html>' ); if ( htmlEnd !== -1 ) { // Just cut everything after `</html>`, so everything after htmlEnd index + length of `</html>`. // Required to workaround bug: https://bugs.chromium.org/p/chromium/issues/detail?id=696978 return data.substring( 0, htmlEnd + 7 ); } return data; } type = this._.normalizeType( type ); var data = this._.data[ type ], result; if ( isEmpty( data ) ) { try { data = this.$.getData( type ); } catch ( e ) {} } if ( isEmpty( data ) ) { data = ''; } // Some browsers add <meta http-equiv="content-type" content="text/html; charset=utf-8"> at the begging of the HTML data // or surround it with <html><head>...</head><body>(some content)<!--StartFragment--> and <!--EndFragment-->(some content)</body></html> // This code removes meta tags and returns only the contents of the <body> element if found. Note that // some significant content may be placed outside Start/EndFragment comments so it's kept. // // See http://dev.ckeditor.com/ticket/13583 for more details. // Additionally http://dev.ckeditor.com/ticket/16847 adds a flag allowing to get the whole, original content. if ( type == 'text/html' && !getNative ) { data = data.replace( this._.metaRegExp, '' ); // Keep only contents of the <body> element result = this._.bodyRegExp.exec( data ); if ( result && result.length ) { data = result[ 1 ]; // Remove also comments. data = data.replace( this._.fragmentRegExp, '' ); } } // Firefox on Linux put files paths as a text/plain data if there are files // in the dataTransfer object. We need to hide it, because files should be // handled on paste only if dataValue is empty. else if ( type == 'Text' && CKEDITOR.env.gecko && this.getFilesCount() && data.substring( 0, 7 ) == 'file://' ) { data = ''; } return filterUnwantedCharacters( data ); }, /** * Facade for the native `setData` method. * * @param {String} type The type of data to retrieve. * @param {String} value The data to add. */ setData: function( type, value ) { type = this._.normalizeType( type ); this._.data[ type ] = value; // There is "Unexpected call to method or property access." error if you try // to set data of unsupported type on IE. if ( !CKEDITOR.plugins.clipboard.isCustomDataTypesSupported && type != 'URL' && type != 'Text' ) { return; } // If we use the text type to bind the ID, then if someone tries to set the text, we must also // update ID accordingly. http://dev.ckeditor.com/ticket/13468. if ( clipboardIdDataType == 'Text' && type == 'Text' ) { this.id = value; } try { this.$.setData( type, value ); } catch ( e ) {} }, /** * Gets the data transfer type. * * @param {CKEDITOR.editor} targetEditor The drop/paste target editor instance. * @returns {Number} Possible values: {@link CKEDITOR#DATA_TRANSFER_INTERNAL}, * {@link CKEDITOR#DATA_TRANSFER_CROSS_EDITORS}, {@link CKEDITOR#DATA_TRANSFER_EXTERNAL}. */ getTransferType: function( targetEditor ) { if ( !this.sourceEditor ) { return CKEDITOR.DATA_TRANSFER_EXTERNAL; } else if ( this.sourceEditor == targetEditor ) { return CKEDITOR.DATA_TRANSFER_INTERNAL; } else { return CKEDITOR.DATA_TRANSFER_CROSS_EDITORS; } }, /** * Copies the data from the native data transfer to a private cache. * This function is needed because the data from the native data transfer * is available only synchronously to the event listener. It is not possible * to get the data asynchronously, after a timeout, and the {@link CKEDITOR.editor#paste} * event is fired asynchronously &mdash; hence the need for caching the data. */ cacheData: function() { if ( !this.$ ) { return; } var that = this, i, file; function getAndSetData( type ) { type = that._.normalizeType( type ); var data = that.getData( type, true ); if ( data ) { that._.data[ type ] = data; } } // Copy data. if ( CKEDITOR.plugins.clipboard.isCustomDataTypesSupported ) { if ( this.$.types ) { for ( i = 0; i < this.$.types.length; i++ ) { getAndSetData( this.$.types[ i ] ); } } } else { getAndSetData( 'Text' ); getAndSetData( 'URL' ); } // Copy files references. file = this._getImageFromClipboard(); if ( ( this.$ && this.$.files ) || file ) { this._.files = []; // Edge have empty files property with no length (http://dev.ckeditor.com/ticket/13755). if ( this.$.files && this.$.files.length ) { for ( i = 0; i < this.$.files.length; i++ ) { this._.files.push( this.$.files[ i ] ); } } // Don't include $.items if both $.files and $.items contains files, because, // according to spec and browsers behavior, they contain the same files. if ( this._.files.length === 0 && file ) { this._.files.push( file ); } } }, /** * Gets the number of files in the dataTransfer object. * * @returns {Number} The number of files. */ getFilesCount: function() { if ( this._.files.length ) { return this._.files.length; } if ( this.$ && this.$.files && this.$.files.length ) { return this.$.files.length; } return this._getImageFromClipboard() ? 1 : 0; }, /** * Gets the file at the index given. * * @param {Number} i Index. * @returns {File} File instance. */ getFile: function( i ) { if ( this._.files.length ) { return this._.files[ i ]; } if ( this.$ && this.$.files && this.$.files.length ) { return this.$.files[ i ]; } // File or null if the file was not found. return i === 0 ? this._getImageFromClipboard() : undefined; }, /** * Checks if the data transfer contains any data. * * @returns {Boolean} `true` if the object contains no data. */ isEmpty: function() { var typesToCheck = {}, type; // If dataTransfer contains files it is not empty. if ( this.getFilesCount() ) { return false; } // Add custom types. for ( type in this._.data ) { typesToCheck[ type ] = 1; } // Add native types. if ( this.$ ) { if ( CKEDITOR.plugins.clipboard.isCustomDataTypesSupported ) { if ( this.$.types ) { for ( var i = 0; i < this.$.types.length; i++ ) { typesToCheck[ this.$.types[ i ] ] = 1; } } } else { typesToCheck.Text = 1; typesToCheck.URL = 1; } } // Remove ID. if ( clipboardIdDataType != 'Text' ) { typesToCheck[ clipboardIdDataType ] = 0; } for ( type in typesToCheck ) { if ( typesToCheck[ type ] && this.getData( type ) !== '' ) { return false; } } return true; }, /** * When the content of the clipboard is pasted in Chrome, the clipboard data object has an empty `files` property, * but it is possible to get the file as `items[0].getAsFile();` (http://dev.ckeditor.com/ticket/12961). * * @private * @returns {File} File instance or `null` if not found. */ _getImageFromClipboard: function() { var file; if ( this.$ && this.$.items && this.$.items[ 0 ] ) { try { file = this.$.items[ 0 ].getAsFile(); // Duck typing if ( file && file.type ) { return file; } } catch ( err ) { // noop } } return undefined; } }; } )(); /** * The default content type that is used when pasted data cannot be clearly recognized as HTML or text. * * For example: `'foo'` may come from a plain text editor or a website. It is not possible to recognize the content * type in this case, so the default type will be used. At the same time it is clear that `'<b>example</b> text'` is * HTML and its origin is a web page, email or another rich text editor. * * **Note:** If content type is text, then styles of the paste context are preserved. * * CKEDITOR.config.clipboard_defaultContentType = 'text'; * * See also the {@link CKEDITOR.editor#paste} event and read more about the integration with clipboard * in the [Clipboard Deep Dive guide](#!/guide/dev_clipboard). * * @since 4.0 * @cfg {'html'/'text'} [clipboard_defaultContentType='html'] * @member CKEDITOR.config */ /** * Fired after the user initiated a paste action, but before the data is inserted into the editor. * The listeners to this event are able to process the content before its insertion into the document. * * Read more about the integration with clipboard in the [Clipboard Deep Dive guide](#!/guide/dev_clipboard). * * See also: * * * the {@link CKEDITOR.config#pasteFilter} option, * * the {@link CKEDITOR.editor#drop} event, * * the {@link CKEDITOR.plugins.clipboard.dataTransfer} class. * * @since 3.1 * @event paste * @member CKEDITOR.editor * @param {CKEDITOR.editor} editor This editor instance. * @param data * @param {String} data.type The type of data in `data.dataValue`. Usually `'html'` or `'text'`, but for listeners * with a priority smaller than `6` it may also be `'auto'` which means that the content type has not been recognised yet * (this will be done by the content type sniffer that listens with priority `6`). * @param {String} data.dataValue HTML to be pasted. * @param {String} data.method Indicates the data transfer method. It could be drag and drop or copy and paste. * Possible values: `'drop'`, `'paste'`. Introduced in CKEditor 4.5. * @param {CKEDITOR.plugins.clipboard.dataTransfer} data.dataTransfer Facade for the native dataTransfer object * which provides access to various data types and files, and passes some data between linked events * (like drag and drop). Introduced in CKEditor 4.5. * @param {Boolean} [data.dontFilter=false] Whether the {@link CKEDITOR.editor#pasteFilter paste filter} should not * be applied to data. This option has no effect when `data.type` equals `'text'` which means that for instance * {@link CKEDITOR.config#forcePasteAsPlainText} has a higher priority. Introduced in CKEditor 4.5. */ /** * Fired before the {@link #paste} event. Allows to preset data type. * * **Note:** This event is deprecated. Add a `0` priority listener for the * {@link #paste} event instead. * * @deprecated * @event beforePaste * @member CKEDITOR.editor */ /** * Fired after the {@link #paste} event if content was modified. Note that if the paste * event does not insert any data, the `afterPaste` event will not be fired. * * @event afterPaste * @member CKEDITOR.editor */ /** * Facade for the native `drop` event. Fired when the native `drop` event occurs. * * **Note:** To manipulate dropped data, use the {@link CKEDITOR.editor#paste} event. * Use the `drop` event only to control drag and drop operations (e.g. to prevent the ability to drop some content). * * Read more about integration with drag and drop in the [Clipboard Deep Dive guide](#!/guide/dev_clipboard). * * See also: * * * The {@link CKEDITOR.editor#paste} event, * * The {@link CKEDITOR.editor#dragstart} and {@link CKEDITOR.editor#dragend} events, * * The {@link CKEDITOR.plugins.clipboard.dataTransfer} class. * * @since 4.5 * @event drop * @member CKEDITOR.editor * @param {CKEDITOR.editor} editor This editor instance. * @param data * @param {Object} data.$ Native drop event. * @param {CKEDITOR.dom.node} data.target Drop target. * @param {CKEDITOR.plugins.clipboard.dataTransfer} data.dataTransfer DataTransfer facade. * @param {CKEDITOR.dom.range} data.dragRange Drag range, lets you manipulate the drag range. * Note that dragged HTML is saved as `text/html` data on `dragstart` so if you change the drag range * on drop, dropped HTML will not change. You need to change it manually using * {@link CKEDITOR.plugins.clipboard.dataTransfer#setData dataTransfer.setData}. * @param {CKEDITOR.dom.range} data.dropRange Drop range, lets you manipulate the drop range. */ /** * Facade for the native `dragstart` event. Fired when the native `dragstart` event occurs. * * This event can be canceled in order to block the drag start operation. It can also be fired to mimic the start of the drag and drop * operation. For instance, the `widget` plugin uses this option to integrate its custom block widget drag and drop with * the entire system. * * Read more about integration with drag and drop in the [Clipboard Deep Dive guide](#!/guide/dev_clipboard). * * See also: * * * The {@link CKEDITOR.editor#paste} event, * * The {@link CKEDITOR.editor#drop} and {@link CKEDITOR.editor#dragend} events, * * The {@link CKEDITOR.plugins.clipboard.dataTransfer} class. * * @since 4.5 * @event dragstart * @member CKEDITOR.editor * @param {CKEDITOR.editor} editor This editor instance. * @param data * @param {Object} data.$ Native dragstart event. * @param {CKEDITOR.dom.node} data.target Drag target. * @param {CKEDITOR.plugins.clipboard.dataTransfer} data.dataTransfer DataTransfer facade. */ /** * Facade for the native `dragend` event. Fired when the native `dragend` event occurs. * * Read more about integration with drag and drop in the [Clipboard Deep Dive guide](#!/guide/dev_clipboard). * * See also: * * * The {@link CKEDITOR.editor#paste} event, * * The {@link CKEDITOR.editor#drop} and {@link CKEDITOR.editor#dragend} events, * * The {@link CKEDITOR.plugins.clipboard.dataTransfer} class. * * @since 4.5 * @event dragend * @member CKEDITOR.editor * @param {CKEDITOR.editor} editor This editor instance. * @param data * @param {Object} data.$ Native dragend event. * @param {CKEDITOR.dom.node} data.target Drag target. * @param {CKEDITOR.plugins.clipboard.dataTransfer} data.dataTransfer DataTransfer facade. */ /** * Defines a filter which is applied to external data pasted or dropped into the editor. Possible values are: * * * `'plain-text'` &ndash; Content will be pasted as a plain text. * * `'semantic-content'` &ndash; Known tags (except `div`, `span`) with all attributes (except * `style` and `class`) will be kept. * * `'h1 h2 p div'` &ndash; Custom rules compatible with {@link CKEDITOR.filter}. * * `null` &ndash; Content will not be filtered by the paste filter (but it still may be filtered * by [Advanced Content Filter](#!/guide/dev_advanced_content_filter)). This value can be used to * disable the paste filter in Chrome and Safari, where this option defaults to `'semantic-content'`. * * Example: * * config.pasteFilter = 'plain-text'; * * Custom setting: * * config.pasteFilter = 'h1 h2 p ul ol li; img[!src, alt]; a[!href]'; * * Based on this configuration option, a proper {@link CKEDITOR.filter} instance will be defined and assigned to the editor * as a {@link CKEDITOR.editor#pasteFilter}. You can tweak the paste filter settings on the fly on this object * as well as delete or replace it. * * var editor = CKEDITOR.replace( 'editor', { * pasteFilter: 'semantic-content' * } ); * * editor.on( 'instanceReady', function() { * // The result of this will be that all semantic content will be preserved * // except tables. * editor.pasteFilter.disallow( 'table' ); * } ); * * Note that the paste filter is applied only to **external** data. There are three data sources: * * * copied and pasted in the same editor (internal), * * copied from one editor and pasted into another (cross-editor), * * coming from all other sources like websites, MS Word, etc. (external). * * If {@link CKEDITOR.config#allowedContent Advanced Content Filter} is not disabled, then * it will also be applied to pasted and dropped data. The paste filter job is to "normalize" * external data which often needs to be handled differently than content produced by the editor. * * This setting defaults to `'semantic-content'` in Chrome, Opera and Safari (all Blink and Webkit based browsers) * due to messy HTML which these browsers keep in the clipboard. In other browsers it defaults to `null`. * * @since 4.5 * @cfg {String} [pasteFilter='semantic-content' in Chrome and Safari and `null` in other browsers] * @member CKEDITOR.config */ /** * {@link CKEDITOR.filter Content filter} which is used when external data is pasted or dropped into the editor * or a forced paste as plain text occurs. * * This object might be used on the fly to define rules for pasted external content. * This object is available and used if the {@link CKEDITOR.plugins.clipboard clipboard} plugin is enabled and * {@link CKEDITOR.config#pasteFilter} or {@link CKEDITOR.config#forcePasteAsPlainText} was defined. * * To enable the filter: * * var editor = CKEDITOR.replace( 'editor', { * pasteFilter: 'plain-text' * } ); * * You can also modify the filter on the fly later on: * * editor.pasteFilter = new CKEDITOR.filter( 'p h1 h2; a[!href]' ); * * Note that the paste filter is only applied to **external** data. There are three data sources: * * * copied and pasted in the same editor (internal), * * copied from one editor and pasted into another (cross-editor), * * coming from all other sources like websites, MS Word, etc. (external). * * If {@link CKEDITOR.config#allowedContent Advanced Content Filter} is not disabled, then * it will also be applied to pasted and dropped data. The paste filter job is to "normalize" * external data which often needs to be handled differently than content produced by the editor. * * @since 4.5 * @readonly * @property {CKEDITOR.filter} [pasteFilter] * @member CKEDITOR.editor */ /** * Duration of the notification displayed after pasting was blocked by the browser. * * @since 4.7.0 * @cfg {Number} [clipboard_notificationDuration=10000] * @member CKEDITOR.config */ CKEDITOR.config.clipboard_notificationDuration = 10000;
{ "content_hash": "7d90e2ea8bba075396a9dda5728d85df", "timestamp": "", "source": "github", "line_count": 2777, "max_line_length": 271, "avg_line_length": 36.88656823910695, "alnum_prop": 0.6552804732803561, "repo_name": "gfrodriguez/yii2-ckeditor", "id": "42191cf70793c1a8cf06b81c82ea7fc01576f6a0", "size": "102595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/ckeditor/plugins/clipboard/plugin.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "175571" }, { "name": "HTML", "bytes": "592538" }, { "name": "JavaScript", "bytes": "5552566" }, { "name": "PHP", "bytes": "9720" } ], "symlink_target": "" }
#ifndef TrackBase_h #define TrackBase_h #include "core/events/EventTarget.h" #include "wtf/RefCounted.h" namespace WebCore { class TrackBase : public RefCounted<TrackBase>, public EventTargetWithInlineData { REFCOUNTED_EVENT_TARGET(TrackBase); public: virtual ~TrackBase() { } enum Type { TextTrack, AudioTrack, VideoTrack }; Type type() const { return m_type; } protected: explicit TrackBase(Type type) : m_type(type) { } private: Type m_type; }; } // namespace WebCore #endif // TrackBase_h
{ "content_hash": "5710fc3e7f1abf19966312955c0d2413", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 82, "avg_line_length": 18.821428571428573, "alnum_prop": 0.7039848197343453, "repo_name": "lordmos/blink", "id": "38ead6489f06ed437ee6bd750dffa58f5be083d1", "size": "1878", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/core/html/track/TrackBase.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "6433" }, { "name": "C", "bytes": "753714" }, { "name": "C++", "bytes": "40028043" }, { "name": "CSS", "bytes": "539440" }, { "name": "F#", "bytes": "8755" }, { "name": "Java", "bytes": "18650" }, { "name": "JavaScript", "bytes": "25700387" }, { "name": "Objective-C", "bytes": "426711" }, { "name": "PHP", "bytes": "141755" }, { "name": "Perl", "bytes": "901523" }, { "name": "Python", "bytes": "3748305" }, { "name": "Ruby", "bytes": "141818" }, { "name": "Shell", "bytes": "9635" }, { "name": "XSLT", "bytes": "49328" } ], "symlink_target": "" }
module Elmas class BadRequestException < StandardError def initialize(response, parsed) @response = response @parsed = parsed super(message) end def message if @parsed.error_message.present? "code #{@response.status}: #{@parsed.error_message}" else @response.inspect end end end class UnauthorizedException < StandardError; end end
{ "content_hash": "f1fcdac99a6f0aa315cae1543aabb137", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 60, "avg_line_length": 21.473684210526315, "alnum_prop": 0.6470588235294118, "repo_name": "exactonline/exactonline-api-ruby-client", "id": "237bc9014c20b576005022412295503d1ed770fb", "size": "439", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/elmas/exception.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "157547" }, { "name": "Shell", "bytes": "621" } ], "symlink_target": "" }
/* Insta-QRP Firmware - OLED Display Library Written By: Joyce Ng & Bertrand Teo Version: 1.0 Date: 21/2/2018 */ #include "oled.h" /* Shift register connections: QA - Connected to Register Select pin or pin 4 of OLED QE - Least Significant Bit, it is connected to DB4 or pin 11 of OLED QF - 2nd bit, it is connected to DB5 or pin 12 of OLED QG - 3rd bit, it is connected to DB6 or pin 13 of OLED QH - Most Significant Bit, it is connected to DB7 or pin 14 of OLED */ // Create an OLED struct for internal use OLED oled_int; // Initializes the OLED display void oled_init(OLED oled) { // Assign the structure oled_int = oled; /* The data sheets warn that the LCD module may fail to initialize properly when power is first applied. This is particularly likely if the Vdd supply does not rise to its correct operating voltage quickly enough. It is recommended that after power is applied, a command sequence of 3 bytes of 3xh be sent to the module. This will ensure that the module is in 8-bit mode and is properly initialized. Following this, the LCD module can be switched to 4-bit mode. */ oled_write_cmd(0x33); oled_write_cmd(0x32); /* Notice: For displays utilizing the WS0010, like the OLED display used in The Insta-QRP transceiver, the commands listed below have to be STRICTLY sent in that order. It is observed that if you do not, the display may behave erratically after a reset. */ oled_write_cmd(0x28); // Function Set instruction - 4 bit mode oled_write_cmd(0x08); // Turns display off oled_write_cmd(0x01); // Clear display oled_write_cmd(0x06); // Entry mode select oled_write_cmd(0x17); // Required for OLED initialization, no effect on LCDs oled_write_cmd(0x0C); // Display On, Cursor Off } /* Loads data into OLED display EXAMPLE OF HOW THE CHAR MANIPULATION WORKS LET UINT8_t data be 0x80 0x80 = 1000 0000 so when it is divided by 128 we get 1. 2 shifts the 1 to the left, 0001 0000 0000 From there we can see how each bit is loaded into the shift reg */ void oled_load(char data) { int counter; for(counter = 0; counter < 8; counter++) { /* Note that the pins would load in from the LSB to MSB. so from bit 0 to bit 7 However, in order for the OLED to work, we only want bits 4 to 7 Thus some data manipulation of the char is required for the pins to load from pin 7 to 0 */ // Check the MSB of the char. if(data/128 == 1) HAL_GPIO_WritePin(oled_int.OLED_IO, oled_int.DATA, GPIO_PIN_SET); // If the bit at the time is a 0, the Data pin will go low else HAL_GPIO_WritePin(oled_int.OLED_IO, oled_int.DATA, 0); HAL_Delay(1);//some delay before clocking data in. HAL_GPIO_WritePin(oled_int.OLED_IO, oled_int.CLK, 1);//shift reg clk HAL_Delay(1); HAL_GPIO_WritePin(oled_int.OLED_IO, oled_int.CLK, 0);//shift reg clk //makes the bit before the MSB become the MSB. E.g. bit 7 is now removed and the binary digit in bit 6 is in bit 7 data *= 2; } // Strobe data in. HAL_GPIO_WritePin(oled_int.OLED_IO, oled_int.E, 1); HAL_Delay(1); HAL_GPIO_WritePin(oled_int.OLED_IO, oled_int.E, 0); HAL_Delay(1); } // Writes command into OLED void oled_write_cmd(char cmd) { char temp; temp = cmd & 0xF0;//mask out the lower 4bits for 4bit operation of OLED oled_load(temp); temp = cmd << 4;//shift Lower 4 bits oled_load(temp); } // Writes character data into OLED void oled_write_data(char word) { char temp; temp = word & 0xF0;//mask out the lower 4bits for 4bit operation of OLED temp++;//setup the bit for RS oled_load(temp); temp = word << 4; temp++;//RS selection bit oled_load(temp); } // Writes a sentence into the OLED + line selection void oled_write_line(char array[]) { for(int i=0;array[i]!=0;i++) { oled_write_data(array[i]); } } // Writes in the middle of the OLED + line selection void oled_write_centre_line(char array[20]) { int counter, spaces; for(int i=0; array[i]!=0;i++) { counter++; } spaces=(16-counter)/2; while(spaces > 0) { oled_write_data(' '); spaces--; } for(int i=0; array[i]!=0;i++) { oled_write_data(array[i]); } } // Displays integer values. Do note that if int value is 0, it will not be displayed. void display_int(unsigned int number) { char array[10]; int i,x; for( i=0;number > 0;i++) { x = number % 10; number /= 10; array[i] = x + 0x30; } i--; while(i >= 0) { oled_write_data(array[i]); i--; } } // Sets cursor position on the OLED display (2 line OLED) void oled_pos(int x, int y) { if(x == 1) // Line 1 { oled_write_cmd(0x80 + y); } else if(x == 2) // Line 2 { oled_write_cmd(0xC0 + y); } } // Clears the OLED display void oled_clear() { oled_write_cmd(0x01); }
{ "content_hash": "c01d5e72558b9a87b946cc62546929ae", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 117, "avg_line_length": 25.57068062827225, "alnum_prop": 0.6552006552006552, "repo_name": "hyantechnologies/insta-qrp", "id": "f276ae78abe9912abc707e17e9aec1ba7a4c0f0b", "size": "4884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Firmware/Insta-QRP/Src/oled.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "10223" }, { "name": "C", "bytes": "3277787" }, { "name": "C++", "bytes": "69440" } ], "symlink_target": "" }
require "log4r" module Vagrant module Plugin module V1 # This is the superclass for all V1 plugins. class Plugin # Special marker that can be used for action hooks that matches # all action sequences. ALL_ACTIONS = :__all_actions__ # The logger for this class. LOGGER = Log4r::Logger.new("vagrant::plugin::v1::plugin") # Set the root class up to be ourself, so that we can reference this # from within methods which are probably in subclasses. ROOT_CLASS = self # Returns a list of registered plugins for this version. # # @return [Array] def self.registered @registry || [] end # Set the name of the plugin. The moment that this is called, the # plugin will be registered and available. Before this is called, a # plugin does not exist. The name must be unique among all installed # plugins. # # @param [String] name Name of the plugin. # @return [String] The name of the plugin. def self.name(name=UNSET_VALUE) # Get or set the value first, so we have a name for logging when # we register. result = get_or_set(:name, name) # The plugin should be registered if we're setting a real name on it register! if name != UNSET_VALUE # Return the result result end # Sets a human-friendly descrition of the plugin. # # @param [String] value Description of the plugin. # @return [String] Description of the plugin. def self.description(value=UNSET_VALUE) get_or_set(:description, value) end # Registers a callback to be called when a specific action sequence # is run. This allows plugin authors to hook into things like VM # bootup, VM provisioning, etc. # # @param [Symbol] name Name of the action. # @return [Array] List of the hooks for the given action. def self.action_hook(name, &block) # Get the list of hooks for the given hook name data[:action_hooks] ||= {} hooks = data[:action_hooks][name.to_sym] ||= [] # Return the list if we don't have a block return hooks if !block_given? # Otherwise add the block to the list of hooks for this action. hooks << block end # The given block will be called when this plugin is activated. The # activation block should be used to load any of the classes used by # the plugin other than the plugin definition itself. Vagrant only # guarantees that the plugin definition will remain backwards # compatible, but not any other classes (such as command base classes # or so on). Therefore, to avoid crashing future versions of Vagrant, # these classes should be placed in separate files and loaded in the # activation block. def self.activated(&block) data[:activation_block] = block if block_given? data[:activation_block] end # Defines additional command line commands available by key. The key # becomes the subcommand, so if you register a command "foo" then # "vagrant foo" becomes available. # # @param [String] name Subcommand key. def self.command(name=UNSET_VALUE, &block) data[:command] ||= Registry.new if name != UNSET_VALUE # Validate the name of the command if name.to_s !~ /^[-a-z0-9]+$/i raise InvalidCommandName, "Commands can only contain letters, numbers, and hyphens" end # Register a new command class only if a name was given. data[:command].register(name.to_sym, &block) end # Return the registry data[:command] end # Defines additional configuration keys to be available in the # Vagrantfile. The configuration class should be returned by a # block passed to this method. This is done to ensure that the class # is lazy loaded, so if your class inherits from any classes that # are specific to Vagrant 1.0, then the plugin can still be defined # without breaking anything in future versions of Vagrant. # # @param [String] name Configuration key. def self.config(name=UNSET_VALUE, &block) data[:config] ||= Registry.new # Register a new config class only if a name was given. data[:config].register(name.to_sym, &block) if name != UNSET_VALUE # Return the registry data[:config] end # Defines an "easy hook," which gives an easier interface to hook # into action sequences. def self.easy_hook(position, name, &block) if ![:before, :after].include?(position) raise InvalidEasyHookPosition, "must be :before, :after" end # This is the command sent to sequences to insert insert_method = "insert_#{position}".to_sym # Create the hook hook = Easy.create_hook(&block) # Define an action hook that listens to all actions and inserts # the hook properly if the sequence contains what we're looking for action_hook(ALL_ACTIONS) do |seq| index = seq.index(name) seq.send(insert_method, index, hook) if index end end # Defines an "easy command," which is a command with limited # functionality but far less boilerplate required over traditional # commands. Easy commands let you make basic commands quickly and # easily. # # @param [String] name Name of the command, how it will be invoked # on the command line. def self.easy_command(name, &block) command(name) { Easy.create_command(name, &block) } end # Defines an additionally available guest implementation with # the given key. # # @param [String] name Name of the guest. def self.guest(name=UNSET_VALUE, &block) data[:guests] ||= Registry.new # Register a new guest class only if a name was given data[:guests].register(name.to_sym, &block) if name != UNSET_VALUE # Return the registry data[:guests] end # Defines an additionally available host implementation with # the given key. # # @param [String] name Name of the host. def self.host(name=UNSET_VALUE, &block) data[:hosts] ||= Registry.new # Register a new host class only if a name was given data[:hosts].register(name.to_sym, &block) if name != UNSET_VALUE # Return the registry data[:hosts] end # Registers additional provisioners to be available. # # @param [String] name Name of the provisioner. def self.provisioner(name=UNSET_VALUE, &block) data[:provisioners] ||= Registry.new # Register a new provisioner class only if a name was given data[:provisioners].register(name.to_sym, &block) if name != UNSET_VALUE # Return the registry data[:provisioners] end # Activates the current plugin. This shouldn't be called publicly. def self.activate! if !data[:activated_called] LOGGER.info("Activating plugin: #{self.name}") data[:activated_called] = true # Call the activation block block = activated block.call if block end end # Registers the plugin. This makes the plugin actually work with # Vagrant. Prior to registering, the plugin is merely a skeleton. # # This shouldn't be called by the general public. Plugins are automatically # registered when they are given a name. def self.register!(plugin=nil) plugin ||= self # Register only on the root class return ROOT_CLASS.register!(plugin) if self != ROOT_CLASS # Register it into the list @registry ||= [] if !@registry.include?(plugin) LOGGER.info("Registered plugin: #{plugin.name}") @registry << plugin end end # This unregisters the plugin. Note that to re-register the plugin # you must call `register!` again. def self.unregister!(plugin=nil) plugin ||= self # Unregister only on the root class return ROOT_CLASS.unregister!(plugin) if self != ROOT_CLASS # Unregister it from the registry @registry ||= [] if @registry.include?(plugin) LOGGER.info("Unregistered: #{plugin.name}") @registry.delete(plugin) end end protected # Sentinel value denoting that a value has not been set. UNSET_VALUE = Object.new # Returns the internal data associated with this plugin. # # @return [Hash] def self.data @data ||= {} end # Helper method that will set a value if a value is given, or otherwise # return the already set value. # # @param [Symbol] key Key for the data # @param [Object] value Value to store. # @return [Object] Stored value. def self.get_or_set(key, value=UNSET_VALUE) # If no value is to be set, then return the value we have already set return data[key] if value.eql?(UNSET_VALUE) # Otherwise set the value data[key] = value end end end end end
{ "content_hash": "9407932f874ea60a933736614d21f8df", "timestamp": "", "source": "github", "line_count": 272, "max_line_length": 97, "avg_line_length": 36.05882352941177, "alnum_prop": 0.5954323001631321, "repo_name": "rickard-von-essen/vagrant", "id": "decc7aaaec41b39e168709ee7d03c32a45922bda", "size": "9808", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/vagrant/plugin/v1/plugin.rb", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.apache.hadoop.hive.metastore; import java.io.IOException; import java.util.HashMap; import javax.security.auth.login.LoginException; import javax.security.sasl.AuthenticationException; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.metastore.conf.MetastoreConf; import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars; import org.apache.hadoop.hive.metastore.security.TUGIContainingTransport; import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils; import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge; import org.apache.hadoop.hive.metastore.security.MetastoreDelegationTokenManager; import org.apache.thrift.transport.layered.TFramedTransport; import org.apache.thrift.transport.TSaslServerTransport; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.apache.thrift.transport.TTransportFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class helps in some aspects of authentication. It creates the proper Thrift classes for the * given configuration as well as helps with authenticating requests. * * This is copied from HiveAuthFactory and modified to be used for HMS. But we should see if we can * use same code for both Hive and HMS. */ public class AuthFactory { private static final Logger LOG = LoggerFactory.getLogger(AuthFactory.class); private HadoopThriftAuthBridge.Server saslServer; private String authTypeStr; private final String transportMode; private String hadoopAuth; private MetastoreDelegationTokenManager delegationTokenManager = null; private boolean useFramedTransport; private boolean executeSetUGI; private Configuration conf; public AuthFactory(HadoopThriftAuthBridge bridge, Configuration conf, Object baseHandler) throws HiveMetaException, TTransportException { // For now metastore only operates in binary mode. It would be good if we could model an HMS // as a ThriftCliService, but right now that's too much tied with HiveServer2. this.conf = conf; transportMode = "binary"; authTypeStr = MetastoreConf.getVar(conf, MetastoreConf.ConfVars.THRIFT_METASTORE_AUTHENTICATION); useFramedTransport = MetastoreConf.getBoolVar(conf, ConfVars.USE_THRIFT_FRAMED_TRANSPORT); executeSetUGI = MetastoreConf.getBoolVar(conf, ConfVars.EXECUTE_SET_UGI); // Secured mode communication with Hadoop // Blend this with THRIFT_METASTORE_AUTHENTICATION, for now they are separate. useSasl // should be set to true when authentication is anything other than NONE. Or we should use a // separate configuration for that? // In case of HS2, this is defined by configuration HADOOP_SECURITY_AUTHENTICATION, which // indicates the authentication used by underlying HDFS. In case of metastore SASL and hadoop // authentication seem to be tied up. But with password based SASL we might have to break // this coupling. Should we provide HADOOP_SECURITY_AUTHENTICATION for hadoop too, or use // USE_THRIFT_SASL itself to indicate that the underlying Hadoop is kerberized. if (StringUtils.isBlank(authTypeStr)) { authTypeStr = AuthConstants.AuthTypes.NOSASL.getAuthName(); } if (MetastoreConf.getBoolVar(conf, MetastoreConf.ConfVars.USE_THRIFT_SASL)) { hadoopAuth = "kerberos"; // If SASL is enabled but no authentication method is specified, we use only kerberos as an // authentication mechanism. if (authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.NOSASL.getAuthName())) { authTypeStr = AuthConstants.AuthTypes.KERBEROS.getAuthName(); } } else { hadoopAuth = "simple"; } LOG.info("Using authentication " + authTypeStr + " with kerberos authentication " + (isSASLWithKerberizedHadoop() ? "enabled." : "disabled")); if (isSASLWithKerberizedHadoop()) { // we are in secure mode. if (useFramedTransport) { throw new HiveMetaException("Framed transport is not supported with SASL enabled."); } saslServer = bridge.createServer(MetastoreConf.getVar(conf, MetastoreConf.ConfVars.KERBEROS_KEYTAB_FILE), MetastoreConf.getVar(conf, ConfVars.KERBEROS_PRINCIPAL), MetastoreConf.getVar(conf, ConfVars.CLIENT_KERBEROS_PRINCIPAL)); // Start delegation token manager delegationTokenManager = new MetastoreDelegationTokenManager(); try { delegationTokenManager.startDelegationTokenSecretManager(conf, baseHandler, HadoopThriftAuthBridge.Server.ServerMode.METASTORE); saslServer.setSecretManager(delegationTokenManager.getSecretManager()); } catch (IOException e) { throw new TTransportException("Failed to start token manager", e); } } } TTransportFactory getAuthTransFactory(boolean useSSL, Configuration conf) throws LoginException { TTransportFactory transportFactory; TSaslServerTransport.Factory serverTransportFactory; if (isSASLWithKerberizedHadoop()) { try { if (useFramedTransport) { throw new LoginException("Framed transport is not supported with SASL enabled."); } serverTransportFactory = saslServer.createSaslServerTransportFactory( MetaStoreUtils.getMetaStoreSaslProperties(conf, useSSL)); transportFactory = saslServer.wrapTransportFactoryInClientUGI(serverTransportFactory); } catch (TTransportException e) { throw new LoginException(e.getMessage()); } if (authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.KERBEROS.getAuthName())) { // no-op } else if (authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.NONE.getAuthName()) || authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.LDAP.getAuthName()) || authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.PAM.getAuthName()) || authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.CUSTOM.getAuthName()) || authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.CONFIG.getAuthName())) { try { MetaStorePlainSaslHelper.init(); LOG.debug("Adding server definition for PLAIN SaSL with authentication "+ authTypeStr + " to transport factory " + serverTransportFactory); serverTransportFactory.addServerDefinition("PLAIN", authTypeStr, null, new HashMap<String, String>(), new MetaStorePlainSaslHelper.PlainServerCallbackHandler(authTypeStr, conf)); } catch (AuthenticationException e) { throw new LoginException("Error setting callback handler" + e); } } else { throw new LoginException("Unsupported authentication type " + authTypeStr); } } else { if (authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.NONE.getAuthName()) || authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.LDAP.getAuthName()) || authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.PAM.getAuthName()) || authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.CUSTOM.getAuthName()) || authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.CONFIG.getAuthName())) { if (useFramedTransport) { throw new LoginException("Framed transport is not supported with password based " + "authentication enabled."); } if (executeSetUGI) { throw new LoginException("Setting " + ConfVars.EXECUTE_SET_UGI + " is not supported " + "with password based authentication enabled."); } LOG.info("Using plain SASL transport factory with " + authTypeStr + " authentication"); transportFactory = MetaStorePlainSaslHelper.getPlainTransportFactory(authTypeStr, conf); } else if (authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.NOSASL.getAuthName())) { if (executeSetUGI) { transportFactory = useFramedTransport ? new ChainedTTransportFactory(new TFramedTransport.Factory(), new TUGIContainingTransport.Factory()) :new TUGIContainingTransport.Factory(); } else { transportFactory = useFramedTransport ? new TFramedTransport.Factory() : new TTransportFactory(); } } else { throw new LoginException("Unsupported authentication type " + authTypeStr); } } return transportFactory; } public HadoopThriftAuthBridge.Server getSaslServer() throws IllegalStateException { if (!isSASLWithKerberizedHadoop() || null == saslServer) { throw new IllegalStateException("SASL server is not setup"); } return saslServer; } public MetastoreDelegationTokenManager getDelegationTokenManager() throws IllegalStateException { if (!isSASLWithKerberizedHadoop() || null == saslServer) { throw new IllegalStateException("SASL server is not setup"); } return delegationTokenManager; } public boolean isSASLWithKerberizedHadoop() { return "kerberos".equalsIgnoreCase(hadoopAuth) && !authTypeStr.equalsIgnoreCase(AuthConstants.AuthTypes.NOSASL.getAuthName()); } private static final class ChainedTTransportFactory extends TTransportFactory { private final TTransportFactory parentTransFactory; private final TTransportFactory childTransFactory; private ChainedTTransportFactory( TTransportFactory parentTransFactory, TTransportFactory childTransFactory) { this.parentTransFactory = parentTransFactory; this.childTransFactory = childTransFactory; } @Override public TTransport getTransport(TTransport trans) throws TTransportException { return childTransFactory.getTransport(parentTransFactory.getTransport(trans)); } } }
{ "content_hash": "e05bdf04be12f8410fdc67adc6516513", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 105, "avg_line_length": 47.333333333333336, "alnum_prop": 0.7275653923541248, "repo_name": "jcamachor/hive", "id": "84ae7b51814ee5043fe9c0080827b7142d39395c", "size": "10745", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/AuthFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "54376" }, { "name": "Batchfile", "bytes": "845" }, { "name": "C", "bytes": "28218" }, { "name": "C++", "bytes": "45308" }, { "name": "CSS", "bytes": "5157" }, { "name": "GAP", "bytes": "179697" }, { "name": "HTML", "bytes": "58711" }, { "name": "HiveQL", "bytes": "7606577" }, { "name": "Java", "bytes": "53149057" }, { "name": "JavaScript", "bytes": "43855" }, { "name": "M4", "bytes": "2276" }, { "name": "PHP", "bytes": "148097" }, { "name": "PLSQL", "bytes": "5261" }, { "name": "PLpgSQL", "bytes": "302587" }, { "name": "Perl", "bytes": "319842" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Python", "bytes": "408662" }, { "name": "Roff", "bytes": "5379" }, { "name": "SQLPL", "bytes": "409" }, { "name": "Shell", "bytes": "299497" }, { "name": "TSQL", "bytes": "2560286" }, { "name": "Thrift", "bytes": "144733" }, { "name": "XSLT", "bytes": "20199" }, { "name": "q", "bytes": "320552" } ], "symlink_target": "" }
<?php /** * * Created by mtils on 11.08.19 at 11:53. **/ namespace Ems\Routing; use Ems\Contracts\Core\Exceptions\Termination; use Ems\Contracts\Core\SupportsCustomFactory; use Ems\Contracts\Routing\Input; use Ems\Contracts\Routing\MiddlewareCollection as MiddlewareCollectionContract; use Ems\Core\Exceptions\UnConfiguredException; use Ems\Core\Response; use Ems\Core\Support\CustomFactorySupport; use Ems\Contracts\Expression\ConstraintParsingMethods; use Ems\Skeleton\ProxyInputHandler; /** * Class RouteMiddleware * * This class runs any per route middleware (that was assigned by Route::middleware(). * * @package Ems\Routing */ class RouteMiddleware implements SupportsCustomFactory { use CustomFactorySupport; use ConstraintParsingMethods; /** * @var MiddlewareCollectionContract */ protected $middlewareCollection; public function __construct(MiddlewareCollectionContract $middlewareCollection=null) { $this->middlewareCollection = $middlewareCollection ?: new MiddlewareCollection(); } /** * Run the request trough the assigned route middlewares. * * @param Input $input * @param callable $next * @return Response * * @throws \ReflectionException */ public function __invoke(Input $input, callable $next) { if (!$input->isRouted()) { throw new UnConfiguredException('The input has to be routed to get handled by ' . static::class . '.'); } $route = $input->getMatchedRoute(); $middlewares = $route->middlewares; if (!$middlewares) { return $next($input); } $this->configureCollection($middlewares); try { return $this->middlewareCollection->__invoke($input); } catch (Termination $termination) { return $next($input); } } protected function configureCollection(array $middlewares) { $this->middlewareCollection->clear(); foreach ($middlewares as $middlewareCommand) { $constraints = $this->parseConstraint($middlewareCommand); foreach ($constraints as $middlewareName=>$parameters) { $this->middlewareCollection->add($middlewareCommand, $middlewareName, $parameters); } } $this->middlewareCollection->add('termination', new ProxyInputHandler(function (Input $input) { throw new Termination(); })); } /** * No normalizing needed here. * * @param string $name * * @return string **/ protected function normalizeConstraintName($name) { return $name; } }
{ "content_hash": "4f3b92e5124cae55289dea0f814cce64", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 115, "avg_line_length": 26.84, "alnum_prop": 0.646795827123696, "repo_name": "mtils/php-ems", "id": "2a0e2a452ad9d5a982d09eb3b907baa6aef35f86", "size": "2684", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Ems/Routing/RouteMiddleware.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "4490502" }, { "name": "Shell", "bytes": "1138" } ], "symlink_target": "" }
{% extends "layout_unbranded.html" %} {% block page_title %} GOV.UK prototype kit {% endblock %} {% block content %} <main id="content" role="main"> <div class="grid-row"> <div class="column-two-thirds"> <div id="global-breadcrumb"> <a class="link-back" href="results_confirm2?search=DD678910C">Back</a> </div> <h1 class="heading-large">DD678910C</h1> <!--<div class="panel panel-border-wide alert-warning">Has automatic pension credits. Check is these apply before issuing a statement or answering enquiries. </div>--> </div> </div> <div class="grid-row"> <div class="column-one-half column-one-half-left"> <h2 class="heading-medium">Print and send a forecast</h2> <p>Enter name and address to send the forecast.</p> <form action="issue_address_customer_DD678910C" method="get" class="form"> <div class="form-group"> <fieldset> <legend style="font-weight: 700"> Send forecast to the customer or a third party? </legend> <label for="radio-part-2" class="block-label"> <input id="radio-part-2" type="radio" name="thirdparties" value="Customer" checked="checked"> Customer </label> <label for="radio-part-3" class="block-label"> <input id="radio-part-3" type="radio" name="thirdparties" value="Third party"> Third party </label> </fieldset> </div> <input type="submit" class="button" value="Continue"> </form> </div> <div class="column-one-half column-one-half-right"> <h2 class="heading-medium">Deal with enquiries</h2> <p>Get information that will help to answer customer queries.</p> <p><a href="forecast_DD678910C#lie-forecast" class="button">View information</a></p> </div> </div> </main> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript"> // function show(elementId) { // document.getElementById("id1").style.display = "none"; // document.getElementById("id2").style.display = "block"; // document.getElementById(elementId).style.display = "block"; // } $(document).on('click', '#calculate', function () { $('#id1').hide(); $('#id2').show(); }); </script> {% endblock %}
{ "content_hash": "84c2891db4d12dff41d3172518ed030a", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 188, "avg_line_length": 42.8125, "alnum_prop": 0.5262773722627737, "repo_name": "steven-borthwick/check-support", "id": "269a0ff7a6e1b2d7c447799fe014d0d3e3a6c888", "size": "2740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/overseasv2/overseas_choice_DD678910C.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19101" }, { "name": "HTML", "bytes": "6924034" }, { "name": "JavaScript", "bytes": "119841" }, { "name": "Shell", "bytes": "1872" } ], "symlink_target": "" }
package iht.controllers.application.exemptions.qualifyingBody import iht.config.AppConfig import iht.controllers.application.ApplicationControllerTest import iht.models.application.exemptions.QualifyingBody import iht.testhelpers.CommonBuilder import iht.views.html.application.exemption.qualifyingBody.qualifying_body_value import org.scalatest.BeforeAndAfter import play.api.data.Form import play.api.mvc.{AnyContentAsFormUrlEncoded, MessagesControllerComponents, Request} import play.api.test.Helpers._ import uk.gov.hmrc.play.bootstrap.frontend.controller.FrontendController /** * Created by jennygj on 26/08/16. */ class QualifyingBodyValueControllerTest extends ApplicationControllerTest with BeforeAndAfter { val qualifyingBody1 = QualifyingBody(Some("1"), Some("Qualifying Body 1"), Some(BigDecimal(324))) val qualifyingBody2 = QualifyingBody(Some("2"), Some("Qualifying Body 2"), Some(BigDecimal(65454))) val referrerURL = "localhost:9070" protected abstract class TestController extends FrontendController(mockControllerComponents) with QualifyingBodyValueController { override val cc: MessagesControllerComponents = mockControllerComponents override implicit val appConfig: AppConfig = mockAppConfig override val qualifyingBodyValueView: qualifying_body_value = app.injector.instanceOf[qualifying_body_value] } def qualifyingBodyValueController = new TestController { override val authConnector = mockAuthConnector override val cachingConnector = mockCachingConnector override val ihtConnector = mockIhtConnector } def qualifyingBodyValueControllerNotAuthorised = new TestController { override val authConnector = mockAuthConnector override val cachingConnector = mockCachingConnector override val ihtConnector = mockIhtConnector } def createMocksForQualifyingBodyValue = { val ad = CommonBuilder.buildApplicationDetails copy (qualifyingBodies = Seq(qualifyingBody1)) createMocksForApplication(mockCachingConnector, mockIhtConnector, appDetails = Some(ad), getAppDetails = true, saveAppDetails = true, storeAppDetailsInCache = true) } def createMocksForQualifyingBodyValueWithTwoItems = { val ad = CommonBuilder.buildApplicationDetails copy (qualifyingBodies = Seq(qualifyingBody1, qualifyingBody2)) createMocksForApplication(mockCachingConnector, mockIhtConnector, appDetails = Some(ad), getAppDetails = true, saveAppDetails = true, storeAppDetailsInCache = true) } lazy val resultOnPageLoadNotAuthorised = qualifyingBodyValueControllerNotAuthorised.onPageLoad(createFakeRequest(isAuthorised = false)) def resultOnEditPageLoadNotAuthorised(id: String) = qualifyingBodyValueControllerNotAuthorised.onEditPageLoad(id)(createFakeRequest(isAuthorised = false)) def resultOnSubmitNotAuthorised(request: Request[AnyContentAsFormUrlEncoded]) = qualifyingBodyValueControllerNotAuthorised.onSubmit(request) def resultOnEditSubmitNotAuthorised(id: String) = qualifyingBodyValueControllerNotAuthorised.onEditSubmit(id)(createFakeRequest(isAuthorised = false)) lazy val resultOnPageLoad = qualifyingBodyValueController.onPageLoad(createFakeRequest(authRetrieveNino = false)) def resultOnEditPageLoad(id: String) = qualifyingBodyValueController.onEditPageLoad(id)(createFakeRequest()) def resultOnSubmit(request: Request[AnyContentAsFormUrlEncoded]) = qualifyingBodyValueController.onSubmit(request) def resultOnEditSubmit(id: String)(request: Request[AnyContentAsFormUrlEncoded]) = qualifyingBodyValueController.onEditSubmit(id)(request) def request(form: Form[_]) = createFakeRequestWithReferrerWithBody(referrerURL = referrerURL, host = "localhost:9070", data = form.data.toSeq) "QualifyingBodyValueControllerTest" must { "redirect to log in page onPageLoad if user is not logged in" in { status(resultOnPageLoadNotAuthorised) must be(SEE_OTHER) redirectLocation(resultOnPageLoadNotAuthorised) must be(Some(loginUrl)) } "redirect to log in page onEditPageLoad if user is not logged in" in { status(resultOnEditPageLoadNotAuthorised("1")) must be(SEE_OTHER) redirectLocation(resultOnEditPageLoadNotAuthorised("1")) must be(Some(loginUrl)) } "redirect to log in page onSubmit if user is not logged in" in { status(resultOnSubmitNotAuthorised(createFakeRequest(isAuthorised = false).withFormUrlEncodedBody(( "totalValue", "101.00")))) must be(SEE_OTHER) redirectLocation(resultOnSubmitNotAuthorised(createFakeRequest(isAuthorised = false).withFormUrlEncodedBody(( "totalValue", "101.00")))) must be(Some(loginUrl)) } "redirect to log in page onEditSubmit if user is not logged in" in { status(resultOnEditSubmitNotAuthorised("1")) must be(SEE_OTHER) redirectLocation(resultOnEditSubmitNotAuthorised("1")) must be(Some(loginUrl)) } "return OK onPageLoad" in { createMocksForQualifyingBodyValue status(resultOnPageLoad) must be(OK) } "display an error message when a non-numeric value is entered" in { createMocksForQualifyingBodyValue implicit val fakePostRequest = createFakeRequest().withFormUrlEncodedBody(("totalValue", "blaaaaah")).withMethod("POST") val result = resultOnSubmit(fakePostRequest) status(result) mustBe BAD_REQUEST contentAsString(result) must include("a problem") } "save new value with new ID to application details onSubmit and redirect to QB detail overview" in { createMocksForQualifyingBodyValue implicit val fakePostRequest = createFakeRequest().withFormUrlEncodedBody(("totalValue", "100")).withMethod("POST") val result = resultOnSubmit(fakePostRequest) status(result) mustBe SEE_OTHER redirectLocation(result) mustBe Some(iht.controllers.application.exemptions.qualifyingBody.routes.QualifyingBodyDetailsOverviewController.onEditPageLoad("2").url) val appDetails = verifyAndReturnSavedApplicationDetails(mockIhtConnector) appDetails.qualifyingBodies.size mustBe 2 appDetails.qualifyingBodies.tail.head mustBe QualifyingBody(Some("2"), None, Some(100)) } "display previously entered value on EditPageLoad" in { createMocksForQualifyingBodyValue contentAsString(resultOnEditPageLoad("1")) must include("324") } "amend existing value with ID 1 in application details onEditSubmit and redirect to QB detail overview" in { createMocksForQualifyingBodyValueWithTwoItems implicit val fakePostRequest = createFakeRequest().withFormUrlEncodedBody(("totalValue", "777")).withMethod("POST") val result = resultOnEditSubmit("1")(fakePostRequest) status(result) mustBe SEE_OTHER redirectLocation(result) mustBe Some(iht.controllers.application.exemptions.qualifyingBody.routes.QualifyingBodyDetailsOverviewController.onEditPageLoad("1").url) val appDetails = verifyAndReturnSavedApplicationDetails(mockIhtConnector) appDetails.qualifyingBodies.size mustBe 2 appDetails.qualifyingBodies.head mustBe QualifyingBody(Some("1"), Some("Qualifying Body 1"), Some(777)) } "amend existing value with ID 2 in application details onEditSubmit and redirect to QB detail overview" in { createMocksForQualifyingBodyValueWithTwoItems implicit val fakePostRequest = createFakeRequest().withFormUrlEncodedBody(("totalValue", "888")).withMethod("POST") val result = resultOnEditSubmit("2")(fakePostRequest) status(result) mustBe SEE_OTHER redirectLocation(result) mustBe Some(iht.controllers.application.exemptions.qualifyingBody.routes.QualifyingBodyDetailsOverviewController.onEditPageLoad("2").url) val appDetails = verifyAndReturnSavedApplicationDetails(mockIhtConnector) appDetails.qualifyingBodies.size mustBe 2 appDetails.qualifyingBodies.tail.head mustBe QualifyingBody(Some("2"), Some("Qualifying Body 2"), Some(888)) } "return an internal server error if onPageLoad for invalid ID is entered" in { createMocksForQualifyingBodyValue a[RuntimeException] mustBe thrownBy { await(resultOnEditPageLoad("10")) } } behave like controllerOnPageLoadWithNoExistingRegistrationDetails(mockCachingConnector, qualifyingBodyValueController.onPageLoad(createFakeRequest(authRetrieveNino = false))) } }
{ "content_hash": "c98ccb38f6c87d6de3e1302940f2eb1f", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 168, "avg_line_length": 46.01092896174863, "alnum_prop": 0.7781472684085511, "repo_name": "hmrc/iht-frontend", "id": "b81cba597bc0598e339978951092f9cc2b8c8495", "size": "9023", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "test/iht/controllers/application/exemptions/qualifyingBody/QualifyingBodyValueControllerTest.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Cycript", "bytes": "245093" }, { "name": "HTML", "bytes": "713728" }, { "name": "JavaScript", "bytes": "38292" }, { "name": "SCSS", "bytes": "26537" }, { "name": "Scala", "bytes": "3850086" }, { "name": "XSLT", "bytes": "241076" } ], "symlink_target": "" }
- Basic grammar imported from language-ruby and modified to handle comments
{ "content_hash": "7638d330530cdb9699049b54a52a80b9", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 75, "avg_line_length": 76, "alnum_prop": 0.8289473684210527, "repo_name": "Peekmo/atom-raxe-lang", "id": "ee15865dd2017809d7aebb5d6c513868f1b4a305", "size": "95", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "237" }, { "name": "CoffeeScript", "bytes": "71916" } ], "symlink_target": "" }
'use strict'; module.exports = function (grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'lib/*.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, jscs: { src: [ 'Gruntfile.js', 'lib/*.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { config: 'node_modules/bitexpert-cs-jscs/config/config.json' } }, // Before generating any new files, remove any previously-created files. clean: { tests: [ 'tmp' ] }, // Configuration to be run (and then tested). mntyjs: { cli: { options: { mountPoint: 'data-plugins' }, files: { src: [ 'test/fixtures/test.html' ] } } }, // Unit tests. nodeunit: { tests: [ 'test/*_test.js' ] } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-jscs'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'mntyjs', 'nodeunit']); // By default, lint and check style // @TODO: write and add tests here grunt.registerTask('default', ['jshint', 'jscs']); };
{ "content_hash": "2af0a0e26f1055e5f6fa103d91e53006", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 80, "avg_line_length": 25.205128205128204, "alnum_prop": 0.43540183112919634, "repo_name": "bitExpert/grunt-mntyjs", "id": "33260078c264b25ea8d819f3ee3816d4e00bbb69", "size": "2113", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Gruntfile.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "7357" } ], "symlink_target": "" }
import * as ActionType from './actions'; import * as StatusType from 'konux/common/constants/statusType'; import * as NotificationType from './notificationType'; import * as SwitchStatusType from './switch/statusType'; import * as AxelType from './axelType'; import * as ChartType from './actions/chartType'; import * as Routes from './routes'; import * as PopupTypes from './popupType'; export { ActionType, StatusType, NotificationType, SwitchStatusType, AxelType, ChartType, Routes, PopupTypes };
{ "content_hash": "3b07ad23a17ccbb2a151fe319f026699", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 111, "avg_line_length": 50, "alnum_prop": 0.76, "repo_name": "Haaarp/geo", "id": "ce1093a1f69b21443759dc5bfc1860b6762a215e", "size": "500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/analytics/constants/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "145157" }, { "name": "HTML", "bytes": "598634" }, { "name": "JavaScript", "bytes": "4568889" } ], "symlink_target": "" }
export { assertResolversPresent } from './assertResolversPresent'; export { chainResolvers } from './chainResolvers'; export { addResolversToSchema } from './addResolversToSchema'; export { checkForResolveTypeResolver } from './checkForResolveTypeResolver'; export { extendResolversFromInterfaces } from './extendResolversFromInterfaces'; export * from './makeExecutableSchema'; export * from './types'; export * from './merge-schemas';
{ "content_hash": "989fe6f1a691089cdc51076683455caf", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 80, "avg_line_length": 54.625, "alnum_prop": 0.7803203661327232, "repo_name": "BigBoss424/portfolio", "id": "68212c5ac907de0fe4970224c57f86be7e9570d5", "size": "437", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v8/development/node_modules/@graphql-tools/load/node_modules/@graphql-tools/schema/index.d.ts", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.sshd.common.signature; import java.security.KeyPair; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.Factory; import org.apache.sshd.common.NamedFactory; import org.apache.sshd.common.RuntimeSshException; import org.apache.sshd.common.config.keys.PublicKeyEntryDecoder; import org.apache.sshd.common.keyprovider.AbstractKeyPairProvider; import org.apache.sshd.common.keyprovider.KeyPairProvider; import org.apache.sshd.common.util.ValidateUtils; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.junit.After; import org.junit.Before; /** * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a> */ public abstract class AbstractSignatureFactoryTestSupport extends BaseTestSupport { private SshServer sshd; private SshClient client; private int port; private final String keyType; private final int keySize; protected AbstractSignatureFactoryTestSupport(String keyType, int keySize) { this.keyType = ValidateUtils.checkNotNullAndNotEmpty(keyType, "No key type specified"); ValidateUtils.checkTrue(keySize > 0, "Invalid key size: %d", keySize); this.keySize = keySize; } public final int getKeySize() { return keySize; } public final String getKeyType() { return keyType; } @Before public void setUp() throws Exception { sshd = setupTestServer(); } @After public void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } if (client != null) { client.stop(); } } protected void testKeyPairProvider(PublicKeyEntryDecoder<?, ?> decoder, List<NamedFactory<Signature>> signatures) throws Exception { testKeyPairProvider(getKeyType(), getKeySize(), decoder, signatures); } protected void testKeyPairProvider( final String keyName, final int keySize, final PublicKeyEntryDecoder<?, ?> decoder, List<NamedFactory<Signature>> signatures) throws Exception { testKeyPairProvider(keyName, new Factory<Iterable<KeyPair>>() { @Override public Iterable<KeyPair> create() { try { KeyPair kp = decoder.generateKeyPair(keySize); System.out.println("Generated key pair for " + keyName + "[" + keySize + "]"); return Collections.singletonList(kp); } catch (Exception e) { throw new RuntimeSshException(e); } } }, signatures); } protected void testKeyPairProvider( final String keyName, final Factory<Iterable<KeyPair>> factory, List<NamedFactory<Signature>> signatures) throws Exception { final Iterable<KeyPair> iter = factory.create(); testKeyPairProvider(new AbstractKeyPairProvider() { @Override public Iterable<KeyPair> loadKeys() { return iter; } }, signatures); } protected void testKeyPairProvider(KeyPairProvider provider, List<NamedFactory<Signature>> signatures) throws Exception { sshd.setKeyPairProvider(provider); sshd.start(); port = sshd.getPort(); client = setupTestClient(); client.setSignatureFactories(signatures); client.start(); try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { s.addPasswordIdentity(getCurrentTestName()); // allow a rather long timeout since generating some keys may take some time s.auth().verify(30L, TimeUnit.SECONDS); } finally { client.stop(); } } }
{ "content_hash": "19ad1c626e118e013d6e9e6ee39df1d5", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 137, "avg_line_length": 35.203539823008846, "alnum_prop": 0.6601307189542484, "repo_name": "avthart/mina-sshd", "id": "14a88b3eedd4b925c8247d8656d9a05c87a31318", "size": "4779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6194" }, { "name": "HTML", "bytes": "5769" }, { "name": "Java", "bytes": "3506181" }, { "name": "Shell", "bytes": "13910" } ], "symlink_target": "" }
var Transport = (function () { 'use strict'; var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, sharedCache = new LruCache(10); // constructor // ----------- function Transport(o) { o = o || {}; this.cancelled = false; this.lastUrl = null; this._send = o.transport ? callbackToDeferred(o.transport) : $.ajax; this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get; // eh, should this even exist? relying on the browser's cache may be enough this._cache = o.cache === false ? new LruCache(0) : sharedCache; } // static methods // -------------- Transport.setMaxPendingRequests = function setMaxPendingRequests(num) { maxPendingRequests = num; }; Transport.resetCache = function resetCache() { sharedCache.reset(); }; // instance methods // ---------------- _.mixin(Transport.prototype, { // ### private _get: function (url, o, cb) { var that = this, jqXhr; // #149: don't make a network request if there has been a cancellation // or if the url doesn't match the last url Transport#get was invoked with if (this.cancelled || url !== this.lastUrl) { return; } // a request is already in progress, piggyback off of it if (jqXhr = pendingRequests[url]) { jqXhr.done(done).fail(fail); } // under the pending request threshold, so fire off a request else if (pendingRequestsCount < maxPendingRequests) { pendingRequestsCount++; pendingRequests[url] = this._send(url, o).done(done).fail(fail).always(always); } // at the pending request threshold, so hang out in the on deck circle else { this.onDeckRequestArgs = [].slice.call(arguments, 0); } function done(resp) { cb && cb(null, resp); that._cache.set(url, resp); } function fail() { cb && cb(true); } function always() { pendingRequestsCount--; delete pendingRequests[url]; // ensures request is always made for the last query if (that.onDeckRequestArgs) { that._get.apply(that, that.onDeckRequestArgs); that.onDeckRequestArgs = null; } } }, // ### public get: function (url, o, cb) { var resp; if (_.isFunction(o)) { cb = o; o = {}; } this.cancelled = false; this.lastUrl = url; // in-memory cache hit if (resp = this._cache.get(url)) { // defer to stay consistent with behavior of ajax call _.defer(function () { cb && cb(null, resp); }); } else { this._get(url, o, cb); } // return bool indicating whether or not a cache hit occurred return !!resp; }, cancel: function () { this.cancelled = true; } }); return Transport; // helper functions // ---------------- function callbackToDeferred(fn) { return function customSendWrapper(url, o) { var deferred = $.Deferred(); fn(url, o, onSuccess, onError); return deferred; function onSuccess(resp) { // defer in case fn is synchronous, otherwise done // and always handlers will be attached after the resolution _.defer(function () { deferred.resolve(resp); }); } function onError(err) { // defer in case fn is synchronous, otherwise done // and always handlers will be attached after the resolution _.defer(function () { deferred.reject(err); }); } }; } })();
{ "content_hash": "22bbf15be5048fcf47cb2d860436c2a4", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 80, "avg_line_length": 23.55128205128205, "alnum_prop": 0.5623298856831791, "repo_name": "quaintm/octopus", "id": "baca28dfc62f4b2274357f2526a409fadedb544a", "size": "3813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "octopus/static/libs/typeahead.js/src/bloodhound/transport.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "428142" }, { "name": "JavaScript", "bytes": "2354678" }, { "name": "Makefile", "bytes": "5620" }, { "name": "PHP", "bytes": "38" }, { "name": "Python", "bytes": "110341" }, { "name": "Shell", "bytes": "5547" } ], "symlink_target": "" }
/* 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 org.flowable.spring.test.fieldinjection; import java.util.Map; import org.flowable.engine.common.impl.util.CollectionUtil; import org.flowable.engine.test.Deployment; import org.flowable.spring.impl.test.SpringFlowableTestCase; import org.flowable.task.api.Task; import org.springframework.test.context.ContextConfiguration; /** * @author Joram Barrez */ @ContextConfiguration("classpath:org/flowable/spring/test/fieldinjection/fieldInjectionSpringTest-context.xml") public class ServiceTaskFieldInjectionTest extends SpringFlowableTestCase { @Deployment public void testDelegateExpressionWithSingletonBean() { runtimeService.startProcessInstanceByKey("delegateExpressionSingleton", CollectionUtil.singletonMap("input", 100)); Task task = taskService.createTaskQuery().singleResult(); Map<String, Object> variables = taskService.getVariables(task.getId()); Integer resultServiceTask1 = (Integer) variables.get("resultServiceTask1"); assertEquals(202, resultServiceTask1.intValue()); Integer resultServiceTask2 = (Integer) variables.get("resultServiceTask2"); assertEquals(579, resultServiceTask2.intValue()); // Verify only one instance was created assertEquals(1, SingletonDelegateExpressionBean.INSTANCE_COUNT.get()); } @Deployment public void testDelegateExpressionWithPrototypeBean() { runtimeService.startProcessInstanceByKey("delegateExpressionPrototype", CollectionUtil.singletonMap("input", 100)); Task task = taskService.createTaskQuery().singleResult(); Map<String, Object> variables = taskService.getVariables(task.getId()); Integer resultServiceTask1 = (Integer) variables.get("resultServiceTask1"); assertEquals(202, resultServiceTask1.intValue()); Integer resultServiceTask2 = (Integer) variables.get("resultServiceTask2"); assertEquals(579, resultServiceTask2.intValue()); // Verify TWO INSTANCES were created assertEquals(2, PrototypeDelegateExpressionBean.INSTANCE_COUNT.get()); } }
{ "content_hash": "26b0676bd7812240f04be05e17574251", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 123, "avg_line_length": 43.47540983606557, "alnum_prop": 0.7530165912518854, "repo_name": "gro-mar/flowable-engine", "id": "9e64c9efc9e28b9d21815d8162a6e61fcb260e6d", "size": "2652", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "modules/flowable-spring/src/test/java/org/flowable/spring/test/fieldinjection/ServiceTaskFieldInjectionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "96556" }, { "name": "Batchfile", "bytes": "166" }, { "name": "CSS", "bytes": "657911" }, { "name": "HTML", "bytes": "864813" }, { "name": "Java", "bytes": "21964973" }, { "name": "JavaScript", "bytes": "12440227" }, { "name": "Shell", "bytes": "9556" } ], "symlink_target": "" }
package org.sakaiproject.tool.impl; import org.apache.commons.collections.iterators.IteratorChain; import org.apache.commons.lang.mutable.MutableLong; import org.sakaiproject.event.api.UsageSession; import org.sakaiproject.id.api.IdManager; import org.sakaiproject.thread_local.api.ThreadLocalManager; import org.sakaiproject.tool.api.*; import org.sakaiproject.util.IteratorEnumeration; import org.sakaiproject.util.RequestFilter; import org.sakaiproject.util.ResourceLoader; import javax.servlet.ServletContext; import javax.servlet.http.*; import java.io.Serializable; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /************************************************************************************************************************************************* * Entity: Session Also is an HttpSession ************************************************************************************************************************************************/ public class MySession implements Session, HttpSession, Serializable { /** * Value that identifies the version of this class that has been Serialized. * 1 = original definition * 2 = added expirationTimeSuggestion */ private static final long serialVersionUID = 2L; /** * The possible time this Session may be inactive and available for expiration. * This value is an optimization for Terracotta clustered environments, to avoid * faulting object in, unless we have a best guess that it may be out of date. * We also choose not to use the m_accessed field directly, to avoid updating the * SHARED (on every box) data structure, except every inactive/2 period. */ protected final MutableLong expirationTimeSuggestion; /** Hold attributes in a Map. */ protected Map<String, Object> m_attributes = new ConcurrentHashMap<String, Object>(); /** Hold toolSessions in a Map, by placement id. */ protected Map<String, MyLittleSession> m_toolSessions = new ConcurrentHashMap<String, MyLittleSession>(); /** Hold context toolSessions in a Map, by context (webapp) id. */ protected Map<String, MyLittleSession> m_contextSessions = new ConcurrentHashMap<String, MyLittleSession>(); /** The creation time of the session. */ protected long m_created = 0; /** The session id. */ protected String m_id = null; /** Time last accessed (via getSession()). */ protected long m_accessed = 0; /** Seconds of inactive time before being automatically invalidated - 0 turns off this feature. */ protected int m_inactiveInterval; /** The user id for this session. */ protected String m_userId = null; /** The user enterprise id for this session. */ protected String m_userEid = null; /** True while the session is valid. */ protected boolean m_valid = true; /** * SessionManager */ private transient SessionManager sessionManager; private transient SessionStore sessionStore; private transient ThreadLocalManager threadLocalManager; private transient IdManager idManager; private transient boolean TERRACOTTA_CLUSTER; private transient NonPortableSession m_nonPortalSession; private transient SessionAttributeListener sessionListener; private transient RebuildBreakdownService rebuildBreakdownService; public MySession(SessionManager sessionManager, String id, ThreadLocalManager threadLocalManager, IdManager idManager, SessionStore sessionStore, SessionAttributeListener sessionListener, int inactiveInterval, NonPortableSession nonPortableSession, MutableLong expirationTimeSuggestion, RebuildBreakdownService rebuildBreakdownService) { this.sessionManager = sessionManager; m_id = id; this.threadLocalManager = threadLocalManager; this.idManager = idManager; this.sessionStore = sessionStore; this.sessionListener = sessionListener; m_inactiveInterval = inactiveInterval; m_nonPortalSession = nonPortableSession; m_created = System.currentTimeMillis(); m_accessed = m_created; this.expirationTimeSuggestion = expirationTimeSuggestion; resetExpirationTimeSuggestion(); // set the TERRACOTTA_CLUSTER flag resolveTerracottaClusterProperty(); this.rebuildBreakdownService = rebuildBreakdownService; } /** * @return true if the session is valid OR false otherwise */ public boolean isValid() { return m_valid; } protected void resolveTransientFields() { // These are spelled out instead of using imports, to be explicit org.sakaiproject.component.api.ComponentManager compMgr = org.sakaiproject.component.cover.ComponentManager.getInstance(); sessionManager = (SessionManager)compMgr.get(org.sakaiproject.tool.api.SessionManager.class); sessionStore = (SessionStore)compMgr.get(org.sakaiproject.tool.api.SessionStore.class); threadLocalManager = (ThreadLocalManager)compMgr.get(org.sakaiproject.thread_local.api.ThreadLocalManager.class); idManager = (IdManager)compMgr.get(org.sakaiproject.id.api.IdManager.class); // set the TERRACOTTA_CLUSTER flag resolveTerracottaClusterProperty(); m_nonPortalSession = new MyNonPortableSession(); sessionListener = (SessionAttributeListener)compMgr.get(org.sakaiproject.tool.api.SessionBindingListener.class); } protected void resolveTerracottaClusterProperty() { String clusterTerracotta = System.getProperty("sakai.cluster.terracotta"); TERRACOTTA_CLUSTER = "true".equals(clusterTerracotta); } /** * @inheritDoc */ public Object getAttribute(String name) { Object target = m_attributes.get(name); if ((target == null) && (m_nonPortalSession != null)) { target = m_nonPortalSession.getAttribute(name); } return target; } /** * @inheritDoc */ public Enumeration getAttributeNames() { Set<String> nonPortableAttributeNames = m_nonPortalSession.getAllAttributes().keySet(); IteratorChain ic = new IteratorChain(m_attributes.keySet().iterator(),nonPortableAttributeNames.iterator()); return new IteratorEnumeration(ic); } /** * @inheritDoc */ public long getCreationTime() { return m_created; } /** * @inheritDoc */ public String getId() { return m_id; } /** * @inheritDoc */ public long getLastAccessedTime() { return m_accessed; } /** * @inheritDoc */ public int getMaxInactiveInterval() { return m_inactiveInterval; } /** * @inheritDoc */ public void setMaxInactiveInterval(int interval) { m_inactiveInterval = interval; resetExpirationTimeSuggestion(); // added for KNL-1088 } /** * @inheritDoc */ public String getUserEid() { return m_userEid; } /** * @inheritDoc */ public void setUserEid(String eid) { m_userEid = eid; } /** * @inheritDoc */ public String getUserId() { return m_userId; } /** * @inheritDoc */ public void setUserId(String uid) { m_userId = uid; } /** * @inheritDoc */ public void invalidate() { String sessionId = getId(); destroy(); // ensure that the session cache is cleared when session is invalidated if (rebuildBreakdownService != null) { rebuildBreakdownService.purgeSessionFromStorageById(sessionId); } } /** * TESTING ONLY * Special method to destroy a session without purging the sessions storage data */ public void destroy() { m_valid = false; String sessionId = getId(); synchronized (this) { clear(); sessionStore.remove(sessionId); } // if this is the current session, remove it if (this.equals(this.sessionManager.getCurrentSession())) { this.sessionManager.setCurrentSession(null); } } /** * @return the current request associated with this Session */ public HttpServletRequest currentRequest() { HttpServletRequest req = (HttpServletRequest) this.threadLocalManager.get(RequestFilter.CURRENT_HTTP_REQUEST); return req; } /** * @return info about the map attributes for debugging purposes mostly */ public Map<String, String> currentAttributesSummary() { LinkedHashMap<String,String> data = new LinkedHashMap<String, String>(); data.put("ID",this.m_id); data.put("userId",this.m_userId); data.put("userEid",this.m_userEid); data.put("created",this.m_created+""); data.put("accessed",this.m_accessed+""); data.put("valid",this.m_valid+""); for (Map.Entry<String, Object> entry : ((Map<String,Object>) m_attributes).entrySet()) { data.put(entry.getKey(), convertValueToString(entry.getValue())); } for (Iterator i = m_toolSessions.entrySet().iterator(); i.hasNext();) { Map.Entry e = (Map.Entry) i.next(); ToolSession s = (ToolSession) e.getValue(); String sKey = "TS_"+s.getId()+"_"; data.put(sKey+"placementId", s.getPlacementId()); Enumeration<String> keys = s.getAttributeNames(); while (keys.hasMoreElements()) { String key = keys.nextElement(); Object val = s.getAttribute(key); data.put(sKey+key, convertValueToString(val)); } } for (Iterator i = m_contextSessions.entrySet().iterator(); i.hasNext();) { Map.Entry e = (Map.Entry) i.next(); ContextSession s = (ContextSession) e.getValue(); String sKey = "CS_"+s.getId()+"_"; data.put(sKey+"contextId", s.getContextId()); Enumeration<String> keys = s.getAttributeNames(); while (keys.hasMoreElements()) { String key = keys.nextElement(); Object val = s.getAttribute(key); data.put(sKey+key, convertValueToString(val)); } } return data; } private String convertValueToString(Object value) { if (value == null) { return "NULL"; } try { if (value.getClass().isPrimitive() || value instanceof String || value instanceof Number || value instanceof Boolean) { return value.toString(); } else if (value.getClass().isArray()) { return value.getClass().getCanonicalName()+"("+Array.getLength(value)+")"; } else if (value instanceof ResourceLoader) { // have to do this since the ResourceLoader looks like a map but doesn't have most of the methods implemented (like size) return value.toString(); } else if (value instanceof UsageSession) { UsageSession us = (UsageSession) value; return value.getClass().getCanonicalName()+":("+us.getId()+")"; } else if (value instanceof Collection) { Collection c = (Collection) value; return value.getClass().getCanonicalName()+"["+c.size()+"]"; } else if (value instanceof Map) { Map m = (Map) value; return value.getClass().getCanonicalName()+"["+m.size()+"]"; } else { return value.getClass().getCanonicalName(); } } catch (Exception e) { return value.getClass().getCanonicalName()+":[e="+e.getMessage()+"]"; } } /** * {@inheritDoc} */ public void clear() { // move the attributes and tool sessions to local maps in a synchronized block so the unbinding happens only on one thread Map unbindMap = null; Map toolMap = null; Map contextMap = null; Map<String,Object> nonPortableMap = null; synchronized (this) { unbindMap = new HashMap(m_attributes); m_attributes.clear(); toolMap = new HashMap(m_toolSessions); m_toolSessions.clear(); contextMap = new HashMap(m_contextSessions); m_contextSessions.clear(); nonPortableMap = m_nonPortalSession.getAllAttributes(); m_nonPortalSession.clear(); } // clear each tool session for (Iterator i = toolMap.entrySet().iterator(); i.hasNext();) { Map.Entry e = (Map.Entry) i.next(); ToolSession t = (ToolSession) e.getValue(); t.clearAttributes(); } // clear each context session for (Iterator i = contextMap.entrySet().iterator(); i.hasNext();) { Map.Entry e = (Map.Entry) i.next(); ToolSession t = (ToolSession) e.getValue(); t.clearAttributes(); } // send unbind events for normal (possibly clustered) session data for (Iterator i = unbindMap.entrySet().iterator(); i.hasNext();) { Map.Entry e = (Map.Entry) i.next(); String name = (String) e.getKey(); Object value = e.getValue(); unBind(name, value); } // send unbind events for non clustered session data (in a clustered environment) for (Map.Entry<String, Object> e: nonPortableMap.entrySet()) { unBind(e.getKey(), e.getValue()); } } /** * {@inheritDoc} */ public void clearExcept(Collection names) { // save any attributes in names Map saveAttributes = new HashMap(); Map<String,Object> saveNonPortableAttributes = new HashMap<String,Object>(); for (Iterator i = names.iterator(); i.hasNext();) { String name = (String) i.next(); Object value = m_attributes.get(name); if (value != null) { // remove, but do NOT unbind m_attributes.remove(name); saveAttributes.put(name, value); } else { value = m_nonPortalSession.removeAttribute(name); if (value != null) { saveNonPortableAttributes.put(name, value); } } } // clear the remaining clear(); // restore the saved attributes for (Iterator i = saveAttributes.entrySet().iterator(); i.hasNext();) { Map.Entry e = (Map.Entry) i.next(); String name = (String) e.getKey(); Object value = e.getValue(); m_attributes.put(name, value); } for(Map.Entry<String,Object> e: saveNonPortableAttributes.entrySet()) { m_nonPortalSession.setAttribute(e.getKey(), e.getValue()); } } /** * @inheritDoc */ public void setActive() { m_accessed = System.currentTimeMillis(); updateExpirationTimeSuggestion(); } protected void updateExpirationTimeSuggestion() { long now = System.currentTimeMillis(); long diff = expirationTimeSuggestion.longValue() - now; long max = getMaxInactiveIntervalMillis(); if (diff < (max/2)) { resetExpirationTimeSuggestion(); } } protected void resetExpirationTimeSuggestion() { expirationTimeSuggestion.setValue(System.currentTimeMillis() + getMaxInactiveIntervalMillis()); } protected long getMaxInactiveIntervalMillis() { return getMaxInactiveInterval() * 1000L; } /** * @inheritDoc */ public void removeAttribute(String name) { // remove Object value = m_attributes.remove(name); if ((value == null) && (m_nonPortalSession != null)) { value = m_nonPortalSession.removeAttribute(name); } // unbind event unBind(name, value); } /** * @inheritDoc */ public void setAttribute(String name, Object value) { // treat a set to null as a remove if (value == null) { removeAttribute(name); } else { Object old = null; // If this is not a terracotta clustered environment then immediately // place the attribute in the normal data structure // Otherwise, if this *IS* a TERRACOTTA_CLUSTER, then check the current // tool id against the tool whitelist, to see if attributes from this // tool should be clustered, or not. if ((!TERRACOTTA_CLUSTER) || (sessionStore.isCurrentToolClusterable())) { old = m_attributes.put(name, value); } else { old = m_nonPortalSession.setAttribute(name, value); } // bind event bind(name, value); // unbind event if old exiss if (old != null) { unBind(name, old); } } } /** * @inheritDoc */ public ToolSession getToolSession(String placementId) { MyLittleSession t = m_toolSessions.get(placementId); if (t == null) { NonPortableSession nPS = new MyNonPortableSession(); t = new MyLittleSession(MyLittleSession.TYPE_TOOL, sessionManager,idManager.createUuid(),this,placementId, threadLocalManager, sessionListener,sessionStore,nPS); m_toolSessions.put(placementId, t); // try to populate the tool id and context when the session is created if (sessionStore instanceof SessionComponent) { String sakaiToolId = ((SessionComponent)sessionStore).identifyCurrentTool(); t.setSessionToolId(sakaiToolId); String context = ((SessionComponent)sessionStore).identifyCurrentContext(); t.setSessionContextId(context); } } // mark it as accessed t.setAccessed(); return t; } /** * @inheritDoc */ public ContextSession getContextSession(String contextId) { MyLittleSession t = m_contextSessions.get(contextId); if (t == null) { NonPortableSession nPS = new MyNonPortableSession(); t = new MyLittleSession(MyLittleSession.TYPE_CONTEXT, sessionManager, idManager.createUuid(),this,contextId, threadLocalManager,sessionListener,sessionStore,nPS); m_contextSessions.put(contextId, t); t.setSessionContextId(contextId); } // mark it as accessed t.setAccessed(); return t; } /** * Check if the session has become inactive * * @return true if the session is capable of becoming inactive and has done so, false if not. */ protected boolean isInactive() { return ((m_inactiveInterval > 0) && (System.currentTimeMillis() > (m_accessed + (m_inactiveInterval * 1000)))); } /** * {@inheritDoc} */ public boolean equals(Object obj) { if (!(obj instanceof Session)) { return false; } return ((Session) obj).getId().equals(getId()); } /** * {@inheritDoc} */ public int hashCode() { return getId().hashCode(); } /** * {@inheritDoc} */ public ServletContext getServletContext() { return (ServletContext) threadLocalManager.get(SessionComponent.CURRENT_SERVLET_CONTEXT); } /** * {@inheritDoc} */ public HttpSessionContext getSessionContext() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public Object getValue(String arg0) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public String[] getValueNames() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public void putValue(String arg0, Object arg1) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public void removeValue(String arg0) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public boolean isNew() { return false; } /** * Unbind the value if it's a SessionBindingListener. Also does the HTTP unbinding if it's a HttpSessionBindingListener. * * @param name * The attribute name bound. * @param value * The bond value. */ protected void unBind(String name, Object value) { if (value instanceof SessionBindingListener) { SessionBindingEvent event = new MySessionBindingEvent(name, this, value); ((SessionBindingListener) value).valueUnbound(event); } // also unbind any objects that are regular HttpSessionBindingListeners if (value instanceof HttpSessionBindingListener) { HttpSessionBindingEvent event = new HttpSessionBindingEvent(this, name, value); ((HttpSessionBindingListener) value).valueUnbound(event); } // Added for testing purposes. Very much unsure whether this is a proper // use of MySessionBindingEvent. if ( sessionListener != null ) { sessionListener.attributeRemoved(new MySessionBindingEvent(name, this, value)); } } /** * Bind the value if it's a SessionBindingListener. Also does the HTTP binding if it's a HttpSessionBindingListener. * * @param name * The attribute name bound. * @param value * The bond value. */ protected void bind(String name, Object value) { if (value instanceof SessionBindingListener) { SessionBindingEvent event = new MySessionBindingEvent(name, this, value); ((SessionBindingListener) value).valueBound(event); } // also bind any objects that are regular HttpSessionBindingListeners if (value instanceof HttpSessionBindingListener) { HttpSessionBindingEvent event = new HttpSessionBindingEvent(this, name, value); ((HttpSessionBindingListener) value).valueBound(event); } // Added for testing purposes. Very much unsure whether this is a proper // use of MySessionBindingEvent. if ( sessionListener != null ) { sessionListener.attributeAdded(new MySessionBindingEvent(name, this, value)); } } @Override public String toString() { return "MyS_"+m_userEid+"{" + m_id + ", userId='" + m_userId + '\'' + ", at=" + (m_attributes != null ? m_attributes.size() : 0) + ", ts=" + (m_toolSessions != null ? m_toolSessions.size() : 0) + ", cs=" + (m_contextSessions != null ? m_contextSessions.size() : 0) + ", " + (m_created > 0 ? new Date(m_created) : "?") + '}'; } }
{ "content_hash": "4b7bfb314e826c09540edd768c9f9a22", "timestamp": "", "source": "github", "line_count": 729, "max_line_length": 146, "avg_line_length": 28.790123456790123, "alnum_prop": 0.6636649514008005, "repo_name": "eemirtekin/Sakai-10.6-TR", "id": "d7f9041bf9af91a3eb1be18fab2f9b7c730cfea2", "size": "22079", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kernel/kernel-impl/src/main/java/org/sakaiproject/tool/impl/MySession.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "59098" }, { "name": "Batchfile", "bytes": "6366" }, { "name": "C++", "bytes": "6402" }, { "name": "CSS", "bytes": "2616828" }, { "name": "ColdFusion", "bytes": "146057" }, { "name": "HTML", "bytes": "5982358" }, { "name": "Java", "bytes": "49585098" }, { "name": "JavaScript", "bytes": "6722774" }, { "name": "Lasso", "bytes": "26436" }, { "name": "PHP", "bytes": "223840" }, { "name": "PLSQL", "bytes": "2163243" }, { "name": "Perl", "bytes": "102776" }, { "name": "Python", "bytes": "87575" }, { "name": "Ruby", "bytes": "3606" }, { "name": "Shell", "bytes": "33041" }, { "name": "SourcePawn", "bytes": "2274" }, { "name": "XSLT", "bytes": "607759" } ], "symlink_target": "" }
require 'spec_helper' describe 'assimilation' do let(:title) { 'assimilation' } ['Debian', 'RedHat'].each do |osfamily| describe "assimilation class without any parameters on #{osfamily}" do let(:params) {{ }} let(:facts) { { :osfamily => osfamily } } it { should create_class('assimilation') } it { should create_package('assimilation') } it { should create_file('/etc/assimilation.conf') } it { should create_file('/etc/assimilation.conf')\ .with_content(/^server pool.assimilation.org$/) } if osfamily == 'RedHat' it { should create_service('assimilationd') } else it { should create_service('assimilation') } end end end end
{ "content_hash": "d5f4ca4327e716ed8d942f806b97b847", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 75, "avg_line_length": 29.6, "alnum_prop": 0.6054054054054054, "repo_name": "seattle-biomed/puppet-assimilation", "id": "23db1799a81e90227ea8e9a3696f88efcfa26f96", "size": "740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/classes/example_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Puppet", "bytes": "6386" }, { "name": "Ruby", "bytes": "1236" } ], "symlink_target": "" }
package android.app; import android.content.Intent; import android.os.RemoteException; /** * This class provides access to the system alarm services. These allow you * to schedule your application to be run at some point in the future. When * an alarm goes off, the {@link Intent} that had been registered for it * is broadcast by the system, automatically starting the target application * if it is not already running. Registered alarms are retained while the * device is asleep (and can optionally wake the device up if they go off * during that time), but will be cleared if it is turned off and rebooted. * * <p>The Alarm Manager holds a CPU wake lock as long as the alarm receiver's * onReceive() method is executing. This guarantees that the phone will not sleep * until you have finished handling the broadcast. Once onReceive() returns, the * Alarm Manager releases this wake lock. This means that the phone will in some * cases sleep as soon as your onReceive() method completes. If your alarm receiver * called {@link android.content.Context#startService Context.startService()}, it * is possible that the phone will sleep before the requested service is launched. * To prevent this, your BroadcastReceiver and Service will need to implement a * separate wake lock policy to ensure that the phone continues running until the * service becomes available. * * <p><b>Note: The Alarm Manager is intended for cases where you want to have * your application code run at a specific time, even if your application is * not currently running. For normal timing operations (ticks, timeouts, * etc) it is easier and much more efficient to use * {@link android.os.Handler}.</b> * * <p>You do not * instantiate this class directly; instead, retrieve it through * {@link android.content.Context#getSystemService * Context.getSystemService(Context.ALARM_SERVICE)}. */ public class AlarmManager { /** * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()} * (wall clock time in UTC), which will wake up the device when * it goes off. */ public static final int RTC_WAKEUP = 0; /** * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()} * (wall clock time in UTC). This alarm does not wake the * device up; if it goes off while the device is asleep, it will not be * delivered until the next time the device wakes up. */ public static final int RTC = 1; /** * Alarm time in {@link android.os.SystemClock#elapsedRealtime * SystemClock.elapsedRealtime()} (time since boot, including sleep), * which will wake up the device when it goes off. */ public static final int ELAPSED_REALTIME_WAKEUP = 2; /** * Alarm time in {@link android.os.SystemClock#elapsedRealtime * SystemClock.elapsedRealtime()} (time since boot, including sleep). * This alarm does not wake the device up; if it goes off while the device * is asleep, it will not be delivered until the next time the device * wakes up. */ public static final int ELAPSED_REALTIME = 3; private final IAlarmManager mService; /** * package private on purpose */ AlarmManager(IAlarmManager service) { mService = service; } /** * Schedule an alarm. <b>Note: for timing operations (ticks, timeouts, * etc) it is easier and much more efficient to use * {@link android.os.Handler}.</b> If there is already an alarm scheduled * for the same IntentSender, it will first be canceled. * * <p>If the time occurs in the past, the alarm will be triggered * immediately. If there is already an alarm for this Intent * scheduled (with the equality of two intents being defined by * {@link Intent#filterEquals}), then it will be removed and replaced by * this one. * * <p> * The alarm is an intent broadcast that goes to a broadcast receiver that * you registered with {@link android.content.Context#registerReceiver} * or through the &lt;receiver&gt; tag in an AndroidManifest.xml file. * * <p> * Alarm intents are delivered with a data extra of type int called * {@link Intent#EXTRA_ALARM_COUNT Intent.EXTRA_ALARM_COUNT} that indicates * how many past alarm events have been accumulated into this intent * broadcast. Recurring alarms that have gone undelivered because the * phone was asleep may have a count greater than one when delivered. * * @param type One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC or * RTC_WAKEUP. * @param triggerAtMillis time in milliseconds that the alarm should go * off, using the appropriate clock (depending on the alarm type). * @param operation Action to perform when the alarm goes off; * typically comes from {@link PendingIntent#getBroadcast * IntentSender.getBroadcast()}. * * @see android.os.Handler * @see #setRepeating * @see #cancel * @see android.content.Context#sendBroadcast * @see android.content.Context#registerReceiver * @see android.content.Intent#filterEquals * @see #ELAPSED_REALTIME * @see #ELAPSED_REALTIME_WAKEUP * @see #RTC * @see #RTC_WAKEUP */ public void set(int type, long triggerAtMillis, PendingIntent operation) { try { mService.set(type, triggerAtMillis, operation); } catch (RemoteException ex) { } } /** * Schedule a repeating alarm. <b>Note: for timing operations (ticks, * timeouts, etc) it is easier and much more efficient to use * {@link android.os.Handler}.</b> If there is already an alarm scheduled * for the same IntentSender, it will first be canceled. * * <p>Like {@link #set}, except you can also * supply a rate at which the alarm will repeat. This alarm continues * repeating until explicitly removed with {@link #cancel}. If the time * occurs in the past, the alarm will be triggered immediately, with an * alarm count depending on how far in the past the trigger time is relative * to the repeat interval. * * <p>If an alarm is delayed (by system sleep, for example, for non * _WAKEUP alarm types), a skipped repeat will be delivered as soon as * possible. After that, future alarms will be delivered according to the * original schedule; they do not drift over time. For example, if you have * set a recurring alarm for the top of every hour but the phone was asleep * from 7:45 until 8:45, an alarm will be sent as soon as the phone awakens, * then the next alarm will be sent at 9:00. * * <p>If your application wants to allow the delivery times to drift in * order to guarantee that at least a certain time interval always elapses * between alarms, then the approach to take is to use one-time alarms, * scheduling the next one yourself when handling each alarm delivery. * * @param type One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP}, RTC or * RTC_WAKEUP. * @param triggerAtMillis time in milliseconds that the alarm should first * go off, using the appropriate clock (depending on the alarm type). * @param intervalMillis interval in milliseconds between subsequent repeats * of the alarm. * @param operation Action to perform when the alarm goes off; * typically comes from {@link PendingIntent#getBroadcast * IntentSender.getBroadcast()}. * * @see android.os.Handler * @see #set * @see #cancel * @see android.content.Context#sendBroadcast * @see android.content.Context#registerReceiver * @see android.content.Intent#filterEquals * @see #ELAPSED_REALTIME * @see #ELAPSED_REALTIME_WAKEUP * @see #RTC * @see #RTC_WAKEUP */ public void setRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation) { try { mService.setRepeating(type, triggerAtMillis, intervalMillis, operation); } catch (RemoteException ex) { } } /** * Available inexact recurrence intervals recognized by * {@link #setInexactRepeating(int, long, long, PendingIntent)} */ public static final long INTERVAL_FIFTEEN_MINUTES = 15 * 60 * 1000; public static final long INTERVAL_HALF_HOUR = 2*INTERVAL_FIFTEEN_MINUTES; public static final long INTERVAL_HOUR = 2*INTERVAL_HALF_HOUR; public static final long INTERVAL_HALF_DAY = 12*INTERVAL_HOUR; public static final long INTERVAL_DAY = 2*INTERVAL_HALF_DAY; /** * Schedule a repeating alarm that has inexact trigger time requirements; * for example, an alarm that repeats every hour, but not necessarily at * the top of every hour. These alarms are more power-efficient than * the strict recurrences supplied by {@link #setRepeating}, since the * system can adjust alarms' phase to cause them to fire simultaneously, * avoiding waking the device from sleep more than necessary. * * <p>Your alarm's first trigger will not be before the requested time, * but it might not occur for almost a full interval after that time. In * addition, while the overall period of the repeating alarm will be as * requested, the time between any two successive firings of the alarm * may vary. If your application demands very low jitter, use * {@link #setRepeating} instead. * * @param type One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP}, RTC or * RTC_WAKEUP. * @param triggerAtMillis time in milliseconds that the alarm should first * go off, using the appropriate clock (depending on the alarm type). This * is inexact: the alarm will not fire before this time, but there may be a * delay of almost an entire alarm interval before the first invocation of * the alarm. * @param intervalMillis interval in milliseconds between subsequent repeats * of the alarm. If this is one of INTERVAL_FIFTEEN_MINUTES, * INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_HALF_DAY, or INTERVAL_DAY * then the alarm will be phase-aligned with other alarms to reduce the * number of wakeups. Otherwise, the alarm will be set as though the * application had called {@link #setRepeating}. * @param operation Action to perform when the alarm goes off; * typically comes from {@link PendingIntent#getBroadcast * IntentSender.getBroadcast()}. * * @see android.os.Handler * @see #set * @see #cancel * @see android.content.Context#sendBroadcast * @see android.content.Context#registerReceiver * @see android.content.Intent#filterEquals * @see #ELAPSED_REALTIME * @see #ELAPSED_REALTIME_WAKEUP * @see #RTC * @see #RTC_WAKEUP * @see #INTERVAL_FIFTEEN_MINUTES * @see #INTERVAL_HALF_HOUR * @see #INTERVAL_HOUR * @see #INTERVAL_HALF_DAY * @see #INTERVAL_DAY */ public void setInexactRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation) { try { mService.setInexactRepeating(type, triggerAtMillis, intervalMillis, operation); } catch (RemoteException ex) { } } /** * Remove any alarms with a matching {@link Intent}. * Any alarm, of any type, whose Intent matches this one (as defined by * {@link Intent#filterEquals}), will be canceled. * * @param operation IntentSender which matches a previously added * IntentSender. * * @see #set */ public void cancel(PendingIntent operation) { try { mService.remove(operation); } catch (RemoteException ex) { } } /** * Set the system wall clock time. * Requires the permission android.permission.SET_TIME. * * @param millis time in milliseconds since the Epoch */ public void setTime(long millis) { try { mService.setTime(millis); } catch (RemoteException ex) { } } /** * Set the system default time zone. * Requires the permission android.permission.SET_TIME_ZONE. * * @param timeZone in the format understood by {@link java.util.TimeZone} */ public void setTimeZone(String timeZone) { try { mService.setTimeZone(timeZone); } catch (RemoteException ex) { } } }
{ "content_hash": "a5355017a26ec3391c5112f01c63de6d", "timestamp": "", "source": "github", "line_count": 291, "max_line_length": 91, "avg_line_length": 43.2852233676976, "alnum_prop": 0.6775960622419815, "repo_name": "haikuowuya/android_system_code", "id": "2fe682d1861f7521175d7bb8f850c6404a0e8b35", "size": "13215", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/android/app/AlarmManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "182432" }, { "name": "Java", "bytes": "124952631" } ], "symlink_target": "" }
class CCG::GameModel::GridSerializer CARD_SERIALIZER = CCG::GameModel::PlayedCardSerializer def self.load(value) grid = CCG::GameModel::Grid.new value.each do |row, col, card| grid[row, col] = CARD_SERIALIZER.load(card) end grid end def self.dump(value) grid = value.grid grid.map.reject { |_k, v| v.nil? }.map do |k, v| [k[0], k[1], CARD_SERIALIZER.dump(v)] end end end
{ "content_hash": "410137b3027b0c831f2fec3c06dd2506", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 56, "avg_line_length": 20.285714285714285, "alnum_prop": 0.6244131455399061, "repo_name": "JPricey/joejoejoe", "id": "dfa729becaa3a9123f788929add9fee8e64b9085", "size": "426", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/ccg/ccg/game_model/grid_serializer.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "127" }, { "name": "JavaScript", "bytes": "115948" }, { "name": "Ruby", "bytes": "95073" }, { "name": "Shell", "bytes": "50" } ], "symlink_target": "" }
package net.sf.farrago.plugin; import java.util.*; import net.sf.farrago.catalog.*; import net.sf.farrago.resource.*; import net.sf.farrago.util.*; /** * FarragoPluginCache is an abstract private cache for loading instances of * {@link FarragoPlugin} (and their component sub-objects). It requires an * underlying shared {@link FarragoObjectCache}. * * <p>This class is only a partial implementation. For an example of how to * build a full implementation, see {@link * net.sf.farrago.namespace.util.FarragoDataWrapperCache}. * * @author John V. Sichi * @version $Id$ */ public abstract class FarragoPluginCache extends FarragoCompoundAllocation { //~ Instance fields -------------------------------------------------------- private final Map<String, Object> mapMofIdToPlugin; private final FarragoObjectCache sharedCache; private final FarragoRepos repos; private final FarragoPluginClassLoader classLoader; //~ Constructors ----------------------------------------------------------- /** * Creates an empty cache. * * @param owner FarragoAllocationOwner for this cache, to make sure * everything gets discarded eventually * @param sharedCache underlying shared cache * @param repos FarragoRepos for wrapper initialization */ public FarragoPluginCache( FarragoAllocationOwner owner, FarragoObjectCache sharedCache, FarragoPluginClassLoader classLoader, FarragoRepos repos) { owner.addAllocation(this); this.sharedCache = sharedCache; this.repos = repos; this.classLoader = classLoader; this.mapMofIdToPlugin = new HashMap<String, Object>(); } //~ Methods ---------------------------------------------------------------- /** * @return the underlying repos */ public FarragoRepos getRepos() { return repos; } /** * @return the underlying shared cache */ public FarragoObjectCache getSharedCache() { return sharedCache; } /** * @return mapMofIdToPlugin */ public Map<String, Object> getMapMofIdToPlugin() { return mapMofIdToPlugin; } /** * Searches this cache for a plugin object identified by its catalog MofId. * * @param mofId MofId of plugin object being loaded * * @return cached instance or null if not yet cached */ protected Object searchPrivateCache(String mofId) { return mapMofIdToPlugin.get(mofId); } /** * Adds a plugin object to this cache. * * @param entry pinned entry from underlying shared cache; key must be * plugin object's catalog MofId * * @return cached plugin object */ protected Object addToPrivateCache(FarragoObjectCache.Entry entry) { // take ownership of the pinned cache entry addAllocation(entry); Object obj = entry.getValue(); mapMofIdToPlugin.put( (String) entry.getKey(), obj); return obj; } /** * Initializes a plugin instance. * * @param libraryName filename of jar containing plugin implementation * @param jarAttributeName name of jar attribute to use to determine class * name * @param options options with which to initialize plugin * * @return initialized plugin */ protected FarragoPlugin initializePlugin( String libraryName, String jarAttributeName, Properties options) { Class pluginClass = classLoader.loadClassFromLibraryManifest( libraryName, jarAttributeName); FarragoPlugin plugin; try { Object obj = classLoader.newPluginInstance(pluginClass); assert (obj instanceof FarragoPlugin) : obj.getClass(); plugin = (FarragoPlugin) obj; plugin.initialize(repos, options); plugin.setLibraryName(libraryName); } catch (Throwable ex) { throw FarragoResource.instance().PluginInitFailed.ex( repos.getLocalizedObjectName(libraryName), ex); } return plugin; } } // End FarragoPluginCache.java
{ "content_hash": "cd1b165f916c4c30ea1af46a3e201dba", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 80, "avg_line_length": 28.446666666666665, "alnum_prop": 0.6158893836419029, "repo_name": "julianhyde/luciddb", "id": "de575c96a9a183dd4de2bb224db727fcb70111fe", "size": "5065", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "farrago/src/net/sf/farrago/plugin/FarragoPluginCache.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Google\AdsApi\AdWords\v201609\cm; /** * This file was generated from WSDL. DO NOT EDIT. */ class BiddingStrategyOperation extends \Google\AdsApi\AdWords\v201609\cm\Operation { /** * @var \Google\AdsApi\AdWords\v201609\cm\SharedBiddingStrategy $operand */ protected $operand = null; /** * @param string $operator * @param string $OperationType * @param \Google\AdsApi\AdWords\v201609\cm\SharedBiddingStrategy $operand */ public function __construct($operator = null, $OperationType = null, $operand = null) { parent::__construct($operator, $OperationType); $this->operand = $operand; } /** * @return \Google\AdsApi\AdWords\v201609\cm\SharedBiddingStrategy */ public function getOperand() { return $this->operand; } /** * @param \Google\AdsApi\AdWords\v201609\cm\SharedBiddingStrategy $operand * @return \Google\AdsApi\AdWords\v201609\cm\BiddingStrategyOperation */ public function setOperand($operand) { $this->operand = $operand; return $this; } }
{ "content_hash": "0c9145001022e3c403c375dc30584e62", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 89, "avg_line_length": 24.23913043478261, "alnum_prop": 0.6493273542600897, "repo_name": "shakaran/googleads-php-lib", "id": "d0bd4e34ebbfcf0827ba9b40d874b5ef18ede310", "size": "1115", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Google/AdsApi/AdWords/v201609/cm/BiddingStrategyOperation.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "4066564" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Carrotware.CMS.Mvc.UI.Admin.Models { public class FileUpModel { public FileUpModel() { } [DataType(DataType.Upload)] [Display(Name = "Posted File")] public HttpPostedFileBase PostedFile { get; set; } } }
{ "content_hash": "2b9633b1f7827f60a61c220cb28db93b", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 52, "avg_line_length": 19.894736842105264, "alnum_prop": 0.7116402116402116, "repo_name": "ninianne98/CarrotCakeCMS-MVC", "id": "82af2d85a0ea38cd9f4eaee8b07802c41ca257ec", "size": "563", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CMSAdmin/Models/FileUpModel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "4241" }, { "name": "C#", "bytes": "1438086" }, { "name": "CSS", "bytes": "730642" }, { "name": "HTML", "bytes": "619502" }, { "name": "JavaScript", "bytes": "203691" }, { "name": "TSQL", "bytes": "1408975" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.implementation.serializer; import com.azure.core.exception.HttpResponseException; import com.azure.core.http.HttpMethod; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; import com.azure.core.http.MockHttpResponse; import com.azure.core.http.rest.Page; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.ResponseBase; import com.azure.core.implementation.http.UnexpectedExceptionInformation; import com.azure.core.util.Base64Url; import com.azure.core.util.DateTimeRfc1123; import com.azure.core.util.IterableStream; import com.azure.core.util.mocking.MockHttpResponseDecodeData; import com.azure.core.util.mocking.MockSerializerAdapter; import com.azure.core.util.serializer.JacksonAdapter; import com.azure.core.util.serializer.SerializerAdapter; import com.azure.core.util.serializer.SerializerEncoding; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests {@link HttpResponseBodyDecoder}. */ public class HttpResponseBodyDecoderTests { private static final JacksonAdapter ADAPTER = new JacksonAdapter(); private static final HttpRequest GET_REQUEST = new HttpRequest(HttpMethod.GET, "https://localhost"); private static final HttpRequest HEAD_REQUEST = new HttpRequest(HttpMethod.HEAD, "https://localhost"); @ParameterizedTest @MethodSource("invalidHttpResponseSupplier") public void invalidHttpResponse(HttpResponse response) { assertThrows(NullPointerException.class, () -> HttpResponseBodyDecoder.decodeByteArray(null, response, null, null)); } private static Stream<Arguments> invalidHttpResponseSupplier() { return Stream.of( // Null response. Arguments.of((HttpResponse) null), // Response without a request. Arguments.of(new MockHttpResponse(null, 200)), // Response with a request that is missing the HttpMethod. Arguments.of(new MockHttpResponse(new HttpRequest(null, "https://example.com"), 200)) ); } @ParameterizedTest @MethodSource("errorResponseSupplier") public void errorResponse(HttpResponse httpResponse, HttpResponseDecodeData decodeData, boolean isEmpty, Object expected) { StepVerifier.FirstStep<Object> firstStep = StepVerifier.create(httpResponse.getBodyAsByteArray() .mapNotNull(body -> HttpResponseBodyDecoder.decodeByteArray(body, httpResponse, ADAPTER, decodeData))); if (isEmpty) { firstStep.verifyComplete(); } else { firstStep.assertNext(actual -> assertEquals(expected, actual)).verifyComplete(); } } private static Stream<Arguments> errorResponseSupplier() { UnexpectedExceptionInformation exceptionInformation = new MockUnexpectedExceptionInformation( HttpResponseException.class, String.class); HttpResponseDecodeData noExpectedStatusCodes = new MockHttpResponseDecodeData(exceptionInformation); HttpResponseDecodeData expectedStatusCodes = new MockHttpResponseDecodeData(202, exceptionInformation); HttpResponse emptyResponse = new MockHttpResponse(GET_REQUEST, 300, (Object) null); HttpResponse response = new MockHttpResponse(GET_REQUEST, 300, "expected"); HttpResponse wrongGoodResponse = new MockHttpResponse(GET_REQUEST, 200, "good response"); return Stream.of( Arguments.of(emptyResponse, noExpectedStatusCodes, true, null), Arguments.of(emptyResponse, expectedStatusCodes, true, null), Arguments.of(response, noExpectedStatusCodes, false, "expected"), Arguments.of(response, expectedStatusCodes, false, "expected"), Arguments.of(wrongGoodResponse, expectedStatusCodes, false, "good response"), // Improperly formatted JSON string causes MalformedValueException. Arguments.of(emptyResponse, noExpectedStatusCodes, true, null) ); } @Test public void ioExceptionInErrorDeserializationReturnsEmpty() { JacksonAdapter ioExceptionThrower = new JacksonAdapter() { @Override public <T> T deserialize(InputStream inputStream, Type type, SerializerEncoding encoding) throws IOException { throw new IOException(); } }; HttpResponseDecodeData noExpectedStatusCodes = new MockHttpResponseDecodeData( new UnexpectedExceptionInformation(HttpResponseException.class)); HttpResponse response = new MockHttpResponse(GET_REQUEST, 300); assertNull(HttpResponseBodyDecoder.decodeByteArray(null, response, ioExceptionThrower, noExpectedStatusCodes)); } @Test public void headRequestReturnsEmpty() { HttpResponseDecodeData decodeData = new MockHttpResponseDecodeData(200); HttpResponse response = new MockHttpResponse(HEAD_REQUEST, 200); assertNull(HttpResponseBodyDecoder.decodeByteArray(null, response, ADAPTER, decodeData)); } @ParameterizedTest @MethodSource("nonDecodableResponseSupplier") public void nonDecodableResponse(HttpResponseDecodeData decodeData) { HttpResponse response = new MockHttpResponse(GET_REQUEST, 200); assertNull(HttpResponseBodyDecoder.decodeByteArray(null, response, ADAPTER, decodeData)); } private static Stream<Arguments> nonDecodableResponseSupplier() { // Types that will cause a response to be non decodable. HttpResponseDecodeData nullReturnType = new MockHttpResponseDecodeData(200, null, false); ParameterizedType fluxByteBuffer = mockParameterizedType(Flux.class, ByteBuffer.class); HttpResponseDecodeData fluxByteBufferReturnType = new MockHttpResponseDecodeData(200, fluxByteBuffer, false); ParameterizedType monoByteArray = mockParameterizedType(Mono.class, byte[].class); HttpResponseDecodeData monoByteArrayReturnType = new MockHttpResponseDecodeData(200, monoByteArray, false); ParameterizedType voidTypeResponse = mockParameterizedType(ResponseBase.class, int.class, Void.TYPE); HttpResponseDecodeData voidTypeResponseReturnType = new MockHttpResponseDecodeData(200, voidTypeResponse, false); ParameterizedType voidClassResponse = mockParameterizedType(ResponseBase.class, int.class, void.class); HttpResponseDecodeData voidClassResponseReturnType = new MockHttpResponseDecodeData(200, voidClassResponse, false); return Stream.of( Arguments.of(nullReturnType), Arguments.of(fluxByteBufferReturnType), Arguments.of(monoByteArrayReturnType), Arguments.of(voidTypeResponseReturnType), Arguments.of(voidClassResponseReturnType) ); } @Test public void emptyResponseReturnsMonoEmpty() { HttpResponse response = new MockHttpResponse(GET_REQUEST, 200, (Object) null); HttpResponseDecodeData decodeData = new MockHttpResponseDecodeData(200, String.class, true); assertNull(HttpResponseBodyDecoder.decodeByteArray(null, response, ADAPTER, decodeData)); } @ParameterizedTest @MethodSource("decodableResponseSupplier") public void decodableResponse(HttpResponse response, HttpResponseDecodeData decodeData, Object expected) { StepVerifier.create(response.getBodyAsByteArray() .mapNotNull(bytes -> HttpResponseBodyDecoder.decodeByteArray(bytes, response, ADAPTER, decodeData))) .assertNext(actual -> assertEquals(expected, actual)) .verifyComplete(); } private static Stream<Arguments> decodableResponseSupplier() { HttpResponseDecodeData stringDecodeData = new MockHttpResponseDecodeData(200, String.class, String.class, true); HttpResponse stringResponse = new MockHttpResponse(GET_REQUEST, 200, "hello"); HttpResponseDecodeData offsetDateTimeDecodeData = new MockHttpResponseDecodeData(200, OffsetDateTime.class, OffsetDateTime.class, true); OffsetDateTime offsetDateTimeNow = OffsetDateTime.now(ZoneOffset.UTC); HttpResponse offsetDateTimeResponse = new MockHttpResponse(GET_REQUEST, 200, offsetDateTimeNow); HttpResponseDecodeData dateTimeRfc1123DecodeData = new MockHttpResponseDecodeData(200, OffsetDateTime.class, DateTimeRfc1123.class, true); DateTimeRfc1123 dateTimeRfc1123Now = new DateTimeRfc1123(offsetDateTimeNow); HttpResponse dateTimeRfc1123Response = new MockHttpResponse(GET_REQUEST, 200, dateTimeRfc1123Now); HttpResponseDecodeData unixTimeDecodeData = new MockHttpResponseDecodeData(200, OffsetDateTime.class, OffsetDateTime.class, true); HttpResponse unixTimeResponse = new MockHttpResponse(GET_REQUEST, 200, offsetDateTimeNow); ParameterizedType stringList = mockParameterizedType(List.class, String.class); HttpResponseDecodeData stringListDecodeData = new MockHttpResponseDecodeData(200, stringList, String.class, true); List<String> list = Arrays.asList("hello", "azure"); HttpResponse stringListResponse = new MockHttpResponse(GET_REQUEST, 200, list); ParameterizedType mapStringString = mockParameterizedType(Map.class, String.class, String.class); HttpResponseDecodeData mapStringStringDecodeData = new MockHttpResponseDecodeData(200, mapStringString, String.class, true); Map<String, String> map = Collections.singletonMap("hello", "azure"); HttpResponse mapStringStringResponse = new MockHttpResponse(GET_REQUEST, 200, map); return Stream.of( Arguments.of(stringResponse, stringDecodeData, "hello"), Arguments.of(offsetDateTimeResponse, offsetDateTimeDecodeData, offsetDateTimeNow), Arguments.of(dateTimeRfc1123Response, dateTimeRfc1123DecodeData, new DateTimeRfc1123(dateTimeRfc1123Now.toString()).getDateTime()), Arguments.of(unixTimeResponse, unixTimeDecodeData, offsetDateTimeNow), Arguments.of(stringListResponse, stringListDecodeData, list), Arguments.of(mapStringStringResponse, mapStringStringDecodeData, map) ); } @Test public void decodeListBase64UrlResponse() { ParameterizedType parameterizedType = mockParameterizedType(List.class, byte[].class); HttpResponseDecodeData decodeData = new MockHttpResponseDecodeData(200, parameterizedType, Base64Url.class, true); List<Base64Url> base64Urls = Arrays.asList(new Base64Url("base"), new Base64Url("64")); HttpResponse response = new MockHttpResponse(GET_REQUEST, 200, base64Urls); StepVerifier.create(response.getBodyAsByteArray() .mapNotNull(body -> HttpResponseBodyDecoder.decodeByteArray(body, response, ADAPTER, decodeData))) .assertNext(actual -> { assertTrue(actual instanceof List); @SuppressWarnings("unchecked") List<byte[]> decoded = (List<byte[]>) actual; assertEquals(2, decoded.size()); assertArrayEquals(base64Urls.get(0).decodedBytes(), decoded.get(0)); assertArrayEquals(base64Urls.get(1).decodedBytes(), decoded.get(1)); }).verifyComplete(); } @SuppressWarnings("unchecked") @Test public void decodePageResponse() { HttpResponse response = new MockHttpResponse(GET_REQUEST, 200, new Page<String>() { @Override public IterableStream<String> getElements() { return IterableStream.of(null); } @Override public String getContinuationToken() { return null; } }); HttpResponseDecodeData pageDecodeData = new MockHttpResponseDecodeData(200, String.class, Page.class, true); HttpResponseDecodeData itemPageDecodeData = new MockHttpResponseDecodeData(200, String.class, ItemPage.class, true); StepVerifier.create(response.getBodyAsByteArray() .mapNotNull(body -> HttpResponseBodyDecoder.decodeByteArray(body, response, ADAPTER, pageDecodeData))) .assertNext(actual -> { assertTrue(actual instanceof Page); Page<String> page = (Page<String>) actual; assertFalse(page.getElements().iterator().hasNext()); assertNull(page.getContinuationToken()); }).verifyComplete(); StepVerifier.create(response.getBodyAsByteArray() .mapNotNull(body -> HttpResponseBodyDecoder.decodeByteArray(body, response, ADAPTER, itemPageDecodeData))) .assertNext(actual -> { assertTrue(actual instanceof Page); Page<String> page = (Page<String>) actual; assertFalse(page.getElements().iterator().hasNext()); assertNull(page.getContinuationToken()); }).verifyComplete(); } @Test public void malformedBodyReturnsError() { HttpResponse response = new MockHttpResponse(GET_REQUEST, 200, (Object) null); HttpResponseDecodeData decodeData = new MockHttpResponseDecodeData(200, String.class, String.class, true); assertThrows(HttpResponseException.class, () -> HttpResponseBodyDecoder.decodeByteArray( "malformed JSON string".getBytes(StandardCharsets.UTF_8), response, ADAPTER, decodeData)); } @Test public void ioExceptionReturnsError() throws IOException { HttpResponse response = new MockHttpResponse(GET_REQUEST, 200, "valid JSON string"); HttpResponseDecodeData decodeData = new MockHttpResponseDecodeData(200, String.class, String.class, true); SerializerAdapter serializer = new MockSerializerAdapter() { @Override public <T> T deserialize(byte[] bytes, Type type, SerializerEncoding encoding) throws IOException { throw new IOException(); } }; assertThrows(HttpResponseException.class, () -> HttpResponseBodyDecoder.decodeByteArray(new byte[0], response, serializer, decodeData)); } @ParameterizedTest @MethodSource("decodeTypeSupplier") public void decodeType(HttpResponse response, HttpResponseDecodeData data, Type expected) { assertEquals(expected, HttpResponseBodyDecoder.decodedType(response, data)); } private static Stream<Arguments> decodeTypeSupplier() { HttpResponse badResponse = new MockHttpResponse(GET_REQUEST, 400); HttpResponse headResponse = new MockHttpResponse(HEAD_REQUEST, 200); HttpResponse getResponse = new MockHttpResponse(GET_REQUEST, 200); HttpResponseDecodeData badResponseData = new MockHttpResponseDecodeData(-1, new UnexpectedExceptionInformation(HttpResponseException.class)); HttpResponseDecodeData nonDecodable = new MockHttpResponseDecodeData(200, void.class, false); HttpResponseDecodeData stringReturn = new MockHttpResponseDecodeData(200, String.class, true); ParameterizedType monoString = mockParameterizedType(Mono.class, String.class); HttpResponseDecodeData monoStringReturn = new MockHttpResponseDecodeData(200, monoString, true); ParameterizedType responseString = mockParameterizedType(Response.class, String.class); HttpResponseDecodeData responseStringReturn = new MockHttpResponseDecodeData(200, responseString, true); HttpResponseDecodeData headDecodeData = new MockHttpResponseDecodeData(200, null, false); return Stream.of( Arguments.of(badResponse, badResponseData, Object.class), Arguments.of(headResponse, headDecodeData, null), Arguments.of(getResponse, nonDecodable, null), Arguments.of(getResponse, stringReturn, String.class), Arguments.of(getResponse, monoStringReturn, String.class), Arguments.of(getResponse, responseStringReturn, String.class) ); } private static ParameterizedType mockParameterizedType(Type rawType, Type... actualTypeArguments) { return new ParameterizedType() { @Override public Type[] getActualTypeArguments() { return actualTypeArguments; } @Override public Type getRawType() { return rawType; } @Override public Type getOwnerType() { return null; } }; } private static final class MockUnexpectedExceptionInformation extends UnexpectedExceptionInformation { private final Class<?> exceptionBodyType; /** * Creates an UnexpectedExceptionInformation object with the given exception type and expected response body. * * @param exceptionType Exception type to be thrown. */ MockUnexpectedExceptionInformation(Class<? extends HttpResponseException> exceptionType, Class<?> exceptionBodyType) { super(exceptionType); this.exceptionBodyType = exceptionBodyType; } @Override public Class<? extends HttpResponseException> getExceptionType() { return super.getExceptionType(); } @Override public Class<?> getExceptionBodyType() { return exceptionBodyType; } } }
{ "content_hash": "882b4b3f257f5a0c26da313f17b0983d", "timestamp": "", "source": "github", "line_count": 401, "max_line_length": 122, "avg_line_length": 46.244389027431424, "alnum_prop": 0.7134383088869716, "repo_name": "Azure/azure-sdk-for-java", "id": "fa4018801369bd682d5809da82fa25eb19d8c280", "size": "18544", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoderTests.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
#ifndef __RotationAffector_H__ #define __RotationAffector_H__ #include "OgreMath.h" #include "OgreParticleFXPrerequisites.h" #include "OgreParticleAffector.h" #include "OgreStringInterface.h" namespace Ogre { /** This plugin subclass of ParticleAffector allows you to alter the rotation of particles. @remarks This class supplies the ParticleAffector implementation required to make the particle expand or contract in mid-flight. */ class _OgreParticleFXExport RotationAffector : public ParticleAffector { public: /// Command object for particle emitter - see ParamCommand class CmdRotationSpeedRangeStart : public ParamCommand { public: String doGet(const void* target) const; void doSet(void* target, const String& val); }; /// Command object for particle emitter - see ParamCommand class CmdRotationSpeedRangeEnd : public ParamCommand { public: String doGet(const void* target) const; void doSet(void* target, const String& val); }; /// Command object for particle emitter - see ParamCommand class CmdRotationRangeStart : public ParamCommand { public: String doGet(const void* target) const; void doSet(void* target, const String& val); }; /// Command object for particle emitter - see ParamCommand class CmdRotationRangeEnd : public ParamCommand { public: String doGet(const void* target) const; void doSet(void* target, const String& val); }; /** Default constructor. */ RotationAffector(ParticleSystem* psys); /** See ParticleAffector. */ void _initParticle(Particle* pParticle); /** See ParticleAffector. */ void _affectParticles(ParticleSystem* pSystem, Real timeElapsed); /** Sets the minimum rotation speed of particles to be emitted. */ void setRotationSpeedRangeStart(const Radian& angle); /** Sets the maximum rotation speed of particles to be emitted. */ void setRotationSpeedRangeEnd(const Radian& angle); /** Gets the minimum rotation speed of particles to be emitted. */ const Radian& getRotationSpeedRangeStart(void) const; /** Gets the maximum rotation speed of particles to be emitted. */ const Radian& getRotationSpeedRangeEnd(void) const; /** Sets the minimum rotation angle of particles to be emitted. */ void setRotationRangeStart(const Radian& angle); /** Sets the maximum rotation angle of particles to be emitted. */ void setRotationRangeEnd(const Radian& angle); /** Gets the minimum rotation of particles to be emitted. */ const Radian& getRotationRangeStart(void) const; /** Gets the maximum rotation of particles to be emitted. */ const Radian& getRotationRangeEnd(void) const; static CmdRotationSpeedRangeStart msRotationSpeedRangeStartCmd; static CmdRotationSpeedRangeEnd msRotationSpeedRangeEndCmd; static CmdRotationRangeStart msRotationRangeStartCmd; static CmdRotationRangeEnd msRotationRangeEndCmd; protected: /// Initial rotation speed of particles (range start) Radian mRotationSpeedRangeStart; /// Initial rotation speed of particles (range end) Radian mRotationSpeedRangeEnd; /// Initial rotation angle of particles (range start) Radian mRotationRangeStart; /// Initial rotation angle of particles (range end) Radian mRotationRangeEnd; }; } #endif
{ "content_hash": "d9766b8be2a28e49f65887f95ae0d769", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 100, "avg_line_length": 34.95238095238095, "alnum_prop": 0.6689373297002725, "repo_name": "jakzale/ogre", "id": "1d0dd6fea5be9d6ddc57e9962130709f305d4ec6", "size": "5029", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "PlugIns/ParticleFX/include/OgreRotationAffector.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4588107" }, { "name": "C++", "bytes": "20466233" }, { "name": "Java", "bytes": "5855" }, { "name": "Objective-C", "bytes": "562324" }, { "name": "Python", "bytes": "479296" }, { "name": "Shell", "bytes": "19333" }, { "name": "Visual Basic", "bytes": "1095" } ], "symlink_target": "" }
<?php // By default the code coverage files are written to the same directory // that contains the covered sourcecode files. Use this setting to change // the default behaviour and set a specific directory to write the files to. // If you change the default setting, please make sure to also configure // the same directory in phpunit_coverage.php. Also note that the webserver // needs write access to the directory. $GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = FALSE; if ( isset($_COOKIE['PHPUNIT_SELENIUM_TEST_ID']) && !isset($_GET['PHPUNIT_SELENIUM_TEST_ID']) && extension_loaded('xdebug')) { $GLOBALS['PHPUNIT_FILTERED_FILES'] = array(__FILE__); xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); } ?>
{ "content_hash": "947f0e111722f8021fce1632d31c119d", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 76, "avg_line_length": 39.1578947368421, "alnum_prop": 0.7244623655913979, "repo_name": "Harvard-ATG/Quizmo", "id": "59c868e9ed935c8e922d7c6a06aef36abdc31d94", "size": "2748", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "quizmo/protected/tests/phpunit/PHPUnit/Extensions/SeleniumTestCase/prepend.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "66565" }, { "name": "JavaScript", "bytes": "825235" }, { "name": "PHP", "bytes": "2843836" }, { "name": "Shell", "bytes": "6593" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <objects default-autowire="no" xmlns="http://www.springframework.net" xmlns:db="http://www.springframework.net/database"> <object name="TwitterJob" type="Spring.Scheduling.Quartz.MethodInvokingJobDetailFactoryObject, Spring.Scheduling.Quartz"> <property name="TargetObject" ref="TwitterWorker" /> <property name="TargetMethod" value="Run" /> <property name="Concurrent" value="false"/> </object> <object name ="TwitterWorker" type="uter.sociallistener.general.Jobs.TwitterJob,uter.sociallistener.general "> <property name="Connection" ref="CrmConnection" /> <property name="ConsumerKey" value="${Twitter.ConsumerKey}" /> <property name="ConsumerSecret" value="${Twitter.ConsumerSecret}" /> </object> <object id="TwitterJobTrigger" type="Spring.Scheduling.Quartz.CronTriggerObject, Spring.Scheduling.Quartz"> <property name="jobDetail" ref="TwitterJob" /> <property name="cronExpressionString" value="${Twitter.JobTriggerTime}"/> </object> <object name="FacebookJob" type="Spring.Scheduling.Quartz.MethodInvokingJobDetailFactoryObject, Spring.Scheduling.Quartz"> <property name="TargetObject" ref="FacebookWorker" /> <property name="TargetMethod" value="Run" /> <property name="Concurrent" value="false"/> </object> <object name ="FacebookWorker" type="uter.sociallistener.general.Jobs.FacebookJob,uter.sociallistener.general "> <property name="Connection" ref="CrmConnection" /> <property name="ConsumerKey" value="${Facebook.ConsumerKey}" /> <property name="ConsumerSecret" value="${Facebook.ConsumerSecret}" /> </object> <object id="FacebookJobTrigger" type="Spring.Scheduling.Quartz.CronTriggerObject, Spring.Scheduling.Quartz"> <property name="jobDetail" ref="FacebookJob" /> <property name="cronExpressionString" value="${Facebook.JobTriggerTime}"/> </object> <object name="CrmConnection" type="uter.sociallistener.general.CRM.Connection.CrmConnection, uter.sociallistener.general"> <property name="Url" value="${Crm.Host}" /> <property name="Domain" value="${Crm.UserDomain}" /> <property name="UserName" value="${Crm.UserName}" /> <property name="Password" value="${Crm.Password}" /> <property name="Organization" value="${Crm.Organisation}" /> </object> <object type="Spring.Scheduling.Quartz.SchedulerFactoryObject, Spring.Scheduling.Quartz" id="schedulerFactory"> <property name="triggers"> <list> <ref object="TwitterJobTrigger"/> <ref object="FacebookJobTrigger"/> </list> </property> <property name="autoStartup" value="true" /> </object> </objects>
{ "content_hash": "99f56bfa2531e2ecdb13fb8d191bdedd", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 125, "avg_line_length": 47.672413793103445, "alnum_prop": 0.6918625678119349, "repo_name": "Uter1007/socialmscrm", "id": "735306f5d1845d212653b455d1f0acd02987b36a", "size": "2767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "uter.sociallistener.general/Config/socialjob.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "119" }, { "name": "C#", "bytes": "256678" }, { "name": "CSS", "bytes": "1051" }, { "name": "JavaScript", "bytes": "45763" }, { "name": "Shell", "bytes": "331" } ], "symlink_target": "" }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- **************************************************************** --> <!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * --> <!-- * i.e. only iterate & print data where possible. Thanks, Jez. * --> <!-- **************************************************************** --> <html> <head> <!-- Generated by groovydoc --> <title>WoogaStrategies (Gradle Wooga Release plugin API)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="../../../../groovy.ico" type="image/x-icon" rel="shortcut icon"> <link href="../../../../groovy.ico" type="image/x-icon" rel="icon"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <body class="center"> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="WoogaStrategies (Gradle Wooga Release plugin API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <div> <ul class="navList"> <li><a href="../../../../index.html?wooga/gradle/release/utils/WoogaStrategies" target="_top">Frames</a></li> <li><a href="WoogaStrategies.html" target="_top">No Frames</a></li> </ul> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> Nested&nbsp;&nbsp;&nbsp;Field&nbsp;&nbsp;&nbsp;<li><a href="#property_summary">Property</a></li>&nbsp;&nbsp;&nbsp;Constructor&nbsp;&nbsp;&nbsp;Method&nbsp;&nbsp;&nbsp; </ul> <ul class="subNavList"> <li>&nbsp;|&nbsp;Detail:&nbsp;</li> Field&nbsp;&nbsp;&nbsp;<li><a href="#prop_detail">Property</a></li>&nbsp;&nbsp;&nbsp;Constructor&nbsp;&nbsp;&nbsp;Method&nbsp;&nbsp;&nbsp; </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">Package: <strong>wooga.gradle.release.utils</strong></div> <h2 title="[Groovy] Class WoogaStrategies" class="title">[Groovy] Class WoogaStrategies</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li><ul class="inheritance"></ul></li><li>wooga.gradle.release.utils.WoogaStrategies </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <p> Set of <CODE>SemVerStrategy</CODE> properties to determine current version. <p> All strategies are base on <a href="https://github.com/nebula-plugins/nebula-release-plugin">Nebular Release</a> or it's super set <a href="https://github.com/ajoberstar/gradle-git">Gradle Git</a>. </p> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== NESTED CLASS SUMMARY =========== --> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <!-- =========== FIELD SUMMARY =========== --> <!-- =========== PROPERTY SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="property_summary"><!-- --></a> <h3>Properties Summary</h3> <ul class="blockList"> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Properties Summary table, listing nested classes, and an explanation"> <caption><span>Properties</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Type</th> <th class="colLast" scope="col">Name and description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><strong>static&nbsp;org.ajoberstar.gradle.git.release.semver.PartialSemVerStrategy</strong></code>&nbsp;</td> <td class="colLast"><code><a href="#COUNT_INCREMENTED">COUNT_INCREMENTED</a></code><br></td> </tr> <tr class="rowColor"> <td class="colFirst"><code><strong>static&nbsp;org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code>&nbsp;</td> <td class="colLast"><code><a href="#DEVELOPMENT">DEVELOPMENT</a></code><br>Returns a version strategy to be used for <CODE>development</CODE> builds.</td> </tr> <tr class="altColor"> <td class="colFirst"><code><strong>static&nbsp;org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code>&nbsp;</td> <td class="colLast"><code><a href="#FINAL">FINAL</a></code><br>Returns a version strategy to be used for <CODE>final</CODE> builds.</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><strong>static&nbsp;org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code>&nbsp;</td> <td class="colLast"><code><a href="#PRE_RELEASE">PRE_RELEASE</a></code><br>Returns a version strategy to be used for <CODE>pre-release</CODE>/<CODE>candidate</CODE> builds.</td> </tr> <tr class="altColor"> <td class="colFirst"><code><strong>static&nbsp;org.ajoberstar.gradle.git.release.semver.SemVerStrategy</strong></code>&nbsp;</td> <td class="colLast"><code><a href="#SNAPSHOT">SNAPSHOT</a></code><br>Returns a version strategy to be used for <CODE>snapshot</CODE> builds.</td> </tr> </table> </ul> </li> </ul> <!-- =========== ELEMENT SUMMARY =========== --> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"><!-- --></a> <h3>Inherited Methods Summary</h3> <ul class="blockList"> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Inherited Methods Summary table"> <caption><span>Inherited Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Methods inherited from class</th> <th class="colLast" scope="col">Name</th> </tr> <tr class="altColor"> <td class="colFirst"><code>class java.lang.Object</code></td> <td class="colLast"><code>java.lang.Object#wait(long, int), java.lang.Object#wait(long), java.lang.Object#wait(), java.lang.Object#equals(java.lang.Object), java.lang.Object#toString(), java.lang.Object#hashCode(), java.lang.Object#getClass(), java.lang.Object#notify(), java.lang.Object#notifyAll()</code></td> </tr> </table> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- =========== PROPERTY DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="prop_detail"> <!-- --> </a> <h3>Property Detail</h3> <a name="COUNT_INCREMENTED"><!-- --></a> <ul class="blockListLast"> <li class="blockList"> <h4>static&nbsp;final&nbsp;org.ajoberstar.gradle.git.release.semver.PartialSemVerStrategy <strong>COUNT_INCREMENTED</strong></h4> <p></p> </li> </ul> <a name="DEVELOPMENT"><!-- --></a> <ul class="blockListLast"> <li class="blockList"> <h4>static&nbsp;final&nbsp;org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>DEVELOPMENT</strong></h4> <p> Returns a version strategy to be used for <CODE>development</CODE> builds. <p> This strategy creates a unique version string based on last commit hash and the distance of commits to nearest normal version. This version string is not compatible with <a href="https://fsprojects.github.io/Paket/">Paket</a> or <a href="https://www.nuget.org/">Nuget</a> <p> Example: <pre> <CODE>releaseScope = "minor" nearestVersion = "1.3.0" commitHash = "90c90b9" distance = 22 inferred = "1.3.0-dev.22+90c90b9" </CODE> </pre> </p> </li> </ul> <a name="FINAL"><!-- --></a> <ul class="blockListLast"> <li class="blockList"> <h4>static&nbsp;final&nbsp;org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>FINAL</strong></h4> <p> Returns a version strategy to be used for <CODE>final</CODE> builds. <p> This strategy infers the release version by checking the nearest release. <p> Example: <pre> <CODE>releaseScope = "minor" nearestVersion = "1.3.0" inferred = "1.4.0" </CODE> </pre> </p> </li> </ul> <a name="PRE_RELEASE"><!-- --></a> <ul class="blockListLast"> <li class="blockList"> <h4>static&nbsp;final&nbsp;org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>PRE_RELEASE</strong></h4> <p> Returns a version strategy to be used for <CODE>pre-release</CODE>/<CODE>candidate</CODE> builds. <p> This strategy infers the release version by checking the nearest any release. If a <CODE>pre-release</CODE> with the same <CODE>major</CODE>.<CODE>minor</CODE>.<CODE>patch</CODE> version exists, bumps the count part. <p> Example <i>new pre release</i>: <pre> <CODE>releaseScope = "minor" nearestVersion = "1.2.0" nearestAnyVersion = "" inferred = "1.3.0-rc00001" </CODE> </pre> <p> Example <i>pre release version exists</i>: <pre> <CODE>releaseScope = "minor" nearestVersion = "1.2.0" nearestAnyVersion = "1.3.0-rc00001" inferred = "1.3.0-rc00002" </CODE> </pre> <p> Example <i>last final release higher than pre-release</i>: <pre> <CODE>releaseScope = "minor" nearestVersion = "1.3.0" nearestAnyVersion = "1.3.0-rc00001" inferred = "1.4.0-rc00001" </CODE> </pre> </p> </li> </ul> <a name="SNAPSHOT"><!-- --></a> <ul class="blockListLast"> <li class="blockList"> <h4>static&nbsp;final&nbsp;org.ajoberstar.gradle.git.release.semver.SemVerStrategy <strong>SNAPSHOT</strong></h4> <p> Returns a version strategy to be used for <CODE>snapshot</CODE> builds. <p> This strategy creates a snapshot version suitable for <a href="https://fsprojects.github.io/Paket/">Paket</a> and <a href="https://www.nuget.org/">Nuget</a>. <CODE>Nuget</CODE> and <CODE>Paket</CODE> don't support <CODE>SNAPSHOT</CODE> versions or any numerical values after the <CODE>patch</CODE> component. We trick these package managers by creating a unique version based on <CODE>branch</CODE> and the distance of commits to nearest normal version. If the branch name contains numerical values, they will be converted into alphanumerical counterparts. The <CODE>master</CODE> branch is a special case so it will end up being higher than any other branch build (m>b) <p> Example <i>from master branch</i>: <pre> <CODE>releaseScope = "minor" nearestVersion = "1.3.0" branch = "master" distance = 22 inferred = "1.4.0-master00022" </CODE> </pre> <p> Example <i>from topic branch</i>: <pre> <CODE>releaseScope = "minor" nearestVersion = "1.3.0" branch = "feature/fix_22" distance = 34 inferred = "1.4.0-branchFeatureFixTwoTow00034" </CODE> </pre> </p> </li> </ul> </li> </ul> </li> </ul> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <div> <ul class="navList"> <li><a href="../../../../index.html?wooga/gradle/release/utils/WoogaStrategies" target="_top">Frames</a></li> <li><a href="WoogaStrategies.html" target="_top">No Frames</a></li> </ul> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> Nested&nbsp;&nbsp;&nbsp;Field&nbsp;&nbsp;&nbsp;<li><a href="#property_summary">Property</a></li>&nbsp;&nbsp;&nbsp;Constructor&nbsp;&nbsp;&nbsp;Method&nbsp;&nbsp;&nbsp; </ul> <ul class="subNavList"> <li>&nbsp;|&nbsp;Detail:&nbsp;</li> Field&nbsp;&nbsp;&nbsp;<li><a href="#prop_detail">Property</a></li>&nbsp;&nbsp;&nbsp;Constructor&nbsp;&nbsp;&nbsp;Method&nbsp;&nbsp;&nbsp; </ul> </div> <p>Gradle Wooga Release plugin API</p> <a name="skip-navbar_bottom"> <!-- --> </a> </div> </div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "91f33057d799e911415d555b58d3dc9a", "timestamp": "", "source": "github", "line_count": 397, "max_line_length": 339, "avg_line_length": 41.53904282115869, "alnum_prop": 0.5240434176217331, "repo_name": "wooga/atlas-release", "id": "07428eeaffeb2b76886da2a8a4cd3abeef94987e", "size": "16491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/wooga/gradle/release/utils/WoogaStrategies.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "778" }, { "name": "Groovy", "bytes": "105794" }, { "name": "HTML", "bytes": "2255" }, { "name": "Mustache", "bytes": "2876" }, { "name": "Shell", "bytes": "396" } ], "symlink_target": "" }
package org.jheaps.tree; import java.io.Serializable; import java.lang.reflect.Array; import java.util.Comparator; import java.util.NoSuchElementException; import org.jheaps.AddressableHeap; import org.jheaps.annotations.ConstantTime; import org.jheaps.annotations.LogarithmicTime; /** * An explicit d-ary tree addressable heap. The heap is sorted according to the * {@linkplain Comparable natural ordering} of its keys, or by a * {@link Comparator} provided at heap creation time, depending on which * constructor is used. * * <p> * The worst-case cost of {@code insert}, {@code deleteMin}, {@code delete} and * {@code decreaceKey} operations is O(d log_d(n)) and the cost of {@code findMin} * is O(1). * * <p> * Note that the ordering maintained by a binary heap, like any heap, and * whether or not an explicit comparator is provided, must be <em>consistent * with {@code equals}</em> if this heap is to correctly implement the * {@code Heap} interface. (See {@code Comparable} or {@code Comparator} for a * precise definition of <em>consistent with equals</em>.) This is so because * the {@code Heap} interface is defined in terms of the {@code equals} * operation, but a binary heap performs all key comparisons using its * {@code compareTo} (or {@code compare}) method, so two keys that are deemed * equal by this method are, from the standpoint of the binary heap, equal. The * behavior of a heap <em>is</em> well-defined even if its ordering is * inconsistent with {@code equals}; it just fails to obey the general contract * of the {@code Heap} interface. * * <p> * <strong>Note that this implementation is not synchronized.</strong> If * multiple threads access a heap concurrently, and at least one of the threads * modifies the heap structurally, it <em>must</em> be synchronized externally. * (A structural modification is any operation that adds or deletes one or more * elements or changing the key of some element.) This is typically accomplished * by synchronizing on some object that naturally encapsulates the heap. * * @param <K> * the type of keys maintained by this heap * @param <V> * the type of values maintained by this heap * * @author Dimitrios Michail * * @see AddressableHeap * @see Comparable * @see Comparator */ public class DaryTreeAddressableHeap<K, V> implements AddressableHeap<K, V>, Serializable { private static final long serialVersionUID = 1; /** * The comparator used to maintain order in this heap, or null if it uses * the natural ordering of its keys. * * @serial */ private final Comparator<? super K> comparator; /** * Size of the heap */ private long size; /** * Root node of the heap */ private Node root; /** * Branching factor. Always a power of two. */ private final int d; /** * Base 2 logarithm of branching factor. */ private final int log2d; /** * Auxiliary for swapping children. */ private Node[] aux; /** * Constructs a new, empty heap, using the natural ordering of its keys. * * <p> * All keys inserted into the heap must implement the {@link Comparable} * interface. Furthermore, all such keys must be <em>mutually * comparable</em>: {@code k1.compareTo(k2)} must not throw a * {@code ClassCastException} for any keys {@code k1} and {@code k2} in the * heap. If the user attempts to put a key into the heap that violates this * constraint (for example, the user attempts to put a string key into a * heap whose keys are integers), the {@code insert(Object key)} call will * throw a {@code ClassCastException}. * * @param d * the branching factor. Should be a power of 2. */ public DaryTreeAddressableHeap(int d) { this(d, null); } /** * Constructs a new, empty heap, ordered according to the given comparator. * * <p> * All keys inserted into the heap must be <em>mutually comparable</em> by * the given comparator: {@code comparator.compare(k1, * k2)} must not throw a {@code ClassCastException} for any keys {@code k1} * and {@code k2} in the heap. If the user attempts to put a key into the * heap that violates this constraint, the {@code insert(Object key)} call * will throw a {@code ClassCastException}. * * @param d * the branching factor. Should be a power of 2. * @param comparator * the comparator that will be used to order this heap. If * {@code null}, the {@linkplain Comparable natural ordering} of * the keys will be used. */ @SuppressWarnings("unchecked") public DaryTreeAddressableHeap(int d, Comparator<? super K> comparator) { this.comparator = comparator; this.size = 0; this.root = null; if (d < 2 || ((d & (d - 1)) != 0)) { throw new IllegalArgumentException("Branching factor d should be a power of 2."); } this.d = d; this.log2d = log2(d); this.aux = (DaryTreeAddressableHeap<K, V>.Node[]) Array.newInstance(Node.class, d); } @Override @LogarithmicTime public Handle<K, V> insert(K key, V value) { if (key == null) { throw new NullPointerException("Null keys not permitted"); } Node n = new Node(key, value, d); if (size == 0) { root = n; size = 1; return n; } Node p = findNode(size); for (int i = 0; i < d; i++) { if (p.children[i] == null) { p.children[i] = n; break; } } n.parent = p; size++; fixup(n); return n; } @Override @LogarithmicTime public Handle<K, V> insert(K key) { return insert(key, null); } @Override @ConstantTime public Handle<K, V> findMin() { if (size == 0) { throw new NoSuchElementException(); } return root; } @Override @LogarithmicTime public Handle<K, V> deleteMin() { if (size == 0) { throw new NoSuchElementException(); } Node oldRoot = root; if (size == 1) { root = null; size = 0; } else { root.delete(); } return oldRoot; } @Override @ConstantTime public boolean isEmpty() { return size == 0; } @Override @ConstantTime public long size() { return size; } @Override @ConstantTime public void clear() { size = 0; root = null; } @Override public Comparator<? super K> comparator() { return comparator; } // handle private class Node implements AddressableHeap.Handle<K, V>, Serializable { private final static long serialVersionUID = 1; K key; V value; Node parent; Node[] children; @SuppressWarnings("unchecked") Node(K key, V value, int d) { this.key = key; this.value = value; this.parent = null; this.children = (DaryTreeAddressableHeap<K, V>.Node[]) Array.newInstance(Node.class, d); } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public void setValue(V value) { this.value = value; } @Override @LogarithmicTime @SuppressWarnings("unchecked") public void decreaseKey(K newKey) { if (parent == null && root != this) { throw new IllegalArgumentException("Invalid handle!"); } int c; if (comparator == null) { c = ((Comparable<? super K>) newKey).compareTo(key); } else { c = comparator.compare(newKey, key); } if (c > 0) { throw new IllegalArgumentException("Keys can only be decreased!"); } key = newKey; if (c == 0 || root == this) { return; } fixup(this); } @Override @LogarithmicTime public void delete() { if (parent == null && root != this) { throw new IllegalArgumentException("Invalid handle!"); } if (size == 0) { throw new NoSuchElementException(); } // swap with last node Node last = findNode(size - 1); swap(this, last); // remove from parent if (this.parent != null) { for (int i = 0; i < d; i++) { if (this.parent.children[i] == this) { this.parent.children[i] = null; } } this.parent = null; } size--; if (size == 0) { root = null; } else if (this != last) { fixdown(last); } } } /** * Start at the root and traverse the tree in order to find a particular * node based on its numbering on a level-order traversal of the tree. Uses * the bit representation to keep the cost log_d(n). * * @param node * the node number assuming that the root node is number zero */ private Node findNode(long node) { if (node == 0) return root; long mask = (long)d - 1; long location = (node - 1); int log = log2(node - 1) / log2d; Node cur = root; for (int i = log; i >= 0; i--) { int s = i * log2d; int path = (int) ((location & (mask << s)) >>> s); Node next = cur.children[path]; if (next == null) { break; } cur = next; } return cur; } /** * Calculate the floor of the binary logarithm of n. * * @param n * the input number * @return the binary logarithm */ private int log2(long n) { // returns 0 for n=0 long log = 0; if ((n & 0xffffffff00000000L) != 0) { n >>>= 32; log = 32; } if ((n & 0xffff0000) != 0) { n >>>= 16; log += 16; } if (n >= 256) { n >>>= 8; log += 8; } if (n >= 16) { n >>>= 4; log += 4; } if (n >= 4) { n >>>= 2; log += 2; } return (int) (log + (n >>> 1)); } @SuppressWarnings("unchecked") private void fixup(Node n) { if (comparator == null) { Node p = n.parent; while (p != null) { if (((Comparable<? super K>) n.key).compareTo(p.key) >= 0) { break; } Node pp = p.parent; swap(n, p); p = pp; } } else { Node p = n.parent; while (p != null) { if (comparator.compare(n.key, p.key) >= 0) { break; } Node pp = p.parent; swap(n, p); p = pp; } } } @SuppressWarnings("unchecked") private void fixdown(Node n) { if (comparator == null) { while (n.children[0] != null) { int min = 0; Node child = n.children[min]; for (int i = 1; i < d; i++) { Node candidate = n.children[i]; if (candidate != null && ((Comparable<? super K>) candidate.key).compareTo(child.key) < 0) { min = i; child = candidate; } } if (((Comparable<? super K>) n.key).compareTo(child.key) <= 0) { break; } swap(child, n); } } else { while (n.children[0] != null) { int min = 0; Node child = n.children[min]; for (int i = 1; i < d; i++) { Node candidate = n.children[i]; if (candidate != null && comparator.compare(candidate.key, child.key) < 0) { min = i; child = candidate; } } if (comparator.compare(n.key, child.key) <= 0) { break; } swap(child, n); } } } /** * Swap two nodes * * @param a * first node * @param b * second node */ private void swap(Node a, Node b) { if (a == null || b == null || a == b) { return; } if (a.parent == b) { Node tmp = a; a = b; b = tmp; } Node pa = a.parent; if (b.parent == a) { // a is the parent int whichChild = -1; for (int i = 0; i < d; i++) { aux[i] = b.children[i]; if (b == a.children[i]) { b.children[i] = a; a.parent = b; } else { b.children[i] = a.children[i]; if (b.children[i] != null) { b.children[i].parent = b; } } if (pa != null && pa.children[i] == a) { whichChild = i; } } b.parent = pa; if (pa != null) { pa.children[whichChild] = b; } for (int i = 0; i < d; i++) { a.children[i] = aux[i]; if (a.children[i] != null) { a.children[i].parent = a; } aux[i] = null; } } else { // no parent child relationship Node pb = b.parent; for (int i = 0; i < d; i++) { aux[i] = b.children[i]; b.children[i] = a.children[i]; if (b.children[i] != null) { b.children[i].parent = b; } } for (int i = 0; i < d; i++) { a.children[i] = aux[i]; if (a.children[i] != null) { a.children[i].parent = a; } aux[i] = null; } int aIsChild = -1; if (pa != null) { for (int i = 0; i < d; i++) { if (pa.children[i] == a) { aIsChild = i; } } } else { b.parent = null; } int bIsChild = -1; if (pb != null) { for (int i = 0; i < d; i++) { if (pb.children[i] == b) { bIsChild = i; } } } else { a.parent = null; } if (aIsChild>=0) { pa.children[aIsChild] = b; b.parent = pa; } if (bIsChild>=0) { pb.children[bIsChild] = a; a.parent = pb; } } // switch root if (root == a) { root = b; } else if (root == b) { root = a; } } }
{ "content_hash": "a33fa25e8b5b00ee44c1c2cad0b67bb7", "timestamp": "", "source": "github", "line_count": 556, "max_line_length": 112, "avg_line_length": 28.66726618705036, "alnum_prop": 0.46740698914611956, "repo_name": "d-michail/jheaps", "id": "4831b77f60ba0a31fe8743a17f91f8ffaa6e3a0f", "size": "15939", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/jheaps/tree/DaryTreeAddressableHeap.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "845749" } ], "symlink_target": "" }
import React from 'react'; class ProjectInfoList extends React.Component { shouldComponentUpdate() { return false; } render() { const { subtitle, list } = this.props; return ( <div className="project-info-list-container"> <h3 className="project-subtitle">{subtitle}:</h3> <ul className="project-info-list"> {list.map((item, i) => ( <li key={i} className="project-info-list-item">{item}</li> ))} </ul> </div> ); } } ProjectInfoList.propTypes = { subtitle: React.PropTypes.string.isRequired, list: React.PropTypes.array.isRequired, }; export default ProjectInfoList;
{ "content_hash": "d213c114eb122762276bbdbada2e807e", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 70, "avg_line_length": 22.96551724137931, "alnum_prop": 0.6141141141141141, "repo_name": "evancorl/skate-scenes", "id": "2caa5e74055e372590b42a72296e508e378cacf3", "size": "666", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "imports/client/components/Project/ProjectInfoList.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "24819" }, { "name": "HTML", "bytes": "232" }, { "name": "JavaScript", "bytes": "27552" }, { "name": "Ruby", "bytes": "932" } ], "symlink_target": "" }
FROM ubuntu:14.04 MAINTAINER Nathaniel Hoag, info@nathanielhoag.com RUN apt-get update && \ apt-get install -y wget && \ wget -q -O - https://deb.nodesource.com/setup_0.12 | sudo bash - && \ apt-get install -y build-essential nodejs && \ rm -rf /var/lib/apt/lists/*
{ "content_hash": "29793653302efb234e21c15093902382", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 71, "avg_line_length": 34.375, "alnum_prop": 0.6727272727272727, "repo_name": "nhoag/nodejs", "id": "32555c7983df341705ea3bd5cd0b3e7a44442453", "size": "299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Dockerfile", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import sbt._ import Keys._ import play.Project._ object ApplicationBuild extends Build { val appName = "kanban-salad-server" val appVersion = "1.0-SNAPSHOT" val appDependencies = Seq( // Add your project dependencies here, jdbc, anorm ) val main = play.Project(appName, appVersion, appDependencies).settings( // Add your own project settings here ) }
{ "content_hash": "ae09f10fb31840eb56d7a72bd2d6c655", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 73, "avg_line_length": 19.238095238095237, "alnum_prop": 0.6608910891089109, "repo_name": "jthurne/kanban-salad", "id": "901f055c61b3fdb28bca1d73f0cd417886db5c94", "size": "404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/project/Build.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "186530" }, { "name": "Scala", "bytes": "4175" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0012_auto_20160819_0709'), ] operations = [ migrations.AlterField( model_name='user', name='birthday', field=models.DateField(blank=True, null=True), ), ]
{ "content_hash": "d17e40d15a6d12ba890d1e3d9c26873f", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 58, "avg_line_length": 21.27777777777778, "alnum_prop": 0.5900783289817232, "repo_name": "internship2016/sovolo", "id": "eb8d56cce4df4103ce2f97ca2f9d23d3ead16452", "size": "454", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/user/migrations/0013_auto_20160820_1029.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "56092" }, { "name": "HTML", "bytes": "132262" }, { "name": "JavaScript", "bytes": "107993" }, { "name": "Python", "bytes": "255017" } ], "symlink_target": "" }
@class GroupMemberModel; @interface MemberListViewController : UIViewController - (instancetype)initWithAllMembersModel:(NSArray <GroupMemberModel *>*)members totalMember:(NSInteger)memberCount; @end
{ "content_hash": "a64e1c603f3ea1809687c637d28effff", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 114, "avg_line_length": 33.666666666666664, "alnum_prop": 0.8366336633663366, "repo_name": "huixinHu/XiaoYa", "id": "73acb41466c05955a8f4a14a359415320e6631f4", "size": "368", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XiaoYa/MemberListViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1253000" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67a.c Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.string.label.xml Template File: sources-sink-67a.tmpl.c */ /* * @description * CWE: 121 Stack Based Buffer Overflow * BadSource: Set data pointer to the bad buffer * GoodSource: Set data pointer to the good buffer * Sinks: ncat * BadSink : Copy string to data using strncat * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> typedef struct _CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_structType { char * structFirst; } CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_structType; #ifndef OMITBAD /* bad function declaration */ void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67b_badSink(CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_structType myStruct); void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_bad() { char * data; CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_structType myStruct; char dataBadBuffer[50]; char dataGoodBuffer[100]; /* FLAW: Set a pointer to a "small" buffer. This buffer will be used in the sinks as a destination * buffer in various memory copying functions using a "large" source buffer. */ data = dataBadBuffer; data[0] = '\0'; /* null terminate */ myStruct.structFirst = data; CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67b_badSink(myStruct); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67b_goodG2BSink(CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_structType myStruct); static void goodG2B() { char * data; CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_structType myStruct; char dataBadBuffer[50]; char dataGoodBuffer[100]; /* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */ data = dataGoodBuffer; data[0] = '\0'; /* null terminate */ myStruct.structFirst = data; CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67b_goodG2BSink(myStruct); } void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "a2a161193b8a453b6e0f5b77e1987d6d", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 167, "avg_line_length": 35.154639175257735, "alnum_prop": 0.704692082111437, "repo_name": "maurer/tiamat", "id": "41678567bb3731b3090dd3b3c60de6ef94bba764", "size": "3410", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE121_Stack_Based_Buffer_Overflow/s03/CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_ncat_67a.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// @@author A0130195M package jfdi.logic.events; import jfdi.storage.apis.TaskAttributes; /** * @author Liu Xinan */ public class RescheduleTaskDoneEvent { private TaskAttributes task; public RescheduleTaskDoneEvent(TaskAttributes task) { this.task = task; } public TaskAttributes getTask() { return task; } }
{ "content_hash": "b16e80020188e9fa781e28b384a7b165", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 57, "avg_line_length": 16.136363636363637, "alnum_prop": 0.6788732394366197, "repo_name": "cs2103jan2016-w13-4j/main", "id": "d4440b75b4161217d328e246b6517964ca2f6a03", "size": "355", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/jfdi/logic/events/RescheduleTaskDoneEvent.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "766" }, { "name": "Java", "bytes": "295686" } ], "symlink_target": "" }
from test import test_support from test.test_support import verbose, verify, TESTFN, TestSkipped test_support.requires('network') from SocketServer import * import socket import select import time import threading import os NREQ = 3 DELAY = 0.5 class MyMixinHandler: def handle(self): time.sleep(DELAY) line = self.rfile.readline() time.sleep(DELAY) self.wfile.write(line) class MyStreamHandler(MyMixinHandler, StreamRequestHandler): pass class MyDatagramHandler(MyMixinHandler, DatagramRequestHandler): pass class MyMixinServer: def serve_a_few(self): for i in range(NREQ): self.handle_request() def handle_error(self, request, client_address): self.close_request(request) self.server_close() raise teststring = "hello world\n" def receive(sock, n, timeout=20): r, w, x = select.select([sock], [], [], timeout) if sock in r: return sock.recv(n) else: raise RuntimeError, "timed out on %s" % `sock` def testdgram(proto, addr): s = socket.socket(proto, socket.SOCK_DGRAM) s.sendto(teststring, addr) buf = data = receive(s, 100) while data and '\n' not in buf: data = receive(s, 100) buf += data verify(buf == teststring) s.close() def teststream(proto, addr): s = socket.socket(proto, socket.SOCK_STREAM) s.connect(addr) s.sendall(teststring) buf = data = receive(s, 100) while data and '\n' not in buf: data = receive(s, 100) buf += data verify(buf == teststring) s.close() class ServerThread(threading.Thread): def __init__(self, addr, svrcls, hdlrcls): threading.Thread.__init__(self) self.__addr = addr self.__svrcls = svrcls self.__hdlrcls = hdlrcls def run(self): class svrcls(MyMixinServer, self.__svrcls): pass if verbose: print "thread: creating server" svr = svrcls(self.__addr, self.__hdlrcls) if verbose: print "thread: serving three times" svr.serve_a_few() if verbose: print "thread: done" seed = 0 def pickport(): global seed seed += 1 return 10000 + (os.getpid() % 1000)*10 + seed host = "localhost" testfiles = [] def pickaddr(proto): if proto == socket.AF_INET: return (host, pickport()) else: fn = TESTFN + str(pickport()) testfiles.append(fn) return fn def cleanup(): for fn in testfiles: try: os.remove(fn) except os.error: pass testfiles[:] = [] def testloop(proto, servers, hdlrcls, testfunc): for svrcls in servers: addr = pickaddr(proto) if verbose: print "ADDR =", addr print "CLASS =", svrcls t = ServerThread(addr, svrcls, hdlrcls) if verbose: print "server created" t.start() if verbose: print "server running" for i in range(NREQ): time.sleep(DELAY) if verbose: print "test client", i testfunc(proto, addr) if verbose: print "waiting for server" t.join() if verbose: print "done" tcpservers = [TCPServer, ThreadingTCPServer] if hasattr(os, 'fork') and os.name not in ('os2',): tcpservers.append(ForkingTCPServer) udpservers = [UDPServer, ThreadingUDPServer] if hasattr(os, 'fork') and os.name not in ('os2',): udpservers.append(ForkingUDPServer) if not hasattr(socket, 'AF_UNIX'): streamservers = [] dgramservers = [] else: class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): pass streamservers = [UnixStreamServer, ThreadingUnixStreamServer, ForkingUnixStreamServer] class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): pass dgramservers = [UnixDatagramServer, ThreadingUnixDatagramServer, ForkingUnixDatagramServer] def testall(): testloop(socket.AF_INET, tcpservers, MyStreamHandler, teststream) testloop(socket.AF_INET, udpservers, MyDatagramHandler, testdgram) if hasattr(socket, 'AF_UNIX'): testloop(socket.AF_UNIX, streamservers, MyStreamHandler, teststream) # Alas, on Linux (at least) recvfrom() doesn't return a meaningful # client address so this cannot work: ##testloop(socket.AF_UNIX, dgramservers, MyDatagramHandler, testdgram) def test_main(): import imp if imp.lock_held(): # If the import lock is held, the threads will hang. raise TestSkipped("can't run when import lock is held") try: testall() finally: cleanup() if __name__ == "__main__": test_main()
{ "content_hash": "fd21c08ce984690a6a13efb331d48806", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 78, "avg_line_length": 28.63803680981595, "alnum_prop": 0.6304627249357326, "repo_name": "OS2World/APP-INTERNET-torpak_2", "id": "36396daa6f93a87dc1782ae4883fc45a5bc11057", "size": "4702", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "Lib/test/test_socketserver.py", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php Route::get('/', 'HomeController@mainIndex'); Route::controllers([ 'auth' => 'Auth\AuthController', 'password' => 'Auth\PasswordController', ]); Route::get('landing', 'WelcomeController@index'); //////////////// //User Routes // //////////////// Route::get('users', 'UserController@index'); Route::get('users/one/{id}', ['as' => 'user/profile', 'uses' => 'UserController@show']); Route::get('users/one/{id}/tasks', ['as' => 'user/tasks', 'uses' => 'UserController@tasks']); Route::get('users/create', 'UserController@create'); Route::get('users/edit/{id}', 'UserController@edit'); Route::get('users/delete/{id}', 'UserController@destroy'); Route::post('users/update', 'UserController@update'); Route::post('users/store', 'UserController@store'); Route::post('users/units', 'UserController@addUnits'); Route::post('users/search', 'UserController@search'); //////////////// //Unit Routes // //////////////// Route::get('units', ['as' => 'units', 'uses' => 'UnitController@index']); Route::get('units/tree/{id}', 'UnitController@tree'); Route::get('units/one/{id}', ['as' => 'unit/one', 'uses' => 'UnitController@show']); Route::get('units/create', 'UnitController@create'); Route::get('units/edit/{id}', 'UnitController@edit'); Route::get('units/delete/{id}', 'UnitController@destroy'); Route::post('units/store', 'UnitController@store'); Route::post('units/update', 'UnitController@update'); Route::post('units/users', 'UnitController@addUsers'); Route::post('units/volunteers', 'UnitController@addVolunteers'); Route::post('units/search', 'UnitController@search'); Route::post('units/results', 'UnitController@results'); Route::get('rootUnit', 'UnitController@rootUnit'); Route::get('wholeTree', 'UnitController@wholeTree'); ///////////////////// //Volunteer Routes // ///////////////////// Route::get('volunteers', 'VolunteerController@index'); Route::get('volunteers/create', 'VolunteerController@create'); Route::get('volunteers/new', 'VolunteerController@newVolunteers'); Route::get('volunteers/edit/{id}', 'VolunteerController@edit'); Route::get('volunteers/delete/{id}', 'VolunteerController@destroy'); Route::get('volunteers/one/{id}', ['as' => 'volunteer/profile', 'uses' => 'VolunteerController@show']); Route::get('volunteers/addToRootUnit/{id}', 'VolunteerController@addToRootUnit'); Route::get('volunteers/{volunteerId}/unit/detach/{unitId}', 'VolunteerController@detachFromUnit'); Route::get('volunteers/{volunteerId}/action/detach/{unitId}', 'VolunteerController@detachFromAction'); Route::post('volunteers/addToUnit', 'VolunteerController@addToUnit'); Route::post('volunteers/addToAction', 'VolunteerController@addToAction'); Route::post('volunteers/store', 'VolunteerController@store'); Route::post('volunteers/update', 'VolunteerController@update'); Route::post('volunteers/stepStatus/update', 'VolunteerController@updateStepStatus'); Route::post('volunteers/search', 'VolunteerController@search'); Route::post('volunteers/blacklisted', 'VolunteerController@blacklisted'); Route::post('volunteers/unblacklisted', 'VolunteerController@unBlacklisted'); Route::post('volunteers/notAvailable', 'VolunteerController@notAvailable'); Route::post('volunteers/available', 'VolunteerController@available'); Route::post('volunteers/deleteFile', 'VolunteerController@deleteFile'); Route::get('volunteers/publicForm', 'VolunteerController@publicForm'); ////////////////// //Action Routes // ////////////////// Route::get('actions', 'ActionController@index'); Route::get('actions/one/{id}', ['as' => 'action/one', 'uses' => 'ActionController@show']); Route::get('actions/create', 'ActionController@create'); Route::get('actions/edit/{id}', 'ActionController@edit'); Route::get('actions/delete/{id}', 'ActionController@destroy'); Route::post('actions/store', 'ActionController@store'); Route::post('actions/update', 'ActionController@update'); Route::post('actions/volunteers', 'ActionController@addVolunteers'); Route::get('actions/ratings/{id}', 'ActionController@fullRatings'); Route::post('actions/search', 'ActionController@search'); //////////////// //Task Routes // //////////////// Route::get('actions/tasks/one/{id}', 'TaskController@show'); Route::post('actions/tasks/store', 'TaskController@store'); Route::get('actions/tasks/update', 'TaskController@update'); Route::get('actions/tasks/delete/{id}', 'TaskController@destroy'); //////////////////// //SubTask Routes // ////////////////// Route::get('actions/tasks/subtasks/one/{id}', 'SubTaskController@show'); Route::post('actions/tasks/subtasks/store', 'SubTaskController@store'); Route::post('actions/tasks/subtasks/update', 'SubTaskController@update'); Route::get('actions/tasks/subtasks/updateStatus', 'SubTaskController@updateStatus'); Route::get('actions/tasks/subtasks/delete/{id}', 'SubTaskController@destroy'); //////////////////// //Shifts Routes // ////////////////// Route::get('actions/tasks/shifts/store', 'TaskShiftController@store'); Route::get('actions/tasks/shifts/update', 'TaskShiftController@update'); Route::get('actions/tasks/shifts/delete/{id}', 'TaskShiftController@destroy'); Route::get('actions/tasks/subtasks/shifts/store', 'SubtaskShiftController@store'); Route::get('actions/tasks/subtasks/shifts/update', 'SubtaskShiftController@update'); Route::get('actions/tasks/subtasks/shifts/delete/{id}', 'SubtaskShiftController@destroy'); ////////////////////////// //Collaboration Routes // //////////////////////// Route::get('collaborations', 'CollaborationController@index'); Route::get('collaborations/one/{id}', ['as' => 'collaboration/one', 'uses' => 'CollaborationController@show']); Route::get('collaborations/create', 'CollaborationController@create'); Route::get('collaborations/edit/{id}', 'CollaborationController@edit'); Route::get('collaborations/delete/{id}', 'CollaborationController@destroy'); Route::post('collaborations/store', 'CollaborationController@store'); Route::post('collaborations/update', 'CollaborationController@update'); Route::post('collaborations/search', 'CollaborationController@search'); Route::post('collaborations/deleteFile', 'CollaborationController@deleteFile'); //////////////// //Step Routes // //////////////// Route::get('steps/volunteer/{id}', 'StepController@volunteerSteps'); //////////////// //Rating Routes // //////////////// Route::post('ratings/action/store', 'RatingController@storeActionRating'); Route::post('ratings/action/volunteers/store', 'RatingController@storeVolunteersRating'); Route::get('ratings/action/volunteers/delete/{id}', 'RatingController@deleteVolunteerRating'); Route::get('ratings/action/thankyou/{actionId}', 'RatingController@actionThankyou'); Route::get('ratings/action/volunteers/thankyou/{actionId}', 'RatingController@volunteersThankyou'); Route::get('ratings/action/{token}', 'RatingController@rateAction'); Route::get('rateVolunteers/{token}', 'RatingController@rateVolunteers'); //////////////////// // Notifications // //////////////////// Route::get('/addNotification/{userId}/{typeId}/{msg}/{url}/{reference1Id}/{reference2Id?}', array( 'as' => 'notifications.add', 'uses' => 'NotificationController@addNotification' )); Route::get('stopBellNotification/{notificationId}', array( 'as' => 'notifications.stopBell', 'uses' => 'NotificationController@stopBellNotification' )); Route::get('/deactivateNotification/{notificationId}', array( 'as' => 'notification.deactivate', 'uses' => 'NotificationController@deactivateNotification' )); Route::get('/checkForNotifications', array( 'as' => 'notifications.check', 'uses' => 'NotificationController@checkForNotifications' )); Route::get('notifications', 'NotificationController@index'); ///////////////// //Search Route // ///////////////// Route::get('search/city', 'SearchController@city'); Route::get('search/country', 'SearchController@country'); Route::get('search/actionUser', 'SearchController@actionUser'); Route::get('search/collabType', 'SearchController@collabType'); Route::get('search/volunteers/firstName', 'SearchController@volunteerFirstName'); Route::get('search/volunteers/lastName', 'SearchController@volunteerLastName'); Route::get('search/volunteers/additionalSkills', 'SearchController@volunteerAdditionalSkills'); Route::get('search/volunteers/extraLang', 'SearchController@volunteerExtraLang'); Route::get('search/volunteers/workDescription', 'SearchController@volunteerWorkDescription'); Route::get('search/volunteers/specialty', 'SearchController@volunteerSpecialty'); Route::get('search/volunteers/department', 'SearchController@volunteerDepartment'); Route::get('search/volunteers/participationΑctions', 'SearchController@volunteerParticipationΑctions'); Route::get('search/volunteers/computerUsageComments', 'SearchController@volunteerComputerUsageComments'); /////////////////// //Reports Routes // ////////////////// Route::get('reports', 'ReportsController@index'); Route::get('reports/idleVolunteers', 'ReportsController@idleVolunteers'); Route::get('reports/volunteersByMonth', 'ReportsController@volunteersByMonth'); Route::get('reports/volunteersBySex', 'ReportsController@volunteersBySex'); Route::get('reports/volunteersByAgeGroup', 'ReportsController@volunteersByAgeGroup'); Route::get('reports/volunteersByCity', 'ReportsController@volunteersByCity'); Route::get('reports/volunteersByEducationLevel', 'ReportsController@volunteersByEducationLevel'); Route::get('reports/volunteersByInterest', 'ReportsController@volunteersByInterest'); Route::get('reports/volunteersByAction', 'ReportsController@volunteersByAction'); Route::get('reports/volunteerHoursByAction', 'ReportsController@volunteerHoursByAction'); Route::get('reports/activeAndAvailableVolunteersByUnit', 'ReportsController@activeAndAvailableVolunteersByUnit'); /////////////////// //CTA Routes // ////////////////// Route::get('cta', 'CTAController@cta'); Route::get('participate/{id}', 'CTAController@participate'); Route::get('cta/store', 'CTAController@store'); Route::get('cta/update', 'CTAController@update'); Route::post('cta/volunteerInterested', 'CTAController@volunteerInterested'); /////////////////// //CTAVolunteer Routes // ////////////////// Route::get('ctaVolunteer/update', 'CTAVolunteerController@update'); Route::get('ctaVolunteer/delete/{id}', 'CTAVolunteerController@destroy'); Route::get('ctaVolunteer/assignToVolunteer', 'CTAVolunteerController@assignToVolunteer'); /////////////////// //Checklist Routes // ////////////////// Route::get('actions/tasks/checklist/store', 'TaskChecklistController@store'); Route::get('actions/tasks/checklist/update', 'TaskChecklistController@update'); Route::get('actions/tasks/checklist/delete', 'TaskChecklistController@delete'); Route::get('actions/tasks/subtasks/checklist/store', 'SubtaskChecklistController@store'); Route::get('actions/tasks/subtasks/checklist/update', 'SubtaskChecklistController@update'); Route::get('actions/tasks/subtasks/checklist/delete', 'SubtaskChecklistController@delete'); /////////////////// //Cron Routes //// ////////////////// Route::get('cron/checkActions', 'CronController@checkActions'); ///////////////// //API Routes // ///////////////// Route::group(['middleware' => 'cors', 'prefix' => 'api'], function () { Route::get('volunteers', 'Api\VolunteerApiController@all'); Route::get('volunteers/status/{status}', 'Api\VolunteerApiController@status'); Route::get('volunteers/one/{id}', 'Api\VolunteerApiController@show'); Route::post('volunteers/apiStore', 'Api\VolunteerApiController@apiStore'); Route::get('units', 'Api\UnitApiController@all'); Route::get('units/{id}/volunteers', 'Api\UnitApiController@volunteers'); Route::get('units/{id}/actions', 'Api\UnitApiController@actions'); Route::get('users', 'Api\UserApiController@all'); Route::get('actions', 'Api\ActionApiController@all'); Route::get('actions/{id}/volunteers', 'Api\ActionApiController@volunteers'); Route::get('actions/calendar', 'Api\ActionApiController@calendar'); Route::get('actions/rating/{id}', 'Api\ActionApiController@rating'); Route::get('collaborations', 'Api\CollaborationApiController@all'); Route::get('tree', 'Api\TreeApiController@tree'); Route::get('tree/activeUnits/{id}', 'Api\TreeApiController@activeUnits'); }); Route::get('faq', 'EtcController@faq'); Route::get('cityofathens', 'TestController@cityofathens'); //////////////////////////////////////////// // Log Viewer // // Route to view logs in a more human way // //////////////////////////////////////////// Route::get('logs', '\Rap2hpoutre\LaravelLogViewer\LogViewerController@index'); //////////// // TESTS // //////////// Route::get('test', 'TestController@test'); Route::post('testPost', 'TestController@test'); Route::get('faker', 'TestController@faker'); Route::get('boxytree', 'TestController@boxytree'); Route::get('experiment', 'TestController@experiment'); Route::get('ekpizo', 'TestController@ekpizo'); // Display all SQL executed in Eloquent Event::listen('illuminate.query', function ($query) { //var_dump($query); });
{ "content_hash": "de1ac83c9a2f616f945bb7b9b0cfca16", "timestamp": "", "source": "github", "line_count": 303, "max_line_length": 113, "avg_line_length": 43.20462046204621, "alnum_prop": 0.7026201206936062, "repo_name": "scify/VoluntEasy", "id": "fe2691ee5a74b95516254d4612d3d3e0782bdbed", "size": "13093", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VoluntEasy/app/Http/routes.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "81534" }, { "name": "HTML", "bytes": "1156229" }, { "name": "JavaScript", "bytes": "890335" }, { "name": "PHP", "bytes": "717271" }, { "name": "Perl", "bytes": "2191" } ], "symlink_target": "" }
package org.kuali.rice.krad.datadictionary; import java.beans.PropertyDescriptor; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.ListUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kuali.rice.core.api.config.property.ConfigContext; import org.kuali.rice.core.api.util.ClassLoaderUtils; import org.kuali.rice.krad.bo.PersistableBusinessObjectExtension; import org.kuali.rice.krad.datadictionary.exception.AttributeValidationException; import org.kuali.rice.krad.datadictionary.exception.CompletionException; import org.kuali.rice.krad.datadictionary.parse.StringListConverter; import org.kuali.rice.krad.datadictionary.parse.StringMapConverter; import org.kuali.rice.krad.datadictionary.uif.UifDictionaryIndex; import org.kuali.rice.krad.service.KRADServiceLocator; import org.kuali.rice.krad.service.PersistenceStructureService; import org.kuali.rice.krad.uif.UifConstants.ViewType; import org.kuali.rice.krad.uif.util.ComponentBeanPostProcessor; import org.kuali.rice.krad.uif.util.UifBeanFactoryPostProcessor; import org.kuali.rice.krad.uif.view.View; import org.kuali.rice.krad.util.ObjectUtils; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.expression.StandardBeanExpressionResolver; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; /** * Encapsulates a bean factory and indexes to the beans within the factory for providing * framework metadata * * @author Kuali Rice Team (rice.collab@kuali.org) */ public class DataDictionary { private static final Log LOG = LogFactory.getLog(DataDictionary.class); protected static boolean validateEBOs = true; protected DefaultListableBeanFactory ddBeans = new DefaultListableBeanFactory(); protected XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ddBeans); protected DataDictionaryIndex ddIndex = new DataDictionaryIndex(ddBeans); protected UifDictionaryIndex uifIndex = new UifDictionaryIndex(ddBeans); protected DataDictionaryMapper ddMapper = new DataDictionaryIndexMapper(); protected Map<String, List<String>> moduleDictionaryFiles = new HashMap<String, List<String>>(); protected List<String> moduleLoadOrder = new ArrayList<String>(); protected ArrayList<String> beanValidationFiles = new ArrayList<String>(); /** * Populates and processes the dictionary bean factory based on the configured files and * performs indexing * * @param allowConcurrentValidation - indicates whether the indexing should occur on a different thread * or the same thread */ public void parseDataDictionaryConfigurationFiles(boolean allowConcurrentValidation) { setupProcessor(ddBeans); loadDictionaryBeans(ddBeans, moduleDictionaryFiles, ddIndex, beanValidationFiles); performDictionaryPostProcessing(allowConcurrentValidation); } /** * Sets up the bean post processor and conversion service * * @param beans - The bean factory for the the dictionary beans */ public static void setupProcessor(DefaultListableBeanFactory beans) { try { // UIF post processor that sets component ids BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance(); beans.addBeanPostProcessor(idPostProcessor); beans.setBeanExpressionResolver(new StandardBeanExpressionResolver()); // special converters for shorthand map and list property syntax GenericConversionService conversionService = new GenericConversionService(); conversionService.addConverter(new StringMapConverter()); conversionService.addConverter(new StringListConverter()); beans.setConversionService(conversionService); } catch (Exception e1) { throw new DataDictionaryException("Cannot create component decorator post processor: " + e1.getMessage(), e1); } } /** * Populates and processes the dictionary bean factory based on the configured files * * @param beans - The bean factory for the dictionary bean * @param moduleDictionaryFiles - List of bean xml files * @param index - Index of the data dictionary beans * @param validationFiles - The List of bean xml files loaded into the bean file */ public void loadDictionaryBeans(DefaultListableBeanFactory beans, Map<String, List<String>> moduleDictionaryFiles, DataDictionaryIndex index, ArrayList<String> validationFiles) { // expand configuration locations into files LOG.info("Starting DD XML File Load"); List<String> allBeanNames = new ArrayList<String>(); for (String namespaceCode : moduleLoadOrder) { List<String> moduleDictionaryLocations = moduleDictionaryFiles.get(namespaceCode); if (moduleDictionaryLocations == null) { continue; } XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(beans); String configFileLocationsArray[] = new String[moduleDictionaryLocations.size()]; configFileLocationsArray = moduleDictionaryLocations.toArray(configFileLocationsArray); for (int i = 0; i < configFileLocationsArray.length; i++) { validationFiles.add(configFileLocationsArray[i]); } try { xmlReader.loadBeanDefinitions(configFileLocationsArray); // get updated bean names from factory and compare to our previous list to get those that // were added by the last namespace List<String> addedBeanNames = Arrays.asList(beans.getBeanDefinitionNames()); addedBeanNames = ListUtils.removeAll(addedBeanNames, allBeanNames); index.addBeanNamesToNamespace(namespaceCode, addedBeanNames); allBeanNames.addAll(addedBeanNames); } catch (Exception e) { throw new DataDictionaryException("Error loading bean definitions: " + e.getLocalizedMessage()); } } LOG.info("Completed DD XML File Load"); } /** * Invokes post processors and builds indexes for the beans contained in the dictionary * * @param allowConcurrentValidation - indicates whether the indexing should occur on a different thread * or the same thread */ public void performDictionaryPostProcessing(boolean allowConcurrentValidation) { PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer(); propertyPlaceholderConfigurer.setProperties(ConfigContext.getCurrentContextConfig().getProperties()); propertyPlaceholderConfigurer.postProcessBeanFactory(ddBeans); DictionaryBeanFactoryPostProcessor dictionaryBeanPostProcessor = new DictionaryBeanFactoryPostProcessor(this, ddBeans); dictionaryBeanPostProcessor.postProcessBeanFactory(); // post processes UIF beans for pulling out expressions within property values UifBeanFactoryPostProcessor factoryPostProcessor = new UifBeanFactoryPostProcessor(); factoryPostProcessor.postProcessBeanFactory(ddBeans); if (allowConcurrentValidation) { Thread t = new Thread(ddIndex); t.start(); Thread t2 = new Thread(uifIndex); t2.start(); } else { ddIndex.run(); uifIndex.run(); } } public void validateDD(boolean validateEbos) { DataDictionary.validateEBOs = validateEbos; /* ValidationController validator = new ValidationController(); String files[] = new String[beanValidationFiles.size()]; files = beanValidationFiles.toArray(files); validator.validate(files, xmlReader.getResourceLoader(), ddBeans, LOG, false);*/ Map<String, DataObjectEntry> doBeans = ddBeans.getBeansOfType(DataObjectEntry.class); for (DataObjectEntry entry : doBeans.values()) { entry.completeValidation(); } Map<String, DocumentEntry> docBeans = ddBeans.getBeansOfType(DocumentEntry.class); for (DocumentEntry entry : docBeans.values()) { entry.completeValidation(); } } public void validateDD() { validateDD(true); } /** * Adds a location of files or a individual resource to the data dictionary * * <p> * The location can either be an XML file on the classpath or a file or folder location within the * file system. If a folder location is given, the folder and all sub-folders will be traversed and any * XML files will be added to the dictionary * </p> * * @param namespaceCode - namespace the beans loaded from the location should be associated with * @param location - classpath resource or file system location * @throws IOException */ public void addConfigFileLocation(String namespaceCode, String location) throws IOException { // add module to load order so we load in the order modules were configured if (!moduleLoadOrder.contains(namespaceCode)) { moduleLoadOrder.add(namespaceCode); } indexSource(namespaceCode, location); } /** * Processes a given source for XML files to populate the dictionary with * * @param namespaceCode - namespace the beans loaded from the location should be associated with * @param sourceName - a file system or classpath resource locator * @throws IOException */ protected void indexSource(String namespaceCode, String sourceName) throws IOException { if (sourceName == null) { throw new DataDictionaryException("Source Name given is null"); } if (!sourceName.endsWith(".xml")) { Resource resource = getFileResource(sourceName); if (resource.exists()) { try { indexSource(namespaceCode, resource.getFile()); } catch (IOException e) { // ignore resources that exist and cause an error here // they may be directories resident in jar files LOG.debug("Skipped existing resource without absolute file path"); } } else { LOG.warn("Could not find " + sourceName); throw new DataDictionaryException("DD Resource " + sourceName + " not found"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("adding sourceName " + sourceName + " "); } Resource resource = getFileResource(sourceName); if (!resource.exists()) { throw new DataDictionaryException("DD Resource " + sourceName + " not found"); } addModuleDictionaryFile(namespaceCode, sourceName); } } protected Resource getFileResource(String sourceName) { DefaultResourceLoader resourceLoader = new DefaultResourceLoader(ClassLoaderUtils.getDefaultClassLoader()); return resourceLoader.getResource(sourceName); } protected void indexSource(String namespaceCode, File dir) { for (File file : dir.listFiles()) { if (file.isDirectory()) { indexSource(namespaceCode, file); } else if (file.getName().endsWith(".xml")) { addModuleDictionaryFile(namespaceCode, "file:" + file.getAbsolutePath()); } else { if (LOG.isDebugEnabled()) { LOG.debug("Skipping non xml file " + file.getAbsolutePath() + " in DD load"); } } } } /** * Adds a file location to the list of dictionary files for the given namespace code * * @param namespaceCode - namespace to add location for * @param location - file or resource location to add */ protected void addModuleDictionaryFile(String namespaceCode, String location) { List<String> moduleFileLocations = new ArrayList<String>(); if (moduleDictionaryFiles.containsKey(namespaceCode)) { moduleFileLocations = moduleDictionaryFiles.get(namespaceCode); } moduleFileLocations.add(location); moduleDictionaryFiles.put(namespaceCode, moduleFileLocations); } /** * Mapping of namespace codes to dictionary files that are associated with * that namespace * * @return Map<String, List<String>> where map key is namespace code, and value is list of dictionary * file locations */ public Map<String, List<String>> getModuleDictionaryFiles() { return moduleDictionaryFiles; } /** * Setter for the map of module dictionary files * * @param moduleDictionaryFiles */ public void setModuleDictionaryFiles(Map<String, List<String>> moduleDictionaryFiles) { this.moduleDictionaryFiles = moduleDictionaryFiles; } /** * Order modules should be loaded into the dictionary * * <p> * Modules are loaded in the order they are found in this list. If not explicity set, they will be loaded in * the order their dictionary file locations are added * </p> * * @return List<String> list of namespace codes indicating the module load order */ public List<String> getModuleLoadOrder() { return moduleLoadOrder; } /** * Setter for the list of namespace codes indicating the module load order * * @param moduleLoadOrder */ public void setModuleLoadOrder(List<String> moduleLoadOrder) { this.moduleLoadOrder = moduleLoadOrder; } /** * Sets the DataDictionaryMapper * * @param mapper the datadictionary mapper */ public void setDataDictionaryMapper(DataDictionaryMapper mapper) { this.ddMapper = mapper; } /** * @param className * @return BusinessObjectEntry for the named class, or null if none exists */ @Deprecated public BusinessObjectEntry getBusinessObjectEntry(String className) { return ddMapper.getBusinessObjectEntry(ddIndex, className); } /** * @param className * @return BusinessObjectEntry for the named class, or null if none exists */ public DataObjectEntry getDataObjectEntry(String className) { return ddMapper.getDataObjectEntry(ddIndex, className); } /** * This method gets the business object entry for a concrete class * * @param className * @return */ public BusinessObjectEntry getBusinessObjectEntryForConcreteClass(String className) { return ddMapper.getBusinessObjectEntryForConcreteClass(ddIndex, className); } /** * @return List of businessObject classnames */ public List<String> getBusinessObjectClassNames() { return ddMapper.getBusinessObjectClassNames(ddIndex); } /** * @return Map of (classname, BusinessObjectEntry) pairs */ public Map<String, BusinessObjectEntry> getBusinessObjectEntries() { return ddMapper.getBusinessObjectEntries(ddIndex); } /** * @param className * @return DataDictionaryEntryBase for the named class, or null if none * exists */ public DataDictionaryEntry getDictionaryObjectEntry(String className) { return ddMapper.getDictionaryObjectEntry(ddIndex, className); } /** * Returns the KNS document entry for the given lookup key. The documentTypeDDKey is interpreted * successively in the following ways until a mapping is found (or none if found): * <ol> * <li>KEW/workflow document type</li> * <li>business object class name</li> * <li>maintainable class name</li> * </ol> * This mapping is compiled when DataDictionary files are parsed on startup (or demand). Currently this * means the mapping is static, and one-to-one (one KNS document maps directly to one and only * one key). * * @param documentTypeDDKey the KEW/workflow document type name * @return the KNS DocumentEntry if it exists */ public DocumentEntry getDocumentEntry(String documentTypeDDKey) { return ddMapper.getDocumentEntry(ddIndex, documentTypeDDKey); } /** * Note: only MaintenanceDocuments are indexed by businessObject Class * * This is a special case that is referenced in one location. Do we need * another map for this stuff?? * * @param businessObjectClass * @return DocumentEntry associated with the given Class, or null if there * is none */ public MaintenanceDocumentEntry getMaintenanceDocumentEntryForBusinessObjectClass(Class<?> businessObjectClass) { return ddMapper.getMaintenanceDocumentEntryForBusinessObjectClass(ddIndex, businessObjectClass); } public Map<String, DocumentEntry> getDocumentEntries() { return ddMapper.getDocumentEntries(ddIndex); } /** * Returns the View entry identified by the given id * * @param viewId unique id for view * @return View instance associated with the id */ public View getViewById(String viewId) { return ddMapper.getViewById(uifIndex, viewId); } /** * Returns the View entry identified by the given id, meant for view readonly * access (not running the lifecycle but just checking configuration) * * @param viewId unique id for view * @return View instance associated with the id */ public View getImmutableViewById(String viewId) { return ddMapper.getImmutableViewById(uifIndex, viewId); } /** * Returns View instance identified by the view type name and index * * @param viewTypeName - type name for the view * @param indexKey - Map of index key parameters, these are the parameters the * indexer used to index the view initially and needs to identify * an unique view instance * @return View instance that matches the given index */ public View getViewByTypeIndex(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.getViewByTypeIndex(uifIndex, viewTypeName, indexKey); } /** * Returns the view id for the view that matches the given view type and index * * @param viewTypeName type name for the view * @param indexKey Map of index key parameters, these are the parameters the * indexer used to index the view initially and needs to identify * an unique view instance * @return id for the view that matches the view type and index or null if a match is not found */ public String getViewIdByTypeIndex(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.getViewIdByTypeIndex(uifIndex, viewTypeName, indexKey); } /** * Indicates whether a <code>View</code> exists for the given view type and index information * * @param viewTypeName - type name for the view * @param indexKey - Map of index key parameters, these are the parameters the * indexer used to index the view initially and needs to identify * an unique view instance * @return boolean true if view exists, false if not */ public boolean viewByTypeExist(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.viewByTypeExist(uifIndex, viewTypeName, indexKey); } /** * Gets all <code>View</code> prototypes configured for the given view type * name * * @param viewTypeName - view type name to retrieve * @return List<View> view prototypes with the given type name, or empty * list */ public List<View> getViewsForType(ViewType viewTypeName) { return ddMapper.getViewsForType(uifIndex, viewTypeName); } /** * Returns an object from the dictionary by its spring bean name * * @param beanName - id or name for the bean definition * @return Object object instance created or the singleton being maintained */ public Object getDictionaryObject(String beanName) { return ddBeans.getBean(beanName); } /** * Indicates whether the data dictionary contains a bean with the given id * * @param id - id of the bean to check for * @return boolean true if dictionary contains bean, false otherwise */ public boolean containsDictionaryObject(String id) { return ddBeans.containsBean(id); } /** * Retrieves the configured property values for the view bean definition associated with the given id * * <p> * Since constructing the View object can be expensive, when metadata only is needed this method can be used * to retrieve the configured property values. Note this looks at the merged bean definition * </p> * * @param viewId - id for the view to retrieve * @return PropertyValues configured on the view bean definition, or null if view is not found */ public PropertyValues getViewPropertiesById(String viewId) { return ddMapper.getViewPropertiesById(uifIndex, viewId); } /** * Retrieves the configured property values for the view bean definition associated with the given type and * index * * <p> * Since constructing the View object can be expensive, when metadata only is needed this method can be used * to retrieve the configured property values. Note this looks at the merged bean definition * </p> * * @param viewTypeName - type name for the view * @param indexKey - Map of index key parameters, these are the parameters the indexer used to index * the view initially and needs to identify an unique view instance * @return PropertyValues configured on the view bean definition, or null if view is not found */ public PropertyValues getViewPropertiesByType(ViewType viewTypeName, Map<String, String> indexKey) { return ddMapper.getViewPropertiesByType(uifIndex, viewTypeName, indexKey); } /** * Retrieves the list of dictionary bean names that are associated with the given namespace code * * @param namespaceCode - namespace code to retrieve associated bean names for * @return List<String> bean names associated with the namespace */ public List<String> getBeanNamesForNamespace(String namespaceCode) { List<String> namespaceBeans = new ArrayList<String>(); Map<String, List<String>> dictionaryBeansByNamespace = ddIndex.getDictionaryBeansByNamespace(); if (dictionaryBeansByNamespace.containsKey(namespaceCode)) { namespaceBeans = dictionaryBeansByNamespace.get(namespaceCode); } return namespaceBeans; } /** * Retrieves the namespace code the given bean name is associated with * * @param beanName - name of the dictionary bean to find namespace code for * @return String namespace code the bean is associated with, or null if a namespace was not found */ public String getNamespaceForBeanDefinition(String beanName) { String beanNamespace = null; Map<String, List<String>> dictionaryBeansByNamespace = ddIndex.getDictionaryBeansByNamespace(); for (Map.Entry<String, List<String>> moduleDefinitions : dictionaryBeansByNamespace.entrySet()) { List<String> namespaceBeans = moduleDefinitions.getValue(); if (namespaceBeans.contains(beanName)) { beanNamespace = moduleDefinitions.getKey(); break; } } return beanNamespace; } /** * @param targetClass * @param propertyName * @return true if the given propertyName names a property of the given class * @throws CompletionException if there is a problem accessing the named property on the given class */ public static boolean isPropertyOf(Class targetClass, String propertyName) { if (targetClass == null) { throw new IllegalArgumentException("invalid (null) targetClass"); } if (StringUtils.isBlank(propertyName)) { throw new IllegalArgumentException("invalid (blank) propertyName"); } PropertyDescriptor propertyDescriptor = buildReadDescriptor(targetClass, propertyName); boolean isPropertyOf = (propertyDescriptor != null); return isPropertyOf; } /** * @param targetClass * @param propertyName * @return true if the given propertyName names a Collection property of the given class * @throws CompletionException if there is a problem accessing the named property on the given class */ public static boolean isCollectionPropertyOf(Class targetClass, String propertyName) { boolean isCollectionPropertyOf = false; PropertyDescriptor propertyDescriptor = buildReadDescriptor(targetClass, propertyName); if (propertyDescriptor != null) { Class clazz = propertyDescriptor.getPropertyType(); if ((clazz != null) && Collection.class.isAssignableFrom(clazz)) { isCollectionPropertyOf = true; } } return isCollectionPropertyOf; } public static PersistenceStructureService persistenceStructureService; /** * @return the persistenceStructureService */ public static PersistenceStructureService getPersistenceStructureService() { if (persistenceStructureService == null) { persistenceStructureService = KRADServiceLocator.getPersistenceStructureService(); } return persistenceStructureService; } /** * This method determines the Class of the attributeName passed in. Null will be returned if the member is not * available, or if * a reflection exception is thrown. * * @param boClass - Class that the attributeName property exists in. * @param attributeName - Name of the attribute you want a class for. * @return The Class of the attributeName, if the attribute exists on the rootClass. Null otherwise. */ public static Class getAttributeClass(Class boClass, String attributeName) { // fail loudly if the attributeName isnt a member of rootClass if (!isPropertyOf(boClass, attributeName)) { throw new AttributeValidationException( "unable to find attribute '" + attributeName + "' in rootClass '" + boClass.getName() + "'"); } //Implementing Externalizable Business Object Services... //The boClass can be an interface, hence handling this separately, //since the original method was throwing exception if the class could not be instantiated. if (boClass.isInterface()) { return getAttributeClassWhenBOIsInterface(boClass, attributeName); } else { return getAttributeClassWhenBOIsClass(boClass, attributeName); } } /** * This method gets the property type of the given attributeName when the bo class is a concrete class * * @param boClass * @param attributeName * @return */ private static Class getAttributeClassWhenBOIsClass(Class boClass, String attributeName) { Object boInstance; try { boInstance = boClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Unable to instantiate Data Object: " + boClass, e); } // attempt to retrieve the class of the property try { return ObjectUtils.getPropertyType(boInstance, attributeName, getPersistenceStructureService()); } catch (Exception e) { throw new RuntimeException( "Unable to determine property type for: " + boClass.getName() + "." + attributeName, e); } } /** * This method gets the property type of the given attributeName when the bo class is an interface * This method will also work if the bo class is not an interface, * but that case requires special handling, hence a separate method getAttributeClassWhenBOIsClass * * @param boClass * @param attributeName * @return */ private static Class getAttributeClassWhenBOIsInterface(Class boClass, String attributeName) { if (boClass == null) { throw new IllegalArgumentException("invalid (null) boClass"); } if (StringUtils.isBlank(attributeName)) { throw new IllegalArgumentException("invalid (blank) attributeName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = attributeName.split("\\."); int lastLevel = intermediateProperties.length - 1; Class currentClass = boClass; for (int i = 0; i <= lastLevel; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (propertyDescriptor != null) { Class propertyType = propertyDescriptor.getPropertyType(); if (propertyType.equals(PersistableBusinessObjectExtension.class)) { propertyType = getPersistenceStructureService().getBusinessObjectAttributeClass(currentClass, currentPropertyName); } if (Collection.class.isAssignableFrom(propertyType)) { // TODO: determine property type using generics type definition throw new AttributeValidationException( "Can't determine the Class of Collection elements because when the business object is an (possibly ExternalizableBusinessObject) interface."); } else { currentClass = propertyType; } } else { throw new AttributeValidationException( "Can't find getter method of " + boClass.getName() + " for property " + attributeName); } } return currentClass; } /** * This method determines the Class of the elements in the collectionName passed in. * * @param boClass Class that the collectionName collection exists in. * @param collectionName the name of the collection you want the element class for * @return */ public static Class getCollectionElementClass(Class boClass, String collectionName) { if (boClass == null) { throw new IllegalArgumentException("invalid (null) boClass"); } if (StringUtils.isBlank(collectionName)) { throw new IllegalArgumentException("invalid (blank) collectionName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = collectionName.split("\\."); Class currentClass = boClass; for (int i = 0; i < intermediateProperties.length; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (propertyDescriptor != null) { Class type = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(type)) { if (getPersistenceStructureService().isPersistable(currentClass)) { Map<String, Class> collectionClasses = new HashMap<String, Class>(); collectionClasses = getPersistenceStructureService().listCollectionObjectTypes(currentClass); currentClass = collectionClasses.get(currentPropertyName); } else { throw new RuntimeException( "Can't determine the Class of Collection elements because persistenceStructureService.isPersistable(" + currentClass.getName() + ") returns false."); } } else { currentClass = propertyDescriptor.getPropertyType(); } } } return currentClass; } static private Map<String, Map<String, PropertyDescriptor>> cache = new TreeMap<String, Map<String, PropertyDescriptor>>(); /** * @param propertyClass * @param propertyName * @return PropertyDescriptor for the getter for the named property of the given class, if one exists. */ public static PropertyDescriptor buildReadDescriptor(Class propertyClass, String propertyName) { if (propertyClass == null) { throw new IllegalArgumentException("invalid (null) propertyClass"); } if (StringUtils.isBlank(propertyName)) { throw new IllegalArgumentException("invalid (blank) propertyName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = propertyName.split("\\."); int lastLevel = intermediateProperties.length - 1; Class currentClass = propertyClass; for (int i = 0; i <= lastLevel; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (i < lastLevel) { if (propertyDescriptor != null) { Class propertyType = propertyDescriptor.getPropertyType(); if (propertyType.equals(PersistableBusinessObjectExtension.class)) { propertyType = getPersistenceStructureService().getBusinessObjectAttributeClass(currentClass, currentPropertyName); } if (Collection.class.isAssignableFrom(propertyType)) { if (getPersistenceStructureService().isPersistable(currentClass)) { Map<String, Class> collectionClasses = new HashMap<String, Class>(); collectionClasses = getPersistenceStructureService().listCollectionObjectTypes( currentClass); currentClass = collectionClasses.get(currentPropertyName); } else { throw new RuntimeException( "Can't determine the Class of Collection elements because persistenceStructureService.isPersistable(" + currentClass.getName() + ") returns false."); } } else { currentClass = propertyType; } } } } return propertyDescriptor; } /** * @param propertyClass * @param propertyName * @return PropertyDescriptor for the getter for the named property of the given class, if one exists. */ public static PropertyDescriptor buildSimpleReadDescriptor(Class propertyClass, String propertyName) { if (propertyClass == null) { throw new IllegalArgumentException("invalid (null) propertyClass"); } if (StringUtils.isBlank(propertyName)) { throw new IllegalArgumentException("invalid (blank) propertyName"); } PropertyDescriptor p = null; // check to see if we've cached this descriptor already. if yes, return true. String propertyClassName = propertyClass.getName(); Map<String, PropertyDescriptor> m = cache.get(propertyClassName); if (null != m) { p = m.get(propertyName); if (null != p) { return p; } } // Use PropertyUtils.getPropertyDescriptors instead of manually constructing PropertyDescriptor because of // issues with introspection and generic/co-variant return types // See https://issues.apache.org/jira/browse/BEANUTILS-340 for more details PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(propertyClass); if (ArrayUtils.isNotEmpty(descriptors)) { for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getName().equals(propertyName)) { p = descriptor; } } } // cache the property descriptor if we found it. if (p != null) { if (m == null) { m = new TreeMap<String, PropertyDescriptor>(); cache.put(propertyClassName, m); } m.put(propertyName, p); } return p; } public Set<InactivationBlockingMetadata> getAllInactivationBlockingMetadatas(Class blockedClass) { return ddMapper.getAllInactivationBlockingMetadatas(ddIndex, blockedClass); } /** * This method gathers beans of type BeanOverride and invokes each one's performOverride() method. */ // KULRICE-4513 public void performBeanOverrides() { Collection<BeanOverride> beanOverrides = ddBeans.getBeansOfType(BeanOverride.class).values(); if (beanOverrides.isEmpty()) { LOG.info("DataDictionary.performOverrides(): No beans to override"); } for (BeanOverride beanOverride : beanOverrides) { Object bean = ddBeans.getBean(beanOverride.getBeanName()); beanOverride.performOverride(bean); LOG.info("DataDictionary.performOverrides(): Performing override on bean: " + bean.toString()); } } }
{ "content_hash": "ef947bb2a5036c166ec0eacc98694453", "timestamp": "", "source": "github", "line_count": 965, "max_line_length": 170, "avg_line_length": 41.167875647668396, "alnum_prop": 0.644146298487175, "repo_name": "ua-eas/ksd-kc5.2.1-rice2.3.6-ua", "id": "89e46b1b2d82c34921a83b260420b40a3e8f6dc1", "size": "40362", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/datadictionary/DataDictionary.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "542248" }, { "name": "Groovy", "bytes": "2403552" }, { "name": "HTML", "bytes": "3275928" }, { "name": "Java", "bytes": "30805440" }, { "name": "JavaScript", "bytes": "2486893" }, { "name": "PHP", "bytes": "15766" }, { "name": "PLSQL", "bytes": "108325" }, { "name": "SQLPL", "bytes": "51212" }, { "name": "Shell", "bytes": "1808" }, { "name": "XSLT", "bytes": "109576" } ], "symlink_target": "" }
/** * @file * * Implementation of POSIX thread condition variable alikes using actual POSIX * threads condition variables. */ #include "amp_condition_variable.h" #include <assert.h> #include <errno.h> #include <stddef.h> #include "amp_return_code.h" #include "amp_mutex.h" #include "amp_raw_mutex.h" #include "amp_raw_condition_variable.h" int amp_raw_condition_variable_init(amp_condition_variable_t cond) { assert(NULL != cond); int retval = pthread_cond_init(&cond->cond, NULL); switch (retval){ case 0: /* retval is already equal to AMP_SUCCES */ /* Fallthrough */ case ENOMEM: /* retval is already equal to AMP_NOMEM */ break; case EAGAIN: /* Platform resources not available */ retval = AMP_ERROR; break; default: /* EINVAL, EBUSY - programming error */ assert(0); retval = AMP_ERROR; } return retval; } int amp_raw_condition_variable_finalize(amp_condition_variable_t cond) { assert(NULL != cond); int retval = pthread_cond_destroy(&cond->cond); switch (retval){ case 0: /* retval is already equal to AMP_SUCCESS */ break; default: /* EINVAL, EBUSY - programming error */ assert(0); retval = AMP_ERROR; } return retval; } int amp_condition_variable_broadcast(amp_condition_variable_t cond) { assert(NULL != cond); int retval = pthread_cond_broadcast(&cond->cond); if (0 != retval) { /* Condition variable is invalid which must not happen */ assert(0); retval = AMP_ERROR; } return retval; } int amp_condition_variable_signal(amp_condition_variable_t cond) { assert(NULL != cond); int retval = pthread_cond_signal(&cond->cond); if (0 != retval) { /* Condition variable is invalid which must not happen */ assert(0); retval = AMP_ERROR; } return retval; } int amp_condition_variable_wait(amp_condition_variable_t cond, amp_mutex_t mutex) { assert(NULL != cond); assert(NULL != mutex); int retval = pthread_cond_wait(&cond->cond, &mutex->mutex); if (0 != retval) { /* Condition variable or mutex are invalid which must not happen */ assert(0); retval = AMP_ERROR; } return retval; }
{ "content_hash": "cad964459ea3ad7b6412b602451f0e2c", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 78, "avg_line_length": 21.4, "alnum_prop": 0.5798455912230801, "repo_name": "bjoernknafla/amp", "id": "ca07c9a0b20a553210450b19ef11e188b20f211d", "size": "4143", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/c/amp/amp_condition_variable_pthreads.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "345080" }, { "name": "C++", "bytes": "154471" }, { "name": "Objective-C", "bytes": "3931" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | AUTO-LOADER | ------------------------------------------------------------------- | This file specifies which systems should be loaded by default. | | In order to keep the framework as light-weight as possible only the | absolute minimal resources are loaded by default. For example, | the database is not connected to automatically since no assumption | is made regarding whether you intend to use it. This file lets | you globally define which systems you would like loaded with every | request. | | ------------------------------------------------------------------- | Instructions | ------------------------------------------------------------------- | | These are the things you can load automatically: | | 1. Packages | 2. Libraries | 3. Drivers | 4. Helper files | 5. Custom config files | 6. Language files | 7. Models | */ /* | ------------------------------------------------------------------- | Auto-load Packages | ------------------------------------------------------------------- | Prototype: | | $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared'); | */ $autoload['packages'] = array(); /* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in system/libraries/ or your | application/libraries/ directory, with the addition of the | 'database' library, which is somewhat of a special case. | | Prototype: | | $autoload['libraries'] = array('database', 'email', 'session'); | | You can also supply an alternative library name to be assigned | in the controller: | | $autoload['libraries'] = array('user_agent' => 'ua'); */ $autoload['libraries'] = array('database','session','upload','fpdf'); /* | ------------------------------------------------------------------- | Auto-load Drivers | ------------------------------------------------------------------- | These classes are located in system/libraries/ or in your | application/libraries/ directory, but are also placed inside their | own subdirectory and they extend the CI_Driver_Library class. They | offer multiple interchangeable driver options. | | Prototype: | | $autoload['drivers'] = array('cache'); | | You can also supply an alternative property name to be assigned in | the controller: | | $autoload['drivers'] = array('cache' => 'cch'); | */ $autoload['drivers'] = array(); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('url','file'); /* | ------------------------------------------------------------------- | Auto-load Config files | ------------------------------------------------------------------- | Prototype: | | $autoload['config'] = array('config1', 'config2'); | | NOTE: This item is intended for use ONLY if you have created custom | config files. Otherwise, leave it blank. | */ $autoload['config'] = array(); /* | ------------------------------------------------------------------- | Auto-load Language files | ------------------------------------------------------------------- | Prototype: | | $autoload['language'] = array('lang1', 'lang2'); | | NOTE: Do not include the "_lang" part of your file. For example | "codeigniter_lang.php" would be referenced as array('codeigniter'); | */ $autoload['language'] = array(); /* | ------------------------------------------------------------------- | Auto-load Models | ------------------------------------------------------------------- | Prototype: | | $autoload['model'] = array('first_model', 'second_model'); | | You can also supply an alternative model name to be assigned | in the controller: | | $autoload['model'] = array('first_model' => 'first'); */ $autoload['model'] = array('apps_model','apps_model' => 'qm');
{ "content_hash": "605e835fb141aa0d17b07563e2014b52", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 77, "avg_line_length": 30.414814814814815, "alnum_prop": 0.47832440331222603, "repo_name": "hadyfasters/aplikasi_cuti", "id": "8321e07e80483e9c54dbcc0e9796b310b258f09d", "size": "4106", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/config/autoload.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "401" }, { "name": "CSS", "bytes": "683213" }, { "name": "HTML", "bytes": "15346935" }, { "name": "JavaScript", "bytes": "3016708" }, { "name": "PHP", "bytes": "2047693" } ], "symlink_target": "" }
layout: default modal-id: 1 date: 2014-07-18 img: command.png alt: image-alt project-date: April 2014 client: Start Bootstrap category: Web Development description: Version control is important ---
{ "content_hash": "091dc15be4c3ae1077def166e1992ade", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 41, "avg_line_length": 18.09090909090909, "alnum_prop": 0.7788944723618091, "repo_name": "RprogameR/RprogameR.github.io", "id": "a92a81899d38b9b79c41221eb1bfbfa88821e52b", "size": "203", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2014-07-18-CLI-Git.markdown", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8311" }, { "name": "HTML", "bytes": "29785" }, { "name": "JavaScript", "bytes": "43594" }, { "name": "PHP", "bytes": "1193" } ], "symlink_target": "" }
''' Production Configurations - Use djangosecure - Use Amazon's S3 for storing static files and uploaded media - Use mailgun to send emails - Use Redis on Heroku ''' from __future__ import absolute_import, unicode_literals from boto.s3.connection import OrdinaryCallingFormat from django.utils import six from .common import * # noqa # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ SECRET_KEY = env("DJANGO_SECRET_KEY") # This ensures that Django will be able to detect a secure connection # properly on Heroku. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # django-secure # ------------------------------------------------------------------------------ INSTALLED_APPS += ("djangosecure", ) SECURITY_MIDDLEWARE = ( 'djangosecure.middleware.SecurityMiddleware', ) # Make sure djangosecure.middleware.SecurityMiddleware is listed first MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES # set this to 60 seconds and then to 518400 when you can prove it works SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True) SECURE_FRAME_DENY = env.bool("DJANGO_SECURE_FRAME_DENY", default=True) SECURE_CONTENT_TYPE_NOSNIFF = env.bool( "DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True) SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = False SESSION_COOKIE_HTTPONLY = True SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) # SITE CONFIGURATION # ------------------------------------------------------------------------------ # Hosts/domain names that are valid for this site # See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['basicincome.rocks']) # END SITE CONFIGURATION INSTALLED_APPS += ("gunicorn", ) # STORAGE CONFIGURATION # ------------------------------------------------------------------------------ # Uploaded Media Files # ------------------------ # See: http://django-storages.readthedocs.org/en/latest/index.html INSTALLED_APPS += ( 'storages', ) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_AUTO_CREATE_BUCKET = True AWS_QUERYSTRING_AUTH = False AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat() # AWS cache settings, don't change unless you know what you're doing: AWS_EXPIRY = 60 * 60 * 24 * 7 # TODO See: https://github.com/jschneier/django-storages/issues/47 # Revert the following and use str after the above-mentioned bug is fixed in # either django-storage-redux or boto AWS_HEADERS = { 'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % ( AWS_EXPIRY, AWS_EXPIRY)) } # URL that handles the media served from MEDIA_ROOT, used for managing # stored files. MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME # Static Assets # ------------------------ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # EMAIL # ------------------------------------------------------------------------------ DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL', default='basicincome <noreply@basicincome.rocks>') EMAIL_BACKEND = 'django_mailgun.MailgunBackend' MAILGUN_ACCESS_KEY = env('DJANGO_MAILGUN_API_KEY') MAILGUN_SERVER_NAME = env('DJANGO_MAILGUN_SERVER_NAME') EMAIL_SUBJECT_PREFIX = env("DJANGO_EMAIL_SUBJECT_PREFIX", default='[basicincome] ') SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ # See: # https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader TEMPLATES[0]['OPTIONS']['loaders'] = [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ] # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ DATABASES['default'] = env.db("DATABASE_URL") # CACHING # ------------------------------------------------------------------------------ # Heroku URL does not pass the DB number, so we parse it in CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "{0}/{1}".format(env.cache_url('REDIS_URL', default="redis://127.0.0.1:6379"), 0), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "IGNORE_EXCEPTIONS": True, # mimics memcache behavior. # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior } } } # LOGGING CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True }, 'django.security.DisallowedHost': { 'level': 'ERROR', 'handlers': ['console', 'mail_admins'], 'propagate': True } } } # Custom Admin URL, use {% url 'admin:index' %} ADMIN_URL = env('DJANGO_ADMIN_URL') # Your production stuff: Below this line define 3rd party library settings
{ "content_hash": "414d15daff74d54b7e39f65b95216472", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 117, "avg_line_length": 35.58638743455497, "alnum_prop": 0.6017360600264823, "repo_name": "aparamo/basicincome", "id": "c2c47fe6d6080c7841ebb4604222230e91b93a7a", "size": "6821", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/settings/production.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1768" }, { "name": "HTML", "bytes": "20184" }, { "name": "JavaScript", "bytes": "3142" }, { "name": "Nginx", "bytes": "1095" }, { "name": "Python", "bytes": "38781" }, { "name": "Shell", "bytes": "4535" } ], "symlink_target": "" }
package de.skuzzle.jeve; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * <p> * This class is the base of all events that can be fired. It holds the source * of the event and provides methods to stop delegation to further listeners if * this event has been handled by one listener. Events are meant to be short * living objects which are only used once - one Event instance for each call to * {@link EventProvider#dispatch(Event, java.util.function.BiConsumer) dispatch} * . Any different usage might result in undefined behavior, especially when * using the {@link #isHandled()} property. Also, to prevent memory leaks, Event * objects should never be stored over longer time. * </p> * <p> * Events explicitly belong to one kind of {@link Listener} implementation which * is able to handle it. The class of this listener is passed to the constructor * and queried by the {@link EventProvider} when collecting a list of targeted * listeners for a dispatch action. * </p> * * <p> * Events are used in conjunction with the {@link EventProvider} and its * {@link EventProvider#dispatch(Event, java.util.function.BiConsumer, ExceptionCallback) * dispatch} method. The dispatch method serves for notifying all registered * listeners with a certain event. The EventProvider will stop notifying further * listeners as soon as one listener sets this class' {@link #isHandled()} to * <code>true</code>. * </p> * * <h2>Note on multi-threading</h2> * <p> * Event objects are not thread safe! Some EventProviders dispatch events * asynchronously. If the same event instance is used within different threads, * avoid modifying properties of the Event. Those modifications will result in * undefined behavior. * </p> * * @param <T> Type of the source of this event. * @param <L> Type of the listener which can handle this event. * @author Simon Taddiken * @since 1.0.0 * @version 2.0.0 */ public class Event<T, L extends Listener> { /** The source of the event */ private final T source; /** Whether this event has been marked as handled */ private boolean handled; /** The class of the listener which can handle this event */ private final Class<L> listenerClass; /** * Whether this event was prevented the last time it was passed to any * dispatch method. * * @since 3.0.0 */ private boolean prevented; /** * Map for assigning further objects to this event. Map is lazily * initialized. */ private Map<String, Object> properties; /** * Creates a new event with a given source. * * @param source The source of this event. * @param listenerClass The type of the listener which can handle this * event. This value must not be <code>null</code>. */ public Event(T source, Class<L> listenerClass) { if (source == null) { throw new IllegalArgumentException("source is null"); } else if (listenerClass == null) { throw new IllegalArgumentException("listenerClass is null"); } this.source = source; this.listenerClass = listenerClass; this.handled = false; } /** * Returns the Map that is used to store properties in this event instance. * All modifications to that map are directly reflected to its Event * instance. * * @return The property Map of this event. * @since 3.0.0 */ public Map<String, Object> getProperties() { if (this.properties == null) { this.properties = new HashMap<>(); } return this.properties; } /** * Returns a value that has been stored using * {@link #setValue(String, Object)}. As this method is generic, the value * will automatically be casted to the target type of the expression in * which this method is called. So this method has to be used with caution * in respect to type safety. * * @param <E> Type of the resulting value. * @param key The key of the value to retrieve. * @return The value or an empty optional if the value does not exist. * @since 3.0.0 * @see #getValueAs(String, Class) */ @SuppressWarnings("unchecked") public <E> Optional<E> getValue(String key) { if (this.properties == null) { return Optional.empty(); } return Optional.ofNullable((E) getProperties().get(key)); } /** * Returns a value that has been stored using * {@link #setValue(String, Object)}. The value will be casted to the given * type. * * @param <E> Type of the resulting value. * @param key The key of the value to retrieve. * @param type The type that the value will be casted to. * @return The value or an empty optional if the value does not exist. * @see #getValue(String) */ public <E> Optional<E> getValueAs(String key, Class<E> type) { if (this.properties == null) { return Optional.empty(); } return Optional.ofNullable(type.cast(getProperties().get(key))); } /** * Adds the given key-value mapping to this Event. The value can be queried * using {@link #getValue(String)}. * <p> * <b>Note:</b> Storing properties on events is generally discouraged in * favor of creating explicit attributes with getters. However, there might * arise situations in which you must attach further properties to an event * without being able to modify its original source code. In these * situations, storing properties with a String key might be useful. * * @param key The key under which the value is stored. * @param value The value to store. * @since 3.0.0 * @see #getValue(String) * @see #getProperties() */ public void setValue(String key, Object value) { getProperties().put(key, value); } /** * Gets the source of this event. * * @return The source of this event. */ public T getSource() { return this.source; } /** * Whether this event was prevented the last time it has been passed to any * dispatch method of an {@link EventProvider}. * * @return Whether this event has been prevented. */ public boolean isPrevented() { return this.prevented; } /** * Called only by {@link EventProvider EventProvider's} dispatch method if * this event was prevented from being dispatched. * * @param prevented Whether the event was prevented. */ public void setPrevented(boolean prevented) { this.prevented = prevented; } /** * Gets the type of the listener which can handle this event. * * @return The listener's type. * @version 2.0.0 */ public Class<L> getListenerClass() { return this.listenerClass; } /** * Gets whether this event was already handled. If this returns * <code>true</code>, no further listeners will be notified about this * event. * * @return Whether this event was handled. */ public boolean isHandled() { return this.handled; } /** * Sets whether this event was already handled. If an event has been marked * as "handled", no further listeners will be notified about it. * * <p> * Note that setting an event to be handled might have unintended side * effects when using an {@link EventProvider} which is not * {@link EventProvider#isSequential() sequential}. * </p> * * @param isHandled Whether this event was handled. */ public void setHandled(boolean isHandled) { this.handled = isHandled; } @Override public String toString() { final StringBuilder b = new StringBuilder(); b.append(getClass().getSimpleName()); b.append("[") .append("source=") .append(getSource()) .append(", handled=") .append(this.isHandled()) .append(", prevented=") .append(isPrevented()); if (this.properties != null && !this.properties.isEmpty()) { b.append(", properties=") .append(this.properties.toString()); } b.append("]"); return b.toString(); } }
{ "content_hash": "57bf5e7b6d88ed7d8b309eca092f4eb2", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 89, "avg_line_length": 33.568, "alnum_prop": 0.6357244995233555, "repo_name": "skuzzle/jeve", "id": "cf1994a402834698cd64d2fb819db9837ce084c5", "size": "8392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jeve/src/main/java/de/skuzzle/jeve/Event.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "327259" } ], "symlink_target": "" }
package org.nibiru.ui.core.api; public interface FramePanel extends Container { }
{ "content_hash": "860bc7761047b321e58f670917ee3688", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 47, "avg_line_length": 20.75, "alnum_prop": 0.7951807228915663, "repo_name": "AAJTechnologies/ui", "id": "0ff90803333c12a969838a9237a6d558316ce2fb", "size": "83", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "org.nibiru.ui.core/src/main/java/org/nibiru/ui/core/api/FramePanel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "180" }, { "name": "Java", "bytes": "127449" } ], "symlink_target": "" }
#include "stdafx.h" #include "dx103DFluidBlenders.h" #include "dx103DFluidManager.h" #include "dx103DFluidRenderer.h" namespace { // Volume texture width class cl_textureWidth : public R_constant_setup { virtual void setup(R_constant* C) { float tW = (float)FluidManager.GetTextureWidth(); RCache.set_c(C, tW); } }; static cl_textureWidth binder_textureWidth; // Volume texture height class cl_textureHeight : public R_constant_setup { virtual void setup(R_constant* C) { float tH = (float)FluidManager.GetTextureHeight(); RCache.set_c(C, tH); } }; static cl_textureHeight binder_textureHeight; // Volume texture depth class cl_textureDepth : public R_constant_setup { virtual void setup(R_constant* C) { float tD = (float)FluidManager.GetTextureDepth(); RCache.set_c(C, tD); } }; static cl_textureDepth binder_textureDepth; class cl_gridDim : public R_constant_setup { virtual void setup(R_constant* C) { float tW = (float)FluidManager.GetTextureWidth(); float tH = (float)FluidManager.GetTextureHeight(); float tD = (float)FluidManager.GetTextureDepth(); RCache.set_c(C, tW, tH, tD, 0.0f); } }; static cl_gridDim binder_gridDim; class cl_recGridDim : public R_constant_setup { virtual void setup(R_constant* C) { float tW = (float)FluidManager.GetTextureWidth(); float tH = (float)FluidManager.GetTextureHeight(); float tD = (float)FluidManager.GetTextureDepth(); RCache.set_c(C, 1.0f / tW, 1.0f / tH, 1.0f / tD, 0.0f); } }; static cl_recGridDim binder_recGridDim; class cl_maxDim : public R_constant_setup { virtual void setup(R_constant* C) { int tW = FluidManager.GetTextureWidth(); int tH = FluidManager.GetTextureHeight(); int tD = FluidManager.GetTextureDepth(); float tMax = (float)std::max(tW, std::max(tH, tD)); RCache.set_c(C, (float)tMax); } }; static cl_maxDim binder_maxDim; /* // decay simulation option class cl_decay : public R_constant_setup { virtual void setup(R_constant* C) { float fDecay = FluidManager.GetDecay(); RCache.set_c( C, fDecay ); } }; static cl_decay binder_decay; // decay simulation ImpulseSize class cl_impulseSize : public R_constant_setup { virtual void setup(R_constant* C) { float fIS = FluidManager.GetImpulseSize(); RCache.set_c( C, fIS ); } }; static cl_impulseSize binder_impulseSize; */ void BindConstants(CBlender_Compile& C) { // Bind constants here // TextureWidthShaderVariable = pEffect->GetVariableByName( "textureWidth")->AsScalar(); C.r_Constant("textureWidth", &binder_textureWidth); // TextureHeightShaderVariable = pEffect->GetVariableByName( "textureHeight")->AsScalar(); C.r_Constant("textureHeight", &binder_textureHeight); // TextureDepthShaderVariable = pEffect->GetVariableByName( "textureDepth")->AsScalar(); C.r_Constant("textureDepth", &binder_textureDepth); // Renderer constants // D3DXVECTOR3 recGridDim(1.0f/gridDim[0], 1.0f/gridDim[1], 1.0f/gridDim[2]); // pEffect->GetVariableByName("gridDim")->AsVector()->SetFloatVector(gridDim); C.r_Constant("gridDim", &binder_gridDim); // pEffect->GetVariableByName("recGridDim")->AsVector()->SetFloatVector(recGridDim); C.r_Constant("recGridDim", &binder_recGridDim); // pEffect->GetVariableByName("maxGridDim")->AsScalar()->SetFloat(maxDim); C.r_Constant("maxGridDim", &binder_maxDim); // Each technique should set up these variables itself /* // For project, advect //ModulateShaderVariable = pEffect->GetVariableByName( "modulate")->AsScalar(); //C.r_Constant( "modulate", &binder_decay); // For gaussian // Used to apply external impulse //ImpulseSizeShaderVariable = pEffect->GetVariableByName( "size")->AsScalar(); //C.r_Constant( "size", &binder_impulseSize); // Setup manually by technique //ImpulseCenterShaderVariable = pEffect->GetVariableByName( "center")->AsVector(); //SplatColorShaderVariable = pEffect->GetVariableByName( "splatColor")->AsVector(); // For confinement EpsilonShaderVariable = pEffect->GetVariableByName( "epsilon")->AsScalar(); // For confinement, advect TimeStepShaderVariable = pEffect->GetVariableByName( "timestep")->AsScalar(); // For advect BFECC ForwardShaderVariable = pEffect->GetVariableByName( "forward")->AsScalar(); HalfVolumeDimShaderVariable = pEffect->GetVariableByName( "halfVolumeDim")->AsVector(); // For render call //DrawTextureShaderVariable = pEffect->GetVariableByName( "textureNumber")->AsScalar(); */ } void SetupSamplers(CBlender_Compile& C) { int smp = C.r_dx10Sampler("samPointClamp"); if (smp != u32(-1)) { C.i_dx10Address(smp, D3DTADDRESS_CLAMP); C.i_dx10Filter(smp, D3DTEXF_POINT, D3DTEXF_POINT, D3DTEXF_POINT); } smp = C.r_dx10Sampler("samLinear"); if (smp != u32(-1)) { C.i_dx10Address(smp, D3DTADDRESS_CLAMP); C.i_dx10Filter(smp, D3DTEXF_LINEAR, D3DTEXF_LINEAR, D3DTEXF_LINEAR); } smp = C.r_dx10Sampler("samLinearClamp"); if (smp != u32(-1)) { C.i_dx10Address(smp, D3DTADDRESS_CLAMP); C.i_dx10Filter(smp, D3DTEXF_LINEAR, D3DTEXF_LINEAR, D3DTEXF_LINEAR); } smp = C.r_dx10Sampler("samRepeat"); if (smp != u32(-1)) { C.i_dx10Address(smp, D3DTADDRESS_WRAP); C.i_dx10Filter(smp, D3DTEXF_LINEAR, D3DTEXF_LINEAR, D3DTEXF_LINEAR); } } void SetupTextures(CBlender_Compile& C) { LPCSTR* TNames = FluidManager.GetEngineTextureNames(); LPCSTR* RNames = FluidManager.GetShaderTextureNames(); for (int i = 0; i < dx103DFluidManager::NUM_RENDER_TARGETS; ++i) C.r_dx10Texture(RNames[i], TNames[i]); // Renderer C.r_dx10Texture("sceneDepthTex", r2_RT_P); // C.r_dx10Texture("colorTex", "Texture_color"); C.r_dx10Texture("colorTex", TNames[dx103DFluidManager::RENDER_TARGET_COLOR_IN]); C.r_dx10Texture("jitterTex", "$user$NVjitterTex"); C.r_dx10Texture("HHGGTex", "$user$NVHHGGTex"); C.r_dx10Texture("fireTransferFunction", "internal\\internal_fireTransferFunction"); TNames = dx103DFluidRenderer::GetRTNames(); RNames = dx103DFluidRenderer::GetResourceRTNames(); for (int i = 0; i < dx103DFluidRenderer::RRT_NumRT; ++i) C.r_dx10Texture(RNames[i], TNames[i]); } } // namespace void CBlender_fluid_advect::Compile(CBlender_Compile& C) { IBlender::Compile(C); switch (C.iElement) { case 0: // Advect C.r_Pass("fluid_grid", "fluid_array", "fluid_advect", false, FALSE, FALSE, FALSE); break; case 1: // AdvectBFECC C.r_Pass("fluid_grid", "fluid_array", "fluid_advect_bfecc", false, FALSE, FALSE, FALSE); break; case 2: // AdvectTemp C.r_Pass("fluid_grid", "fluid_array", "fluid_advect_temp", false, FALSE, FALSE, FALSE); break; case 3: // AdvectBFECCTemp C.r_Pass("fluid_grid", "fluid_array", "fluid_advect_bfecc_temp", false, FALSE, FALSE, FALSE); break; case 4: // AdvectVel C.r_Pass("fluid_grid", "fluid_array", "fluid_advect_vel", false, FALSE, FALSE, FALSE); break; } C.r_CullMode(D3DCULL_NONE); BindConstants(C); SetupSamplers(C); SetupTextures(C); // Constants must be bound befor r_End() C.r_End(); } void CBlender_fluid_advect_velocity::Compile(CBlender_Compile& C) { IBlender::Compile(C); switch (C.iElement) { case 0: // AdvectVel C.r_Pass("fluid_grid", "fluid_array", "fluid_advect_vel", false, FALSE, FALSE, FALSE); break; case 1: // AdvectVelGravity C.r_Pass("fluid_grid", "fluid_array", "fluid_advect_vel_g", false, FALSE, FALSE, FALSE); break; } C.r_CullMode(D3DCULL_NONE); BindConstants(C); SetupSamplers(C); SetupTextures(C); // Constants must be bound befor r_End() C.r_End(); } void CBlender_fluid_simulate::Compile(CBlender_Compile& C) { IBlender::Compile(C); switch (C.iElement) { case 0: // Vorticity C.r_Pass("fluid_grid", "fluid_array", "fluid_vorticity", false, FALSE, FALSE, FALSE); break; case 1: // Confinement // Use additive blending C.r_Pass("fluid_grid", "fluid_array", "fluid_confinement", false, FALSE, FALSE, TRUE, D3DBLEND_ONE, D3DBLEND_ONE); break; case 2: // Divergence C.r_Pass("fluid_grid", "fluid_array", "fluid_divergence", false, FALSE, FALSE, FALSE); break; case 3: // Jacobi C.r_Pass("fluid_grid", "fluid_array", "fluid_jacobi", false, FALSE, FALSE, FALSE); break; case 4: // Project C.r_Pass("fluid_grid", "fluid_array", "fluid_project", false, FALSE, FALSE, FALSE); break; } C.r_CullMode(D3DCULL_NONE); BindConstants(C); SetupSamplers(C); SetupTextures(C); // Constants must be bound before r_End() C.r_End(); } void CBlender_fluid_obst::Compile(CBlender_Compile& C) { IBlender::Compile(C); switch (C.iElement) { case 0: // ObstStaticBox // AABB // C.r_Pass ("fluid_grid", "fluid_array", "fluid_obststaticbox", // false,FALSE,FALSE,FALSE); OOBB C.r_Pass("fluid_grid_oobb", "fluid_array_oobb", "fluid_obst_static_oobb", false, FALSE, FALSE, FALSE); break; case 1: // ObstDynBox // OOBB C.r_Pass("fluid_grid_dyn_oobb", "fluid_array_dyn_oobb", "fluid_obst_dynamic_oobb", false, FALSE, FALSE, FALSE); break; } C.r_CullMode(D3DCULL_NONE); BindConstants(C); SetupSamplers(C); SetupTextures(C); // Constants must be bound before r_End() C.r_End(); } void CBlender_fluid_emitter::Compile(CBlender_Compile& C) { IBlender::Compile(C); switch (C.iElement) { case 0: // ET_SimpleGausian C.r_Pass("fluid_grid", "fluid_array", "fluid_gaussian", false, FALSE, FALSE, TRUE, D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA); C.RS.SetRS(D3DRS_DESTBLENDALPHA, D3DBLEND_ONE); C.RS.SetRS(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE); break; } C.r_CullMode(D3DCULL_NONE); BindConstants(C); SetupSamplers(C); SetupTextures(C); // Constants must be bound before r_End() C.r_End(); } void CBlender_fluid_obstdraw::Compile(CBlender_Compile& C) { IBlender::Compile(C); switch (C.iElement) { case 0: // DrawTexture C.r_Pass("fluid_grid", "null", "fluid_draw_texture", false, FALSE, FALSE, FALSE); break; // TechniqueDrawWhiteTriangles = pEffect->GetTechniqueByName( //"DrawWhiteTriangles" ); // TechniqueDrawWhiteLines = pEffect->GetTechniqueByName( "DrawWhiteLines" ); // TechniqueDrawBox = pEffect->GetTechniqueByName( "DrawBox" ); } C.r_CullMode(D3DCULL_NONE); BindConstants(C); SetupSamplers(C); SetupTextures(C); // Constants must be bound before r_End() C.r_End(); } void CBlender_fluid_raydata::Compile(CBlender_Compile& C) { IBlender::Compile(C); switch (C.iElement) { case 0: // CompRayData_Back C.r_Pass("fluid_raydata_back", "null", "fluid_raydata_back", false, FALSE, FALSE, FALSE); C.r_CullMode(D3DCULL_CW); // Front // C.r_CullMode(D3DCULL_CCW); // Front break; case 1: // CompRayData_Front C.r_Pass("fluid_raydata_front", "null", "fluid_raydata_front", false, FALSE, FALSE, TRUE, D3DBLEND_ONE, D3DBLEND_ONE); // RS.SetRS(D3DRS_SRCBLENDALPHA, bABlend?abSRC:D3DBLEND_ONE ); // We need different blend arguments for color and alpha // One Zero for color // One One for alpha // so patch dest color. // Note: You can't set up dest blend to zero in r_pass // since r_pass would disable blend if src=one and blend - zero. C.RS.SetRS(D3DRS_DESTBLEND, D3DBLEND_ZERO); C.RS.SetRS(D3DRS_BLENDOP, D3DBLENDOP_REVSUBTRACT); // DST - SRC C.RS.SetRS(D3DRS_BLENDOPALPHA, D3DBLENDOP_REVSUBTRACT); // DST - SRC C.r_CullMode(D3DCULL_CCW); // Back // C.r_CullMode(D3DCULL_CW); // Back break; case 2: // QuadDownSampleRayDataTexture C.r_Pass("fluid_raycast_quad", "null", "fluid_raydatacopy_quad", false, FALSE, FALSE, FALSE); C.r_CullMode(D3DCULL_CCW); // Back break; } // C.PassSET_ZB(FALSE,FALSE); BindConstants(C); SetupSamplers(C); SetupTextures(C); // Constants must be bound before r_End() C.r_End(); } void CBlender_fluid_raycast::Compile(CBlender_Compile& C) { IBlender::Compile(C); switch (C.iElement) { case 0: // QuadEdgeDetect C.r_Pass("fluid_edge_detect", "null", "fluid_edge_detect", false, FALSE, FALSE, FALSE); C.r_CullMode(D3DCULL_NONE); // Back break; case 1: // QuadRaycastFog C.r_Pass("fluid_raycast_quad", "null", "fluid_raycast_quad", false, FALSE, FALSE, FALSE); C.r_CullMode(D3DCULL_CCW); // Back break; case 2: // QuadRaycastCopyFog C.r_Pass("fluid_raycast_quad", "null", "fluid_raycastcopy_quad", false, FALSE, FALSE, TRUE, D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA); C.r_ColorWriteEnable(true, true, true, false); C.r_CullMode(D3DCULL_CCW); // Back break; case 3: // QuadRaycastFire C.r_Pass("fluid_raycast_quad", "null", "fluid_raycast_quad_fire", false, FALSE, FALSE, FALSE); C.r_CullMode(D3DCULL_CCW); // Back break; case 4: // QuadRaycastCopyFire C.r_Pass("fluid_raycast_quad", "null", "fluid_raycastcopy_quad_fire", false, FALSE, FALSE, TRUE, D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA); C.r_ColorWriteEnable(true, true, true, false); C.r_CullMode(D3DCULL_CCW); // Back break; } BindConstants(C); SetupSamplers(C); SetupTextures(C); // Constants must be bound before r_End() C.r_End(); }
{ "content_hash": "7ac6c5e14722e1de1e56019b615ee5ed", "timestamp": "", "source": "github", "line_count": 427, "max_line_length": 99, "avg_line_length": 33.23653395784543, "alnum_prop": 0.6300028184892897, "repo_name": "Im-dex/xray-162", "id": "9013d144b23c8a9ff27a7cb4ce1c9742ef293a94", "size": "14192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/engine/xrRenderDX10/3DFluid/dx103DFluidBlenders.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1642482" }, { "name": "C++", "bytes": "22541957" }, { "name": "CMake", "bytes": "636522" }, { "name": "Objective-C", "bytes": "40174" }, { "name": "Pascal", "bytes": "19058" }, { "name": "xBase", "bytes": "151706" } ], "symlink_target": "" }
package edu.thinktank.togglz; import io.dropwizard.Configuration; import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.setup.AdminEnvironment; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.junit.Test; import org.togglz.console.TogglzConsoleServlet; import org.togglz.core.Feature; import org.togglz.core.manager.FeatureManager; import org.togglz.core.manager.FeatureManagerBuilder; import org.togglz.core.repository.FeatureState; import org.togglz.core.repository.StateRepository; import org.togglz.core.repository.mem.InMemoryStateRepository; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; public class AbstractFeatureToggleBundleTest { @Test public void buildFeatureManager() throws Exception { final FeatureToggleConfig featureToggleConfig = new FeatureToggleConfig(); featureToggleConfig.setFeatureSpec(TestFeature.class.getCanonicalName()); final AbstractFeatureToggleBundle<Configuration> featureToggleBundle = createDefaultBundle(null, null); final FeatureManager featureManager = featureToggleBundle.buildFeatureManager(featureToggleConfig, featureToggleBundle.getStateRepository(null, null)); assertThat(featureManager.getFeatures()).contains(TestFeature.TEST_FEATURE); assertThat(featureManager.getCurrentFeatureUser().getName()).isEqualTo("admin"); assertThat(featureManager.getCurrentFeatureUser().isFeatureAdmin()).isTrue(); } @Test(expected = IllegalArgumentException.class) public void missingFeatureSpecWillThrowExceptionWhileBuildingFeatureManager() throws Exception { final FeatureToggleConfig featureToggleConfig = new FeatureToggleConfig(); final AbstractFeatureToggleBundle<Configuration> featureToggleBundle = createDefaultBundle(null, null); final FeatureManager featureManager = featureToggleBundle.buildFeatureManager(featureToggleConfig, featureToggleBundle.getStateRepository(null, null)); } @Test public void overrideFeatureSettings() throws Exception { final AbstractFeatureToggleBundle<Configuration> featureToggleBundle = createDefaultBundle(null, null); final InMemoryStateRepository stateRepository = new InMemoryStateRepository(); final Feature feature = new Feature() { public String name() { return "feature"; } }; stateRepository.setFeatureState(new FeatureState(feature, true)); final FeatureManager featureManager = new FeatureManagerBuilder().stateRepository(stateRepository).featureEnum(TestFeature.class).build(); final Map<String, Boolean> featureStatesOverride = new HashMap<>(1); featureStatesOverride.put("feature", false); assertThat(featureManager.getFeatureState(feature).isEnabled()).isTrue(); featureToggleBundle.overrideFeatureStatesFromConfig(featureManager, featureStatesOverride); assertThat(featureManager.getFeatureState(feature).isEnabled()).isFalse(); } @Test public void addServletToAdminContext() throws Exception { final Environment environment = mock(Environment.class); final AdminEnvironment admin = mock(AdminEnvironment.class, RETURNS_DEEP_STUBS); when(environment.admin()).thenReturn(admin); final AbstractFeatureToggleBundle<Configuration> featureToggleBundle = createDefaultBundle(null, null); featureToggleBundle.addServlet(new FeatureToggleConfig(), environment); verify(admin).addServlet("togglz", TogglzConsoleServlet.class); } @Test public void addServletToApplicationContext() throws Exception { final Environment environment = mock(Environment.class); final AdminEnvironment adminMock = mock(AdminEnvironment.class); when(environment.admin()).thenReturn(adminMock); final ServletEnvironment servletMock = mock(ServletEnvironment.class, RETURNS_DEEP_STUBS); when(environment.servlets()).thenReturn(servletMock); final AbstractFeatureToggleBundle<Configuration> featureToggleBundle = createDefaultBundle(null, null); final FeatureToggleConfig config = spy(new FeatureToggleConfig()); when(config.isServletContextAdmin()).thenReturn(false); featureToggleBundle.addServlet(config, environment); verifyZeroInteractions(adminMock); verify(servletMock).addServlet("togglz", TogglzConsoleServlet.class); } @Test public void defaultStateRepositoryShouldBeInMemmory() throws Exception { final AbstractFeatureToggleBundle<Configuration> bundle = createDefaultBundle(null, null); assertThat(bundle.getStateRepository(null, null)).isInstanceOf(InMemoryStateRepository.class); } @Test public void initMethodShouldDoNothing() throws Exception { final AbstractFeatureToggleBundle<Configuration> defaultBundle = createDefaultBundle(null, null); Bootstrap<Configuration> bootstrapMock = mock(Bootstrap.class); defaultBundle.initialize(bootstrapMock); verifyZeroInteractions(bootstrapMock); } private AbstractFeatureToggleBundle<Configuration> createDefaultBundle(final FeatureToggleConfig featureToggleConfig, final StateRepository stateRepository) { return new AbstractFeatureToggleBundle<Configuration>() { @Override public FeatureToggleConfig getBundleConfiguration(final Configuration configuration) { return featureToggleConfig; } @Override public StateRepository getStateRepository(Configuration configuration, Environment environment) { return stateRepository != null ? stateRepository : super.getStateRepository(null, null); } }; } }
{ "content_hash": "5af7c976c7d620ccee3fac0dfc757d70", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 162, "avg_line_length": 47.112, "alnum_prop": 0.7566649685854984, "repo_name": "3ddysan/dropwizard-togglz", "id": "54092e18bc45f84defa158bd766b50dbd7de62e6", "size": "5889", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/edu/thinktank/togglz/AbstractFeatureToggleBundleTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "20718" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <form name="frmFichaRPGmeister7_svg" align="client" theme="dark" margins="{top=1}"> <template name="smallInventory"> <rectangle align="client" color="black"/> <label left="5" top="1" width="150" height="20" text="$(title)"/> <textEditor left="5" top="25" width="190" height="165" field="$(field)"/> <label left="5" top="195" width="50" height="20" text="Vol"/> <formatEdit left="25" top="195" width="70" height="20" field="peso$(field2)" unit="Vol"/> <label left="105" top="195" width="50" height="20" text="$"/> <formatEdit left="120" top="195" width="70" height="20" field="preco$(field2)" unit="PO"/> </template> <template name="weaponInfoField"> <flowPart minWidth="290" maxWidth="300" height="35"> <label align="top" class="tituloCampo" fontSize="10" text="$(text)" horzTextAlign="center" wordWrap="true" textTrimming="none" autoSize="true" hint="$(hint)" hitTest="true"/> <edit align="client" class="" field="$(field)" fontSize="12"/> </flowPart> </template> <template name="weaponInfoFieldSmallCenter"> <flowPart minWidth="90" maxWidth="100" height="35"> <label align="top" class="tituloCampo" fontSize="10" text="$(text)" horzTextAlign="center" wordWrap="true" textTrimming="none" autoSize="true" hint="$(hint)" hitTest="true"/> <edit align="client" class="" field="$(field)" horzTextAlign="center" fontSize="12"/> </flowPart> </template> <template name="weaponInfoFieldSmall"> <flowPart minWidth="90" maxWidth="100" height="35"> <label align="top" class="tituloCampo" fontSize="10" text="$(text)" horzTextAlign="center" wordWrap="true" textTrimming="none" autoSize="true" hint="$(hint)" hitTest="true"/> <edit align="client" class="" field="$(field)" fontSize="12"/> </flowPart> </template> <template name="itemInfoFieldSmall"> <flowPart minWidth="90" maxWidth="100" height="35"> <label align="top" class="tituloCampo" fontSize="10" text="$(text)" horzTextAlign="center" wordWrap="true" textTrimming="none" autoSize="true" hint="$(hint)" hitTest="true"/> <edit align="client" class="" field="$(field)" fontSize="12" type="float"/> </flowPart> </template> <popup name="popArma" width="300" height="400" backOpacity="0.4" autoScopeNode="false"> <flowLayout align="top" autoHeight="true" maxControlsPerLine="3" margins="{bottom=4}" horzAlign="center"> <weaponInfoFieldSmall text="NOME" field="batismo" hint="Se a arma possui um nome de batismo ponha ele aqui."/> <weaponInfoFieldSmall text="ARMA" field="arma" hint="Qual a arma? Espada Longa? Machado de Batalha? Arco Longo?"/> <weaponInfoFieldSmall text="TAMANHO" field="tamanho" hint="Essa arma foi feita para um personagem de que tamanho? Médio? Pequeno? Grande?"/> <weaponInfoFieldSmall text="MATERIAL" field="material" hint="Essa arma foi feita de um material especial? Adamante? Prata?"/> <weaponInfoFieldSmallCenter text="QUALIDADE" field="qualidade" hint="Essa arma é Obra-Prima? +1? +2?"/> <weaponInfoFieldSmall text="CATEGORIA" field="categoria" hint="Essa arma é Simples? Comum? Exotica?"/> <weaponInfoFieldSmallCenter text="DANO" field="dano" hint="Qual o dado de dano dessa arma?"/> <weaponInfoFieldSmallCenter text="DECISIVO" field="decisivo" hint="Quando a margem de ameaça dessa arma?20? 19-20?"/> <weaponInfoFieldSmallCenter text="MULTIPLICADOR" field="multiplicador" hint="Em um decisivo por quanto é multiplicado o dano dessa arma?"/> <weaponInfoFieldSmall text="ALCANCE" field="alcance" hint="Qual o alcance em metros da arma? Normalmente usado apenas em armas de ataque a distancia. "/> <weaponInfoFieldSmall text="ESPECIAL" field="especial" hint="Essa arma tem efeitos especiais? Pode ser usada em derrubar? desarmar? Pode ser preparada contra investida?"/> <weaponInfoFieldSmall text="TIPO" field="tipo" hint="Qual o tipo de dano que essa arma causa? Concusivo? Cortante?"/> <weaponInfoField text="EFEITOS" field="efeitos" hint="Essa arma tem efeitos mágicos? Flamejante? Vorpal?"/> <weaponInfoFieldSmallCenter text="CA" field="ca" hint="Para escudos: qual o bonus que ele fornece na CA?"/> <weaponInfoFieldSmallCenter text="PEN" field="penalidade" hint="Para escudos: qual a penalidade do escudo?"/> <weaponInfoFieldSmallCenter text="FALHA" field="falha" hint="Para escudos: qual a falha arcana?"/> </flowLayout> <textEditor align="client" field="descricao" class=""/> </popup> <popup name="popInv" width="200" height="200" backOpacity="0.4" autoScopeNode="false"> <textEditor align="client" field="descricao" class=""/> </popup> <popup name="popItem" width="300" height="250" backOpacity="0.4" autoScopeNode="false"> <flowLayout align="top" autoHeight="true" maxControlsPerLine="3" margins="{bottom=4}" horzAlign="center"> <weaponInfoFieldSmall text="Nome" field="nome" hint=""/> <weaponInfoFieldSmall text="Tipo" field="tipo" hint="Varinha? Poção? Cajado?"/> <weaponInfoFieldSmall text="Rolagem" field="dados" hint="Rolagem feita ao usar o item."/> <weaponInfoFieldSmallCenter text="NC" field="nc" hint="Nível de Conjurador"/> <weaponInfoFieldSmallCenter text="CD" field="cd" hint="Classe de Dificuldade"/> <itemInfoFieldSmall text="PREÇO" field="preco" hint=""/> </flowLayout> <textEditor align="client" field="descricao" class=""/> </popup> <scrollBox align="client"> <layout left="0" top="0" width="475" height="220"> <rectangle align="client" color="black"/> <button text="+" left="5" top="5" width="20" height="20"> <event name="onClick"> self.rclListaDasArmas:append(); </event> </button> <label left="30" top="5" width="435" height="20" text="VESTIDO Vol $"/> <recordList name="rclListaDasArmas" field="campoDasArmas" templateForm="frmInventarioItem" left="5" top="25" width="465" height="190" layout="vertical" minQt="1"/> <label left="280" top="310" width="50" height="20" text="Vol"/> <formatEdit left="300" top="310" width="70" height="20" field="pesoArmas" unit="Vol"/> <label left="380" top="310" width="50" height="20" text="$"/> <formatEdit left="395" top="310" width="71" height="20" field="precoArmas" unit="PO"/> </layout> <layout left="0" top="225" width="475" height="220"> <rectangle align="client" color="black"/> <button text="+" left="5" top="5" width="20" height="20"> <event name="onClick"> self.rclMochila:append(); </event> </button> <label left="30" top="5" width="435" height="20" text="MOCHILA Vol $"/> <recordList name="rclMochila" field="campoMochila" templateForm="frmInventarioItem" left="5" top="25" width="465" height="190" layout="vertical" minQt="1"/> <label left="280" top="310" width="50" height="20" text="Vol"/> <formatEdit left="300" top="310" width="70" height="20" field="pesoMochila" unit="Vol"/> <label left="380" top="310" width="50" height="20" text="$"/> <formatEdit left="395" top="310" width="71" height="20" field="precoMochila" unit="PO"/> </layout> <layout left="0" top="450" width="475" height="220"> <rectangle align="client" color="black"/> <button text="+" left="5" top="5" width="20" height="20"> <event name="onClick"> self.rclPreparado:append(); </event> </button> <label left="30" top="5" width="435" height="20" text="PREPARADO Vol $"/> <recordList name="rclPreparado" field="campoPreparado" templateForm="frmInventarioItem" left="5" top="25" width="465" height="190" layout="vertical" minQt="1"/> <label left="280" top="310" width="50" height="20" text="Vol"/> <formatEdit left="300" top="310" width="70" height="20" field="pesoPreparado" unit="Vol"/> <label left="380" top="310" width="50" height="20" text="$"/> <formatEdit left="395" top="310" width="71" height="20" field="precoPreparado" unit="PO"/> </layout> <layout left="480" top="0" width="200" height="220"> <smallInventory title="PERMANENCIAS" field="permanencias" field2="Permanencias"/> </layout> <layout left="685" top="0" width="200" height="220"> <smallInventory title="LIVRES" field="livres" field2="Livres"/> </layout> <layout left="480" top="225" width="200" height="220"> <smallInventory title="OUTROS" field="outros" field2="Outros"/> </layout> <layout left="685" top="225" width="200" height="220"> <smallInventory title="MUNIÇÕES" field="municoes" field2="Municoes"/> </layout> <layout left="480" top="450" width="200" height="221"> <smallInventory title="BOLSOS" field="bolsos" field2="Bolsos"/> </layout> <layout left="685" top="450" width="200" height="221"> <smallInventory title="IMOVEIS" field="moveis" field2="Imoveis"/> </layout> <layout left="890" top="0" width="315" height="480"> <rectangle align="client" color="#0000007F" strokeColor="black" strokeSize="1"/> <button left="5" top="5" height="20" width="305" text="Novo Item" onClick="self.rclConsumiveis:append();"/> <recordList left="5" top="30" width="305" height="445" name="rclConsumiveis" field="itensConsumiveis" templateForm="frmConsumiveis" /> </layout> <layout left="890" top="485" width="155" height="185"> <rectangle align="client" color="black"/> <label left="5" top="1" width="200" height="20" text="DINHEIRO"/> <label left="10" top="25" width="50" height="20" text="PC"/> <formatEdit left="65" top="25" width="85" height="20" field="dinheiroPC" unit="PC"/> <label left="10" top="45" width="50" height="20" text="PP"/> <formatEdit left="65" top="45" width="85" height="20" field="dinheiroPP" unit="PP"/> <label left="10" top="65" width="50" height="20" text="PO"/> <formatEdit left="65" top="65" width="85" height="20" field="dinheiroPO" unit="PO"/> <label left="10" top="85" width="50" height="20" text="PL"/> <formatEdit left="65" top="85" width="85" height="20" field="dinheiroPL" unit="PL"/> <label left="10" top="110" width="50" height="20" text="TOTAL"/> <formatEdit left="65" top="110" width="85" height="20" field="dinheiroTotal" unit="PO"/> <label left="10" top="135" width="50" height="20" text="GASTOS"/> <rectangle left="65" top="135" width="85" height="20" color="black" strokeColor="white" strokeSize="1"/> <label field="gastos" text="0" left="65" top="135" width="85" height="20" horzTextAlign="center" fontSize="11" formatFloat=",0.## PO"/> <label left="10" top="160" width="50" height="20" text="RESTANTE" fontSize="10"/> <rectangle left="65" top="160" width="85" height="20" color="black" strokeColor="white" strokeSize="1"/> <label field="dinheiroRestante" text="0" left="65" top="160" width="85" height="20" horzTextAlign="center" fontSize="11" formatFloat=",0.## PO"/> </layout> <layout left="1050" top="485" width="155" height="185"> <rectangle align="client" color="black"/> <label left="5" top="1" width="150" height="20" text="CARGA"/> <label left="5" top="25" width="145" height="20" text="SOBRECARREGADO" horzTextAlign="center"/> <rectangle left="5" top="50" width="100" height="20" color="black" strokeColor="white" strokeSize="1"/> <label left="5" top="50" width="100" height="20" field="sobrecarregado" horzTextAlign="center" formatFloat=",0.## Vol"/> <edit left="105" top="50" width="45" height="20" field="sobrecarregadoExtra"/> <label left="5" top="75" width="145" height="20" text="MAXIMO" horzTextAlign="center"/> <rectangle left="5" top="100" width="100" height="20" color="black" strokeColor="white" strokeSize="1"/> <label left="5" top="100" width="100" height="20" field="cargaMaxima" horzTextAlign="center" formatFloat=",0.## Vol"/> <edit left="105" top="100" width="45" height="20" field="cargaMaximaExtra"/> <label left="5" top="125" width="145" height="20" text="ATUAL" horzTextAlign="center"/> <label field="cargaAtual" width="145" height="20" left="5" top="150" horzTextAlign="center" fontColor="white" formatFloat=",0.## Vol"/> </layout> <dataLink fields="{'efetModFor','sobrecarregadoExtra','cargaMaximaExtra'}"> <event name="onChange"> if sheet== nil then return end; local sobrecarregadoExtra = tonumber(sheet.sobrecarregadoExtra) or 0; local cargaMaximaExtra = tonumber(sheet.cargaMaximaExtra) or 0; local str = tonumber(sheet.efetModFor) or 0; sheet.sobrecarregado = 5 + str + sobrecarregadoExtra; sheet.cargaMaxima = 10 + str + cargaMaximaExtra; </event> </dataLink> <dataLink fields="{'precoEquipamento', 'precoArmas', 'precoMochila', 'precoPermanencias', 'precoLivres', 'precoOutros', 'precoMunicoes', 'precoBolsos', 'precoImoveis', 'precoInventorioComp', 'dinheiroTotal', 'precoItens'}"> <event name="onChange"> if sheet~= nil then -- Calculando todos gastos local gastos = (tonumber(sheet.precoEquipamento) or 0) + (tonumber(sheet.precoArmas) or 0) + (tonumber(sheet.precoMochila) or 0) + (tonumber(sheet.precoPermanencias) or 0) + (tonumber(sheet.precoLivres) or 0) + (tonumber(sheet.precoOutros) or 0) + (tonumber(sheet.precoMunicoes) or 0) + (tonumber(sheet.precoBolsos) or 0) + (tonumber(sheet.precoImoveis) or 0) + (tonumber(sheet.precoInventorioComp) or 0) + (tonumber(sheet.precoItens) or 0); -- Calculando dinheiro restante local total = tonumber(sheet.dinheiroTotal) or 0; local restante = total - gastos; sheet.gastos = gastos; sheet.dinheiroRestante = restante; end; </event> </dataLink> <dataLink fields="{'pesoEquipamento', 'pesoArmas', 'pesoMochila', 'pesoPreparado', 'pesoPermanencias', 'pesoLivres', 'pesoOutros', 'pesoMunicoes', 'pesoBolsos', 'pesoImoveis', 'pesoInventorioComp'}"> <event name="onChange"> if sheet~=nil then local carga = (tonumber(sheet.pesoEquipamento) or 0) + (tonumber(sheet.pesoArmas) or 0) + (tonumber(sheet.pesoMochila) or 0) + (tonumber(sheet.pesoPreparado) or 0) + (tonumber(sheet.pesoPermanencias) or 0) + (tonumber(sheet.pesoLivres) or 0) + (tonumber(sheet.pesoOutros) or 0) + (tonumber(sheet.pesoMunicoes) or 0) + (tonumber(sheet.pesoBolsos) or 0) + (tonumber(sheet.pesoImoveis) or 0); sheet.cargaAtual = carga; end; </event> </dataLink> </scrollBox> </form>
{ "content_hash": "859457c0018b791b72ebd495b2868fd1", "timestamp": "", "source": "github", "line_count": 254, "max_line_length": 225, "avg_line_length": 57.30708661417323, "alnum_prop": 0.6582165430063204, "repo_name": "rrpgfirecast/firecast", "id": "34ecf80f90353d7b1974c6880da7bd83ade023d5", "size": "14570", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Plugins/Sheets/Ficha Pathfinder 2e/FichaPathfinder2e/07.Inventario.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2671" }, { "name": "HTML", "bytes": "3233" }, { "name": "Java", "bytes": "264699" }, { "name": "JavaScript", "bytes": "30233" }, { "name": "Lua", "bytes": "109149272" }, { "name": "Pascal", "bytes": "50948" }, { "name": "Shell", "bytes": "8747" } ], "symlink_target": "" }
package org.apache.samza.util; /** * An object that can provide time points (useful for getting the elapsed time between two time * points) and can sleep for a specified period of time. * <p> * Instances of this interface must be thread-safe. */ interface HighResolutionClock { /** * Returns a time point that can be used to calculate the difference in nanoseconds with another * time point. Resolution of the timer is platform dependent and not guaranteed to actually * operate at nanosecond precision. * * @return current time point in nanoseconds */ long nanoTime(); /** * Sleeps for a period of time that approximates the requested number of nanoseconds. Actual sleep * time can vary significantly based on the JVM implementation and platform. This function returns * the measured error between expected and actual sleep time. * * @param nanos the number of nanoseconds to sleep. * @throws InterruptedException if the current thread is interrupted while blocked in this method. */ long sleep(long nanos) throws InterruptedException; }
{ "content_hash": "d5d8894e65dd36e53496a550d84f6328", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 100, "avg_line_length": 36.5, "alnum_prop": 0.7424657534246575, "repo_name": "InnovaCo/samza", "id": "69ba441ed087305dfe4e1272b00fad67b644e13f", "size": "1902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samza-core/src/main/java/org/apache/samza/util/HighResolutionClock.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4148" }, { "name": "HTML", "bytes": "10645" }, { "name": "Java", "bytes": "1062726" }, { "name": "Python", "bytes": "37524" }, { "name": "Scala", "bytes": "1105212" }, { "name": "Shell", "bytes": "31438" }, { "name": "XSLT", "bytes": "7116" } ], "symlink_target": "" }
<?php namespace zpt\db\test\adapter; require_once __DIR__ . '/../test-common.php'; use PHPUnit_Framework_TestCase as TestCase; use zpt\db\DatabaseConnection; use zpt\db\adapter\PgsqlAdminAdapter; use zpt\db\exception\DatabaseException; /** * This class defines test cases for the PgsqlAdminAdapter class. * * @author Philip Graham <philip@zeptech.ca> */ class PgsqlAdminAdapterTest extends TestCase { protected function setUp() { if (!isset($GLOBALS['PGSQL_USER']) || !isset($GLOBALS['PGSQL_PASS'])) { $this->markTestSkipped("Postgresql connection information not available." . " View the README for information on how to setup database tests."); } } public function testConstruction() { $db = new DatabaseConnection([ 'driver' => 'pgsql', 'username' => 'test_user', 'password' => '123abc' ]); $adapter = new PgsqlAdminAdapter($db); } public function testCopyAuthError() { $db = new DatabaseConnection([ 'driver' => 'pgsql', 'username' => 'test_user', 'password' => '123abc' ]); $adapter = new PgsqlAdminAdapter($db); try { $adapter->copyDatabase('postgresql', 'postgresql_backup'); $this->fail("Expected an error attempting to copy database postgresql"); } catch (DatabaseException $e) { $this->assertTrue($e->isAuthorizationError()); $this->assertEquals('42501', $e->getSqlCode()); } } }
{ "content_hash": "e7c73fc94b5f5f5191afee920c4462b5", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 76, "avg_line_length": 24.482142857142858, "alnum_prop": 0.6805251641137856, "repo_name": "pgraham/database", "id": "6302ec5b7defca1b088c4a915bc2b76798cf7530", "size": "1599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/adapter/PgsqlAdminAdapterTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "70589" } ], "symlink_target": "" }
package natsx import ( "context" "github.com/altairsix/pkg/tracer" "github.com/altairsix/pkg/tracer/k" "github.com/savaki/nats-protobuf" ) // Log provides the standardized logging service for nats queries func Log(bc string) nats_protobuf.Filter { return func(fn nats_protobuf.HandlerFunc) nats_protobuf.HandlerFunc { return func(ctx context.Context, subject string, m *nats_protobuf.Message) (*nats_protobuf.Message, error) { segment, ctx := tracer.NewSegment(ctx, "nats.api_call", k.String("subject", subject), k.String("bc", bc), k.String("method", m.Method), ) defer segment.Finish() out, err := fn(ctx, subject, m) if err != nil { segment.LogFields(k.Err(err)) return nil, err } return out, nil } } }
{ "content_hash": "d177b6b3933e06ab3adbda969c949443", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 110, "avg_line_length": 24.580645161290324, "alnum_prop": 0.6824146981627297, "repo_name": "altairsix/pkg", "id": "32e0094e4d9ec90e0878bde829bd920d209b8e10", "size": "762", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "natsx/logger.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "200924" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Python Module Index &#8212; Rubber Docker 0.1 documentation</title> <link rel="stylesheet" href="_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript" src="_static/documentation_options.js"></script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <link rel="stylesheet" href="_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> <script type="text/javascript"> DOCUMENTATION_OPTIONS.COLLAPSE_INDEX = true; </script> </head><body> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <h1>Python Module Index</h1> <div class="modindex-jumpbox"> <a href="#cap-l"><strong>l</strong></a> </div> <table class="indextable modindextable"> <tr class="pcap"><td></td><td>&#160;</td><td></td></tr> <tr class="cap" id="cap-l"><td></td><td> <strong>l</strong></td><td></td></tr> <tr> <td></td> <td> <a href="index.html#module-linux"><code class="xref">linux</code></a></td><td> <em></em></td></tr> </table> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"><div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="index.html">Documentation overview</a><ul> </ul></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2016, Avishai Ish-Shalom, Nati Cohen. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.7.2</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a> </div> </body> </html>
{ "content_hash": "cf079b3ae270042ceda1becfac405937", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 93, "avg_line_length": 31.22680412371134, "alnum_prop": 0.5992076592934962, "repo_name": "Fewbytes/rubber-docker", "id": "cdd3bd38a31454d15d48198ccad4e960dd3e5f3b", "size": "3030", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/linux/py-modindex.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "14634" }, { "name": "HTML", "bytes": "7938" }, { "name": "Python", "bytes": "56658" }, { "name": "Shell", "bytes": "3569" }, { "name": "Vim script", "bytes": "5353" } ], "symlink_target": "" }
<?php /* * Author: Todd Motto | @toddmotto * URL: html5blank.com | @html5blank * Custom functions, support, custom post types and more. */ /*------------------------------------*\ External Modules/Files \*------------------------------------*/ // Load any external files you have here /*------------------------------------*\ Theme Support \*------------------------------------*/ if (!isset($content_width)) { $content_width = 900; } if (function_exists('add_theme_support')) { // Add Menu Support add_theme_support('menus'); // Add Thumbnail Theme Support add_theme_support('post-thumbnails'); add_image_size('large', 700, '', true); // Large Thumbnail add_image_size('medium', 250, '', true); // Medium Thumbnail add_image_size('small', 120, '', true); // Small Thumbnail add_image_size('custom-size', 700, 200, true); // Custom Thumbnail Size call using the_post_thumbnail('custom-size'); // Add Support for Custom Backgrounds - Uncomment below if you're going to use /*add_theme_support('custom-background', array( 'default-color' => 'FFF', 'default-image' => get_template_directory_uri() . '/img/bg.jpg' ));*/ // Add Support for Custom Header - Uncomment below if you're going to use /*add_theme_support('custom-header', array( 'default-image' => get_template_directory_uri() . '/img/headers/default.jpg', 'header-text' => false, 'default-text-color' => '000', 'width' => 1000, 'height' => 198, 'random-default' => false, 'wp-head-callback' => $wphead_cb, 'admin-head-callback' => $adminhead_cb, 'admin-preview-callback' => $adminpreview_cb ));*/ // Enables post and comment RSS feed links to head add_theme_support('automatic-feed-links'); // Localisation Support load_theme_textdomain('html5blank', get_template_directory() . '/languages'); } // Register custom navigation walker require_once('wp_bootstrap_navwalker.php'); /*------------------------------------*\ Functions \*------------------------------------*/ // HTML5 Blank navigation function html5blank_nav() { wp_nav_menu( /* array( 'theme_location' => 'header-menu', 'menu' => '', 'container' => 'div', 'container_class' => 'menu-{menu slug}-container', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul>%3$s</ul>', 'depth' => 0, 'walker' => '' ) */ // replaced the menu with the one needed for bootstrap / bootstrap menu plugin // https://github.com/twittem/wp-bootstrap-navwalker array( 'menu' => 'primary', 'theme_location' => 'header-menu', 'depth' => 2, 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'bs-example-navbar-collapse-1', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => 'wp_bootstrap_navwalker::fallback', 'walker' => new wp_bootstrap_navwalker()) ); } function custom_law_wp_footer() { return '<div></div>'; } // extra css added by me function custom_law_cv_header_css() { wp_enqueue_style('fontawesome', get_stylesheet_directory_uri() . '/css/font-awesome.min.css'); wp_enqueue_style('bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css'); wp_enqueue_style('animate', get_stylesheet_directory_uri() . '/css/animate.css'); wp_enqueue_style('google-fonts-css', 'http://fonts.googleapis.com/css?family=Josefin+Sans&#038;subset=latin%2Clatin-ext&#038;ver=4.1.1'); wp_enqueue_style('owl-carousel-css', get_stylesheet_directory_uri() . '/css/owl.carousel.css'); wp_enqueue_style('owl-theme-css', get_stylesheet_directory_uri() . '/css/owl.theme.css'); } // Load HTML5 Blank scripts (header.php) function html5blank_header_scripts() { if ($GLOBALS['pagenow'] != 'wp-login.php' && !is_admin()) { wp_register_script('conditionizr', get_template_directory_uri() . '/js/lib/conditionizr-4.3.0.min.js', array(), '4.3.0'); // Conditionizr wp_enqueue_script('conditionizr'); // Enqueue it! wp_register_script('modernizr', get_template_directory_uri() . '/js/lib/modernizr-2.7.1.min.js', array(), '2.7.1'); // Modernizr wp_enqueue_script('modernizr'); // Enqueue it! wp_register_script('html5blankscripts', get_template_directory_uri() . '/js/main.js', array('jquery'), '1.0.0'); // Custom scripts wp_enqueue_script('html5blankscripts'); // Enqueue it! wp_register_script('bootstrap', get_template_directory_uri() . '/js/lib/bootstrap.min.js', array(), '3.1.1'); wp_enqueue_script('bootstrap'); // Enqueue it! // check if element has scrolled into the viewport - use for animation with animate.css wp_register_script('viewportchecker', get_template_directory_uri() . '/js/lib/viewportchecker.js', array(), '1.3.2'); wp_enqueue_script('viewportchecker'); // Enqueue it! wp_register_script('owlcarousel', get_template_directory_uri() . '/js/lib/owl.carousel.min.js', array(), '1.3.2'); wp_enqueue_script('owlcarousel'); // Enqueue it! } } // Load HTML5 Blank conditional scripts function html5blank_conditional_scripts() { if (is_page('pagenamehere')) { wp_register_script('scriptname', get_template_directory_uri() . '/js/scriptname.js', array('jquery'), '1.0.0'); // Conditional script(s) wp_enqueue_script('scriptname'); // Enqueue it! } } // Load HTML5 Blank styles function html5blank_styles() { wp_register_style('normalize', get_template_directory_uri() . '/normalize.css', array(), '1.0', 'all'); wp_enqueue_style('normalize'); // Enqueue it! wp_register_style('html5blank', get_template_directory_uri() . '/style.css', array(), '1.0', 'all'); wp_enqueue_style('html5blank'); // Enqueue it! } // Register HTML5 Blank Navigation function register_html5_menu() { register_nav_menus(array( // Using array to specify more menus if needed 'header-menu' => __('Header Menu', 'html5blank'), // Main Navigation 'sidebar-menu' => __('Sidebar Menu', 'html5blank'), // Sidebar Navigation 'extra-menu' => __('Extra Menu', 'html5blank') // Extra Navigation if needed (duplicate as many as you need!) )); } // Remove the <div> surrounding the dynamic navigation to cleanup markup function my_wp_nav_menu_args($args = '') { $args['container'] = false; return $args; } // Remove Injected classes, ID's and Page ID's from Navigation <li> items function my_css_attributes_filter($var) { return is_array($var) ? array() : ''; } // Remove invalid rel attribute values in the categorylist function remove_category_rel_from_category_list($thelist) { return str_replace('rel="category tag"', 'rel="tag"', $thelist); } // Add page slug to body class, love this - Credit: Starkers Wordpress Theme function add_slug_to_body_class($classes) { global $post; if (is_home()) { $key = array_search('blog', $classes); if ($key > -1) { unset($classes[$key]); } } elseif (is_page()) { $classes[] = sanitize_html_class($post->post_name); } elseif (is_singular()) { $classes[] = sanitize_html_class($post->post_name); } return $classes; } // If Dynamic Sidebar Exists if (function_exists('register_sidebar')) { // Define Sidebar Widget Area 1 register_sidebar(array( 'name' => __('Widget Area 1', 'html5blank'), 'description' => __('Description for this widget-area...', 'html5blank'), 'id' => 'widget-area-1', 'before_widget' => '<div id="%1$s" class="%2$s">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>' )); // Define Sidebar Widget Area 2 register_sidebar(array( 'name' => __('Widget Area 2', 'html5blank'), 'description' => __('Description for this widget-area...', 'html5blank'), 'id' => 'widget-area-2', 'before_widget' => '<div id="%1$s" class="%2$s">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>' )); } // Remove wp_head() injected Recent Comment styles function my_remove_recent_comments_style() { global $wp_widget_factory; remove_action('wp_head', array( $wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style' )); } // Pagination for paged posts, Page 1, Page 2, Page 3, with Next and Previous Links, No plugin function html5wp_pagination() { global $wp_query; $big = 999999999; echo paginate_links(array( 'base' => str_replace($big, '%#%', get_pagenum_link($big)), 'format' => '?paged=%#%', 'current' => max(1, get_query_var('paged')), 'total' => $wp_query->max_num_pages )); } // Custom Excerpts function html5wp_index($length) // Create 20 Word Callback for Index page Excerpts, call using html5wp_excerpt('html5wp_index'); { return 20; } // Create 40 Word Callback for Custom Post Excerpts, call using html5wp_excerpt('html5wp_custom_post'); function html5wp_custom_post($length) { return 40; } // Create the Custom Excerpts callback function html5wp_excerpt($length_callback = '', $more_callback = '') { global $post; if (function_exists($length_callback)) { add_filter('excerpt_length', $length_callback); } if (function_exists($more_callback)) { add_filter('excerpt_more', $more_callback); } $output = get_the_excerpt(); $output = apply_filters('wptexturize', $output); $output = apply_filters('convert_chars', $output); $output = '<p>' . $output . '</p>'; echo $output; } // Custom View Article link to Post function html5_blank_view_article($more) { global $post; return '... <a class="view-article" href="' . get_permalink($post->ID) . '">' . __('View Article', 'html5blank') . '</a>'; } // Remove Admin bar function remove_admin_bar() { return false; } // Remove 'text/css' from our enqueued stylesheet function html5_style_remove($tag) { return preg_replace('~\s+type=["\'][^"\']++["\']~', '', $tag); } // Remove thumbnail width and height dimensions that prevent fluid images in the_thumbnail function remove_thumbnail_dimensions( $html ) { $html = preg_replace('/(width|height)=\"\d*\"\s/', "", $html); return $html; } // Custom Gravatar in Settings > Discussion function html5blankgravatar ($avatar_defaults) { $myavatar = get_template_directory_uri() . '/img/gravatar.jpg'; $avatar_defaults[$myavatar] = "Custom Gravatar"; return $avatar_defaults; } // Threaded Comments function enable_threaded_comments() { if (!is_admin()) { if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) { wp_enqueue_script('comment-reply'); } } } // Custom Comments Callback function html5blankcomments($comment, $args, $depth) { $GLOBALS['comment'] = $comment; extract($args, EXTR_SKIP); if ( 'div' == $args['style'] ) { $tag = 'div'; $add_below = 'comment'; } else { $tag = 'li'; $add_below = 'div-comment'; } ?> <!-- heads up: starting < for the html tag (li or div) in the next line: --> <<?php echo $tag ?> <?php comment_class(empty( $args['has_children'] ) ? '' : 'parent') ?> id="comment-<?php comment_ID() ?>"> <?php if ( 'div' != $args['style'] ) : ?> <div id="div-comment-<?php comment_ID() ?>" class="comment-body"> <?php endif; ?> <div class="comment-author vcard"> <?php if ($args['avatar_size'] != 0) echo get_avatar( $comment, $args['180'] ); ?> <?php printf(__('<cite class="fn">%s</cite> <span class="says">says:</span>'), get_comment_author_link()) ?> </div> <?php if ($comment->comment_approved == '0') : ?> <em class="comment-awaiting-moderation"><?php _e('Your comment is awaiting moderation.') ?></em> <br /> <?php endif; ?> <div class="comment-meta commentmetadata"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"> <?php printf( __('%1$s at %2$s'), get_comment_date(), get_comment_time()) ?></a><?php edit_comment_link(__('(Edit)'),' ','' ); ?> </div> <?php comment_text() ?> <div class="reply"> <?php comment_reply_link(array_merge( $args, array('add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth']))) ?> </div> <?php if ( 'div' != $args['style'] ) : ?> </div> <?php endif; ?> <?php } /*------------------------------------*\ Actions + Filters + ShortCodes \*------------------------------------*/ // Add Actions add_action('init', 'html5blank_header_scripts'); // Add Custom Scripts to wp_head add_action('wp_print_scripts', 'html5blank_conditional_scripts'); // Add Conditional Page Scripts add_action('get_header', 'enable_threaded_comments'); // Enable Threaded Comments add_action('wp_enqueue_scripts', 'custom_law_cv_header_css'); // Add Theme Stylesheet add_action('wp_enqueue_scripts', 'html5blank_styles'); // Add Theme Stylesheet add_action('init', 'register_html5_menu'); // Add HTML5 Blank Menu add_action('init', 'create_post_type_html5'); // Add our HTML5 Blank Custom Post Type add_action('widgets_init', 'my_remove_recent_comments_style'); // Remove inline Recent Comment Styles from wp_head() add_action('init', 'html5wp_pagination'); // Add our HTML5 Pagination // Remove Actions remove_action('wp_head', 'feed_links_extra', 3); // Display the links to the extra feeds such as category feeds remove_action('wp_head', 'feed_links', 2); // Display the links to the general feeds: Post and Comment Feed remove_action('wp_head', 'rsd_link'); // Display the link to the Really Simple Discovery service endpoint, EditURI link remove_action('wp_head', 'wlwmanifest_link'); // Display the link to the Windows Live Writer manifest file. remove_action('wp_head', 'index_rel_link'); // Index link remove_action('wp_head', 'parent_post_rel_link', 10, 0); // Prev link remove_action('wp_head', 'start_post_rel_link', 10, 0); // Start link remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); // Display relational links for the posts adjacent to the current post. remove_action('wp_head', 'wp_generator'); // Display the XHTML generator that is generated on the wp_head hook, WP version remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); remove_action('wp_head', 'rel_canonical'); remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0); // Add Filters add_filter('avatar_defaults', 'html5blankgravatar'); // Custom Gravatar in Settings > Discussion add_filter('body_class', 'add_slug_to_body_class'); // Add slug to body class (Starkers build) add_filter('widget_text', 'do_shortcode'); // Allow shortcodes in Dynamic Sidebar add_filter('widget_text', 'shortcode_unautop'); // Remove <p> tags in Dynamic Sidebars (better!) add_filter('wp_nav_menu_args', 'my_wp_nav_menu_args'); // Remove surrounding <div> from WP Navigation // add_filter('nav_menu_css_class', 'my_css_attributes_filter', 100, 1); // Remove Navigation <li> injected classes (Commented out by default) // add_filter('nav_menu_item_id', 'my_css_attributes_filter', 100, 1); // Remove Navigation <li> injected ID (Commented out by default) // add_filter('page_css_class', 'my_css_attributes_filter', 100, 1); // Remove Navigation <li> Page ID's (Commented out by default) add_filter('the_category', 'remove_category_rel_from_category_list'); // Remove invalid rel attribute add_filter('the_excerpt', 'shortcode_unautop'); // Remove auto <p> tags in Excerpt (Manual Excerpts only) add_filter('the_excerpt', 'do_shortcode'); // Allows Shortcodes to be executed in Excerpt (Manual Excerpts only) add_filter('excerpt_more', 'html5_blank_view_article'); // Add 'View Article' button instead of [...] for Excerpts add_filter('show_admin_bar', 'remove_admin_bar'); // Remove Admin bar add_filter('style_loader_tag', 'html5_style_remove'); // Remove 'text/css' from enqueued stylesheet add_filter('post_thumbnail_html', 'remove_thumbnail_dimensions', 10); // Remove width and height dynamic attributes to thumbnails add_filter('image_send_to_editor', 'remove_thumbnail_dimensions', 10); // Remove width and height dynamic attributes to post images function remove_footer_admin () { echo 'Fueled by <a href="http://www.wordpress.org" target="_blank">WordPress</a> | Designed by <a href="http://www.uzzz.net" target="_blank">Uzzz Productions</a> | WordPress Tutorials: <a href="http://www.wpbeginner.com" target="_blank">WPBeginner</a></p>'; } add_filter('admin_footer_text', 'remove_footer_admin'); // Remove Filters remove_filter('the_excerpt', 'wpautop'); // Remove <p> tags from Excerpt altogether // Shortcodes add_shortcode('html5_shortcode_demo', 'html5_shortcode_demo'); // You can place [html5_shortcode_demo] in Pages, Posts now. add_shortcode('html5_shortcode_demo_2', 'html5_shortcode_demo_2'); // Place [html5_shortcode_demo_2] in Pages, Posts now. // Shortcodes above would be nested like this - // [html5_shortcode_demo] [html5_shortcode_demo_2] Here's the page title! [/html5_shortcode_demo_2] [/html5_shortcode_demo] /*------------------------------------*\ Custom Post Types \*------------------------------------*/ // Create 1 Custom Post type for a Demo, called HTML5-Blank function create_post_type_html5() { register_taxonomy_for_object_type('category', 'html5-blank'); // Register Taxonomies for Category register_taxonomy_for_object_type('post_tag', 'html5-blank'); register_post_type('html5-blank', // Register Custom Post Type array( 'labels' => array( 'name' => __('HTML5 Blank Custom Post', 'html5blank'), // Rename these to suit 'singular_name' => __('HTML5 Blank Custom Post', 'html5blank'), 'add_new' => __('Add New', 'html5blank'), 'add_new_item' => __('Add New HTML5 Blank Custom Post', 'html5blank'), 'edit' => __('Edit', 'html5blank'), 'edit_item' => __('Edit HTML5 Blank Custom Post', 'html5blank'), 'new_item' => __('New HTML5 Blank Custom Post', 'html5blank'), 'view' => __('View HTML5 Blank Custom Post', 'html5blank'), 'view_item' => __('View HTML5 Blank Custom Post', 'html5blank'), 'search_items' => __('Search HTML5 Blank Custom Post', 'html5blank'), 'not_found' => __('No HTML5 Blank Custom Posts found', 'html5blank'), 'not_found_in_trash' => __('No HTML5 Blank Custom Posts found in Trash', 'html5blank') ), 'public' => true, 'hierarchical' => true, // Allows your posts to behave like Hierarchy Pages 'has_archive' => true, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail' ), // Go to Dashboard Custom HTML5 Blank post for supports 'can_export' => true, // Allows export in Tools > Export 'taxonomies' => array( 'post_tag', 'category' ) // Add Category and Post Tags support )); } /*------------------------------------*\ ShortCode Functions \*------------------------------------*/ // Shortcode Demo with Nested Capability function html5_shortcode_demo($atts, $content = null) { return '<div class="shortcode-demo">' . do_shortcode($content) . '</div>'; // do_shortcode allows for nested Shortcodes } // Shortcode Demo with simple <h2> tag function html5_shortcode_demo_2($atts, $content = null) // Demo Heading H2 shortcode, allows for nesting within above element. Fully expandable. { return '<h2>' . $content . '</h2>'; } ?>
{ "content_hash": "9ef333823354a3a4acde06b6ad30138b", "timestamp": "", "source": "github", "line_count": 512, "max_line_length": 258, "avg_line_length": 38.607421875, "alnum_prop": 0.6214397733596398, "repo_name": "lawkng/html5blank-modified", "id": "f5760b21efd446b79e3171c1a5ac81298b322bdb", "size": "19767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "functions.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16699" }, { "name": "JavaScript", "bytes": "6257" }, { "name": "PHP", "bytes": "42870" } ], "symlink_target": "" }
namespace media { namespace cast { // Used by test code to create fake VideoEncodeAccelerators. The test code // controls when the response callback is invoked. class FakeVideoEncodeAcceleratorFactory { public: explicit FakeVideoEncodeAcceleratorFactory( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner); FakeVideoEncodeAcceleratorFactory(const FakeVideoEncodeAcceleratorFactory&) = delete; FakeVideoEncodeAcceleratorFactory& operator=( const FakeVideoEncodeAcceleratorFactory&) = delete; ~FakeVideoEncodeAcceleratorFactory(); int vea_response_count() const { return vea_response_count_; } // Set whether the next created media::FakeVideoEncodeAccelerator will // initialize successfully. void SetInitializationWillSucceed(bool will_init_succeed); // Enable/disable auto-respond mode. Default is disabled. void SetAutoRespond(bool auto_respond); // Creates a media::FakeVideoEncodeAccelerator. If in auto-respond mode, // |callback| is run synchronously (i.e., before this method returns). void CreateVideoEncodeAccelerator( ReceiveVideoEncodeAcceleratorCallback callback); // Runs the |callback| provided to the last call to // CreateVideoEncodeAccelerator() with the new VideoEncodeAccelerator // instance. void RespondWithVideoEncodeAccelerator(); private: const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; bool will_init_succeed_ = true; bool auto_respond_ = false; std::unique_ptr<media::VideoEncodeAccelerator> next_response_vea_; ReceiveVideoEncodeAcceleratorCallback vea_response_callback_; int vea_response_count_ = 0; }; } // namespace cast } // namespace media #endif // MEDIA_CAST_TEST_FAKE_VIDEO_ENCODE_ACCELERATOR_FACTORY_H_
{ "content_hash": "1af009f36580c57d29ed000d00c66b11", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 79, "avg_line_length": 35.857142857142854, "alnum_prop": 0.7723392145702903, "repo_name": "scheib/chromium", "id": "8a52796fc8860c34a7fdac9d863843c53ec4a883", "size": "2352", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "media/cast/test/fake_video_encode_accelerator_factory.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import sys import os from datetime import date sys.path.append(os.path.join(os.path.dirname(__file__), "..", "pox")) sys.path.append(os.path.join(os.path.dirname(__file__), "hassel/hsa-python")) def check_sw_version(path, remote_branch): ''' Return whether the latest commit of the git repo located at the given path is the same as the remote repo's remote_branch. ''' def get_version(branch="HEAD"): return os.popen("git rev-parse %s" % branch).read() old_cwd = os.getcwd() try: os.chdir(path) if os.system("git fetch") != 0: raise IOError("Unable to fetch from origin for repo %s" % path) local_version = get_version() remote_version = get_version(branch=remote_branch) return local_version == remote_version except Exception as e: print >> sys.stderr, ('''Unable to check whether software versions are ''' '''up-to-date: %s''' % e) finally: os.chdir(old_cwd) def check_dependencies(): ''' Double check whether POX and Hassel are at the latest software versions. ''' print >> sys.stderr, "Checking software versions..." pox_path = os.path.join(os.path.dirname(__file__), "..", "pox") if not check_sw_version(pox_path, "remotes/origin/debugger"): print >> sys.stderr, ('''Warning: POX version not up-to-date. You should ''' '''probably run:\n $ (cd pox; git pull) ''') hassel_path = os.path.join(os.path.dirname(__file__), "hassel") if not os.path.exists(os.path.join(hassel_path, "LICENSE.txt")): print >> sys.stderr, "Warning: Hassel submodule not loaded." elif not check_sw_version(hassel_path, "remotes/origin/HEAD"): print >> sys.stderr, ('''Warning: Hassel version not up-to-date. You should ''' '''probably run:\n $ git submodule update ''') # We store the last date we checked software versions in sts/last-version-check. # The format of the file is: date.today().toordinal() timestamp_path = os.path.join(os.path.dirname(__file__), "last-version-check") def checked_recently(): ''' Return whether we have checked dependencies in the last day. ''' if not os.path.exists(timestamp_path): return False current_date = date.today() with open(timestamp_path) as timestamp_file: try: last_check_date = date.fromordinal(int(timestamp_file.read())) except: # Possible corruption. return False return last_check_date == current_date def write_new_timestamp(): with open(timestamp_path, "w") as timestamp_file: current_date = date.today() timestamp_file.write(str(current_date.toordinal())) # We only check dependencies once a day, since `git fetch` takes a fair amount of # time. if not checked_recently(): check_dependencies() write_new_timestamp()
{ "content_hash": "31f0f1aef4a2224c5bf4b67d771c80e6", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 83, "avg_line_length": 38.10958904109589, "alnum_prop": 0.6599568655643422, "repo_name": "jmiserez/sts", "id": "2f694463ba9218477cfacf73f84512273adab5fe", "size": "3402", "binary": false, "copies": "2", "ref": "refs/heads/hb", "path": "sts/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "1167857" }, { "name": "Shell", "bytes": "16594" } ], "symlink_target": "" }
title: Parsing with PetitParser2 layout: default --- # Parsing with PetitParser2 In this blog we describe [PetitParser2](https://github.com/kursjan/petitparser2) --- a modular and flexible high-performance top-down parsing framework. ## Structure ### Introduction This introduction describes basics of PetitParser2 and how to migrate from PetitParser to PetitParser2. There are other tutorials for PetitParser. We recommend the following: - [Writing Parser with PetitParser](https://www.lukas-renggli.ch/blog/petitparser-1) from Lukas Renggli. - [PetitParser chapter](http://scg.unibe.ch/archive/papers/Kurs13a-PetitParser.pdf) in the [Deep into Pharo](http://www.deepintopharo.com/) book. - [Introduction to PetitParser2](http://www.humane-assessment.com/blog/introducing-petitparser2/) by Tudor Girba. ### Development Guide Describes full cycle of parser development. Starts from scripting in a playground and ends with a full-fledged, tested and high-performance parser. Covers topics such as tolerant parsing, abstract-syntax tree, optimizations and debugging. <!-- ## Uniqe Features of PetitParser2 We cover many topics, some of them well-known in the area of parsing, nevertheless, the following technologies are unique for PetitParser: - **Bounded seas** is a technology that allows a programmer to focus on the interesting parts of an input (i.e. Javascript code in our case) and ignore the rest (i.e. the remaining HTML code). - **Context-sensitive rules** that allow us to detect matching begin and end HTML tags and recover from malformed inputs. - **Optimizations** of PetitParser to turn our prototype into a an efficient top-down parser. --> ## Getting Started The easiest way to start this tutorial is to use [Moose](http://moosetechnology.org). Moose is a software and data analysis platform that has everything we need already installed. Alternatively, you can download clean [Pharo 6](http://pharo.org) (or higher) image and install PetitParser2 using the following command: ```smalltalk Metacello new baseline: 'PetitParser2Gui'; repository: 'github://kursjan/petitparser2'; load ``` In case it does not work, please let me know: <kurs.jan@gmail.com>. ## Changelog - *2019-12-30* - Introduction to PetitParser2. - *2018-10-10* - Minor text tweaks, turned to Markdown and Jekyll on GitHub pages. - *2017-02-21* - First draft of he Developer's workflow ## TODO {% include todo.html content="Parsing Streams" %} <!-- {% include todo.html content=" Smalltalk parser On a concrete example of a Smalltalk grammar, we describe how to develop a parser whose performance is comparable to a table-driven parsers such as [SmaCC](https://github.com/ThierryGoubier/SmaCC) or hand-written parsers such as RBParser (a parser used by Pharo compiler). @@todo add some graphs? "%} --> <!-- {% include todo.html content="Syntax Highlighting " %} --> ## License The text is released under the [MIT license]({% link LICENSE.md %}). ## Contact Do you have ideas, suggestions or issues? Write me an email (<kurs.jan@gmail.com>), or contact us on [github](github.com/kursjan/petitparser2/issues)!
{ "content_hash": "4a40817f2bfce428f2d411e480f67488", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 272, "avg_line_length": 42.78082191780822, "alnum_prop": 0.7620877361511367, "repo_name": "kursjan/petitparser2", "id": "59b6f89e90a1598239e65869c6340e7e24af147c", "size": "3127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "21422" }, { "name": "Shell", "bytes": "2326" }, { "name": "Smalltalk", "bytes": "916700" } ], "symlink_target": "" }
@implementation HMMessageBusiness + (void)readNewestCommonMsgFromServerWithFamilyId:(NSString *)familyId messageType:(HMMessageType)messageType completion:(commonBlockWithObject)completion { // 获得本地数据库中当前家庭普通消息的最大序号 int maxUserSequence = [HMMessageCommonModel getMaxSequenceNumWithFamilyId:familyId messageType:messageType]; [self readCommonMsgBetweenMinSequence:maxUserSequence andMaxSequence:-1 familyId:familyId messageType:messageType completion:completion]; } + (void)readNewestSecurityMsgFromServerWithFamilyId:(NSString *)familyId completion:(commonBlockWithObject)completion { // 获得本地数据库中当前家庭安防消息的最大序号 int maxUserSequence = [HMMessageSecurityModel getMaxSequenceNumWithFamilyld:familyId]; [self readSecurityMsgBetweenMinSequence:maxUserSequence andMaxSequence:-1 familyId:familyId completion:completion]; } + (void)readSecurityMsgBetweenMinSequence:(int)minSe andMaxSequence:(int)maxSe familyId:(NSString *)familyId completion:(commonBlockWithObject)completion { if (!isNetworkAvailable()) { if (completion) { completion(KReturnValueNetWorkProblem,nil); } return; } QueryUserMessage *cmd = [QueryUserMessage object]; cmd.userId = userAccout().userId; cmd.familyId = familyId; cmd.tableName = @"messageSecurity"; cmd.maxSequence = maxSe; cmd.minSequence = minSe; cmd.readCount = kHMMessageAPI_PerReadCount; cmd.sendToServer = YES; sendCmd(cmd, ^(KReturnValue returnValue, NSDictionary *returnDic) { if (returnValue == KReturnValueSuccess) { NSArray *statusRecordArr = returnDic[@"data"]; for (NSDictionary *dic in statusRecordArr) { if (dic && [dic isKindOfClass:[NSDictionary class]]) { HMMessageSecurityModel *model = [HMMessageSecurityModel objectFromDictionary:dic]; model.readType = 0; [model insertObject]; } } if (completion) { completion(returnValue,returnDic); } } }); } + (void)readNewStatusRecordWithSecurityDevice:(HMDevice *)device completion:(commonBlockWithObject)completion { if (![device isKindOfClass:[HMDevice class]]) { if (completion) { completion(KReturnValueParameterError,nil); } return; } if (!isNetworkAvailable()) { if (completion) { completion(KReturnValueNetWorkProblem,nil); } return; } int minSequence = (int)[HMStatusRecordModel getLastDeleteSequence:device recordType:StatusRecordTypeAll]; QueryStatusRecordCmd *qsrCmd = [QueryStatusRecordCmd object]; qsrCmd.deviceId = device.deviceId; qsrCmd.maxSequence = -1; qsrCmd.minSequence = minSequence; qsrCmd.readCount = kHMMessageAPI_PerReadCount; qsrCmd.userName = userAccout().userName; qsrCmd.uid = device.uid; qsrCmd.sendToServer = YES; sendCmd(qsrCmd, ^(KReturnValue returnValue, NSDictionary *returnDic) { if (returnValue == KReturnValueSuccess) { [HMDatabaseManager insertInTransactionWithHandler:^(NSMutableArray *objectArray) { NSArray *statusRecordArr = returnDic[@"statusRecordList"]; if ([statusRecordArr isKindOfClass:[NSArray class]]) { for (NSDictionary *dic in statusRecordArr) { HMStatusRecordModel *model = [HMStatusRecordModel objectFromDictionary:dic]; model.readType = 1; // [model insertObject]; [objectArray addObject:model]; } } } completion:^{ if (completion) { completion(returnValue,returnDic); } }]; } }); } + (void)readOldCommonMsgBeforeSequence:(int)sequence familyId:(NSString *)familyId messageType:(HMMessageType)messageType completion:(commonBlockWithObject)completion { int maxDeleteSequence = [HMMessageCommonModel getMaxDeleteSequenceWithFamilyId:familyId messageType:messageType]; if (sequence <= maxDeleteSequence) { DLog(@"打算请求序号:%d以前的数据 最大删除序号:%d 不再请求小于最大删除序号的数据",sequence,maxDeleteSequence); } [self readCommonMsgBetweenMinSequence:maxDeleteSequence andMaxSequence:sequence familyId:familyId messageType:messageType completion:completion]; } + (void)readCommonMsgBetweenMinSequence:(int)minSe andMaxSequence:(int)maxSe familyId:(NSString *)familyId messageType:(HMMessageType)messageType completion:(commonBlockWithObject)completion { if (!isNetworkAvailable()) { if (completion) { completion(KReturnValueNetWorkProblem,nil); } return; } QueryUserMessage *qurCmd = [QueryUserMessage object]; qurCmd.userId = userAccout().userId; qurCmd.familyId = familyId; qurCmd.tableName = @"messageCommon"; qurCmd.minSequence = minSe; qurCmd.maxSequence = maxSe; qurCmd.type = (int)messageType; qurCmd.readCount = kHMMessageAPI_PerReadCount; qurCmd.sendToServer = YES; sendCmd(qurCmd, ^(KReturnValue returnValue, NSDictionary *returnDic) { DLog(@"读messageCommon表返回数据:%@",returnDic); NSString *tableName = returnDic[@"tableName"]; if ([tableName isKindOfClass:[NSString class]] && [tableName isEqualToString:@"messageCommon"]) { NSArray *commonMsgArr = returnDic[@"data"]; if ([commonMsgArr isKindOfClass:[NSArray class]]) { if (commonMsgArr.count) { [[HMDatabaseManager shareDatabase]inSerialQueue:^{ NSMutableArray *objectsArray = [NSMutableArray array]; for (NSDictionary *msgDic in commonMsgArr) { //DLog(@"msgDic : %@",msgDic); HMMessageCommonModel *model = [HMMessageCommonModel objectFromDictionary:msgDic]; NSString *paramStr = [msgDic objectForKey:@"params"]; if (paramStr != nil && ![paramStr isEqual:[NSNull null]]) { NSData *jsonData = [paramStr dataUsingEncoding:NSUTF8StringEncoding]; if (jsonData.length) { NSDictionary *paramStrDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil]; if (paramStrDic) { id deviceNameObj = [paramStrDic objectForKey:@"deviceName"]; id roomNameObj = [paramStrDic objectForKey:@"roomName"]; if ([deviceNameObj isKindOfClass:[NSString class]]) { model.deviceName = deviceNameObj; }else { model.deviceName = @""; } if ([roomNameObj isKindOfClass:[NSString class]]) { model.roomName = roomNameObj; }else { model.roomName = @""; } } } } [model sql]; [objectsArray addObject:model]; } [[HMDatabaseManager shareDatabase]inTransaction:^(FMDatabase *db, BOOL *rollback) { [objectsArray setValue:db forKey:@"insertWithDb"]; if (completion) { dispatch_async(dispatch_get_main_queue(), ^{ completion(returnValue,returnDic); }); } }]; }]; } } } }); } @end
{ "content_hash": "e8e20e0ea69c62b45a2491c8637ea650", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 192, "avg_line_length": 45.67379679144385, "alnum_prop": 0.5542676501580611, "repo_name": "kenny2006cen/GYXMPP", "id": "839e560e53aac1e42a12864c24b365cadf0bf03a", "size": "8883", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HMModules/HomeMateModule/HomeMateModule/Classes/HMSDK/HMBusiness/HMMessage/HMMessageBusiness.m", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "51011" }, { "name": "Objective-C", "bytes": "5119543" }, { "name": "Ruby", "bytes": "369" }, { "name": "Shell", "bytes": "10377" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe Nomis::Client do let(:api_host) { Rails.configuration.prison_api_host } let(:path) { 'v1/lookup/active_offender' } let(:params) { { noms_id: 'G7244GR', date_of_birth: Date.parse('1966-11-22') } } subject { described_class.new(api_host) } describe 'with a valid request', vcr: { cassette_name: 'client-request-id' } do it 'sets the X-Request-Id header if a request_id is present' do RequestStore.store[:request_id] = 'uuid' subject.get(path, params) expect(WebMock).to have_requested(:get, /\w/). with(headers: { 'X-Request-Id' => 'uuid' }) end end context 'when there is an http status error' do let(:error) do Excon::Error::HTTPStatus.new('error', double('request'), double('response', status: 422, body: '<html>')) end before do WebMock.stub_request(:get, /\w/).to_raise(error) end it 'raises an APIError', :expect_exception do expect { subject.get(path, params) }. to raise_error(Nomis::APIError, 'Unexpected status 422 calling GET /api/v1/lookup/active_offender: (invalid-JSON) <html>') end it 'sends the error to sentry' do expect(PVB::ExceptionHandler).to receive(:capture_exception).with(error, fingerprint: %w[nomis excon]) expect { subject.get(path, params) }.to raise_error(Nomis::APIError) end end context 'when there is a timeout' do before do WebMock.stub_request(:get, /\w/).to_timeout end it 'raises an Nomis::TimeoutError if a timeout occurs', :expect_exception do expect { subject.get(path, params) }.to raise_error(Nomis::APIError) end end context 'when there is an unexpected exception' do let(:error) do Excon::Errors::SocketError.new(StandardError.new('Socket error')) end before do WebMock.stub_request(:get, /\w/).to_raise(error) end it 'raises an APIError if an unexpected exception is raised containing request information', :expect_exception do expect { subject.get(path, params) }.to raise_error(Nomis::APIError) end end describe 'with an error' do let(:error) do Excon::Error::HTTPStatus.new('error', double('request'), double('response', status: 422, body: '<html>')) end before do WebMock.stub_request(:get, /\w/).to_raise(error) end it 'raises an APIError if an unexpected exception is raised containing request information', :expect_exception do expect { subject.get(path, params) }.to raise_error(Nomis::APIError, 'Unexpected status 422 calling GET /api/v1/lookup/active_offender: (invalid-JSON) <html>') end it 'sends the error to sentry' do expect(PVB::ExceptionHandler).to receive(:capture_exception).with(error, fingerprint: %w[nomis excon]) expect { subject.get(path, params) }.to raise_error(Nomis::APIError) end it 'increments the api error count', :expect_exception do expect { subject.get(path, params) }.to raise_error(Nomis::APIError). and change { PVB::Instrumentation.custom_log_items[:api_request_count] }.from(nil).to(1) end end describe 'with auth configured' do let(:public_key) { Base64.decode64(ENV['NOMIS_OAUTH_PUBLIC_KEY']) } let(:cert) { OpenSSL::PKey::RSA.new(public_key) } it 'sends an Authorization header containing a JWT token', vcr: { cassette_name: 'client-auth' } do subject.get(path, params) expect(WebMock).to have_requested(:get, /\w/). with { |req| auth_type, token = req.headers["Authorization"].split(' ') next unless auth_type == 'Bearer' # raises an error if token is not an ES256 JWT token JWT.decode(token, cert, true, algorithm: 'RS256') true } end end end
{ "content_hash": "f2327902f4e4895485ce3f6ae7f72037", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 130, "avg_line_length": 31.77777777777778, "alnum_prop": 0.6198801198801199, "repo_name": "ministryofjustice/prison-visits-2", "id": "d3eae063158efaa7710ab79e046f873b051dfffd", "size": "4004", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spec/services/nomis/client_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "803" }, { "name": "Dockerfile", "bytes": "993" }, { "name": "HTML", "bytes": "115705" }, { "name": "JavaScript", "bytes": "59559" }, { "name": "Procfile", "bytes": "133" }, { "name": "Ruby", "bytes": "779398" }, { "name": "SCSS", "bytes": "42663" }, { "name": "Shell", "bytes": "3558" } ], "symlink_target": "" }
'use strict'; /** * Defines workload agnostic properties for a job. * */ class Job { /** * Create a Job. * @member {string} [entityFriendlyName] Friendly name of the entity on which * the current job is executing. * @member {string} [backupManagementType] Backup management type to execute * the current job. Possible values include: 'Invalid', 'AzureIaasVM', 'MAB', * 'DPM', 'AzureBackupServer', 'AzureSql', 'AzureStorage', 'AzureWorkload', * 'DefaultBackup' * @member {string} [operation] The operation name. * @member {string} [status] Job status. * @member {date} [startTime] The start time. * @member {date} [endTime] The end time. * @member {string} [activityId] ActivityId of job. * @member {string} jobType Polymorphic Discriminator */ constructor() { } /** * Defines the metadata of Job * * @returns {object} metadata of Job * */ mapper() { return { required: false, serializedName: 'Job', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: 'jobType', clientName: 'jobType' }, uberParent: 'Job', className: 'Job', modelProperties: { entityFriendlyName: { required: false, serializedName: 'entityFriendlyName', type: { name: 'String' } }, backupManagementType: { required: false, serializedName: 'backupManagementType', type: { name: 'String' } }, operation: { required: false, serializedName: 'operation', type: { name: 'String' } }, status: { required: false, serializedName: 'status', type: { name: 'String' } }, startTime: { required: false, serializedName: 'startTime', type: { name: 'DateTime' } }, endTime: { required: false, serializedName: 'endTime', type: { name: 'DateTime' } }, activityId: { required: false, serializedName: 'activityId', type: { name: 'String' } }, jobType: { required: true, serializedName: 'jobType', isPolymorphicDiscriminator: true, type: { name: 'String' } } } } }; } } module.exports = Job;
{ "content_hash": "347ccdf06bf30da6fd693a05f77e3f1f", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 79, "avg_line_length": 24.618181818181817, "alnum_prop": 0.48190546528803546, "repo_name": "xingwu1/azure-sdk-for-node", "id": "585c78c3b392683b9691485d87e24e401c5484db", "size": "3025", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/services/recoveryServicesBackupManagement/lib/models/job.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "661" }, { "name": "JavaScript", "bytes": "122792600" }, { "name": "Shell", "bytes": "437" }, { "name": "TypeScript", "bytes": "2558" } ], "symlink_target": "" }
{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% import "_macros.html" as macros %} {% block title %}Ansible{% endblock %} {% block page_content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <script> $(document).ready(function() { var ip=$('#ip').val(); <!--var inventory=2;--> <!--var playbookName='cisco_xe.yml';--> <!--alert(playbookName);--> $('#progress').show(); $.ajax({ type: "POST", url: "http://200.12.221.13:5005/runtraceroute", data: { ip : ip }, success:function(result){ //alert(result); $('#AllResult').show(); $('#downloadlink').show(); $('#progress').hide(); $('#AllResult').text(result.value); }, error:function(xhr, status, error) { $('#AllResult').show(); $('#downloadlink').show(); $('#progress').hide(); alert(xhr.status); alert(status); $('#AllResult').text(error); } }); }); </script> <!-- <div class="jumbotron"> --> <input hidden type="text" name="ip" id="ip" value="{{ ip }}"><br/><br/> <center> </center> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">Stdout </a> <p class="navbar-text navbar-right" id="downloadlink" hidden>Download <a href="http://200.12.221.13:5005/downloadstdout?result={{ resultid }}" class="navbar-link">Output</a></p> <div class="bs-example clearfix"> <textarea rows="100" cols="100" id="AllResult" hidden> </textarea> </div> </div> </div> </nav> <div id="progress" class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"> <span class="sr-only">100% Complete</span> </div> </div> {% endblock %} {% block scripts %} {{ super() }} {{ pagedown.include_pagedown() }} {% endblock %}
{ "content_hash": "c4eb640b575820efb3d110dcc4a2bf87", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 184, "avg_line_length": 29.011764705882353, "alnum_prop": 0.46877534468775345, "repo_name": "davismathew/netautgui", "id": "c46f05a0236f89a555ea19b7d080469a9513bfce", "size": "2466", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/templates/ansible/traceroute.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1855" }, { "name": "HTML", "bytes": "44191" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "124900" } ], "symlink_target": "" }
<?php namespace App\Model\Table; use Cake\ORM\Query; use Cake\ORM\RulesChecker; use Cake\ORM\Table; use Cake\Validation\Validator; /** * Skills Model * * @property \Cake\ORM\Association\BelongsTo $Talents * @property \Cake\ORM\Association\HasMany $Links * @property \Cake\ORM\Association\HasMany $Ranks * @property \Cake\ORM\Association\HasMany $SkillsTree * @property \Cake\ORM\Association\BelongsToMany $Stats * @property \Cake\ORM\Association\BelongsToMany $Users * * @method \App\Model\Entity\Skill get($primaryKey, $options = []) * @method \App\Model\Entity\Skill newEntity($data = null, array $options = []) * @method \App\Model\Entity\Skill[] newEntities(array $data, array $options = []) * @method \App\Model\Entity\Skill|bool save(\Cake\Datasource\EntityInterface $entity, $options = []) * @method \App\Model\Entity\Skill patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = []) * @method \App\Model\Entity\Skill[] patchEntities($entities, array $data, array $options = []) * @method \App\Model\Entity\Skill findOrCreate($search, callable $callback = null) */ class SkillsTable extends Table { /** * Initialize method * * @param array $config The configuration for the Table. * @return void */ public function initialize(array $config) { parent::initialize($config); $this->table('skills'); $this->displayField('title'); $this->primaryKey('id'); $this->belongsTo('Talents', [ 'foreignKey' => 'talent_id', 'joinType' => 'LEFT' ]); $this->hasMany('Links', [ 'foreignKey' => 'skill_id' ]); $this->hasMany('Ranks', [ 'foreignKey' => 'skill_id' ]); $this->hasMany('SkillsTree', [ 'foreignKey' => 'skill_id' ]); $this->belongsToMany('Stats', [ 'foreignKey' => 'skill_id', 'targetForeignKey' => 'stat_id', 'joinTable' => 'skills_stats' ]); $this->belongsToMany('Users', [ 'foreignKey' => 'skill_id', 'targetForeignKey' => 'user_id', 'joinTable' => 'users_skills' ]); // $this->addBehavior('CounterCache', [ // 'Ranks' => ['rank_count'] // ]); // Add the behaviour and configure any options you want $this->addBehavior('Proffer.Proffer', [ 'photo' => [ // The name of your upload field 'root' => WWW_ROOT . 'files', // Customise the root upload folder here, or omit to use the default 'dir' => 'photo_dir', // The name of the field to store the folder 'thumbnailSizes' => [ // Declare your thumbnails 'square' => [ // Define the prefix of your thumbnail 'w' => 128, // Width 'h' => 128, // Height 'jpeg_quality' => 100 ], ], 'thumbnailMethod' => 'gd', // Options are Imagick or Gd 'crop' => true ] ]); } /** * Default validation rules. * * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator */ public function validationDefault(Validator $validator) { $validator ->uuid('id') ->allowEmpty('id', 'create'); $validator ->requirePresence('title', 'create') ->notEmpty('title'); $validator ->requirePresence('description', 'create') ->notEmpty('description'); $validator->provider('proffer', 'Proffer\Model\Validation\ProfferRules'); // Set the thumbnail resize dimensions $validator->add('photo', 'proffer', [ 'rule' => ['dimensions', [ 'min' => ['w' => 50, 'h' => 50], 'max' => ['w' => 3000, 'h' => 3000] ]], 'message' => 'Image is not correct dimensions.', 'provider' => 'proffer' ]); $validator->allowEmpty('photo'); return $validator; } /** * Returns a rules checker object that will be used for validating * application integrity. * * @param \Cake\ORM\RulesChecker $rules The rules object to be modified. * @return \Cake\ORM\RulesChecker */ public function buildRules(RulesChecker $rules) { $rules->add($rules->existsIn(['talent_id'], 'Talents')); return $rules; } }
{ "content_hash": "f7085bfb4f432d13ea0154e49929c541", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 122, "avg_line_length": 33.13669064748201, "alnum_prop": 0.546461137646548, "repo_name": "mobilefunuk/skilltree", "id": "51673d1551db12c0f61666bfd433ad04ce0b6722", "size": "4606", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cake/src/Model/Table/SkillsTable.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "270" }, { "name": "Batchfile", "bytes": "834" }, { "name": "CSS", "bytes": "49496" }, { "name": "HTML", "bytes": "162884" }, { "name": "JavaScript", "bytes": "41277" }, { "name": "PHP", "bytes": "220445" }, { "name": "Pascal", "bytes": "4096" }, { "name": "Puppet", "bytes": "935723" }, { "name": "Ruby", "bytes": "2163990" }, { "name": "Shell", "bytes": "190519" }, { "name": "VimL", "bytes": "10274" } ], "symlink_target": "" }
'use strict' /* Add controller to app by using the controller function */ /* Passing in a function that defines the controller include parameters with this * controller for the scope and services we might need to use. */ motoApp.controller('ListRidesCtrl', function($scope, motoRidesDataService){ motoRidesDataService.getListOfRides().$promise.then(function(data){ $scope.rides = data.rides; }); });
{ "content_hash": "8af16a4e07866f80dfdee833597bd3b9", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 81, "avg_line_length": 41.9, "alnum_prop": 0.7374701670644391, "repo_name": "josh-bradley/MotorcycleRidesWeb", "id": "0099bec9aeaa4defb2184d6e49b7f925e2c5f982", "size": "419", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/js/controllers/ListRidesCtrl.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6811" }, { "name": "JavaScript", "bytes": "256877" }, { "name": "Ruby", "bytes": "503" }, { "name": "Shell", "bytes": "1051" } ], "symlink_target": "" }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Reflection; using System.Text; namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// Class containing miscellaneous helpers to deal with /// PSObject manipulation. /// </summary> internal static class PSObjectHelper { #region tracer [TraceSource("PSObjectHelper", "PSObjectHelper")] private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("PSObjectHelper", "PSObjectHelper"); #endregion tracer internal const char Ellipsis = '\u2026'; internal static string PSObjectIsOfExactType(Collection<string> typeNames) { if (typeNames.Count != 0) return typeNames[0]; return null; } internal static bool PSObjectIsEnum(Collection<string> typeNames) { if (typeNames.Count < 2 || string.IsNullOrEmpty(typeNames[1])) return false; return string.Equals(typeNames[1], "System.Enum", StringComparison.Ordinal); } /// <summary> /// Retrieve the display name. It looks for a well known property and, /// if not found, it uses some heuristics to get a "close" match. /// </summary> /// <param name="target">Shell object to process.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <returns>Resolved PSPropertyExpression; null if no match was found.</returns> internal static PSPropertyExpression GetDisplayNameExpression(PSObject target, PSPropertyExpressionFactory expressionFactory) { // first try to get the expression from the object (types.ps1xml data) PSPropertyExpression expressionFromObject = GetDefaultNameExpression(target); if (expressionFromObject != null) { return expressionFromObject; } // we failed the default display name, let's try some well known names // trying to get something potentially useful string[] knownPatterns = new string[] { "name", "id", "key", "*key", "*name", "*id", }; // go over the patterns, looking for the first match foreach (string pattern in knownPatterns) { PSPropertyExpression ex = new PSPropertyExpression(pattern); List<PSPropertyExpression> exprList = ex.ResolveNames(target); while ((exprList.Count > 0) && ( exprList[0].ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || exprList[0].ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || exprList[0].ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase) || exprList[0].ToString().Equals(RemotingConstants.SourceJobInstanceId, StringComparison.OrdinalIgnoreCase))) { exprList.RemoveAt(0); } if (exprList.Count == 0) continue; // if more than one match, just return the first one return exprList[0]; } // we did not find anything return null; } /// <summary> /// It gets the display name value. /// </summary> /// <param name="target">Shell object to process.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <returns>PSPropertyExpressionResult if successful; null otherwise.</returns> internal static PSPropertyExpressionResult GetDisplayName(PSObject target, PSPropertyExpressionFactory expressionFactory) { // get the expression to evaluate PSPropertyExpression ex = GetDisplayNameExpression(target, expressionFactory); if (ex == null) return null; // evaluate the expression List<PSPropertyExpressionResult> resList = ex.GetValues(target); if (resList.Count == 0 || resList[0].Exception != null) { // no results or the retrieval on the first one failed return null; } // return something only if the first match was successful return resList[0]; } /// <summary> /// This is necessary only to consider IDictionaries as IEnumerables, since LanguagePrimitives.GetEnumerable does not. /// </summary> /// <param name="obj">Object to extract the IEnumerable from.</param> internal static IEnumerable GetEnumerable(object obj) { PSObject mshObj = obj as PSObject; if (mshObj != null) { obj = mshObj.BaseObject; } if (obj is IDictionary) { return (IEnumerable)obj; } return LanguagePrimitives.GetEnumerable(obj); } private static string GetSmartToStringDisplayName(object x, PSPropertyExpressionFactory expressionFactory) { PSPropertyExpressionResult r = PSObjectHelper.GetDisplayName(PSObjectHelper.AsPSObject(x), expressionFactory); if ((r != null) && (r.Exception == null)) { return PSObjectHelper.AsPSObject(r.Result).ToString(); } else { return PSObjectHelper.AsPSObject(x).ToString(); } } private static string GetObjectName(object x, PSPropertyExpressionFactory expressionFactory) { string objName; // check if the underlying object is of primitive type // if so just return its value if (x is PSObject && (LanguagePrimitives.IsBoolOrSwitchParameterType((((PSObject)x).BaseObject).GetType()) || LanguagePrimitives.IsNumeric(((((PSObject)x).BaseObject).GetType()).GetTypeCode()) || LanguagePrimitives.IsNull(x))) { objName = x.ToString(); } else if (x == null) { // use PowerShell's $null variable to indicate that the value is null... objName = "$null"; } else { MethodInfo toStringMethod = x.GetType().GetMethod("ToString", Type.EmptyTypes); // TODO:CORECLR double check with CORE CLR that x.GetType() == toStringMethod.ReflectedType // Check if the given object "x" implements "toString" method. Do that by comparing "DeclaringType" which 'Gets the class that declares this member' and the object type if (toStringMethod.DeclaringType == x.GetType()) { objName = PSObjectHelper.AsPSObject(x).ToString(); } else { PSPropertyExpressionResult r = PSObjectHelper.GetDisplayName(PSObjectHelper.AsPSObject(x), expressionFactory); if ((r != null) && (r.Exception == null)) { objName = PSObjectHelper.AsPSObject(r.Result).ToString(); } else { objName = PSObjectHelper.AsPSObject(x).ToString(); if (objName == string.Empty) { var baseObj = PSObject.Base(x); if (baseObj != null) { objName = baseObj.ToString(); } } } } } return objName; } /// <summary> /// Helper to convert an PSObject into a string /// It takes into account enumerations (use display name) /// </summary> /// <param name="so">Shell object to process.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <param name="enumerationLimit">Limit on IEnumerable enumeration.</param> /// <param name="formatErrorObject">Stores errors during string conversion.</param> /// <returns>String representation.</returns> internal static string SmartToString(PSObject so, PSPropertyExpressionFactory expressionFactory, int enumerationLimit, StringFormatError formatErrorObject) { if (so == null) return string.Empty; try { IEnumerable e = PSObjectHelper.GetEnumerable(so); if (e != null) { StringBuilder sb = new StringBuilder(); sb.Append('{'); bool first = true; int enumCount = 0; IEnumerator enumerator = e.GetEnumerator(); if (enumerator != null) { IBlockingEnumerator<object> be = enumerator as IBlockingEnumerator<object>; if (be != null) { while (be.MoveNext(false)) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(Ellipsis); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(be.Current, expressionFactory)); if (first) first = false; } } else { foreach (object x in e) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(Ellipsis); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(x, expressionFactory)); if (first) first = false; } } } sb.Append('}'); return sb.ToString(); } // take care of the case there is no base object return so.ToString(); } catch (Exception e) when (e is ExtendedTypeSystemException || e is InvalidOperationException) { // These exceptions are being caught and handled by returning an empty string when // the object cannot be stringified due to ETS or an instance in the collection has been modified s_tracer.TraceWarning($"SmartToString method: Exception during conversion to string, emitting empty string: {e.Message}"); if (formatErrorObject != null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = e; } return string.Empty; } } private static readonly PSObject s_emptyPSObject = new PSObject(string.Empty); internal static PSObject AsPSObject(object obj) { return (obj == null) ? s_emptyPSObject : PSObject.AsPSObject(obj); } /// <summary> /// Format an object using a provided format string directive. /// </summary> /// <param name="directive">Format directive object to use.</param> /// <param name="val">Object to format.</param> /// <param name="enumerationLimit">Limit on IEnumerable enumeration.</param> /// <param name="formatErrorObject">Formatting error object, if present.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <returns>String representation.</returns> internal static string FormatField(FieldFormattingDirective directive, object val, int enumerationLimit, StringFormatError formatErrorObject, PSPropertyExpressionFactory expressionFactory) { PSObject so = PSObjectHelper.AsPSObject(val); if (directive != null && !string.IsNullOrEmpty(directive.formatString)) { // we have a formatting directive, apply it // NOTE: with a format directive, we do not make any attempt // to deal with IEnumerable try { // use some heuristics to determine if we have "composite formatting" // 2004/11/16-JonN This is heuristic but should be safe enough if (directive.formatString.Contains("{0") || directive.formatString.Contains('}')) { // we do have it, just use it return string.Format(CultureInfo.CurrentCulture, directive.formatString, so); } // we fall back to the PSObject's IFormattable.ToString() // pass a null IFormatProvider return so.ToString(directive.formatString, null); } catch (Exception e) // 2004/11/17-JonN This covers exceptions thrown in // string.Format and PSObject.ToString(). // I think we can swallow these. { // NOTE: we catch all the exceptions, since we do not know // what the underlying object access would throw if (formatErrorObject != null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = e; formatErrorObject.formatString = directive.formatString; return string.Empty; } } } // we do not have a formatting directive or we failed the formatting (fallback) // but we did not report as an error; // this call would deal with IEnumerable if the object implements it return PSObjectHelper.SmartToString(so, expressionFactory, enumerationLimit, formatErrorObject); } private static PSMemberSet MaskDeserializedAndGetStandardMembers(PSObject so) { Diagnostics.Assert(so != null, "Shell object to process cannot be null"); var typeNames = so.InternalTypeNames; Collection<string> typeNamesWithoutDeserializedPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typeNamesWithoutDeserializedPrefix == null) { return null; } TypeTable typeTable = so.GetTypeTable(); if (typeTable == null) { return null; } PSMemberInfoInternalCollection<PSMemberInfo> members = typeTable.GetMembers<PSMemberInfo>(new ConsolidatedString(typeNamesWithoutDeserializedPrefix)); return members[TypeTable.PSStandardMembers] as PSMemberSet; } private static List<PSPropertyExpression> GetDefaultPropertySet(PSMemberSet standardMembersSet) { if (standardMembersSet != null) { PSPropertySet defaultDisplayPropertySet = standardMembersSet.Members[TypeTable.DefaultDisplayPropertySet] as PSPropertySet; if (defaultDisplayPropertySet != null) { List<PSPropertyExpression> retVal = new List<PSPropertyExpression>(); foreach (string prop in defaultDisplayPropertySet.ReferencedPropertyNames) { if (!string.IsNullOrEmpty(prop)) { retVal.Add(new PSPropertyExpression(prop)); } } return retVal; } } return new List<PSPropertyExpression>(); } /// <summary> /// Helper to retrieve the default property set of a shell object. /// </summary> /// <param name="so">Shell object to process.</param> /// <returns>Resolved expression; empty list if not found.</returns> internal static List<PSPropertyExpression> GetDefaultPropertySet(PSObject so) { List<PSPropertyExpression> retVal = GetDefaultPropertySet(so.PSStandardMembers); if (retVal.Count == 0) { retVal = GetDefaultPropertySet(MaskDeserializedAndGetStandardMembers(so)); } return retVal; } private static PSPropertyExpression GetDefaultNameExpression(PSMemberSet standardMembersSet) { if (standardMembersSet != null) { PSNoteProperty defaultDisplayProperty = standardMembersSet.Members[TypeTable.DefaultDisplayProperty] as PSNoteProperty; if (defaultDisplayProperty != null) { string expressionString = defaultDisplayProperty.Value.ToString(); if (string.IsNullOrEmpty(expressionString)) { // invalid data, the PSObject is empty return null; } else { return new PSPropertyExpression(expressionString); } } } return null; } private static PSPropertyExpression GetDefaultNameExpression(PSObject so) { PSPropertyExpression retVal = GetDefaultNameExpression(so.PSStandardMembers) ?? GetDefaultNameExpression(MaskDeserializedAndGetStandardMembers(so)); return retVal; } /// <summary> /// Helper to retrieve the value of an PSPropertyExpression and to format it. /// </summary> /// <param name="so">Shell object to process.</param> /// <param name="enumerationLimit">Limit on IEnumerable enumeration.</param> /// <param name="ex">Expression to use for retrieval.</param> /// <param name="directive">Format directive to use for formatting.</param> /// <param name="formatErrorObject"></param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <param name="result">Not null if an error condition arose.</param> /// <returns>Formatted string.</returns> internal static string GetExpressionDisplayValue( PSObject so, int enumerationLimit, PSPropertyExpression ex, FieldFormattingDirective directive, StringFormatError formatErrorObject, PSPropertyExpressionFactory expressionFactory, out PSPropertyExpressionResult result) { result = null; List<PSPropertyExpressionResult> resList = ex.GetValues(so); if (resList.Count == 0) { return string.Empty; } result = resList[0]; if (result.Exception != null) { return string.Empty; } return PSObjectHelper.FormatField(directive, result.Result, enumerationLimit, formatErrorObject, expressionFactory); } /// <summary> /// Queries PSObject and determines if ComputerName property should be shown. /// </summary> /// <param name="so"></param> /// <returns></returns> internal static bool ShouldShowComputerNameProperty(PSObject so) { bool result = false; if (so != null) { try { PSPropertyInfo computerNameProperty = so.Properties[RemotingConstants.ComputerNameNoteProperty]; PSPropertyInfo showComputerNameProperty = so.Properties[RemotingConstants.ShowComputerNameNoteProperty]; // if computer name property exists then this must be a remote object. see // if it can be displayed. if ((computerNameProperty != null) && (showComputerNameProperty != null)) { LanguagePrimitives.TryConvertTo<bool>(showComputerNameProperty.Value, out result); } } catch (ArgumentException) { // ignore any exceptions thrown retrieving the *ComputerName properties // from the object } catch (ExtendedTypeSystemException) { // ignore any exceptions thrown retrieving the *ComputerName properties // from the object } } return result; } } internal abstract class FormattingError { internal object sourceObject; } internal sealed class PSPropertyExpressionError : FormattingError { internal PSPropertyExpressionResult result; } internal sealed class StringFormatError : FormattingError { internal string formatString; internal Exception exception; } internal delegate ScriptBlock CreateScriptBlockFromString(string scriptBlockString); /// <summary> /// Helper class to create PSPropertyExpression's from format.ps1xml data structures. /// </summary> internal sealed class PSPropertyExpressionFactory { /// <exception cref="ParseException"></exception> internal void VerifyScriptBlockText(string scriptText) { ScriptBlock.Create(scriptText); } /// <summary> /// Create an expression from an expression token. /// </summary> /// <param name="et">Expression token to use.</param> /// <returns>Constructed expression.</returns> /// <exception cref="ParseException"></exception> internal PSPropertyExpression CreateFromExpressionToken(ExpressionToken et) { return CreateFromExpressionToken(et, null); } /// <summary> /// Create an expression from an expression token. /// </summary> /// <param name="et">Expression token to use.</param> /// <param name="loadingInfo">The context from which the file was loaded.</param> /// <returns>Constructed expression.</returns> /// <exception cref="ParseException"></exception> internal PSPropertyExpression CreateFromExpressionToken(ExpressionToken et, DatabaseLoadingInfo loadingInfo) { if (et.isScriptBlock) { // we cache script blocks from expression tokens if (_expressionCache != null) { PSPropertyExpression value; if (_expressionCache.TryGetValue(et, out value)) { // got a hit on the cache, just return return value; } } else { _expressionCache = new Dictionary<ExpressionToken, PSPropertyExpression>(); } bool isFullyTrusted = false; bool isProductCode = false; if (loadingInfo != null) { isFullyTrusted = loadingInfo.isFullyTrusted; isProductCode = loadingInfo.isProductCode; } // no hit, we build one and we cache ScriptBlock sb = ScriptBlock.CreateDelayParsedScriptBlock(et.expressionValue, isProductCode: isProductCode); sb.DebuggerStepThrough = true; if (isFullyTrusted) { sb.LanguageMode = PSLanguageMode.FullLanguage; } PSPropertyExpression ex = new PSPropertyExpression(sb); _expressionCache.Add(et, ex); return ex; } // we do not cache if it is just a property name return new PSPropertyExpression(et.expressionValue); } private Dictionary<ExpressionToken, PSPropertyExpression> _expressionCache; } }
{ "content_hash": "48216cd72ca0c86702c3484cd196fe45", "timestamp": "", "source": "github", "line_count": 633, "max_line_length": 184, "avg_line_length": 41.78988941548183, "alnum_prop": 0.5332476467697426, "repo_name": "TravisEz13/PowerShell", "id": "7760e86b13d1245daad2dd5dba5f1c96329dcaf7", "size": "26529", "binary": false, "copies": "1", "ref": "refs/heads/travisez13-main", "path": "src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "24" }, { "name": "C#", "bytes": "30828572" }, { "name": "Dockerfile", "bytes": "6464" }, { "name": "HTML", "bytes": "18060" }, { "name": "JavaScript", "bytes": "8738" }, { "name": "PowerShell", "bytes": "4998299" }, { "name": "Rich Text Format", "bytes": "40664" }, { "name": "Roff", "bytes": "214981" }, { "name": "Shell", "bytes": "57904" }, { "name": "XSLT", "bytes": "14397" } ], "symlink_target": "" }
package gmapsfx.javascript; import netscape.javascript.JSObject; import java.util.HashMap; import java.util.Map; /** * JavascriptObject implementation of an array. * <p/> * Return values are supplied as their raw return value from Javascript, unless that value has previously been passed in * to the array as a JavascriptObject. The caller is then responsible for wrapping any new JSObjects in the appropriate * JavascriptObject, as they should know what is needed. * <p/> * * @author Geoff Capper */ public class JavascriptArray extends JavascriptObject { private final Map<JSObject, JavascriptObject> content = new HashMap<>(); public JavascriptArray() { runtime.execute("var " + variableName + " = []"); jsObject = runtime.execute(variableName); } public Object get(int idx) { Object obj = getJSObject().getSlot(idx); if (obj instanceof JSObject && content.containsKey((JSObject) obj)) { return (JavascriptObject) content.get((JSObject) obj); } return obj; } //concat() Joins two or more arrays, and returns a copy of the joined arrays //indexOf() Search the array for an element and returns its position public int indexOf(Object obj) { if (obj instanceof JavascriptObject) { return checkInteger(invokeJavascript("indexOf", ((JavascriptObject) obj).getJSObject()), -1); } return checkInteger(invokeJavascript("indexOf", obj), -1); } //join() Joins all elements of an array into a string //lastIndexOf() Search the array for an element, starting at the end, and returns its position public int lastIndexOf(Object obj) { if (obj instanceof JavascriptObject) { return checkInteger(invokeJavascript("lastIndexOf", ((JavascriptObject) obj).getJSObject()), -1); } return checkInteger(invokeJavascript("lastIndexOf", obj), -1); } //pop() Removes the last element of an array, and returns that element public Object pop() { //Object obj = jsObject.getSlot(jsLen - 1); Object obj = invokeJavascript("pop"); if (obj instanceof JSObject && content.containsKey((JSObject) obj)) { return (JavascriptObject) content.get((JSObject) obj); } return obj; } //push() Adds new elements to the end of an array, and returns the new length public int push(Object obj) { if (obj instanceof JavascriptObject) { //jsObject.setSlot(length(), ((JavascriptObject) obj).getJSObject()); content.put(((JavascriptObject) obj).getJSObject(), (JavascriptObject) obj); } return checkInteger(invokeJavascript("push", obj), 0); } //reverse() Reverses the order of the elements in an array public void reverse() { invokeJavascript("reverse"); } //shift() Removes the first element of an array, and returns that element public Object shift() { Object obj = invokeJavascript("shift"); if (obj instanceof JSObject && content.containsKey((JSObject) obj)) { return (JavascriptObject) content.get((JSObject) obj); } return obj; } //slice() Selects a part of an array, and returns the new array //sort() Sorts the elements of an array public void sort(String func) { if (func == null || func.isEmpty()) { Object ary = invokeJavascript("sort"); } else { Object ary = invokeJavascript("sort", func); } } //splice() Adds/Removes elements from an array //toString() Converts an array to a string, and returns the result @Override public String toString() { return invokeJavascriptReturnValue("toString", String.class); } //unshift() Adds new elements to the beginning of an array, and returns the new length public int unshift(Object obj) { if (obj instanceof JavascriptObject) { //jsObject.setSlot(length(), ((JavascriptObject) obj).getJSObject()); content.put(((JavascriptObject) obj).getJSObject(), (JavascriptObject) obj); } return checkInteger(invokeJavascript("unshift", obj), 0); } //valueOf() /** * Get the length of the array. This returns the value from the underlying Javascrpt object. * * @return */ public int length() { return checkInteger(getProperty("length"), 0); } }
{ "content_hash": "70ca690f9317a7a416d552ec4b2438db", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 120, "avg_line_length": 35.41269841269841, "alnum_prop": 0.6443298969072165, "repo_name": "devinmcgloin/UCSDGraphs", "id": "f972812614fe85c28597322a9ee048d3eb09bb0f", "size": "5054", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/gmapsfx/javascript/JavascriptArray.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "554" }, { "name": "HTML", "bytes": "601" }, { "name": "Java", "bytes": "304502" }, { "name": "JavaScript", "bytes": "839" } ], "symlink_target": "" }
package blended.akka.http import domino.DominoActivator abstract class WebBundleActivator extends DominoActivator { val contentDir : String val contextName : String whenBundleActive { val uiRoute = new UiRoute(contentDir, getClass().getClassLoader()) // In an OSGi container this will be picked by the Akka Http service using a whiteboard pattern SimpleHttpContext(contextName, uiRoute.route).providesService[HttpContext] } }
{ "content_hash": "61fa1aaf776dfa459bc3fa067e9c4af3", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 99, "avg_line_length": 26.58823529411765, "alnum_prop": 0.7765486725663717, "repo_name": "woq-blended/blended", "id": "20f74c5ce5e1617627580b48a9b1e3bc0adb2cc5", "size": "452", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "blended.akka.http/src/main/scala/blended/akka/http/WebBundleActivator.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5594" }, { "name": "Java", "bytes": "19287" }, { "name": "Scala", "bytes": "1583288" }, { "name": "Shell", "bytes": "13134" } ], "symlink_target": "" }
cd "$(dirname "${BASH_SOURCE}")" && source "../utils.sh" # Homebrew Formulae # https://github.com/Homebrew/homebrew declare -a HOMEBREW_FORMULAE=( "bash-completion" "caskroom/cask/brew-cask" "git" "imagemagick --with-webp" "vim --override-system-vi" "zopfli" ) # Homebrew Casks # https://github.com/caskroom/homebrew-cask declare -a HOMEBREW_CASKS=( "android-file-transfer" "dropbox" "firefox" "flash" "imageoptim" "libreoffice" "licecap" "lisanet-gimp" "spectacle" "the-unarchiver" "transmission" "virtualbox" "vlc" "android-platform-tools" "aria2" "eot-utils" "fdupes" "fontforge" "gpg" "jq" "lame" "openssl" "pidof" "pip" "python" "rar" "reattach-to-user-namespace" "ruby" "stat" "tmux" "unrar" "wget" "yarn" ) # Homebrew Alternate Casks # https://github.com/caskroom/homebrew-versions declare -a HOMEBREW_ALTERNATE_CASKS=( "firefox-nightly" "google-chrome-canary" "webkit-nightly" ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { local i="", tmp="" # XCode Command Line Tools if [ $(xcode-select -p &> /dev/null; printf $?) -ne 0 ]; then xcode-select --install &> /dev/null # Wait until the XCode Command Line Tools are installed while [ $(xcode-select -p &> /dev/null; printf $?) -ne 0 ]; do sleep 5 done fi print_success "XCode Command Line Tools\n" # Homebrew if ! cmd_exists "brew"; then printf "\n" | ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" # └─ simulate the ENTER keypress print_result $? "brew" fi if cmd_exists "brew"; then execute "brew update" "brew (update)" execute "brew upgrade" "brew (upgrade)" execute "brew cleanup" "brew (cleanup)" # Homebrew formulae for i in ${!HOMEBREW_FORMULAE[*]}; do tmp="${HOMEBREW_FORMULAE[$i]}" [ $(brew list "$tmp" &> /dev/null; printf $?) -eq 0 ] \ && print_success "$tmp" \ || execute "brew install $tmp" "$tmp" done printf "\n" # Homebrew casks if [ $(brew list brew-cask &> /dev/null; printf $?) -eq 0 ]; then for i in ${!HOMEBREW_CASKS[*]}; do tmp="${HOMEBREW_CASKS[$i]}" [ $(brew cask list "$tmp" &> /dev/null; printf $?) -eq 0 ] \ && print_success "$tmp" \ || execute "brew cask install $tmp" "$tmp" done printf "\n" # Homebrew alternate casks brew tap caskroom/versions &> /dev/null if [ $(brew tap | grep "caskroom/versions" &> /dev/null; printf $?) -eq 0 ]; then for i in ${!HOMEBREW_ALTERNATE_CASKS[*]}; do tmp="${HOMEBREW_ALTERNATE_CASKS[$i]}" [ $(brew cask list "$tmp" &> /dev/null; printf $?) -eq 0 ] \ && print_success "$tmp" \ || execute "brew cask install $tmp" "$tmp" done fi fi fi slack sublime } slack() { open_webpage 'https://www.google.com/?q=download+slack+mac' ask_for_confirmation "Is slack installed?" printf "\n" } sublime() { open_webpage 'https://www.google.com/?q=download+sublime text 3+mac' echo 'Sublime Text License' cat ~/Dropbox/Backup/sublime_text/sublime.txt printf "\n" ask_for_confirmation "Is sublime text installed?" printf "\n" } main
{ "content_hash": "473f987ec8090db33c1a1750cac6c564", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 111, "avg_line_length": 23.87012987012987, "alnum_prop": 0.5269314472252449, "repo_name": "stevenirby/dotfiles-1", "id": "6c438512f50e661b1cddf95063ef141bfb6c0df5", "size": "3693", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "os/os_x/install_applications.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Shell", "bytes": "83577" }, { "name": "Vim script", "bytes": "20942" } ], "symlink_target": "" }
#include "tensorflow/lite/kernels/internal/reference/maximum_minimum.h" #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/c_api_internal.h" #include "tensorflow/lite/kernels/internal/common.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/op_macros.h" namespace tflite { namespace ops { namespace micro { namespace maximum_minimum { namespace { // This file has a reference implementation of TFMaximum/TFMinimum. enum KernelType { kReference, }; constexpr int kInputTensor1 = 0; constexpr int kInputTensor2 = 1; constexpr int kOutputTensor = 0; struct OpContext { OpContext(TfLiteContext* context, TfLiteNode* node) { input1 = GetInput(context, node, kInputTensor1); input2 = GetInput(context, node, kInputTensor2); output = GetOutput(context, node, kOutputTensor); } const TfLiteTensor* input1; const TfLiteTensor* input2; TfLiteTensor* output; }; struct MaximumOp { template <typename data_type> static data_type op(data_type el1, data_type el2) { return el1 > el2 ? el1 : el2; } }; struct MinimumOp { template <typename data_type> static data_type op(data_type el1, data_type el2) { return el1 < el2 ? el1 : el2; } }; } // namespace template <typename data_type, typename op_type> void TFLiteOperation(TfLiteContext* context, TfLiteNode* node, const OpContext& op_context) { reference_ops::MaximumMinimumBroadcast4DSlow( GetTensorShape(op_context.input1), GetTensorData<data_type>(op_context.input1), GetTensorShape(op_context.input2), GetTensorData<data_type>(op_context.input2), GetTensorShape(op_context.output), GetTensorData<data_type>(op_context.output), op_type::template op<data_type>); } template <KernelType kernel_type, typename OpType> TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { OpContext op_context(context, node); if (kernel_type == kReference) { switch (op_context.output->type) { case kTfLiteFloat32: TFLiteOperation<float, OpType>(context, node, op_context); break; case kTfLiteUInt8: TFLiteOperation<uint8_t, OpType>(context, node, op_context); break; case kTfLiteInt8: TFLiteOperation<int8_t, OpType>(context, node, op_context); break; case kTfLiteInt32: TFLiteOperation<int32_t, OpType>(context, node, op_context); break; case kTfLiteInt64: TFLiteOperation<int64_t, OpType>(context, node, op_context); break; default: context->ReportError( context, "Type %s (%d) is not supported by Maximum/Minimum.", TfLiteTypeGetName(op_context.output->type), op_context.output->type); return kTfLiteError; } } else { context->ReportError(context, "Kernel type not supported by Maximum/Minimum."); return kTfLiteError; } return kTfLiteOk; } } // namespace maximum_minimum TfLiteRegistration* Register_MAXIMUM() { static TfLiteRegistration r = { /* init */ nullptr, /* free */ nullptr, /* prepare */ nullptr, maximum_minimum::Eval<maximum_minimum::kReference, maximum_minimum::MaximumOp>}; return &r; } TfLiteRegistration* Register_MINIMUM() { static TfLiteRegistration r = { /* init */ nullptr, /* free */ nullptr, /* prepare */ nullptr, maximum_minimum::Eval<maximum_minimum::kReference, maximum_minimum::MinimumOp>}; return &r; } } // namespace micro } // namespace ops } // namespace tflite
{ "content_hash": "32e050ab0e403925f01fdfbe4312f82a", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 74, "avg_line_length": 29.453125, "alnum_prop": 0.6726790450928382, "repo_name": "ppwwyyxx/tensorflow", "id": "dbf819849f76d643b0ef4b7b51cc3cb490215c35", "size": "4438", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tensorflow/lite/experimental/micro/kernels/maximum_minimum.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "5003" }, { "name": "Batchfile", "bytes": "45318" }, { "name": "C", "bytes": "796611" }, { "name": "C#", "bytes": "8562" }, { "name": "C++", "bytes": "76521274" }, { "name": "CMake", "bytes": "6545" }, { "name": "Dockerfile", "bytes": "81136" }, { "name": "Go", "bytes": "1679107" }, { "name": "HTML", "bytes": "4686483" }, { "name": "Java", "bytes": "952883" }, { "name": "Jupyter Notebook", "bytes": "567243" }, { "name": "LLVM", "bytes": "6536" }, { "name": "MLIR", "bytes": "1254789" }, { "name": "Makefile", "bytes": "61284" }, { "name": "Objective-C", "bytes": "104706" }, { "name": "Objective-C++", "bytes": "297774" }, { "name": "PHP", "bytes": "24055" }, { "name": "Pascal", "bytes": "3752" }, { "name": "Pawn", "bytes": "17546" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "38709528" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "7469" }, { "name": "Shell", "bytes": "643731" }, { "name": "Smarty", "bytes": "34743" }, { "name": "Swift", "bytes": "62814" } ], "symlink_target": "" }
package com.example.android.asynctaskloader; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import com.example.android.asynctaskloader.utilities.NetworkUtils; import java.io.IOException; import java.net.URL; public class MainActivity extends AppCompatActivity { // TODO (1) Create a static final key to store the query's URL public static final String URL = "url"; // TODO (2) Create a static final key to store the search's raw JSON public static final String RAW_JSON = "raw_json"; private EditText mSearchBoxEditText; private TextView mUrlDisplayTextView; private TextView mSearchResultsTextView; private TextView mErrorMessageDisplay; private ProgressBar mLoadingIndicator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSearchBoxEditText = (EditText) findViewById(R.id.et_search_box); mUrlDisplayTextView = (TextView) findViewById(R.id.tv_url_display); mSearchResultsTextView = (TextView) findViewById(R.id.tv_github_search_results_json); mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display); mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator); if(savedInstanceState != null){ if(savedInstanceState.containsKey(URL) && savedInstanceState.containsKey(RAW_JSON)){ mUrlDisplayTextView.setText(savedInstanceState.getString(URL)); mSearchResultsTextView.setText(savedInstanceState.getString(RAW_JSON)); } } // TODO (9) If the savedInstanceState bundle is not null, set the text of the URL and search results TextView respectively } /** * This method retrieves the search text from the EditText, constructs the * URL (using {@link NetworkUtils}) for the github repository you'd like to find, displays * that URL in a TextView, and finally fires off an AsyncTask to perform the GET request using * our {@link GithubQueryTask} */ private void makeGithubSearchQuery() { String githubQuery = mSearchBoxEditText.getText().toString(); URL githubSearchUrl = NetworkUtils.buildUrl(githubQuery); mUrlDisplayTextView.setText(githubSearchUrl.toString()); new GithubQueryTask().execute(githubSearchUrl); } /** * This method will make the View for the JSON data visible and * hide the error message. * <p> * Since it is okay to redundantly set the visibility of a View, we don't * need to check whether each view is currently visible or invisible. */ private void showJsonDataView() { /* First, make sure the error is invisible */ mErrorMessageDisplay.setVisibility(View.INVISIBLE); /* Then, make sure the JSON data is visible */ mSearchResultsTextView.setVisibility(View.VISIBLE); } /** * This method will make the error message visible and hide the JSON * View. * <p> * Since it is okay to redundantly set the visibility of a View, we don't * need to check whether each view is currently visible or invisible. */ private void showErrorMessage() { /* First, hide the currently visible data */ mSearchResultsTextView.setVisibility(View.INVISIBLE); /* Then, show the error */ mErrorMessageDisplay.setVisibility(View.VISIBLE); } public class GithubQueryTask extends AsyncTask<URL, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); mLoadingIndicator.setVisibility(View.VISIBLE); } @Override protected String doInBackground(URL... params) { URL searchUrl = params[0]; String githubSearchResults = null; try { githubSearchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl); } catch (IOException e) { e.printStackTrace(); } return githubSearchResults; } @Override protected void onPostExecute(String githubSearchResults) { mLoadingIndicator.setVisibility(View.INVISIBLE); if (githubSearchResults != null && !githubSearchResults.equals("")) { showJsonDataView(); mSearchResultsTextView.setText(githubSearchResults); } else { showErrorMessage(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemThatWasClickedId = item.getItemId(); if (itemThatWasClickedId == R.id.action_search) { makeGithubSearchQuery(); return true; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(URL, mUrlDisplayTextView.getText().toString()); outState.putString(RAW_JSON, mSearchResultsTextView.getText().toString()); } // TODO (3) Override onSaveInstanceState to persist data across Activity recreation // Do the following steps within onSaveInstanceState // TODO (4) Make sure super.onSaveInstanceState is called before doing anything else // TODO (5) Put the contents of the TextView that contains our URL into a variable // TODO (6) Using the key for the query URL, put the string in the outState Bundle // TODO (7) Put the contents of the TextView that contains our raw JSON search results into a variable // TODO (8) Using the key for the raw JSON search results, put the search results into the outState Bundle }
{ "content_hash": "263641bb7205a80749b87a232d8b7495", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 130, "avg_line_length": 37.25454545454546, "alnum_prop": 0.6801691882218969, "repo_name": "f1dz/ud851-Exercises", "id": "1c9cff8ef918dd8a2b5789b2bec20d844f4b205d", "size": "6766", "binary": false, "copies": "1", "ref": "refs/heads/student", "path": "Lesson05b-Smarter-GitHub-Repo-Search/T05b.01-Exercise-SaveResults/app/src/main/java/com/example/android/asynctaskloader/MainActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2423319" }, { "name": "Python", "bytes": "4312" } ], "symlink_target": "" }
package com.arhs.cube.thats.my.spot.web.rest.errors; public final class ErrorConstants { public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure"; public static final String ERR_ACCESS_DENIED = "error.accessDenied"; public static final String ERR_VALIDATION = "error.validation"; public static final String ERR_METHOD_NOT_SUPPORTED = "error.methodNotSupported"; private ErrorConstants() { } }
{ "content_hash": "6bd16246bf8affe6a2468c809424abfc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 85, "avg_line_length": 34.15384615384615, "alnum_prop": 0.75, "repo_name": "arhs-cube-gameofcode/gameofcode", "id": "86ddc78fc8aedda714453b6692968037199b39bc", "size": "444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/arhs/cube/thats/my/spot/web/rest/errors/ErrorConstants.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "6244" }, { "name": "HTML", "bytes": "114701" }, { "name": "Java", "bytes": "228772" }, { "name": "JavaScript", "bytes": "185442" }, { "name": "Scala", "bytes": "3240" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
package desiredstatefetcher_test import ( "encoding/json" "fmt" . "github.com/cloudfoundry/hm9000/desiredstatefetcher" "github.com/cloudfoundry/hm9000/testhelpers/appfixture" . "github.com/cloudfoundry/hm9000/testhelpers/custommatchers" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Desired State Server Response JSON", func() { var ( a appfixture.AppFixture response DesiredStateServerResponse ) BeforeEach(func() { a = appfixture.NewAppFixture() desired, _ := json.Marshal(a.DesiredState(1)) responseJson := fmt.Sprintf(` { "results":{"%s":%s}, "bulk_token":{"id":17} } `, a.AppGuid, string(desired)) var err error response, err = NewDesiredStateServerResponse([]byte(responseJson)) Ω(err).ShouldNot(HaveOccurred()) }) It("can parse from JSON", func() { Ω(response.Results).Should(HaveLen(1)) Ω(response.Results[a.AppGuid]).Should(EqualDesiredState(a.DesiredState(1))) Ω(response.BulkToken.Id).Should(Equal(17)) }) It("can return the bulk_token representation", func() { Ω(response.BulkTokenRepresentation()).Should(Equal(`{"id":17}`)) }) Context("when the JSON can't be parsed", func() { It("should return an error", func() { _, err := NewDesiredStateServerResponse([]byte("{")) Ω(err).Should(HaveOccurred()) }) }) Describe("ToJson", func() { It("should return json that survives the round trip", func() { resurrectedResponse, err := NewDesiredStateServerResponse(response.ToJSON()) Ω(err).ShouldNot(HaveOccurred()) Ω(resurrectedResponse).Should(Equal(response)) }) }) })
{ "content_hash": "1efbdcee0b72b6812c65acbe74460580", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 79, "avg_line_length": 28.137931034482758, "alnum_prop": 0.6795343137254902, "repo_name": "cloudfoundry/hm9000", "id": "d58912fcdeaa8be613d7fd3080172c7389c1bb57", "size": "1640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "desiredstatefetcher/desired_state_server_response_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "534250" } ], "symlink_target": "" }
package net.sf.katta.node; import net.sf.katta.node.Node.NodeOperationProcessor; import net.sf.katta.operation.node.NodeOperation; import net.sf.katta.protocol.NodeQueue; import net.sf.katta.testutil.mockito.SleepingAnswer; import org.I0Itec.zkclient.exception.ZkInterruptedException; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class NodeOperationProcessorTest { private NodeQueue _queue = mock(NodeQueue.class); private NodeContext _context = mock(NodeContext.class); private Node _node = mock(Node.class); private NodeOperationProcessor _processor; public NodeOperationProcessorTest() throws InterruptedException { when(_context.getNode()).thenReturn(_node); when(_node.isRunning()).thenReturn(true); when(_node.getName()).thenReturn("aNode"); _processor = new NodeOperationProcessor(_queue, _context); // when(queue.peek()).thenAnswer(new SleepingAnswer()); } @Test(timeout = 10000) public void testInterruptedException_Queue() throws Exception { when(_queue.peek()).thenThrow(new InterruptedException()); _processor.run(); } @Test(timeout = 10000) public void testInterruptedException_Queue_Zk() throws Exception { when(_queue.peek()).thenThrow(new ZkInterruptedException(new InterruptedException())); _processor.run(); } @Test(timeout = 10000) public void testInterruptedException_Operation() throws Exception { NodeOperation nodeOperation = mock(NodeOperation.class); when(_queue.peek()).thenReturn(nodeOperation); when(nodeOperation.execute(_context)).thenThrow(new InterruptedException()); _processor.run(); } @Test(timeout = 10000) public void testInterruptedException_Operation_ZK() throws Exception { NodeOperation nodeOperation = mock(NodeOperation.class); when(_queue.peek()).thenReturn(nodeOperation); when(nodeOperation.execute(_context)).thenThrow(new ZkInterruptedException(new InterruptedException())); _processor.run(); } @Test(timeout = 10000) public void testDontStopOnOOM() throws Exception { when(_queue.peek()).thenThrow(new OutOfMemoryError("test exception")).thenAnswer(new SleepingAnswer()); Thread thread = new Thread() { public void run() { _processor.run(); }; }; thread.start(); Thread.sleep(500); assertEquals(true, thread.isAlive()); thread.interrupt(); verify(_queue, atLeast(2)).peek(); } }
{ "content_hash": "361375609f50280a8d12544b8f76bbe8", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 108, "avg_line_length": 34.18421052631579, "alnum_prop": 0.7347959969207082, "repo_name": "sgroschupf/katta", "id": "3bc67fbb09eaefddae7ac8d49fa5534f7af354ba", "size": "3209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/katta-core/src/test/java/net/sf/katta/node/NodeOperationProcessorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1160623" }, { "name": "Shell", "bytes": "47859" }, { "name": "XML", "bytes": "5384" } ], "symlink_target": "" }
package org.apache.beam.runners.direct; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.runners.TransformTreeNode; import org.apache.beam.sdk.transforms.display.DisplayData; import org.apache.beam.sdk.transforms.display.HasDisplayData; /** * Validate correct implementation of {@link DisplayData} by evaluating * {@link HasDisplayData#populateDisplayData(DisplayData.Builder)} during pipeline construction. */ class DisplayDataValidator { // Do not instantiate private DisplayDataValidator() {} static void validatePipeline(Pipeline pipeline) { validateOptions(pipeline); validateTransforms(pipeline); } private static void validateOptions(Pipeline pipeline) { evaluateDisplayData(pipeline.getOptions()); } private static void validateTransforms(Pipeline pipeline) { pipeline.traverseTopologically(Visitor.INSTANCE); } private static void evaluateDisplayData(HasDisplayData component) { DisplayData.from(component); } private static class Visitor extends Pipeline.PipelineVisitor.Defaults { private static final Visitor INSTANCE = new Visitor(); @Override public CompositeBehavior enterCompositeTransform(TransformTreeNode node) { if (!node.isRootNode()) { evaluateDisplayData(node.getTransform()); } return CompositeBehavior.ENTER_TRANSFORM; } @Override public void visitPrimitiveTransform(TransformTreeNode node) { evaluateDisplayData(node.getTransform()); } } }
{ "content_hash": "8def5cf93bf31d0d350d96e71102c1df", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 96, "avg_line_length": 29.392156862745097, "alnum_prop": 0.7598398932621748, "repo_name": "tweise/incubator-beam", "id": "e09fe626f780ea7c2c29219720fc7ff3a937a4ca", "size": "2304", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "runners/direct-java/src/main/java/org/apache/beam/runners/direct/DisplayDataValidator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7764249" }, { "name": "Protocol Buffer", "bytes": "1407" }, { "name": "Shell", "bytes": "4126" } ], "symlink_target": "" }
@interface PodsDummy_Dollar_iOS : NSObject @end @implementation PodsDummy_Dollar_iOS @end
{ "content_hash": "b5e2556101f33996382f276c725816b5", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 42, "avg_line_length": 22.5, "alnum_prop": 0.8111111111111111, "repo_name": "yariksmirnov/aerial", "id": "ec646dc5436e356940f24051d8139090019854cd", "size": "124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pods/Target Support Files/Dollar-iOS/Dollar-iOS-dummy.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "13483" }, { "name": "Ruby", "bytes": "1288" }, { "name": "Swift", "bytes": "68268" } ], "symlink_target": "" }
#include "src/core/CL/kernels/CLDepthToSpaceLayerKernel.h" #include "arm_compute/core/CL/CLHelpers.h" #include "arm_compute/core/CL/ICLTensor.h" #include "arm_compute/core/utils/misc/ShapeCalculator.h" #include "src/core/CL/CLValidate.h" #include "src/core/helpers/AutoConfiguration.h" #include "src/core/helpers/WindowHelpers.h" #include "support/StringSupport.h" using namespace arm_compute::misc::shape_calculator; namespace arm_compute { namespace { Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, int32_t block_shape) { ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input, output); ARM_COMPUTE_RETURN_ERROR_ON(input->data_type() == DataType::UNKNOWN); ARM_COMPUTE_RETURN_ERROR_ON(input->num_dimensions() > 4); ARM_COMPUTE_RETURN_ERROR_ON(block_shape < 2); const DataLayout data_layout = input->data_layout(); const int idx_channel = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL); ARM_COMPUTE_RETURN_ERROR_ON(input->tensor_shape()[idx_channel] % (block_shape * block_shape) != 0); // Validate output if initialized if(output->total_size() != 0) { const int idx_width = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH); const int idx_height = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT); ARM_COMPUTE_RETURN_ERROR_ON(output->tensor_shape()[idx_width] != (block_shape * input->tensor_shape()[idx_width])); ARM_COMPUTE_RETURN_ERROR_ON(output->tensor_shape()[idx_height] != (block_shape * input->tensor_shape()[idx_height])); ARM_COMPUTE_RETURN_ERROR_ON(output->num_dimensions() > 4); ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output); } return Status{}; } } // namespace CLDepthToSpaceLayerKernel::CLDepthToSpaceLayerKernel() : _input(nullptr), _output(nullptr), _block_shape() { _type = CLKernelType::ELEMENTWISE; } void CLDepthToSpaceLayerKernel::configure(const ICLTensor *input, ICLTensor *output, int32_t block_shape) { configure(CLKernelLibrary::get().get_compile_context(), input, output, block_shape); } void CLDepthToSpaceLayerKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, ICLTensor *output, int32_t block_shape) { ARM_COMPUTE_ERROR_ON_NULLPTR(input, output); TensorShape output_shape = compute_depth_to_space_shape(input->info()->tensor_shape(), input->info()->data_layout(), block_shape); auto_init_if_empty(*output->info(), output_shape, 1, input->info()->data_type()); auto padding_info = get_padding_info({ input, output }); ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), block_shape)); _input = input; _output = output; _block_shape = block_shape; const int idx_width = get_data_layout_dimension_index(input->info()->data_layout(), DataLayoutDimension::WIDTH); const int idx_channel = get_data_layout_dimension_index(input->info()->data_layout(), DataLayoutDimension::CHANNEL); // Create kernel CLBuildOptions build_opts; build_opts.add_option("-DDATA_TYPE=" + get_cl_unsigned_type_from_element_size(input->info()->element_size())); build_opts.add_option("-DCHANNEL_SIZE=" + support::cpp11::to_string(input->info()->dimension(idx_channel))); build_opts.add_option("-DBLOCK_SHAPE=" + support::cpp11::to_string(block_shape)); build_opts.add_option("-DWIDTH_IN=" + support::cpp11::to_string(input->info()->dimension(idx_width))); _kernel = create_kernel(compile_context, "depth_to_space_" + lower_string(string_from_data_layout(input->info()->data_layout())), build_opts.options()); // Configure kernel window Window win = calculate_max_window(*input->info(), Steps()); ICLKernel::configure_internal(win); ARM_COMPUTE_ERROR_ON(has_padding_changed(padding_info)); } Status CLDepthToSpaceLayerKernel::validate(const ITensorInfo *input, const ITensorInfo *output, int32_t block_shape) { ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input, output); ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, block_shape)); return Status{}; } void CLDepthToSpaceLayerKernel::run(const Window &window, cl::CommandQueue &queue) { ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(ICLKernel::window(), window); Window slice_in = window.first_slice_window_3D(); Window slice_out = window.first_slice_window_4D(); slice_out.set(Window::DimX, Window::Dimension(0, 0, 0)); slice_out.set(Window::DimY, Window::Dimension(0, 0, 0)); slice_out.set(Window::DimZ, Window::Dimension(0, 0, 0)); slice_out.set(3, Window::Dimension(0, 0, 0)); int batch_id = 0; do { unsigned int idx = 0; add_3D_tensor_argument(idx, _input, slice_in); add_argument(idx, batch_id); add_4D_tensor_argument(idx, _output, slice_out); enqueue(queue, *this, slice_in, lws_hint()); ++batch_id; } while(window.slide_window_slice_3D(slice_in)); } } // namespace arm_compute
{ "content_hash": "3411a07720bf41bdf978f32626eeec6c", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 156, "avg_line_length": 42.541666666666664, "alnum_prop": 0.6973555337904016, "repo_name": "ARM-software/ComputeLibrary", "id": "efc6f820f2369dbaf7b9f899503c1d294436f9c1", "size": "6261", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/core/CL/kernels/CLDepthToSpaceLayerKernel.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3062248" }, { "name": "C++", "bytes": "34872664" }, { "name": "Go", "bytes": "4183" }, { "name": "Python", "bytes": "122193" }, { "name": "Shell", "bytes": "3515" } ], "symlink_target": "" }
<?php /* * You can remove this if you are confident that your PHP version is sufficient. */ if (version_compare(PHP_VERSION, '5.5.9') < 0) { trigger_error('Your PHP version must be equal or higher than 5.5.9 to use CakePHP.', E_USER_ERROR); } /* * You can remove this if you are confident you have intl installed. */ if (!extension_loaded('intl')) { trigger_error('You must enable the intl extension to use CakePHP.', E_USER_ERROR); } /* * You can remove this if you are confident you have mbstring installed. */ if (!extension_loaded('mbstring')) { trigger_error('You must enable the mbstring extension to use CakePHP.', E_USER_ERROR); } /* * Configure paths required to find CakePHP + general filepath * constants */ require __DIR__ . '/paths.php'; /* * Bootstrap CakePHP. * * Does the various bits of setup that CakePHP needs to do. * This includes: * * - Registering the CakePHP autoloader. * - Setting the default application paths. */ require CORE_PATH . 'config' . DS . 'bootstrap.php'; use Cake\Cache\Cache; use Cake\Console\ConsoleErrorHandler; use Cake\Core\App; use Cake\Core\Configure; use Cake\Core\Configure\Engine\PhpConfig; use Cake\Core\Plugin; use Cake\Database\Type; use Cake\Datasource\ConnectionManager; use Cake\Error\ErrorHandler; use Cake\Log\Log; use Cake\Mailer\Email; use Cake\Network\Request; use Cake\Utility\Inflector; use Cake\Utility\Security; // Habilita o parseamento de datas localizadas date_default_timezone_set('America/Fortaleza'); \Cake\I18n\Time::setToStringFormat([IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT]); Inflector::rules('irregular', [ 'solicitacao' => 'solicitacoes' ]); /** * Locale Formats */ \Cake\I18n\Time::setToStringFormat([IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT]); \Cake\I18n\Time::setToStringFormat('dd/MM/YYYY HH:mm'); \Cake\Database\Type::build('date') ->useLocaleParser() ->setLocaleFormat('dd/MM/yyyy'); \Cake\Database\Type::build('datetime') ->useLocaleParser() ->setLocaleFormat('dd/MM/yyyy HH:mm'); \Cake\Database\Type::build('timestamp') ->useLocaleParser() ->setLocaleFormat('dd/MM/yyyy HH:mm'); \Cake\Database\Type::build('decimal') ->useLocaleParser(); \Cake\Database\Type::build('float') ->useLocaleParser(); /* * Read configuration file and inject configuration into various * CakePHP classes. * * By default there is only one configuration file. It is often a good * idea to create multiple configuration files, and separate the configuration * that changes from configuration that does not. This makes deployment simpler. */ try { Configure::config('default', new PhpConfig()); Configure::load('app', 'default', false); } catch (\Exception $e) { exit($e->getMessage() . "\n"); } /* * Load an environment local configuration file. * You can use a file like app_local.php to provide local overrides to your * shared configuration. */ //Configure::load('app_local', 'default'); /* * When debug = false the metadata cache should last * for a very very long time, as we don't want * to refresh the cache while users are doing requests. */ if (!Configure::read('debug')) { Configure::write('Cache._cake_model_.duration', '+1 years'); Configure::write('Cache._cake_core_.duration', '+1 years'); } /* * Set server timezone to UTC. You can change it to another timezone of your * choice but using UTC makes time calculations / conversions easier. */ date_default_timezone_set('UTC'); /* * Configure the mbstring extension to use the correct encoding. */ mb_internal_encoding(Configure::read('App.encoding')); /* * Set the default locale. This controls how dates, number and currency is * formatted and sets the default language to use for translations. */ //ini_set('intl.default_locale', Configure::read('App.defaultLocale')); ini_set('intl.default_locale', 'pt_BR'); /* * Register application error and exception handlers. */ $isCli = PHP_SAPI === 'cli'; if ($isCli) { (new ConsoleErrorHandler(Configure::read('Error')))->register(); } else { (new ErrorHandler(Configure::read('Error')))->register(); } /* * Include the CLI bootstrap overrides. */ if ($isCli) { require __DIR__ . '/bootstrap_cli.php'; } /* * Set the full base URL. * This URL is used as the base of all absolute links. * * If you define fullBaseUrl in your config file you can remove this. */ if (!Configure::read('App.fullBaseUrl')) { $s = null; if (env('HTTPS')) { $s = 's'; } $httpHost = env('HTTP_HOST'); if (isset($httpHost)) { Configure::write('App.fullBaseUrl', 'http' . $s . '://' . $httpHost); } unset($httpHost, $s); } Cache::config(Configure::consume('Cache')); ConnectionManager::config(Configure::consume('Datasources')); Email::configTransport(Configure::consume('EmailTransport')); Email::config(Configure::consume('Email')); Log::config(Configure::consume('Log')); Security::salt(Configure::consume('Security.salt')); /* * The default crypto extension in 3.0 is OpenSSL. * If you are migrating from 2.x uncomment this code to * use a more compatible Mcrypt based implementation */ //Security::engine(new \Cake\Utility\Crypto\Mcrypt()); /* * Setup detectors for mobile and tablet. */ Request::addDetector('mobile', function ($request) { $detector = new \Detection\MobileDetect(); return $detector->isMobile(); }); Request::addDetector('tablet', function ($request) { $detector = new \Detection\MobileDetect(); return $detector->isTablet(); }); /* * Enable immutable time objects in the ORM. * * You can enable default locale format parsing by adding calls * to `useLocaleParser()`. This enables the automatic conversion of * locale specific date formats. For details see * @link http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#parsing-localized-datetime-data */ Type::build('time') ->useImmutable(); Type::build('date') ->useImmutable(); Type::build('datetime') ->useImmutable(); /** * Default formats */ \Cake\I18n\Time::setToStringFormat('dd/MM/yyyy HH:mm:ss'); \Cake\I18n\Date::setToStringFormat('dd/MM/yyyy'); \Cake\I18n\FrozenTime::setToStringFormat('dd/MM/yyyy HH:mm:ss'); \Cake\I18n\FrozenDate::setToStringFormat('dd/MM/yyyy'); /* * Custom Inflector rules, can be set to correctly pluralize or singularize * table, model, controller names or whatever other string is passed to the * inflection functions. */ //Inflector::rules('plural', ['/^(inflect)or$/i' => '\1ables']); //Inflector::rules('irregular', ['red' => 'redlings']); //Inflector::rules('uninflected', ['dontinflectme']); //Inflector::rules('transliteration', ['/å/' => 'aa']); /* * Plugins need to be loaded manually, you can either load them one by one or all of them in a single call * Uncomment one of the lines below, as you need. make sure you read the documentation on Plugin to use more * advanced ways of loading plugins * * Plugin::loadAll(); // Loads all plugins at once * Plugin::load('Migrations'); //Loads a single plugin named Migrations * */ /* * Only try to load DebugKit in development mode * Debug Kit should not be installed on a production system */ if (Configure::read('debug')) { Plugin::load('DebugKit', ['bootstrap' => true]); } Plugin::load('Migrations'); Plugin::load('CakeControl', ['bootstrap' => true]); Plugin::load('Cake/Localized');
{ "content_hash": "0cc3b263e1364010b21910df52b1657f", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 129, "avg_line_length": 28.671814671814673, "alnum_prop": 0.6951252356584972, "repo_name": "ribafs/cake-control", "id": "2c7a2d09ddb4ed10542447ec06d89679a91452e4", "size": "8012", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/bootstrap.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "240246" }, { "name": "PHP", "bytes": "59115" } ], "symlink_target": "" }
package org.assertj.core.api.url; import static org.mockito.Mockito.verify; import org.assertj.core.api.UrlAssert; import org.assertj.core.api.UrlAssertBaseTest; /** * Test for <code>{@link org.assertj.core.api.UrlAssert#hasProtocol(String)}</code>. */ class UrlAssert_hasProtocol_Test extends UrlAssertBaseTest { private String expected = "http"; @Override protected UrlAssert invoke_api_method() { return assertions.hasProtocol(expected); } @Override protected void verify_internal_effects() { verify(urls).assertHasProtocol(getInfo(assertions), getActual(assertions), expected); } }
{ "content_hash": "c811b3347508cbd226cdd7f2dbcccb8c", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 89, "avg_line_length": 25.666666666666668, "alnum_prop": 0.7516233766233766, "repo_name": "hazendaz/assertj-core", "id": "1ca280c1c0164572e58ddae3a28d794f658452dd", "size": "1222", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/org/assertj/core/api/url/UrlAssert_hasProtocol_Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "17521277" }, { "name": "Shell", "bytes": "39247" } ], "symlink_target": "" }
CPqD ASR Recognizer =================== O Recognizer é uma API para criação de aplicações de voz que utilizam o servidor CPqD Reconhecimento de Fala (CPqD ASR). Para maiores informações sobre o CPqD ASR, consulte o [site do produto](http://speechweb.cpqd.com.br/asr/docs/latest/). Para entender como usar esta biblioteca, sugerimos verificar e executar os exemplos, em particular [basic.cc](https://github.com/CPqD/asr-sdk-cpp/blob/master/examples/basic.cc). Os códigos de exemplo estão sob o diretório `examples` do repositório ### Dependências * cmake >= 2.8.12 * Biblioteca de desenvolvimento ALSA * Debian/Ubuntu e derivados: `apt-get install libasound2-dev` * RedHat/CentOS/Fedora e derivados: `yum install alsa-lib-devel` ### Compilando a partir do código-fonte Baixe a última versão do repositório `git pull origin master` e execute: mkdir build cd build cmake .. -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=1 -DBUILD_EXAMPLES=1 make Para mais opções de compilação, recomendamos o uso da ferramenta `cmake-gui` ### Executando um teste Depois de compilar, a partir do diretório `build/examples` criado, execute um teste usando o exemplo `basic.cc`: export LD_LIBRARY_PATH=$PWD/src ./basic ws://127.0.0.1:8025/asr-server/asr builtin:grammar/samples/phone ../../examples/audio/phone-1937050211-8k.wav **Você deve mudar o IP do servidor ASR de 127.0.0.1 para o IP correto do servidor ASR na sua instalação.** Supomos que esteja usando modelos para áudio de 8kHz, caso contrário, deve testar com o arquivo de áudio de 16kHz: export LD_LIBRARY_PATH=$PWD/src ./basic ws://127.0.0.1:8025/asr-server/asr builtin:grammar/samples/phone ../../examples/audio/phone-1937050211-16k.wav ### Usando a biblioteca em aplicações A biblioteca cliente pode ser usada em sua aplicação através do arquivo `libasr-client.so` criado em `build/src` e dos arquivos de *header* presentes em `include/cpqd/asr-client`. Licença ------- Copyright (c) 2017 CPqD. Todos os direitos reservados. Publicado sob a licença Apache Software 2.0, veja LICENSE.
{ "content_hash": "9b2f5ed809a386df23422943a6a6ee38", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 177, "avg_line_length": 36.63157894736842, "alnum_prop": 0.7447318007662835, "repo_name": "CPqD/asr-sdk-cpp", "id": "c5db47695a0d9d23570231cbf13daad51db39085", "size": "2122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "152677" }, { "name": "CMake", "bytes": "25402" } ], "symlink_target": "" }
try { Object.defineProperty(null, null, null); assertTrue(false); } catch (e) { assertTrue(/called on non-object/.test(e)); } // Check that an exception is thrown when undefined is passed as object. try { Object.defineProperty(undefined, undefined, undefined); assertTrue(false); } catch (e) { assertTrue(/called on non-object/.test(e)); } // Check that an exception is thrown when non-object is passed as object. try { Object.defineProperty(0, "foo", undefined); assertTrue(false); } catch (e) { assertTrue(/called on non-object/.test(e)); } // Object. var obj1 = {}; // Values. var val1 = 0; var val2 = 0; var val3 = 0; function setter1() {val1++; } function getter1() {return val1; } function setter2() {val2++; } function getter2() {return val2; } function setter3() {val3++; } function getter3() {return val3; } // Descriptors. var emptyDesc = {}; var accessorConfigurable = { set: setter1, get: getter1, configurable: true }; var accessorNoConfigurable = { set: setter2, get: getter2, configurable: false }; var accessorOnlySet = { set: setter3, configurable: true }; var accessorOnlyGet = { get: getter3, configurable: true }; var accessorDefault = {set: function(){} }; var dataConfigurable = { value: 1000, configurable: true }; var dataNoConfigurable = { value: 2000, configurable: false }; var dataWritable = { value: 3000, writable: true}; // Check that we can't add property with undefined attributes. try { Object.defineProperty(obj1, "foo", undefined); assertTrue(false); } catch (e) { assertTrue(/must be an object/.test(e)); } // Make sure that we can add a property with an empty descriptor and // that it has the default descriptor values. Object.defineProperty(obj1, "foo", emptyDesc); // foo should be undefined as it has no get, set or value assertEquals(undefined, obj1.foo); // We should, however, be able to retrieve the propertydescriptor which should // have all default values (according to 8.6.1). var desc = Object.getOwnPropertyDescriptor(obj1, "foo"); assertFalse(desc.configurable); assertFalse(desc.enumerable); assertFalse(desc.writable); assertEquals(desc.get, undefined); assertEquals(desc.set, undefined); assertEquals(desc.value, undefined); // Make sure that getOwnPropertyDescriptor does not return a descriptor // with default values if called with non existing property (otherwise // the test above is invalid). desc = Object.getOwnPropertyDescriptor(obj1, "bar"); assertEquals(desc, undefined); // Make sure that foo can't be reset (as configurable is false). try { Object.defineProperty(obj1, "foo", accessorConfigurable); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // Accessor properties Object.defineProperty(obj1, "bar", accessorConfigurable); desc = Object.getOwnPropertyDescriptor(obj1, "bar"); assertTrue(desc.configurable); assertFalse(desc.enumerable); assertEquals(desc.writable, undefined); assertEquals(desc.get, accessorConfigurable.get); assertEquals(desc.set, accessorConfigurable.set); assertEquals(desc.value, undefined); assertEquals(1, obj1.bar = 1); assertEquals(1, val1); assertEquals(1, obj1.bar = 1); assertEquals(2, val1); assertEquals(2, obj1.bar); // Redefine bar with non configurable test Object.defineProperty(obj1, "bar", accessorNoConfigurable); desc = Object.getOwnPropertyDescriptor(obj1, "bar"); assertFalse(desc.configurable); assertFalse(desc.enumerable); assertEquals(desc.writable, undefined); assertEquals(desc.get, accessorNoConfigurable.get); assertEquals(desc.set, accessorNoConfigurable.set); assertEquals(desc.value, undefined); assertEquals(1, obj1.bar = 1); assertEquals(2, val1); assertEquals(1, val2); assertEquals(1, obj1.bar = 1) assertEquals(2, val1); assertEquals(2, val2); assertEquals(2, obj1.bar); // Try to redefine bar again - should fail as configurable is false. try { Object.defineProperty(obj1, "bar", accessorConfigurable); assertTrue(false); } catch(e) { assertTrue(/Cannot redefine property/.test(e)); } // Try to redefine bar again using the data descriptor - should fail. try { Object.defineProperty(obj1, "bar", dataConfigurable); assertTrue(false); } catch(e) { assertTrue(/Cannot redefine property/.test(e)); } // Redefine using same descriptor - should succeed. Object.defineProperty(obj1, "bar", accessorNoConfigurable); desc = Object.getOwnPropertyDescriptor(obj1, "bar"); assertFalse(desc.configurable); assertFalse(desc.enumerable); assertEquals(desc.writable, undefined); assertEquals(desc.get, accessorNoConfigurable.get); assertEquals(desc.set, accessorNoConfigurable.set); assertEquals(desc.value, undefined); assertEquals(1, obj1.bar = 1); assertEquals(2, val1); assertEquals(3, val2); assertEquals(1, obj1.bar = 1) assertEquals(2, val1); assertEquals(4, val2); assertEquals(4, obj1.bar); // Define an accessor that has only a setter. Object.defineProperty(obj1, "setOnly", accessorOnlySet); desc = Object.getOwnPropertyDescriptor(obj1, "setOnly"); assertTrue(desc.configurable); assertFalse(desc.enumerable); assertEquals(desc.set, accessorOnlySet.set); assertEquals(desc.writable, undefined); assertEquals(desc.value, undefined); assertEquals(desc.get, undefined); assertEquals(1, obj1.setOnly = 1); assertEquals(1, val3); // Add a getter - should not touch the setter. Object.defineProperty(obj1, "setOnly", accessorOnlyGet); desc = Object.getOwnPropertyDescriptor(obj1, "setOnly"); assertTrue(desc.configurable); assertFalse(desc.enumerable); assertEquals(desc.get, accessorOnlyGet.get); assertEquals(desc.set, accessorOnlySet.set); assertEquals(desc.writable, undefined); assertEquals(desc.value, undefined); assertEquals(1, obj1.setOnly = 1); assertEquals(2, val3); // The above should also work if redefining just a getter or setter on // an existing property with both a getter and a setter. Object.defineProperty(obj1, "both", accessorConfigurable); Object.defineProperty(obj1, "both", accessorOnlySet); desc = Object.getOwnPropertyDescriptor(obj1, "both"); assertTrue(desc.configurable); assertFalse(desc.enumerable); assertEquals(desc.set, accessorOnlySet.set); assertEquals(desc.get, accessorConfigurable.get); assertEquals(desc.writable, undefined); assertEquals(desc.value, undefined); assertEquals(1, obj1.both = 1); assertEquals(3, val3); // Data properties Object.defineProperty(obj1, "foobar", dataConfigurable); desc = Object.getOwnPropertyDescriptor(obj1, "foobar"); assertEquals(obj1.foobar, 1000); assertEquals(desc.value, 1000); assertTrue(desc.configurable); assertFalse(desc.writable); assertFalse(desc.enumerable); assertEquals(desc.get, undefined); assertEquals(desc.set, undefined); //Try writing to non writable attribute - should remain 1000 obj1.foobar = 1001; assertEquals(obj1.foobar, 1000); // Redefine to writable descriptor - now writing to foobar should be allowed. Object.defineProperty(obj1, "foobar", dataWritable); desc = Object.getOwnPropertyDescriptor(obj1, "foobar"); assertEquals(obj1.foobar, 3000); assertEquals(desc.value, 3000); // Note that since dataWritable does not define configurable the configurable // setting from the redefined property (in this case true) is used. assertTrue(desc.configurable); assertTrue(desc.writable); assertFalse(desc.enumerable); assertEquals(desc.get, undefined); assertEquals(desc.set, undefined); // Writing to the property should now be allowed obj1.foobar = 1001; assertEquals(obj1.foobar, 1001); // Redefine with non configurable data property. Object.defineProperty(obj1, "foobar", dataNoConfigurable); desc = Object.getOwnPropertyDescriptor(obj1, "foobar"); assertEquals(obj1.foobar, 2000); assertEquals(desc.value, 2000); assertFalse(desc.configurable); assertTrue(desc.writable); assertFalse(desc.enumerable); assertEquals(desc.get, undefined); assertEquals(desc.set, undefined); // Try redefine again - shold fail because configurable is now false. try { Object.defineProperty(obj1, "foobar", dataConfigurable); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // Try redefine again with accessor property - shold also fail. try { Object.defineProperty(obj1, "foobar", dataConfigurable); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // Redifine with the same descriptor - should succeed (step 6). Object.defineProperty(obj1, "foobar", dataNoConfigurable); desc = Object.getOwnPropertyDescriptor(obj1, "foobar"); assertEquals(obj1.foobar, 2000); assertEquals(desc.value, 2000); assertFalse(desc.configurable); assertTrue(desc.writable); assertFalse(desc.enumerable); assertEquals(desc.get, undefined); assertEquals(desc.set, undefined); // New object var obj2 = {}; // Make accessor - redefine to data Object.defineProperty(obj2, "foo", accessorConfigurable); // Redefine to data property Object.defineProperty(obj2, "foo", dataConfigurable); desc = Object.getOwnPropertyDescriptor(obj2, "foo"); assertEquals(obj2.foo, 1000); assertEquals(desc.value, 1000); assertTrue(desc.configurable); assertFalse(desc.writable); assertFalse(desc.enumerable); assertEquals(desc.get, undefined); assertEquals(desc.set, undefined); // Redefine back to accessor Object.defineProperty(obj2, "foo", accessorConfigurable); desc = Object.getOwnPropertyDescriptor(obj2, "foo"); assertTrue(desc.configurable); assertFalse(desc.enumerable); assertEquals(desc.writable, undefined); assertEquals(desc.get, accessorConfigurable.get); assertEquals(desc.set, accessorConfigurable.set); assertEquals(desc.value, undefined); assertEquals(1, obj2.foo = 1); assertEquals(3, val1); assertEquals(4, val2); assertEquals(3, obj2.foo); // Make data - redefine to accessor Object.defineProperty(obj2, "bar", dataConfigurable) // Redefine to accessor property Object.defineProperty(obj2, "bar", accessorConfigurable); desc = Object.getOwnPropertyDescriptor(obj2, "bar"); assertTrue(desc.configurable); assertFalse(desc.enumerable); assertEquals(desc.writable, undefined); assertEquals(desc.get, accessorConfigurable.get); assertEquals(desc.set, accessorConfigurable.set); assertEquals(desc.value, undefined); assertEquals(1, obj2.bar = 1); assertEquals(4, val1); assertEquals(4, val2); assertEquals(4, obj2.foo); // Redefine back to data property Object.defineProperty(obj2, "bar", dataConfigurable); desc = Object.getOwnPropertyDescriptor(obj2, "bar"); assertEquals(obj2.bar, 1000); assertEquals(desc.value, 1000); assertTrue(desc.configurable); assertFalse(desc.writable); assertFalse(desc.enumerable); assertEquals(desc.get, undefined); assertEquals(desc.set, undefined); // Redefinition of an accessor defined using __defineGetter__ and // __defineSetter__. function get(){return this.x} function set(x){this.x=x}; var obj3 = {x:1000}; obj3.__defineGetter__("foo", get); obj3.__defineSetter__("foo", set); desc = Object.getOwnPropertyDescriptor(obj3, "foo"); assertTrue(desc.configurable); assertTrue(desc.enumerable); assertEquals(desc.writable, undefined); assertEquals(desc.get, get); assertEquals(desc.set, set); assertEquals(desc.value, undefined); assertEquals(1, obj3.foo = 1); assertEquals(1, obj3.x); assertEquals(1, obj3.foo); // Redefine to accessor property (non configurable) - note that enumerable // which we do not redefine should remain the same (true). Object.defineProperty(obj3, "foo", accessorNoConfigurable); desc = Object.getOwnPropertyDescriptor(obj3, "foo"); assertFalse(desc.configurable); assertTrue(desc.enumerable); assertEquals(desc.writable, undefined); assertEquals(desc.get, accessorNoConfigurable.get); assertEquals(desc.set, accessorNoConfigurable.set); assertEquals(desc.value, undefined); assertEquals(1, obj3.foo = 1); assertEquals(5, val2); assertEquals(5, obj3.foo); obj3.__defineGetter__("bar", get); obj3.__defineSetter__("bar", set); // Redefine back to data property Object.defineProperty(obj3, "bar", dataConfigurable); desc = Object.getOwnPropertyDescriptor(obj3, "bar"); assertEquals(obj3.bar, 1000); assertEquals(desc.value, 1000); assertTrue(desc.configurable); assertFalse(desc.writable); assertTrue(desc.enumerable); assertEquals(desc.get, undefined); assertEquals(desc.set, undefined); var obj4 = {}; var func = function (){return 42;}; obj4.bar = func; assertEquals(42, obj4.bar()); Object.defineProperty(obj4, "bar", accessorConfigurable); desc = Object.getOwnPropertyDescriptor(obj4, "bar"); assertTrue(desc.configurable); assertTrue(desc.enumerable); assertEquals(desc.writable, undefined); assertEquals(desc.get, accessorConfigurable.get); assertEquals(desc.set, accessorConfigurable.set); assertEquals(desc.value, undefined); assertEquals(1, obj4.bar = 1); assertEquals(5, val1); assertEquals(5, obj4.bar); // Make sure an error is thrown when trying to access to redefined function. try { obj4.bar(); assertTrue(false); } catch (e) { assertTrue(/is not a function/.test(e)); } // Test runtime calls to DefineOrRedefineDataProperty and // DefineOrRedefineAccessorProperty - make sure we don't // crash. try { %DefineOrRedefineAccessorProperty(0, 0, 0, 0, 0); } catch (e) { assertTrue(/illegal access/.test(e)); } try { %DefineOrRedefineDataProperty(0, 0, 0, 0); } catch (e) { assertTrue(/illegal access/.test(e)); } try { %DefineOrRedefineDataProperty(null, null, null, null); } catch (e) { assertTrue(/illegal access/.test(e)); } try { %DefineOrRedefineAccessorProperty(null, null, null, null, null); } catch (e) { assertTrue(/illegal access/.test(e)); } try { %DefineOrRedefineDataProperty({}, null, null, null); } catch (e) { assertTrue(/illegal access/.test(e)); } // Defining properties null should fail even when we have // other allowed values try { %DefineOrRedefineAccessorProperty(null, 'foo', 0, func, 0); } catch (e) { assertTrue(/illegal access/.test(e)); } try { %DefineOrRedefineDataProperty(null, 'foo', 0, 0); } catch (e) { assertTrue(/illegal access/.test(e)); } // Test that all possible differences in step 6 in DefineOwnProperty are // exercised, i.e., any difference in the given property descriptor and the // existing properties should not return true, but throw an error if the // existing configurable property is false. var obj5 = {}; // Enumerable will default to false. Object.defineProperty(obj5, 'foo', accessorNoConfigurable); desc = Object.getOwnPropertyDescriptor(obj5, 'foo'); // First, test that we are actually allowed to set the accessor if all // values are of the descriptor are the same as the existing one. Object.defineProperty(obj5, 'foo', accessorNoConfigurable); // Different setter. var descDifferent = { configurable:false, enumerable:false, set: setter1, get: getter2 }; try { Object.defineProperty(obj5, 'foo', descDifferent); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // Different getter. descDifferent = { configurable:false, enumerable:false, set: setter2, get: getter1 }; try { Object.defineProperty(obj5, 'foo', descDifferent); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // Different enumerable. descDifferent = { configurable:false, enumerable:true, set: setter2, get: getter2 }; try { Object.defineProperty(obj5, 'foo', descDifferent); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // Different configurable. descDifferent = { configurable:false, enumerable:true, set: setter2, get: getter2 }; try { Object.defineProperty(obj5, 'foo', descDifferent); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // No difference. descDifferent = { configurable:false, enumerable:false, set: setter2, get: getter2 }; // Make sure we can still redefine if all properties are the same. Object.defineProperty(obj5, 'foo', descDifferent); // Make sure that obj5 still holds the original values. desc = Object.getOwnPropertyDescriptor(obj5, 'foo'); assertEquals(desc.get, getter2); assertEquals(desc.set, setter2); assertFalse(desc.enumerable); assertFalse(desc.configurable); // Also exercise step 6 on data property, writable and enumerable // defaults to false. Object.defineProperty(obj5, 'bar', dataNoConfigurable); // Test that redefinition with the same property descriptor is possible Object.defineProperty(obj5, 'bar', dataNoConfigurable); // Different value. descDifferent = { configurable:false, enumerable:false, writable: false, value: 1999 }; try { Object.defineProperty(obj5, 'bar', descDifferent); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // Different writable. descDifferent = { configurable:false, enumerable:false, writable: true, value: 2000 }; try { Object.defineProperty(obj5, 'bar', descDifferent); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // Different enumerable. descDifferent = { configurable:false, enumerable:true , writable:false, value: 2000 }; try { Object.defineProperty(obj5, 'bar', descDifferent); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // Different configurable. descDifferent = { configurable:true, enumerable:false, writable:false, value: 2000 }; try { Object.defineProperty(obj5, 'bar', descDifferent); assertTrue(false); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } // No difference. descDifferent = { configurable:false, enumerable:false, writable:false, value:2000 }; // Make sure we can still redefine if all properties are the same. Object.defineProperty(obj5, 'bar', descDifferent); // Make sure that obj5 still holds the original values. desc = Object.getOwnPropertyDescriptor(obj5, 'bar'); assertEquals(desc.value, 2000); assertFalse(desc.writable); assertFalse(desc.enumerable); assertFalse(desc.configurable); // Make sure that we can't overwrite +0 with -0 and vice versa. var descMinusZero = {value: -0, configurable: false}; var descPlusZero = {value: +0, configurable: false}; Object.defineProperty(obj5, 'minuszero', descMinusZero); // Make sure we can redefine with -0. Object.defineProperty(obj5, 'minuszero', descMinusZero); try { Object.defineProperty(obj5, 'minuszero', descPlusZero); assertUnreachable(); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } Object.defineProperty(obj5, 'pluszero', descPlusZero); // Make sure we can redefine with +0. Object.defineProperty(obj5, 'pluszero', descPlusZero); try { Object.defineProperty(obj5, 'pluszero', descMinusZero); assertUnreachable(); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } var obj6 = {}; obj6[1] = 'foo'; obj6[2] = 'bar'; obj6[3] = '42'; obj6[4] = '43'; obj6[5] = '44'; var descElement = { value: 'foobar' }; var descElementNonConfigurable = { value: 'barfoo', configurable: false }; var descElementNonWritable = { value: 'foofoo', writable: false }; var descElementNonEnumerable = { value: 'barbar', enumerable: false }; var descElementAllFalse = { value: 'foofalse', configurable: false, writable: false, enumerable: false }; // Redefine existing property. Object.defineProperty(obj6, '1', descElement); desc = Object.getOwnPropertyDescriptor(obj6, '1'); assertEquals(desc.value, 'foobar'); assertTrue(desc.writable); assertTrue(desc.enumerable); assertTrue(desc.configurable); // Redefine existing property with configurable: false. Object.defineProperty(obj6, '2', descElementNonConfigurable); desc = Object.getOwnPropertyDescriptor(obj6, '2'); assertEquals(desc.value, 'barfoo'); assertTrue(desc.writable); assertTrue(desc.enumerable); assertFalse(desc.configurable); // Ensure that we can't overwrite the non configurable element. try { Object.defineProperty(obj6, '2', descElement); assertUnreachable(); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } Object.defineProperty(obj6, '3', descElementNonWritable); desc = Object.getOwnPropertyDescriptor(obj6, '3'); assertEquals(desc.value, 'foofoo'); assertFalse(desc.writable); assertTrue(desc.enumerable); assertTrue(desc.configurable); // Redefine existing property with configurable: false. Object.defineProperty(obj6, '4', descElementNonEnumerable); desc = Object.getOwnPropertyDescriptor(obj6, '4'); assertEquals(desc.value, 'barbar'); assertTrue(desc.writable); assertFalse(desc.enumerable); assertTrue(desc.configurable); // Redefine existing property with configurable: false. Object.defineProperty(obj6, '5', descElementAllFalse); desc = Object.getOwnPropertyDescriptor(obj6, '5'); assertEquals(desc.value, 'foofalse'); assertFalse(desc.writable); assertFalse(desc.enumerable); assertFalse(desc.configurable); // Define non existing property - all attributes should default to false. Object.defineProperty(obj6, '15', descElement); desc = Object.getOwnPropertyDescriptor(obj6, '15'); assertEquals(desc.value, 'foobar'); assertFalse(desc.writable); assertFalse(desc.enumerable); assertFalse(desc.configurable); // Make sure that we can't redefine using direct access. obj6[15] ='overwrite'; assertEquals(obj6[15],'foobar'); // Repeat the above tests on an array. var arr = new Array(); arr[1] = 'foo'; arr[2] = 'bar'; arr[3] = '42'; arr[4] = '43'; arr[5] = '44'; var descElement = { value: 'foobar' }; var descElementNonConfigurable = { value: 'barfoo', configurable: false }; var descElementNonWritable = { value: 'foofoo', writable: false }; var descElementNonEnumerable = { value: 'barbar', enumerable: false }; var descElementAllFalse = { value: 'foofalse', configurable: false, writable: false, enumerable: false }; // Redefine existing property. Object.defineProperty(arr, '1', descElement); desc = Object.getOwnPropertyDescriptor(arr, '1'); assertEquals(desc.value, 'foobar'); assertTrue(desc.writable); assertTrue(desc.enumerable); assertTrue(desc.configurable); // Redefine existing property with configurable: false. Object.defineProperty(arr, '2', descElementNonConfigurable); desc = Object.getOwnPropertyDescriptor(arr, '2'); assertEquals(desc.value, 'barfoo'); assertTrue(desc.writable); assertTrue(desc.enumerable); assertFalse(desc.configurable); // Ensure that we can't overwrite the non configurable element. try { Object.defineProperty(arr, '2', descElement); assertUnreachable(); } catch (e) { assertTrue(/Cannot redefine property/.test(e)); } Object.defineProperty(arr, '3', descElementNonWritable); desc = Object.getOwnPropertyDescriptor(arr, '3'); assertEquals(desc.value, 'foofoo'); assertFalse(desc.writable); assertTrue(desc.enumerable); assertTrue(desc.configurable); // Redefine existing property with configurable: false. Object.defineProperty(arr, '4', descElementNonEnumerable); desc = Object.getOwnPropertyDescriptor(arr, '4'); assertEquals(desc.value, 'barbar'); assertTrue(desc.writable); assertFalse(desc.enumerable); assertTrue(desc.configurable); // Redefine existing property with configurable: false. Object.defineProperty(arr, '5', descElementAllFalse); desc = Object.getOwnPropertyDescriptor(arr, '5'); assertEquals(desc.value, 'foofalse'); assertFalse(desc.writable); assertFalse(desc.enumerable); assertFalse(desc.configurable); // Define non existing property - all attributes should default to false. Object.defineProperty(arr, '15', descElement); desc = Object.getOwnPropertyDescriptor(arr, '15'); assertEquals(desc.value, 'foobar'); assertFalse(desc.writable); assertFalse(desc.enumerable); assertFalse(desc.configurable);
{ "content_hash": "db66c4cfa054c80dcbce55b51fdee785", "timestamp": "", "source": "github", "line_count": 837, "max_line_length": 78, "avg_line_length": 28.25448028673835, "alnum_prop": 0.7452746416338957, "repo_name": "sinisterchipmunk/tomato", "id": "b258aa75bf375e279e207746c383168d5ba62dd6", "size": "25406", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ext/tomato/external/v8/test/mjsunit/object-define-property.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2815122" }, { "name": "C++", "bytes": "19935082" }, { "name": "JavaScript", "bytes": "4019959" }, { "name": "Python", "bytes": "1833190" }, { "name": "Ruby", "bytes": "245959" }, { "name": "Scheme", "bytes": "10604" } ], "symlink_target": "" }
/** * Created by Wayne on 16/3/17. */ 'use strict'; var async = require('async'), error = require('../../errors/all'); var appDb = require('../mongoose').appDb, TransportEvent = appDb.model('TransportEvent'); var self = exports; function getEventByOrder(orderIds, callback) { if (!orderIds || !Array.isArray(orderIds)) { return callback({err: error.params.invalid_value}); } TransportEvent.find({order: {$in: orderIds}}) .populate('driver order') .exec(function (err, transportEvents) { if (err) { err = {err: error.system.db_error}; } return callback(err, transportEvents); }); } exports.getEventByOrder = function (orderIds, callback) { getEventByOrder(orderIds, callback); };
{ "content_hash": "3997ad1fffbbf1e2cd50cf51fb574313", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 57, "avg_line_length": 22.484848484848484, "alnum_prop": 0.6469002695417789, "repo_name": "hardylake8020/youka-server", "id": "d33edc06cb6c9356ed7aba518951e1d758e3e094", "size": "742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libraries/services/transport_event.server.service.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "762739" }, { "name": "HTML", "bytes": "347951" }, { "name": "JavaScript", "bytes": "3581083" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>lc: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.9.1 / lc - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> lc <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-18 10:02:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-18 10:02:02 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.9.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/lc&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/lc&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: modules&quot; &quot;keyword: monads&quot; &quot;keyword: category&quot; &quot;keyword: lambda calculus&quot; &quot;keyword: higher-order syntax&quot; &quot;category: Computer Science/Lambda Calculi&quot; &quot;date: 2006-01-12&quot; &quot;date: 2008-09-9&quot; ] authors: [ &quot;André Hirschowitz &lt;ah@math.unice.fr&gt; [http://math.unice.fr/~ah/]&quot; &quot;Marco Maggesi &lt;maggesi@math.unifi.it&gt; [http://www.math.unifi.it/~maggesi/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/lc/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/lc.git&quot; synopsis: &quot;Modules over monads and lambda-calculi&quot; description: &quot;&quot;&quot; http://www.math.unifi.it/~/maggesi/mechanized/ We define a notion of module over a monad and use it to propose a new definition (or semantics) for abstract syntax (with binding constructions). Using our notion of module, we build a category of `exponential&#39; monads, which can be understood as the category of lambda-calculi, and prove that it has an initial object (the pure untyped lambda-calculus).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/lc/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=a827e42c57b1b80f30c7160d05029321&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-lc.8.6.0 coq.8.9.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.9.1). The following dependencies couldn&#39;t be met: - coq-lc -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-lc.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "f38f6f45481bc2020dcc2805c0c98e36", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 188, "avg_line_length": 41.06703910614525, "alnum_prop": 0.5490409468099579, "repo_name": "coq-bench/coq-bench.github.io", "id": "11533350c65fc84ced201d9f65946092e8a5af3d", "size": "7377", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.9.1/lc/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
iOS Digest #2 ======================= ## Coding I confess I really like to use managers in my projects. NetworkManager, DataManager, CryptoManager. Using managers could be sign a bad app architectural. [The Trouble with Manager Objects](https://sandofsky.com/blog/manager-classes.html) Building your app remember there basic rules: - [Don't Repeat Yourself](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) - [Single responsibility principle](https://en.m.wikipedia.org/wiki/Single_responsibility_principle) !!!Large C style classes stink!!! ## Open Source **Swift modules** in coming Swift 3.0 are going to be huge. Check the list of existing modules at [Swift Modules](https://swiftmodules.com/about) **JVFloatLabeledTextField** [JVFloatLabeledTextField](https://github.com/jverdi/JVFloatLabeledTextField) is the implementation a UX pattern that has come to be known the "Float Label Pattern" [FBMemoryProfiler](https://github.com/facebook/FBMemoryProfiler) is an iOS library providing developer tools for browsing objects in memory over time **Another storage with open source projects for iOS** [iOS Cookies](http://www.ioscookies.com/) ## Design Very interesting alternative to standart hamburger menu. I wonder if there any implementations (DESIGNING AN ALTERNATIVE TO THE HAMBURGER MENU)[http://scottjensen.design/2016/04/designing-an-alternative-to-the-hamburger-menu] ## Work [Hired](https://www.hired.com) - find your new job with the top companies (not available in Vancouver) ## Apps [Turo](https://www.turo.com) - Peer-to-peer car sharing is now in Canada [Kite](https://kite.com) is your AI pair programmer ## Tools **Show build duration** defaults write com.apple.dt.Xcode ShowBuildOperationDuration -bool YES restart Xcode [TextWrangler](itunes.apple.com/ru/app/textwrangler/id404010395?mt=12) - better text editor [GetPostman](https://www.getpostman.com/) - REST API client
{ "content_hash": "993cef0ae8925f0428a7c5e89f89c5a0", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 163, "avg_line_length": 39.16326530612245, "alnum_prop": 0.7665450755601876, "repo_name": "jeksys/iOSDigest", "id": "f62c46546f05f807afe61c2d2567820f91e1df14", "size": "1919", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Digest #02.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8997" }, { "name": "HTML", "bytes": "4621" } ], "symlink_target": "" }
Godot Engine is developed by a community of voluntary contributors who contribute code, bug reports, documentation, artwork, support, etc. It is impossible to list them all; nevertheless, this file aims at listing the developers who contributed significant patches to this MIT licensed source code. "Significant" is arbitrarily decided, but should be fair :) GitHub usernames are indicated in parentheses, or as sole entry when no other name is available. ## Original authors Juan Linietsky (reduz) Ariel Manzur (punto-) ## Developers (in alphabetical order, with 10 commits or more excluding merges) Alexander Holland (AlexHolly) Alexey Velikiy (jonyrock) Andreas Haas (Hinsbart) Anton Yabchinskiy (a12n) Aren Villanueva (kurikaesu) Ariel Manzur (punto-) Bastiaan Olij (BastiaanOlij) Bojidar Marinov (bojidar-bg) Błażej Szczygieł (zaps166) Carl Olsson (not-surt) Dana Olson (adolson) Daniel J. Ramirez (djrm) Emmanuel Leblond (touilleMan) Fabio Alessandrelli (Faless) Ferenc Arn (tagcup) Franklin Sobrinho (TheHX) Geequlim Gen (dbsGen) George Marques (vnen) Guilherme Felipe (guilhermefelipecgs) Hein-Pieter van Braam (hpvb) Hubert Jarosz (Marqin) Ignacio Etcheverry (neikeq) J08nY Johan Manuel (29jm) Joshua Grams (JoshuaGrams) Juan Linietsky (reduz) Julian Murgia (StraToN) Kostadin Damyanov (Max-Might) L. Krause (eska014) Marc Gilleron (Zylann) Marcelo Fernandez (marcelofg55) Mariano Javier Suligoy (MarianoGnu) Mario Schlack (hurikhan) Masoud BH (masoudbh3) Nathan Warden (NathanWarden) Ovnuniarchos Patrick (firefly2442) Paul Batty (Paulb23) Pawel Kowal (pkowal1982) Pedro J. Estébanez (RandomShaper) Ralf Hölzemer (rollenrolm) Ramesh Ravone (RameshRavone) Ray Koopa (RayKoopa) Rémi Verschelde (akien-mga) SaracenOne Thomas Herzog (karroffel) V. Vamsi Krishna (vkbsb) Vinzenz Feenstra (vinzenz) Zher Huei Lee (leezh) ZuBsPaCe 박한얼 (volzhs) est31 marynate mrezai romulox-x sanikoyes yg2f (SuperUserNameMan)
{ "content_hash": "58a999d971b4944ffba32d62d70c0958", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 77, "avg_line_length": 28.051948051948052, "alnum_prop": 0.7092592592592593, "repo_name": "ficoos/godot", "id": "728ba5f6eecf0951bb0026cfef85d21b34931ed0", "size": "2196", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "AUTHORS.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "50004" }, { "name": "C++", "bytes": "16809683" }, { "name": "HTML", "bytes": "10302" }, { "name": "Java", "bytes": "497034" }, { "name": "Makefile", "bytes": "451" }, { "name": "Objective-C", "bytes": "2644" }, { "name": "Objective-C++", "bytes": "146786" }, { "name": "Python", "bytes": "266362" }, { "name": "Shell", "bytes": "11105" } ], "symlink_target": "" }
title: "Booyah!" layout: "post" permalink: "/2012/09/booyah.html" uuid: "8029689439193204577" guid: "tag:blogger.com,1999:blog-4897882164686544357.post-8029689439193204577" date: "2012-09-01 21:00:00" updated: "2012-09-01 21:00:02" description: blogger: siteid: "4897882164686544357" postid: "8029689439193204577" comments: "0" categories: [beer, pancakes, belgian, breakfast, booyah, milwaukee brewing company, farmhouse ale, saison, wisconsin] author: bradorego --- <div class="css-full-post-content js-full-post-content"> <div dir="ltr" style="text-align: left;" trbidi="on"> <div class="separator" style="clear: both; text-align: center;"> <span style="font-family: Trebuchet MS, sans-serif;"> <br /> </span> </div> <span style="font-family: Trebuchet MS, sans-serif;">I'm normally all over the beer/pancake puns, but with a name like Booyah, I feel like it'd be an injustice to the beer and to any potential pun that I could come up with. Milwaukee Brewing Co's <a href="http://mkebrewing.com/beer/booyah/">Booyah</a>&nbsp;is a Belgian-style Farmhouse Ale that's apparently inspired by some type of soup that's made in the tiny town of De Pere, Wisconsin (as per the video on their webpage I just saw). Both the name and inspiration come from this varied-ingredient stew, and is more than just a beer - there're Booyah Parties, an entire event, county fair...I really lost track of what that guy was talking about. He broke his ankle watching a the Vikings beat the Packers or something. What? Sure.</span> <br /> <table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"> <tbody> <tr> <td style="text-align: center;"> <a href="{{ site.url }}/assets/full/booyah/beer.png"> <span style="font-family: Trebuchet MS, sans-serif;"> <img border="0" height="640" src="{{ site.url }}/assets/compressed/booyah/beer.png" width="360" /> </span> </a> </td> </tr> <tr> <td class="tr-caption" style="text-align: center;"> <span style="font-family: Trebuchet MS, sans-serif;">Local flavor alright...</span> </td> </tr> </tbody> </table> <span style="font-family: Trebuchet MS, sans-serif;">This particular bottle of Booyah came to me after a house party - someone had brought some over and I'd never heard of the stuff, but they wound up leaving it at our place, and with a name like Booyah, I couldn't resist. It's a light and flavorful ale with a lot of subtle undertones. I was a fan of it in liquid form (for a Farmhouse Ale, that is - I'll take any porter over any light ale any day), but the time came to see how it stacks up as a flapjack.</span> <span style="font-family: Trebuchet MS, sans-serif;"></span> <table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"> <tbody> <tr> <td style="text-align: center;"> <a href="{{ site.url }}/assets/full/booyah/batter.png"> <span style="font-family: Trebuchet MS, sans-serif;"> <img border="0" height="360" src="{{ site.url }}/assets/compressed/booyah/batter.png" width="640" /> </span> </a> </td> </tr> <tr> <td class="tr-caption" style="text-align: center;"> <span style="font-family: Trebuchet MS, sans-serif;">You sure there's Booyah in there?</span> </td> </tr> </tbody> </table> <span style="font-family: Trebuchet MS, sans-serif;">The batter shared the delightful aroma of the beer, but colorwise/otherwise it had nothing special about it. You could probably, with proper mixture, pass this off as normal batter (considering batter's already kind of yeast-y) and get away with it. But why would you want to do that. Embrace the Booyah. Love the Booyah.</span> <div> <h4 style="text-align: left;"> <span style="font-family: Trebuchet MS, sans-serif;">Results:</span> </h4> <div> <span style="font-family: Trebuchet MS, sans-serif;">Booyah came out looking and smelling like pretty standard pancakes. Unlike Spotted Cow, Booyah kept a bit of its flavors in pancake form, and didn't give much of a beery aftertaste. Unlike Leine's Summer Wheat, the pancaking process didn't really enhance the flavors at all. If anything, some of the subtlety that Booyah is known for was lost in the process.&nbsp;</span> </div> </div> <table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"> <tbody> <tr> <td style="text-align: center;"> <a href="{{ site.url }}/assets/full/booyah/pancakes.png" imageanchor="1" style="margin-left: auto; margin-right: auto; text-align: center;"> <span style="font-family: Trebuchet MS, sans-serif;"> <img border="0" height="360" src="{{ site.url }}/assets/compressed/booyah/pancakes.png" width="640" /> </span> </a> </td> </tr> <tr> <td class="tr-caption" style="text-align: center;"> <span style="font-family: Trebuchet MS, sans-serif;">Check out my super-classy plastic plates!</span> </td> </tr> </tbody> </table> <h4> <span style="font-family: Trebuchet MS, sans-serif;">The Binary Scale:</span> </h4> <div> <span style="font-family: Trebuchet MS, sans-serif;">1 - Go ahead and make them!</span> </div> <div> <span style="font-family: Trebuchet MS, sans-serif;"> <br /> </span> </div> <div> <span style="font-family: Trebuchet MS, sans-serif;">If you get your hands on a bottle of Booyah you certainly won't be disappointed in pancake form. They aren't anything special like some of our previous creations, but they maintain a delightful somewhat-wheaty-not-too-beery flavor.</span> </div> <div> <span style="font-family: Trebuchet MS, sans-serif;"> <br /> </span> </div> <blockquote class="tr_bq"> <span style="font-family: Trebuchet MS, sans-serif;"><i>What do you think of Booyah? The stuff of legends like MKE's video says? Think I didn't utilize the name enough? Keep the conversation going in the comments section!</i>&nbsp;</span> </blockquote> <div></div> </div> </div> {% include twitter.html tweetAt=" from @MKEbrewco" %}
{ "content_hash": "cb36db4e6c036891738c7941694e010e", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 799, "avg_line_length": 63.72649572649573, "alnum_prop": 0.5802038626609443, "repo_name": "bradorego/beerbatterbreakfast", "id": "b547d4f0df50d4b28357f6dfa54f794a11ed3c0c", "size": "7460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2012-09-01-booyah.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24859" }, { "name": "HTML", "bytes": "279978" } ], "symlink_target": "" }
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QStyleOptionViewItemV2.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:24 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QStyleOptionViewItemV2 ( QqStyleOptionViewItemV2(..) ,QqStyleOptionViewItemV2_nf(..) ,qStyleOptionViewItemV2_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QStyleOptionViewItemV2 import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui class QqStyleOptionViewItemV2 x1 where qStyleOptionViewItemV2 :: x1 -> IO (QStyleOptionViewItemV2 ()) instance QqStyleOptionViewItemV2 (()) where qStyleOptionViewItemV2 () = withQStyleOptionViewItemV2Result $ qtc_QStyleOptionViewItemV2 foreign import ccall "qtc_QStyleOptionViewItemV2" qtc_QStyleOptionViewItemV2 :: IO (Ptr (TQStyleOptionViewItemV2 ())) instance QqStyleOptionViewItemV2 ((QStyleOptionViewItem t1)) where qStyleOptionViewItemV2 (x1) = withQStyleOptionViewItemV2Result $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionViewItemV21 cobj_x1 foreign import ccall "qtc_QStyleOptionViewItemV21" qtc_QStyleOptionViewItemV21 :: Ptr (TQStyleOptionViewItem t1) -> IO (Ptr (TQStyleOptionViewItemV2 ())) instance QqStyleOptionViewItemV2 ((QStyleOptionViewItemV2 t1)) where qStyleOptionViewItemV2 (x1) = withQStyleOptionViewItemV2Result $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionViewItemV22 cobj_x1 foreign import ccall "qtc_QStyleOptionViewItemV22" qtc_QStyleOptionViewItemV22 :: Ptr (TQStyleOptionViewItemV2 t1) -> IO (Ptr (TQStyleOptionViewItemV2 ())) class QqStyleOptionViewItemV2_nf x1 where qStyleOptionViewItemV2_nf :: x1 -> IO (QStyleOptionViewItemV2 ()) instance QqStyleOptionViewItemV2_nf (()) where qStyleOptionViewItemV2_nf () = withObjectRefResult $ qtc_QStyleOptionViewItemV2 instance QqStyleOptionViewItemV2_nf ((QStyleOptionViewItem t1)) where qStyleOptionViewItemV2_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionViewItemV21 cobj_x1 instance QqStyleOptionViewItemV2_nf ((QStyleOptionViewItemV2 t1)) where qStyleOptionViewItemV2_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionViewItemV22 cobj_x1 instance Qfeatures (QStyleOptionViewItemV2 a) (()) (IO (ViewItemFeatures)) where features x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionViewItemV2_features cobj_x0 foreign import ccall "qtc_QStyleOptionViewItemV2_features" qtc_QStyleOptionViewItemV2_features :: Ptr (TQStyleOptionViewItemV2 a) -> IO CLong instance QsetFeatures (QStyleOptionViewItemV2 a) ((ViewItemFeatures)) where setFeatures x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionViewItemV2_setFeatures cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QStyleOptionViewItemV2_setFeatures" qtc_QStyleOptionViewItemV2_setFeatures :: Ptr (TQStyleOptionViewItemV2 a) -> CLong -> IO () qStyleOptionViewItemV2_delete :: QStyleOptionViewItemV2 a -> IO () qStyleOptionViewItemV2_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionViewItemV2_delete cobj_x0 foreign import ccall "qtc_QStyleOptionViewItemV2_delete" qtc_QStyleOptionViewItemV2_delete :: Ptr (TQStyleOptionViewItemV2 a) -> IO ()
{ "content_hash": "6e0783d6f271747b64524c366e5f0782", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 155, "avg_line_length": 36.717171717171716, "alnum_prop": 0.7433287482806052, "repo_name": "uduki/hsQt", "id": "efcdf5ca14ae6d4d60edffef6d1bdfb0822e5aa2", "size": "3635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Qtc/Gui/QStyleOptionViewItemV2.hs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "2793571" }, { "name": "C++", "bytes": "12313408" }, { "name": "Haskell", "bytes": "19244532" }, { "name": "JavaScript", "bytes": "20091" }, { "name": "Perl", "bytes": "28106" }, { "name": "Prolog", "bytes": "527" }, { "name": "Shell", "bytes": "8079" }, { "name": "XML", "bytes": "28053" } ], "symlink_target": "" }
package com.javarush.task.task14.task1408; public class MoldovanHen extends Hen { public MoldovanHen() { System.out.println(getDescription()); } @Override int getCountOfEggsPerMonth() { return 5; } public String getDescription() { return super.getDescription() + " Моя страна - " + Country.MOLDOVA + ". Я несу " + this.getCountOfEggsPerMonth() + " яиц в месяц."; } }
{ "content_hash": "8142ab3e738fe3fbb014406e0fc21d4a", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 96, "avg_line_length": 24.333333333333332, "alnum_prop": 0.6141552511415526, "repo_name": "pshynin/JavaRushTasks", "id": "270b98d53f956c08ada2b4f9f6616c9aae5f6895", "size": "461", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2.JavaCore/src/com/javarush/task/task14/task1408/MoldovanHen.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "606700" }, { "name": "Roff", "bytes": "4197803" } ], "symlink_target": "" }
import json import serf import pipe def handler(obj): name, payload = obj serf.serf_plain('event', name, json.dumps(payload)) if __name__ == '__main__': pipe.server('/serfnode/parent', handler)
{ "content_hash": "19fbd50b2d79e01279b416a2ccc88468", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 55, "avg_line_length": 16.23076923076923, "alnum_prop": 0.6445497630331753, "repo_name": "waltermoreira/serfnode", "id": "c9eb64a1b551f216438647966510eea582b8330e", "size": "234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "serfnode/handler/parent_server.py", "mode": "33261", "license": "mit", "language": [ { "name": "Makefile", "bytes": "444" }, { "name": "Python", "bytes": "37282" }, { "name": "Ruby", "bytes": "4831" }, { "name": "Shell", "bytes": "2271" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="all_74.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Wczytywanie...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">Szukanie...</div> <div class="SRStatus" id="NoMatches">Brak dopasowań</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
{ "content_hash": "68f0dad9b25717bb588228e86db15497", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 121, "avg_line_length": 38.84, "alnum_prop": 0.7075180226570545, "repo_name": "superdyzio/PWR-Stuff", "id": "3cfbf70f37e95b97bded39fa876c959db721024c", "size": "972", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "AIR-ARR/Programowanie Obiektowe/12/dox/html/search/all_74.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "17829" }, { "name": "Batchfile", "bytes": "1042" }, { "name": "C", "bytes": "2403055" }, { "name": "C#", "bytes": "625528" }, { "name": "C++", "bytes": "3066245" }, { "name": "CMake", "bytes": "983251" }, { "name": "CSS", "bytes": "218848" }, { "name": "Common Lisp", "bytes": "378578" }, { "name": "HTML", "bytes": "4999679" }, { "name": "Java", "bytes": "475300" }, { "name": "JavaScript", "bytes": "266296" }, { "name": "M", "bytes": "2385" }, { "name": "M4", "bytes": "3010" }, { "name": "Makefile", "bytes": "3734730" }, { "name": "Matlab", "bytes": "160418" }, { "name": "OCaml", "bytes": "2021" }, { "name": "PHP", "bytes": "10629" }, { "name": "Perl", "bytes": "7551" }, { "name": "PowerShell", "bytes": "31323" }, { "name": "Python", "bytes": "607184" }, { "name": "QMake", "bytes": "1211" }, { "name": "Scala", "bytes": "4781" }, { "name": "Shell", "bytes": "1550640" }, { "name": "Tcl", "bytes": "4143" }, { "name": "q", "bytes": "1050" } ], "symlink_target": "" }
<?php namespace App\WebBundle\Entity; use Doctrine\ORM\EntityRepository; /** * EtapaConcursoRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class EtapaConcursoRepository extends EntityRepository { public function findAllEtapas($idConcurso,$tipo){ $em=$this->getEntityManager(); $dql= "SELECT ec.id,e.id as etapaId,e.nombre,ec.fechaInicio,ec.fechaFin,ec.extendido,ec.fechaExtension FROM AppWebBundle:Etapa e JOIN e.tipoConcurso tc LEFT JOIN e.etapasconcurso ec WITH ec.id IN (SELECT x.id FROM AppWebBundle:EtapaConcurso x JOIN x.concurso c WHERE c.id=:id) WHERE tc.id=$tipo "; $query=$em->createQuery($dql)->setParameter('id', $idConcurso); try { return $query->getResult(); } catch (\Doctrine\ORM\NoResultException $e) { return null; } } public function findByEtapa($idconsurso,$idetapa){ $em=$this->getEntityManager(); $dql= "SELECT ec FROM AppWebBundle:EtapaConcurso ec JOIN ec.concurso c JOIN ec.etapa e WHERE c.id=:idconcurso and e.id=:idetapa"; $query=$em->createQuery($dql) ->setParameter('idconcurso', $idconsurso) ->setParameter('idetapa', $idetapa); try { return $query->getSingleResult(); } catch (\Doctrine\ORM\NoResultException $e) { return null; } } public function findByTipoEtapa($idconsurso,$idtipoetapa,$idtipoconcurso){ $em=$this->getEntityManager(); $dql= "SELECT ec FROM AppWebBundle:EtapaConcurso ec JOIN ec.concurso c JOIN ec.etapa e JOIN e.tipoEtapa te JOIN e.tipoConcurso t WHERE c.id=:idconcurso AND te.id=:idtipoetapa AND t.id=:idtipoconcurso"; $query=$em->createQuery($dql) ->setParameter('idconcurso', $idconsurso) ->setParameter('idtipoetapa', $idtipoetapa) ->setParameter('idtipoconcurso', $idtipoconcurso); try { return $query->getArrayResult(); } catch (\Doctrine\ORM\NoResultException $e) { return null; } } }
{ "content_hash": "c6818a43c7f1ccbeb7f43cb957a95f63", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 140, "avg_line_length": 35.661764705882355, "alnum_prop": 0.5682474226804124, "repo_name": "yumini/PNC", "id": "0dfcd26859c2a533f7a6407bdc5a3df65b5c48cd", "size": "2425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/App/WebBundle/Entity/EtapaConcursoRepository.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "38882" }, { "name": "JavaScript", "bytes": "2344870" }, { "name": "PHP", "bytes": "703512" } ], "symlink_target": "" }
/** * @author Daisuke Homma */ new function() { // block an.PathSplitter = function() { an.g.PathSplitter = this; }; var self = an.PathSplitter; // inherit from an.EventState; self.prototype = new an.EventState(); self.prototype.test = function(e) { this.select(); return true; } self.prototype.select = function() { this.selectSelf(); }; self.prototype.deselect = function() { this.deselectSelf(); }; self.prototype.onClick = function(e) { var position = an.u.getMousePositionInCanvas(e); var x = position.x; var y = position.y; // hit test (Anchor Point) var hitInfo = an.g.editor.isOnAnchorPoints(x, y); if(hitInfo) { an.g.editor.splitPath(hitInfo.path, hitInfo.curve, hitInfo.point); an.g.editor.draw(); } } } // block
{ "content_hash": "cadef41ccbf4fe8c83fbf422669d1fdb", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 70, "avg_line_length": 15.215686274509803, "alnum_prop": 0.654639175257732, "repo_name": "homma/Anima", "id": "e99ef86436910b2e5fca47271c8cb850331f7232", "size": "776", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui_event/splitter/path_splitter.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "212604" }, { "name": "Shell", "bytes": "399" } ], "symlink_target": "" }
#include <folly/experimental/symbolizer/SignalHandler.h> int main() { folly::symbolizer::installFatalSignalHandler(); __builtin_trap(); }
{ "content_hash": "eb884473d75adedfaa5cd822a77ff9d7", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 56, "avg_line_length": 18.125, "alnum_prop": 0.7310344827586207, "repo_name": "facebook/folly", "id": "17ff8968c1060630f466ae0451efd4bd982be982", "size": "763", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "folly/experimental/symbolizer/test/Crash.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "21191" }, { "name": "Batchfile", "bytes": "989" }, { "name": "C", "bytes": "73316" }, { "name": "C++", "bytes": "16280936" }, { "name": "CMake", "bytes": "204978" }, { "name": "CSS", "bytes": "786" }, { "name": "Cython", "bytes": "41061" }, { "name": "GDB", "bytes": "2493" }, { "name": "Makefile", "bytes": "804" }, { "name": "Python", "bytes": "413397" }, { "name": "Ruby", "bytes": "2882" }, { "name": "Shell", "bytes": "12465" } ], "symlink_target": "" }
XOCC=xocc CC=g++ #Host code HOST_SRC=./chain.cpp crmsd.cpp eef1.cpp leaf.cpp node.cpp pairtree.cpp pdb.cpp rss.cpp simulation.cpp slist.cpp spheres.cpp #HOST_HDRS=MatVec.h RectDist.h RectDistCL.h kernel.h AA.hpp bv.hpp chain.hpp cl.hpp crmsd.hpp eef1.hpp leaf.hpp leafCL.hpp node.hpp pairtree.hpp pdb.hpp rss.hpp slist.hpp spheres.hpp #HOST_SRC=simulation.cpp HOSTS_HDRS= HOST_CFLAGS=-D FPGA_DEVICE -g -Wall -I${XILINX_SDX}/runtime/include/1_2 -D C_KERNEL -O3 -Wno-deprecated HOST_LFLAGS=-L${XILINX_SDX}/runtime/lib/x86_64 -lxilinxopencl #name of host executable HOST_EXE=host_profax #kernel KERNEL_SRC=./kernel.cpp KERNEL_HDRS=./ KERNEL_FLAGS= KERNEL_EXE=computePairEnergy KERNEL_NAME=computePairEnergy_k #custom flag to give to xocc KERNEL_LDCLFLAGS=--nk $(KERNEL_NAME):1 \ --xp param:compiler.preserveHlsOutput=1 \ --max_memory_ports $(KERNEL_NAME) \ --memory_port_data_width $(KERNEL_NAME):512 KERNEL_ADDITIONAL_FLAGS=--debug TARGET_DEVICE=xilinx:adm-pcie-ku3:2ddr-xpr:4.0 #TARGET for compilation [sw_emu | hw_emu | hw] TARGET=none REPORT_FLAG=n REPORT= ifeq (${TARGET}, sw_emu) $(info software emulation) TARGET=sw_emu ifeq (${REPORT_FLAG}, y) $(info creating REPORT for software emulation set to true. This is going to take longer at it will synthesize the kernel) REPORT=--report estimate else $(info I am not creating a REPORT for software emulation, set REPORT_FLAG=y if you want it) REPORT= endif else ifeq (${TARGET}, hw_emu) $(info hardware emulation) TARGET=hw_emu REPORT=--report estimate else ifeq (${TARGET}, hw) $(info system build) TARGET=hw REPORT=--report system else $(info no TARGET selected) endif PERIOD:= : UNDERSCORE:= _ dest_dir=$(TARGET)/$(subst $(PERIOD),$(UNDERSCORE),$(TARGET_DEVICE)) ifndef XILINX_SDX $(error XILINX_SDX is not set. Please source the SDx settings64.{csh,sh} first) endif clean: rm -rf .Xil emconfig.json clean_sw_emu: clean rm -rf sw_emu clean_hw_emu: clean rm -rf hw_emu clean_hw: clean rm -rf hw cleanall: clean_sw_emu clean_hw_emu clean_hw rm -rf _xocc_* xcl_design_wrapper_* check_TARGET: ifeq (${TARGET}, none) $(error Target can not be set to none) endif host: check_TARGET $(HOST_SRC) $(HOST_HDRS) mkdir -p $(dest_dir) $(CC) $(HOST_SRC) $(HOST_HDRS) $(HOST_CFLAGS) $(HOST_LFLAGS) -o $(dest_dir)/$(HOST_EXE) xo: check_TARGET mkdir -p $(dest_dir) $(XOCC) --platform $(TARGET_DEVICE) --target $(TARGET) --compile --include $(KERNEL_HDRS) --save-temps $(REPORT) --kernel $(KERNEL_NAME) $(KERNEL_SRC) $(KERNEL_LDCLFLAGS) $(KERNEL_FLAGS) $(KERNEL_ADDITIONAL_FLAGS) --output $(dest_dir)/$(KERNEL_EXE).xo xclbin: check_TARGET xo $(XOCC) --platform $(TARGET_DEVICE) --target $(TARGET) --link --include $(KERNEL_HDRS) --save-temps $(REPORT) --kernel $(KERNEL_NAME) $(dest_dir)/$(KERNEL_EXE).xo $(KERNEL_LDCLFLAGS) $(KERNEL_FLAGS) $(KERNEL_ADDITIONAL_FLAGS) --output $(dest_dir)/$(KERNEL_EXE).xclbin emulation: host xclbin export XCL_EMULATION_MODE=$(TARGET) emconfigutil --xdevice $(TARGET_DEVICE) --nd 1 cp prova1.angs rotamer_coords exclusions $(dest_dir) ./$(dest_dir)/$(HOST_EXE) -I $(dest_dir)/prova1.angs $(info Remeber to export XCL_EMULATION_MODE=$(TARGET) and run emcondigutil for emulation purposes) #sw_emu: host xclbin # export XCL_EMULATION_MODE=$(TARGET) # emconfigutil --xdevice $(TARGET_DEVICE) --nd 1 # #emconfigutil -f xilinx:adm-pcie-ku3:2ddr-xpr:4.0 --nd 1 #hw_emu: host xclbin # #add stuff to run build: host xclbin run_system: build ./$(dest_dir)/$(HOST_EXE) $(dest_dir)/$(KERNEL_EXE)
{ "content_hash": "f2a6b4b52d3c20349f73d786ad338b55", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 268, "avg_line_length": 30.48695652173913, "alnum_prop": 0.7162007986309185, "repo_name": "lorenzoditucci/sda_examples_aws", "id": "42e6b59fa4e0740eb5c7fee67c01ed794971ae10", "size": "4031", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "profax/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "87488" }, { "name": "C++", "bytes": "1276958" }, { "name": "HTML", "bytes": "520561" }, { "name": "Makefile", "bytes": "47817" }, { "name": "Objective-C", "bytes": "68047" }, { "name": "Python", "bytes": "84850" }, { "name": "Shell", "bytes": "7996" }, { "name": "Tcl", "bytes": "8616" } ], "symlink_target": "" }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Capsule : MonoBehaviour { public bool Assigned; public bool Landed; private void OnCollisionEnter(Collision other) { if (other.collider.tag == "Building" && !Landed) { if (other.collider.GetComponentInParent<Facility>() != null) { GameData.Instance.Capsules++; Destroy(gameObject); } } else if (other.collider.tag == "Terrain") { Landed = true; } } }
{ "content_hash": "947c9681c608dd6f7d6cf874d36d9034", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 23.96, "alnum_prop": 0.5542570951585977, "repo_name": "Aspekt1024/MazeOfAI", "id": "bb22c2241f3ed10f5175aa988e66d2cdb14b25a9", "size": "601", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/CoreGame/SpawnableObjects/Resrces/Capsule.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "118815" }, { "name": "GLSL", "bytes": "2059" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <Text xmlns="http://www.opentravel.org/OTM/Common/v2" language="en" textFormat="PlainText">Formatted text example.</Text>
{ "content_hash": "24a8d5af088f29d2f824d3e89c4a6267", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 121, "avg_line_length": 80.5, "alnum_prop": 0.7267080745341615, "repo_name": "OpenTravel-Forum-2016/otaforum-mock-content", "id": "2f320d445497f46bfc8d06bae5a6376a272773b6", "size": "161", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dmgriffin/pro_CompilerOutput/schemas/examples/Common_2_0_0/Text.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1143" } ], "symlink_target": "" }
from h2o.estimators.xgboost import * from tests import pyunit_utils def xgboost_insurance_poisson_small(): assert H2OXGBoostEstimator.available() # Import big dataset to ensure run across multiple nodes training_frame = h2o.import_file(pyunit_utils.locate("smalldata/testng/insurance_train1.csv")) test_frame = h2o.import_file(pyunit_utils.locate("smalldata/testng/insurance_validation1.csv")) x = ['District', 'Group', 'Age', 'Holders'] y = 'Claims' # Model with maximum of 2 trees model_2_trees = H2OXGBoostEstimator(training_frame=training_frame, learn_rate=0.1, max_depth=1, booster='gbtree', seed=1, ntrees=2, distribution='poisson'); model_2_trees.train(x=x, y=y, training_frame=training_frame) # check and make sure training frame column names and types info are returned correctly in model output pyunit_utils.assertModelColNamesTypesCorrect(model_2_trees._model_json["output"]["names"], model_2_trees._model_json["output"]["column_types"], ['District', 'Group', 'Age', 'Holders', 'Claims'],training_frame.types) prediction_2_trees = model_2_trees.predict(test_frame) assert prediction_2_trees.nrows == test_frame.nrows # Model with 10 trees model_10_trees = H2OXGBoostEstimator(training_frame=training_frame, learn_rate=0.1, max_depth=1, booster='gbtree', seed=1, ntrees=10, distribution='poisson') model_10_trees.train(x=x, y=y, training_frame=training_frame) prediction_10_trees = model_10_trees.predict(test_frame) assert prediction_10_trees.nrows == test_frame.nrows ## Mean square error on model with lower number of decision trees should be higher assert model_2_trees.mse() > model_10_trees.mse() if __name__ == "__main__": pyunit_utils.standalone_test(xgboost_insurance_poisson_small) else: xgboost_insurance_poisson_small()
{ "content_hash": "cfc35aa9ab5a9f5479550e0587b27ed2", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 120, "avg_line_length": 47, "alnum_prop": 0.6605640771895102, "repo_name": "h2oai/h2o-3", "id": "f24652951aebca0494ada74501fc14f2e313ac5e", "size": "2021", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "h2o-py/tests/testdir_algos/xgboost/pyunit_insurance_poisson_small.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "12803" }, { "name": "CSS", "bytes": "882321" }, { "name": "CoffeeScript", "bytes": "7550" }, { "name": "DIGITAL Command Language", "bytes": "106" }, { "name": "Dockerfile", "bytes": "10459" }, { "name": "Emacs Lisp", "bytes": "2226" }, { "name": "Groovy", "bytes": "205646" }, { "name": "HCL", "bytes": "36232" }, { "name": "HTML", "bytes": "8018117" }, { "name": "HiveQL", "bytes": "3985" }, { "name": "Java", "bytes": "15981357" }, { "name": "JavaScript", "bytes": "148426" }, { "name": "Jupyter Notebook", "bytes": "20638329" }, { "name": "Makefile", "bytes": "46043" }, { "name": "PHP", "bytes": "800" }, { "name": "Python", "bytes": "8188608" }, { "name": "R", "bytes": "4149977" }, { "name": "Ruby", "bytes": "64" }, { "name": "Sass", "bytes": "23790" }, { "name": "Scala", "bytes": "4845" }, { "name": "Shell", "bytes": "214495" }, { "name": "Smarty", "bytes": "1792" }, { "name": "TeX", "bytes": "554940" } ], "symlink_target": "" }
<?php namespace Doctrine\ORM\Query; /** * This class is used to generate DQL expressions via a set of PHP static functions * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @author Guilherme Blanco <guilhermeblanco@hotmail.com> * @author Jonathan Wage <jonwage@gmail.com> * @author Roman Borschel <roman@code-factory.org> * @author Benjamin Eberlei <kontakt@beberlei.de> * @todo Rename: ExpressionBuilder */ class Expr { /** * Creates a conjunction of the given boolean expressions. * * Example: * * [php] * // (u.type = ?1) AND (u.role = ?2) * $expr->andX('u.type = ?1', 'u.role = ?2')); * * @param mixed $x Optional clause. Defaults = null, but requires * at least one defined when converting to string. * @return Expr\Andx */ public function andX($x = null) { return new Expr\Andx(func_get_args()); } /** * Creates a disjunction of the given boolean expressions. * * Example: * * [php] * // (u.type = ?1) OR (u.role = ?2) * $q->where($q->expr()->orX('u.type = ?1', 'u.role = ?2')); * * @param mixed $x Optional clause. Defaults = null, but requires * at least one defined when converting to string. * @return Expr\Orx */ public function orX($x = null) { return new Expr\Orx(func_get_args()); } /** * Creates an ASCending order expression. * * @param $sort * @return OrderBy */ public function asc($expr) { return new Expr\OrderBy($expr, 'ASC'); } /** * Creates a DESCending order expression. * * @param $sort * @return OrderBy */ public function desc($expr) { return new Expr\OrderBy($expr, 'DESC'); } /** * Creates an equality comparison expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> = <right expr>. Example: * * [php] * // u.id = ?1 * $expr->eq('u.id', '?1'); * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Comparison */ public function eq($x, $y) { return new Expr\Comparison($x, Expr\Comparison::EQ, $y); } /** * Creates an instance of Expr\Comparison, with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> <> <right expr>. Example: * * [php] * // u.id <> ?1 * $q->where($q->expr()->neq('u.id', '?1')); * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Comparison */ public function neq($x, $y) { return new Expr\Comparison($x, Expr\Comparison::NEQ, $y); } /** * Creates an instance of Expr\Comparison, with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> < <right expr>. Example: * * [php] * // u.id < ?1 * $q->where($q->expr()->lt('u.id', '?1')); * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Comparison */ public function lt($x, $y) { return new Expr\Comparison($x, Expr\Comparison::LT, $y); } /** * Creates an instance of Expr\Comparison, with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> <= <right expr>. Example: * * [php] * // u.id <= ?1 * $q->where($q->expr()->lte('u.id', '?1')); * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Comparison */ public function lte($x, $y) { return new Expr\Comparison($x, Expr\Comparison::LTE, $y); } /** * Creates an instance of Expr\Comparison, with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> > <right expr>. Example: * * [php] * // u.id > ?1 * $q->where($q->expr()->gt('u.id', '?1')); * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Comparison */ public function gt($x, $y) { return new Expr\Comparison($x, Expr\Comparison::GT, $y); } /** * Creates an instance of Expr\Comparison, with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> >= <right expr>. Example: * * [php] * // u.id >= ?1 * $q->where($q->expr()->gte('u.id', '?1')); * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Comparison */ public function gte($x, $y) { return new Expr\Comparison($x, Expr\Comparison::GTE, $y); } /** * Creates an instance of AVG() function, with the given argument. * * @param mixed $x Argument to be used in AVG() function. * @return Expr\Func */ public function avg($x) { return new Expr\Func('AVG', array($x)); } /** * Creates an instance of MAX() function, with the given argument. * * @param mixed $x Argument to be used in MAX() function. * @return Expr\Func */ public function max($x) { return new Expr\Func('MAX', array($x)); } /** * Creates an instance of MIN() function, with the given argument. * * @param mixed $x Argument to be used in MIN() function. * @return Expr\Func */ public function min($x) { return new Expr\Func('MIN', array($x)); } /** * Creates an instance of COUNT() function, with the given argument. * * @param mixed $x Argument to be used in COUNT() function. * @return Expr\Func */ public function count($x) { return new Expr\Func('COUNT', array($x)); } /** * Creates an instance of COUNT(DISTINCT) function, with the given argument. * * @param mixed $x Argument to be used in COUNT(DISTINCT) function. * @return string */ public function countDistinct($x) { return 'COUNT(DISTINCT ' . implode(', ', func_get_args()) . ')'; } /** * Creates an instance of EXISTS() function, with the given DQL Subquery. * * @param mixed $subquery DQL Subquery to be used in EXISTS() function. * @return Expr\Func */ public function exists($subquery) { return new Expr\Func('EXISTS', array($subquery)); } /** * Creates an instance of ALL() function, with the given DQL Subquery. * * @param mixed $subquery DQL Subquery to be used in ALL() function. * @return Expr\Func */ public function all($subquery) { return new Expr\Func('ALL', array($subquery)); } /** * Creates a SOME() function expression with the given DQL subquery. * * @param mixed $subquery DQL Subquery to be used in SOME() function. * @return Expr\Func */ public function some($subquery) { return new Expr\Func('SOME', array($subquery)); } /** * Creates an ANY() function expression with the given DQL subquery. * * @param mixed $subquery DQL Subquery to be used in ANY() function. * @return Expr\Func */ public function any($subquery) { return new Expr\Func('ANY', array($subquery)); } /** * Creates a negation expression of the given restriction. * * @param mixed $restriction Restriction to be used in NOT() function. * @return Expr\Func */ public function not($restriction) { return new Expr\Func('NOT', array($restriction)); } /** * Creates an ABS() function expression with the given argument. * * @param mixed $x Argument to be used in ABS() function. * @return Expr\Func */ public function abs($x) { return new Expr\Func('ABS', array($x)); } /** * Creates a product mathematical expression with the given arguments. * * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> * <right expr>. Example: * * [php] * // u.salary * u.percentAnualSalaryIncrease * $q->expr()->prod('u.salary', 'u.percentAnualSalaryIncrease') * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Math */ public function prod($x, $y) { return new Expr\Math($x, '*', $y); } /** * Creates a difference mathematical expression with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> - <right expr>. Example: * * [php] * // u.monthlySubscriptionCount - 1 * $q->expr()->diff('u.monthlySubscriptionCount', '1') * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Math */ public function diff($x, $y) { return new Expr\Math($x, '-', $y); } /** * Creates a sum mathematical expression with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> + <right expr>. Example: * * [php] * // u.numChildren + 1 * $q->expr()->diff('u.numChildren', '1') * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Math */ public function sum($x, $y) { return new Expr\Math($x, '+', $y); } /** * Creates a quotient mathematical expression with the given arguments. * First argument is considered the left expression and the second is the right expression. * When converted to string, it will generated a <left expr> / <right expr>. Example: * * [php] * // u.total / u.period * $expr->quot('u.total', 'u.period') * * @param mixed $x Left expression * @param mixed $y Right expression * @return Expr\Math */ public function quot($x, $y) { return new Expr\Math($x, '/', $y); } /** * Creates a SQRT() function expression with the given argument. * * @param mixed $x Argument to be used in SQRT() function. * @return Expr\Func */ public function sqrt($x) { return new Expr\Func('SQRT', array($x)); } /** * Creates an IN() expression with the given arguments. * * @param string $x Field in string format to be restricted by IN() function * @param mixed $y Argument to be used in IN() function. * @return Expr\Func */ public function in($x, $y) { if (is_array($y)) { foreach ($y as &$literal) { if ( ! ($literal instanceof Expr\Literal)) { $literal = $this->_quoteLiteral($literal); } } } return new Expr\Func($x . ' IN', (array) $y); } /** * Creates a NOT IN() expression with the given arguments. * * @param string $x Field in string format to be restricted by NOT IN() function * @param mixed $y Argument to be used in NOT IN() function. * @return Expr\Func */ public function notIn($x, $y) { if (is_array($y)) { foreach ($y as &$literal) { if ( ! ($literal instanceof Expr\Literal)) { $literal = $this->_quoteLiteral($literal); } } } return new Expr\Func($x . ' NOT IN', (array) $y); } /** * Creates an IS NULL expression with the given arguments. * * @param string $x Field in string format to be restricted by IS NULL * @return string */ public function isNull($x) { return $x . ' IS NULL'; } /** * Creates an IS NOT NULL expression with the given arguments. * * @param string $x Field in string format to be restricted by IS NOT NULL * @return string */ public function isNotNull($x) { return $x . ' IS NOT NULL'; } /** * Creates a LIKE() comparison expression with the given arguments. * * @param string $x Field in string format to be inspected by LIKE() comparison. * @param mixed $y Argument to be used in LIKE() comparison. * @return Expr\Comparison */ public function like($x, $y) { return new Expr\Comparison($x, 'LIKE', $y); } /** * Creates a CONCAT() function expression with the given arguments. * * @param mixed $x First argument to be used in CONCAT() function. * @param mixed $x Second argument to be used in CONCAT() function. * @return Expr\Func */ public function concat($x, $y) { return new Expr\Func('CONCAT', array($x, $y)); } /** * Creates a SUBSTRING() function expression with the given arguments. * * @param mixed $x Argument to be used as string to be cropped by SUBSTRING() function. * @param integer $from Initial offset to start cropping string. May accept negative values. * @param integer $len Length of crop. May accept negative values. * @return Expr\Func */ public function substring($x, $from, $len = null) { $args = array($x, $from); if (null !== $len) { $args[] = $len; } return new Expr\Func('SUBSTRING', $args); } /** * Creates a LOWER() function expression with the given argument. * * @param mixed $x Argument to be used in LOWER() function. * @return Expr\Func A LOWER function expression. */ public function lower($x) { return new Expr\Func('LOWER', array($x)); } /** * Creates an UPPER() function expression with the given argument. * * @param mixed $x Argument to be used in UPPER() function. * @return Expr\Func An UPPER function expression. */ public function upper($x) { return new Expr\Func('UPPER', array($x)); } /** * Creates a LENGTH() function expression with the given argument. * * @param mixed $x Argument to be used as argument of LENGTH() function. * @return Expr\Func A LENGTH function expression. */ public function length($x) { return new Expr\Func('LENGTH', array($x)); } /** * Creates a literal expression of the given argument. * * @param mixed $literal Argument to be converted to literal. * @return Expr\Literal */ public function literal($literal) { return new Expr\Literal($this->_quoteLiteral($literal)); } /** * Quotes a literal value, if necessary, according to the DQL syntax. * * @param mixed $literal The literal value. * @return string */ private function _quoteLiteral($literal) { if (is_numeric($literal) && !is_string($literal)) { return (string) $literal; } else { return "'" . str_replace("'", "''", $literal) . "'"; } } /** * Creates an instance of BETWEEN() function, with the given argument. * * @param mixed $val Valued to be inspected by range values. * @param integer $x Starting range value to be used in BETWEEN() function. * @param integer $y End point value to be used in BETWEEN() function. * @return Expr\Func A BETWEEN expression. */ public function between($val, $x, $y) { return $val . ' BETWEEN ' . $x . ' AND ' . $y; } /** * Creates an instance of TRIM() function, with the given argument. * * @param mixed $x Argument to be used as argument of TRIM() function. * @return Expr\Func a TRIM expression. */ public function trim($x) { return new Expr\Func('TRIM', $x); } }
{ "content_hash": "3d4a72267310754fb58ed86618d368ba", "timestamp": "", "source": "github", "line_count": 575, "max_line_length": 96, "avg_line_length": 30.321739130434782, "alnum_prop": 0.5501577287066246, "repo_name": "krishcdbry/z-zangura", "id": "877ef1025cdb7d9abc4df0cec32bb49beb4cd692", "size": "18425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/libraries/Doctrine/ORM/Query/Expr.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "474" }, { "name": "CSS", "bytes": "30948" }, { "name": "HTML", "bytes": "5396471" }, { "name": "JavaScript", "bytes": "59592" }, { "name": "PHP", "bytes": "4357353" } ], "symlink_target": "" }