code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php namespace Backend\Modules\Kwaliteitslabels\Ajax; use Backend\Core\Engine\Base\AjaxAction; use Backend\Modules\Kwaliteitslabels\Engine\Model as BackendKwaliteitslabelsModel; /** * Alters the sequence of Kwaliteitslabels articles * * @author Stijn Schets <stijn@schetss.be> */ class SequenceCategories extends AjaxAction { public function execute() { parent::execute(); // get parameters $newIdSequence = trim(\SpoonFilter::getPostValue('new_id_sequence', null, '', 'string')); // list id $ids = (array) explode(',', rtrim($newIdSequence, ',')); // loop id's and set new sequence foreach ($ids as $i => $id) { $item['id'] = $id; $item['sequence'] = $i + 1; // update sequence if (BackendKwaliteitslabelsModel::existsCategory($id)) { BackendKwaliteitslabelsModel::updateCategory($item); } } // success output $this->output(self::OK, null, 'sequence updated'); } }
Schetss/CarCor
src/Backend/Modules/Kwaliteitslabels/Ajax/SequenceCategories.php
PHP
mit
1,047
using Tweetinvi.Core.Controllers; using Tweetinvi.Core.Iterators; using Tweetinvi.Core.Web; using Tweetinvi.Models; using Tweetinvi.Models.DTO; using Tweetinvi.Parameters; namespace Tweetinvi.Controllers.Timeline { public class TimelineController : ITimelineController { private readonly ITimelineQueryExecutor _timelineQueryExecutor; private readonly IPageCursorIteratorFactories _pageCursorIteratorFactories; public TimelineController(ITimelineQueryExecutor timelineQueryExecutor, IPageCursorIteratorFactories pageCursorIteratorFactories) { _timelineQueryExecutor = timelineQueryExecutor; _pageCursorIteratorFactories = pageCursorIteratorFactories; } // Home Timeline public ITwitterPageIterator<ITwitterResult<ITweetDTO[]>, long?> GetHomeTimelineIterator(IGetHomeTimelineParameters parameters, ITwitterRequest request) { return _pageCursorIteratorFactories.Create(parameters, cursor => { var cursoredParameters = new GetHomeTimelineParameters(parameters) { MaxId = cursor }; return _timelineQueryExecutor.GetHomeTimelineAsync(cursoredParameters, new TwitterRequest(request)); }); } public ITwitterPageIterator<ITwitterResult<ITweetDTO[]>, long?> GetUserTimelineIterator(IGetUserTimelineParameters parameters, ITwitterRequest request) { return _pageCursorIteratorFactories.Create(parameters, cursor => { var cursoredParameters = new GetUserTimelineParameters(parameters) { MaxId = cursor }; return _timelineQueryExecutor.GetUserTimelineAsync(cursoredParameters, new TwitterRequest(request)); }); } public ITwitterPageIterator<ITwitterResult<ITweetDTO[]>, long?> GetMentionsTimelineIterator(IGetMentionsTimelineParameters parameters, ITwitterRequest request) { return _pageCursorIteratorFactories.Create(parameters, cursor => { var cursoredParameters = new GetMentionsTimelineParameters(parameters) { MaxId = cursor }; return _timelineQueryExecutor.GetMentionsTimelineAsync(cursoredParameters, new TwitterRequest(request)); }); } public ITwitterPageIterator<ITwitterResult<ITweetDTO[]>, long?> GetRetweetsOfMeTimelineIterator(IGetRetweetsOfMeTimelineParameters parameters, ITwitterRequest request) { return _pageCursorIteratorFactories.Create(parameters, cursor => { var cursoredParameters = new GetRetweetsOfMeTimelineParameters(parameters) { MaxId = cursor }; return _timelineQueryExecutor.GetRetweetsOfMeTimelineAsync(cursoredParameters, new TwitterRequest(request)); }); } } }
linvi/tweetinvi
src/Tweetinvi.Controllers/Timeline/TimelineController.cs
C#
mit
3,067
class DashboardController < ApplicationController respond_to :html def index @groups = Group.where(id: current_user.projects.pluck(:group_id)) @projects = current_user.projects_with_events @projects = @projects.page(params[:page]).per(20) @events = Event.in_projects(current_user.project_ids).limit(20).offset(params[:offset] || 0) @last_push = current_user.recent_push respond_to do |format| format.html format.js format.atom { render layout: false } end end # Get authored or assigned open merge requests def merge_requests @projects = current_user.projects.all @merge_requests = current_user.cared_merge_requests.recent.page(params[:page]).per(20) end # Get only assigned issues def issues @projects = current_user.projects.all @user = current_user @issues = current_user.assigned_issues.opened.recent.page(params[:page]).per(20) @issues = @issues.includes(:author, :project) respond_to do |format| format.html format.atom { render layout: false } end end end
robbkidd/gitlabhq
app/controllers/dashboard_controller.rb
Ruby
mit
1,079
#include <iostream> #include <vector> #include <string> #include <sstream> #include <set> #include <algorithm> //std::vector<std::string> parseCommand(std::string input); //std::vector<int> parseArray(std::string input); //void exchange(int index, std::vector<int> & numbers); //void printNumbersInArrayFormat(std::vector<int> & numbers); //void findMinMaxEvenOdd(std::vector<std::string> & commandParts,std::vector<int> & numbers); //void findFirstLastEvenOddNumbers(std::vector<std::string>& commandParts, std::vector<int> numbers); // std::vector<int> parseArray(std::string input) { std::vector<int> values; int n; std::stringstream stream(input); while (stream >> n) { values.push_back(n); } return values; } std::vector<std::string> parseCommand(std::string input) { std::vector<std::string> values; std::string n; std::stringstream stream(input); while (stream >> n) { values.push_back(n); } return values; } void printNumbersInArrayFormat(std::vector<int> & numbers) { std::cout << "["; int indexLastElement = numbers.size() - 1; int currentIndex = 0; for (std::vector<int>::iterator iterator = numbers.begin(); iterator != numbers.end(); iterator++, currentIndex++) { if (currentIndex == indexLastElement) { std::cout << *iterator; } else { std::cout << *iterator << ", "; } } std::cout << "]" << std::endl; } void findMinMaxEvenOdd(std::vector<std::string>& commandParts, std::vector<int>& numbers) { if (numbers.size() == 0) { std::cout << "No matches" << std::endl; } std::vector<int>::iterator iter = numbers.begin(); int indexOfMin = 0; int indexOfMax = 0; int currentMin = 10000; int currentMax = -1; bool isEven = commandParts[1] == "even"; int currentIndex = 0; for (; iter != numbers.end(); iter++, currentIndex++) { if (currentMin >= *iter) { if (isEven && *iter % 2 == 0) { currentMin = *iter; indexOfMin = currentIndex; } else if (!isEven && *iter % 2 == 1) { currentMin = *iter; indexOfMin = currentIndex; } } if (currentMax <= *iter) { if (isEven && *iter % 2 == 0) { currentMax = *iter; indexOfMax = currentIndex; } else if (!isEven && *iter % 2 == 1) { currentMax = *iter; indexOfMax = currentIndex; } } } if (commandParts[0] == "min") { if (currentMin == 10000) { std::cout << "No matches" << std::endl; } else { std::cout << indexOfMin << std::endl; } } else { if (currentMax == -1) { std::cout << "No matches" << std::endl; } else { std::cout << indexOfMax << std::endl; } } } void findFirstLastEvenOddNumbers(std::vector<std::string>& commandParts, std::vector<int> numbers) { std::vector<int> result; std::vector<int>::iterator begin; std::vector<int>::iterator end; bool isFirst = commandParts[0] == "first"; bool isEven = commandParts[2] == "even"; int count = stoi(commandParts[1]); if (numbers.size() < count) { std::cout << "Invalid count" << std::endl; return; } // wrong logic; if (isFirst) { begin = numbers.begin(); end = numbers.end(); } else { begin = numbers.end(); begin--; end = numbers.begin(); } for (; begin != end && numbers.size() > 1;) { if (count == result.size()) { break; } if (isEven && *begin % 2 == 0) { result.push_back(*begin); } else if (!isEven && *begin % 2 == 1) { result.push_back(*begin); } if (isFirst) { begin++; } else { begin--; if (count == result.size()) { break; } if (begin == end && !isEven && *begin % 2 == 1) { result.push_back(*begin); if (!isFirst) { std::reverse(result.begin(), result.end()); } printNumbersInArrayFormat(result); return; } } } if (!isFirst) { std::reverse(result.begin(), result.end()); } printNumbersInArrayFormat(result); } void exchange(int index, std::vector<int> & numbers) { if (index >= numbers.size()) { std::cout << "Invalid index" << std::endl; return; } if (index == numbers.size() - 1 && numbers.size() > 0) { return; } std::vector<int> newNumbers; for (int i = index + 1; i < numbers.size(); i++) { newNumbers.push_back(numbers[i]); } for (int i = 0; i <= index; i++) { newNumbers.push_back(numbers[i]); } numbers = newNumbers; } int main() { std::string input; std::getline(std::cin, input); std::vector<int> numbers = parseArray(input); while (true) { std::getline(std::cin, input); std::vector<std::string> commandParts = parseCommand(input); if (commandParts[0] == "end") { break; } else if (commandParts[0] == "exchange") { exchange(std::stoi(commandParts[1]), numbers); } else if (commandParts[0] == "min" || commandParts[0] == "max") { findMinMaxEvenOdd(commandParts, numbers); } else if (commandParts[0] == "first" || commandParts[0] == "last") { findFirstLastEvenOddNumbers(commandParts, numbers); } } printNumbersInArrayFormat(numbers); return 0; }
M-Yankov/CPlusPlus
10.ExamPreparation/ArrayManipulator11October2015/Source.cpp
C++
mit
6,155
var $ = require('jquery'); var layout = module.exports = { init: function() { $('#toggle-sidebar').click(function(e) { e.preventDefault(); layout.sidebar(); }); $('#toggle-overlay').click(function(e) { e.preventDefault(); layout.overlay(); }); }, restore: function() { return this; }, overlay: function(b) { if( typeof b !== 'boolean' ) b = !$('body > .panel').hasClass('overlay'); if( b ) $('body > .panel').addClass('overlay'), $('#toggle-overlay').html('<i class="fa fa-compress"></i>'); else $('body > .panel').removeClass('overlay'), $('#toggle-overlay').html('<i class="fa fa-expand"></i>'); return this; }, sidebar: function(b) { if( typeof b !== 'boolean' ) b = !$('body > .panel').hasClass('sidebar-open'); if( b ) $('body > .panel').addClass('sidebar-open'); else $('body > .panel').removeClass('sidebar-open'); return this; }, fullsize: function(b) { if( typeof b !== 'boolean' ) b = !$('#page').hasClass('fullsize'); if( b ) $('#page').addClass('fullsize'); else $('#page').removeClass('fullsize'); return this; }, dark: function(b) { if( typeof b !== 'boolean' ) b = !$('#page').hasClass('dark'); if( b ) $('#page, header > .utilities').addClass('dark'); else $('#page, header > .utilities').removeClass('dark'); return this; }, gnb: { select: function(url) { $('.gnb > a').each(function() { var el = $(this); if( el.attr('href') === url ) el.addClass('active'); else el.removeClass('active'); }); return this; } } };
joje6/three-cats
www/js/layout.js
JavaScript
mit
1,624
// *********************************************************************** // Copyright (c) 2017 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if PLATFORM_DETECTION using System; using System.Runtime.Serialization; namespace NUnit.Framework.Internal { /// <summary> /// InvalidPlatformException is thrown when the platform name supplied /// to a test is not recognized. /// </summary> [Serializable] class InvalidPlatformException : ArgumentException { /// <summary> /// Instantiates a new instance of the <see cref="InvalidPlatformException"/> class. /// </summary> public InvalidPlatformException() : base() { } /// <summary> /// Instantiates a new instance of the <see cref="InvalidPlatformException"/> class /// </summary> /// <param name="message">The message.</param> public InvalidPlatformException(string message) : base(message) { } /// <summary> /// Instantiates a new instance of the <see cref="InvalidPlatformException"/> class /// </summary> /// <param name="message">The message.</param> /// <param name="inner">The inner.</param> public InvalidPlatformException(string message, Exception inner) : base(message, inner) { } #if !NETSTANDARD1_6 /// <summary> /// Serialization constructor for the <see cref="InvalidPlatformException"/> class /// </summary> protected InvalidPlatformException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } } #endif
jadarnel27/nunit
src/NUnitFramework/framework/Internal/InvalidPlatformException.cs
C#
mit
2,741
package com.nodlee.theogony.ui.adapter; import android.view.View; public interface ItemClickedListener { /** * 在单元格被点击的时候调用 * * @param position */ void onItemClicked(View view, int position); }
VernonLee/Theogony
app/src/main/java/com/nodlee/theogony/ui/adapter/ItemClickedListener.java
Java
mit
247
<?php /** * TOP API: taobao.media.file.delete request * * @author auto create * @since 1.0, 2014-09-13 16:51:05 */ class MediaFileDeleteRequest { /** * 接入多媒体平台的业务code 每个应用有一个特有的业务code **/ private $bizCode; /** * 文件ID字符串,可以一个也可以一组,用英文逗号间隔,如450,120,155 **/ private $fileIds; private $apiParas = array(); public function setBizCode($bizCode) { $this->bizCode = $bizCode; $this->apiParas["biz_code"] = $bizCode; } public function getBizCode() { return $this->bizCode; } public function setFileIds($fileIds) { $this->fileIds = $fileIds; $this->apiParas["file_ids"] = $fileIds; } public function getFileIds() { return $this->fileIds; } public function getApiMethodName() { return "taobao.media.file.delete"; } public function getApiParas() { return $this->apiParas; } public function check() { RequestCheckUtil::checkNotNull($this->bizCode,"bizCode"); RequestCheckUtil::checkNotNull($this->fileIds,"fileIds"); RequestCheckUtil::checkMaxListSize($this->fileIds,50,"fileIds"); } public function putOtherTextParam($key, $value) { $this->apiParas[$key] = $value; $this->$key = $value; } }
zhangbobell/mallshop
plugins/onekey/taobao/top/request/MediaFileDeleteRequest.php
PHP
mit
1,256
<div class="content"> <h2><?php echo $title;?></h2> <div class="panel panel-default"> <div class="panel-heading"> <b>The following is the list of various seed certification charges of Punjab State Certification Authorityu as applicable from Rabi-2004-05</b> </div> <div class="panel-body text-left"> <table class="table table-bordered"> <thead> <tr> <th class="text-center">S.No.</th> <th class="text-center">Name of the item</th> <th class="text-center">Rates(Rs.)</th> </tr> </thead> <tbody> <?php $sno = 1; ?> <tr> <td><?php echo $sno++;?></td> <td>Application Fee</td> <td>25.00 per grower per season</td> </tr> <tr> <td><?php echo $sno++;?></td> <td> Inspection Fee <ol style="list-style-type: upper-alpha"> <li>Self Pollinated Crops</li> <li>Cross Pollinated Crops / Often Cross Pollinated Crops</li> <li>Hybrids / Vegetables</li> </ol> </td> <td><br> 375 / hectare<br> 450 / hectare<br> 750 / hectare<br> </td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Re-Inspection Fee</td> <td>As inspection fee</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Seed Processing Supervision Fee</td> <td> 5.00 per quintal <ol style="list-style-type: upper-alpha"> <li>3.00 per quintal at the time of sampling</li> <li>2.00 per quintal at the time of packing</li> </ol> </td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Re-processing / Re-cleaning / Re-bagging etc.</td> <td>5.00 per quintal</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Sample Testing Fee</td> <td>25.00 per sample</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Grow-Out Test Fee</td> <td>200.00 per sample</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Validation Fee</td> <td> 8.00 per quintal plus cost of tag and seal <ol style="list-style-type: upper-alpha"> <li>3.00 per quintal at the time of sampling</li> <li>5.00 per quintal plus cos of tag and seal at the time of final validation</li> </ol> </td> </tr> <tr> <td><?php echo $sno++;?></td> <td> Tag Charges <ol style="list-style-type: upper-alpha"> <li>Certified Tag (blue color)</li> <li>Foundation Tag (white color)</li> </ol> </td> <td><br> 25.50 per tag<br> 4.00 per tag<br> </td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Seal Charges</td> <td>0.20 per seal</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Regiestration of Processing Plant</td> <td>1000.00 per plant</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Renewal of Processing Plant</td> <td>500.00 per plant per year</td> </tr> <tr> <td><?php echo $sno++;?></td> <td colspan="2">The cost of tags for the seeds graded and cleared from the laboratory but not packed shall be recovered from the producing organization on per acre packing basis.</td> </tr> <tr> <td class="text-center" colspan="3"> NOTE - SERVICE TAX WILL BE CHARGED EXTRA </td> </tr> </tbody> </table> </div> </div> </div>
puneetarora2000/BiS-conformance-
application/views/front/fees.php
PHP
mit
3,364
package com.wt.studio.plugin.pagedesigner.gef.figure; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.FrameBorder; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.PositionConstants; import org.eclipse.draw2d.SchemeBorder; import org.eclipse.draw2d.TitleBarBorder; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.graphics.Color; public class FormFrameBorder extends FrameBorder { protected void createBorders() { inner = new HorizontalBlockTitleBarBorder(); outer = new SchemeBorder(SCHEME_FRAME); } } class HorizontalBlockTitleBarBorder extends TitleBarBorder { Color orange = new Color(null, 211, 211, 211); private Insets padding = new Insets(2, 3, 2, 3); public void paint(IFigure figure, Graphics g, Insets insets) { tempRect.setBounds(getPaintRectangle(figure, insets)); Rectangle rec = tempRect; rec.height = Math.min(rec.height, getTextExtents(figure).height + padding.getHeight()); g.clipRect(rec); g.setBackgroundColor(orange); g.fillRectangle(rec); int x = rec.x + padding.left; int y = rec.y + padding.top; int textWidth = getTextExtents(figure).width; int freeSpace = rec.width - padding.getWidth() - textWidth; if (getTextAlignment() == PositionConstants.CENTER) freeSpace /= 2; if (getTextAlignment() != PositionConstants.LEFT) x += freeSpace; g.setFont(getFont(figure)); g.setForegroundColor(ColorConstants.black); g.drawString(getLabel(), x, y); } }
winture/wt-studio
com.wt.studio.plugin.modeldesigner/src/com/wt/studio/plugin/pagedesigner/gef/figure/FormFrameBorder.java
Java
mit
1,556
namespace Deldysoft.Foundation.CommandHandling { public interface ICommandExecuter { void Execute<T>(T command); } }
geekhubdk/geekhub
Deldysoft.Foundation/CommandHandling/ICommandExecuter.cs
C#
mit
139
require 'spec_helper' require 'rddd/authorization/rule' describe Rddd::Authorization::Rule do let(:action) { :foo } let(:block) { lambda { |user, params| true } } let(:authorize) do Rddd::Authorization::Rule.new( action, &block ) end describe 'should raise if rule block is invalid' do let(:block) { lambda { |user| true } } it { expect { authorize }.to raise_exception Rddd::Authorization::Rule::InvalidEvaluationBlock } end describe '#is_for?' do subject { authorize.is_for?(questioned_action) } context 'matching action' do let(:questioned_action) { :foo } it { should be_true } end context 'not matching action' do let(:questioned_action) { :bar } it { should be_false } end end describe '#can?' do let(:user) { stub('user, params') } let(:params) { stub('user, params') } subject { authorize.can?(user, params) } describe 'passing right params to block' do before do block.expects(:call).with(user, params).returns(false) end it { should be_false } end it 'should return true as lambda does' do should be_true end end end
petrjanda/rddd
spec/lib/authorization/rule_spec.rb
Ruby
mit
1,195
import os,sys #import ez_setup #ez_setup.use_setuptools() from setuptools import setup, find_packages import numpy from Cython.Build import cythonize # not compatible with distribute #from distutils.extension import Extension #from Cython.Distutils import build_ext version = '0.7.0' README = os.path.join(os.path.dirname(__file__), 'README') long_description = open(README).read() + '\n\n' classifiers = """\ Development Status :: 4 - Beta Environment :: Console Intended Audience :: Science/Research License :: OSI Approved :: MIT License Topic :: Scientific/Engineering :: Bio-Informatics Programming Language :: Python Operating System :: Unix """ entry_points = """ [console_scripts] seqview = seqtool.frontend.command:seqview get_genbank = seqtool.frontend.command:get_genbank geneview = seqtool.frontend.command:geneview tssview = seqtool.frontend.command:tssview primers = seqtool.frontend.command:primers sequencing = seqtool.frontend.command:sequencing seqtooldb = seqtool.db:seqdb_command abiview = seqtool.frontend.command:abiview convert_bs = seqtool.bowtie.convert_bs:main virtualpcr = seqtool.bowtie.virtualpcr:main primer = seqtool.nucleotide.primer:main probe = seqtool.nucleotide.primer:probe bsa_figure = seqtool.script.bsa_figure:main pdesign = seqtool.script.pdesign:main bisulfite = seqtool.script.bisulfite:main rpm = seqtool.script.cf:main translate = seqtool.script.translate:main server = seqtool.server.server:main """ setup( name='seqtool', version=version, description=("small scripts visualizing PCR products for molecular biology experimetnts."), classifiers = filter(None, classifiers.split("\n")), keywords='pcr biology bisulfite', author='mizuy', author_email='mizugy@gmail.com', url='http://github.com/mizuy/seqtool', license='MIT', packages=find_packages(), install_requires=['biopython','numpy', 'sqlalchemy', 'cython', 'appdirs', 'mysql-connector-python'], test_suite='nose.collector', ext_modules = cythonize('seqtool/seqtool/nucleotide/sw_c.pyx'), include_dirs = [numpy.get_include()], entry_points=entry_points )
mizuy/seqtool
setup.py
Python
mit
2,123
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Abc.Zebus.Routing { public class BindingKeyPredicateBuilder : IBindingKeyPredicateBuilder { private static readonly MethodInfo _toStringMethod = typeof(object).GetMethod("ToString"); private static readonly MethodInfo _toStringWithFormatMethod = typeof(IConvertible).GetMethod("ToString"); private readonly ConcurrentDictionary<Type, CacheItem> _cacheItems = new ConcurrentDictionary<Type, CacheItem>(); class CacheItem { public ParameterExpression ParameterExpression { get; set; } public IList<MethodCallExpression> MembersToStringExpressions { get; set; } } public Func<IMessage, bool> GetPredicate(Type messageType, BindingKey bindingKey) { if (bindingKey.IsEmpty) return _ => true; var cacheItem = GetOrCreateCacheItem(messageType); var count = Math.Min(cacheItem.MembersToStringExpressions.Count, bindingKey.PartCount); var subPredicates = new List<Expression>(); for (var index = 0; index < count; index++) { if (bindingKey.IsSharp(index)) break; if (bindingKey.IsStar(index)) continue; var part = bindingKey.GetPart(index); var memberToStringExpression = cacheItem.MembersToStringExpressions[index]; subPredicates.Add(Expression.MakeBinary(ExpressionType.Equal, memberToStringExpression, Expression.Constant(part))); } if (!subPredicates.Any()) return _ => true; var finalExpression = subPredicates.Aggregate((Expression)null, (final, exp) => final == null ? exp : Expression.AndAlso(final, exp)); return (Func<IMessage, bool>)Expression.Lambda(finalExpression, cacheItem.ParameterExpression).Compile(); } private CacheItem GetOrCreateCacheItem(Type messageType) { return _cacheItems.GetOrAdd(messageType, type => { var routingMembers = type.GetMembers(BindingFlags.Public | BindingFlags.Instance) .Select(x => new MemberExtendedInfo { Member = x, Attribute = x.GetCustomAttribute<RoutingPositionAttribute>(true) }) .Where(x => x.Attribute != null) .OrderBy(x => x.Attribute.Position) .ToList(); var parameterExpression = Expression.Parameter(typeof(IMessage), "m"); var castedMessage = Expression.Convert(parameterExpression, messageType); return new CacheItem { ParameterExpression = parameterExpression, MembersToStringExpressions = routingMembers.Select(x => GenerateMemberToStringExpression(castedMessage, x)).ToList() }; }); } private static MethodCallExpression GenerateMemberToStringExpression(Expression parameterExpression, MemberExtendedInfo memberExtendedInfo) { Func<Expression, Expression> memberAccessor; Type memberType; var memberInfo = memberExtendedInfo.Member; if (memberInfo.MemberType == MemberTypes.Property) { var propertyInfo = (PropertyInfo)memberInfo; memberAccessor = m => Expression.Property(m, propertyInfo); memberType = propertyInfo.PropertyType; } else if (memberInfo.MemberType == MemberTypes.Field) { var fieldInfo = (FieldInfo)memberInfo; memberAccessor = m => Expression.Field(m, fieldInfo); memberType = fieldInfo.FieldType; } else throw new InvalidOperationException("Cannot define routing position on a member other than a field or property"); var getMemberValue = typeof(IConvertible).IsAssignableFrom(memberType) && memberType != typeof(string) ? Expression.Call(memberAccessor(parameterExpression), _toStringWithFormatMethod, Expression.Constant(CultureInfo.InvariantCulture)) : Expression.Call(memberAccessor(parameterExpression), _toStringMethod); return getMemberValue; } } public class MemberExtendedInfo { public MemberInfo Member { get; set; } public RoutingPositionAttribute Attribute { get; set; } } }
biarne-a/Zebus
src/Abc.Zebus/Routing/BindingKeyPredicateBuilder.cs
C#
mit
4,768
var a = createElement("a"); attr(a, 'href', ""); function anchor(label, href) { var element = createElement(a); attr(element, "href", label); if (isString(label)) { text(element, label); } else { appendChild(element, label); } onclick(element, function (event) { if (/^\w+\:/.test(href)) return; event.preventDefault(); go(href); }); return element; }
yunxu1019/efront
coms/zimoli/anchor.js
JavaScript
mit
423
'use strict'; /** * Module Dependencies */ var config = require('../config/config'); var _ = require('lodash'); var Twit = require('twit'); var async = require('async'); var debug = require('debug')('skeleton'); // https://github.com/visionmedia/debug var graph = require('fbgraph'); var tumblr = require('tumblr.js'); var Github = require('github-api'); var stripe = require('stripe')(config.stripe.key); var twilio = require('twilio')(config.twilio.sid, config.twilio.token); var paypal = require('paypal-rest-sdk'); var cheerio = require('cheerio'); // https://github.com/cheeriojs/cheerio var request = require('request'); // https://github.com/mikeal/request var passport = require('passport'); var foursquare = require('node-foursquare')({ secrets: config.foursquare }); var LastFmNode = require('lastfm').LastFmNode; var querystring = require('querystring'); var passportConf = require('../config/passport'); /** * API Controller */ module.exports.controller = function (app) { /** * GET /api* * *ALL* api routes must be authenticated first */ app.all('/api*', passportConf.isAuthenticated); /** * GET /api * List of API examples. */ // app.get('/api', function (req, res) { // res.render('api/index', { // url: req.url // }); // }); /** * GET /api/react * React examples */ app.get('/api/react', function (req, res) { res.render('api/react', { url: req.url }); }); /** * GET /creditcard * Credit Card Form Example. */ app.get('/api/creditcard', function (req, res) { res.render('api/creditcard', { url: req.url }); }); /** * GET /api/lastfm * Last.fm API example. */ app.get('/api/lastfm', function (req, res, next) { var lastfm = new LastFmNode(config.lastfm); async.parallel({ artistInfo: function (done) { lastfm.request('artist.getInfo', { artist: 'Morcheeba', handlers: { success: function (data) { done(null, data); }, error: function (err) { done(err); } } }); }, artistTopAlbums: function (done) { lastfm.request('artist.getTopAlbums', { artist: 'Morcheeba', handlers: { success: function (data) { var albums = []; _.forEach(data.topalbums.album, function (album) { albums.push(album.image.slice(-1)[0]['#text']); }); done(null, albums.slice(0, 4)); }, error: function (err) { done(err); } } }); } }, function (err, results) { if (err) { return next(err.message); } var artist = { name: results.artistInfo.artist.name, image: results.artistInfo.artist.image.slice(-1)[0]['#text'], tags: results.artistInfo.artist.tags.tag, bio: results.artistInfo.artist.bio.summary, stats: results.artistInfo.artist.stats, similar: results.artistInfo.artist.similar.artist, topAlbums: results.artistTopAlbums }; res.render('api/lastfm', { artist: artist, url: '/apiopen' }); }); }); /** * GET /api/nyt * New York Times API example. */ app.get('/api/nyt', function (req, res, next) { var query = querystring.stringify({ 'api-key': config.nyt.key, 'list-name': 'young-adult' }); var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query; request.get(url, function (error, request, body) { if (request.statusCode === 403) { return next(error('Missing or Invalid New York Times API Key')); } var bestsellers = {}; // NYT occasionally sends bad data :( try { bestsellers = JSON.parse(body); } catch (err) { bestsellers.results = ''; req.flash('error', { msg: err.message }); } res.render('api/nyt', { url: '/apiopen', books: bestsellers.results }); }); }); /** * GET /api/paypal * PayPal SDK example. */ app.get('/api/paypal', function (req, res, next) { paypal.configure(config.paypal); var payment_details = { intent: 'sale', payer: { payment_method: 'paypal' }, redirect_urls: { return_url: config.paypal.returnUrl, cancel_url: config.paypal.cancelUrl }, transactions: [ { description: 'ITEM: Something Awesome!', amount: { currency: 'USD', total: '2.99' } } ] }; paypal.payment.create(payment_details, function (error, payment) { if (error) { // TODO FIXME console.log(error); } else { req.session.payment_id = payment.id; var links = payment.links; for (var i = 0; i < links.length; i++) { if (links[i].rel === 'approval_url') { res.render('api/paypal', { url: '/apilocked', approval_url: links[i].href }); } } } }); }); /** * GET /api/paypal/success * PayPal SDK example. */ app.get('/api/paypal/success', function (req, res, next) { var payment_id = req.session.payment_id; var payment_details = { payer_id: req.query.PayerID }; paypal.payment.execute(payment_id, payment_details, function (error, payment) { if (error) { res.render('api/paypal', { url: req.url, result: true, success: false }); } else { res.render('api/paypal', { url: '/apilocked', result: true, success: true }); } }); }); /** * GET /api/paypal/cancel * PayPal SDK example. */ app.get('/api/paypal/cancel', function (req, res, next) { req.session.payment_id = null; res.render('api/paypal', { url: '/apilocked', result: true, canceled: true }); }); /** * GET /api/scraping * Web scraping example using Cheerio library. */ app.get('/api/scraping', function (req, res, next) { request.get({ url: 'https://news.ycombinator.com/', timeout: 3000 }, function (err, response, body) { if (!err && response.statusCode === 200) { var $ = cheerio.load(body); // Get Articles var links = []; $('.title a[href^="http"], .title a[href^="https"], .title a[href^="item"]').each(function () { if ($(this).text() !== 'scribd') { if ($(this).text() !== 'Bugs') { links.push($(this)); } } }); // Get Comments var comments = []; $('.subtext a[href^="item"]').each(function () { comments.push('<a href="https://news.ycombinator.com/' + $(this).attr('href') + '">' + $(this).text() + '</a>'); }); // Render Page res.render('api/scraping', { url: '/apiopen', links: links, comments: comments }); } else { req.flash('error', { msg: 'Sorry, something went wrong! MSG: ' + err.message }); return res.redirect('back'); } }); }); /** * GET /api/socrata * Web scraping example using Cheerio library. */ app.get('/api/socrata', function (req, res, next) { // Get the socrata open data as JSON // http://dev.socrata.com/docs/queries.html request.get({ url: 'http://controllerdata.lacity.org/resource/qjfm-3srk.json?$order=q4_earnings DESC&$where=year = 2014&$limit=20', timeout: 5000 }, function (err, response, body) { if (!err && response.statusCode === 200) { // Parse the data var payroll = JSON.parse(body); // Render the page res.render('api/socrata', { url: '/apiopen', data: payroll }); } else { req.flash('error', { msg: 'Sorry, something went wrong! MSG: ' + err.message }); return res.redirect('back'); } }); }); /** * GET /api/stripe * Stripe API example. */ app.get('/api/stripe', function (req, res, next) { res.render('api/stripe', { title: 'Stripe API' }); }); /** * POST /api/stripe * @param stipeToken * @param stripeEmail */ app.post('/api/stripe', function (req, res, next) { var stripeToken = req.body.stripeToken; var stripeEmail = req.body.stripeEmail; stripe.charges.create({ amount: 395, currency: 'usd', card: stripeToken, description: stripeEmail }, function (err, charge) { if (err && err.type === 'StripeCardError') { req.flash('error', { msg: 'Your card has been declined.' }); res.redirect('/api/stripe'); } req.flash('success', { msg: 'Your card has been charged successfully.' }); res.redirect('/api/stripe'); }); }); /** * GET /api/twilio * Twilio API example. */ app.get('/api/twilio', function (req, res, next) { res.render('api/twilio', { url: '/apiopen' }); }); /** * POST /api/twilio * Twilio API example. * @param telephone */ app.post('/api/twilio', function (req, res, next) { var message = { to: req.body.telephone, from: config.twilio.phone, body: 'Hello from ' + app.locals.application + '. We are happy you are testing our code!' }; twilio.sendMessage(message, function (err, responseData) { if (err) { return next(err); } req.flash('success', { msg: 'Text sent to ' + responseData.to + '.' }); res.redirect('/api/twilio'); }); }); /** * GET /api/foursquare * Foursquare API example. */ app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { var token = _.find(req.user.tokens, { kind: 'foursquare' }); async.parallel({ trendingVenues: function (callback) { foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function (err, results) { callback(err, results); }); }, venueDetail: function (callback) { foursquare.Venues.getVenue('49da74aef964a5208b5e1fe3', token.accessToken, function (err, results) { callback(err, results); }); }, userCheckins: function (callback) { foursquare.Users.getCheckins('self', null, token.accessToken, function (err, results) { callback(err, results); }); } }, function (err, results) { if (err) { return next(err); } res.render('api/foursquare', { url: '/apilocked', trendingVenues: results.trendingVenues, venueDetail: results.venueDetail, userCheckins: results.userCheckins }); }); }); /** * GET /api/tumblr * Tumblr API example. */ app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res) { var token = _.find(req.user.tokens, { kind: 'tumblr' }); var client = tumblr.createClient({ consumer_key: config.tumblr.key, consumer_secret: config.tumblr.secret, token: token.token, token_secret: token.tokenSecret }); client.posts('danielmoyerdesign.tumblr.com', { type: 'photo' }, function (err, data) { res.render('api/tumblr', { url: '/apilocked', blog: data.blog, photoset: data.posts[0].photos }); }); }); /** * GET /api/facebook * Facebook API example. */ app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { var token = _.find(req.user.tokens, { kind: 'facebook' }); graph.setAccessToken(token.accessToken); async.parallel({ getMe: function (done) { graph.get(req.user.facebook, function (err, me) { done(err, me); }); }, getMyFriends: function (done) { graph.get(req.user.facebook + '/friends', function (err, friends) { debug('Friends: ' + JSON.stringify(friends)); done(err, friends); }); } }, function (err, results) { if (err) { return next(err); } res.render('api/facebook', { url: '/apilocked', me: results.getMe, friends: results.getMyFriends }); }); }); /** * GET /api/github * GitHub API Example. */ app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res) { var token = _.find(req.user.tokens, { kind: 'github' }); var github = new Github({ token: token.accessToken }); var repo = github.getRepo('dstroot', 'skeleton'); repo.show(function (err, repo) { res.render('api/github', { url: '/apilocked', repo: repo }); }); }); /** * GET /api/twitter * Twitter API example. * https://dev.twitter.com/rest/reference/get/search/tweets */ app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { var token = _.find(req.user.tokens, { kind: 'twitter' }); var params = { q: 'iPhone 6', since_id: 24012619984051000, count: 10, result_type: 'popular' }; var T = new Twit({ consumer_key: config.twitter.consumerKey, consumer_secret: config.twitter.consumerSecret, access_token: token.token, access_token_secret: token.tokenSecret }); T.get('search/tweets', params, function (err, data, response) { if (err) { return next(err); } res.render('api/twitter', { url: '/apilocked', tweets: data.statuses }); }); }); /** * POST /api/twitter * Post a tweet. */ app.post('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { req.assert('tweet', 'Tweet cannot be empty.').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/api/twitter'); } var token = _.find(req.user.tokens, { kind: 'twitter' }); var T = new Twit({ consumer_key: config.twitter.consumerKey, consumer_secret: config.twitter.consumerSecret, access_token: token.token, access_token_secret: token.tokenSecret }); T.post('statuses/update', { status: req.body.tweet }, function (err, data, response) { if (err) { return next(err); } req.flash('success', { msg: 'Tweet has been posted.' }); res.redirect('/api/twitter'); }); }); /** * OAuth routes for API examples that require authorization. */ app.get('/auth/foursquare', passport.authorize('foursquare')); app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function (req, res) { res.redirect('/api/foursquare'); }); app.get('/auth/tumblr', passport.authorize('tumblr')); app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function (req, res) { res.redirect('/api/tumblr'); }); };
justyn-clark/mylockedemo
controllers/api.js
JavaScript
mit
15,388
range.collapse(true); // collapse to the starting point console.log(range.collapsed); // outputs "true"
msfrisbie/pjwd-src
Chapter16DOMLevels2And3/Ranges/CollapsingADOMRange/CollapsingADOMRangeExample01.js
JavaScript
mit
108
<?php /** * TL_ROOT/system/modules/videobox_vimeo/languages/lv/tl_videobox_settings.php * * Contao extension: videobox_vimeo 1.0.1 stable * Latvian translation file * * Copyright : David Enke 2010 * License : GNU/GPL * Author : David Enke (david.enke), www.davidenke.de * Translator: Maris Celmins (warrior), http://www.bauskasbiblioteka.lv * * This file was created automatically be the Contao extension repository translation module. * Do not edit this file manually. Contact the author or translator for this module to establish * permanent text corrections which are update-safe. */ $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_legend'] = "Vimeo video"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_template']['0'] = "Veidne"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_template']['1'] = "Izvēleties veidni priekš Vimeo video."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_size']['0'] = "Izmērs"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_size']['1'] = "Iespējams norādīt video platuma un augstuma vērtības."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_autoplay']['0'] = "Automātiska atskaņošana"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_autoplay']['1'] = "Norāda vai video attēlošana tiks veikta automātiski pēc atskaņotāja ielādes vai nē."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_color']['0'] = "Krāsa"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_color']['1'] = "Šī krāsa tonē atskaņotāja kontroles."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showbyline']['0'] = "Rādīt video autora parakstu"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showbyline']['1'] = "Parāda video autora parakstu pirms video atskaņošanas sākuma."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showtitle']['0'] = "Parādīt video nosaukumu"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showtitle']['1'] = "Parāda video nosaukumu pirms video atskaņošanas sākuma."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showportrait']['0'] = "Parādīt lietotāja attēlu"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showportrait']['1'] = "Parāda lietotāja attēlu pirms video atskaņošanas sākuma."; ?>
TechnoGate/contao_template
contao/videobox_vimeo/system/modules/videobox_vimeo/languages/lv/tl_videobox_settings.php
PHP
mit
2,269
<?php class Brandedcrate_Payjunction_Model_Result extends Varien_Object { }
brandedcrate/payjunction-magento
app/code/community/Brandedcrate/Payjunction/Model/Result.php
PHP
mit
82
// Generated by typings // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/80060c94ef549c077a011977c2b5461bd0fd8947/strftime/index.d.ts declare module "strftime" { type strftimeFunction = (format: string, date?: Date) => string; namespace strftime { /** * Sets locale. * @param {Locale} locale A locale. * @return {strftimeFunction} A strftime function. */ export function localize(locale: Locale): strftimeFunction; /** * Sets timezone. * @param {number|string} offset A offset. * @return {strftimeFunction} A strftime function. */ export function timezone(offset: number | string): strftimeFunction; /** * Locale formats. * @interface */ export interface LocaleFormats { D?: string; F?: string; R?: string; T?: string; X?: string; c?: string; r?: string; v?: string; x?: string; } /** * Locale. * @interface */ export interface Locale { days?: Array<string>; shortDays?: Array<string>; months?: Array<string>; shortMonths?: Array<string>; AM?: string; PM?: string; am?: string; pm?: string; formats: LocaleFormats } } /** * Format a local time/date according to locale settings * @param {string} format A format. * @return {string} Returns a string formatted. */ function strftime(format: string): string; /** * Format a local time/date according to locale settings * @param {string} format A format. * @param {Date} date A date. * @return {string} Returns a string formatted according format using the given date or the current local time. */ function strftime(format: string, date: Date): string; export = strftime; }
liqu0/KentChat
src/server/typings/globals/strftime/index.d.ts
TypeScript
mit
2,057
var Sequelize = require('sequelize'); var sequelize = require('./db.js').Sequelize; var UserRooms = sequelize.define('UserRooms', { }, { updatedAt: false, createdAt: false }); module.exports = UserRooms;
nokia-wroclaw/innovativeproject-meetinghelper
server/NodeTest/models/userRoom.js
JavaScript
mit
236
(function(S, $) { var dom = S.Dom; var sharedUserAdmin = new Spontaneous.MetaView.UserAdmin(); var RootMenuView = new JS.Class(S.PopoverView, { initialize: function(afterCloseCallback) { this.afterCloseCallback = afterCloseCallback; this.callSuper(); }, width: function() { return 250; }, title: function() { return "Main Menu"; }, position_from_event: function(event) { var pos = this.callSuper(); return {left: pos.left - 12, top: pos.top + 1}; }, view: function() { var outer = dom.div("#root-menu") outer.append(this.serviceMenu(), this.userActionMenu()); return outer; }, after_close: function() { console.log("root menu after close") if (this.afterCloseCallback && (typeof this.afterCloseCallback === "function")) { this.afterCloseCallback(); } }, userActionMenu: function() { var menu = dom.ul(".user-actions"); menu.append(dom.li('.user.title').text(S.User.name())); if (S.User.is_admin()) { var manage = dom.a().text("User Administration").click(function() { Spontaneous.ContentArea.enterMeta(sharedUserAdmin); Spontaneous.Popover.close(); }); menu.append(dom.li('.user-administration').append(manage)); } var logout = dom.a().text("Logout").click(function() { console.log("Logout"); S.User.logout(); }); menu.append(dom.li('.logout').append(logout)); return menu; }, serviceMenu: function() { var menu = dom.ul(".external-services"); var self = this; var services = S.Services.serviceList(); if (services.length > 0) { menu.append(dom.li(".title").text("Services")); services.forEach(function(service) { var link = dom.a().text(service.title).click(function() { self.close(); S.Services.open(service); }); menu.append(dom.li().append(link)) }); } return menu; } }); S.RootMenuView = RootMenuView; }(Spontaneous, jQuery));
magnetised/spontaneous
application/js/panel/root_menu.js
JavaScript
mit
1,921
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using UiuCanteen.Domain.Entities; namespace UiuCanteen.Domain.Concrete { public class EFDbContext : DbContext { public DbSet<Product> Products { get; set; } public DbSet<User> Users { get; set; } } }
rasel01/Project-1-Online-Cafeteria-
source/UiuCanteen/UiuCanteen.Domain/Concrete/EFDbContext.cs
C#
mit
377
const renderToString = require('rogain-render-string'); const html = require('html').prettyPrint; const config = require('./render.config.js'); const data = require('./fixtures/data.json'); var output = renderToString(config.components.get('Template'), data, config); console.log(html(output, { unformatted: [] }));
krambuhl/rogain
test/render.test.js
JavaScript
mit
318
module.exports = function(planetsData) { planetsData.createPlanet("Earth") .then((planet) => { console.log("Created new Planet"); console.log(planet); }) .catch(() => { console.log("Error"); console.dir(err, { colors: true }); }); }
shopOFF/TelerikAcademyCourses
Web-Applications-with-Node.js/NodeJs-Homeworks & Exams/nodeJSWorkshop/controllers/planets-controller.js
JavaScript
mit
316
// Copyright (c) 2014 Greenheart Games Pty. Ltd. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "greenworks_workshop_workers.h" #include <algorithm> #include "nan.h" #include "steam/steam_api.h" #include "v8.h" #include "greenworks_utils.h" namespace { v8::Local<v8::Object> ConvertToJsObject(const SteamUGCDetails_t& item) { v8::Local<v8::Object> result = Nan::New<v8::Object>(); Nan::Set(result, Nan::New("acceptedForUse").ToLocalChecked(), Nan::New(item.m_bAcceptedForUse)); Nan::Set(result, Nan::New("banned").ToLocalChecked(), Nan::New(item.m_bBanned)); Nan::Set(result, Nan::New("tagsTruncated").ToLocalChecked(), Nan::New(item.m_bTagsTruncated)); Nan::Set(result, Nan::New("fileType").ToLocalChecked(), Nan::New(item.m_eFileType)); Nan::Set(result, Nan::New("result").ToLocalChecked(), Nan::New(item.m_eResult)); Nan::Set(result, Nan::New("visibility").ToLocalChecked(), Nan::New(item.m_eVisibility)); Nan::Set(result, Nan::New("score").ToLocalChecked(), Nan::New(item.m_flScore)); Nan::Set(result, Nan::New("file").ToLocalChecked(), Nan::New(utils::uint64ToString(item.m_hFile)).ToLocalChecked()); Nan::Set(result, Nan::New("fileName").ToLocalChecked(), Nan::New(item.m_pchFileName).ToLocalChecked()); Nan::Set(result, Nan::New("fileSize").ToLocalChecked(), Nan::New(item.m_nFileSize)); Nan::Set( result, Nan::New("previewFile").ToLocalChecked(), Nan::New(utils::uint64ToString(item.m_hPreviewFile)).ToLocalChecked()); Nan::Set(result, Nan::New("previewFileSize").ToLocalChecked(), Nan::New(item.m_nPreviewFileSize)); Nan::Set( result, Nan::New("steamIDOwner").ToLocalChecked(), Nan::New(utils::uint64ToString(item.m_ulSteamIDOwner)).ToLocalChecked()); Nan::Set(result, Nan::New("consumerAppID").ToLocalChecked(), Nan::New(item.m_nConsumerAppID)); Nan::Set(result, Nan::New("creatorAppID").ToLocalChecked(), Nan::New(item.m_nCreatorAppID)); Nan::Set(result, Nan::New("publishedFileId").ToLocalChecked(), Nan::New(utils::uint64ToString(item.m_nPublishedFileId)) .ToLocalChecked()); Nan::Set(result, Nan::New("title").ToLocalChecked(), Nan::New(item.m_rgchTitle).ToLocalChecked()); Nan::Set(result, Nan::New("description").ToLocalChecked(), Nan::New(item.m_rgchDescription).ToLocalChecked()); Nan::Set(result, Nan::New("URL").ToLocalChecked(), Nan::New(item.m_rgchURL).ToLocalChecked()); Nan::Set(result, Nan::New("tags").ToLocalChecked(), Nan::New(item.m_rgchTags).ToLocalChecked()); Nan::Set(result, Nan::New("timeAddedToUserList").ToLocalChecked(), Nan::New(item.m_rtimeAddedToUserList)); Nan::Set(result, Nan::New("timeCreated").ToLocalChecked(), Nan::New(item.m_rtimeCreated)); Nan::Set(result, Nan::New("timeUpdated").ToLocalChecked(), Nan::New(item.m_rtimeUpdated)); Nan::Set(result, Nan::New("votesDown").ToLocalChecked(), Nan::New(item.m_unVotesDown)); Nan::Set(result, Nan::New("votesUp").ToLocalChecked(), Nan::New(item.m_unVotesUp)); return result; } inline std::string GetAbsoluteFilePath(const std::string& file_path, const std::string& download_dir) { std::string file_name = file_path.substr(file_path.find_last_of("/\\") + 1); return download_dir + "/" + file_name; } } // namespace namespace greenworks { FileShareWorker::FileShareWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, const std::string& file_path) :SteamCallbackAsyncWorker(success_callback, error_callback), file_path_(file_path) { } void FileShareWorker::Execute() { // Ignore empty path. if (file_path_.empty()) return; std::string file_name = utils::GetFileNameFromPath(file_path_); SteamAPICall_t share_result = SteamRemoteStorage()->FileShare( file_name.c_str()); call_result_.Set(share_result, this, &FileShareWorker::OnFileShareCompleted); // Wait for FileShare callback result. WaitForCompleted(); } void FileShareWorker::OnFileShareCompleted( RemoteStorageFileShareResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage("Error on sharing file: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { share_file_handle_ = result->m_hFile; } else { SetErrorMessage("Error on sharing file on Steam cloud."); } is_completed_ = true; } void FileShareWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Value> argv[] = { Nan::New(utils::uint64ToString(share_file_handle_)).ToLocalChecked() }; Nan::AsyncResource resource("greenworks:FileShareWorker.HandleOKCallback"); callback->Call(1, argv, &resource); } PublishWorkshopFileWorker::PublishWorkshopFileWorker( Nan::Callback* success_callback, Nan::Callback* error_callback, uint32 app_id, const WorkshopFileProperties& properties) : SteamCallbackAsyncWorker(success_callback, error_callback), app_id_(app_id), properties_(properties) {} void PublishWorkshopFileWorker::Execute() { SteamParamStringArray_t tags; tags.m_nNumStrings = properties_.tags_scratch.size(); tags.m_ppStrings = reinterpret_cast<const char**>(&properties_.tags); std::string file_name = utils::GetFileNameFromPath(properties_.file_path); std::string image_name = utils::GetFileNameFromPath(properties_.image_path); SteamAPICall_t publish_result = SteamRemoteStorage()->PublishWorkshopFile( file_name.c_str(), image_name.empty()? nullptr:image_name.c_str(), app_id_, properties_.title.c_str(), properties_.description.empty()? nullptr:properties_.description.c_str(), k_ERemoteStoragePublishedFileVisibilityPublic, &tags, k_EWorkshopFileTypeCommunity); call_result_.Set(publish_result, this, &PublishWorkshopFileWorker::OnFilePublishCompleted); // Wait for FileShare callback result. WaitForCompleted(); } void PublishWorkshopFileWorker::OnFilePublishCompleted( RemoteStoragePublishFileResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage("Error on publishing workshop file: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { publish_file_id_ = result->m_nPublishedFileId; } else { SetErrorMessage("Error on publishing workshop file."); } is_completed_ = true; } void PublishWorkshopFileWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Value> argv[] = { Nan::New(utils::uint64ToString(publish_file_id_)).ToLocalChecked() }; Nan::AsyncResource resource("greenworks:PublishWorkshopFileWorker.HandleOKCallback"); callback->Call(1, argv, &resource); } UpdatePublishedWorkshopFileWorker::UpdatePublishedWorkshopFileWorker( Nan::Callback* success_callback, Nan::Callback* error_callback, PublishedFileId_t published_file_id, const WorkshopFileProperties& properties) : SteamCallbackAsyncWorker(success_callback, error_callback), published_file_id_(published_file_id), properties_(properties) {} void UpdatePublishedWorkshopFileWorker::Execute() { PublishedFileUpdateHandle_t update_handle = SteamRemoteStorage()->CreatePublishedFileUpdateRequest( published_file_id_); const std::string file_name = utils::GetFileNameFromPath(properties_.file_path); const std::string image_name = utils::GetFileNameFromPath(properties_.image_path); if (!file_name.empty()) SteamRemoteStorage()->UpdatePublishedFileFile(update_handle, file_name.c_str()); if (!image_name.empty()) SteamRemoteStorage()->UpdatePublishedFilePreviewFile(update_handle, image_name.c_str()); if (!properties_.title.empty()) SteamRemoteStorage()->UpdatePublishedFileTitle(update_handle, properties_.title.c_str()); if (!properties_.description.empty()) SteamRemoteStorage()->UpdatePublishedFileDescription(update_handle, properties_.description.c_str()); if (!properties_.tags_scratch.empty()) { SteamParamStringArray_t tags; if (properties_.tags_scratch.size() == 1 && properties_.tags_scratch.front().empty()) { // clean the tag. tags.m_nNumStrings = 0; tags.m_ppStrings = nullptr; } else { tags.m_nNumStrings = properties_.tags_scratch.size(); tags.m_ppStrings = reinterpret_cast<const char**>(&properties_.tags); } SteamRemoteStorage()->UpdatePublishedFileTags(update_handle, &tags); } SteamAPICall_t commit_update_result = SteamRemoteStorage()->CommitPublishedFileUpdate(update_handle); update_published_file_call_result_.Set(commit_update_result, this, &UpdatePublishedWorkshopFileWorker:: OnCommitPublishedFileUpdateCompleted); // Wait for published workshop file updated. WaitForCompleted(); } void UpdatePublishedWorkshopFileWorker::OnCommitPublishedFileUpdateCompleted( RemoteStorageUpdatePublishedFileResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage( "Error on committing published file update: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { } else { SetErrorMessage("Error on getting published file details."); } is_completed_ = true; } QueryUGCWorker::QueryUGCWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, EUGCMatchingUGCType ugc_matching_type, uint32 app_id, uint32 page_num) : SteamCallbackAsyncWorker(success_callback, error_callback), ugc_matching_type_(ugc_matching_type), app_id_(app_id), page_num_(page_num) {} void QueryUGCWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Array> items = Nan::New<v8::Array>( static_cast<int>(ugc_items_.size())); for (size_t i = 0; i < ugc_items_.size(); ++i) Nan::Set(items, i, ConvertToJsObject(ugc_items_[i])); v8::Local<v8::Value> argv[] = { items }; Nan::AsyncResource resource("greenworks:QueryUGCWorker.HandleOKCallback"); callback->Call(1, argv, &resource); } void QueryUGCWorker::OnUGCQueryCompleted(SteamUGCQueryCompleted_t* result, bool io_failure) { if (io_failure) { SetErrorMessage("Error on querying all ugc: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { uint32 count = result->m_unNumResultsReturned; SteamUGCDetails_t item; for (uint32 i = 0; i < count; ++i) { SteamUGC()->GetQueryUGCResult(result->m_handle, i, &item); ugc_items_.push_back(item); } SteamUGC()->ReleaseQueryUGCRequest(result->m_handle); } else { SetErrorMessage("Error on querying ugc."); } is_completed_ = true; } QueryAllUGCWorker::QueryAllUGCWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, EUGCMatchingUGCType ugc_matching_type, EUGCQuery ugc_query_type, uint32 app_id, uint32 page_num) : QueryUGCWorker(success_callback, error_callback, ugc_matching_type, app_id, page_num), ugc_query_type_(ugc_query_type) {} void QueryAllUGCWorker::Execute() { uint32 invalid_app_id = 0; // Set "creator_app_id" parameter to an invalid id to make Steam API return // all ugc items, otherwise the API won't get any results in some cases. UGCQueryHandle_t ugc_handle = SteamUGC()->CreateQueryAllUGCRequest( ugc_query_type_, ugc_matching_type_, /*creator_app_id=*/invalid_app_id, /*consumer_app_id=*/app_id_, page_num_); SteamAPICall_t ugc_query_result = SteamUGC()->SendQueryUGCRequest(ugc_handle); ugc_query_call_result_.Set(ugc_query_result, this, &QueryAllUGCWorker::OnUGCQueryCompleted); // Wait for query all ugc completed. WaitForCompleted(); } QueryUserUGCWorker::QueryUserUGCWorker( Nan::Callback* success_callback, Nan::Callback* error_callback, EUGCMatchingUGCType ugc_matching_type, EUserUGCList ugc_list, EUserUGCListSortOrder ugc_list_sort_order, uint32 app_id, uint32 page_num) : QueryUGCWorker(success_callback, error_callback, ugc_matching_type, app_id, page_num), ugc_list_(ugc_list), ugc_list_sort_order_(ugc_list_sort_order) {} void QueryUserUGCWorker::Execute() { UGCQueryHandle_t ugc_handle = SteamUGC()->CreateQueryUserUGCRequest( SteamUser()->GetSteamID().GetAccountID(), ugc_list_, ugc_matching_type_, ugc_list_sort_order_, app_id_, app_id_, page_num_); SteamAPICall_t ugc_query_result = SteamUGC()->SendQueryUGCRequest(ugc_handle); ugc_query_call_result_.Set(ugc_query_result, this, &QueryUserUGCWorker::OnUGCQueryCompleted); // Wait for query all ugc completed. WaitForCompleted(); } DownloadItemWorker::DownloadItemWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, UGCHandle_t download_file_handle, const std::string& download_dir) :SteamCallbackAsyncWorker(success_callback, error_callback), download_file_handle_(download_file_handle), download_dir_(download_dir) { } void DownloadItemWorker::Execute() { SteamAPICall_t download_item_result = SteamRemoteStorage()->UGCDownload(download_file_handle_, 0); call_result_.Set(download_item_result, this, &DownloadItemWorker::OnDownloadCompleted); // Wait for downloading file completed. WaitForCompleted(); } void DownloadItemWorker::OnDownloadCompleted( RemoteStorageDownloadUGCResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage( "Error on downloading file: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { std::string target_path = GetAbsoluteFilePath(result->m_pchFileName, download_dir_); int file_size_in_bytes = result->m_nSizeInBytes; auto* content = new char[file_size_in_bytes]; SteamRemoteStorage()->UGCRead(download_file_handle_, content, file_size_in_bytes, 0, k_EUGCRead_Close); if (!utils::WriteFile(target_path, content, file_size_in_bytes)) { SetErrorMessage("Error on saving file on local machine."); } delete[] content; } else { SetErrorMessage("Error on downloading file."); } is_completed_ = true; } SynchronizeItemsWorker::SynchronizeItemsWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, const std::string& download_dir, uint32 app_id, uint32 page_num) : SteamCallbackAsyncWorker(success_callback, error_callback), current_download_items_pos_(0), download_dir_(download_dir), app_id_(app_id), page_num_(page_num) {} void SynchronizeItemsWorker::Execute() { UGCQueryHandle_t ugc_handle = SteamUGC()->CreateQueryUserUGCRequest( SteamUser()->GetSteamID().GetAccountID(), k_EUserUGCList_Subscribed, k_EUGCMatchingUGCType_Items, k_EUserUGCListSortOrder_SubscriptionDateDesc, app_id_, app_id_, page_num_); SteamAPICall_t ugc_query_result = SteamUGC()->SendQueryUGCRequest(ugc_handle); ugc_query_call_result_.Set(ugc_query_result, this, &SynchronizeItemsWorker::OnUGCQueryCompleted); // Wait for synchronization completed. WaitForCompleted(); } void SynchronizeItemsWorker::OnUGCQueryCompleted( SteamUGCQueryCompleted_t* result, bool io_failure) { if (io_failure) { SetErrorMessage("Error on querying all ugc: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { SteamUGCDetails_t item; for (uint32 i = 0; i < result->m_unNumResultsReturned; ++i) { SteamUGC()->GetQueryUGCResult(result->m_handle, i, &item); std::string target_path = GetAbsoluteFilePath(item.m_pchFileName, download_dir_); int64 file_update_time = utils::GetFileLastUpdatedTime( target_path.c_str()); ugc_items_.push_back(item); // If the file is not existed or last update time is not equal to Steam, // download it. if (file_update_time == -1 || file_update_time != item.m_rtimeUpdated) download_ugc_items_handle_.push_back(item.m_hFile); } // Start download the file. if (download_ugc_items_handle_.size() > 0) { SteamAPICall_t download_item_result = SteamRemoteStorage()->UGCDownload( download_ugc_items_handle_[current_download_items_pos_], 0); download_call_result_.Set(download_item_result, this, &SynchronizeItemsWorker::OnDownloadCompleted); SteamUGC()->ReleaseQueryUGCRequest(result->m_handle); return; } } else { SetErrorMessage("Error on querying ugc."); } is_completed_ = true; } void SynchronizeItemsWorker::OnDownloadCompleted( RemoteStorageDownloadUGCResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage( "Error on downloading file: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { std::string target_path = GetAbsoluteFilePath(result->m_pchFileName, download_dir_); int file_size_in_bytes = result->m_nSizeInBytes; auto* content = new char[file_size_in_bytes]; SteamRemoteStorage()->UGCRead(result->m_hFile, content, file_size_in_bytes, 0, k_EUGCRead_Close); bool is_save_success = utils::WriteFile(target_path, content, file_size_in_bytes); delete[] content; if (!is_save_success) { SetErrorMessage("Error on saving file on local machine."); is_completed_ = true; return; } int64 file_updated_time = ugc_items_[current_download_items_pos_].m_rtimeUpdated; if (!utils::UpdateFileLastUpdatedTime( target_path.c_str(), static_cast<time_t>(file_updated_time))) { SetErrorMessage("Error on update file time on local machine."); is_completed_ = true; return; } ++current_download_items_pos_; if (current_download_items_pos_ < download_ugc_items_handle_.size()) { SteamAPICall_t download_item_result = SteamRemoteStorage()->UGCDownload( download_ugc_items_handle_[current_download_items_pos_], 0); download_call_result_.Set(download_item_result, this, &SynchronizeItemsWorker::OnDownloadCompleted); return; } } else { SetErrorMessage("Error on downloading file."); } is_completed_ = true; } void SynchronizeItemsWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Array> items = Nan::New<v8::Array>( static_cast<int>(ugc_items_.size())); for (size_t i = 0; i < ugc_items_.size(); ++i) { v8::Local<v8::Object> item = ConvertToJsObject(ugc_items_[i]); bool is_updated = std::find(download_ugc_items_handle_.begin(), download_ugc_items_handle_.end(), ugc_items_[i].m_hFile) != download_ugc_items_handle_.end(); Nan::Set(item, Nan::New("isUpdated").ToLocalChecked(), Nan::New(is_updated)); Nan::Set(items, i, item); } v8::Local<v8::Value> argv[] = { items }; Nan::AsyncResource resource("greenworks:SynchronizeItemsWorker.HandleOKCallback"); callback->Call(1, argv, &resource); } UnsubscribePublishedFileWorker::UnsubscribePublishedFileWorker( Nan::Callback* success_callback, Nan::Callback* error_callback, PublishedFileId_t unsubscribe_file_id) :SteamCallbackAsyncWorker(success_callback, error_callback), unsubscribe_file_id_(unsubscribe_file_id) { } void UnsubscribePublishedFileWorker::Execute() { SteamAPICall_t unsubscribed_result = SteamRemoteStorage()->UnsubscribePublishedFile(unsubscribe_file_id_); unsubscribe_call_result_.Set(unsubscribed_result, this, &UnsubscribePublishedFileWorker::OnUnsubscribeCompleted); // Wait for unsubscribing job completed. WaitForCompleted(); } void UnsubscribePublishedFileWorker::OnUnsubscribeCompleted( RemoteStoragePublishedFileUnsubscribed_t* result, bool io_failure) { is_completed_ = true; } } // namespace greenworks
greenheartgames/greenworks
src/greenworks_workshop_workers.cc
C++
mit
20,261
class Camera { static init() { this.position = vec3.fromValues(-Terrain.tiles.length/2, -Terrain.tiles[0].length/2, -1 * slider_zoom.value); this.rotation = vec3.fromValues(0, 0, 0); } static getViewMatrix() { var q = quat.create(); quat.rotateX(q, q, this.rotation[0]); quat.rotateY(q, q, this.rotation[1]); quat.rotateZ(q, q, this.rotation[2]); var viewMatrix = mat4.create(); mat4.fromRotationTranslationScale(viewMatrix, q, this.position, [1,1,1]); return viewMatrix; } }
Pilex1/Pilex1.github.io
Projects/Wireworld/camera.js
JavaScript
mit
562
/** * Keyboard event keyCodes have proven to be really unreliable. * This util function will cover most of the edge cases where * String.fromCharCode() doesn't work. */ const _toAscii = { 188: '44', 109: '45', 190: '46', 191: '47', 192: '96', 220: '92', 222: '39', 221: '93', 219: '91', 173: '45', 187: '61', // IE Key codes 186: '59', // IE Key codes 189: '45' // IE Key codes }; const _shiftUps = { 96: '~', 49: '!', 50: '@', 51: '#', 52: '$', 53: '%', 54: '^', 55: '&', 56: '*', 57: '(', 48: ')', 45: '_', 61: '+', 91: '{', 93: '}', 92: '|', 59: ':', 39: "'", 44: '<', 46: '>', 47: '?' }; const _arrowKeys = { 38: '', 40: '', 39: '', 37: '' }; /** * This fn takes a keyboard event and returns * the character that was pressed. This fn * purposely doesn't take into account if the alt/meta * key was pressed. */ export default function fromCharCode(e) { let code = String(e.which); if ({}.hasOwnProperty.call(_arrowKeys, code)) { return _arrowKeys[code]; } if ({}.hasOwnProperty.call(_toAscii, code)) { code = _toAscii[code]; } const char = String.fromCharCode(code); if (e.shiftKey) { if ({}.hasOwnProperty.call(_shiftUps, code)) { return _shiftUps[code]; } return char.toUpperCase(); } return char.toLowerCase(); }
derrickpelletier/hyper
lib/utils/key-code.js
JavaScript
mit
1,367
/** * result Module * * Description */ angular .module('result') .directive('navBar', navBar); navBar.$inject = ['loginService', '$log', '$location']; function navBar(loginService, $log, $location) { return { restrict: 'A', link: function(scope, element, attrs, controller) { loginService.user() .success(function(data) { scope.user = data; }) .error(function(data, status) { loginService.logout(); }) scope.isloggedIn = loginService.isLoggedIn(); scope.$on('updateUser', function(event, args) { if(args.login) { scope.user = args.user; scope.isloggedIn = loginService.isLoggedIn(); } else { scope.user = null; scope.isloggedIn = loginService.isLoggedIn(); } }) scope.logout = function() { loginService.logout() .success(function() { $location.path('/login'); }) } }, replace: true, scope: true, templateUrl: 'packages/app/views/navbar.html' } }
techhahn/Result-Analyzer
public/packages/app/directives/app.navigationbarDirective.js
JavaScript
mit
969
<?php defined('BX_DOL') or die('hack attempt'); /** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup UnaCore UNA Core * @{ */ /** * Message constants passed to _t_ext() function by checkAction() * * NOTE: checkAction() returns language dependent messages */ define('CHECK_ACTION_MESSAGE_NOT_ALLOWED', "_sys_acl_action_not_allowed"); define('CHECK_ACTION_MESSAGE_LIMIT_REACHED', "_sys_acl_action_limit_reached"); define('CHECK_ACTION_MESSAGE_MESSAGE_EVERY_PERIOD', "_sys_acl_action_every_period"); define('CHECK_ACTION_MESSAGE_NOT_ALLOWED_BEFORE', "_sys_acl_action_not_allowed_before"); define('CHECK_ACTION_MESSAGE_NOT_ALLOWED_AFTER', "_sys_acl_action_not_allowed_after"); define('CHECK_ACTION_MESSAGE_UNAUTHENTICATED', "_sys_acl_action_unauthenticated"); define('CHECK_ACTION_MESSAGE_UNCONFIRMED', "_sys_acl_action_unconfirmed"); define('CHECK_ACTION_MESSAGE_PENDING', "_sys_acl_action_pending"); define('CHECK_ACTION_MESSAGE_SUSPENDED', "_sys_acl_action_suspended"); /** * Nodes of $args array that are passed to _t_ext() function by checkAction() */ define('CHECK_ACTION_LANG_FILE_ACTION', 1); define('CHECK_ACTION_LANG_FILE_MEMBERSHIP', 2); define('CHECK_ACTION_LANG_FILE_LIMIT', 3); define('CHECK_ACTION_LANG_FILE_PERIOD', 4); define('CHECK_ACTION_LANG_FILE_AFTER', 5); define('CHECK_ACTION_LANG_FILE_BEFORE', 6); define('CHECK_ACTION_LANG_FILE_SITE_EMAIL', 7); define('CHECK_ACTION_LANG_FILE_PERIOD_RESTART_AT', 8); /** * Standard membership ID's */ define('MEMBERSHIP_ID_NON_MEMBER', 1); define('MEMBERSHIP_ID_ACCOUNT', 2); define('MEMBERSHIP_ID_STANDARD', 3); define('MEMBERSHIP_ID_UNCONFIRMED', 4); define('MEMBERSHIP_ID_PENDING', 5); define('MEMBERSHIP_ID_SUSPENDED', 6); define('MEMBERSHIP_ID_MODERATOR', 7); define('MEMBERSHIP_ID_ADMINISTRATOR', 8); /** * Indices for checkAction() result array */ define('CHECK_ACTION_RESULT', 0); define('CHECK_ACTION_MESSAGE', 1); define('CHECK_ACTION_PARAMETER', 3); /** * CHECK_ACTION_RESULT node values */ define('CHECK_ACTION_RESULT_ALLOWED', 0); define('CHECK_ACTION_RESULT_NOT_ALLOWED', 1); define('CHECK_ACTION_RESULT_NOT_ACTIVE', 2); define('CHECK_ACTION_RESULT_LIMIT_REACHED', 3); define('CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE', 4); define('CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER', 5); /** * Standard period units */ define('MEMBERSHIP_PERIOD_UNIT_DAY', 'day'); define('MEMBERSHIP_PERIOD_UNIT_WEEK', 'week'); define('MEMBERSHIP_PERIOD_UNIT_MONTH', 'month'); define('MEMBERSHIP_PERIOD_UNIT_YEAR', 'year'); class BxDolAcl extends BxDolFactory implements iBxDolSingleton { protected static $_aCacheData = array(); protected $oDb; protected $_aStandardMemberships = array( MEMBERSHIP_ID_NON_MEMBER => 1, MEMBERSHIP_ID_ACCOUNT => 1, MEMBERSHIP_ID_UNCONFIRMED => 1, MEMBERSHIP_ID_PENDING => 1, MEMBERSHIP_ID_SUSPENDED => 1, MEMBERSHIP_ID_STANDARD => 1, ); protected $_aProfileStatus2LevelMap = array ( BX_PROFILE_STATUS_SUSPENDED => MEMBERSHIP_ID_SUSPENDED, BX_PROFILE_STATUS_PENDING => MEMBERSHIP_ID_PENDING, ); protected $_aLevel2MessageMap = array ( MEMBERSHIP_ID_NON_MEMBER => '_sys_acl_action_unauthenticated', MEMBERSHIP_ID_ACCOUNT => '_sys_acl_action_account', MEMBERSHIP_ID_UNCONFIRMED => '_sys_acl_action_unconfirmed', MEMBERSHIP_ID_PENDING => '_sys_acl_action_pending', MEMBERSHIP_ID_SUSPENDED => '_sys_acl_action_suspended', ); protected function __construct() { if (isset($GLOBALS['bxDolClasses'][get_class($this)])) trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR); parent::__construct(); $this->oDb = BxDolAclQuery::getInstance(); } /** * Prevent cloning the instance */ public function __clone() { if (isset($GLOBALS['bxDolClasses'][get_class($this)])) trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR); } /** * Get singleton instance of the class */ public static function getInstance() { if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) $GLOBALS['bxDolClasses'][__CLASS__] = new BxTemplAcl(); return $GLOBALS['bxDolClasses'][__CLASS__]; } /** * Get necessary condition array to use membership level in search classes * @param $sContentField content table field name * @param $mixedLevelId level ID or array of level IDs * @return array of conditions is returned */ public function getContentByLevelAsCondition($sContentField, $mixedLevelId) { $iLevelId = !is_array($mixedLevelId) ? $mixedLevelId : 0; if (!$iLevelId && is_array($mixedLevelId) && 1 == count($mixedLevelId)) { $a = array_values($mixedLevelId); $iLevelId = array_shift($a); } // unconfirmed if (MEMBERSHIP_ID_UNCONFIRMED == $iLevelId) { return array( 'restriction_sql' => ' AND `sys_accounts`.`email_confirmed` = 0 ', 'restriction' => array (), 'join' => array (), ); } // standard elseif (MEMBERSHIP_ID_STANDARD == $iLevelId) { return array( 'restriction_sql' => ' AND (`tlm`.DateStarts IS NULL OR `tlm`.DateStarts <= NOW()) AND (`tlm`.DateExpires IS NULL OR `tlm`.DateExpires > NOW()) AND `tlm`.`IDMember` IS NULL AND `sys_accounts`.`email_confirmed` != 0 ', 'restriction' => array ( ), 'join' => array ( 'acl_members' => array( 'type' => 'LEFT', 'table' => 'sys_acl_levels_members', 'table_alias' => 'tlm', 'mainField' => $sContentField, 'onField' => 'IDMember', 'joinFields' => array(), ), ), ); } // other levels else { return array( 'restriction_sql' => ' AND (`tlm`.DateStarts IS NULL OR `tlm`.DateStarts <= NOW()) AND (`tlm`.DateExpires IS NULL OR `tlm`.DateExpires > NOW()) AND `sys_accounts`.`email_confirmed` != 0 ', 'restriction' => array ( 'acl_members' => array( 'value' => $mixedLevelId, 'field' => 'IDLevel', 'operator' => is_array($mixedLevelId) ? 'in' : '=', 'table' => 'tlm', ), ), 'join' => array ( 'acl_members' => array( 'type' => 'INNER', 'table' => 'sys_acl_levels_members', 'table_alias' => 'tlm', 'mainField' => $sContentField, 'onField' => 'IDMember', 'joinFields' => array(), ), ), ); } } /** * Get necessary parts of SQL query to use membership levels in other queries * @param $sContentTable content table name * @param $sContentField content table field name * @param $mixedLevelId level ID or array of level IDs * @return array of SQL string parts, for now 'where' part only is returned */ public function getContentByLevelAsSQLPart($sContentTable, $sContentField, $mixedLevelId) { return $this->oDb->getContentByLevelAsSQLPart($sContentTable, $sContentField, $mixedLevelId); } /** * Check if member has one of the provided membership levels * @param $mixedPermissions - integer value (every bit is matched with some membership ID) or an array of membership IDs to check permissions for * @param $iProfileId - profile to check, if it isn't provided or is false then currently logged in profile is used. * @return true if member has privided membership levels, or false if member hasn't. */ public function isMemberLevelInSet($mixedPermissions, $iProfileId = false) { $iPermissions = 0; if(is_array($mixedPermissions)) foreach($mixedPermissions as $iPermissionId) $iPermissions += pow(2, $iPermissionId - 1); else if(is_numeric($mixedPermissions)) $iPermissions = (int)$mixedPermissions; if(!$iPermissions) return false; return ($iPermissions & $this->getMemberLevelBit($iProfileId)); } /** * Get user's membership level bit for bitwise operarions */ public function getMemberLevelBit($iProfileId = 0) { if (!$iProfileId) $iProfileId = bx_get_logged_profile_id(); $aACL = $this->getMemberMembershipInfo($iProfileId); return pow(2, $aACL['id'] - 1); } /** * Checks if a given action is allowed for a given profile and updates action information if the * action is performed. * * @param int $iProfileId ID of a profile that is going to perform an action * @param int $iActionId ID of the action itself * @param boolean $bPerformAction if true, then action information is updated, i.e. action is 'performed' * @return array( * CHECK_ACTION_RESULT => CHECK_ACTION_RESULT_ constant, * CHECK_ACTION_MESSAGE => CHECK_ACTION_MESSAGE_ constant, * CHECK_ACTION_PARAMETER => additional action parameter (string) * ) * * NOTES: * * $aResult[CHECK_ACTION_MESSAGE] contains a message with detailed information about the result, * already processed by the language file * * if $aResult[CHECK_ACTION_RESULT] === CHECK_ACTION_RESULT_ALLOWED then this node contains * an empty string * * The error messages themselves are stored in the language file. Additional variables are * passed to the languages.inc.php function _t_ext() as an array and can be used there in the form of * {0}, {1}, {2} ... * * Additional variables passed to the lang. file on errors (can be used in error messages): * * For all errors: * * $arg0[CHECK_ACTION_LANG_FILE_ACTION] = name of the action * $arg0[CHECK_ACTION_LANG_FILE_MEMBERSHIP]= name of the current membership * * CHECK_ACTION_RESULT_LIMIT_REACHED: * * $arg0[CHECK_ACTION_LANG_FILE_LIMIT] = limit on number of actions allowed for the profile * $arg0[CHECK_ACTION_LANG_FILE_PERIOD] = period that the limit is set for (in hours, 0 if unlimited) * $arg0[CHECK_ACTION_LANG_FILE_PERIOD_RESTART_AT] = time when new period begins, so counter will be reset * * CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE: * * $arg0[CHECK_ACTION_LANG_FILE_BEFORE] = date/time since when the action is allowed * * CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER: * * $arg0[CHECK_ACTION_LANG_FILE_AFTER] = date/time since when the action is not allowed * * $aResult[CHECK_ACTION_PARAMETER] contains an additional parameter that can be considered * when performing the action (like the number of profiles to show in search result) */ function checkAction($iProfileId, $iActionId, $bPerformAction = false) { $aResult = array(); $aLangFileParams = array(); $iProfileId = (int)$iProfileId; $iActionId = (int)$iActionId; $bPerformAction = $bPerformAction ? true : false; $aMembership = $this->getMemberMembershipInfo($iProfileId); // get current profile's membership information $aLangFileParams[CHECK_ACTION_LANG_FILE_MEMBERSHIP] = _t($aMembership['name']); $aLangFileParams[CHECK_ACTION_LANG_FILE_SITE_EMAIL] = getParam('site_email'); $aAction = $this->oDb->getAction($aMembership['id'], $iActionId); if (!$aAction) bx_trigger_error('Unknown action ID: ' . $iActionId, 2); $aResult[CHECK_ACTION_PARAMETER] = $aAction['additional_param_value']; $aLangFileParams[CHECK_ACTION_LANG_FILE_ACTION] = !empty($aAction['title']) ? _t($aAction['title']) : $aAction['name']; /** * Action is not allowed for the current membership */ if (is_null($aAction['id'])) { $sLangKey = CHECK_ACTION_MESSAGE_NOT_ALLOWED; if (isset($this->_aLevel2MessageMap[$aMembership['id']])) $sLangKey = $this->_aLevel2MessageMap[$aMembership['id']]; $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED; $aResult[CHECK_ACTION_MESSAGE] = _t_ext($sLangKey, $aLangFileParams); return $aResult; } /** * Check fixed period limitations if present (also for non-members) */ if($aAction['allowed_period_start'] && time() < $aAction['allowed_period_start']) { $aLangFileParams[CHECK_ACTION_LANG_FILE_BEFORE] = bx_time_js($aAction['allowed_period_start'], BX_FORMAT_DATE_TIME); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE; $aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_BEFORE, $aLangFileParams); return $aResult; } if($aAction['allowed_period_end'] && time() > $aAction['allowed_period_end']) { $aLangFileParams[CHECK_ACTION_LANG_FILE_AFTER] = bx_time_js($aAction['allowed_period_end'], BX_FORMAT_DATE_TIME); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER; $aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_AFTER, $aLangFileParams); return $aResult; } /** * if non-member, allow action without performing further checks */ if ($aMembership['id'] == MEMBERSHIP_ID_NON_MEMBER) { $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED; return $aResult; } /** * Check other limitations (for members only) */ $iAllowedCnt = (int)$aAction['allowed_count']; ///< Number of allowed actions. Unlimited if not specified or 0 $iPeriodLen = (int)$aAction['allowed_period_len']; ///< Period for AllowedCount in hours. If not specified, AllowedCount is treated as total number of actions permitted. if($iAllowedCnt > 0) { $aActionTrack = $this->oDb->getActionTrack($iActionId, $iProfileId); $iActionsLeft = $bPerformAction ? $iAllowedCnt - 1 : $iAllowedCnt; $iValidSince = time(); /** * Member is requesting/performing this action for the first time, * and there is no corresponding record in sys_acl_actions_track table. */ if(!$aActionTrack) { $this->oDb->insertActionTarck($iActionId, $iProfileId, $iActionsLeft, $iValidSince); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED; return $aResult; } /** * Action has been requested/performed at least once at this point and there is a corresponding record in sys_acl_actions_track table * * Action record in sys_acl_actions_track table is out of date. */ $iPeriodEnd = (int)$aActionTrack['valid_since'] + $iPeriodLen * 3600; //ValidSince is in seconds, PeriodLen is in hours if($iPeriodLen > 0 && $iPeriodEnd < time()) { $this->oDb->updateActionTrack($iActionId, $iProfileId, $iActionsLeft, $iValidSince); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED; return $aResult; } $iActionsLeft = (int)$aActionTrack['actions_left']; ///< Action record is up to date /** * Action limit reached for now */ if($iActionsLeft <= 0){ $aLangFileParams[CHECK_ACTION_LANG_FILE_LIMIT] = $iAllowedCnt; $aLangFileParams[CHECK_ACTION_LANG_FILE_PERIOD] = $iPeriodLen; $aLangFileParams[CHECK_ACTION_LANG_FILE_PERIOD_RESTART_AT] = bx_time_js($iPeriodEnd); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_LIMIT_REACHED; $aResult[CHECK_ACTION_MESSAGE] = '<div class="bx-acl-err-msg">' . _t_ext(CHECK_ACTION_MESSAGE_LIMIT_REACHED, $aLangFileParams) . ($iPeriodLen > 0 ? _t_ext(CHECK_ACTION_MESSAGE_MESSAGE_EVERY_PERIOD, $aLangFileParams) : '') . '.</div>'; return $aResult; } if($bPerformAction) { $iActionsLeft--; $this->oDb->updateActionTrack($iActionId, $iProfileId, $iActionsLeft); } } $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED; return $aResult; } /** * Get the number of allowed action * * @param int $iProfileId ID of a profile that is going to perform an action * @param int $iActionId ID of the action itself * @param boolean $bPerformAction if true, then action information is updated, i.e. action is 'performed' * @return int if the action is countable, or true if it's not countable */ function getActionNumberLeft($iProfileId, $iActionId) { $aMembership = $this->getMemberMembershipInfo($iProfileId); // get current profile's membership information $aAction = $this->oDb->getAction($aMembership['id'], $iActionId); $iAllowedCnt = (int)$aAction['allowed_count']; ///< Number of allowed actions. Unlimited if not specified or 0 if($iAllowedCnt > 0) { $aActionTrack = $this->oDb->getActionTrack($iActionId, $iProfileId); if(!$aActionTrack) return $iAllowedCnt; return (int)$aActionTrack['actions_left']; } return true; } /** * Get the list of existing memberships * * @param bool $bPurchasableOnly if true, fetches only purchasable memberships; 'purchasable' here means that: * - MemLevels.Purchasable = 'yes' * - MemLevels.Active = 'yes' * - there is at least one pricing option for the membership * @return array( membershipID_1 => membershipName_1, membershipID_2 => membershipName_2, ...) if no such memberships, then just array() */ function getMemberships($bPurchasableOnly = false, $bActiveOnly = false, $isTranslate = true, $bFilterOutSystemAutomaticLevels = false) { $sType = 'all_pair'; if($bPurchasableOnly) $sType = 'all_active_purchasble_pair'; else if($bActiveOnly) $sType = 'all_active_pair'; $aLevels = array(); $this->oDb->getLevels(array('type' => $sType), $aLevels, false); if ($isTranslate) foreach ($aLevels as $k => $s) $aLevels[$k] = _t($s); if ($bFilterOutSystemAutomaticLevels) { unset($aLevels[MEMBERSHIP_ID_NON_MEMBER]); unset($aLevels[MEMBERSHIP_ID_ACCOUNT]); unset($aLevels[MEMBERSHIP_ID_UNCONFIRMED]); unset($aLevels[MEMBERSHIP_ID_PENDING]); unset($aLevels[MEMBERSHIP_ID_SUSPENDED]); } return $aLevels; } function getMembershipsBy($aParams) { $aLevels = array(); $this->oDb->getLevels($aParams, $aLevels, false); return $aLevels; } /** * Get info about a given membership * * @param int $iLevelId membership to get info about * @return array( * 'id' => ID, * 'name' => name, * 'icon' => icon, * 'description' => description, * 'active' => active, * 'purchasable' => purchasable, * 'removable' => removable * 'quota_size' => quota size, * 'quota_number' => quota number, * 'quota_max_file_size' => quota max file size * ) */ function getMembershipInfo($iLevelId) { $aLevel = array(); $this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false); return $aLevel; } /** * Retrieves information about membership for a given profile at a given moment. * * If there are no memberships purchased/assigned to the * given profile or all of them have expired at the given point, * the profile is assumed to be a standard profile, and the function * returns information about the Standard membership. This will * also happen if a profile wasnt actually registered in the database * at that point - the function will still return info about Standard * membership, not the Non-member one. * * If there is no profile with the given $iProfileId, * the function returns information about the Non-member or Authenticated * predefined membership. * * The Standard, Authenticated and Non-member memberships have their * DateStarts and DateExpires attributes set to NULL. * * @param int $iProfileId ID of a profile to get info about * @param int $time specifies the time to use when determining membership; if not specified, the function takes the current time * @return array( * 'id' => membership id, * 'name' => membership name, * 'date_starts' => (UNIX timestamp) date/time purchased, * 'date_expires' => (UNIX timestamp) date/time expires * ) */ function getMemberMembershipInfo($iProfileId, $iTime = 0, $bClearCache = 0) { $aMembershipCurrent = $this->getMemberMembershipInfoCurrent($iProfileId, $iTime, $bClearCache); if (isset($this->_aStandardMemberships[$aMembershipCurrent['id']])) return $aMembershipCurrent; $aMembership = $aMembershipCurrent; do { $iDateStarts = $aMembership['date_starts']; $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, ((int)$iDateStarts < 1 ? 0 : $iDateStarts - 1), $bClearCache); } while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_starts']); $aMembership = $aMembershipCurrent; do { $iDateExpires = $aMembership['date_expires']; $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, $iDateExpires, $bClearCache); } while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_expires']); $aMembershipCurrent['date_starts'] = $iDateStarts; $aMembershipCurrent['date_expires'] = $iDateExpires; return $aMembershipCurrent; } /** * Set a membership for a profile * * @param int $iProfileId profile that is going to get the membership * @param int $iLevelId membership that is going to be assigned to the profile * if $iLevelId == MEMBERSHIP_ID_STANDARD then $days and $bStartsNow parameters are not used, * so Standard membership is always set immediately and `forever` * @param mixed $mixedPeriod number of Days to set membership for or an array with 'period'-'period unit' pair. If number or 'period' in pair equal 0, then the membership is set forever * @param boolean $bStartsNow if true, the membership will start immediately if false, the membership will start after the current membership expires * @return boolean true in case of success, false in case of failure */ function setMembership($iProfileId, $iLevelId, $mixedPeriod = 0, $bStartsNow = false, $sTransactionId = '') { $iProfileId = (int)$iProfileId; $iLevelId = (int)$iLevelId; $bStartsNow = $bStartsNow ? true : false; if (!$iProfileId) $iProfileId = -1; if (empty($sTransactionId)) $sTransactionId = 'NULL'; // check if profile exists if(($sProfileEmail = BxDolProfileQuery::getInstance()->getEmailById($iProfileId)) === false) return false; // check if membership exists $aLevel = array(); $this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false); if(empty($aLevel) || !is_array($aLevel)) return false; if($iLevelId == MEMBERSHIP_ID_NON_MEMBER) return false; $aMembershipCurrent = $this->getMemberMembershipInfo($iProfileId); $aMembershipLatest = $this->getMemberMembershipInfoLatest($iProfileId); // setting Standard membership level if ($iLevelId == MEMBERSHIP_ID_STANDARD) { if ($aMembershipCurrent['id'] == MEMBERSHIP_ID_STANDARD) return true; // delete present and future memberships $bResult = $this->oDb->deleteLevelByProfileId($iProfileId); if($bResult) { $this->oDb->cleanMemory('BxDolAclQuery::getLevelCurrent' . $iProfileId . time()); unset(self::$_aCacheData[$iProfileId . '_0']); } return $bResult; } if ((is_numeric($mixedPeriod) && (int)$mixedPeriod < 0) || (is_array($mixedPeriod) && (!isset($mixedPeriod['period']) || $mixedPeriod['period'] < 0))) return false; /* * Make the membership starts after the latest membership expires or starts immediately * if latest membership is lifetime membership or immediate start was requested. */ $iDateStarts = time(); if ($bStartsNow || empty($aMembershipLatest['date_expires'])) { // Delete any profile's membership level and actions traces $this->oDb->deleteLevelByProfileId($iProfileId, true); $this->oDb->clearActionsTracksForMember($iProfileId); $this->oDb->cleanMemory('BxDolAclQuery::getLevelCurrent' . $iProfileId . time()); unset(self::$_aCacheData[$iProfileId . '_0']); } else $iDateStarts = $aMembershipLatest['date_expires']; // set lifetime membership if 0 days is used. if(is_numeric($mixedPeriod)) $mixedPeriod = array('period' => (int)$mixedPeriod, 'period_unit' => MEMBERSHIP_PERIOD_UNIT_DAY); if(!$this->oDb->insertLevelByProfileId($iProfileId, $iLevelId, $iDateStarts, $mixedPeriod, $sTransactionId)) return false; // raise membership alert bx_alert('profile', 'set_membership', '', $iProfileId, array( 'mlevel'=> $iLevelId, 'period' => $mixedPeriod['period'], 'period_unit' => $mixedPeriod['period_unit'], 'starts_now' => $bStartsNow, 'txn_id' => $sTransactionId )); // audit $aDataForAudit = array(); if (!empty($aMembershipCurrent)) $aDataForAudit = array('new_membership_level' => _t($aLevel['name']), 'old_membership_level' => _t($aMembershipCurrent['name'])); BxDolProfile::getInstance($iProfileId)->doAudit('_sys_audit_action_set_membership', $aDataForAudit); // Send notification $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_MemChanged', array('membership_level' => _t($aLevel['name'])), 0, $iProfileId); if ($aTemplate) sendMail($sProfileEmail, $aTemplate['Subject'], $aTemplate['Body']); return true; } function unsetMembership($iProfileId, $iLevelId, $sTransactionId) { return $this->oDb->deleteLevelBy(array( 'IDMember' => $iProfileId, 'IDLevel' => $iLevelId, 'TransactionID' => $sTransactionId )); } /** * get action id by module and name * @param $sAction action name * @param $sModule module name * @param $aActions array of actions from sys_acl_actions table, with default array keys (starting from 0) and text values */ function getMembershipActionId($sAction, $sModule) { $this->oDb->getActions(array('type' => 'by_names_and_module', 'value' => $sAction, 'module' => $sModule), $aActions, false); if (count($aActions) > 1) trigger_error('Duplicate action - name:' . $sAction . ', module:' . $sModule, E_USER_ERROR); $aAction = array_pop($aActions); return $aAction['id']; } function getExpirationLetter($iProfileId, $sLevelName, $iLevelExpireDays ) { $iProfileId = (int)$iProfileId; if(!$iProfileId) return false; $oProfileQuery = BxDolProfileQuery::getInstance(); $sProfileEmail = $oProfileQuery->getEmailById($iProfileId); $aPlus = array( 'membership_name' => _t($sLevelName), 'expire_days' => $iLevelExpireDays, 'page_url' => BxDolRequest::serviceExists('bx_acl', 'get_view_url') ? BxDolService::call('bx_acl', 'get_view_url') : '#' ); $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_MemExpiration', $aPlus, 0, $iProfileId); $iResult = $aTemplate && sendMail($sProfileEmail, $aTemplate['Subject'], $aTemplate['Body'], $iProfileId, $aPlus); return !empty($iResult); } /** * clear expired membership levels */ public function maintenance() { return $this->oDb->maintenance(); } protected function getMemberMembershipInfoCurrent($iProfileId, $iTime = 0, $bClearCache = 0) { $sKey = $iProfileId . '_' . $iTime; if ($bClearCache && isset(self::$_aCacheData[$sKey])) unset(self::$_aCacheData[$sKey]); elseif (array_key_exists($sKey, self::$_aCacheData) && !defined('BX_DOL_INSTALL') && !defined('BX_DOL_CRON_EXECUTE')) return self::$_aCacheData[$sKey]; $aMemLevel = false; do { // get profile status $oProfile = BxDolProfile::getInstance($iProfileId); $aProfileInfo = $oProfile ? $oProfile->getInfo() : false; $sProfileStatus = $aProfileInfo ? $aProfileInfo['status'] : false; $sProfileType = $aProfileInfo ? $aProfileInfo['type'] : false; // account profile if($sProfileType == 'system') { $aMemLevel = $this->oDb->getLevelByIdCached(MEMBERSHIP_ID_ACCOUNT); if (!$aMemLevel) trigger_error ('Standard member level is missing: MEMBERSHIP_ID_ACCOUNT', E_USER_ERROR); break; } // check if account is unconfirmed, every account's profile is unconfirmed if account is unconfirmed $oAccount = $aProfileInfo ? BxDolAccount::getInstance($aProfileInfo['account_id']) : false; if ($oAccount && !$oAccount->isConfirmed()) { $aMemLevel = $this->oDb->getLevelByIdCached(MEMBERSHIP_ID_UNCONFIRMED); if (!$aMemLevel) trigger_error ('Standard member level is missing: MEMBERSHIP_ID_UNCONFIRMED', E_USER_ERROR); break; } // profile is not active, so return standard memberships according to profile status if (false === $sProfileStatus || BX_PROFILE_STATUS_ACTIVE != $sProfileStatus) { if (!isset($this->_aProfileStatus2LevelMap[$sProfileStatus])) $iLevelId = MEMBERSHIP_ID_NON_MEMBER; // if there is no profile status - then it isn't member else $iLevelId = $this->_aProfileStatus2LevelMap[$sProfileStatus]; // get member level id which associated with every non-active status $aMemLevel = $this->oDb->getLevelByIdCached($iLevelId); if (!$aMemLevel) trigger_error ('Standard member level is missing: ' . $iLevelId, E_USER_ERROR); break; } // profile is active get memebr level from profile $aMemLevel = $this->oDb->getLevelCurrent((int)$iProfileId, $iTime); // There are no purchased/assigned memberships for the profile or all of them have expired. // In this case the profile is assumed to have Standard membership. if (!$aMemLevel || is_null($aMemLevel['id'])) { $aMemLevel = $this->oDb->getLevelByIdCached(MEMBERSHIP_ID_STANDARD); if (!$aMemLevel) trigger_error ('Standard member level is missing: ' . MEMBERSHIP_ID_NON_MEMBER, E_USER_ERROR); break; } } while (0); return (self::$_aCacheData[$sKey] = $aMemLevel); } protected function getMemberMembershipInfoLatest($iProfileId, $iTime = 0, $bClearCache = 0) { $aMembershipCurrent = $this->getMemberMembershipInfoCurrent($iProfileId, $iTime, $bClearCache); if (isset($this->_aStandardMemberships[$aMembershipCurrent['id']])) return $aMembershipCurrent; $aMembership = $aMembershipCurrent; while ($aMembership['id'] != MEMBERSHIP_ID_STANDARD) { $aMembershipLast = $aMembership; if(!isset($aMembership['date_expires']) || (int)$aMembership['date_expires'] == 0) break; $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, $aMembership['date_expires'], $bClearCache); } return $aMembershipLast; } public function onProfileDelete ($iProfileId) { return $this->oDb->deleteLevelByProfileId($iProfileId, true); } } function checkAction($iProfileId, $iActionId, $bPerformAction = false) { return BxDolAcl::getInstance()->checkAction($iProfileId, $iActionId, $bPerformAction); } function checkActionModule($iProfileId, $sActionName, $sModuleName, $bPerformAction = false) { $oACL = BxDolAcl::getInstance(); $iActionId = $oACL->getMembershipActionId($sActionName, $sModuleName); if (!$iActionId) bx_trigger_error("Unknown action: '$sActionName' in module '$sModuleName'", 1); return $oACL->checkAction($iProfileId, $iActionId, $bPerformAction); } function getActionNumberLeftModule($iProfileId, $sActionName, $sModuleName) { $oACL = BxDolAcl::getInstance(); $iActionId = $oACL->getMembershipActionId($sActionName, $sModuleName); if (!$iActionId) bx_trigger_error("Unknown action: '$sActionName' in module '$sModuleName'", 1); return $oACL->getActionNumberLeft($iProfileId, $iActionId); } /** @} */
unaio/una
inc/classes/BxDolAcl.php
PHP
mit
35,178
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { ViewPropTypes, Text, View } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import getStyles from './styles'; export default class DefaultMarker extends PureComponent { static propTypes = { markerStyle: ViewPropTypes.style, enabled: PropTypes.bool, currentValue: PropTypes.number, panHandlers: PropTypes.object, icon: PropTypes.bool, iconName: PropTypes.string, disabledIconName: PropTypes.string, iconColor: PropTypes.string, disabledIconColor: PropTypes.string, }; static defaultProps = { icon: false, }; renderDefault = () => { const styles = getStyles(this.props); const iconStyles = [ styles.icon, this.props.enabled ? styles.enabled : styles.disabled, ]; return ( <View style={iconStyles} /> ); }; renderIcon = () => { const styles = getStyles(this.props); const iconStyles = [ styles.icon, this.props.enabled ? styles.enabled : styles.disabled, ]; return ( <Icon size={16} style={iconStyles} selectable={false} name={this.props.enabled ? this.props.iconName : this.props.disabledIconName} color="white", backgroundColor={this.props.enabled ? this.props.iconColor : this.props.disabledIconColor} /> ); }; render() { const styles = getStyles(this.props); const rootStyles = [ styles.markerStyle, this.props.markerStyle, ]; const { currentValue } = this.props; return ( <View style={rootStyles} {...this.props.panHandlers} hitSlop={{ top: 30, bottom: 30, left: 30, right: 30 }} pointerEvents="box-only" > {this.props.icon ? this.renderIcon() : this.renderDefault()} <Text>{currentValue}</Text> </View> ); } }
joshjconlin/react-native-multi-slider-1
DefaultMarker/index.js
JavaScript
mit
1,946
/////////////////////////////////////////////////////////////////////////////// // Name: generic/vlbox.cpp // Purpose: implementation of wxVListBox // Author: Vadim Zeitlin // Modified by: // Created: 31.05.03 // RCS-ID: $Id: vlbox.cpp,v 1.22.2.1 2006/01/18 09:50:37 JS Exp $ // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org> // License: wxWindows license /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_LISTBOX #ifndef WX_PRECOMP #include "wx/settings.h" #include "wx/dcclient.h" #endif //WX_PRECOMP #include "wx/vlbox.h" #include "wx/dcbuffer.h" #include "wx/selstore.h" #include "wx/bitmap.h" // ---------------------------------------------------------------------------- // event tables // ---------------------------------------------------------------------------- BEGIN_EVENT_TABLE(wxVListBox, wxVScrolledWindow) EVT_PAINT(wxVListBox::OnPaint) EVT_KEY_DOWN(wxVListBox::OnKeyDown) EVT_LEFT_DOWN(wxVListBox::OnLeftDown) EVT_LEFT_DCLICK(wxVListBox::OnLeftDClick) END_EVENT_TABLE() // ============================================================================ // implementation // ============================================================================ IMPLEMENT_ABSTRACT_CLASS(wxVListBox, wxVScrolledWindow) // ---------------------------------------------------------------------------- // wxVListBox creation // ---------------------------------------------------------------------------- // due to ABI compatibility reasons, we need to declare double-buffer // outside the class static wxBitmap* gs_doubleBuffer = NULL; void wxVListBox::Init() { m_current = m_anchor = wxNOT_FOUND; m_selStore = NULL; } bool wxVListBox::Create(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) { style |= wxWANTS_CHARS | wxFULL_REPAINT_ON_RESIZE; if ( !wxVScrolledWindow::Create(parent, id, pos, size, style, name) ) return false; if ( style & wxLB_MULTIPLE ) m_selStore = new wxSelectionStore; // make sure the native widget has the right colour since we do // transparent drawing by default SetBackgroundColour(GetBackgroundColour()); m_colBgSel = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT); // flicker-free drawing requires this SetBackgroundStyle(wxBG_STYLE_CUSTOM); return true; } wxVListBox::~wxVListBox() { delete m_selStore; delete gs_doubleBuffer; gs_doubleBuffer = NULL; } void wxVListBox::SetItemCount(size_t count) { if ( m_selStore ) { // tell the selection store that our number of items has changed m_selStore->SetItemCount(count); } SetLineCount(count); } // ---------------------------------------------------------------------------- // selection handling // ---------------------------------------------------------------------------- bool wxVListBox::IsSelected(size_t line) const { return m_selStore ? m_selStore->IsSelected(line) : (int)line == m_current; } bool wxVListBox::Select(size_t item, bool select) { wxCHECK_MSG( m_selStore, false, _T("Select() may only be used with multiselection listbox") ); wxCHECK_MSG( item < GetItemCount(), false, _T("Select(): invalid item index") ); bool changed = m_selStore->SelectItem(item, select); if ( changed ) { // selection really changed RefreshLine(item); } DoSetCurrent(item); return changed; } bool wxVListBox::SelectRange(size_t from, size_t to) { wxCHECK_MSG( m_selStore, false, _T("SelectRange() may only be used with multiselection listbox") ); // make sure items are in correct order if ( from > to ) { size_t tmp = from; from = to; to = tmp; } wxCHECK_MSG( to < GetItemCount(), false, _T("SelectRange(): invalid item index") ); wxArrayInt changed; if ( !m_selStore->SelectRange(from, to, true, &changed) ) { // too many items have changed, we didn't record them in changed array // so we have no choice but to refresh everything between from and to RefreshLines(from, to); } else // we've got the indices of the changed items { const size_t count = changed.GetCount(); if ( !count ) { // nothing changed return false; } // refresh just the lines which have really changed for ( size_t n = 0; n < count; n++ ) { RefreshLine(changed[n]); } } // something changed return true; } bool wxVListBox::DoSelectAll(bool select) { wxCHECK_MSG( m_selStore, false, _T("SelectAll may only be used with multiselection listbox") ); size_t count = GetItemCount(); if ( count ) { wxArrayInt changed; if ( !m_selStore->SelectRange(0, count - 1, select) || !changed.IsEmpty() ) { Refresh(); // something changed return true; } } return false; } bool wxVListBox::DoSetCurrent(int current) { wxASSERT_MSG( current == wxNOT_FOUND || (current >= 0 && (size_t)current < GetItemCount()), _T("wxVListBox::DoSetCurrent(): invalid item index") ); if ( current == m_current ) { // nothing to do return false; } if ( m_current != wxNOT_FOUND ) RefreshLine(m_current); m_current = current; if ( m_current != wxNOT_FOUND ) { // if the line is not visible at all, we scroll it into view but we // don't need to refresh it -- it will be redrawn anyhow if ( !IsVisible(m_current) ) { ScrollToLine(m_current); } else // line is at least partly visible { // it is, indeed, only partly visible, so scroll it into view to // make it entirely visible while ( (size_t)m_current == GetLastVisibleLine() && ScrollToLine(GetVisibleBegin()+1) ); // but in any case refresh it as even if it was only partly visible // before we need to redraw it entirely as its background changed RefreshLine(m_current); } } return true; } void wxVListBox::SendSelectedEvent() { wxASSERT_MSG( m_current != wxNOT_FOUND, _T("SendSelectedEvent() shouldn't be called") ); wxCommandEvent event(wxEVT_COMMAND_LISTBOX_SELECTED, GetId()); event.SetEventObject(this); event.SetInt(m_current); (void)GetEventHandler()->ProcessEvent(event); } void wxVListBox::SetSelection(int selection) { wxCHECK_RET( selection == wxNOT_FOUND || (selection >= 0 && (size_t)selection < GetItemCount()), _T("wxVListBox::SetSelection(): invalid item index") ); if ( HasMultipleSelection() ) { Select(selection); m_anchor = selection; } DoSetCurrent(selection); } size_t wxVListBox::GetSelectedCount() const { return m_selStore ? m_selStore->GetSelectedCount() : m_current == wxNOT_FOUND ? 0 : 1; } int wxVListBox::GetFirstSelected(unsigned long& cookie) const { cookie = 0; return GetNextSelected(cookie); } int wxVListBox::GetNextSelected(unsigned long& cookie) const { wxCHECK_MSG( m_selStore, wxNOT_FOUND, _T("GetFirst/NextSelected() may only be used with multiselection listboxes") ); while ( cookie < GetItemCount() ) { if ( IsSelected(cookie++) ) return cookie - 1; } return wxNOT_FOUND; } // ---------------------------------------------------------------------------- // wxVListBox appearance parameters // ---------------------------------------------------------------------------- void wxVListBox::SetMargins(const wxPoint& pt) { if ( pt != m_ptMargins ) { m_ptMargins = pt; Refresh(); } } void wxVListBox::SetSelectionBackground(const wxColour& col) { m_colBgSel = col; } // ---------------------------------------------------------------------------- // wxVListBox painting // ---------------------------------------------------------------------------- wxCoord wxVListBox::OnGetLineHeight(size_t line) const { return OnMeasureItem(line) + 2*m_ptMargins.y; } void wxVListBox::OnDrawSeparator(wxDC& WXUNUSED(dc), wxRect& WXUNUSED(rect), size_t WXUNUSED(n)) const { } void wxVListBox::OnDrawBackground(wxDC& dc, const wxRect& rect, size_t n) const { // we need to render selected and current items differently const bool isSelected = IsSelected(n), isCurrent = IsCurrent(n); if ( isSelected || isCurrent ) { if ( isSelected ) { dc.SetBrush(wxBrush(m_colBgSel, wxSOLID)); } else // !selected { dc.SetBrush(*wxTRANSPARENT_BRUSH); } dc.SetPen(*(isCurrent ? wxBLACK_PEN : wxTRANSPARENT_PEN)); dc.DrawRectangle(rect); } //else: do nothing for the normal items } void wxVListBox::OnPaint(wxPaintEvent& WXUNUSED(event)) { // If size is larger, recalculate double buffer bitmap wxSize clientSize = GetClientSize(); if ( !gs_doubleBuffer || clientSize.x > gs_doubleBuffer->GetWidth() || clientSize.y > gs_doubleBuffer->GetHeight() ) { delete gs_doubleBuffer; gs_doubleBuffer = new wxBitmap(clientSize.x+25,clientSize.y+25); } wxBufferedPaintDC dc(this,*gs_doubleBuffer); // the update rectangle wxRect rectUpdate = GetUpdateClientRect(); // Fill it with background colour dc.SetBrush(GetBackgroundColour()); dc.Clear(); // the bounding rectangle of the current line wxRect rectLine; rectLine.width = clientSize.x; // iterate over all visible lines const size_t lineMax = GetLastVisibleLine(); for ( size_t line = GetFirstVisibleLine(); line <= lineMax; line++ ) { const wxCoord hLine = OnGetLineHeight(line); rectLine.height = hLine; // and draw the ones which intersect the update rect if ( rectLine.Intersects(rectUpdate) ) { // don't allow drawing outside of the lines rectangle wxDCClipper clip(dc, rectLine); wxRect rect = rectLine; OnDrawBackground(dc, rect, line); OnDrawSeparator(dc, rect, line); rect.Deflate(m_ptMargins.x, m_ptMargins.y); OnDrawItem(dc, rect, line); } else // no intersection { if ( rectLine.GetTop() > rectUpdate.GetBottom() ) { // we are already below the update rect, no need to continue // further break; } //else: the next line may intersect the update rect } rectLine.y += hLine; } } // ============================================================================ // wxVListBox keyboard/mouse handling // ============================================================================ void wxVListBox::DoHandleItemClick(int item, int flags) { // has anything worth telling the client code about happened? bool notify = false; if ( HasMultipleSelection() ) { // select the iteem clicked? bool select = true; // NB: the keyboard interface we implement here corresponds to // wxLB_EXTENDED rather than wxLB_MULTIPLE but this one makes more // sense IMHO if ( flags & ItemClick_Shift ) { if ( m_current != wxNOT_FOUND ) { if ( m_anchor == wxNOT_FOUND ) m_anchor = m_current; select = false; // only the range from the selection anchor to new m_current // must be selected if ( DeselectAll() ) notify = true; if ( SelectRange(m_anchor, item) ) notify = true; } //else: treat it as ordinary click/keypress } else // Shift not pressed { m_anchor = item; if ( flags & ItemClick_Ctrl ) { select = false; if ( !(flags & ItemClick_Kbd) ) { Toggle(item); // the status of the item has definitely changed notify = true; } //else: Ctrl-arrow pressed, don't change selection } //else: behave as in single selection case } if ( select ) { // make the clicked item the only selection if ( DeselectAll() ) notify = true; if ( Select(item) ) notify = true; } } // in any case the item should become the current one if ( DoSetCurrent(item) ) { if ( !HasMultipleSelection() ) { // this has also changed the selection for single selection case notify = true; } } if ( notify ) { // notify the user about the selection change SendSelectedEvent(); } //else: nothing changed at all } // ---------------------------------------------------------------------------- // keyboard handling // ---------------------------------------------------------------------------- void wxVListBox::OnKeyDown(wxKeyEvent& event) { // flags for DoHandleItemClick() int flags = ItemClick_Kbd; int current; switch ( event.GetKeyCode() ) { case WXK_HOME: current = 0; break; case WXK_END: current = GetLineCount() - 1; break; case WXK_DOWN: if ( m_current == (int)GetLineCount() - 1 ) return; current = m_current + 1; break; case WXK_UP: if ( m_current == wxNOT_FOUND ) current = GetLineCount() - 1; else if ( m_current != 0 ) current = m_current - 1; else // m_current == 0 return; break; case WXK_PAGEDOWN: case WXK_NEXT: PageDown(); current = GetFirstVisibleLine(); break; case WXK_PAGEUP: case WXK_PRIOR: if ( m_current == (int)GetFirstVisibleLine() ) { PageUp(); } current = GetFirstVisibleLine(); break; case WXK_SPACE: // hack: pressing space should work like a mouse click rather than // like a keyboard arrow press, so trick DoHandleItemClick() in // thinking we were clicked flags &= ~ItemClick_Kbd; current = m_current; break; #ifdef __WXMSW__ case WXK_TAB: // Since we are using wxWANTS_CHARS we need to send navigation // events for the tabs on MSW { wxNavigationKeyEvent ne; ne.SetDirection(!event.ShiftDown()); ne.SetCurrentFocus(this); ne.SetEventObject(this); GetParent()->GetEventHandler()->ProcessEvent(ne); } // fall through to default #endif default: event.Skip(); current = 0; // just to silent the stupid compiler warnings wxUnusedVar(current); return; } if ( event.ShiftDown() ) flags |= ItemClick_Shift; if ( event.ControlDown() ) flags |= ItemClick_Ctrl; DoHandleItemClick(current, flags); } // ---------------------------------------------------------------------------- // wxVListBox mouse handling // ---------------------------------------------------------------------------- void wxVListBox::OnLeftDown(wxMouseEvent& event) { SetFocus(); int item = HitTest(event.GetPosition()); if ( item != wxNOT_FOUND ) { int flags = 0; if ( event.ShiftDown() ) flags |= ItemClick_Shift; // under Mac Apple-click is used in the same way as Ctrl-click // elsewhere #ifdef __WXMAC__ if ( event.MetaDown() ) #else if ( event.ControlDown() ) #endif flags |= ItemClick_Ctrl; DoHandleItemClick(item, flags); } } void wxVListBox::OnLeftDClick(wxMouseEvent& eventMouse) { int item = HitTest(eventMouse.GetPosition()); if ( item != wxNOT_FOUND ) { // if item double-clicked was not yet selected, then treat // this event as a left-click instead if ( item == m_current ) { wxCommandEvent event(wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, GetId()); event.SetEventObject(this); event.SetInt(item); (void)GetEventHandler()->ProcessEvent(event); } else { OnLeftDown(eventMouse); } } } // ---------------------------------------------------------------------------- // use the same default attributes as wxListBox // ---------------------------------------------------------------------------- #include "wx/listbox.h" //static wxVisualAttributes wxVListBox::GetClassDefaultAttributes(wxWindowVariant variant) { return wxListBox::GetClassDefaultAttributes(variant); } #endif
SickheadGames/Torsion
code/wxWidgets/src/generic/vlbox.cpp
C++
mit
18,240
// // Load the AWS SDK for Node.js // var i = console.log(Math.round(new Date().getTime()/1000.0).toFixed(1)); // var AWS = require('aws-sdk'); // var path = require('path'); // var fs = require('fs'); // // // Load credentials and set region from JSON file // AWS.config.loadFromPath("/Users/jorge/Documents/javascipt_workspace/docking_station/uploader/config.json"); // AWS.config.update({endpoint: "https://dynamodb.sa-east-1.amazonaws.com"}); // // var DynamoDBManager = function () { }; // // DynamoDBManager.uploadToDynamo = function (sensor, file_path, table) { // var docClient = new AWS.DynamoDB.DocumentClient(); // var information = fs.readFileSync(file_path, 'utf-8'); // console.log("INFORMACION: " + information); // var params = { // TableName:table, // Item:{ // "sensor":sensor, // "timeStamp":file_path.split("/").pop(), // "data":information // } // }; // docClient.put(params, function(err, data) { // if (err) { // console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2)); // } else { // console.log("Added item:", JSON.stringify(data, null, 2)); // } // }); // console.log(Math.round(new Date().getTime()/1000.0) - i); // }; // // DynamoDBManager.getItemFromDynamo = function (sensor, timestamp, bucket) { // // } // // // module.exports = DynamoDBManager;
PulseraMartin/docking_station
uploader/dynamoDBManager.js
JavaScript
mit
1,405
<?php namespace c2g\Base; /** * FoundationPile base class * * @author Thurairajah Thujeevan <thujee@gmail.com> */ class FoundationPile extends Pile { const LIMIT = 13; const NAME = 'Foundation'; /** * data member of this class, which holds the base card * when this pile is circular * @var Card */ static $baseCard; /** * Constructor function which initializes foundation pile with * pile name and the cards limit * Foundation piles are not fanned usually * * @param boolean $circular true if this is circular pile */ public function __construct($circular) { parent::__construct(self::LIMIT, self::NAME); $this->circular = $circular; $this->fanned = FALSE; } /** * Specialied version of Pile's can add function, control the restrictions * of adding cards to this pile * * @param \c2g\Base\Card $card card to be added to this pile * @param \c2g\Base\Pile $src the pile from which the card comes * @return boolean */ public function canAdd(Card $card, Pile $src = NULL) { if ($this->count() == $this->limit) { // pile is full return FALSE; } if (!$this->isEmpty() && !$card->isSameSuit($this->top())) { // doesn't belong to same suit return FALSE; } // pile is not circular // pile count is zero // card is not A if (!$this->circular && $this->isEmpty() && !$card->isFirstInRank()) { return FALSE; } // circular pile // has at least one card - implies, should have baseCard // topcard is K and card to be inserted is A if ($this->circular && !$this->isEmpty() && $this->top()->isLastInRank() && $card->isFirstInRank()) { return TRUE; } // can be circular or non circular if (!$this->isEmpty() && !$card->isGreaterThanByOne($this->top())) { return FALSE; } // circular pile // empty pile // basecard exists // card to be added not as equal as basecard in rank if ($this->circular && $this->isEmpty() && static::$baseCard && !$card->isEqual(static::$baseCard)) { return FALSE; } return TRUE; } /** * Foundation pile usually doesn't allow to remove cards * * @param \c2g\Base\Pile $dest Pile to which the card to be added * @return boolean */ public function canRemove(Pile $dest = NULL) { return FALSE; } /** * overridden function of Pile's add card * Since foundation piles can be circular sometimes * * @param \c2g\Base\Card $card * @return Pile */ public function addCard(Card $card) { if ($this->circular && $this->isEmpty()) { static::$baseCard = $card; } return parent::addCard(!$card->isFacedUp() ? $card->flip() : $card); } }
thujeevan/c2g
src/Base/FoundationPile.php
PHP
mit
3,047
using System; class SayHello { static void Main() { string name = Console.ReadLine(); printName(name); } static void printName(string name) { Console.WriteLine("Hello, {0}!", name); } }
ndvalkov/TelerikAcademy2016
Homework/CSharp-Part-2/03. Methods/SayHello.cs
C#
mit
235
// Copyright (c) 2011-2013 The BeCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "wallet/wallet.h" #include <boost/foreach.hpp> #include <QFont> #include <QDebug> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type type, const QString &label, const QString &address): type(type), label(label), address(address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const { return a.address < b.address; } bool operator()(const AddressTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const AddressTableEntry &b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet *wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; AddressTablePriv(CWallet *wallet, AddressTableModel *parent): wallet(wallet), parent(parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, wallet->mapAddressBook) { const CBeCoinAddress& address = item.first; bool fMine = IsMine(*wallet, address.Get()); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch(status) { case CT_NEW: if(inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: if(rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::becoinAddressFont(); } return font; } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if(role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = CBeCoinAddress(rec->address.toStdString()).Get(); if(index.column() == Label) { // Do nothing, if old label == new label if(rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if(index.column() == Address) { CTxDestination newAddress = CBeCoinAddress(value.toString().toStdString()).Get(); // Refuse to set invalid address, set error status and return false if(boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if(newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if(wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if(rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if(rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column()==Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Update address book model from BeCoin core priv->updateEntry(address, label, isMine, purpose, status); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if(type == Send) { if(!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if(wallet->mapAddressBook.count(CBeCoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if(!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if(!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = CBeCoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(CBeCoinAddress(strAddress).Get(), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(CBeCoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString &address) const { { LOCK(wallet->cs_wallet); CBeCoinAddress address_parsed(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); }
MasterX1582/bitcoin-becoin
src/qt/addresstablemodel.cpp
C++
mit
14,351
import _plotly_utils.basevalidators class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__(self, plotly_name="bgcolor", parent_name="pie.hoverlabel", **kwargs): super(BgcolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "style"), **kwargs )
plotly/python-api
packages/python/plotly/plotly/validators/pie/hoverlabel/_bgcolor.py
Python
mit
499
package be.echostyle.moola; import be.echostyle.moola.filters.TransactionFilter; import java.time.LocalDateTime; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public interface GroupedAccount extends Account { default AccountType getType(){ return AccountType.GROUPED; } Set<Account> getMembers(); void addMember(Account member); void removeMember(Account member); default void setMembers(Set<Account> members){ Set<Account> original = getMembers(); for (Account originalMember : original) if (!members.contains(originalMember)) removeMember(originalMember); for (Account newMember : members){ if (!original.contains(newMember)) addMember(newMember); } } @Override default List<AccountEntry> getTransactions(LocalDateTime from, LocalDateTime to) { return getMembers().stream().flatMap(member -> member.getTransactions(from, to).stream()) .sorted(Comparator.comparing(AccountEntry::getTimestamp).thenComparing(AccountEntry::getId)) .collect(Collectors.toList()); } @Override default List<AccountEntry> getTransactions(String batchId) { return getMembers().stream().flatMap(member -> member.getTransactions(batchId).stream()) .sorted(Comparator.comparing(AccountEntry::getTimestamp).thenComparing(AccountEntry::getId)) .collect(Collectors.toList()); } @Override default List<AccountEntry> getTransactions(LocalDateTime to, int count, int from) { //TODO: this count+from trick will work, but it's far from optimal return getMembers().stream().flatMap(member -> member.getTransactions(to, count + from, 0).stream()) .sorted(Comparator.comparing(AccountEntry::getTimestamp).thenComparing(AccountEntry::getId)) .skip(from) .limit(count) .collect(Collectors.toList()); } @Override default List<AccountEntry> getTransactions(LocalDateTime to, TransactionFilter filter, int count, int from) { return getMembers().stream().flatMap(member -> member.getTransactions(to, filter, count + from, 0).stream()) .sorted(Comparator.comparing(AccountEntry::getTimestamp).thenComparing(AccountEntry::getId)) .skip(from) .limit(count) .collect(Collectors.toList()); } @Override default AccountEntry getTransaction(String id) { for (Account member:getMembers()){ AccountEntry r = member.getTransaction(id); if (r!=null) return r; } return null; } @Override default boolean contains(AccountEntry entry) { for (Account member : getMembers()){ if (member.contains(entry)) return true; } return false; } @Override default Set<String> getSimpleIds() { return getMembers().stream().flatMap(acc -> acc.getSimpleIds().stream()).collect(Collectors.toSet()); } }
Kjoep/moola
moola-domain/src/main/java/be/echostyle/moola/GroupedAccount.java
Java
mit
3,248
# Options require 'bobkit' include Bobkit::Tasks # Set options (these are only partial, and the defaults) templates_folder 'templates' layouts_folder "#{templates_folder}/layouts" styles_folder 'styles' output_folder 'output' css_output_folder "#{output_folder}/css" js_output_folder "#{output_folder}/js" # Generate the site render 'youtube', layout: 'default', video: 'tntOCGkgt98', output: "cat" compile_css 'main', output: 'style' compile_js 'main', output: 'script' # Output is in the output folder
DannyBen/bobkit
examples/03_options/example.rb
Ruby
mit
558
package seedu.jobs.storage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Optional; import java.util.logging.Logger; import seedu.jobs.commons.core.LogsCenter; import seedu.jobs.commons.exceptions.DataConversionException; import seedu.jobs.commons.util.FileUtil; import seedu.jobs.model.ReadOnlyTaskBook; /** * A class to access AddressBook data stored as an xml file on the hard disk. */ public class XmlTaskBookStorage implements TaskBookStorage { private static final Logger logger = LogsCenter.getLogger(XmlTaskBookStorage.class); private String filePath; public XmlTaskBookStorage(String filePath) { this.filePath = filePath; } public String getTaskBookFilePath() { return filePath; } @Override public Optional<ReadOnlyTaskBook> readTaskBook() throws DataConversionException, IOException { return readTaskBook(filePath); } /** * Similar to {@link #readTaskBook()} * @param filePath location of the data. Cannot be null * @throws DataConversionException if the file is not in the correct format. */ public Optional<ReadOnlyTaskBook> readTaskBook(String filePath) throws DataConversionException, FileNotFoundException { assert filePath != null; File taskBookFile = new File(filePath); if (!taskBookFile.exists()) { logger.info("TaskBook file " + taskBookFile + " not found"); return Optional.empty(); } ReadOnlyTaskBook taskBookOptional = XmlFileStorage.loadDataFromSaveFile(new File(filePath)); return Optional.of(taskBookOptional); } @Override public void saveTaskBook(ReadOnlyTaskBook taskBook) throws IOException { saveTaskBook(taskBook, filePath); } /** * Similar to {@link #saveAddressBook(ReadOnlyTaskBook)} * @param filePath location of the data. Cannot be null */ public void saveTaskBook(ReadOnlyTaskBook taskBook, String filePath) throws IOException { assert taskBook != null; assert filePath != null; File file = new File(filePath); FileUtil.createIfMissing(file); XmlFileStorage.saveDataToFile(file, new XmlSerializableTaskBook(taskBook)); } public void setFilePath(String filePath) { this.filePath = filePath; } }
CS2103JAN2017-F11-B1/main
src/main/java/seedu/jobs/storage/XmlTaskBookStorage.java
Java
mit
2,457
/** Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. [jasmine-gem]: http://github.com/pivotal/jasmine-gem */ (function() { /** * ## Require &amp; Instantiate * * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. */ window.jasmine = jasmineRequire.core(jasmineRequire); /** * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. */ jasmineRequire.html(jasmine); /** * Create the Jasmine environment. This is used to run all specs in a project. */ var env = jasmine.getEnv(); var originalExecute = env.execute; /** * ## The Global Interface * * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. */ var jasmineInterface = jasmineRequire.interface(jasmine, env); /** * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. */ extend(window, jasmineInterface); /** * ## Runner Parameters * * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. */ var queryString = new jasmine.QueryString({ getWindowLocation: function() { return window.location; } }); var catchingExceptions = queryString.getParam("catch"); env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions); var throwingExpectationFailures = queryString.getParam("throwFailures"); env.throwOnExpectationFailure(throwingExpectationFailures); var random = queryString.getParam("random"); env.randomizeTests(random); var seed = queryString.getParam("seed"); if (seed) { env.seed(seed); } /** * ## Reporters * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). */ var htmlReporter = new jasmine.HtmlReporter({ env: env, onRaiseExceptionsClick: function() { queryString.navigateWithNewParam("catch", !env.catchingExceptions()); }, onThrowExpectationsClick: function() { queryString.navigateWithNewParam("throwFailures", !env.throwingExpectationFailures()); }, onRandomClick: function() { queryString.navigateWithNewParam("random", !env.randomTests()); }, addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, getContainer: function() { return document.body; }, createElement: function() { return document.createElement.apply(document, arguments); }, createTextNode: function() { return document.createTextNode.apply(document, arguments); }, timer: new jasmine.Timer() }); /** * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. */ env.addReporter(jasmineInterface.jsApiReporter); env.addReporter(htmlReporter); /** * Filter which specs will be run by matching the start of the full name against the `spec` query param. */ var specFilter = new jasmine.HtmlSpecFilter({ filterString: function() { return queryString.getParam("spec"); } }); env.specFilter = function(spec) { return specFilter.matches(spec.getFullName()); }; /** * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. */ window.setTimeout = window.setTimeout; window.setInterval = window.setInterval; window.clearTimeout = window.clearTimeout; window.clearInterval = window.clearInterval; /** * ## Execution * * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. */ // [Chutzpah]: Wrapping the onload code in a new function to be called and extracted a separate function for the starting Jasmine var initialized = false; window.initializeJasmine = function () { // [Chutzpah]: Guard against multiple initializations when running blanket if (!initialized && originalExecute == env.execute) { htmlReporter.initialize(); env.execute(); initialized = true; } }; window.initializeJasmineOnLoad = function() { var currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { currentWindowOnload(); } window.initializeJasmine(); }; }; /** * Helper function for readability above. */ function extend(destination, source) { for (var property in source) destination[property] = source[property]; return destination; } }());
mukulikadey/SOEN341-Group1
chutzpah/Chutzpah/TestFiles/Jasmine/v2/boot.js
JavaScript
mit
5,936
package net.lightbody.bmp; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.MapMaker; import net.lightbody.bmp.client.ClientUtil; import net.lightbody.bmp.core.har.Har; import net.lightbody.bmp.core.har.HarLog; import net.lightbody.bmp.core.har.HarNameVersion; import net.lightbody.bmp.core.har.HarPage; import net.lightbody.bmp.filters.AddHeadersFilter; import net.lightbody.bmp.filters.AutoBasicAuthFilter; import net.lightbody.bmp.filters.BlacklistFilter; import net.lightbody.bmp.filters.BrowserMobHttpFilterChain; import net.lightbody.bmp.filters.HarCaptureFilter; import net.lightbody.bmp.filters.HttpConnectHarCaptureFilter; import net.lightbody.bmp.filters.HttpsHostCaptureFilter; import net.lightbody.bmp.filters.HttpsOriginalHostCaptureFilter; import net.lightbody.bmp.filters.LatencyFilter; import net.lightbody.bmp.filters.RegisterRequestFilter; import net.lightbody.bmp.filters.RequestFilter; import net.lightbody.bmp.filters.RequestFilterAdapter; import net.lightbody.bmp.filters.ResolvedHostnameCacheFilter; import net.lightbody.bmp.filters.ResponseFilter; import net.lightbody.bmp.filters.ResponseFilterAdapter; import net.lightbody.bmp.filters.RewriteUrlFilter; import net.lightbody.bmp.filters.UnregisterRequestFilter; import net.lightbody.bmp.filters.WhitelistFilter; import net.lightbody.bmp.mitm.KeyStoreFileCertificateSource; import net.lightbody.bmp.mitm.TrustSource; import net.lightbody.bmp.mitm.keys.ECKeyGenerator; import net.lightbody.bmp.mitm.keys.RSAKeyGenerator; import net.lightbody.bmp.mitm.manager.ImpersonatingMitmManager; import net.lightbody.bmp.proxy.ActivityMonitor; import net.lightbody.bmp.proxy.BlacklistEntry; import net.lightbody.bmp.proxy.CaptureType; import net.lightbody.bmp.proxy.RewriteRule; import net.lightbody.bmp.proxy.Whitelist; import net.lightbody.bmp.proxy.auth.AuthType; import net.lightbody.bmp.proxy.dns.AdvancedHostResolver; import net.lightbody.bmp.proxy.dns.DelegatingHostResolver; import net.lightbody.bmp.util.BrowserMobHttpUtil; import net.lightbody.bmp.util.BrowserMobProxyUtil; import org.littleshoot.proxy.ChainedProxy; import org.littleshoot.proxy.ChainedProxyAdapter; import org.littleshoot.proxy.ChainedProxyManager; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersSource; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.HttpProxyServerBootstrap; import org.littleshoot.proxy.MitmManager; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import org.littleshoot.proxy.impl.ProxyUtils; import org.littleshoot.proxy.impl.ThreadPoolConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; /** * A LittleProxy-based implementation of {@link net.lightbody.bmp.BrowserMobProxy}. */ public class BrowserMobProxyServer implements BrowserMobProxy { private static final Logger log = LoggerFactory.getLogger(BrowserMobProxyServer.class); private static final HarNameVersion HAR_CREATOR_VERSION = new HarNameVersion("BrowserMob Proxy", BrowserMobProxyUtil.getVersionString()); /* Default MITM resources */ private static final String RSA_KEYSTORE_RESOURCE = "/sslSupport/ca-keystore-rsa.p12"; private static final String EC_KEYSTORE_RESOURCE = "/sslSupport/ca-keystore-ec.p12"; private static final String KEYSTORE_TYPE = "PKCS12"; private static final String KEYSTORE_PRIVATE_KEY_ALIAS = "key"; private static final String KEYSTORE_PASSWORD = "password"; /** * The default pseudonym to use when adding the Via header to proxied requests. */ public static final String VIA_HEADER_ALIAS = "browsermobproxy"; /** * True only after the proxy has been successfully started. */ private final AtomicBoolean started = new AtomicBoolean(false); /** * True only after the proxy has been successfully started, then successfully stopped or aborted. */ private final AtomicBoolean stopped = new AtomicBoolean(false); /** * Tracks the current page count, for use when auto-generating HAR page names. */ private final AtomicInteger harPageCount = new AtomicInteger(0); /** * When true, MITM will be disabled. The proxy will no longer intercept HTTPS requests, but they will still be proxied. */ private volatile boolean mitmDisabled = false; /** * The MITM manager that will be used for HTTPS requests. */ private volatile MitmManager mitmManager; /** * The list of filterFactories that will generate the filters that implement browsermob-proxy behavior. */ private final List<HttpFiltersSource> filterFactories = new CopyOnWriteArrayList<>(); /** * List of rejected URL patterns */ private volatile Collection<BlacklistEntry> blacklistEntries = new CopyOnWriteArrayList<>(); /** * List of URLs to rewrite */ private volatile CopyOnWriteArrayList<RewriteRule> rewriteRules = new CopyOnWriteArrayList<>(); /** * The LittleProxy instance that performs all proxy operations. */ private volatile HttpProxyServer proxyServer; /** * No capture types are enabled by default. */ private volatile EnumSet<CaptureType> harCaptureTypes = EnumSet.noneOf(CaptureType.class); /** * The current HAR being captured. */ private volatile Har har; /** * The current HarPage to which new requests will be associated. */ private volatile HarPage currentHarPage; /** * Maximum bandwidth to consume when reading responses from servers. */ private volatile long readBandwidthLimitBps; /** * Maximum bandwidth to consume when writing requests to servers. */ private volatile long writeBandwidthLimitBps; /** * List of accepted URL patterns. Unlisted URL patterns will be rejected with the response code contained in the Whitelist. */ private final AtomicReference<Whitelist> whitelist = new AtomicReference<>(Whitelist.WHITELIST_DISABLED); /** * Additional headers that will be sent with every request. The map is declared as a ConcurrentMap to indicate that writes may be performed * by other threads concurrently (e.g. due to an incoming REST call), but the concurrencyLevel is set to 1 because modifications to the * additionalHeaders are rare, and in most cases happen only once, at start-up. */ private volatile ConcurrentMap<String, String> additionalHeaders = new MapMaker().concurrencyLevel(1).makeMap(); /** * The amount of time to wait while connecting to a server. */ private volatile int connectTimeoutMs; /** * The amount of time a connection to a server can remain idle while receiving data from the server. */ private volatile int idleConnectionTimeoutSec; /** * The amount of time to wait before forwarding the response to the client. */ private volatile int latencyMs; /** * Set to true once the HAR capture filter has been added to the filter chain. */ private final AtomicBoolean harCaptureFilterEnabled = new AtomicBoolean(false); /** * The address of an upstream chained proxy to route traffic through. */ private volatile InetSocketAddress upstreamProxyAddress; /** * The chained proxy manager that manages upstream proxies. */ private volatile ChainedProxyManager chainedProxyManager; /** * The address of the network interface from which the proxy will initiate connections. */ private volatile InetAddress serverBindAddress; /** * The TrustSource that will be used to validate servers' certificates. If null, will not validate server certificates. */ private volatile TrustSource trustSource = TrustSource.defaultTrustSource(); /** * When true, use Elliptic Curve keys and certificates when impersonating upstream servers. */ private volatile boolean useEcc = false; /** * Resolver to use when resolving hostnames to IP addresses. This is a bridge between {@link org.littleshoot.proxy.HostResolver} and * {@link net.lightbody.bmp.proxy.dns.AdvancedHostResolver}. It allows the resolvers to be changed on-the-fly without re-bootstrapping the * littleproxy server. The default resolver (native JDK resolver) can be changed using {@link #setHostNameResolver(net.lightbody.bmp.proxy.dns.AdvancedHostResolver)} and * supplying one of the pre-defined resolvers in {@link ClientUtil}, such as {@link ClientUtil#createDnsJavaWithNativeFallbackResolver()} * or {@link ClientUtil#createDnsJavaResolver()}. You can also build your own resolver, or use {@link net.lightbody.bmp.proxy.dns.ChainedHostResolver} * to chain together multiple DNS resolvers. */ private final DelegatingHostResolver delegatingResolver = new DelegatingHostResolver(ClientUtil.createNativeCacheManipulatingResolver()); private final ActivityMonitor activityMonitor = new ActivityMonitor(); /** * The acceptor and worker thread configuration for the Netty thread pools. */ private volatile ThreadPoolConfiguration threadPoolConfiguration; /** * A mapping of hostnames to base64-encoded Basic auth credentials that will be added to the Authorization header for * matching requests. */ private final ConcurrentMap<String, String> basicAuthCredentials = new MapMaker() .concurrencyLevel(1) .makeMap(); /** * Base64-encoded credentials to use to authenticate with the upstream proxy. */ private volatile String chainedProxyCredentials; public BrowserMobProxyServer() { } @Override public void start(int port, InetAddress clientBindAddress, InetAddress serverBindAddress) { boolean notStarted = started.compareAndSet(false, true); if (!notStarted) { throw new IllegalStateException("Proxy server is already started. Not restarting."); } InetSocketAddress clientBindSocket; if (clientBindAddress == null) { // if no client bind address was specified, bind to the wildcard address clientBindSocket = new InetSocketAddress(port); } else { clientBindSocket = new InetSocketAddress(clientBindAddress, port); } this.serverBindAddress = serverBindAddress; // initialize all the default BrowserMob filter factories that provide core BMP functionality addBrowserMobFilters(); HttpProxyServerBootstrap bootstrap = DefaultHttpProxyServer.bootstrap() .withFiltersSource(new HttpFiltersSource() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext channelHandlerContext) { return new BrowserMobHttpFilterChain(BrowserMobProxyServer.this, originalRequest, channelHandlerContext); } @Override public int getMaximumRequestBufferSizeInBytes() { return getMaximumRequestBufferSize(); } @Override public int getMaximumResponseBufferSizeInBytes() { return getMaximumResponseBufferSize(); } }) .withServerResolver(delegatingResolver) .withAddress(clientBindSocket) .withConnectTimeout(connectTimeoutMs) .withIdleConnectionTimeout(idleConnectionTimeoutSec) .withProxyAlias(VIA_HEADER_ALIAS); if (serverBindAddress != null) { bootstrap.withNetworkInterface(new InetSocketAddress(serverBindAddress, 0)); } if (!mitmDisabled) { if (mitmManager == null) { mitmManager = ImpersonatingMitmManager.builder() .rootCertificateSource(new KeyStoreFileCertificateSource( KEYSTORE_TYPE, useEcc ? EC_KEYSTORE_RESOURCE : RSA_KEYSTORE_RESOURCE, KEYSTORE_PRIVATE_KEY_ALIAS, KEYSTORE_PASSWORD)) .serverKeyGenerator(useEcc ? new ECKeyGenerator() : new RSAKeyGenerator()) .trustSource(trustSource) .build(); } bootstrap.withManInTheMiddle(mitmManager); } if (readBandwidthLimitBps > 0 || writeBandwidthLimitBps > 0) { bootstrap.withThrottling(readBandwidthLimitBps, writeBandwidthLimitBps); } if (chainedProxyManager != null) { bootstrap.withChainProxyManager(chainedProxyManager); } else if (upstreamProxyAddress != null) { bootstrap.withChainProxyManager(new ChainedProxyManager() { @Override public void lookupChainedProxies(HttpRequest httpRequest, Queue<ChainedProxy> chainedProxies) { final InetSocketAddress upstreamProxy = upstreamProxyAddress; if (upstreamProxy != null) { chainedProxies.add(new ChainedProxyAdapter() { @Override public InetSocketAddress getChainedProxyAddress() { return upstreamProxy; } @Override public void filterRequest(HttpObject httpObject) { String chainedProxyAuth = chainedProxyCredentials; if (chainedProxyAuth != null) { if (httpObject instanceof HttpRequest) { HttpHeaders.addHeader((HttpRequest)httpObject, HttpHeaders.Names.PROXY_AUTHORIZATION, "Basic " + chainedProxyAuth); } } } }); } } }); } if (threadPoolConfiguration != null) { bootstrap.withThreadPoolConfiguration(threadPoolConfiguration); } proxyServer = bootstrap.start(); } @Override public boolean isStarted() { return started.get(); } @Override public void start(int port) { this.start(port, null, null); } @Override public void start(int port, InetAddress bindAddress) { this.start(port, bindAddress, null); } @Override public void start() { this.start(0); } @Override public void stop() { stop(true); } @Override public void abort() { stop(false); } protected void stop(boolean graceful) { if (isStarted()) { if (stopped.compareAndSet(false, true)) { if (proxyServer != null) { if (graceful) { proxyServer.stop(); } else { proxyServer.abort(); } } else { log.warn("Attempted to stop proxy server, but proxy was never successfully started."); } } else { throw new IllegalStateException("Proxy server is already stopped. Cannot re-stop."); } } else { throw new IllegalStateException("Proxy server has not been started"); } } @Override public InetAddress getClientBindAddress() { if (started.get()) { return proxyServer.getListenAddress().getAddress(); } else { return null; } } @Override public int getPort() { if (started.get()) { return proxyServer.getListenAddress().getPort(); } else { return 0; } } @Override public InetAddress getServerBindAddress() { return serverBindAddress; } @Override public Har getHar() { return har; } @Override public Har newHar() { return newHar(null); } @Override public Har newHar(String initialPageRef) { return newHar(initialPageRef, null); } @Override public Har newHar(String initialPageRef, String initialPageTitle) { Har oldHar = getHar(); addHarCaptureFilter(); harPageCount.set(0); this.har = new Har(new HarLog(HAR_CREATOR_VERSION)); newPage(initialPageRef, initialPageTitle); return oldHar; } @Override public void setHarCaptureTypes(Set<CaptureType> harCaptureSettings) { if (harCaptureSettings == null || harCaptureSettings.isEmpty()) { harCaptureTypes = EnumSet.noneOf(CaptureType.class); } else { harCaptureTypes = EnumSet.copyOf(harCaptureSettings); } } @Override public void setHarCaptureTypes(CaptureType... captureTypes) { if (captureTypes == null) { setHarCaptureTypes(EnumSet.noneOf(CaptureType.class)); } else { setHarCaptureTypes(EnumSet.copyOf(Arrays.asList(captureTypes))); } } @Override public EnumSet<CaptureType> getHarCaptureTypes() { return EnumSet.copyOf(harCaptureTypes); } @Override public void enableHarCaptureTypes(Set<CaptureType> captureTypes) { harCaptureTypes.addAll(captureTypes); } @Override public void enableHarCaptureTypes(CaptureType... captureTypes) { if (captureTypes == null) { enableHarCaptureTypes(EnumSet.noneOf(CaptureType.class)); } else { enableHarCaptureTypes(EnumSet.copyOf(Arrays.asList(captureTypes))); } } @Override public void disableHarCaptureTypes(Set<CaptureType> captureTypes) { harCaptureTypes.removeAll(captureTypes); } @Override public void disableHarCaptureTypes(CaptureType... captureTypes) { if (captureTypes == null) { disableHarCaptureTypes(EnumSet.noneOf(CaptureType.class)); } else { disableHarCaptureTypes(EnumSet.copyOf(Arrays.asList(captureTypes))); } } @Override public Har newPage() { return newPage(null); } @Override public Har newPage(String pageRef) { return newPage(pageRef, null); } @Override public Har newPage(String pageRef, String pageTitle) { if (har == null) { throw new IllegalStateException("No HAR exists for this proxy. Use newHar() to create a new HAR before calling newPage()."); } Har endOfPageHar = null; if (currentHarPage != null) { String currentPageRef = currentHarPage.getId(); // end the previous page, so that page-wide timings are populated endPage(); // the interface requires newPage() to return the Har as it was immediately after the previous page was ended. endOfPageHar = BrowserMobProxyUtil.copyHarThroughPageRef(har, currentPageRef); } if (pageRef == null) { pageRef = "Page " + harPageCount.getAndIncrement(); } if (pageTitle == null) { pageTitle = pageRef; } HarPage newPage = new HarPage(pageRef, pageTitle); har.getLog().addPage(newPage); currentHarPage = newPage; return endOfPageHar; } @Override public Har endHar() { Har oldHar = getHar(); // end the page and populate timings endPage(); this.har = null; return oldHar; } @Override public void setReadBandwidthLimit(long bytesPerSecond) { this.readBandwidthLimitBps = bytesPerSecond; if (isStarted()) { proxyServer.setThrottle(this.readBandwidthLimitBps, this.writeBandwidthLimitBps); } } @Override public long getReadBandwidthLimit() { return readBandwidthLimitBps; } @Override public void setWriteBandwidthLimit(long bytesPerSecond) { this.writeBandwidthLimitBps = bytesPerSecond; if (isStarted()) { proxyServer.setThrottle(this.readBandwidthLimitBps, this.writeBandwidthLimitBps); } } @Override public long getWriteBandwidthLimit() { return writeBandwidthLimitBps; } public void endPage() { if (har == null) { throw new IllegalStateException("No HAR exists for this proxy. Use newHar() to create a new HAR."); } HarPage previousPage = this.currentHarPage; this.currentHarPage = null; if (previousPage == null) { return; } previousPage.getPageTimings().setOnLoad(new Date().getTime() - previousPage.getStartedDateTime().getTime()); } @Override public void addHeaders(Map<String, String> headers) { ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap(); newHeaders.putAll(headers); this.additionalHeaders = newHeaders; } @Override public void setLatency(long latency, TimeUnit timeUnit) { this.latencyMs = (int) TimeUnit.MILLISECONDS.convert(latency, timeUnit); } @Override public void autoAuthorization(String domain, String username, String password, AuthType authType) { switch (authType) { case BASIC: // base64 encode the "username:password" string String base64EncodedCredentials = BrowserMobHttpUtil.base64EncodeBasicCredentials(username, password); basicAuthCredentials.put(domain, base64EncodedCredentials); break; default: throw new UnsupportedOperationException("AuthType " + authType + " is not supported for HTTP Authorization"); } } @Override public void stopAutoAuthorization(String domain) { basicAuthCredentials.remove(domain); } @Override public void chainedProxyAuthorization(String username, String password, AuthType authType) { switch (authType) { case BASIC: chainedProxyCredentials = BrowserMobHttpUtil.base64EncodeBasicCredentials(username, password); break; default: throw new UnsupportedOperationException("AuthType " + authType + " is not supported for Proxy Authorization"); } } @Override public void setConnectTimeout(int connectTimeout, TimeUnit timeUnit) { this.connectTimeoutMs = (int) TimeUnit.MILLISECONDS.convert(connectTimeout, timeUnit); if (isStarted()) { proxyServer.setConnectTimeout((int) TimeUnit.MILLISECONDS.convert(connectTimeout, timeUnit)); } } /** * The LittleProxy implementation only allows idle connection timeouts to be specified in seconds. idleConnectionTimeouts greater than * 0 but less than 1 second will be set to 1 second; otherwise, values will be truncated (i.e. 1500ms will become 1s). */ @Override public void setIdleConnectionTimeout(int idleConnectionTimeout, TimeUnit timeUnit) { long timeout = TimeUnit.SECONDS.convert(idleConnectionTimeout, timeUnit); if (timeout == 0 && idleConnectionTimeout > 0) { this.idleConnectionTimeoutSec = 1; } else { this.idleConnectionTimeoutSec = (int) timeout; } if (isStarted()) { proxyServer.setIdleConnectionTimeout(idleConnectionTimeoutSec); } } @Override public void setRequestTimeout(int requestTimeout, TimeUnit timeUnit) { //TODO: implement Request Timeouts using LittleProxy. currently this only sets an idle connection timeout, if the idle connection // timeout is higher than the specified requestTimeout. if (idleConnectionTimeoutSec == 0 || idleConnectionTimeoutSec > TimeUnit.SECONDS.convert(requestTimeout, timeUnit)) { setIdleConnectionTimeout(requestTimeout, timeUnit); } } @Override public void rewriteUrl(String pattern, String replace) { rewriteRules.add(new RewriteRule(pattern, replace)); } @Override public void rewriteUrls(Map<String, String> rewriteRules) { List<RewriteRule> newRules = new ArrayList<>(rewriteRules.size()); for (Map.Entry<String, String> rewriteRule : rewriteRules.entrySet()) { RewriteRule newRule = new RewriteRule(rewriteRule.getKey(), rewriteRule.getValue()); newRules.add(newRule); } this.rewriteRules = new CopyOnWriteArrayList<>(newRules); } @Override public void clearRewriteRules() { rewriteRules.clear(); } @Override public void blacklistRequests(String pattern, int responseCode) { blacklistEntries.add(new BlacklistEntry(pattern, responseCode)); } @Override public void blacklistRequests(String pattern, int responseCode, String method) { blacklistEntries.add(new BlacklistEntry(pattern, responseCode, method)); } @Override public void setBlacklist(Collection<BlacklistEntry> blacklist) { this.blacklistEntries = new CopyOnWriteArrayList<>(blacklist); } @Override public Collection<BlacklistEntry> getBlacklist() { return Collections.unmodifiableCollection(blacklistEntries); } @Override public boolean isWhitelistEnabled() { return whitelist.get().isEnabled(); } @Override public Collection<String> getWhitelistUrls() { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (Pattern pattern : whitelist.get().getPatterns()) { builder.add(pattern.pattern()); } return builder.build(); } @Override public int getWhitelistStatusCode() { return whitelist.get().getStatusCode(); } @Override public void clearBlacklist() { blacklistEntries.clear(); } @Override public void whitelistRequests(Collection<String> urlPatterns, int statusCode) { this.whitelist.set(new Whitelist(urlPatterns, statusCode)); } @Override public void addWhitelistPattern(String urlPattern) { // to make sure this method is threadsafe, we need to guarantee that the "snapshot" of the whitelist taken at the beginning // of the method has not been replaced by the time we have constructed a new whitelist at the end of the method boolean whitelistUpdated = false; while (!whitelistUpdated) { Whitelist currentWhitelist = this.whitelist.get(); if (!currentWhitelist.isEnabled()) { throw new IllegalStateException("Whitelist is disabled. Cannot add patterns to a disabled whitelist."); } // retrieve the response code and list of patterns from the current whitelist, the construct a new list of patterns that contains // all of the old whitelist's patterns + this new pattern int statusCode = currentWhitelist.getStatusCode(); List<String> newPatterns = new ArrayList<>(currentWhitelist.getPatterns().size() + 1); for (Pattern pattern : currentWhitelist.getPatterns()) { newPatterns.add(pattern.pattern()); } newPatterns.add(urlPattern); // create a new (immutable) Whitelist object with the new pattern list and status code Whitelist newWhitelist = new Whitelist(newPatterns, statusCode); // replace the current whitelist with the new whitelist only if the current whitelist has not changed since we started whitelistUpdated = this.whitelist.compareAndSet(currentWhitelist, newWhitelist); } } /** * Whitelist the specified request patterns, returning the specified responseCode for non-whitelisted * requests. * * @param patterns regular expression strings matching URL patterns to whitelist. if empty or null, * the whitelist will be enabled but will not match any URLs. * @param responseCode the HTTP response code to return for non-whitelisted requests */ public void whitelistRequests(String[] patterns, int responseCode) { if (patterns == null || patterns.length == 0) { this.enableEmptyWhitelist(responseCode); } else { this.whitelistRequests(Arrays.asList(patterns), responseCode); } } @Override public void enableEmptyWhitelist(int statusCode) { whitelist.set(new Whitelist(statusCode)); } @Override public void disableWhitelist() { whitelist.set(Whitelist.WHITELIST_DISABLED); } @Override public void addHeader(String name, String value) { additionalHeaders.put(name, value); } @Override public void removeHeader(String name) { additionalHeaders.remove(name); } @Override public void removeAllHeaders() { additionalHeaders.clear(); } @Override public Map<String, String> getAllHeaders() { return ImmutableMap.copyOf(additionalHeaders); } @Override public void setHostNameResolver(AdvancedHostResolver resolver) { delegatingResolver.setResolver(resolver); } @Override public AdvancedHostResolver getHostNameResolver() { return delegatingResolver.getResolver(); } @Override public boolean waitForQuiescence(long quietPeriod, long timeout, TimeUnit timeUnit) { return activityMonitor.waitForQuiescence(quietPeriod, timeout, timeUnit); } /** * Instructs this proxy to route traffic through an upstream proxy. Proxy chaining is not compatible with man-in-the-middle * SSL, so HAR capture will be disabled for HTTPS traffic when using an upstream proxy. * <p> * <b>Note:</b> Using {@link #setChainedProxyManager(ChainedProxyManager)} will supersede any value set by this method. * * @param chainedProxyAddress address of the upstream proxy */ @Override public void setChainedProxy(InetSocketAddress chainedProxyAddress) { upstreamProxyAddress = chainedProxyAddress; } @Override public InetSocketAddress getChainedProxy() { return upstreamProxyAddress; } /** * Allows access to the LittleProxy {@link ChainedProxyManager} for fine-grained control of the chained proxies. To enable a single * chained proxy, {@link BrowserMobProxy#setChainedProxy(InetSocketAddress)} is generally more convenient. * * @param chainedProxyManager chained proxy manager to enable */ public void setChainedProxyManager(ChainedProxyManager chainedProxyManager) { if (isStarted()) { throw new IllegalStateException("Cannot configure chained proxy manager after proxy has started."); } this.chainedProxyManager = chainedProxyManager; } /** * Configures the Netty thread pool used by the LittleProxy back-end. See {@link ThreadPoolConfiguration} for details. * * @param threadPoolConfiguration thread pool configuration to use */ public void setThreadPoolConfiguration(ThreadPoolConfiguration threadPoolConfiguration) { if (isStarted()) { throw new IllegalStateException("Cannot configure thread pool after proxy has started."); } this.threadPoolConfiguration = threadPoolConfiguration; } @Override public void addFirstHttpFilterFactory(HttpFiltersSource filterFactory) { filterFactories.add(0, filterFactory); } @Override public void addLastHttpFilterFactory(HttpFiltersSource filterFactory) { filterFactories.add(filterFactory); } /** * <b>Note:</b> The current implementation of this method forces a maximum response size of 2 MiB. To adjust the maximum response size, or * to disable aggregation (which disallows access to the {@link net.lightbody.bmp.util.HttpMessageContents}), you may add the filter source * directly: <code>addFirstHttpFilterFactory(new ResponseFilterAdapter.FilterSource(filter, bufferSizeInBytes));</code> */ @Override public void addResponseFilter(ResponseFilter filter) { addLastHttpFilterFactory(new ResponseFilterAdapter.FilterSource(filter)); } /** * <b>Note:</b> The current implementation of this method forces a maximum request size of 2 MiB. To adjust the maximum request size, or * to disable aggregation (which disallows access to the {@link net.lightbody.bmp.util.HttpMessageContents}), you may add the filter source * directly: <code>addFirstHttpFilterFactory(new RequestFilterAdapter.FilterSource(filter, bufferSizeInBytes));</code> */ @Override public void addRequestFilter(RequestFilter filter) { addFirstHttpFilterFactory(new RequestFilterAdapter.FilterSource(filter)); } @Override public Map<String, String> getRewriteRules() { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (RewriteRule rewriteRule : rewriteRules) { builder.put(rewriteRule.getPattern().pattern(), rewriteRule.getReplace()); } return builder.build(); } @Override public void removeRewriteRule(String urlPattern) { // normally removing elements from the list we are iterating over would not be possible, but since this is a CopyOnWriteArrayList // the iterator it returns is a "snapshot" of the list that will not be affected by removal (and that does not support removal, either) for (RewriteRule rewriteRule : rewriteRules) { if (rewriteRule.getPattern().pattern().equals(urlPattern)) { rewriteRules.remove(rewriteRule); } } } public boolean isStopped() { return stopped.get(); } public HarPage getCurrentHarPage() { return currentHarPage; } public void addHttpFilterFactory(HttpFiltersSource filterFactory) { filterFactories.add(filterFactory); } public List<HttpFiltersSource> getFilterFactories() { return filterFactories; } @Override public void setMitmDisabled(boolean mitmDisabled) throws IllegalStateException { if (isStarted()) { throw new IllegalStateException("Cannot disable MITM after the proxy has been started"); } this.mitmDisabled = mitmDisabled; } @Override public void setMitmManager(MitmManager mitmManager) { this.mitmManager = mitmManager; } @Override public void setTrustAllServers(boolean trustAllServers) { if (isStarted()) { throw new IllegalStateException("Cannot disable upstream server verification after the proxy has been started"); } if (trustAllServers) { trustSource = null; } else { if (trustSource == null) { trustSource = TrustSource.defaultTrustSource(); } } } @Override public void setTrustSource(TrustSource trustSource) { if (isStarted()) { throw new IllegalStateException("Cannot change TrustSource after proxy has been started"); } this.trustSource = trustSource; } public boolean isMitmDisabled() { return this.mitmDisabled; } public void setUseEcc(boolean useEcc) { this.useEcc = useEcc; } /** * Adds the basic browsermob-proxy filters, except for the relatively-expensive HAR capture filter. */ protected void addBrowserMobFilters() { addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new ResolvedHostnameCacheFilter(originalRequest, ctx); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new RegisterRequestFilter(originalRequest, ctx, activityMonitor); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new HttpsOriginalHostCaptureFilter(originalRequest, ctx); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new BlacklistFilter(originalRequest, ctx, getBlacklist()); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { Whitelist currentWhitelist = whitelist.get(); return new WhitelistFilter(originalRequest, ctx, isWhitelistEnabled(), currentWhitelist.getStatusCode(), currentWhitelist.getPatterns()); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new AutoBasicAuthFilter(originalRequest, ctx, basicAuthCredentials); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new RewriteUrlFilter(originalRequest, ctx, rewriteRules); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new HttpsHostCaptureFilter(originalRequest, ctx); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new AddHeadersFilter(originalRequest, additionalHeaders); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new LatencyFilter(originalRequest, latencyMs); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new UnregisterRequestFilter(originalRequest, ctx, activityMonitor); } }); } private int getMaximumRequestBufferSize() { int maxBufferSize = 0; for (HttpFiltersSource source : filterFactories) { int requestBufferSize = source.getMaximumRequestBufferSizeInBytes(); if (requestBufferSize > maxBufferSize) { maxBufferSize = requestBufferSize; } } return maxBufferSize; } private int getMaximumResponseBufferSize() { int maxBufferSize = 0; for (HttpFiltersSource source : filterFactories) { int requestBufferSize = source.getMaximumResponseBufferSizeInBytes(); if (requestBufferSize > maxBufferSize) { maxBufferSize = requestBufferSize; } } return maxBufferSize; } /** * Enables the HAR capture filter if it has not already been enabled. The filter will be added to the end of the filter chain. * The HAR capture filter is relatively expensive, so this method is only called when a HAR is requested. */ protected void addHarCaptureFilter() { if (harCaptureFilterEnabled.compareAndSet(false, true)) { // the HAR capture filter is (relatively) expensive, so only enable it when a HAR is being captured. furthermore, // restricting the HAR capture filter to requests where the HAR exists, as well as excluding HTTP CONNECTs // from the HAR capture filter, greatly simplifies the filter code. addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { Har har = getHar(); if (har != null && !ProxyUtils.isCONNECT(originalRequest)) { return new HarCaptureFilter(originalRequest, ctx, har, getCurrentHarPage() == null ? null : getCurrentHarPage().getId(), getHarCaptureTypes()); } else { return null; } } }); // HTTP CONNECTs are a special case, since they require special timing and error handling addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { Har har = getHar(); if (har != null && ProxyUtils.isCONNECT(originalRequest)) { return new HttpConnectHarCaptureFilter(originalRequest, ctx, har, getCurrentHarPage() == null ? null : getCurrentHarPage().getId()); } else { return null; } } }); } } }
misakuo/Dream-Catcher
app/src/main/java/net/lightbody/bmp/BrowserMobProxyServer.java
Java
mit
42,816
require "spec_helper" describe RefreshTraktTokenJob do subject{described_class.new} Given(:credential){create :credential} Given!(:stub) do stub_request(:post, "https://api-v2launch.trakt.tv/oauth/token") .with(body: {refresh_token: credential.data["refresh_token"], grant_type: "refresh_token"}.to_json).to_return(body: File.new("spec/fixtures/trakt/refresh_token.json").read) end When{subject.perform} Given(:reloaded_credential){credential.reload} Then{expect(stub).to have_been_requested} And{expect(reloaded_credential.data).to include("access_token" => "the_access_token", "refresh_token" => "the_refresh_token")} end
mskog/broad
spec/jobs/refresh_trakt_token_job_spec.rb
Ruby
mit
654
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.11.4-master-5034a04 */ goog.provide('ng.material.components.swipe'); goog.require('ng.material.core'); /** * @ngdoc module * @name material.components.swipe * @description Swipe module! */ /** * @ngdoc directive * @module material.components.swipe * @name mdSwipeLeft * * @restrict A * * @description * The md-swipe-left directives allows you to specify custom behavior when an element is swiped * left. * * @usage * <hljs lang="html"> * <div md-swipe-left="onSwipeLeft()">Swipe me left!</div> * </hljs> */ /** * @ngdoc directive * @module material.components.swipe * @name mdSwipeRight * * @restrict A * * @description * The md-swipe-right directives allows you to specify custom behavior when an element is swiped * right. * * @usage * <hljs lang="html"> * <div md-swipe-right="onSwipeRight()">Swipe me right!</div> * </hljs> */ angular.module('material.components.swipe', ['material.core']) .directive('mdSwipeLeft', getDirective('SwipeLeft')) .directive('mdSwipeRight', getDirective('SwipeRight')); function getDirective(name) { var directiveName = 'md' + name; var eventName = '$md.' + name.toLowerCase(); DirectiveFactory.$inject = ["$parse"]; return DirectiveFactory; /* ngInject */ function DirectiveFactory($parse) { return { restrict: 'A', link: postLink }; function postLink(scope, element, attr) { var fn = $parse(attr[directiveName]); element.on(eventName, function(ev) { scope.$apply(function() { fn(scope, { $event: ev }); }); }); } } } ng.material.components.swipe = angular.module("material.components.swipe");
t0930198/shoait
app/bower_components/angular-material/modules/closure/swipe/swipe.js
JavaScript
mit
1,739
# encoding: utf-8 module BitBucket class Repos::Following < API # List repo followers # # = Examples # bitbucket = BitBucket.new :user => 'user-name', :repo => 'repo-name' # bitbucket.repos.following.followers # bitbucket.repos.following.followers { |watcher| ... } # def followers(user_name, repo_name, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? normalize! params response = get_request("/repositories/#{user}/#{repo.downcase}/followers/", params) return response unless block_given? response.each { |el| yield el } end # List repos being followed by the authenticated user # # = Examples # bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' # bitbucket.repos.following.followed # def followed(*args) params = args.extract_options! normalize! params response = get_request("/user/follows", params) return response unless block_given? response.each { |el| yield el } end end # Repos::Watching end # BitBucket
fairfaxmedia/bitbucket
lib/bitbucket_rest_api/repos/following.rb
Ruby
mit
1,155
'use strict'; const crypto = require('crypto'); /* lib/handshake.js * WebSocket handshake. * * */ module.exports = exports = function(data){ let headers = exports._headers(data); let sha1 = crypto.createHash('sha1'); sha1.update(headers['sec-websocket-key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'); let resp = exports._headers({ Upgrade: 'websocket', Connection: 'Upgrade', 'Sec-WebSocket-Accept': sha1.digest('base64'), }); this.send(resp); this.emit('handshake-done'); }; exports._headers = function(raw){ // Parsing if (typeof raw === 'string' || raw instanceof Buffer) { if (raw instanceof Buffer) raw = raw.toString('utf-8'); let chunks = raw.split(/\r?\n/), headers = { 0:chunks[0] }, chunk = null, toObj = /^(.+?):\s?/; for (let i = 1; i < chunks.length - 1; i++) { chunk = chunks[i].split(toObj); if (chunk[1] && chunk[2]) headers[chunk[1].toLowerCase()] = chunk[2]; } return headers; } // Building else if (typeof raw === 'object' || !(raw instanceof Buffer)) { let val = null, result = ''; if (typeof raw[0] !== 'undefined') { result += raw[0] + '\r\n'; } else { result += 'HTTP/1.1 101 Switching Protocols\r\n'; } for (let key in raw) { if (typeof key !== 'string') continue; val = raw[key]; result += key + ': ' + val + '\r\n'; } return result + '\r\n'; } };
jamen/rela
lib/handshake.js
JavaScript
mit
1,440
require 'spec_helper' describe 'osx::time_machine::ask_to_use_new_disks_for_backup' do let(:facts) { {:boxen_user => 'ilikebees' } } describe('enabled') do let(:params) { {:ensure => 'present'} } it 'should set the value to true' do should contain_boxen__osx_defaults('Toggle Whether Time Machine Asks to Use New Disks for Backup').with({ :user => facts[:boxen_user], :key => 'DoNotOfferNewDisksForBackup', :domain => 'com.apple.TimeMachine', :value => true, }) end end describe('disabled') do let(:params) { {:ensure => 'absent'} } it 'should set the value to false' do should contain_boxen__osx_defaults('Toggle Whether Time Machine Asks to Use New Disks for Backup').with({ :user => facts[:boxen_user], :key => 'DoNotOfferNewDisksForBackup', :domain => 'com.apple.TimeMachine', :value => false, }) end end end
joebadmo/puppet-osx
spec/classes/time_machine/ask_to_use_new_disks_for_backup_spec.rb
Ruby
mit
950
<?php namespace Helpvel\Helpvel; use Illuminate\Support\ServiceProvider; class HelpvelServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('helpvel/helpvel'); } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
Helpvel/helpvel
src/Helpvel/Helpvel/HelpvelServiceProvider.php
PHP
mit
617
############### ### imports ### ############### from fabric.api import cd, env, lcd, put, prompt, local, sudo from fabric.contrib.files import exists ############## ### config ### ############## local_app_dir = './flask_project' local_config_dir = './config' remote_app_dir = '/home/www' remote_git_dir = '/home/git' remote_flask_dir = remote_app_dir + '/flask_project' remote_nginx_dir = '/etc/nginx/sites-enabled' remote_supervisor_dir = '/etc/supervisor/conf.d' env.hosts = ['add_ip_or_domain'] # replace with IP address or hostname env.user = 'newuser' # env.password = 'blah!' ############# ### tasks ### ############# def install_requirements(): """ Install required packages. """ sudo('apt-get update') sudo('apt-get install -y python') sudo('apt-get install -y python-pip') sudo('apt-get install -y python-virtualenv') sudo('apt-get install -y nginx') sudo('apt-get install -y gunicorn') sudo('apt-get install -y supervisor') sudo('apt-get install -y git') def install_flask(): """ 1. Create project directories 2. Create and activate a virtualenv 3. Copy Flask files to remote host """ if exists(remote_app_dir) is False: sudo('mkdir ' + remote_app_dir) if exists(remote_flask_dir) is False: sudo('mkdir ' + remote_flask_dir) with lcd(local_app_dir): with cd(remote_app_dir): sudo('virtualenv env') sudo('source env/bin/activate') sudo('pip install Flask==0.10.1') with cd(remote_flask_dir): put('*', './', use_sudo=True) def configure_nginx(): """ 1. Remove default nginx config file 2. Create new config file 3. Setup new symbolic link 4. Copy local config to remote config 5. Restart nginx """ sudo('/etc/init.d/nginx start') if exists('/etc/nginx/sites-enabled/default'): sudo('rm /etc/nginx/sites-enabled/default') if exists('/etc/nginx/sites-enabled/flask_project') is False: sudo('touch /etc/nginx/sites-available/flask_project') sudo('ln -s /etc/nginx/sites-available/flask_project' + ' /etc/nginx/sites-enabled/flask_project') with lcd(local_config_dir): with cd(remote_nginx_dir): put('./flask_project', './', use_sudo=True) sudo('/etc/init.d/nginx restart') def configure_supervisor(): """ 1. Create new supervisor config file 2. Copy local config to remote config 3. Register new command """ if exists('/etc/supervisor/conf.d/flask_project.conf') is False: with lcd(local_config_dir): with cd(remote_supervisor_dir): put('./flask_project.conf', './', use_sudo=True) sudo('supervisorctl reread') sudo('supervisorctl update') def configure_git(): """ 1. Setup bare Git repo 2. Create post-receive hook """ if exists(remote_git_dir) is False: sudo('mkdir ' + remote_git_dir) with cd(remote_git_dir): sudo('mkdir flask_project.git') with cd('flask_project.git'): sudo('git init --bare') with lcd(local_config_dir): with cd('hooks'): put('./post-receive', './', use_sudo=True) sudo('chmod +x post-receive') def run_app(): """ Run the app! """ with cd(remote_flask_dir): sudo('supervisorctl start flask_project') def deploy(): """ 1. Copy new Flask files 2. Restart gunicorn via supervisor """ with lcd(local_app_dir): local('git add -A') commit_message = prompt("Commit message?") local('git commit -am "{0}"'.format(commit_message)) local('git push production master') sudo('supervisorctl restart flask_project') def rollback(): """ 1. Quick rollback in case of error 2. Restart gunicorn via supervisor """ with lcd(local_app_dir): local('git revert master --no-edit') local('git push production master') sudo('supervisorctl restart flask_project') def status(): """ Is our app live? """ sudo('supervisorctl status') def create(): install_requirements() install_flask() configure_nginx() configure_supervisor() configure_git()
kaiocesar/automation-fab
fabfile.py
Python
mit
4,325
# encoding: UTF-8 # Author:: Akira FUNAI # Copyright:: Copyright (c) 2009 Akira FUNAI require "#{::File.dirname __FILE__}/t" class TC_Text < Test::Unit::TestCase def setup meta = nil Bike::Parser.gsub_scalar('$(foo text 3 1..5)') {|id, m| meta = m '' } @f = Bike::Field.instance meta end def teardown end def test_meta assert_equal( 3, @f[:size], 'Text#initialize should set :size from the token' ) assert_equal( 1, @f[:min], 'Text#initialize should set :min from the range token' ) assert_equal( 5, @f[:max], 'Text#initialize should set :max from the range token' ) end def test_val_cast assert_equal( '', @f.val, 'Text#val_cast should cast the given val to String' ) @f.load 123 assert_equal( '123', @f.val, 'Text#val_cast should cast the given val to String' ) end def test_get @f.load 'bar' assert_equal( 'bar', @f.get, 'Text#get should return proper string' ) assert_equal( '<span class="text"><input type="text" name="" value="bar" size="3" /></span>', @f.get(:action => :update), 'Text#get should return proper string' ) @f.load '<bar>' assert_equal( '&lt;bar&gt;', @f.get, 'Text#get should escape the special characters' ) assert_equal( '<span class="text"><input type="text" name="" value="&lt;bar&gt;" size="3" /></span>', @f.get(:action => :update), 'Text#get should escape the special characters' ) end def test_errors @f.load '' @f[:min] = 0 assert_equal( [], @f.errors, 'Text#errors should return the errors of the current val' ) @f[:min] = 1 assert_equal( ['mandatory'], @f.errors, 'Text#errors should return the errors of the current val' ) @f.load 'a' @f[:min] = 1 assert_equal( [], @f.errors, 'Text#errors should return the errors of the current val' ) @f[:min] = 2 assert_equal( ['too short: 2 characters minimum'], @f.errors, 'Text#errors should return the errors of the current val' ) @f.load 'abcde' @f[:max] = 5 assert_equal( [], @f.errors, 'Text#errors should return the errors of the current val' ) @f[:max] = 4 assert_equal( ['too long: 4 characters maximum'], @f.errors, 'Text#errors should return the errors of the current val' ) end end
afunai/bike
t/test_text.rb
Ruby
mit
2,573
import React from 'react'; import ReactDOM from 'react-dom'; import Deferred from 'deferred-js'; import ElementsModel from './visualizution/elementsModel'; import ElementsList from './visualizution/elementsList'; import ControlsView from './controls/controlsView'; import Immutable from 'immutable'; import styles from '../stylesheets/index.styl'; let state = Immutable.Map({}); const actions = {}; const elementsModel = new ElementsModel(); const elementsList = new ElementsList(); const initApp = () => { elementsList.setElement('periodic-table-data-visualization'); elementsList.setModel(elementsModel); elementsModel.fetch().done(() => { initElements(); elementsList.render(); }); }; const initElements = () => { const colors = { 'nonmetal': '#CD51CB', 'noble gas': '#73D74D', 'alkali metal': '#D55438', 'alkaline earth metal': '#559BBA', 'metalloid': '#57D29E', 'halogen': '#CC567E', 'metal': '#5D8A3A', 'transition metal': '#917ACA', 'lanthanoid': '#BE8630', 'actinoid': '#CDD143' }; setState({ parameters: [ 'atomicNumber', 'groupBlock', 'name', 'symbol' ], selectedSortingKey: 'groupBlock', colors }); elementsList.setColors(colors); }; // Actions actions.onSortingChanged = (selectedSortingKey) => { elementsList.setSortingKey(selectedSortingKey); elementsList.render(); setState({selectedSortingKey}) }; function setState(changes) { state = state.mergeDeep(changes); let Component = React.createElement(ControlsView, { state: state, actions }); ReactDOM.render(Component, document.getElementById('periodic-table-controls')); } window.document.addEventListener('DOMContentLoaded', initApp);
vogelino/periodic-table-data-visualization
src/js/index.js
JavaScript
mit
1,705
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocketDog.Common { public struct ConnectionProtocol { public ConnectionProtocol(Type value) : this() { Value = value; } public enum Type { Tcp = 6, Udp = 17 } public Type Value { get; private set; } public override string ToString() { return Value.ToString(); } public static List<ConnectionProtocol> GetList() { return new List<ConnectionProtocol>(2) { new ConnectionProtocol(Type.Tcp), new ConnectionProtocol(Type.Udp) }; } } }
deniskucherov/SocketDog
SocketDog.Common/ConnectionProtocol.cs
C#
mit
809
package com.myconnector.domain; import com.myconnector.domain.base.BaseDictionary; public class Dictionary extends BaseDictionary { private static final long serialVersionUID = 1L; /*[CONSTRUCTOR MARKER BEGIN]*/ public Dictionary () { super(); } /** * Constructor for primary key */ public Dictionary (java.lang.String word) { super(word); } /*[CONSTRUCTOR MARKER END]*/ }
nileshk/myconnector
src/main/java/com/myconnector/domain/Dictionary.java
Java
mit
395
/* * The MIT License * * Copyright 2017 Arvind Sasikumar. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package sync.db.mysql; import java.sql.*; /** * An object of this class serves as the agent for the synchronization process. * All synchronization tasks are handed over to an object of this class, which * then takes the required steps to perform the actual synchronization depending * on its set properties. It requires all details for establishing a connection * to the server and client MySQL servers and some additional synchronization * specific properties.<p> * An object of this class is created using the Builder pattern as opposed to * the usual constructor based initialization.<p> * An example on using the Builder pattern to create a new DBSyncObject:<p> * <pre> * {@code * DBSyncAgent dbSyncAgent = new DBSyncAgent.Builder() .setServerDatabaseAddress("localhost") .setServerDatabaseName("test1") .setServerDatabaseUsername("root") .setServerDatabasePassword("root") .setServerDatabasePort(3306) .setServerDatabaseConnectionOptions("?useSSL=false") .setClientDatabaseAddress("localhost") .setClientDatabaseName("test2") .setClientDatabaseUsername("root") .setClientDatabasePassword("root") .setClientDatabasePort(3306) .setClientDatabaseConnectionOptions("?useSSL=false") .setDBMap(dbMap) .setSyncInterval(12) .build(); * } * </pre> * @see #DBSyncAgent(sync.db.mysql.DBSyncAgent.Builder) * @author Arvind Sasikumar */ public class DBSyncAgent { private final String serverDatabaseAddress; private final String serverDatabaseName; private final String serverDatabaseUsername; private final String serverDatabasePassword; private final String serverDatabaseConnectionOptions; private final int serverDatabasePort; private final String clientDatabaseAddress; private final String clientDatabaseName; private final String clientDatabaseUsername; private final String clientDatabasePassword; private final String clientDatabaseConnectionOptions; private final int clientDatabasePort; private final DBMap dbMap; private int syncInterval; private Connection serverConnection; private Connection clientConnection; private Statement serverStatement; private Statement clientStatement; private DBSynchronizer dbSynchronizer; private Thread dbSynchronizerThread; /** * Build the DBSyncAgent class using the Builder pattern. * @author Arvind Sasikumar * @see <a href="http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern">Builder Pattern</a> */ public static class Builder{ private String serverDatabaseAddress; private String serverDatabaseName; private String serverDatabaseUsername; private String serverDatabasePassword; private String serverDatabaseConnectionOptions; private int serverDatabasePort; private String clientDatabaseAddress; private String clientDatabaseName; private String clientDatabaseUsername; private String clientDatabasePassword; private String clientDatabaseConnectionOptions; private int clientDatabasePort; private DBMap dbMap; private int syncInterval; /** * Set the address of the server database. * @param serverDatabaseAddress address of the server database, * e.g. "localhost" or "59.23.54.22" * @return Builder object as per the Builder pattern */ public Builder setServerDatabaseAddress(String serverDatabaseAddress){ this.serverDatabaseAddress = serverDatabaseAddress; return this; } /** * Set the name of the server database. * @param serverDatabaseName name of the server database, e.g. "testdb" * @return Builder object as per the Builder pattern */ public Builder setServerDatabaseName(String serverDatabaseName){ this.serverDatabaseName = serverDatabaseName; return this; } /** * Set the username to access the server database. * @param serverDatabaseUsername username to access the server database * @return Builder object as per the Builder pattern */ public Builder setServerDatabaseUsername(String serverDatabaseUsername){ this.serverDatabaseUsername = serverDatabaseUsername; return this; } /** * Set the password to access the server database. * @param serverDatabasePassword password to access the server database * @return Builder object as per the Builder pattern */ public Builder setServerDatabasePassword(String serverDatabasePassword){ this.serverDatabasePassword = serverDatabasePassword; return this; } /** * Set the optional connection string to be used for the server * connection. * All options in the MySQL connection string as per the Connector/J * appear here. e.g. "?useSSL=false" * @param serverDatabaseConnectionOptions optional connection string * @return Builder object as per the Builder pattern */ public Builder setServerDatabaseConnectionOptions(String serverDatabaseConnectionOptions){ this.serverDatabaseConnectionOptions = serverDatabaseConnectionOptions; return this; } /** * Set the port for the server connection. * @param serverDatabasePort port for the server connection, e.g. 3306 * @return Builder object as per the Builder pattern */ public Builder setServerDatabasePort(int serverDatabasePort){ this.serverDatabasePort = serverDatabasePort; return this; } /** * Set the address of the client database. * @param clientDatabaseAddress address of the client database, * e.g. "localhost" or "59.23.54.22" * @return Builder object as per the Builder pattern */ public Builder setClientDatabaseAddress(String clientDatabaseAddress){ this.clientDatabaseAddress = clientDatabaseAddress; return this; } /** * Set the name of the client database. * @param clientDatabaseName name of the client database, e.g. "testdb" * @return Builder object as per the Builder pattern */ public Builder setClientDatabaseName(String clientDatabaseName){ this.clientDatabaseName = clientDatabaseName; return this; } /** * Set the username to access the client database. * @param clientDatabaseUsername username to access the client database * @return Builder object as per the Builder pattern */ public Builder setClientDatabaseUsername(String clientDatabaseUsername){ this.clientDatabaseUsername = clientDatabaseUsername; return this; } /** * Set the password to access the client database. * @param clientDatabasePassword password to access the client database * @return Builder object as per the Builder pattern */ public Builder setClientDatabasePassword(String clientDatabasePassword){ this.clientDatabasePassword = clientDatabasePassword; return this; } /** * Set the optional connection string to be used for the client * connection. * All options in the MySQL connection string as per the Connector/J * appear here. e.g. "?useSSL=false" * @param clientDatabaseConnectionOptions optional connection string * @return Builder object as per the Builder pattern */ public Builder setClientDatabaseConnectionOptions(String clientDatabaseConnectionOptions){ this.clientDatabaseConnectionOptions = clientDatabaseConnectionOptions; return this; } /** * Set the port for the client connection. * @param clientDatabasePort port for the client connection, e.g. 3306 * @return Builder object as per the Builder pattern */ public Builder setClientDatabasePort(int clientDatabasePort){ this.clientDatabasePort = clientDatabasePort; return this; } /** * Set the database map. * @param dbMap database map * @return Builder object as per the Builder pattern */ public Builder setDBMap(DBMap dbMap){ this.dbMap = dbMap; return this; } /** * Set the synchronization interval. * This specifies the time interval between two successive * synchronization attempts during a live sync. Specified in seconds. * @param syncInterval synchronization interval in seconds * @return Builder object as per the Builder pattern */ public Builder setSyncInterval(int syncInterval){ this.syncInterval = syncInterval; return this; } /** * Build the DBSyncAgent object using the Builder pattern after all * properties have been set using the Builder class. * @return a new DBSyncAgent object with all properties set * @see <a href="http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern">Builder Pattern</a> */ public DBSyncAgent build(){ return new DBSyncAgent(this); } } /** * Create a new DBSyncAgent object using the Builder Pattern. * This constructor is declared as private and is hence not accessible from * outside. To use this constructor, one must use the Builder pattern. * @param builder the builder object used to build the new DBSyncAgent * object using the Builder pattern * @see <a href="http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern">Builder Pattern</a> */ private DBSyncAgent(Builder builder){ serverDatabaseAddress = builder.serverDatabaseAddress; serverDatabaseName = builder.serverDatabaseName; serverDatabaseUsername = builder.serverDatabaseUsername; serverDatabasePassword = builder.serverDatabasePassword; serverDatabaseConnectionOptions = builder.serverDatabaseConnectionOptions; serverDatabasePort = builder.serverDatabasePort; clientDatabaseAddress = builder.clientDatabaseAddress; clientDatabaseName = builder.clientDatabaseName; clientDatabaseUsername = builder.clientDatabaseUsername; clientDatabasePassword = builder.clientDatabasePassword; clientDatabaseConnectionOptions = builder.clientDatabaseConnectionOptions; clientDatabasePort = builder.clientDatabasePort; dbMap = builder.dbMap; syncInterval = builder.syncInterval; } /** * Set the synchronization interval. * This specifies the time interval between two successive * synchronization attempts during a live sync. Specified in seconds. * @param syncInterval synchronization interval in seconds */ public void setSyncInterval(int syncInterval){ this.syncInterval = syncInterval; } /** * Connects to the client and server databases as per the set properties. */ public void connect(){ try{ System.out.println("\nAttempting connection..."); Class.forName("com.mysql.jdbc.Driver"); String connectionString = "jdbc:mysql://" + serverDatabaseAddress + ":" + serverDatabasePort + "/" + serverDatabaseName + serverDatabaseConnectionOptions; serverConnection = DriverManager.getConnection(connectionString, serverDatabaseUsername,serverDatabasePassword); serverStatement = serverConnection.createStatement(); connectionString = "jdbc:mysql://" + clientDatabaseAddress + ":" + clientDatabasePort + "/" + clientDatabaseName + clientDatabaseConnectionOptions; clientConnection = DriverManager.getConnection(connectionString, clientDatabaseUsername,clientDatabasePassword); clientStatement = clientConnection.createStatement(); System.out.println("Connection successful!"); } catch(Exception e){ e.printStackTrace(); } } /** * Performs initial synchronization between the client and the server * databases. * When synchronization is done for the first time or after a reasonable * interval of time, call this function before calling the {@link #liveSync()}. */ public void sync(){ dbSynchronizer = new DBSynchronizer(serverStatement, clientStatement, dbMap); dbSynchronizerThread = new Thread(dbSynchronizer); dbSynchronizerThread.start(); } /** * Synchronizes the client and the server databases periodically. * This synchronization is done periodically as specified using * {@link #setSyncInterval(int)} or initialized using the Builder pattern. */ public void liveSync(){ dbSynchronizer = new DBSynchronizer(serverStatement, clientStatement, dbMap, syncInterval); dbSynchronizerThread = new Thread(dbSynchronizer); dbSynchronizerThread.start(); } /** * Stops the synchronization process. * The current transaction will be finished before the stop takes places * to make sure the database is in proper state. */ public void stopSync(){ dbSynchronizer.stopSync(); } /** * Disconnects the existing client and server connections safely. * Call this method after calling {@link #stopSync()}. */ public void disconnect(){ try{ System.out.println("\nDisconnecting..."); clientStatement.close(); serverStatement.close(); clientConnection.close(); serverConnection.close(); System.out.println("Disconnected."); } catch(Exception e){ e.printStackTrace(); } } /** * Waits for the worker thread to finish its job before proceeding forward. * Call this method between {@link #sync()} and {@link #liveSync()}. */ public void hold(){ try{ dbSynchronizerThread.join(); } catch(Exception e){ e.printStackTrace(); } } }
arvindsasikumar/mysql-db-sync
sync/db/mysql/DBSyncAgent.java
Java
mit
17,612
<?php namespace Forecast\WeatherBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class ForecastWeatherExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); $loader->load(sprintf('%s.yml', $config['db_driver'])); } }
alexastro/forecast
src/Forecast/WeatherBundle/DependencyInjection/ForecastWeatherExtension.php
PHP
mit
962
from django.contrib import admin from api_boilerplate.models import ApiKey admin.site.register(ApiKey)
kippt/django-api-boilerplate
api_boilerplate/admin.py
Python
mit
105
package com.sparcs.casino; import com.sparcs.casino.game.Bet; public interface Account { /** * @return The {@link Customer} who owns this Account. */ Customer getCustomer(); /** * @return The number of chips the Customer currently holds */ int getChipCount(); /** * A {@link Bet} has been won! - add chips * * @param pot Number of chips won */ void addChips(int pot); /** * A {@link Bet} has been accepted - remove chips * * @param stake Number of chips wagered. */ void deductChips(int stake); }
sparcs360/Casino
game-srvkit/src/main/java/com/sparcs/casino/Account.java
Java
mit
538
/* Generated By:JJTree: Do not edit this line. ASTInclusiveORExpression.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package org.iguanatool.testobject.cparser; public class ASTInclusiveORExpression extends SimpleNode { public ASTInclusiveORExpression(int id) { super(id); } public ASTInclusiveORExpression(CParser p, int id) { super(p, id); } /** * Accept the visitor. **/ public void jjtAccept(CParserVisitor visitor) { visitor.visit(this); } } /* JavaCC - OriginalChecksum=9dfaa0b606df3826250d5b96a252215d (do not edit this line) */
iguanatool/iguana
src/main/java/org/iguanatool/testobject/cparser/ASTInclusiveORExpression.java
Java
mit
742
package fi.csc.chipster.rest.websocket; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import jakarta.websocket.CloseReason; import jakarta.websocket.CloseReason.CloseCodes; import jakarta.websocket.Endpoint; import jakarta.websocket.EndpointConfig; import jakarta.websocket.MessageHandler; import jakarta.websocket.PongMessage; import jakarta.websocket.Session; public class WebSocketClientEndpoint extends Endpoint { public static interface EndpointListener { public void onOpen(Session session, EndpointConfig config); public void onClose(Session session, CloseReason reason); public void onError(Session session, Throwable thr); } private static final Logger logger = LogManager.getLogger(); private MessageHandler messageHandler; private CountDownLatch disconnectLatch; private CountDownLatch connectLatch = new CountDownLatch(1); private CloseReason closeReason; private Throwable throwable; private Session session; private EndpointListener endpointListener; public WebSocketClientEndpoint(MessageHandler.Whole<String> messageHandler, EndpointListener endpointListener) { this.messageHandler = messageHandler; this.endpointListener = endpointListener; } @Override public void onOpen(Session session, EndpointConfig config) { logger.debug("WebSocket client onOpen"); this.session = session; if (messageHandler != null) { session.addMessageHandler(messageHandler); } disconnectLatch = new CountDownLatch(1); /* Wait for connection or error * * If the server would use HTTP errors for signaling e.g. authentication errors, at this point * we would already know that the connection was successful. Unfortunately JSR 356 Java API * for WebSocket doesn't support servlet filters or other methods * for responding with HTTP errors to the original WebSocket upgrade request. * * The server will check the authentication in the onOpen() method and close the connection if * the authentication fails. We'll know that the authentication failed when the onClose() method * is called here in the client. The problem is to know when the authentication was * accepted. This is solved by sending a ping. If we get the ping reply, we know that authentication * was accepted. * * We have to wait for the ping reply in another thread, blocking this onOpen() method seems to stop also * the ping or it's reply (understandably). * * Side note: this logic is not critical for the information security, that has to be taken care in the server * side. However, this is critical for reliable tests and for the server's to notice when their connection * to other services fail. */ new Thread(new Runnable() { @Override public void run() { try { ping(); connectLatch.countDown(); } catch (IllegalArgumentException | IOException | TimeoutException | InterruptedException e) { logger.warn("WebSocket client error", e); } } }, "websocket-connection-ping").start(); this.endpointListener.onOpen(session, config); } @Override public void onClose(Session session, CloseReason reason) { logger.debug("WebSocket client onClose: " + reason); closeReason = reason; connectLatch.countDown(); disconnectLatch.countDown(); this.endpointListener.onClose(session, reason); } @Override public void onError(Session session, Throwable thr) { logger.debug("WebSocket client onError: " + thr.getMessage()); throwable = thr; connectLatch.countDown(); disconnectLatch.countDown(); this.endpointListener.onError(session, thr); } public void close() throws IOException { session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "client closing")); } public boolean waitForDisconnect(long timeout) throws InterruptedException { logger.debug("WebSocket client will wait for disconnect max " + timeout + " seconds"); return disconnectLatch.await(timeout, TimeUnit.SECONDS); } public void waitForConnection() throws InterruptedException, WebSocketClosedException, WebSocketErrorException { logger.debug("WebSocket client waiting for connection " + closeReason); connectLatch.await(); if (closeReason != null) { throw new WebSocketClosedException(closeReason); } else if (throwable != null) { // most likely error in the HTTP upgrade request, probably happens // only if the configuration or network is broken throw new WebSocketErrorException(throwable); } } public void sendText(String text) throws IOException { session.getBasicRemote().sendText(text); } public void ping() throws IllegalArgumentException, IOException, TimeoutException, InterruptedException { logger.debug("WebSocket client sends ping"); PongHandler pongHandler = new PongHandler(); session.addMessageHandler(pongHandler); session.getBasicRemote().sendPing(null); pongHandler.await(); session.removeMessageHandler(pongHandler); } public static class PongHandler implements MessageHandler.Whole<PongMessage> { private CountDownLatch latch = new CountDownLatch(1); @Override public void onMessage(PongMessage message) { logger.debug("WebSocket client received pong"); latch.countDown(); } public void await() throws TimeoutException, InterruptedException { int timeout = 2; logger.debug("WebSocket client will wait for pong max " + timeout + " seconds"); boolean received = latch.await(timeout, TimeUnit.SECONDS); if (!received) { throw new TimeoutException("timeout while waiting for pong message"); } } } }
chipster/chipster-web-server
src/main/java/fi/csc/chipster/rest/websocket/WebSocketClientEndpoint.java
Java
mit
5,780
require 'open3' When(/^I execute it via the execute function of the PuppetShow module$/) do @results = PuppetShow.execute(@file) end When(/^I execute the PuppetShow binary with the option:$/) do |opt| cmd = "./bin/puppetshow #{opt}" @stdout_str, @status = Open3.capture2(cmd) end When(/^I execute it via the PuppetShow binary$/) do cmd = "./bin/puppetshow #{@file}" @stdout_str, @status = Open3.capture2(cmd) end
ludokng/puppetshow
features/step_definitions/execute_steps.rb
Ruby
mit
428
/* @author rich * Created on 07-Jul-2003 * * This code is covered by a Creative Commons * Attribution, Non Commercial, Share Alike license * <a href="http://creativecommons.org/licenses/by-nc-sa/1.0">License</a> */ package org.lsmp.djep.vectorJep.values; import org.lsmp.djep.vectorJep.*; //import JSci.maths.DoubleMatrix; //import JSci.physics.relativity.Rank1Tensor; /** * Represents a matrix. * * @author Rich Morris * Created on 07-Jul-2003 * @version 2.3.0.2 now extends number * @version 2.3.1.1 Bug with non square matricies fixed. * @since 2.3.2 Added equals method. */ public class Matrix extends Number implements MatrixValueI { // want package access to simplify addition of matricies int rows=0; int cols=0; Object data[][] = null; Dimensions dims; private Matrix() {} /** Construct a matrix with given rows and cols. */ public Matrix(int rows,int cols) { this.rows = rows; this.cols = cols; data = new Object[rows][cols]; dims = Dimensions.valueOf(rows,cols); } /** * Construct a Matrix from a set of row vectors. * @param vecs */ /* public Matrix(MVector[] vecs) throws ParseException { if(vecs==null) { throw new ParseException("Tried to create a matrix with null row vectors"); } rows = vecs.length; if(rows==0) { throw new ParseException("Tried to create a matrix with zero row vectors"); } // now check that each vector has the same size. cols = vecs[0].size(); for(int i = 1;i<rows;++i) if(cols != vecs[i].size()) throw new ParseException("Each vector must be of the same size"); data = new Object[rows][cols]; for(int i = 0;i<rows;++i) for(int j=0;j<cols;++j) { data[i][j]= vecs[i].elementAt(j); if(data[i][j] == null) throw new ParseException("Null element in vector"); } } */ /** * Returns a string rep of matrix. Uses [[a,b],[c,d]] syntax. */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append('['); for(int i = 0;i<rows;++i) { if(i>0) sb.append(','); sb.append('['); for(int j=0;j<cols;++j) { if(j>0)sb.append(','); sb.append(data[i][j]); } sb.append(']'); } sb.append(']'); return sb.toString(); } public Dimensions getDim() { return dims; } public int getNumEles() { return rows*cols; } public int getNumRows() { return rows; } public int getNumCols() { return cols; } public void setEle(int n,Object value) { int i = n / cols; int j = n % cols; data[i][j] = value; } public void setEle(int i,int j,Object value) { data[i][j] = value; } public Object getEle(int n) { int i = n / cols; int j = n % cols; return data[i][j]; } public Object getEle(int i,int j) { return data[i][j]; } public Object[][] getEles() { return data; } /** sets the elements to those of the arguments. */ public void setEles(MatrixValueI val) { if(!dims.equals(val.getDim())) return; for(int i=0;i<rows;++i) System.arraycopy(((Matrix) val).data[i],0,data[i],0,cols); } /** value of ele(1,1). */ public int intValue() {return ((Number) data[0][0]).intValue(); } /** value of ele(1,1). */ public long longValue() {return ((Number) data[0][0]).longValue(); } /** value of ele(1,1). */ public float floatValue() { return ((Number) data[0][0]).floatValue(); } /** value of ele(1,1). */ public double doubleValue() {return ((Number) data[0][0]).doubleValue(); } /** Are two matricies equal, element by element * Overrides Object. */ public boolean equals(Object obj) { if(!(obj instanceof Matrix)) return false; Matrix mat = (Matrix) obj; if(!mat.getDim().equals(getDim())) return false; for(int i=0;i<rows;++i) for(int j=0;j<cols;++j) if(!data[i][j].equals(mat.data[i][j])) return false; return true; } /** * Always override hashCode when you override equals. * Efective Java, Joshua Bloch, Sun Press */ public int hashCode() { int result = 17; // long xl = Double.doubleToLongBits(this.re); // long yl = Double.doubleToLongBits(this.im); // int xi = (int)(xl^(xl>>32)); // int yi = (int)(yl^(yl>>32)); for(int i=0;i<rows;++i) for(int j=0;j<cols;++j) result = 37*result+ data[i][j].hashCode(); return result; } }
Kailashrb/Jep
src/org/lsmp/djep/vectorJep/values/Matrix.java
Java
mit
4,371
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-24 22:03 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('samples', '0004_sample'), ] operations = [ migrations.CreateModel( name='CollectionType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('method_name', models.CharField(max_length=255, verbose_name='Método de coleta')), ('is_primary', models.BooleanField(default=True, verbose_name='Principal?')), ], ), migrations.AlterField( model_name='fluvaccine', name='was_applied', field=models.NullBooleanField(verbose_name='Recebeu vacina contra gripe?'), ), migrations.AddField( model_name='sample', name='collection_type', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='samples.CollectionType'), ), ]
gcrsaldanha/fiocruz
samples/migrations/0005_auto_20170424_1903.py
Python
mit
1,172
# -*- coding:utf-8 -*- import os def split_screen(): val = os.system("xrandr --output HDMI1 --right-of VGA1 --auto") def run_sensorcmd_web(): path = "/home/suyf/swork/git/sensorcmd-web/web/" os.chdir(path) val = os.system("./apprun.py") def run_cas(): path = "/home/suyf/swork/git/cas/web/" os.chdir(path) val = os.system("./casrun.py") def run_windpower(): path = "/home/suyf/swork/git/windpower/web" os.chdir(path) val = os.system("python apprun.py") if __name__ == '__main__': choose = input("Please choose your project(int):\n 1:cas\n 2:sensorcmd-web\n 3:windpower\n") if int(choose) == 1: cas_val = run_cas() print val if int(choose) == 2: cas_val = run_cas() val = run_sensorcmd_web() print val,cas_val if int(choose) == 3: val = run_windpower() print val
myyyy/wiki
shell/work_start.py
Python
mit
791
package net.trolldad.dashclock.redditheadlines.testactivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import net.trolldad.dashclock.redditheadlines.activity.PreviewActivity_; /** * Created by jacob-tabak on 1/28/14. */ public class LaunchNonImgurActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = PreviewActivity_.intent(this) .mCommentsUrl("http://www.reddit.com/r/AdviceAnimals/comments/1wdqd3/after_my_second_paper_jam_in_the_office_today_i/") .mLinkName("t3_1wdqd3") .mLinkUrl("http://www.livememe.com/qk7bcf5.jpg") .get(); startActivity(intent); finish(); } }
Trolldad/Reddit-Headlines
Reddit Headlines for DashClock/src/main/java/net/trolldad/dashclock/redditheadlines/testactivity/LaunchNonImgurActivity.java
Java
mit
815
<?php namespace HeroBundle\Form\Paragraph; use HeroBundle\Entity\Item; use HeroBundle\Repository\ItemRepository; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class AccessConditionsType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('character_level', IntegerType::class, [ 'label' => 'Niveau du personnage', 'required' => false, ]) ->add('required_items', EntityType::class, [ 'required' => false, 'class' => 'HeroBundle:Item', 'choice_value' => 'id', 'choice_label' => 'name', 'label' => 'Objet(s) requis', 'multiple' => true, // 'query_builder' => function(ItemRepository $er) { // return $er->createQueryBuilder('i') // ->where('i.id = 221'); // } ]) ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([]); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'herobundle_access_conditions'; } }
Cryborg/you_are_the_hero
src/HeroBundle/Form/Paragraph/AccessConditionsType.php
PHP
mit
1,613
'use strict'; // CUSTOM ERROR // /** * FUNCTION: createClass() * Creates a CustomError class constructor. Note that we use function generation so that tests may be run in browsers not supporting ES2015 classes. This function may be loaded in non-ES2015 environments, but should only be invoked when ES2015 classes are supported. * * @returns {Function} constructor */ function createClass() { /* jshint evil:true */ var str = ''; str += '(function create() {'; str += 'class CustomError extends Error {'; str += 'constructor( msg ) {'; str += 'super( msg );'; str += '}'; str += '}'; str += 'return CustomError;'; str += '})()'; return eval( str ); } // end FUNCTION createClass() // EXPORTS // module.exports = createClass;
kgryte/utils-copy-error
test/fixtures/customerror.subclass.js
JavaScript
mit
741
let AutomaticComponent = require('./AutomaticComponent'); class PurifyCss extends AutomaticComponent { /** * Required dependencies for the component. */ dependencies() { if (Config.purifyCss) { throw new Error( 'PurifyCSS support is no longer available. We recommend using PurgeCss + postCss instead.' ); } } } module.exports = PurifyCss;
JeffreyWay/laravel-mix
src/components/PurifyCss.js
JavaScript
mit
419
import "ember"; var Router, App, AppView, templates, router, container; var get = Ember.get, set = Ember.set, compile = Ember.Handlebars.compile, forEach = Ember.EnumerableUtils.forEach; function bootApplication() { router = container.lookup('router:main'); Ember.run(App, 'advanceReadiness'); } function handleURL(path) { return Ember.run(function() { return router.handleURL(path).then(function(value) { ok(true, 'url: `' + path + '` was handled'); return value; }, function(reason) { ok(false, 'failed to visit:`' + path + '` reason: `' + QUnit.jsDump.parse(reason)); throw reason; }); }); } function handleURLAborts(path) { Ember.run(function() { router.handleURL(path).then(function(value) { ok(false, 'url: `' + path + '` was NOT to be handled'); }, function(reason) { ok(reason && reason.message === "TransitionAborted", 'url: `' + path + '` was to be aborted'); }); }); } function handleURLRejectsWith(path, expectedReason) { Ember.run(function() { router.handleURL(path).then(function(value) { ok(false, 'expected handleURLing: `' + path + '` to fail'); }, function(reason) { equal(expectedReason, reason); }); }); } module("Basic Routing", { setup: function() { Ember.run(function() { App = Ember.Application.create({ name: "App", rootElement: '#qunit-fixture' }); App.deferReadiness(); App.Router.reopen({ location: 'none' }); Router = App.Router; App.LoadingRoute = Ember.Route.extend({ }); container = App.__container__; Ember.TEMPLATES.application = compile("{{outlet}}"); Ember.TEMPLATES.home = compile("<h3>Hours</h3>"); Ember.TEMPLATES.homepage = compile("<h3>Megatroll</h3><p>{{home}}</p>"); Ember.TEMPLATES.camelot = compile('<section><h3>Is a silly place</h3></section>'); }); }, teardown: function() { Ember.run(function() { App.destroy(); App = null; Ember.TEMPLATES = {}; }); } }); test("warn on URLs not included in the route set", function () { Router.map(function() { this.route("home", { path: "/" }); }); bootApplication(); expectAssertion(function(){ Ember.run(function(){ router.handleURL("/what-is-this-i-dont-even"); }); }, "The URL '/what-is-this-i-dont-even' did not match any routes in your application"); }); test("The Homepage", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ }); var currentPath; App.ApplicationController = Ember.Controller.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); bootApplication(); equal(currentPath, 'home'); equal(Ember.$('h3:contains(Hours)', '#qunit-fixture').length, 1, "The home template was rendered"); }); test("The Home page and the Camelot page with multiple Router.map calls", function() { Router.map(function() { this.route("home", { path: "/" }); }); Router.map(function() { this.route("camelot", {path: "/camelot"}); }); App.HomeRoute = Ember.Route.extend({ }); App.CamelotRoute = Ember.Route.extend({ }); var currentPath; App.ApplicationController = Ember.Controller.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); App.CamelotController = Ember.Controller.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); bootApplication(); handleURL("/camelot"); equal(currentPath, 'camelot'); equal(Ember.$('h3:contains(silly)', '#qunit-fixture').length, 1, "The camelot template was rendered"); handleURL("/"); equal(currentPath, 'home'); equal(Ember.$('h3:contains(Hours)', '#qunit-fixture').length, 1, "The home template was rendered"); }); test("The Homepage register as activeView", function() { Router.map(function() { this.route("home", { path: "/" }); this.route("homepage"); }); App.HomeRoute = Ember.Route.extend({ }); App.HomepageRoute = Ember.Route.extend({ }); bootApplication(); ok(router._lookupActiveView('home'), '`home` active view is connected'); handleURL('/homepage'); ok(router._lookupActiveView('homepage'), '`homepage` active view is connected'); equal(router._lookupActiveView('home'), undefined, '`home` active view is disconnected'); }); test("The Homepage with explicit template name in renderTemplate", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('homepage'); } }); bootApplication(); equal(Ember.$('h3:contains(Megatroll)', '#qunit-fixture').length, 1, "The homepage template was rendered"); }); test("An alternate template will pull in an alternate controller", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('homepage'); } }); App.HomepageController = Ember.Controller.extend({ home: "Comes from homepage" }); bootApplication(); equal(Ember.$('h3:contains(Megatroll) + p:contains(Comes from homepage)', '#qunit-fixture').length, 1, "The homepage template was rendered"); }); test("The template will pull in an alternate controller via key/value", function() { Router.map(function() { this.route("homepage", { path: "/" }); }); App.HomepageRoute = Ember.Route.extend({ renderTemplate: function() { this.render({controller: 'home'}); } }); App.HomeController = Ember.Controller.extend({ home: "Comes from home." }); bootApplication(); equal(Ember.$('h3:contains(Megatroll) + p:contains(Comes from home.)', '#qunit-fixture').length, 1, "The homepage template was rendered from data from the HomeController"); }); test("The Homepage with explicit template name in renderTemplate and controller", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeController = Ember.Controller.extend({ home: "YES I AM HOME" }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('homepage'); } }); bootApplication(); equal(Ember.$('h3:contains(Megatroll) + p:contains(YES I AM HOME)', '#qunit-fixture').length, 1, "The homepage template was rendered"); }); if(Ember.FEATURES.isEnabled("ember-routing-add-model-option")) { test("Model passed via renderTemplate model is set as controller's content", function(){ Ember.TEMPLATES['bio'] = compile("<p>{{name}}</p>"); App.BioController = Ember.ObjectController.extend(); Router.map(function(){ this.route('home', { path: '/'}); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function(){ this.render('bio', { model: {name: 'emberjs'} }); } }); bootApplication(); equal(Ember.$('p:contains(emberjs)', '#qunit-fixture').length, 1, "Passed model was set as controllers content"); }); } test("Renders correct view with slash notation", function() { Ember.TEMPLATES['home/page'] = compile("<p>{{view.name}}</p>"); Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('home/page'); } }); App.HomePageView = Ember.View.extend({ name: "Home/Page" }); bootApplication(); equal(Ember.$('p:contains(Home/Page)', '#qunit-fixture').length, 1, "The homepage template was rendered"); }); test("Renders the view given in the view option", function() { Ember.TEMPLATES['home'] = compile("<p>{{view.name}}</p>"); Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render({view: 'homePage'}); } }); App.HomePageView = Ember.View.extend({ name: "Home/Page" }); bootApplication(); equal(Ember.$('p:contains(Home/Page)', '#qunit-fixture').length, 1, "The homepage view was rendered"); }); test('render does not replace templateName if user provided', function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.the_real_home_template = Ember.Handlebars.compile( "<p>THIS IS THE REAL HOME</p>" ); App.HomeView = Ember.View.extend({ templateName: 'the_real_home_template' }); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend(); bootApplication(); equal(Ember.$('p', '#qunit-fixture').text(), "THIS IS THE REAL HOME", "The homepage template was rendered"); }); test('render does not replace template if user provided', function () { Router.map(function () { this.route("home", { path: "/" }); }); App.HomeView = Ember.View.extend({ template: Ember.Handlebars.compile("<p>THIS IS THE REAL HOME</p>") }); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend(); bootApplication(); Ember.run(function () { router.handleURL("/"); }); equal(Ember.$('p', '#qunit-fixture').text(), "THIS IS THE REAL HOME", "The homepage template was rendered"); }); test('render uses templateName from route', function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.the_real_home_template = Ember.Handlebars.compile( "<p>THIS IS THE REAL HOME</p>" ); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend({ templateName: 'the_real_home_template' }); bootApplication(); equal(Ember.$('p', '#qunit-fixture').text(), "THIS IS THE REAL HOME", "The homepage template was rendered"); }); test('defining templateName allows other templates to be rendered', function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.alert = Ember.Handlebars.compile( "<div class='alert-box'>Invader!</div>" ); Ember.TEMPLATES.the_real_home_template = Ember.Handlebars.compile( "<p>THIS IS THE REAL HOME</p>{{outlet alert}}" ); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend({ templateName: 'the_real_home_template', actions: { showAlert: function(){ this.render('alert', { into: 'home', outlet: 'alert' }); } } }); bootApplication(); equal(Ember.$('p', '#qunit-fixture').text(), "THIS IS THE REAL HOME", "The homepage template was rendered"); Ember.run(function(){ router.send('showAlert'); }); equal(Ember.$('.alert-box', '#qunit-fixture').text(), "Invader!", "Template for alert was render into outlet"); }); test('Specifying a name to render should have precedence over everything else', function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend({ templateName: 'home', controllerName: 'home', viewName: 'home', renderTemplate: function() { this.render('homepage'); } }); App.HomeView = Ember.View.extend({ template: Ember.Handlebars.compile("<h3>This should not be rendered</h3><p>{{home}}</p>") }); App.HomepageController = Ember.ObjectController.extend({ content: { home: 'Tinytroll' } }); App.HomepageView = Ember.View.extend({ layout: Ember.Handlebars.compile( "<span>Outer</span>{{yield}}<span>troll</span>" ), templateName: 'homepage' }); bootApplication(); equal(Ember.$('h3', '#qunit-fixture').text(), "Megatroll", "The homepage template was rendered"); equal(Ember.$('p', '#qunit-fixture').text(), "Tinytroll", "The homepage controller was used"); equal(Ember.$('span', '#qunit-fixture').text(), "Outertroll", "The homepage view was used"); }); test("The Homepage with a `setupController` hook", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ setupController: function(controller) { set(controller, 'hours', Ember.A([ "Monday through Friday: 9am to 5pm", "Saturday: Noon to Midnight", "Sunday: Noon to 6pm" ])); } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<ul>{{#each entry in hours}}<li>{{entry}}</li>{{/each}}</ul>" ); bootApplication(); equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the hours context"); }); test("The route controller is still set when overriding the setupController hook", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ setupController: function(controller) { // no-op // importantly, we are not calling this._super here } }); container.register('controller:home', Ember.Controller.extend()); bootApplication(); deepEqual(container.lookup('route:home').controller, container.lookup('controller:home'), "route controller is the home controller"); }); test("The route controller can be specified via controllerName", function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<p>{{myValue}}</p>" ); App.HomeRoute = Ember.Route.extend({ controllerName: 'myController' }); container.register('controller:myController', Ember.Controller.extend({ myValue: "foo" })); bootApplication(); deepEqual(container.lookup('route:home').controller, container.lookup('controller:myController'), "route controller is set by controllerName"); equal(Ember.$('p', '#qunit-fixture').text(), "foo", "The homepage template was rendered with data from the custom controller"); }); test("The route controller specified via controllerName is used in render", function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.alternative_home = Ember.Handlebars.compile( "<p>alternative home: {{myValue}}</p>" ); App.HomeRoute = Ember.Route.extend({ controllerName: 'myController', renderTemplate: function() { this.render("alternative_home"); } }); container.register('controller:myController', Ember.Controller.extend({ myValue: "foo" })); bootApplication(); deepEqual(container.lookup('route:home').controller, container.lookup('controller:myController'), "route controller is set by controllerName"); equal(Ember.$('p', '#qunit-fixture').text(), "alternative home: foo", "The homepage template was rendered with data from the custom controller"); }); test("The Homepage with a `setupController` hook modifying other controllers", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ setupController: function(controller) { set(this.controllerFor('home'), 'hours', Ember.A([ "Monday through Friday: 9am to 5pm", "Saturday: Noon to Midnight", "Sunday: Noon to 6pm" ])); } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<ul>{{#each entry in hours}}<li>{{entry}}</li>{{/each}}</ul>" ); bootApplication(); equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the hours context"); }); test("The Homepage with a computed context that does not get overridden", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeController = Ember.ArrayController.extend({ content: Ember.computed(function() { return Ember.A([ "Monday through Friday: 9am to 5pm", "Saturday: Noon to Midnight", "Sunday: Noon to 6pm" ]); }) }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<ul>{{#each}}<li>{{this}}</li>{{/each}}</ul>" ); bootApplication(); equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the context intact"); }); test("The Homepage getting its controller context via model", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ model: function() { return Ember.A([ "Monday through Friday: 9am to 5pm", "Saturday: Noon to Midnight", "Sunday: Noon to 6pm" ]); }, setupController: function(controller, model) { equal(this.controllerFor('home'), controller); set(this.controllerFor('home'), 'hours', model); } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<ul>{{#each entry in hours}}<li>{{entry}}</li>{{/each}}</ul>" ); bootApplication(); equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the hours context"); }); test("The Specials Page getting its controller context by deserializing the params hash", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); App.SpecialRoute = Ember.Route.extend({ model: function(params) { return Ember.Object.create({ menuItemId: params.menu_item_id }); }, setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.menuItemId}}</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); handleURL("/specials/1"); equal(Ember.$('p', '#qunit-fixture').text(), "1", "The model was used to render the template"); }); test("The Specials Page defaults to looking models up via `find`", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); App.MenuItem = Ember.Object.extend(); App.MenuItem.reopenClass({ find: function(id) { return App.MenuItem.create({ id: id }); } }); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); handleURL("/specials/1"); equal(Ember.$('p', '#qunit-fixture').text(), "1", "The model was used to render the template"); }); test("The Special Page returning a promise puts the app into a loading state until the promise is resolved", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); return menuItem; } }); App.LoadingRoute = Ember.Route.extend({ }); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); Ember.TEMPLATES.loading = Ember.Handlebars.compile( "<p>LOADING!</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); handleURL("/specials/1"); equal(Ember.$('p', '#qunit-fixture').text(), "LOADING!", "The app is in the loading state"); Ember.run(function() { menuItem.resolve(menuItem); }); equal(Ember.$('p', '#qunit-fixture').text(), "1", "The app is now in the specials state"); }); test("The loading state doesn't get entered for promises that resolve on the same run loop", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); App.MenuItem = Ember.Object.extend(); App.MenuItem.reopenClass({ find: function(id) { return { id: id }; } }); App.LoadingRoute = Ember.Route.extend({ enter: function() { ok(false, "LoadingRoute shouldn't have been entered."); } }); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); Ember.TEMPLATES.loading = Ember.Handlebars.compile( "<p>LOADING!</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); handleURL("/specials/1"); equal(Ember.$('p', '#qunit-fixture').text(), "1", "The app is now in the specials state"); }); /* asyncTest("The Special page returning an error fires the error hook on SpecialRoute", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); Ember.run.later(function() { menuItem.resolve(menuItem); }, 1); return menuItem; } }); App.SpecialRoute = Ember.Route.extend({ setup: function() { throw 'Setup error'; }, actions: { error: function(reason) { equal(reason, 'Setup error'); QUnit.start(); } } }); bootApplication(); handleURLRejectsWith('/specials/1', 'Setup error'); }); */ test("The Special page returning an error invokes SpecialRoute's error handler", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); return menuItem; } }); App.SpecialRoute = Ember.Route.extend({ setup: function() { throw 'Setup error'; }, actions: { error: function(reason) { equal(reason, 'Setup error', 'SpecialRoute#error received the error thrown from setup'); } } }); bootApplication(); handleURLRejectsWith('/specials/1', 'Setup error'); Ember.run(menuItem, menuItem.resolve, menuItem); }); function testOverridableErrorHandler(handlersName) { expect(2); Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); return menuItem; } }); var attrs = {}; attrs[handlersName] = { error: function(reason) { equal(reason, 'Setup error', "error was correctly passed to custom ApplicationRoute handler"); } }; App.ApplicationRoute = Ember.Route.extend(attrs); App.SpecialRoute = Ember.Route.extend({ setup: function() { throw 'Setup error'; } }); bootApplication(); handleURLRejectsWith("/specials/1", "Setup error"); Ember.run(menuItem, 'resolve', menuItem); } test("ApplicationRoute's default error handler can be overridden", function() { testOverridableErrorHandler('actions'); }); test("ApplicationRoute's default error handler can be overridden (with DEPRECATED `events`)", function() { testOverridableErrorHandler('events'); }); asyncTest("Moving from one page to another triggers the correct callbacks", function() { expect(3); Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<h3>Home</h3>" ); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); var transition = handleURL('/'); Ember.run(function() { transition.then(function() { equal(Ember.$('h3', '#qunit-fixture').text(), "Home", "The app is now in the initial state"); var promiseContext = App.MenuItem.create({ id: 1 }); Ember.run.later(function() { promiseContext.resolve(promiseContext); }, 1); return router.transitionTo('special', promiseContext); }).then(function(result) { deepEqual(router.location.path, '/specials/1'); QUnit.start(); }); }); }); asyncTest("Nested callbacks are not exited when moving to siblings", function() { Router.map(function() { this.resource("root", { path: "/" }, function() { this.resource("special", { path: "/specials/:menu_item_id" }); }); }); var currentPath; App.ApplicationController = Ember.Controller.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); return menuItem; } }); App.LoadingRoute = Ember.Route.extend({ }); App.RootRoute = Ember.Route.extend({ model: function() { rootModel++; return this._super.apply(this, arguments); }, serialize: function() { rootSerialize++; return this._super.apply(this, arguments); }, setupController: function() { rootSetup++; }, renderTemplate: function() { rootRender++; } }); App.HomeRoute = Ember.Route.extend({ }); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES['root/index'] = Ember.Handlebars.compile( "<h3>Home</h3>" ); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); Ember.TEMPLATES.loading = Ember.Handlebars.compile( "<p>LOADING!</p>" ); var rootSetup = 0, rootRender = 0, rootModel = 0, rootSerialize = 0; bootApplication(); container.register('controller:special', Ember.Controller.extend()); equal(Ember.$('h3', '#qunit-fixture').text(), "Home", "The app is now in the initial state"); equal(rootSetup, 1, "The root setup was triggered"); equal(rootRender, 1, "The root render was triggered"); equal(rootSerialize, 0, "The root serialize was not called"); equal(rootModel, 1, "The root model was called"); router = container.lookup('router:main'); Ember.run(function() { var menuItem = App.MenuItem.create({ id: 1 }); Ember.run.later(function() { menuItem.resolve(menuItem); }, 1); router.transitionTo('special', menuItem).then(function(result) { equal(rootSetup, 1, "The root setup was not triggered again"); equal(rootRender, 1, "The root render was not triggered again"); equal(rootSerialize, 0, "The root serialize was not called"); // TODO: Should this be changed? equal(rootModel, 1, "The root model was called again"); deepEqual(router.location.path, '/specials/1'); equal(currentPath, 'root.special'); QUnit.start(); }); }); }); asyncTest("Events are triggered on the controller if a matching action name is implemented", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; var stateIsNotCalled = true; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, actions: { showStuff: function(obj) { stateIsNotCalled = false; } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); var controller = Ember.Controller.extend({ actions: { showStuff: function(context) { ok (stateIsNotCalled, "an event on the state is not triggered"); deepEqual(context, { name: "Tom Dale" }, "an event with context is passed"); QUnit.start(); } } }); container.register('controller:home', controller); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); asyncTest("Events are triggered on the current state when defined in `actions` object", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, actions: { showStuff: function(obj) { ok(this instanceof App.HomeRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct"); QUnit.start(); } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); asyncTest("Events defined in `actions` object are triggered on the current state when routes are nested", function() { Router.map(function() { this.resource("root", { path: "/" }, function() { this.route("index", { path: "/" }); }); }); var model = { name: "Tom Dale" }; App.RootRoute = Ember.Route.extend({ actions: { showStuff: function(obj) { ok(this instanceof App.RootRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct"); QUnit.start(); } } }); App.RootIndexRoute = Ember.Route.extend({ model: function() { return model; } }); Ember.TEMPLATES['root/index'] = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); asyncTest("Events are triggered on the current state when defined in `events` object (DEPRECATED)", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, events: { showStuff: function(obj) { ok(this instanceof App.HomeRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct"); QUnit.start(); } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); expectDeprecation(/Action handlers contained in an `events` object are deprecated/); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); asyncTest("Events defined in `events` object are triggered on the current state when routes are nested (DEPRECATED)", function() { Router.map(function() { this.resource("root", { path: "/" }, function() { this.route("index", { path: "/" }); }); }); var model = { name: "Tom Dale" }; App.RootRoute = Ember.Route.extend({ events: { showStuff: function(obj) { ok(this instanceof App.RootRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct"); QUnit.start(); } } }); App.RootIndexRoute = Ember.Route.extend({ model: function() { return model; } }); Ember.TEMPLATES['root/index'] = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); expectDeprecation(/Action handlers contained in an `events` object are deprecated/); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); test("Events can be handled by inherited event handlers", function() { expect(4); App.SuperRoute = Ember.Route.extend({ actions: { foo: function() { ok(true, 'foo'); }, bar: function(msg) { equal(msg, "HELLO"); } } }); App.RouteMixin = Ember.Mixin.create({ actions: { bar: function(msg) { equal(msg, "HELLO"); this._super(msg); } } }); App.IndexRoute = App.SuperRoute.extend(App.RouteMixin, { actions: { baz: function() { ok(true, 'baz'); } } }); bootApplication(); router.send("foo"); router.send("bar", "HELLO"); router.send("baz"); }); if (Ember.FEATURES.isEnabled('ember-routing-drop-deprecated-action-style')) { asyncTest("Actions are not triggered on the controller if a matching action name is implemented as a method", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; var stateIsNotCalled = true; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, actions: { showStuff: function(context) { ok (stateIsNotCalled, "an event on the state is not triggered"); deepEqual(context, { name: "Tom Dale" }, "an event with context is passed"); QUnit.start(); } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); var controller = Ember.Controller.extend({ showStuff: function(context) { stateIsNotCalled = false; ok (stateIsNotCalled, "an event on the state is not triggered"); } }); container.register('controller:home', controller); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); } else { asyncTest("Events are triggered on the controller if a matching action name is implemented as a method (DEPRECATED)", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; var stateIsNotCalled = true; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, events: { showStuff: function(obj) { stateIsNotCalled = false; ok (stateIsNotCalled, "an event on the state is not triggered"); } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); var controller = Ember.Controller.extend({ showStuff: function(context) { ok (stateIsNotCalled, "an event on the state is not triggered"); deepEqual(context, { name: "Tom Dale" }, "an event with context is passed"); QUnit.start(); } }); container.register('controller:home', controller); expectDeprecation(/Action handlers contained in an `events` object are deprecated/); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); } asyncTest("actions can be triggered with multiple arguments", function() { Router.map(function() { this.resource("root", { path: "/" }, function() { this.route("index", { path: "/" }); }); }); var model1 = { name: "Tilde" }, model2 = { name: "Tom Dale" }; App.RootRoute = Ember.Route.extend({ actions: { showStuff: function(obj1, obj2) { ok(this instanceof App.RootRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj1, true), { name: "Tilde" }, "the first context is correct"); deepEqual(Ember.copy(obj2, true), { name: "Tom Dale" }, "the second context is correct"); QUnit.start(); } } }); App.RootIndexController = Ember.Controller.extend({ model1: model1, model2: model2 }); Ember.TEMPLATES['root/index'] = Ember.Handlebars.compile( "<a {{action 'showStuff' model1 model2}}>{{model1.name}}</a>" ); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); test("transitioning multiple times in a single run loop only sets the URL once", function() { Router.map(function() { this.route("root", { path: "/" }); this.route("foo"); this.route("bar"); }); bootApplication(); var urlSetCount = 0; router.get('location').setURL = function(path) { urlSetCount++; set(this, 'path', path); }; equal(urlSetCount, 0); Ember.run(function() { router.transitionTo("foo"); router.transitionTo("bar"); }); equal(urlSetCount, 1); equal(router.get('location').getURL(), "/bar"); }); test('navigating away triggers a url property change', function() { expect(3); Router.map(function() { this.route('root', { path: '/' }); this.route('foo', { path: '/foo' }); this.route('bar', { path: '/bar' }); }); bootApplication(); Ember.run(function() { Ember.addObserver(router, 'url', function() { ok(true, "url change event was fired"); }); }); forEach(['foo', 'bar', '/foo'], function(destination) { Ember.run(router, 'transitionTo', destination); }); }); test("using replaceWith calls location.replaceURL if available", function() { var setCount = 0, replaceCount = 0; Router.reopen({ location: Ember.NoneLocation.createWithMixins({ setURL: function(path) { setCount++; set(this, 'path', path); }, replaceURL: function(path) { replaceCount++; set(this, 'path', path); } }) }); Router.map(function() { this.route("root", { path: "/" }); this.route("foo"); }); bootApplication(); equal(setCount, 0); equal(replaceCount, 0); Ember.run(function() { router.replaceWith("foo"); }); equal(setCount, 0, 'should not call setURL'); equal(replaceCount, 1, 'should call replaceURL once'); equal(router.get('location').getURL(), "/foo"); }); test("using replaceWith calls setURL if location.replaceURL is not defined", function() { var setCount = 0; Router.reopen({ location: Ember.NoneLocation.createWithMixins({ setURL: function(path) { setCount++; set(this, 'path', path); } }) }); Router.map(function() { this.route("root", { path: "/" }); this.route("foo"); }); bootApplication(); equal(setCount, 0); Ember.run(function() { router.replaceWith("foo"); }); equal(setCount, 1, 'should call setURL once'); equal(router.get('location').getURL(), "/foo"); }); test("Route inherits model from parent route", function() { expect(9); Router.map(function() { this.resource("the_post", { path: "/posts/:post_id" }, function() { this.route("comments"); this.resource("shares", { path: "/shares/:share_id"}, function() { this.route("share"); }); }); }); var post1 = {}, post2 = {}, post3 = {}, currentPost; var share1 = {}, share2 = {}, share3 = {}, currentShare; var posts = { 1: post1, 2: post2, 3: post3 }; var shares = { 1: share1, 2: share2, 3: share3 }; App.ThePostRoute = Ember.Route.extend({ model: function(params) { return posts[params.post_id]; } }); App.ThePostCommentsRoute = Ember.Route.extend({ afterModel: function(post, transition) { var parent_model = this.modelFor('thePost'); equal(post, parent_model); } }); App.SharesRoute = Ember.Route.extend({ model: function(params) { return shares[params.share_id]; } }); App.SharesShareRoute = Ember.Route.extend({ afterModel: function(share, transition) { var parent_model = this.modelFor('shares'); equal(share, parent_model); } }); bootApplication(); currentPost = post1; handleURL("/posts/1/comments"); handleURL("/posts/1/shares/1"); currentPost = post2; handleURL("/posts/2/comments"); handleURL("/posts/2/shares/2"); currentPost = post3; handleURL("/posts/3/comments"); handleURL("/posts/3/shares/3"); }); test("Resource does not inherit model from parent resource", function() { expect(6); Router.map(function() { this.resource("the_post", { path: "/posts/:post_id" }, function() { this.resource("comments", function() { }); }); }); var post1 = {}, post2 = {}, post3 = {}, currentPost; var posts = { 1: post1, 2: post2, 3: post3 }; App.ThePostRoute = Ember.Route.extend({ model: function(params) { return posts[params.post_id]; } }); App.CommentsRoute = Ember.Route.extend({ afterModel: function(post, transition) { var parent_model = this.modelFor('thePost'); notEqual(post, parent_model); } }); bootApplication(); currentPost = post1; handleURL("/posts/1/comments"); currentPost = post2; handleURL("/posts/2/comments"); currentPost = post3; handleURL("/posts/3/comments"); }); test("It is possible to get the model from a parent route", function() { expect(9); Router.map(function() { this.resource("the_post", { path: "/posts/:post_id" }, function() { this.resource("comments"); }); }); var post1 = {}, post2 = {}, post3 = {}, currentPost; var posts = { 1: post1, 2: post2, 3: post3 }; App.ThePostRoute = Ember.Route.extend({ model: function(params) { return posts[params.post_id]; } }); App.CommentsRoute = Ember.Route.extend({ model: function() { // Allow both underscore / camelCase format. equal(this.modelFor('thePost'), currentPost); equal(this.modelFor('the_post'), currentPost); } }); bootApplication(); currentPost = post1; handleURL("/posts/1/comments"); currentPost = post2; handleURL("/posts/2/comments"); currentPost = post3; handleURL("/posts/3/comments"); }); test("A redirection hook is provided", function() { Router.map(function() { this.route("choose", { path: "/" }); this.route("home"); }); var chooseFollowed = 0, destination; App.ChooseRoute = Ember.Route.extend({ redirect: function() { if (destination) { this.transitionTo(destination); } }, setupController: function() { chooseFollowed++; } }); destination = 'home'; bootApplication(); equal(chooseFollowed, 0, "The choose route wasn't entered since a transition occurred"); equal(Ember.$("h3:contains(Hours)", "#qunit-fixture").length, 1, "The home template was rendered"); equal(router.container.lookup('controller:application').get('currentPath'), 'home'); }); test("Redirecting from the middle of a route aborts the remainder of the routes", function() { expect(3); Router.map(function() { this.route("home"); this.resource("foo", function() { this.resource("bar", function() { this.route("baz"); }); }); }); App.BarRoute = Ember.Route.extend({ redirect: function() { this.transitionTo("home"); }, setupController: function() { ok(false, "Should transition before setupController"); } }); App.BarBazRoute = Ember.Route.extend({ enter: function() { ok(false, "Should abort transition getting to next route"); } }); bootApplication(); handleURLAborts("/foo/bar/baz"); equal(router.container.lookup('controller:application').get('currentPath'), 'home'); equal(router.get('location').getURL(), "/home"); }); test("Redirecting to the current target in the middle of a route does not abort initial routing", function() { expect(5); Router.map(function() { this.route("home"); this.resource("foo", function() { this.resource("bar", function() { this.route("baz"); }); }); }); var successCount = 0; App.BarRoute = Ember.Route.extend({ redirect: function() { this.transitionTo("bar.baz").then(function() { successCount++; }); }, setupController: function() { ok(true, "Should still invoke bar's setupController"); } }); App.BarBazRoute = Ember.Route.extend({ setupController: function() { ok(true, "Should still invoke bar.baz's setupController"); } }); bootApplication(); handleURL("/foo/bar/baz"); equal(router.container.lookup('controller:application').get('currentPath'), 'foo.bar.baz'); equal(successCount, 1, 'transitionTo success handler was called once'); }); test("Redirecting to the current target with a different context aborts the remainder of the routes", function() { expect(4); Router.map(function() { this.route("home"); this.resource("foo", function() { this.resource("bar", { path: "bar/:id" }, function() { this.route("baz"); }); }); }); var model = { id: 2 }; var count = 0; App.BarRoute = Ember.Route.extend({ afterModel: function(context) { if (count++ > 10) { ok(false, 'infinite loop'); } else { this.transitionTo("bar.baz", model); } }, serialize: function(params) { return params; } }); App.BarBazRoute = Ember.Route.extend({ setupController: function() { ok(true, "Should still invoke setupController"); } }); bootApplication(); handleURLAborts("/foo/bar/1/baz"); equal(router.container.lookup('controller:application').get('currentPath'), 'foo.bar.baz'); equal(router.get('location').getURL(), "/foo/bar/2/baz"); }); test("Transitioning from a parent event does not prevent currentPath from being set", function() { Router.map(function() { this.resource("foo", function() { this.resource("bar", function() { this.route("baz"); }); this.route("qux"); }); }); App.FooRoute = Ember.Route.extend({ actions: { goToQux: function() { this.transitionTo('foo.qux'); } } }); bootApplication(); var applicationController = router.container.lookup('controller:application'); handleURL("/foo/bar/baz"); equal(applicationController.get('currentPath'), 'foo.bar.baz'); Ember.run(function() { router.send("goToQux"); }); equal(applicationController.get('currentPath'), 'foo.qux'); equal(router.get('location').getURL(), "/foo/qux"); }); test("Generated names can be customized when providing routes with dot notation", function() { expect(4); Ember.TEMPLATES.index = compile("<div>Index</div>"); Ember.TEMPLATES.application = compile("<h1>Home</h1><div class='main'>{{outlet}}</div>"); Ember.TEMPLATES.foo = compile("<div class='middle'>{{outlet}}</div>"); Ember.TEMPLATES.bar = compile("<div class='bottom'>{{outlet}}</div>"); Ember.TEMPLATES['bar/baz'] = compile("<p>{{name}}Bottom!</p>"); Router.map(function() { this.resource("foo", { path: "/top" }, function() { this.resource("bar", { path: "/middle" }, function() { this.route("baz", { path: "/bottom" }); }); }); }); App.FooRoute = Ember.Route.extend({ renderTemplate: function() { ok(true, "FooBarRoute was called"); return this._super.apply(this, arguments); } }); App.BarBazRoute = Ember.Route.extend({ renderTemplate: function() { ok(true, "BarBazRoute was called"); return this._super.apply(this, arguments); } }); App.BarController = Ember.Controller.extend({ name: "Bar" }); App.BarBazController = Ember.Controller.extend({ name: "BarBaz" }); bootApplication(); handleURL("/top/middle/bottom"); equal(Ember.$('.main .middle .bottom p', '#qunit-fixture').text(), "BarBazBottom!", "The templates were rendered into their appropriate parents"); }); test("Child routes render into their parent route's template by default", function() { Ember.TEMPLATES.index = compile("<div>Index</div>"); Ember.TEMPLATES.application = compile("<h1>Home</h1><div class='main'>{{outlet}}</div>"); Ember.TEMPLATES.top = compile("<div class='middle'>{{outlet}}</div>"); Ember.TEMPLATES.middle = compile("<div class='bottom'>{{outlet}}</div>"); Ember.TEMPLATES['middle/bottom'] = compile("<p>Bottom!</p>"); Router.map(function() { this.resource("top", function() { this.resource("middle", function() { this.route("bottom"); }); }); }); bootApplication(); handleURL("/top/middle/bottom"); equal(Ember.$('.main .middle .bottom p', '#qunit-fixture').text(), "Bottom!", "The templates were rendered into their appropriate parents"); }); test("Child routes render into specified template", function() { Ember.TEMPLATES.index = compile("<div>Index</div>"); Ember.TEMPLATES.application = compile("<h1>Home</h1><div class='main'>{{outlet}}</div>"); Ember.TEMPLATES.top = compile("<div class='middle'>{{outlet}}</div>"); Ember.TEMPLATES.middle = compile("<div class='bottom'>{{outlet}}</div>"); Ember.TEMPLATES['middle/bottom'] = compile("<p>Bottom!</p>"); Router.map(function() { this.resource("top", function() { this.resource("middle", function() { this.route("bottom"); }); }); }); App.MiddleBottomRoute = Ember.Route.extend({ renderTemplate: function() { this.render('middle/bottom', { into: 'top' }); } }); bootApplication(); handleURL("/top/middle/bottom"); equal(Ember.$('.main .middle .bottom p', '#qunit-fixture').length, 0, "should not render into the middle template"); equal(Ember.$('.main .middle > p', '#qunit-fixture').text(), "Bottom!", "The template was rendered into the top template"); }); test("Rendering into specified template with slash notation", function() { Ember.TEMPLATES['person/profile'] = compile("profile {{outlet}}"); Ember.TEMPLATES['person/details'] = compile("details!"); Router.map(function() { this.resource("home", { path: '/' }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('person/profile'); this.render('person/details', { into: 'person/profile' }); } }); bootApplication(); equal(Ember.$('#qunit-fixture:contains(profile details!)').length, 1, "The templates were rendered"); }); test("Parent route context change", function() { var editCount = 0, editedPostIds = Ember.A(); Ember.TEMPLATES.application = compile("{{outlet}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES.post = compile("{{outlet}}"); Ember.TEMPLATES['post/index'] = compile("showing"); Ember.TEMPLATES['post/edit'] = compile("editing"); Router.map(function() { this.resource("posts", function() { this.resource("post", { path: "/:postId" }, function() { this.route("edit"); }); }); }); App.PostsRoute = Ember.Route.extend({ actions: { showPost: function(context) { this.transitionTo('post', context); } } }); App.PostRoute = Ember.Route.extend({ model: function(params) { return {id: params.postId}; }, actions: { editPost: function(context) { this.transitionTo('post.edit'); } } }); App.PostEditRoute = Ember.Route.extend({ model: function(params) { var postId = this.modelFor("post").id; editedPostIds.push(postId); return null; }, setup: function() { this._super.apply(this, arguments); editCount++; } }); bootApplication(); handleURL("/posts/1"); Ember.run(function() { router.send('editPost'); }); Ember.run(function() { router.send('showPost', {id: '2'}); }); Ember.run(function() { router.send('editPost'); }); equal(editCount, 2, 'set up the edit route twice without failure'); deepEqual(editedPostIds, ['1', '2'], 'modelFor posts.post returns the right context'); }); test("Router accounts for rootURL on page load when using history location", function() { var rootURL = window.location.pathname + '/app', postsTemplateRendered = false, setHistory, HistoryTestLocation; setHistory = function(obj, path) { obj.set('history', { state: { path: path } }); }; // Create new implementation that extends HistoryLocation // and set current location to rootURL + '/posts' HistoryTestLocation = Ember.HistoryLocation.extend({ initState: function() { var path = rootURL + '/posts'; setHistory(this, path); this.set('location', { pathname: path }); }, replaceState: function(path) { setHistory(this, path); }, pushState: function(path) { setHistory(this, path); } }); container.register('location:historyTest', HistoryTestLocation); Router.reopen({ location: 'historyTest', rootURL: rootURL }); Router.map(function() { this.resource("posts", { path: '/posts' }); }); App.PostsRoute = Ember.Route.extend({ model: function() {}, renderTemplate: function() { postsTemplateRendered = true; } }); bootApplication(); ok(postsTemplateRendered, "Posts route successfully stripped from rootURL"); }); test("The rootURL is passed properly to the location implementation", function() { expect(1); var rootURL = "/blahzorz", HistoryTestLocation; HistoryTestLocation = Ember.HistoryLocation.extend({ rootURL: 'this is not the URL you are looking for', initState: function() { equal(this.get('rootURL'), rootURL); } }); container.register('location:history-test', HistoryTestLocation); Router.reopen({ location: 'history-test', rootURL: rootURL, // if we transition in this test we will receive failures // if the tests are run from a static file _doTransition: function(){} }); bootApplication(); }); test("Only use route rendered into main outlet for default into property on child", function() { Ember.TEMPLATES.application = compile("{{outlet menu}}{{outlet}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES['posts/index'] = compile("postsIndex"); Ember.TEMPLATES['posts/menu'] = compile("postsMenu"); Router.map(function() { this.resource("posts", function() {}); }); App.PostsMenuView = Ember.View.extend({ tagName: 'div', templateName: 'posts/menu', classNames: ['posts-menu'] }); App.PostsIndexView = Ember.View.extend({ tagName: 'p', classNames: ['posts-index'] }); App.PostsRoute = Ember.Route.extend({ renderTemplate: function() { this.render(); this.render('postsMenu', { into: 'application', outlet: 'menu' }); } }); bootApplication(); handleURL("/posts"); equal(Ember.$('div.posts-menu:contains(postsMenu)', '#qunit-fixture').length, 1, "The posts/menu template was rendered"); equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered"); }); test("Generating a URL should not affect currentModel", function() { Router.map(function() { this.route("post", { path: "/posts/:post_id" }); }); var posts = { 1: { id: 1 }, 2: { id: 2 } }; App.PostRoute = Ember.Route.extend({ model: function(params) { return posts[params.post_id]; } }); bootApplication(); handleURL("/posts/1"); var route = container.lookup('route:post'); equal(route.modelFor('post'), posts[1]); var url = router.generate('post', posts[2]); equal(url, "/posts/2"); equal(route.modelFor('post'), posts[1]); }); test("Generated route should be an instance of App.Route if provided", function() { var generatedRoute; Router.map(function() { this.route('posts'); }); App.Route = Ember.Route.extend(); bootApplication(); handleURL("/posts"); generatedRoute = container.lookup('route:posts'); ok(generatedRoute instanceof App.Route, 'should extend the correct route'); }); test("Nested index route is not overriden by parent's implicit index route", function() { Router.map(function() { this.resource('posts', function() { this.route('index', { path: ':category' } ); }); }); App.Route = Ember.Route.extend({ serialize: function(model) { return { category: model.category }; } }); bootApplication(); Ember.run(function() { router.transitionTo('posts', { category: 'emberjs' }); }); deepEqual(router.location.path, '/posts/emberjs'); }); test("Application template does not duplicate when re-rendered", function() { Ember.TEMPLATES.application = compile("<h3>I Render Once</h3>{{outlet}}"); Router.map(function() { this.route('posts'); }); App.ApplicationRoute = Ember.Route.extend({ model: function() { return Ember.A(); } }); bootApplication(); // should cause application template to re-render handleURL('/posts'); equal(Ember.$('h3:contains(I Render Once)').size(), 1); }); test("Child routes should render inside the application template if the application template causes a redirect", function() { Ember.TEMPLATES.application = compile("<h3>App</h3> {{outlet}}"); Ember.TEMPLATES.posts = compile("posts"); Router.map(function() { this.route('posts'); this.route('photos'); }); App.ApplicationRoute = Ember.Route.extend({ afterModel: function() { this.transitionTo('posts'); } }); bootApplication(); equal(Ember.$('#qunit-fixture > div').text(), "App posts"); }); test("The template is not re-rendered when the route's context changes", function() { Router.map(function() { this.route("page", { path: "/page/:name" }); }); App.PageRoute = Ember.Route.extend({ model: function(params) { return Ember.Object.create({name: params.name}); } }); var insertionCount = 0; App.PageView = Ember.View.extend({ didInsertElement: function() { insertionCount += 1; } }); Ember.TEMPLATES.page = Ember.Handlebars.compile( "<p>{{name}}</p>" ); bootApplication(); handleURL("/page/first"); equal(Ember.$('p', '#qunit-fixture').text(), "first"); equal(insertionCount, 1); handleURL("/page/second"); equal(Ember.$('p', '#qunit-fixture').text(), "second"); equal(insertionCount, 1, "view should have inserted only once"); Ember.run(function() { router.transitionTo('page', Ember.Object.create({name: 'third'})); }); equal(Ember.$('p', '#qunit-fixture').text(), "third"); equal(insertionCount, 1, "view should still have inserted only once"); }); test("The template is not re-rendered when two routes present the exact same template, view, & controller", function() { Router.map(function() { this.route("first"); this.route("second"); this.route("third"); this.route("fourth"); }); App.SharedRoute = Ember.Route.extend({ viewName: 'shared', setupController: function(controller) { this.controllerFor('shared').set('message', "This is the " + this.routeName + " message"); }, renderTemplate: function(controller, context) { this.render({ controller: 'shared' }); } }); App.FirstRoute = App.SharedRoute.extend(); App.SecondRoute = App.SharedRoute.extend(); App.ThirdRoute = App.SharedRoute.extend(); App.FourthRoute = App.SharedRoute.extend({ viewName: 'fourth' }); App.SharedController = Ember.Controller.extend(); var insertionCount = 0; App.SharedView = Ember.View.extend({ templateName: 'shared', didInsertElement: function() { insertionCount += 1; } }); // Extending, in essence, creates a different view App.FourthView = App.SharedView.extend(); Ember.TEMPLATES.shared = Ember.Handlebars.compile( "<p>{{message}}</p>" ); bootApplication(); handleURL("/first"); equal(Ember.$('p', '#qunit-fixture').text(), "This is the first message"); equal(insertionCount, 1, 'expected one assertion'); // Transition by URL handleURL("/second"); equal(Ember.$('p', '#qunit-fixture').text(), "This is the second message"); equal(insertionCount, 1, "view should have inserted only once"); // Then transition directly by route name Ember.run(function() { router.transitionTo('third').then(function(value){ ok(true, 'expected transition'); }, function(reason) { ok(false, 'unexpected transition failure: ', QUnit.jsDump.parse(reason)); }); }); equal(Ember.$('p', '#qunit-fixture').text(), "This is the third message"); equal(insertionCount, 1, "view should still have inserted only once"); // Lastly transition to a different view, with the same controller and template handleURL("/fourth"); equal(Ember.$('p', '#qunit-fixture').text(), "This is the fourth message"); equal(insertionCount, 2, "view should have inserted a second time"); }); test("ApplicationRoute with model does not proxy the currentPath", function() { var model = {}; var currentPath; App.ApplicationRoute = Ember.Route.extend({ model: function () { return model; } }); App.ApplicationController = Ember.ObjectController.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); bootApplication(); equal(currentPath, 'index', 'currentPath is index'); equal('currentPath' in model, false, 'should have defined currentPath on controller'); }); test("Promises encountered on app load put app into loading state until resolved", function() { expect(2); var deferred = Ember.RSVP.defer(); App.IndexRoute = Ember.Route.extend({ model: function() { return deferred.promise; } }); Ember.TEMPLATES.index = Ember.Handlebars.compile("<p>INDEX</p>"); Ember.TEMPLATES.loading = Ember.Handlebars.compile("<p>LOADING</p>"); bootApplication(); equal(Ember.$('p', '#qunit-fixture').text(), "LOADING", "The loading state is displaying."); Ember.run(deferred.resolve); equal(Ember.$('p', '#qunit-fixture').text(), "INDEX", "The index route is display."); }); test("Route should tear down multiple outlets", function() { Ember.TEMPLATES.application = compile("{{outlet menu}}{{outlet}}{{outlet footer}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES.users = compile("users"); Ember.TEMPLATES['posts/index'] = compile("postsIndex"); Ember.TEMPLATES['posts/menu'] = compile("postsMenu"); Ember.TEMPLATES['posts/footer'] = compile("postsFooter"); Router.map(function() { this.resource("posts", function() {}); this.resource("users", function() {}); }); App.PostsMenuView = Ember.View.extend({ tagName: 'div', templateName: 'posts/menu', classNames: ['posts-menu'] }); App.PostsIndexView = Ember.View.extend({ tagName: 'p', classNames: ['posts-index'] }); App.PostsFooterView = Ember.View.extend({ tagName: 'div', templateName: 'posts/footer', classNames: ['posts-footer'] }); App.PostsRoute = Ember.Route.extend({ renderTemplate: function() { this.render('postsMenu', { into: 'application', outlet: 'menu' }); this.render(); this.render('postsFooter', { into: 'application', outlet: 'footer' }); } }); bootApplication(); handleURL('/posts'); equal(Ember.$('div.posts-menu:contains(postsMenu)', '#qunit-fixture').length, 1, "The posts/menu template was rendered"); equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered"); equal(Ember.$('div.posts-footer:contains(postsFooter)', '#qunit-fixture').length, 1, "The posts/footer template was rendered"); handleURL('/users'); equal(Ember.$('div.posts-menu:contains(postsMenu)', '#qunit-fixture').length, 0, "The posts/menu template was removed"); equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 0, "The posts/index template was removed"); equal(Ember.$('div.posts-footer:contains(postsFooter)', '#qunit-fixture').length, 0, "The posts/footer template was removed"); }); test("Route supports clearing outlet explicitly", function() { Ember.TEMPLATES.application = compile("{{outlet}}{{outlet modal}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES.users = compile("users"); Ember.TEMPLATES['posts/index'] = compile("postsIndex {{outlet}}"); Ember.TEMPLATES['posts/modal'] = compile("postsModal"); Ember.TEMPLATES['posts/extra'] = compile("postsExtra"); Router.map(function() { this.resource("posts", function() {}); this.resource("users", function() {}); }); App.PostsIndexView = Ember.View.extend({ classNames: ['posts-index'] }); App.PostsModalView = Ember.View.extend({ templateName: 'posts/modal', classNames: ['posts-modal'] }); App.PostsExtraView = Ember.View.extend({ templateName: 'posts/extra', classNames: ['posts-extra'] }); App.PostsRoute = Ember.Route.extend({ actions: { showModal: function() { this.render('postsModal', { into: 'application', outlet: 'modal' }); }, hideModal: function() { this.disconnectOutlet({outlet: 'modal', parentView: 'application'}); } } }); App.PostsIndexRoute = Ember.Route.extend({ actions: { showExtra: function() { this.render('postsExtra', { into: 'posts/index' }); }, hideExtra: function() { this.disconnectOutlet({parentView: 'posts/index'}); } } }); bootApplication(); handleURL('/posts'); equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered"); Ember.run(function() { router.send('showModal'); }); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 1, "The posts/modal template was rendered"); Ember.run(function() { router.send('showExtra'); }); equal(Ember.$('div.posts-extra:contains(postsExtra)', '#qunit-fixture').length, 1, "The posts/extra template was rendered"); Ember.run(function() { router.send('hideModal'); }); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 0, "The posts/modal template was removed"); Ember.run(function() { router.send('hideExtra'); }); equal(Ember.$('div.posts-extra:contains(postsExtra)', '#qunit-fixture').length, 0, "The posts/extra template was removed"); handleURL('/users'); equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 0, "The posts/index template was removed"); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 0, "The posts/modal template was removed"); equal(Ember.$('div.posts-extra:contains(postsExtra)', '#qunit-fixture').length, 0, "The posts/extra template was removed"); }); test("Route supports clearing outlet using string parameter", function() { Ember.TEMPLATES.application = compile("{{outlet}}{{outlet modal}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES.users = compile("users"); Ember.TEMPLATES['posts/index'] = compile("postsIndex {{outlet}}"); Ember.TEMPLATES['posts/modal'] = compile("postsModal"); Router.map(function() { this.resource("posts", function() {}); this.resource("users", function() {}); }); App.PostsIndexView = Ember.View.extend({ classNames: ['posts-index'] }); App.PostsModalView = Ember.View.extend({ templateName: 'posts/modal', classNames: ['posts-modal'] }); App.PostsRoute = Ember.Route.extend({ actions: { showModal: function() { this.render('postsModal', { into: 'application', outlet: 'modal' }); }, hideModal: function() { this.disconnectOutlet('modal'); } } }); bootApplication(); handleURL('/posts'); equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered"); Ember.run(function() { router.send('showModal'); }); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 1, "The posts/modal template was rendered"); Ember.run(function() { router.send('hideModal'); }); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 0, "The posts/modal template was removed"); handleURL('/users'); equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 0, "The posts/index template was removed"); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 0, "The posts/modal template was removed"); }); test("Route silently fails when cleaning an outlet from an inactive view", function() { expect(1); // handleURL Ember.TEMPLATES.application = compile("{{outlet}}"); Ember.TEMPLATES.posts = compile("{{outlet modal}}"); Ember.TEMPLATES.modal = compile("A Yo."); Router.map(function() { this.route("posts"); }); App.PostsRoute = Ember.Route.extend({ actions: { hideSelf: function() { this.disconnectOutlet({outlet: 'main', parentView: 'application'}); }, showModal: function() { this.render('modal', {into: 'posts', outlet: 'modal'}); }, hideModal: function() { this.disconnectOutlet({outlet: 'modal', parentView: 'posts'}); } } }); bootApplication(); handleURL('/posts'); Ember.run(function() { router.send('showModal'); }); Ember.run(function() { router.send('hideSelf'); }); Ember.run(function() { router.send('hideModal'); }); }); test("Aborting/redirecting the transition in `willTransition` prevents LoadingRoute from being entered", function() { expect(8); Router.map(function() { this.route("nork"); this.route("about"); }); var redirect = false; App.IndexRoute = Ember.Route.extend({ actions: { willTransition: function(transition) { ok(true, "willTransition was called"); if (redirect) { // router.js won't refire `willTransition` for this redirect this.transitionTo('about'); } else { transition.abort(); } } } }); var deferred = null; App.LoadingRoute = Ember.Route.extend({ activate: function() { ok(deferred, "LoadingRoute should be entered at this time"); }, deactivate: function() { ok(true, "LoadingRoute was exited"); } }); App.NorkRoute = Ember.Route.extend({ activate: function() { ok(true, "NorkRoute was entered"); } }); App.AboutRoute = Ember.Route.extend({ activate: function() { ok(true, "AboutRoute was entered"); }, model: function() { if (deferred) { return deferred.promise; } } }); bootApplication(); // Attempted transitions out of index should abort. Ember.run(router, 'transitionTo', 'nork'); Ember.run(router, 'handleURL', '/nork'); // Attempted transitions out of index should redirect to about redirect = true; Ember.run(router, 'transitionTo', 'nork'); Ember.run(router, 'transitionTo', 'index'); // Redirected transitions out of index to a route with a // promise model should pause the transition and // activate LoadingRoute deferred = Ember.RSVP.defer(); Ember.run(router, 'transitionTo', 'nork'); Ember.run(deferred.resolve); }); test("`didTransition` event fires on the router", function() { expect(3); Router.map(function(){ this.route("nork"); }); router = container.lookup('router:main'); router.one('didTransition', function(){ ok(true, 'didTransition fired on initial routing'); }); bootApplication(); router.one('didTransition', function(){ ok(true, 'didTransition fired on the router'); equal(router.get('url'), "/nork", 'The url property is updated by the time didTransition fires'); }); Ember.run(router, 'transitionTo', 'nork'); }); test("`didTransition` can be reopened", function() { expect(1); Router.map(function(){ this.route("nork"); }); Router.reopen({ didTransition: function(){ this._super.apply(this, arguments); ok(true, 'reopened didTransition was called'); } }); bootApplication(); }); test("Actions can be handled by inherited action handlers", function() { expect(4); App.SuperRoute = Ember.Route.extend({ actions: { foo: function() { ok(true, 'foo'); }, bar: function(msg) { equal(msg, "HELLO"); } } }); App.RouteMixin = Ember.Mixin.create({ actions: { bar: function(msg) { equal(msg, "HELLO"); this._super(msg); } } }); App.IndexRoute = App.SuperRoute.extend(App.RouteMixin, { actions: { baz: function() { ok(true, 'baz'); } } }); bootApplication(); router.send("foo"); router.send("bar", "HELLO"); router.send("baz"); }); test("currentRouteName is a property installed on ApplicationController that can be used in transitionTo", function() { expect(24); Router.map(function() { this.resource("be", function() { this.resource("excellent", function() { this.resource("to", function() { this.resource("each", function() { this.route("other"); }); }); }); }); }); bootApplication(); var appController = router.container.lookup('controller:application'); function transitionAndCheck(path, expectedPath, expectedRouteName) { if (path) { Ember.run(router, 'transitionTo', path); } equal(appController.get('currentPath'), expectedPath); equal(appController.get('currentRouteName'), expectedRouteName); } transitionAndCheck(null, 'index', 'index'); transitionAndCheck('/be', 'be.index', 'be.index'); transitionAndCheck('/be/excellent', 'be.excellent.index', 'excellent.index'); transitionAndCheck('/be/excellent/to', 'be.excellent.to.index', 'to.index'); transitionAndCheck('/be/excellent/to/each', 'be.excellent.to.each.index', 'each.index'); transitionAndCheck('/be/excellent/to/each/other', 'be.excellent.to.each.other', 'each.other'); transitionAndCheck('index', 'index', 'index'); transitionAndCheck('be', 'be.index', 'be.index'); transitionAndCheck('excellent', 'be.excellent.index', 'excellent.index'); transitionAndCheck('to.index', 'be.excellent.to.index', 'to.index'); transitionAndCheck('each', 'be.excellent.to.each.index', 'each.index'); transitionAndCheck('each.other', 'be.excellent.to.each.other', 'each.other'); }); test("Route model hook finds the same model as a manual find", function() { var Post; App.Post = Ember.Object.extend(); App.Post.reopenClass({ find: function() { Post = this; return {}; } }); Router.map(function() { this.route('post', { path: '/post/:post_id' }); }); bootApplication(); handleURL('/post/1'); equal(App.Post, Post); }); test("Can register an implementation via Ember.Location.registerImplementation (DEPRECATED)", function(){ var TestLocation = Ember.NoneLocation.extend({ implementation: 'test' }); expectDeprecation(/Using the Ember.Location.registerImplementation is no longer supported/); Ember.Location.registerImplementation('test', TestLocation); Router.reopen({ location: 'test' }); bootApplication(); equal(router.get('location.implementation'), 'test', 'custom location implementation can be registered with registerImplementation'); }); test("Ember.Location.registerImplementation is deprecated", function(){ var TestLocation = Ember.NoneLocation.extend({ implementation: 'test' }); expectDeprecation(function(){ Ember.Location.registerImplementation('test', TestLocation); }, "Using the Ember.Location.registerImplementation is no longer supported. Register your custom location implementation with the container instead."); }); test("Routes can refresh themselves causing their model hooks to be re-run", function() { Router.map(function() { this.resource('parent', { path: '/parent/:parent_id' }, function() { this.route('child'); }); }); var appcount = 0; App.ApplicationRoute = Ember.Route.extend({ model: function() { ++appcount; } }); var parentcount = 0; App.ParentRoute = Ember.Route.extend({ model: function(params) { equal(params.parent_id, '123'); ++parentcount; }, actions: { refreshParent: function() { this.refresh(); } } }); var childcount = 0; App.ParentChildRoute = Ember.Route.extend({ model: function() { ++childcount; } }); bootApplication(); equal(appcount, 1); equal(parentcount, 0); equal(childcount, 0); Ember.run(router, 'transitionTo', 'parent.child', '123'); equal(appcount, 1); equal(parentcount, 1); equal(childcount, 1); Ember.run(router, 'send', 'refreshParent'); equal(appcount, 1); equal(parentcount, 2); equal(childcount, 2); }); test("Specifying non-existent controller name in route#render throws", function() { expect(1); Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { try { this.render('homepage', { controller: 'stefanpenneristhemanforme' }); } catch(e) { equal(e.message, "You passed `controller: 'stefanpenneristhemanforme'` into the `render` method, but no such controller could be found."); } } }); bootApplication(); }); test("Redirecting with null model doesn't error out", function() { Router.map(function() { this.route("home", { path: '/' }); this.route("about", { path: '/about/:hurhurhur' }); }); App.HomeRoute = Ember.Route.extend({ beforeModel: function() { this.transitionTo('about', null); } }); App.AboutRoute = Ember.Route.extend({ serialize: function(model) { if (model === null) { return { hurhurhur: 'TreeklesMcGeekles' }; } } }); bootApplication(); equal(router.get('location.path'), "/about/TreeklesMcGeekles"); }); test("rejecting the model hooks promise with a non-error prints the `message` property", function() { var rejectedMessage = 'OMG!! SOOOOOO BAD!!!!', rejectedStack = 'Yeah, buddy: stack gets printed too.', originalLoggerError = Ember.Logger.error; Router.map(function() { this.route("yippie", { path: "/" }); }); Ember.Logger.error = function(initialMessage, errorMessage, errorStack) { equal(initialMessage, 'Error while loading route: yippie', 'a message with the current route name is printed'); equal(errorMessage, rejectedMessage, "the rejected reason's message property is logged"); equal(errorStack, rejectedStack, "the rejected reason's stack property is logged"); }; App.YippieRoute = Ember.Route.extend({ model: function(){ return Ember.RSVP.reject({message: rejectedMessage, stack: rejectedStack}); } }); bootApplication(); Ember.Logger.error = originalLoggerError; }); test("rejecting the model hooks promise with no reason still logs error", function() { var originalLoggerError = Ember.Logger.error; Router.map(function() { this.route("wowzers", { path: "/" }); }); Ember.Logger.error = function(initialMessage) { equal(initialMessage, 'Error while loading route: wowzers', 'a message with the current route name is printed'); }; App.WowzersRoute = Ember.Route.extend({ model: function(){ return Ember.RSVP.reject(); } }); bootApplication(); Ember.Logger.error = originalLoggerError; }); test("rejecting the model hooks promise with a string shows a good error", function() { var originalLoggerError = Ember.Logger.error, rejectedMessage = "Supercalifragilisticexpialidocious"; Router.map(function() { this.route("yondo", { path: "/" }); }); Ember.Logger.error = function(initialMessage, errorMessage) { equal(initialMessage, 'Error while loading route: yondo', 'a message with the current route name is printed'); equal(errorMessage, rejectedMessage, "the rejected reason's message property is logged"); }; App.YondoRoute = Ember.Route.extend({ model: function(){ return Ember.RSVP.reject(rejectedMessage); } }); bootApplication(); Ember.Logger.error = originalLoggerError; }); if (Ember.FEATURES.isEnabled("ember-routing-will-change-hooks")) { test("willLeave, willChangeModel actions fire on routes", function() { expect(2); App.Router.map(function() { this.route('user', { path: '/user/:id' }); }); function shouldNotFire() { ok(false, "this action shouldn't have been received"); } var willChangeFired = false, willLeaveFired = false; App.IndexRoute = Ember.Route.extend({ actions: { willChangeModel: shouldNotFire, willChangeContext: shouldNotFire, willLeave: function() { willLeaveFired = true; } } }); App.UserRoute = Ember.Route.extend({ actions: { willChangeModel: function() { willChangeFired = true; }, willChangeContext: shouldNotFire, willLeave: shouldNotFire } }); bootApplication(); Ember.run(router, 'transitionTo', 'user', { id: 'wat' }); ok(willLeaveFired, "#actions.willLeaveFired"); Ember.run(router, 'transitionTo', 'user', { id: 'lol' }); ok(willChangeFired, "user#actions.willChangeModel"); }); } else { test("willLeave, willChangeContext, willChangeModel actions don't fire unless feature flag enabled", function() { expect(1); App.Router.map(function() { this.route('about'); }); function shouldNotFire() { ok(false, "this action shouldn't have been received"); } App.IndexRoute = Ember.Route.extend({ actions: { willChangeModel: shouldNotFire, willChangeContext: shouldNotFire, willLeave: shouldNotFire } }); App.AboutRoute = Ember.Route.extend({ setupController: function() { ok(true, "about route was entered"); } }); bootApplication(); Ember.run(router, 'transitionTo', 'about'); }); }
g13013/ember.js
packages_es6/ember/tests/routing/basic_test.js
JavaScript
mit
84,137
""" from https://codelab.interviewbit.com/problems/symmetry/ """ # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param A : root node of tree # @return an integer def isSymmetric(self, A): return self.are_symmetric(A.left, A.right) def are_symmetric(self, tree1, tree2): if tree1 is None or tree2 is None: # when checking the bottom return tree1 == tree2 return tree1.val == tree2.val and self.are_symmetric(tree1.left, tree2.right) and self.are_symmetric( tree1.right, tree2.left) # Could
JuanCTorres/interview-prep-solutions
codelab/symmetric_trees.py
Python
mit
694
/** * Simple themeing with color overrides */ export namespace Colors { export let flatButtonPrimary = 'rgb(0, 188, 212)'; }
basarat/uic
src/base/styles.tsx
TypeScript
mit
129
package CellContent; import java.util.*; import Cell.Cell; import Models.Ant; import javafx.scene.paint.Color; public class ForagingAntsContent extends CellContent{ List<Ant>antsHere; double homePheromone, foodPheromone, maxPheromone; boolean isFoodSource, isHome; public ForagingAntsContent (int i, Color col,boolean home, boolean food, double maxPh, double foodPh, double homePh, List<Ant> ants) { super(i, col); isHome = home; isFoodSource = food; antsHere = ants; homePheromone = homePh; foodPheromone = foodPh; // TODO Auto-generated constructor stub } public List<Ant> getAnts(){ return antsHere; } public void setAnts(List<Ant> ants){ antsHere = ants; } public void setIsFoodSource(boolean food){ isFoodSource = food; } public boolean getIsFoodSource(){ return isFoodSource; } public void setIsHome(boolean home){ isHome = home; } public boolean getIsHome(){ return isHome; } public void setHomePheromone(double home){ homePheromone = home; } public double getHomePheromone(){ return homePheromone; } public void setFoodPheromone(double food){ foodPheromone = food; } public double getFoodPheromone(){ return foodPheromone; } public double getPheromone(boolean goingHome){ if(goingHome){ return homePheromone; }else{ return foodPheromone; } } public double getMaxPheromone(){ return maxPheromone; } public void setMaxPheromone(boolean home){ if(home){ homePheromone = maxPheromone; }else{ foodPheromone = maxPheromone; } } public List<Ant> getAntsClone(){ List<Ant> clone = new ArrayList<Ant>(); for(Ant a : antsHere){ Ant aClone = new Ant(a.getLifeLeft()); aClone.setOrientation(a.getOrientation()); aClone.hasFoodItem(a.hasFoodItem()); clone.add(aClone); } return clone; } }
NaijiaoZhang/cellsociety
src/CellContent/ForagingAntsContent.java
Java
mit
2,214
package math.calculus; /** * * @author Joris Schelfaut */ public class NonLinearEquation { }
noisedriver/java-math-library
src/math/calculus/NonLinearEquation.java
Java
mit
111
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("EatMeWpf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("EatMeWpf")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a33627f8-abbd-4a30-9b76-cb6d5ef2c6aa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Wheredidigo/RebornBuddyPublic
EatMeWpf/EatMeWpf/Properties/AssemblyInfo.cs
C#
mit
1,410
import React from 'react'; import Plus from 'react-icons/fa/plus' export default ({routes, onSelectChange, onCreateLink}) => ( <div className="field has-addons"> <div className="control is-expanded"> <div className="select is-fullwidth"> <select name="route" onChange={e => onSelectChange(e.target.value)}> <option value="">Selecciona una ruta</option> { routes.map(route => ( <option value={route.id}>{route.number}</option> )) } </select> </div> </div> <div className="control"> <button className="button is-primary" onClick={() => onCreateLink()}><Plus/></button> </div> </div> );
Donluigimx/transporta2_admin
app/components/BusStops/LinkBusStop.js
JavaScript
mit
852
import React from 'react' import clsx from 'clsx' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { push } from 'connected-react-router' import CircularProgress from '@material-ui/core/CircularProgress' import List from '@material-ui/core/List' import { withStyles } from '@material-ui/core/styles' import ItemListItem from './ItemListItem' import NoItemsInfo from './NoItemsInfo' const styles = (theme: any) => ({ root: {}, progress: { alignSelf: 'center', marginTop: theme.spacing(4), marginBottom: theme.spacing(4) } }) class ItemList extends React.Component<{ [key: string]: any }> { handleRedirectItem = (id: any) => this.props.push(`/item/prototype/${id}`) mapListItem = (item: any) => ( <ItemListItem key={item.id} item={item} onClick={this.handleRedirectItem} /> ) render() { const { classes, className, items, fetching } = this.props if (items.size === 0) { return fetching ? ( <CircularProgress className={classes.progress} /> ) : ( <NoItemsInfo /> ) } return ( <List dense disablePadding className={clsx(classes.root, className)} > {items.map(this.mapListItem)} </List> ) } } const mapDispatchToProps = (dispatch: any) => { return bindActionCreators({ push }, dispatch) } export default connect( () => ({}), mapDispatchToProps )(withStyles(styles)(ItemList))
petrdsvoboda/prototype-orders
app/src/components/common/ItemList/ItemList.tsx
TypeScript
mit
1,402
#include "EEPROMWearLevelingReader.h" EEPROMWearLevelingReader::EEPROMWearLevelingReader() { reader.setPosition(findPosition()); reader.next(); // We know the next byte is the begin mark, so just skip it } uint8 EEPROMWearLevelingReader::next() { if (atEnd()) { return 0; } else { return escapeIfNecessary(reader.next()); } } uint8 EEPROMWearLevelingReader::next(bool& timeout) { timeout = false; return next(); } bool EEPROMWearLevelingReader::atEnd() { return reader.getPosition() == endPosition; } uint8 EEPROMWearLevelingReader::escapeIfNecessary(uint8 byte) { if ((byte == EEPROM_BEGIN_MARK && reader.peek() == EEPROM_BEGIN_MARK) || (byte == EEPROM_END_MARK && reader.peek() == EEPROM_END_MARK)) { reader.next(); } return byte; } int16 EEPROMWearLevelingReader::findPosition() { EEPROMReader reader; int16 count, position; // Skip beginning end marks count = 0; while (count < EEPROM_SIZE && reader.peek() == EEPROM_END_MARK) { // Skip this byte reader.next(); count++; } // Now, look for the end mark on the entire memory count = 0; while (count <= EEPROM_SIZE) { count++; if (reader.next() == EEPROM_END_MARK) { if (reader.peek() == EEPROM_END_MARK) { // It was escaped. Skip next reader.next(); count++; } else { // We found it! Break out of the loop break; } } } // Skip end mark and take note of its position reader.back(); endPosition = reader.getPosition(); // Finally, go back until you find the begin mark position = count = 0; while (count <= EEPROM_SIZE) { count++; if (reader.back() == EEPROM_BEGIN_MARK) { if (reader.peekBack() == EEPROM_BEGIN_MARK) { // It was escaped. Skip back reader.back(); count++; } else { // We found it! Break out of the loop position = reader.getPosition(); break; } } } return position; }
RichoM/Uzi
c++/UziFirmware/EEPROMWearLevelingReader.cpp
C++
mit
1,892
from PyQt4 import QtGui, QtCore from PyQt4 import uic form_class = uic.loadUiType('logWindow.ui')[0] class LogWindow(QtGui.QDialog, form_class): def __init__(self, parent=None): super(LogWindow, self).__init__(parent) self.setup_ui() def setup_ui(self): self.setupUi(self) self.show() def addLog(self, msg): self.list_log.addItem(msg)
RaynoldKim/MyTrade
LogWindow.py
Python
mit
394
// DO NOT EDIT. This file is generated #include "../Precompiled.h" #include "../AngelScript/APITemplates.h" #include "../AngelScript/GeneratedIncludes.h" #include "../AngelScript/Manual.h" namespace Urho3D { void FakeAddRef(void* ptr); void FakeReleaseRef(void* ptr); // explicit File::File(Context* context) | File: ../IO/File.h static File* File_File_Context() { return new File(GetScriptContext()); } // File::File(Context* context, const String& fileName, FileMode mode=FILE_READ) | File: ../IO/File.h static File* File_File_Context_String_FileMode(const String &fileName, FileMode mode=FILE_READ) { return new File(GetScriptContext(), fileName, mode); } // File::File(Context* context, PackageFile* package, const String& fileName) | File: ../IO/File.h static File* File_File_Context_PackageFile_String(PackageFile *package, const String &fileName) { return new File(GetScriptContext(), package, fileName); } // StringVector Deserializer::ReadStringVector() | File: ../IO/Deserializer.h static CScriptArray* File_ReadStringVector_void(File* ptr) { StringVector result = ptr->ReadStringVector(); return VectorToArray<String>(result, "Array<String>"); } // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h static void File_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool(File* ptr, CScriptArray* exceptions, bool onlyUserData) { PODVector<StringHash> param0 = ArrayToPODVector<StringHash>(exceptions); ptr->UnsubscribeFromAllEventsExcept(param0, onlyUserData); } // explicit FileSelector::FileSelector(Context* context) | File: ../UI/FileSelector.h static FileSelector* FileSelector_FileSelector_Context() { return new FileSelector(GetScriptContext()); } // void FileSelector::SetFilters(const Vector<String>& filters, unsigned defaultIndex) | File: ../UI/FileSelector.h static void FileSelector_SetFilters_VectorString_unsigned(FileSelector* ptr, CScriptArray* filters, unsigned defaultIndex) { Vector<String> param0 = ArrayToVector<String>(filters); ptr->SetFilters(param0, defaultIndex); } // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h static void FileSelector_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool(FileSelector* ptr, CScriptArray* exceptions, bool onlyUserData) { PODVector<StringHash> param0 = ArrayToPODVector<StringHash>(exceptions); ptr->UnsubscribeFromAllEventsExcept(param0, onlyUserData); } // explicit FileSystem::FileSystem(Context* context) | File: ../IO/FileSystem.h static FileSystem* FileSystem_FileSystem_Context() { return new FileSystem(GetScriptContext()); } // int FileSystem::SystemRun(const String& fileName, const Vector<String>& arguments) | File: ../IO/FileSystem.h static int FileSystem_SystemRun_String_VectorString(FileSystem* ptr, const String& fileName, CScriptArray* arguments) { Vector<String> param1 = ArrayToVector<String>(arguments); int result = ptr->SystemRun(fileName, param1); return result; } // unsigned FileSystem::SystemRunAsync(const String& fileName, const Vector<String>& arguments) | File: ../IO/FileSystem.h static unsigned FileSystem_SystemRunAsync_String_VectorString(FileSystem* ptr, const String& fileName, CScriptArray* arguments) { Vector<String> param1 = ArrayToVector<String>(arguments); unsigned result = ptr->SystemRunAsync(fileName, param1); return result; } // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h static void FileSystem_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool(FileSystem* ptr, CScriptArray* exceptions, bool onlyUserData) { PODVector<StringHash> param0 = ArrayToPODVector<StringHash>(exceptions); ptr->UnsubscribeFromAllEventsExcept(param0, onlyUserData); } // explicit FileWatcher::FileWatcher(Context* context) | File: ../IO/FileWatcher.h static FileWatcher* FileWatcher_FileWatcher_Context() { return new FileWatcher(GetScriptContext()); } // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h static void FileWatcher_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool(FileWatcher* ptr, CScriptArray* exceptions, bool onlyUserData) { PODVector<StringHash> param0 = ArrayToPODVector<StringHash>(exceptions); ptr->UnsubscribeFromAllEventsExcept(param0, onlyUserData); } // explicit Font::Font(Context* context) | File: ../UI/Font.h static Font* Font_Font_Context() { return new Font(GetScriptContext()); } // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h static void Font_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool(Font* ptr, CScriptArray* exceptions, bool onlyUserData) { PODVector<StringHash> param0 = ArrayToPODVector<StringHash>(exceptions); ptr->UnsubscribeFromAllEventsExcept(param0, onlyUserData); } // const Vector<SharedPtr<Texture2D>>& FontFace::GetTextures() const | File: ../UI/FontFace.h static CScriptArray* FontFace_GetTextures_void(FontFace* ptr) { const Vector<SharedPtr<Texture2D>>& result = ptr->GetTextures(); return VectorToHandleArray(result, "Array<Texture2D@>"); } // explicit FontFaceBitmap::FontFaceBitmap(Font* font) | File: ../UI/FontFaceBitmap.h static FontFaceBitmap* FontFaceBitmap_FontFaceBitmap_Font(Font *font) { return new FontFaceBitmap(font); } // const Vector<SharedPtr<Texture2D>>& FontFace::GetTextures() const | File: ../UI/FontFace.h static CScriptArray* FontFaceBitmap_GetTextures_void(FontFaceBitmap* ptr) { const Vector<SharedPtr<Texture2D>>& result = ptr->GetTextures(); return VectorToHandleArray(result, "Array<Texture2D@>"); } // explicit FontFaceFreeType::FontFaceFreeType(Font* font) | File: ../UI/FontFaceFreeType.h static FontFaceFreeType* FontFaceFreeType_FontFaceFreeType_Font(Font *font) { return new FontFaceFreeType(font); } // const Vector<SharedPtr<Texture2D>>& FontFace::GetTextures() const | File: ../UI/FontFace.h static CScriptArray* FontFaceFreeType_GetTextures_void(FontFaceFreeType* ptr) { const Vector<SharedPtr<Texture2D>>& result = ptr->GetTextures(); return VectorToHandleArray(result, "Array<Texture2D@>"); } // Frustum::Frustum(const Frustum& frustum) noexcept | File: ../Math/Frustum.h static void Frustum_Frustum_Frustum(Frustum* ptr, const Frustum &frustum) { new(ptr) Frustum(frustum); } // Frustum::~Frustum() | Implicitly-declared static void Frustum_Destructor(Frustum* ptr) { ptr->~Frustum(); } // FileSelectorEntry::~FileSelectorEntry() | Implicitly-declared static void FileSelectorEntry_Destructor(FileSelectorEntry* ptr) { ptr->~FileSelectorEntry(); } // FocusParameters::FocusParameters(bool focus, bool nonUniform, bool autoSize, float quantize, float minView) | File: ../Graphics/Light.h static void FocusParameters_FocusParameters_bool_bool_bool_float_float(FocusParameters* ptr, bool focus, bool nonUniform, bool autoSize, float quantize, float minView) { new(ptr) FocusParameters(focus, nonUniform, autoSize, quantize, minView); } // FontGlyph::~FontGlyph() | Implicitly-declared static void FontGlyph_Destructor(FontGlyph* ptr) { ptr->~FontGlyph(); } // FrameInfo::~FrameInfo() | Implicitly-declared static void FrameInfo_Destructor(FrameInfo* ptr) { ptr->~FrameInfo(); } void ASRegisterGenerated_Members_F(asIScriptEngine* engine) { // void RefCounted::AddRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("File", asBEHAVE_ADDREF, "void f()", asMETHODPR(File, AddRef, (), void), asCALL_THISCALL); // template<typename T> T* Object::Cast() | File: ../Core/Object.h // Not registered because template // template<typename T> const T* Object::Cast() const | File: ../Core/Object.h // Not registered because template // void File::Close() | File: ../IO/File.h engine->RegisterObjectMethod("File", "void Close()", asMETHODPR(File, Close, (), void), asCALL_THISCALL); // explicit File::File(Context* context) | File: ../IO/File.h engine->RegisterObjectBehaviour("File", asBEHAVE_FACTORY, "File@+ f()", asFUNCTION(File_File_Context), asCALL_CDECL); // File::File(Context* context, const String& fileName, FileMode mode=FILE_READ) | File: ../IO/File.h engine->RegisterObjectBehaviour("File", asBEHAVE_FACTORY, "File@+ f(const String&in, FileMode = FILE_READ)", asFUNCTION(File_File_Context_String_FileMode), asCALL_CDECL); // File::File(Context* context, PackageFile* package, const String& fileName) | File: ../IO/File.h engine->RegisterObjectBehaviour("File", asBEHAVE_FACTORY, "File@+ f(PackageFile@+, const String&in)", asFUNCTION(File_File_Context_PackageFile_String), asCALL_CDECL); // void File::Flush() | File: ../IO/File.h engine->RegisterObjectMethod("File", "void Flush()", asMETHODPR(File, Flush, (), void), asCALL_THISCALL); // bool Object::GetBlockEvents() const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "bool GetBlockEvents() const", asMETHODPR(File, GetBlockEvents, () const, bool), asCALL_THISCALL); // const String& Object::GetCategory() const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "const String& GetCategory() const", asMETHODPR(File, GetCategory, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("File", "const String& get_category() const", asMETHODPR(File, GetCategory, () const, const String&), asCALL_THISCALL); // unsigned File::GetChecksum() override | File: ../IO/File.h engine->RegisterObjectMethod("File", "uint GetChecksum()", asMETHODPR(File, GetChecksum, (), unsigned), asCALL_THISCALL); engine->RegisterObjectMethod("File", "uint get_checksum()", asMETHODPR(File, GetChecksum, (), unsigned), asCALL_THISCALL); // Context* Object::GetContext() const | File: ../Core/Object.h // Error: type "Context*" can not be returned // VariantMap& Object::GetEventDataMap() const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "VariantMap& GetEventDataMap() const", asMETHODPR(File, GetEventDataMap, () const, VariantMap&), asCALL_THISCALL); // EventHandler* Object::GetEventHandler() const | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // Object* Object::GetEventSender() const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "Object@+ GetEventSender() const", asMETHODPR(File, GetEventSender, () const, Object*), asCALL_THISCALL); // const Variant& Object::GetGlobalVar(StringHash key) const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "const Variant& GetGlobalVar(StringHash) const", asMETHODPR(File, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); engine->RegisterObjectMethod("File", "const Variant& get_globalVar(StringHash) const", asMETHODPR(File, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); // const VariantMap& Object::GetGlobalVars() const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "const VariantMap& GetGlobalVars() const", asMETHODPR(File, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); engine->RegisterObjectMethod("File", "const VariantMap& get_globalVars() const", asMETHODPR(File, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); // void* File::GetHandle() const | File: ../IO/File.h // Error: type "void*" can not automatically bind // FileMode File::GetMode() const | File: ../IO/File.h engine->RegisterObjectMethod("File", "FileMode GetMode() const", asMETHODPR(File, GetMode, () const, FileMode), asCALL_THISCALL); engine->RegisterObjectMethod("File", "FileMode get_mode() const", asMETHODPR(File, GetMode, () const, FileMode), asCALL_THISCALL); // const String& AbstractFile::GetName() const override | File: ../IO/AbstractFile.h engine->RegisterObjectMethod("File", "const String& GetName() const", asMETHODPR(File, GetName, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("File", "const String& get_name() const", asMETHODPR(File, GetName, () const, const String&), asCALL_THISCALL); // unsigned Deserializer::GetPosition() const | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint GetPosition() const", asMETHODPR(File, GetPosition, () const, unsigned), asCALL_THISCALL); engine->RegisterObjectMethod("File", "uint get_position() const", asMETHODPR(File, GetPosition, () const, unsigned), asCALL_THISCALL); // unsigned Deserializer::GetSize() const | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint GetSize() const", asMETHODPR(File, GetSize, () const, unsigned), asCALL_THISCALL); engine->RegisterObjectMethod("File", "uint get_size() const", asMETHODPR(File, GetSize, () const, unsigned), asCALL_THISCALL); // Object* Object::GetSubsystem(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "Object@+ GetSubsystem(StringHash) const", asMETHODPR(File, GetSubsystem, (StringHash) const, Object*), asCALL_THISCALL); // template<class T> T* Object::GetSubsystem() const | File: ../Core/Object.h // Not registered because template // virtual StringHash Object::GetType() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("File", "StringHash GetType() const", asMETHODPR(File, GetType, () const, StringHash), asCALL_THISCALL); engine->RegisterObjectMethod("File", "StringHash get_type() const", asMETHODPR(File, GetType, () const, StringHash), asCALL_THISCALL); // virtual const TypeInfo* Object::GetTypeInfo() const =0 | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // static const TypeInfo* Object::GetTypeInfoStatic() | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // virtual const String& Object::GetTypeName() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("File", "const String& GetTypeName() const", asMETHODPR(File, GetTypeName, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("File", "const String& get_typeName() const", asMETHODPR(File, GetTypeName, () const, const String&), asCALL_THISCALL); // bool Object::HasEventHandlers() const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "bool HasEventHandlers() const", asMETHODPR(File, HasEventHandlers, () const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "bool HasSubscribedToEvent(StringHash) const", asMETHODPR(File, HasSubscribedToEvent, (StringHash) const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(Object* sender, StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "bool HasSubscribedToEvent(Object@+, StringHash) const", asMETHODPR(File, HasSubscribedToEvent, (Object*, StringHash) const, bool), asCALL_THISCALL); // virtual bool Deserializer::IsEof() const | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "bool IsEof() const", asMETHODPR(File, IsEof, () const, bool), asCALL_THISCALL); engine->RegisterObjectMethod("File", "bool get_eof() const", asMETHODPR(File, IsEof, () const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("File", "bool IsInstanceOf(StringHash) const", asMETHODPR(File, IsInstanceOf, (StringHash) const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(const TypeInfo* typeInfo) const | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // template<typename T> bool Object::IsInstanceOf() const | File: ../Core/Object.h // Not registered because template // bool File::IsOpen() const | File: ../IO/File.h engine->RegisterObjectMethod("File", "bool IsOpen() const", asMETHODPR(File, IsOpen, () const, bool), asCALL_THISCALL); engine->RegisterObjectMethod("File", "bool get_open() const", asMETHODPR(File, IsOpen, () const, bool), asCALL_THISCALL); // bool File::IsPackaged() const | File: ../IO/File.h engine->RegisterObjectMethod("File", "bool IsPackaged() const", asMETHODPR(File, IsPackaged, () const, bool), asCALL_THISCALL); engine->RegisterObjectMethod("File", "bool get_packaged() const", asMETHODPR(File, IsPackaged, () const, bool), asCALL_THISCALL); // virtual void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void OnEvent(Object@+, StringHash, VariantMap&)", asMETHODPR(File, OnEvent, (Object*, StringHash, VariantMap&), void), asCALL_THISCALL); // bool File::Open(const String& fileName, FileMode mode=FILE_READ) | File: ../IO/File.h engine->RegisterObjectMethod("File", "bool Open(const String&in, FileMode = FILE_READ)", asMETHODPR(File, Open, (const String&, FileMode), bool), asCALL_THISCALL); // bool File::Open(PackageFile* package, const String& fileName) | File: ../IO/File.h engine->RegisterObjectMethod("File", "bool Open(PackageFile@+, const String&in)", asMETHODPR(File, Open, (PackageFile*, const String&), bool), asCALL_THISCALL); // unsigned File::Read(void* dest, unsigned size) override | File: ../IO/File.h // Error: type "void*" can not automatically bind // bool Deserializer::ReadBool() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "bool ReadBool()", asMETHODPR(File, ReadBool, (), bool), asCALL_THISCALL); // BoundingBox Deserializer::ReadBoundingBox() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "BoundingBox ReadBoundingBox()", asMETHODPR(File, ReadBoundingBox, (), BoundingBox), asCALL_THISCALL); // PODVector<unsigned char> Deserializer::ReadBuffer() | File: ../IO/Deserializer.h // Error: type "PODVector<unsigned char>" can not automatically bind // signed char Deserializer::ReadByte() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "int8 ReadByte()", asMETHODPR(File, ReadByte, (), signed char), asCALL_THISCALL); // Color Deserializer::ReadColor() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Color ReadColor()", asMETHODPR(File, ReadColor, (), Color), asCALL_THISCALL); // double Deserializer::ReadDouble() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "double ReadDouble()", asMETHODPR(File, ReadDouble, (), double), asCALL_THISCALL); // String Deserializer::ReadFileID() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "String ReadFileID()", asMETHODPR(File, ReadFileID, (), String), asCALL_THISCALL); // float Deserializer::ReadFloat() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "float ReadFloat()", asMETHODPR(File, ReadFloat, (), float), asCALL_THISCALL); // int Deserializer::ReadInt() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "int ReadInt()", asMETHODPR(File, ReadInt, (), int), asCALL_THISCALL); // long long Deserializer::ReadInt64() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "int64 ReadInt64()", asMETHODPR(File, ReadInt64, (), long long), asCALL_THISCALL); // IntRect Deserializer::ReadIntRect() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "IntRect ReadIntRect()", asMETHODPR(File, ReadIntRect, (), IntRect), asCALL_THISCALL); // IntVector2 Deserializer::ReadIntVector2() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "IntVector2 ReadIntVector2()", asMETHODPR(File, ReadIntVector2, (), IntVector2), asCALL_THISCALL); // IntVector3 Deserializer::ReadIntVector3() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "IntVector3 ReadIntVector3()", asMETHODPR(File, ReadIntVector3, (), IntVector3), asCALL_THISCALL); // String Deserializer::ReadLine() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "String ReadLine()", asMETHODPR(File, ReadLine, (), String), asCALL_THISCALL); // Matrix3 Deserializer::ReadMatrix3() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Matrix3 ReadMatrix3()", asMETHODPR(File, ReadMatrix3, (), Matrix3), asCALL_THISCALL); // Matrix3x4 Deserializer::ReadMatrix3x4() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Matrix3x4 ReadMatrix3x4()", asMETHODPR(File, ReadMatrix3x4, (), Matrix3x4), asCALL_THISCALL); // Matrix4 Deserializer::ReadMatrix4() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Matrix4 ReadMatrix4()", asMETHODPR(File, ReadMatrix4, (), Matrix4), asCALL_THISCALL); // unsigned Deserializer::ReadNetID() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint ReadNetID()", asMETHODPR(File, ReadNetID, (), unsigned), asCALL_THISCALL); // Quaternion Deserializer::ReadPackedQuaternion() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Quaternion ReadPackedQuaternion()", asMETHODPR(File, ReadPackedQuaternion, (), Quaternion), asCALL_THISCALL); // Vector3 Deserializer::ReadPackedVector3(float maxAbsCoord) | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Vector3 ReadPackedVector3(float)", asMETHODPR(File, ReadPackedVector3, (float), Vector3), asCALL_THISCALL); // Quaternion Deserializer::ReadQuaternion() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Quaternion ReadQuaternion()", asMETHODPR(File, ReadQuaternion, (), Quaternion), asCALL_THISCALL); // Rect Deserializer::ReadRect() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Rect ReadRect()", asMETHODPR(File, ReadRect, (), Rect), asCALL_THISCALL); // ResourceRef Deserializer::ReadResourceRef() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "ResourceRef ReadResourceRef()", asMETHODPR(File, ReadResourceRef, (), ResourceRef), asCALL_THISCALL); // ResourceRefList Deserializer::ReadResourceRefList() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "ResourceRefList ReadResourceRefList()", asMETHODPR(File, ReadResourceRefList, (), ResourceRefList), asCALL_THISCALL); // short Deserializer::ReadShort() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "int16 ReadShort()", asMETHODPR(File, ReadShort, (), short), asCALL_THISCALL); // String Deserializer::ReadString() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "String ReadString()", asMETHODPR(File, ReadString, (), String), asCALL_THISCALL); // StringHash Deserializer::ReadStringHash() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "StringHash ReadStringHash()", asMETHODPR(File, ReadStringHash, (), StringHash), asCALL_THISCALL); // StringVector Deserializer::ReadStringVector() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Array<String>@ ReadStringVector()", asFUNCTION(File_ReadStringVector_void), asCALL_CDECL_OBJFIRST); // unsigned char Deserializer::ReadUByte() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint8 ReadUByte()", asMETHODPR(File, ReadUByte, (), unsigned char), asCALL_THISCALL); // unsigned Deserializer::ReadUInt() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint ReadUInt()", asMETHODPR(File, ReadUInt, (), unsigned), asCALL_THISCALL); // unsigned long long Deserializer::ReadUInt64() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint64 ReadUInt64()", asMETHODPR(File, ReadUInt64, (), unsigned long long), asCALL_THISCALL); // unsigned short Deserializer::ReadUShort() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint16 ReadUShort()", asMETHODPR(File, ReadUShort, (), unsigned short), asCALL_THISCALL); // Variant Deserializer::ReadVariant() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Variant ReadVariant()", asMETHODPR(File, ReadVariant, (), Variant), asCALL_THISCALL); // Variant Deserializer::ReadVariant(VariantType type) | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Variant ReadVariant(VariantType)", asMETHODPR(File, ReadVariant, (VariantType), Variant), asCALL_THISCALL); // VariantMap Deserializer::ReadVariantMap() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "VariantMap ReadVariantMap()", asMETHODPR(File, ReadVariantMap, (), VariantMap), asCALL_THISCALL); // VariantVector Deserializer::ReadVariantVector() | File: ../IO/Deserializer.h // Error: type "VariantVector" can not automatically bind // Vector2 Deserializer::ReadVector2() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Vector2 ReadVector2()", asMETHODPR(File, ReadVector2, (), Vector2), asCALL_THISCALL); // Vector3 Deserializer::ReadVector3() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Vector3 ReadVector3()", asMETHODPR(File, ReadVector3, (), Vector3), asCALL_THISCALL); // Vector4 Deserializer::ReadVector4() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "Vector4 ReadVector4()", asMETHODPR(File, ReadVector4, (), Vector4), asCALL_THISCALL); // unsigned Deserializer::ReadVLE() | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint ReadVLE()", asMETHODPR(File, ReadVLE, (), unsigned), asCALL_THISCALL); // RefCount* RefCounted::RefCountPtr() | File: ../Container/RefCounted.h // Error: type "RefCount*" can not automatically bind // int RefCounted::Refs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("File", "int Refs() const", asMETHODPR(File, Refs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("File", "int get_refs() const", asMETHODPR(File, Refs, () const, int), asCALL_THISCALL); // void RefCounted::ReleaseRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("File", asBEHAVE_RELEASE, "void f()", asMETHODPR(File, ReleaseRef, (), void), asCALL_THISCALL); // unsigned File::Seek(unsigned position) override | File: ../IO/File.h engine->RegisterObjectMethod("File", "uint Seek(uint)", asMETHODPR(File, Seek, (unsigned), unsigned), asCALL_THISCALL); // unsigned Deserializer::SeekRelative(int delta) | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint SeekRelative(int)", asMETHODPR(File, SeekRelative, (int), unsigned), asCALL_THISCALL); // void Object::SendEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void SendEvent(StringHash)", asMETHODPR(File, SendEvent, (StringHash), void), asCALL_THISCALL); // void Object::SendEvent(StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void SendEvent(StringHash, VariantMap&)", asMETHODPR(File, SendEvent, (StringHash, VariantMap&), void), asCALL_THISCALL); // template<typename... Args> void Object::SendEvent(StringHash eventType, Args... args) | File: ../Core/Object.h // Not registered because template // void Object::SetBlockEvents(bool block) | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void SetBlockEvents(bool)", asMETHODPR(File, SetBlockEvents, (bool), void), asCALL_THISCALL); // void Object::SetGlobalVar(StringHash key, const Variant& value) | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void SetGlobalVar(StringHash, const Variant&in)", asMETHODPR(File, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); engine->RegisterObjectMethod("File", "void set_globalVar(StringHash, const Variant&in)", asMETHODPR(File, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); // virtual void AbstractFile::SetName(const String& name) | File: ../IO/AbstractFile.h engine->RegisterObjectMethod("File", "void SetName(const String&in)", asMETHODPR(File, SetName, (const String&), void), asCALL_THISCALL); engine->RegisterObjectMethod("File", "void set_name(const String&in)", asMETHODPR(File, SetName, (const String&), void), asCALL_THISCALL); // void Object::SubscribeToEvent(StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // unsigned Deserializer::Tell() const | File: ../IO/Deserializer.h engine->RegisterObjectMethod("File", "uint Tell() const", asMETHODPR(File, Tell, () const, unsigned), asCALL_THISCALL); // void Object::UnsubscribeFromAllEvents() | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void UnsubscribeFromAllEvents()", asMETHODPR(File, UnsubscribeFromAllEvents, (), void), asCALL_THISCALL); // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void UnsubscribeFromAllEventsExcept(Array<StringHash>@+, bool)", asFUNCTION(File_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool), asCALL_CDECL_OBJFIRST); // void Object::UnsubscribeFromEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void UnsubscribeFromEvent(StringHash)", asMETHODPR(File, UnsubscribeFromEvent, (StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvent(Object* sender, StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void UnsubscribeFromEvent(Object@+, StringHash)", asMETHODPR(File, UnsubscribeFromEvent, (Object*, StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvents(Object* sender) | File: ../Core/Object.h engine->RegisterObjectMethod("File", "void UnsubscribeFromEvents(Object@+)", asMETHODPR(File, UnsubscribeFromEvents, (Object*), void), asCALL_THISCALL); // int RefCounted::WeakRefs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("File", "int WeakRefs() const", asMETHODPR(File, WeakRefs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("File", "int get_weakRefs() const", asMETHODPR(File, WeakRefs, () const, int), asCALL_THISCALL); // unsigned File::Write(const void* data, unsigned size) override | File: ../IO/File.h // Error: type "void*" can not automatically bind // bool Serializer::WriteBool(bool value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteBool(bool)", asMETHODPR(File, WriteBool, (bool), bool), asCALL_THISCALL); // bool Serializer::WriteBoundingBox(const BoundingBox& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteBoundingBox(const BoundingBox&in)", asMETHODPR(File, WriteBoundingBox, (const BoundingBox&), bool), asCALL_THISCALL); // bool Serializer::WriteBuffer(const PODVector<unsigned char>& value) | File: ../IO/Serializer.h // Error: type "const PODVector<unsigned char>&" can not automatically bind // bool Serializer::WriteByte(signed char value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteByte(int8)", asMETHODPR(File, WriteByte, (signed char), bool), asCALL_THISCALL); // bool Serializer::WriteColor(const Color& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteColor(const Color&in)", asMETHODPR(File, WriteColor, (const Color&), bool), asCALL_THISCALL); // bool Serializer::WriteDouble(double value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteDouble(double)", asMETHODPR(File, WriteDouble, (double), bool), asCALL_THISCALL); // bool Serializer::WriteFileID(const String& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteFileID(const String&in)", asMETHODPR(File, WriteFileID, (const String&), bool), asCALL_THISCALL); // bool Serializer::WriteFloat(float value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteFloat(float)", asMETHODPR(File, WriteFloat, (float), bool), asCALL_THISCALL); // bool Serializer::WriteInt(int value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteInt(int)", asMETHODPR(File, WriteInt, (int), bool), asCALL_THISCALL); // bool Serializer::WriteInt64(long long value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteInt64(int64)", asMETHODPR(File, WriteInt64, (long long), bool), asCALL_THISCALL); // bool Serializer::WriteIntRect(const IntRect& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteIntRect(const IntRect&in)", asMETHODPR(File, WriteIntRect, (const IntRect&), bool), asCALL_THISCALL); // bool Serializer::WriteIntVector2(const IntVector2& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteIntVector2(const IntVector2&in)", asMETHODPR(File, WriteIntVector2, (const IntVector2&), bool), asCALL_THISCALL); // bool Serializer::WriteIntVector3(const IntVector3& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteIntVector3(const IntVector3&in)", asMETHODPR(File, WriteIntVector3, (const IntVector3&), bool), asCALL_THISCALL); // bool Serializer::WriteLine(const String& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteLine(const String&in)", asMETHODPR(File, WriteLine, (const String&), bool), asCALL_THISCALL); // bool Serializer::WriteMatrix3(const Matrix3& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteMatrix3(const Matrix3&in)", asMETHODPR(File, WriteMatrix3, (const Matrix3&), bool), asCALL_THISCALL); // bool Serializer::WriteMatrix3x4(const Matrix3x4& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteMatrix3x4(const Matrix3x4&in)", asMETHODPR(File, WriteMatrix3x4, (const Matrix3x4&), bool), asCALL_THISCALL); // bool Serializer::WriteMatrix4(const Matrix4& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteMatrix4(const Matrix4&in)", asMETHODPR(File, WriteMatrix4, (const Matrix4&), bool), asCALL_THISCALL); // bool Serializer::WriteNetID(unsigned value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteNetID(uint)", asMETHODPR(File, WriteNetID, (unsigned), bool), asCALL_THISCALL); // bool Serializer::WritePackedQuaternion(const Quaternion& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WritePackedQuaternion(const Quaternion&in)", asMETHODPR(File, WritePackedQuaternion, (const Quaternion&), bool), asCALL_THISCALL); // bool Serializer::WritePackedVector3(const Vector3& value, float maxAbsCoord) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WritePackedVector3(const Vector3&in, float)", asMETHODPR(File, WritePackedVector3, (const Vector3&, float), bool), asCALL_THISCALL); // bool Serializer::WriteQuaternion(const Quaternion& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteQuaternion(const Quaternion&in)", asMETHODPR(File, WriteQuaternion, (const Quaternion&), bool), asCALL_THISCALL); // bool Serializer::WriteRect(const Rect& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteRect(const Rect&in)", asMETHODPR(File, WriteRect, (const Rect&), bool), asCALL_THISCALL); // bool Serializer::WriteResourceRef(const ResourceRef& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteResourceRef(const ResourceRef&in)", asMETHODPR(File, WriteResourceRef, (const ResourceRef&), bool), asCALL_THISCALL); // bool Serializer::WriteResourceRefList(const ResourceRefList& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteResourceRefList(const ResourceRefList&in)", asMETHODPR(File, WriteResourceRefList, (const ResourceRefList&), bool), asCALL_THISCALL); // bool Serializer::WriteShort(short value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteShort(int16)", asMETHODPR(File, WriteShort, (short), bool), asCALL_THISCALL); // bool Serializer::WriteString(const String& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteString(const String&in)", asMETHODPR(File, WriteString, (const String&), bool), asCALL_THISCALL); // bool Serializer::WriteStringHash(const StringHash& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteStringHash(const StringHash&in)", asMETHODPR(File, WriteStringHash, (const StringHash&), bool), asCALL_THISCALL); // bool Serializer::WriteStringVector(const StringVector& value) | File: ../IO/Serializer.h // Error: type "const StringVector&" can not automatically bind // bool Serializer::WriteUByte(unsigned char value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteUByte(uint8)", asMETHODPR(File, WriteUByte, (unsigned char), bool), asCALL_THISCALL); // bool Serializer::WriteUInt(unsigned value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteUInt(uint)", asMETHODPR(File, WriteUInt, (unsigned), bool), asCALL_THISCALL); // bool Serializer::WriteUInt64(unsigned long long value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteUInt64(uint64)", asMETHODPR(File, WriteUInt64, (unsigned long long), bool), asCALL_THISCALL); // bool Serializer::WriteUShort(unsigned short value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteUShort(uint16)", asMETHODPR(File, WriteUShort, (unsigned short), bool), asCALL_THISCALL); // bool Serializer::WriteVariant(const Variant& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteVariant(const Variant&in)", asMETHODPR(File, WriteVariant, (const Variant&), bool), asCALL_THISCALL); // bool Serializer::WriteVariantData(const Variant& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteVariantData(const Variant&in)", asMETHODPR(File, WriteVariantData, (const Variant&), bool), asCALL_THISCALL); // bool Serializer::WriteVariantMap(const VariantMap& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteVariantMap(const VariantMap&in)", asMETHODPR(File, WriteVariantMap, (const VariantMap&), bool), asCALL_THISCALL); // bool Serializer::WriteVariantVector(const VariantVector& value) | File: ../IO/Serializer.h // Error: type "const VariantVector&" can not automatically bind // bool Serializer::WriteVector2(const Vector2& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteVector2(const Vector2&in)", asMETHODPR(File, WriteVector2, (const Vector2&), bool), asCALL_THISCALL); // bool Serializer::WriteVector3(const Vector3& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteVector3(const Vector3&in)", asMETHODPR(File, WriteVector3, (const Vector3&), bool), asCALL_THISCALL); // bool Serializer::WriteVector4(const Vector4& value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteVector4(const Vector4&in)", asMETHODPR(File, WriteVector4, (const Vector4&), bool), asCALL_THISCALL); // bool Serializer::WriteVLE(unsigned value) | File: ../IO/Serializer.h engine->RegisterObjectMethod("File", "bool WriteVLE(uint)", asMETHODPR(File, WriteVLE, (unsigned), bool), asCALL_THISCALL); #ifdef REGISTER_MANUAL_PART_Object REGISTER_MANUAL_PART_Object(File, "File") #endif #ifdef REGISTER_MANUAL_PART_RefCounted REGISTER_MANUAL_PART_RefCounted(File, "File") #endif #ifdef REGISTER_MANUAL_PART_AbstractFile REGISTER_MANUAL_PART_AbstractFile(File, "File") #endif #ifdef REGISTER_MANUAL_PART_Deserializer REGISTER_MANUAL_PART_Deserializer(File, "File") #endif #ifdef REGISTER_MANUAL_PART_Serializer REGISTER_MANUAL_PART_Serializer(File, "File") #endif #ifdef REGISTER_MANUAL_PART_File REGISTER_MANUAL_PART_File(File, "File") #endif RegisterSubclass<Object, File>(engine, "Object", "File"); RegisterSubclass<RefCounted, File>(engine, "RefCounted", "File"); RegisterSubclass<AbstractFile, File>(engine, "AbstractFile", "File"); RegisterSubclass<Deserializer, File>(engine, "Deserializer", "File"); RegisterSubclass<Serializer, File>(engine, "Serializer", "File"); // void RefCounted::AddRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FileSelector", asBEHAVE_ADDREF, "void f()", asMETHODPR(FileSelector, AddRef, (), void), asCALL_THISCALL); // template<typename T> T* Object::Cast() | File: ../Core/Object.h // Not registered because template // template<typename T> const T* Object::Cast() const | File: ../Core/Object.h // Not registered because template // explicit FileSelector::FileSelector(Context* context) | File: ../UI/FileSelector.h engine->RegisterObjectBehaviour("FileSelector", asBEHAVE_FACTORY, "FileSelector@+ f()", asFUNCTION(FileSelector_FileSelector_Context), asCALL_CDECL); // bool Object::GetBlockEvents() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "bool GetBlockEvents() const", asMETHODPR(FileSelector, GetBlockEvents, () const, bool), asCALL_THISCALL); // Button* FileSelector::GetCancelButton() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "Button@+ GetCancelButton() const", asMETHODPR(FileSelector, GetCancelButton, () const, Button*), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "Button@+ get_cancelButton() const", asMETHODPR(FileSelector, GetCancelButton, () const, Button*), asCALL_THISCALL); // const String& Object::GetCategory() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "const String& GetCategory() const", asMETHODPR(FileSelector, GetCategory, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "const String& get_category() const", asMETHODPR(FileSelector, GetCategory, () const, const String&), asCALL_THISCALL); // Button* FileSelector::GetCloseButton() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "Button@+ GetCloseButton() const", asMETHODPR(FileSelector, GetCloseButton, () const, Button*), asCALL_THISCALL); // Context* Object::GetContext() const | File: ../Core/Object.h // Error: type "Context*" can not be returned // XMLFile* FileSelector::GetDefaultStyle() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "XMLFile@+ GetDefaultStyle() const", asMETHODPR(FileSelector, GetDefaultStyle, () const, XMLFile*), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "XMLFile@+ get_defaultStyle() const", asMETHODPR(FileSelector, GetDefaultStyle, () const, XMLFile*), asCALL_THISCALL); // bool FileSelector::GetDirectoryMode() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "bool GetDirectoryMode() const", asMETHODPR(FileSelector, GetDirectoryMode, () const, bool), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "bool get_directoryMode() const", asMETHODPR(FileSelector, GetDirectoryMode, () const, bool), asCALL_THISCALL); // VariantMap& Object::GetEventDataMap() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "VariantMap& GetEventDataMap() const", asMETHODPR(FileSelector, GetEventDataMap, () const, VariantMap&), asCALL_THISCALL); // EventHandler* Object::GetEventHandler() const | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // Object* Object::GetEventSender() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "Object@+ GetEventSender() const", asMETHODPR(FileSelector, GetEventSender, () const, Object*), asCALL_THISCALL); // ListView* FileSelector::GetFileList() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "ListView@+ GetFileList() const", asMETHODPR(FileSelector, GetFileList, () const, ListView*), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "ListView@+ get_fileList() const", asMETHODPR(FileSelector, GetFileList, () const, ListView*), asCALL_THISCALL); // const String& FileSelector::GetFileName() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "const String& GetFileName() const", asMETHODPR(FileSelector, GetFileName, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "const String& get_fileName() const", asMETHODPR(FileSelector, GetFileName, () const, const String&), asCALL_THISCALL); // LineEdit* FileSelector::GetFileNameEdit() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "LineEdit@+ GetFileNameEdit() const", asMETHODPR(FileSelector, GetFileNameEdit, () const, LineEdit*), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "LineEdit@+ get_fileNameEdit() const", asMETHODPR(FileSelector, GetFileNameEdit, () const, LineEdit*), asCALL_THISCALL); // const String& FileSelector::GetFilter() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "const String& GetFilter() const", asMETHODPR(FileSelector, GetFilter, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "const String& get_filter() const", asMETHODPR(FileSelector, GetFilter, () const, const String&), asCALL_THISCALL); // unsigned FileSelector::GetFilterIndex() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "uint GetFilterIndex() const", asMETHODPR(FileSelector, GetFilterIndex, () const, unsigned), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "uint get_filterIndex() const", asMETHODPR(FileSelector, GetFilterIndex, () const, unsigned), asCALL_THISCALL); // DropDownList* FileSelector::GetFilterList() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "DropDownList@+ GetFilterList() const", asMETHODPR(FileSelector, GetFilterList, () const, DropDownList*), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "DropDownList@+ get_filterList() const", asMETHODPR(FileSelector, GetFilterList, () const, DropDownList*), asCALL_THISCALL); // const Variant& Object::GetGlobalVar(StringHash key) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "const Variant& GetGlobalVar(StringHash) const", asMETHODPR(FileSelector, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "const Variant& get_globalVar(StringHash) const", asMETHODPR(FileSelector, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); // const VariantMap& Object::GetGlobalVars() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "const VariantMap& GetGlobalVars() const", asMETHODPR(FileSelector, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "const VariantMap& get_globalVars() const", asMETHODPR(FileSelector, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); // Button* FileSelector::GetOKButton() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "Button@+ GetOKButton() const", asMETHODPR(FileSelector, GetOKButton, () const, Button*), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "Button@+ get_okButton() const", asMETHODPR(FileSelector, GetOKButton, () const, Button*), asCALL_THISCALL); // const String& FileSelector::GetPath() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "const String& GetPath() const", asMETHODPR(FileSelector, GetPath, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "const String& get_path() const", asMETHODPR(FileSelector, GetPath, () const, const String&), asCALL_THISCALL); // LineEdit* FileSelector::GetPathEdit() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "LineEdit@+ GetPathEdit() const", asMETHODPR(FileSelector, GetPathEdit, () const, LineEdit*), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "LineEdit@+ get_pathEdit() const", asMETHODPR(FileSelector, GetPathEdit, () const, LineEdit*), asCALL_THISCALL); // Object* Object::GetSubsystem(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "Object@+ GetSubsystem(StringHash) const", asMETHODPR(FileSelector, GetSubsystem, (StringHash) const, Object*), asCALL_THISCALL); // template<class T> T* Object::GetSubsystem() const | File: ../Core/Object.h // Not registered because template // const String& FileSelector::GetTitle() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "const String& GetTitle() const", asMETHODPR(FileSelector, GetTitle, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "const String& get_title() const", asMETHODPR(FileSelector, GetTitle, () const, const String&), asCALL_THISCALL); // Text* FileSelector::GetTitleText() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "Text@+ GetTitleText() const", asMETHODPR(FileSelector, GetTitleText, () const, Text*), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "Text@+ get_titleText() const", asMETHODPR(FileSelector, GetTitleText, () const, Text*), asCALL_THISCALL); // virtual StringHash Object::GetType() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "StringHash GetType() const", asMETHODPR(FileSelector, GetType, () const, StringHash), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "StringHash get_type() const", asMETHODPR(FileSelector, GetType, () const, StringHash), asCALL_THISCALL); // virtual const TypeInfo* Object::GetTypeInfo() const =0 | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // static const TypeInfo* Object::GetTypeInfoStatic() | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // virtual const String& Object::GetTypeName() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "const String& GetTypeName() const", asMETHODPR(FileSelector, GetTypeName, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "const String& get_typeName() const", asMETHODPR(FileSelector, GetTypeName, () const, const String&), asCALL_THISCALL); // Window* FileSelector::GetWindow() const | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "Window@+ GetWindow() const", asMETHODPR(FileSelector, GetWindow, () const, Window*), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "Window@+ get_window() const", asMETHODPR(FileSelector, GetWindow, () const, Window*), asCALL_THISCALL); // bool Object::HasEventHandlers() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "bool HasEventHandlers() const", asMETHODPR(FileSelector, HasEventHandlers, () const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "bool HasSubscribedToEvent(StringHash) const", asMETHODPR(FileSelector, HasSubscribedToEvent, (StringHash) const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(Object* sender, StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "bool HasSubscribedToEvent(Object@+, StringHash) const", asMETHODPR(FileSelector, HasSubscribedToEvent, (Object*, StringHash) const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "bool IsInstanceOf(StringHash) const", asMETHODPR(FileSelector, IsInstanceOf, (StringHash) const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(const TypeInfo* typeInfo) const | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // template<typename T> bool Object::IsInstanceOf() const | File: ../Core/Object.h // Not registered because template // virtual void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void OnEvent(Object@+, StringHash, VariantMap&)", asMETHODPR(FileSelector, OnEvent, (Object*, StringHash, VariantMap&), void), asCALL_THISCALL); // RefCount* RefCounted::RefCountPtr() | File: ../Container/RefCounted.h // Error: type "RefCount*" can not automatically bind // int RefCounted::Refs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FileSelector", "int Refs() const", asMETHODPR(FileSelector, Refs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "int get_refs() const", asMETHODPR(FileSelector, Refs, () const, int), asCALL_THISCALL); // static void FileSelector::RegisterObject(Context* context) | File: ../UI/FileSelector.h // Context can be used as firs parameter of constructors only // void RefCounted::ReleaseRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FileSelector", asBEHAVE_RELEASE, "void f()", asMETHODPR(FileSelector, ReleaseRef, (), void), asCALL_THISCALL); // void Object::SendEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void SendEvent(StringHash)", asMETHODPR(FileSelector, SendEvent, (StringHash), void), asCALL_THISCALL); // void Object::SendEvent(StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void SendEvent(StringHash, VariantMap&)", asMETHODPR(FileSelector, SendEvent, (StringHash, VariantMap&), void), asCALL_THISCALL); // template<typename... Args> void Object::SendEvent(StringHash eventType, Args... args) | File: ../Core/Object.h // Not registered because template // void Object::SetBlockEvents(bool block) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void SetBlockEvents(bool)", asMETHODPR(FileSelector, SetBlockEvents, (bool), void), asCALL_THISCALL); // void FileSelector::SetButtonTexts(const String& okText, const String& cancelText) | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "void SetButtonTexts(const String&in, const String&in)", asMETHODPR(FileSelector, SetButtonTexts, (const String&, const String&), void), asCALL_THISCALL); // void FileSelector::SetDefaultStyle(XMLFile* style) | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "void SetDefaultStyle(XMLFile@+)", asMETHODPR(FileSelector, SetDefaultStyle, (XMLFile*), void), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "void set_defaultStyle(XMLFile@+)", asMETHODPR(FileSelector, SetDefaultStyle, (XMLFile*), void), asCALL_THISCALL); // void FileSelector::SetDirectoryMode(bool enable) | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "void SetDirectoryMode(bool)", asMETHODPR(FileSelector, SetDirectoryMode, (bool), void), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "void set_directoryMode(bool)", asMETHODPR(FileSelector, SetDirectoryMode, (bool), void), asCALL_THISCALL); // void FileSelector::SetFileName(const String& fileName) | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "void SetFileName(const String&in)", asMETHODPR(FileSelector, SetFileName, (const String&), void), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "void set_fileName(const String&in)", asMETHODPR(FileSelector, SetFileName, (const String&), void), asCALL_THISCALL); // void FileSelector::SetFilters(const Vector<String>& filters, unsigned defaultIndex) | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "void SetFilters(Array<String>@+, uint)", asFUNCTION(FileSelector_SetFilters_VectorString_unsigned), asCALL_CDECL_OBJFIRST); // void Object::SetGlobalVar(StringHash key, const Variant& value) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void SetGlobalVar(StringHash, const Variant&in)", asMETHODPR(FileSelector, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "void set_globalVar(StringHash, const Variant&in)", asMETHODPR(FileSelector, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); // void FileSelector::SetPath(const String& path) | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "void SetPath(const String&in)", asMETHODPR(FileSelector, SetPath, (const String&), void), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "void set_path(const String&in)", asMETHODPR(FileSelector, SetPath, (const String&), void), asCALL_THISCALL); // void FileSelector::SetTitle(const String& text) | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "void SetTitle(const String&in)", asMETHODPR(FileSelector, SetTitle, (const String&), void), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "void set_title(const String&in)", asMETHODPR(FileSelector, SetTitle, (const String&), void), asCALL_THISCALL); // void Object::SubscribeToEvent(StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // void Object::UnsubscribeFromAllEvents() | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void UnsubscribeFromAllEvents()", asMETHODPR(FileSelector, UnsubscribeFromAllEvents, (), void), asCALL_THISCALL); // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void UnsubscribeFromAllEventsExcept(Array<StringHash>@+, bool)", asFUNCTION(FileSelector_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool), asCALL_CDECL_OBJFIRST); // void Object::UnsubscribeFromEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void UnsubscribeFromEvent(StringHash)", asMETHODPR(FileSelector, UnsubscribeFromEvent, (StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvent(Object* sender, StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void UnsubscribeFromEvent(Object@+, StringHash)", asMETHODPR(FileSelector, UnsubscribeFromEvent, (Object*, StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvents(Object* sender) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSelector", "void UnsubscribeFromEvents(Object@+)", asMETHODPR(FileSelector, UnsubscribeFromEvents, (Object*), void), asCALL_THISCALL); // void FileSelector::UpdateElements() | File: ../UI/FileSelector.h engine->RegisterObjectMethod("FileSelector", "void UpdateElements()", asMETHODPR(FileSelector, UpdateElements, (), void), asCALL_THISCALL); // int RefCounted::WeakRefs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FileSelector", "int WeakRefs() const", asMETHODPR(FileSelector, WeakRefs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FileSelector", "int get_weakRefs() const", asMETHODPR(FileSelector, WeakRefs, () const, int), asCALL_THISCALL); #ifdef REGISTER_MANUAL_PART_Object REGISTER_MANUAL_PART_Object(FileSelector, "FileSelector") #endif #ifdef REGISTER_MANUAL_PART_RefCounted REGISTER_MANUAL_PART_RefCounted(FileSelector, "FileSelector") #endif #ifdef REGISTER_MANUAL_PART_FileSelector REGISTER_MANUAL_PART_FileSelector(FileSelector, "FileSelector") #endif RegisterSubclass<Object, FileSelector>(engine, "Object", "FileSelector"); RegisterSubclass<RefCounted, FileSelector>(engine, "RefCounted", "FileSelector"); // void RefCounted::AddRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FileSystem", asBEHAVE_ADDREF, "void f()", asMETHODPR(FileSystem, AddRef, (), void), asCALL_THISCALL); // template<typename T> T* Object::Cast() | File: ../Core/Object.h // Not registered because template // template<typename T> const T* Object::Cast() const | File: ../Core/Object.h // Not registered because template // bool FileSystem::CheckAccess(const String& pathName) const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool CheckAccess(const String&in) const", asMETHODPR(FileSystem, CheckAccess, (const String&) const, bool), asCALL_THISCALL); // bool FileSystem::Copy(const String& srcFileName, const String& destFileName) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool Copy(const String&in, const String&in)", asMETHODPR(FileSystem, Copy, (const String&, const String&), bool), asCALL_THISCALL); // bool FileSystem::CreateDir(const String& pathName) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool CreateDir(const String&in)", asMETHODPR(FileSystem, CreateDir, (const String&), bool), asCALL_THISCALL); // bool FileSystem::Delete(const String& fileName) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool Delete(const String&in)", asMETHODPR(FileSystem, Delete, (const String&), bool), asCALL_THISCALL); // bool FileSystem::DirExists(const String& pathName) const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool DirExists(const String&in) const", asMETHODPR(FileSystem, DirExists, (const String&) const, bool), asCALL_THISCALL); // bool FileSystem::FileExists(const String& fileName) const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool FileExists(const String&in) const", asMETHODPR(FileSystem, FileExists, (const String&) const, bool), asCALL_THISCALL); // explicit FileSystem::FileSystem(Context* context) | File: ../IO/FileSystem.h engine->RegisterObjectBehaviour("FileSystem", asBEHAVE_FACTORY, "FileSystem@+ f()", asFUNCTION(FileSystem_FileSystem_Context), asCALL_CDECL); // String FileSystem::GetAppPreferencesDir(const String& org, const String& app) const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "String GetAppPreferencesDir(const String&in, const String&in) const", asMETHODPR(FileSystem, GetAppPreferencesDir, (const String&, const String&) const, String), asCALL_THISCALL); // bool Object::GetBlockEvents() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "bool GetBlockEvents() const", asMETHODPR(FileSystem, GetBlockEvents, () const, bool), asCALL_THISCALL); // const String& Object::GetCategory() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "const String& GetCategory() const", asMETHODPR(FileSystem, GetCategory, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "const String& get_category() const", asMETHODPR(FileSystem, GetCategory, () const, const String&), asCALL_THISCALL); // Context* Object::GetContext() const | File: ../Core/Object.h // Error: type "Context*" can not be returned // String FileSystem::GetCurrentDir() const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "String GetCurrentDir() const", asMETHODPR(FileSystem, GetCurrentDir, () const, String), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "String get_currentDir() const", asMETHODPR(FileSystem, GetCurrentDir, () const, String), asCALL_THISCALL); // VariantMap& Object::GetEventDataMap() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "VariantMap& GetEventDataMap() const", asMETHODPR(FileSystem, GetEventDataMap, () const, VariantMap&), asCALL_THISCALL); // EventHandler* Object::GetEventHandler() const | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // Object* Object::GetEventSender() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "Object@+ GetEventSender() const", asMETHODPR(FileSystem, GetEventSender, () const, Object*), asCALL_THISCALL); // bool FileSystem::GetExecuteConsoleCommands() const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool GetExecuteConsoleCommands() const", asMETHODPR(FileSystem, GetExecuteConsoleCommands, () const, bool), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "bool get_executeConsoleCommands() const", asMETHODPR(FileSystem, GetExecuteConsoleCommands, () const, bool), asCALL_THISCALL); // const Variant& Object::GetGlobalVar(StringHash key) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "const Variant& GetGlobalVar(StringHash) const", asMETHODPR(FileSystem, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "const Variant& get_globalVar(StringHash) const", asMETHODPR(FileSystem, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); // const VariantMap& Object::GetGlobalVars() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "const VariantMap& GetGlobalVars() const", asMETHODPR(FileSystem, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "const VariantMap& get_globalVars() const", asMETHODPR(FileSystem, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); // unsigned FileSystem::GetLastModifiedTime(const String& fileName) const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "uint GetLastModifiedTime(const String&in) const", asMETHODPR(FileSystem, GetLastModifiedTime, (const String&) const, unsigned), asCALL_THISCALL); // String FileSystem::GetProgramDir() const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "String GetProgramDir() const", asMETHODPR(FileSystem, GetProgramDir, () const, String), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "String get_programDir() const", asMETHODPR(FileSystem, GetProgramDir, () const, String), asCALL_THISCALL); // Object* Object::GetSubsystem(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "Object@+ GetSubsystem(StringHash) const", asMETHODPR(FileSystem, GetSubsystem, (StringHash) const, Object*), asCALL_THISCALL); // template<class T> T* Object::GetSubsystem() const | File: ../Core/Object.h // Not registered because template // String FileSystem::GetTemporaryDir() const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "String GetTemporaryDir() const", asMETHODPR(FileSystem, GetTemporaryDir, () const, String), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "String get_temporaryDir() const", asMETHODPR(FileSystem, GetTemporaryDir, () const, String), asCALL_THISCALL); // virtual StringHash Object::GetType() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "StringHash GetType() const", asMETHODPR(FileSystem, GetType, () const, StringHash), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "StringHash get_type() const", asMETHODPR(FileSystem, GetType, () const, StringHash), asCALL_THISCALL); // virtual const TypeInfo* Object::GetTypeInfo() const =0 | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // static const TypeInfo* Object::GetTypeInfoStatic() | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // virtual const String& Object::GetTypeName() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "const String& GetTypeName() const", asMETHODPR(FileSystem, GetTypeName, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "const String& get_typeName() const", asMETHODPR(FileSystem, GetTypeName, () const, const String&), asCALL_THISCALL); // String FileSystem::GetUserDocumentsDir() const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "String GetUserDocumentsDir() const", asMETHODPR(FileSystem, GetUserDocumentsDir, () const, String), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "String get_userDocumentsDir() const", asMETHODPR(FileSystem, GetUserDocumentsDir, () const, String), asCALL_THISCALL); // bool Object::HasEventHandlers() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "bool HasEventHandlers() const", asMETHODPR(FileSystem, HasEventHandlers, () const, bool), asCALL_THISCALL); // bool FileSystem::HasRegisteredPaths() const | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool HasRegisteredPaths() const", asMETHODPR(FileSystem, HasRegisteredPaths, () const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "bool HasSubscribedToEvent(StringHash) const", asMETHODPR(FileSystem, HasSubscribedToEvent, (StringHash) const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(Object* sender, StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "bool HasSubscribedToEvent(Object@+, StringHash) const", asMETHODPR(FileSystem, HasSubscribedToEvent, (Object*, StringHash) const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "bool IsInstanceOf(StringHash) const", asMETHODPR(FileSystem, IsInstanceOf, (StringHash) const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(const TypeInfo* typeInfo) const | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // template<typename T> bool Object::IsInstanceOf() const | File: ../Core/Object.h // Not registered because template // virtual void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void OnEvent(Object@+, StringHash, VariantMap&)", asMETHODPR(FileSystem, OnEvent, (Object*, StringHash, VariantMap&), void), asCALL_THISCALL); // RefCount* RefCounted::RefCountPtr() | File: ../Container/RefCounted.h // Error: type "RefCount*" can not automatically bind // int RefCounted::Refs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FileSystem", "int Refs() const", asMETHODPR(FileSystem, Refs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "int get_refs() const", asMETHODPR(FileSystem, Refs, () const, int), asCALL_THISCALL); // void FileSystem::RegisterPath(const String& pathName) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "void RegisterPath(const String&in)", asMETHODPR(FileSystem, RegisterPath, (const String&), void), asCALL_THISCALL); // void RefCounted::ReleaseRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FileSystem", asBEHAVE_RELEASE, "void f()", asMETHODPR(FileSystem, ReleaseRef, (), void), asCALL_THISCALL); // bool FileSystem::Rename(const String& srcFileName, const String& destFileName) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool Rename(const String&in, const String&in)", asMETHODPR(FileSystem, Rename, (const String&, const String&), bool), asCALL_THISCALL); // void FileSystem::ScanDir(Vector<String>& result, const String& pathName, const String& filter, unsigned flags, bool recursive) const | File: ../IO/FileSystem.h // Error: type "Vector<String>&" can not automatically bind // void Object::SendEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void SendEvent(StringHash)", asMETHODPR(FileSystem, SendEvent, (StringHash), void), asCALL_THISCALL); // void Object::SendEvent(StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void SendEvent(StringHash, VariantMap&)", asMETHODPR(FileSystem, SendEvent, (StringHash, VariantMap&), void), asCALL_THISCALL); // template<typename... Args> void Object::SendEvent(StringHash eventType, Args... args) | File: ../Core/Object.h // Not registered because template // void Object::SetBlockEvents(bool block) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void SetBlockEvents(bool)", asMETHODPR(FileSystem, SetBlockEvents, (bool), void), asCALL_THISCALL); // bool FileSystem::SetCurrentDir(const String& pathName) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool SetCurrentDir(const String&in)", asMETHODPR(FileSystem, SetCurrentDir, (const String&), bool), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "bool set_currentDir(const String&in)", asMETHODPR(FileSystem, SetCurrentDir, (const String&), bool), asCALL_THISCALL); // void FileSystem::SetExecuteConsoleCommands(bool enable) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "void SetExecuteConsoleCommands(bool)", asMETHODPR(FileSystem, SetExecuteConsoleCommands, (bool), void), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "void set_executeConsoleCommands(bool)", asMETHODPR(FileSystem, SetExecuteConsoleCommands, (bool), void), asCALL_THISCALL); // void Object::SetGlobalVar(StringHash key, const Variant& value) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void SetGlobalVar(StringHash, const Variant&in)", asMETHODPR(FileSystem, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "void set_globalVar(StringHash, const Variant&in)", asMETHODPR(FileSystem, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); // bool FileSystem::SetLastModifiedTime(const String& fileName, unsigned newTime) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool SetLastModifiedTime(const String&in, uint)", asMETHODPR(FileSystem, SetLastModifiedTime, (const String&, unsigned), bool), asCALL_THISCALL); // void Object::SubscribeToEvent(StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // int FileSystem::SystemCommand(const String& commandLine, bool redirectStdOutToLog=false) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "int SystemCommand(const String&in, bool = false)", asMETHODPR(FileSystem, SystemCommand, (const String&, bool), int), asCALL_THISCALL); // unsigned FileSystem::SystemCommandAsync(const String& commandLine) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "uint SystemCommandAsync(const String&in)", asMETHODPR(FileSystem, SystemCommandAsync, (const String&), unsigned), asCALL_THISCALL); // bool FileSystem::SystemOpen(const String& fileName, const String& mode=String::EMPTY) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "bool SystemOpen(const String&in, const String&in = String::EMPTY)", asMETHODPR(FileSystem, SystemOpen, (const String&, const String&), bool), asCALL_THISCALL); // int FileSystem::SystemRun(const String& fileName, const Vector<String>& arguments) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "int SystemRun(const String&in, Array<String>@+)", asFUNCTION(FileSystem_SystemRun_String_VectorString), asCALL_CDECL_OBJFIRST); // unsigned FileSystem::SystemRunAsync(const String& fileName, const Vector<String>& arguments) | File: ../IO/FileSystem.h engine->RegisterObjectMethod("FileSystem", "uint SystemRunAsync(const String&in, Array<String>@+)", asFUNCTION(FileSystem_SystemRunAsync_String_VectorString), asCALL_CDECL_OBJFIRST); // void Object::UnsubscribeFromAllEvents() | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void UnsubscribeFromAllEvents()", asMETHODPR(FileSystem, UnsubscribeFromAllEvents, (), void), asCALL_THISCALL); // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void UnsubscribeFromAllEventsExcept(Array<StringHash>@+, bool)", asFUNCTION(FileSystem_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool), asCALL_CDECL_OBJFIRST); // void Object::UnsubscribeFromEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void UnsubscribeFromEvent(StringHash)", asMETHODPR(FileSystem, UnsubscribeFromEvent, (StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvent(Object* sender, StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void UnsubscribeFromEvent(Object@+, StringHash)", asMETHODPR(FileSystem, UnsubscribeFromEvent, (Object*, StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvents(Object* sender) | File: ../Core/Object.h engine->RegisterObjectMethod("FileSystem", "void UnsubscribeFromEvents(Object@+)", asMETHODPR(FileSystem, UnsubscribeFromEvents, (Object*), void), asCALL_THISCALL); // int RefCounted::WeakRefs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FileSystem", "int WeakRefs() const", asMETHODPR(FileSystem, WeakRefs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FileSystem", "int get_weakRefs() const", asMETHODPR(FileSystem, WeakRefs, () const, int), asCALL_THISCALL); #ifdef REGISTER_MANUAL_PART_Object REGISTER_MANUAL_PART_Object(FileSystem, "FileSystem") #endif #ifdef REGISTER_MANUAL_PART_RefCounted REGISTER_MANUAL_PART_RefCounted(FileSystem, "FileSystem") #endif #ifdef REGISTER_MANUAL_PART_FileSystem REGISTER_MANUAL_PART_FileSystem(FileSystem, "FileSystem") #endif RegisterSubclass<Object, FileSystem>(engine, "Object", "FileSystem"); RegisterSubclass<RefCounted, FileSystem>(engine, "RefCounted", "FileSystem"); // void FileWatcher::AddChange(const String& fileName) | File: ../IO/FileWatcher.h engine->RegisterObjectMethod("FileWatcher", "void AddChange(const String&in)", asMETHODPR(FileWatcher, AddChange, (const String&), void), asCALL_THISCALL); // void RefCounted::AddRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FileWatcher", asBEHAVE_ADDREF, "void f()", asMETHODPR(FileWatcher, AddRef, (), void), asCALL_THISCALL); // template<typename T> T* Object::Cast() | File: ../Core/Object.h // Not registered because template // template<typename T> const T* Object::Cast() const | File: ../Core/Object.h // Not registered because template // explicit FileWatcher::FileWatcher(Context* context) | File: ../IO/FileWatcher.h engine->RegisterObjectBehaviour("FileWatcher", asBEHAVE_FACTORY, "FileWatcher@+ f()", asFUNCTION(FileWatcher_FileWatcher_Context), asCALL_CDECL); // bool Object::GetBlockEvents() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "bool GetBlockEvents() const", asMETHODPR(FileWatcher, GetBlockEvents, () const, bool), asCALL_THISCALL); // const String& Object::GetCategory() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "const String& GetCategory() const", asMETHODPR(FileWatcher, GetCategory, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileWatcher", "const String& get_category() const", asMETHODPR(FileWatcher, GetCategory, () const, const String&), asCALL_THISCALL); // Context* Object::GetContext() const | File: ../Core/Object.h // Error: type "Context*" can not be returned // static ThreadID Thread::GetCurrentThreadID() | File: ../Core/Thread.h // Not registered because have @nobind mark // float FileWatcher::GetDelay() const | File: ../IO/FileWatcher.h engine->RegisterObjectMethod("FileWatcher", "float GetDelay() const", asMETHODPR(FileWatcher, GetDelay, () const, float), asCALL_THISCALL); // VariantMap& Object::GetEventDataMap() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "VariantMap& GetEventDataMap() const", asMETHODPR(FileWatcher, GetEventDataMap, () const, VariantMap&), asCALL_THISCALL); // EventHandler* Object::GetEventHandler() const | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // Object* Object::GetEventSender() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "Object@+ GetEventSender() const", asMETHODPR(FileWatcher, GetEventSender, () const, Object*), asCALL_THISCALL); // const Variant& Object::GetGlobalVar(StringHash key) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "const Variant& GetGlobalVar(StringHash) const", asMETHODPR(FileWatcher, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); engine->RegisterObjectMethod("FileWatcher", "const Variant& get_globalVar(StringHash) const", asMETHODPR(FileWatcher, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); // const VariantMap& Object::GetGlobalVars() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "const VariantMap& GetGlobalVars() const", asMETHODPR(FileWatcher, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); engine->RegisterObjectMethod("FileWatcher", "const VariantMap& get_globalVars() const", asMETHODPR(FileWatcher, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); // bool FileWatcher::GetNextChange(String& dest) | File: ../IO/FileWatcher.h engine->RegisterObjectMethod("FileWatcher", "bool GetNextChange(String&)", asMETHODPR(FileWatcher, GetNextChange, (String&), bool), asCALL_THISCALL); // const String& FileWatcher::GetPath() const | File: ../IO/FileWatcher.h engine->RegisterObjectMethod("FileWatcher", "const String& GetPath() const", asMETHODPR(FileWatcher, GetPath, () const, const String&), asCALL_THISCALL); // Object* Object::GetSubsystem(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "Object@+ GetSubsystem(StringHash) const", asMETHODPR(FileWatcher, GetSubsystem, (StringHash) const, Object*), asCALL_THISCALL); // template<class T> T* Object::GetSubsystem() const | File: ../Core/Object.h // Not registered because template // virtual StringHash Object::GetType() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "StringHash GetType() const", asMETHODPR(FileWatcher, GetType, () const, StringHash), asCALL_THISCALL); engine->RegisterObjectMethod("FileWatcher", "StringHash get_type() const", asMETHODPR(FileWatcher, GetType, () const, StringHash), asCALL_THISCALL); // virtual const TypeInfo* Object::GetTypeInfo() const =0 | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // static const TypeInfo* Object::GetTypeInfoStatic() | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // virtual const String& Object::GetTypeName() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "const String& GetTypeName() const", asMETHODPR(FileWatcher, GetTypeName, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("FileWatcher", "const String& get_typeName() const", asMETHODPR(FileWatcher, GetTypeName, () const, const String&), asCALL_THISCALL); // bool Object::HasEventHandlers() const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "bool HasEventHandlers() const", asMETHODPR(FileWatcher, HasEventHandlers, () const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "bool HasSubscribedToEvent(StringHash) const", asMETHODPR(FileWatcher, HasSubscribedToEvent, (StringHash) const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(Object* sender, StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "bool HasSubscribedToEvent(Object@+, StringHash) const", asMETHODPR(FileWatcher, HasSubscribedToEvent, (Object*, StringHash) const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "bool IsInstanceOf(StringHash) const", asMETHODPR(FileWatcher, IsInstanceOf, (StringHash) const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(const TypeInfo* typeInfo) const | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // template<typename T> bool Object::IsInstanceOf() const | File: ../Core/Object.h // Not registered because template // static bool Thread::IsMainThread() | File: ../Core/Thread.h engine->SetDefaultNamespace("FileWatcher"); engine->RegisterGlobalFunction("bool IsMainThread()", asFUNCTIONPR(FileWatcher::IsMainThread, (), bool), asCALL_CDECL); engine->SetDefaultNamespace(""); // bool Thread::IsStarted() const | File: ../Core/Thread.h engine->RegisterObjectMethod("FileWatcher", "bool IsStarted() const", asMETHODPR(FileWatcher, IsStarted, () const, bool), asCALL_THISCALL); // virtual void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void OnEvent(Object@+, StringHash, VariantMap&)", asMETHODPR(FileWatcher, OnEvent, (Object*, StringHash, VariantMap&), void), asCALL_THISCALL); // RefCount* RefCounted::RefCountPtr() | File: ../Container/RefCounted.h // Error: type "RefCount*" can not automatically bind // int RefCounted::Refs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FileWatcher", "int Refs() const", asMETHODPR(FileWatcher, Refs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FileWatcher", "int get_refs() const", asMETHODPR(FileWatcher, Refs, () const, int), asCALL_THISCALL); // void RefCounted::ReleaseRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FileWatcher", asBEHAVE_RELEASE, "void f()", asMETHODPR(FileWatcher, ReleaseRef, (), void), asCALL_THISCALL); // bool Thread::Run() | File: ../Core/Thread.h engine->RegisterObjectMethod("FileWatcher", "bool Run()", asMETHODPR(FileWatcher, Run, (), bool), asCALL_THISCALL); // void Object::SendEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void SendEvent(StringHash)", asMETHODPR(FileWatcher, SendEvent, (StringHash), void), asCALL_THISCALL); // void Object::SendEvent(StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void SendEvent(StringHash, VariantMap&)", asMETHODPR(FileWatcher, SendEvent, (StringHash, VariantMap&), void), asCALL_THISCALL); // template<typename... Args> void Object::SendEvent(StringHash eventType, Args... args) | File: ../Core/Object.h // Not registered because template // void Object::SetBlockEvents(bool block) | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void SetBlockEvents(bool)", asMETHODPR(FileWatcher, SetBlockEvents, (bool), void), asCALL_THISCALL); // void FileWatcher::SetDelay(float interval) | File: ../IO/FileWatcher.h engine->RegisterObjectMethod("FileWatcher", "void SetDelay(float)", asMETHODPR(FileWatcher, SetDelay, (float), void), asCALL_THISCALL); // void Object::SetGlobalVar(StringHash key, const Variant& value) | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void SetGlobalVar(StringHash, const Variant&in)", asMETHODPR(FileWatcher, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); engine->RegisterObjectMethod("FileWatcher", "void set_globalVar(StringHash, const Variant&in)", asMETHODPR(FileWatcher, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); // static void Thread::SetMainThread() | File: ../Core/Thread.h engine->SetDefaultNamespace("FileWatcher"); engine->RegisterGlobalFunction("void SetMainThread()", asFUNCTIONPR(FileWatcher::SetMainThread, (), void), asCALL_CDECL); engine->SetDefaultNamespace(""); // void Thread::SetPriority(int priority) | File: ../Core/Thread.h engine->RegisterObjectMethod("FileWatcher", "void SetPriority(int)", asMETHODPR(FileWatcher, SetPriority, (int), void), asCALL_THISCALL); // bool FileWatcher::StartWatching(const String& pathName, bool watchSubDirs) | File: ../IO/FileWatcher.h engine->RegisterObjectMethod("FileWatcher", "bool StartWatching(const String&in, bool)", asMETHODPR(FileWatcher, StartWatching, (const String&, bool), bool), asCALL_THISCALL); // void Thread::Stop() | File: ../Core/Thread.h engine->RegisterObjectMethod("FileWatcher", "void Stop()", asMETHODPR(FileWatcher, Stop, (), void), asCALL_THISCALL); // void FileWatcher::StopWatching() | File: ../IO/FileWatcher.h engine->RegisterObjectMethod("FileWatcher", "void StopWatching()", asMETHODPR(FileWatcher, StopWatching, (), void), asCALL_THISCALL); // void Object::SubscribeToEvent(StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // void FileWatcher::ThreadFunction() override | File: ../IO/FileWatcher.h engine->RegisterObjectMethod("FileWatcher", "void ThreadFunction()", asMETHODPR(FileWatcher, ThreadFunction, (), void), asCALL_THISCALL); // void Object::UnsubscribeFromAllEvents() | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void UnsubscribeFromAllEvents()", asMETHODPR(FileWatcher, UnsubscribeFromAllEvents, (), void), asCALL_THISCALL); // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void UnsubscribeFromAllEventsExcept(Array<StringHash>@+, bool)", asFUNCTION(FileWatcher_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool), asCALL_CDECL_OBJFIRST); // void Object::UnsubscribeFromEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void UnsubscribeFromEvent(StringHash)", asMETHODPR(FileWatcher, UnsubscribeFromEvent, (StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvent(Object* sender, StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void UnsubscribeFromEvent(Object@+, StringHash)", asMETHODPR(FileWatcher, UnsubscribeFromEvent, (Object*, StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvents(Object* sender) | File: ../Core/Object.h engine->RegisterObjectMethod("FileWatcher", "void UnsubscribeFromEvents(Object@+)", asMETHODPR(FileWatcher, UnsubscribeFromEvents, (Object*), void), asCALL_THISCALL); // int RefCounted::WeakRefs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FileWatcher", "int WeakRefs() const", asMETHODPR(FileWatcher, WeakRefs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FileWatcher", "int get_weakRefs() const", asMETHODPR(FileWatcher, WeakRefs, () const, int), asCALL_THISCALL); #ifdef REGISTER_MANUAL_PART_Object REGISTER_MANUAL_PART_Object(FileWatcher, "FileWatcher") #endif #ifdef REGISTER_MANUAL_PART_RefCounted REGISTER_MANUAL_PART_RefCounted(FileWatcher, "FileWatcher") #endif #ifdef REGISTER_MANUAL_PART_Thread REGISTER_MANUAL_PART_Thread(FileWatcher, "FileWatcher") #endif #ifdef REGISTER_MANUAL_PART_FileWatcher REGISTER_MANUAL_PART_FileWatcher(FileWatcher, "FileWatcher") #endif RegisterSubclass<Object, FileWatcher>(engine, "Object", "FileWatcher"); RegisterSubclass<RefCounted, FileWatcher>(engine, "RefCounted", "FileWatcher"); // void RefCounted::AddRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("Font", asBEHAVE_ADDREF, "void f()", asMETHODPR(Font, AddRef, (), void), asCALL_THISCALL); // bool Font::BeginLoad(Deserializer& source) override | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "bool BeginLoad(Deserializer&)", asMETHODPR(Font, BeginLoad, (Deserializer&), bool), asCALL_THISCALL); // template<typename T> T* Object::Cast() | File: ../Core/Object.h // Not registered because template // template<typename T> const T* Object::Cast() const | File: ../Core/Object.h // Not registered because template // virtual bool Resource::EndLoad() | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "bool EndLoad()", asMETHODPR(Font, EndLoad, (), bool), asCALL_THISCALL); // explicit Font::Font(Context* context) | File: ../UI/Font.h engine->RegisterObjectBehaviour("Font", asBEHAVE_FACTORY, "Font@+ f()", asFUNCTION(Font_Font_Context), asCALL_CDECL); // const IntVector2& Font::GetAbsoluteGlyphOffset() const | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "const IntVector2& GetAbsoluteGlyphOffset() const", asMETHODPR(Font, GetAbsoluteGlyphOffset, () const, const IntVector2&), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "const IntVector2& get_absoluteGlyphOffset() const", asMETHODPR(Font, GetAbsoluteGlyphOffset, () const, const IntVector2&), asCALL_THISCALL); // AsyncLoadState Resource::GetAsyncLoadState() const | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "AsyncLoadState GetAsyncLoadState() const", asMETHODPR(Font, GetAsyncLoadState, () const, AsyncLoadState), asCALL_THISCALL); // bool Object::GetBlockEvents() const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "bool GetBlockEvents() const", asMETHODPR(Font, GetBlockEvents, () const, bool), asCALL_THISCALL); // const String& Object::GetCategory() const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "const String& GetCategory() const", asMETHODPR(Font, GetCategory, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "const String& get_category() const", asMETHODPR(Font, GetCategory, () const, const String&), asCALL_THISCALL); // Context* Object::GetContext() const | File: ../Core/Object.h // Error: type "Context*" can not be returned // VariantMap& Object::GetEventDataMap() const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "VariantMap& GetEventDataMap() const", asMETHODPR(Font, GetEventDataMap, () const, VariantMap&), asCALL_THISCALL); // EventHandler* Object::GetEventHandler() const | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // Object* Object::GetEventSender() const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "Object@+ GetEventSender() const", asMETHODPR(Font, GetEventSender, () const, Object*), asCALL_THISCALL); // FontFace* Font::GetFace(float pointSize) | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "FontFace@+ GetFace(float)", asMETHODPR(Font, GetFace, (float), FontFace*), asCALL_THISCALL); // FontType Font::GetFontType() const | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "FontType GetFontType() const", asMETHODPR(Font, GetFontType, () const, FontType), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "FontType get_fontType() const", asMETHODPR(Font, GetFontType, () const, FontType), asCALL_THISCALL); // const Variant& Object::GetGlobalVar(StringHash key) const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "const Variant& GetGlobalVar(StringHash) const", asMETHODPR(Font, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "const Variant& get_globalVar(StringHash) const", asMETHODPR(Font, GetGlobalVar, (StringHash) const, const Variant&), asCALL_THISCALL); // const VariantMap& Object::GetGlobalVars() const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "const VariantMap& GetGlobalVars() const", asMETHODPR(Font, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "const VariantMap& get_globalVars() const", asMETHODPR(Font, GetGlobalVars, () const, const VariantMap&), asCALL_THISCALL); // unsigned Resource::GetMemoryUse() const | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "uint GetMemoryUse() const", asMETHODPR(Font, GetMemoryUse, () const, unsigned), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "uint get_memoryUse() const", asMETHODPR(Font, GetMemoryUse, () const, unsigned), asCALL_THISCALL); // const String& Resource::GetName() const | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "const String& GetName() const", asMETHODPR(Font, GetName, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "const String& get_name() const", asMETHODPR(Font, GetName, () const, const String&), asCALL_THISCALL); // StringHash Resource::GetNameHash() const | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "StringHash GetNameHash() const", asMETHODPR(Font, GetNameHash, () const, StringHash), asCALL_THISCALL); // const Vector2& Font::GetScaledGlyphOffset() const | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "const Vector2& GetScaledGlyphOffset() const", asMETHODPR(Font, GetScaledGlyphOffset, () const, const Vector2&), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "const Vector2& get_scaledGlyphOffset() const", asMETHODPR(Font, GetScaledGlyphOffset, () const, const Vector2&), asCALL_THISCALL); // Object* Object::GetSubsystem(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "Object@+ GetSubsystem(StringHash) const", asMETHODPR(Font, GetSubsystem, (StringHash) const, Object*), asCALL_THISCALL); // template<class T> T* Object::GetSubsystem() const | File: ../Core/Object.h // Not registered because template // IntVector2 Font::GetTotalGlyphOffset(float pointSize) const | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "IntVector2 GetTotalGlyphOffset(float) const", asMETHODPR(Font, GetTotalGlyphOffset, (float) const, IntVector2), asCALL_THISCALL); // virtual StringHash Object::GetType() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "StringHash GetType() const", asMETHODPR(Font, GetType, () const, StringHash), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "StringHash get_type() const", asMETHODPR(Font, GetType, () const, StringHash), asCALL_THISCALL); // virtual const TypeInfo* Object::GetTypeInfo() const =0 | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // static const TypeInfo* Object::GetTypeInfoStatic() | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // virtual const String& Object::GetTypeName() const =0 | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "const String& GetTypeName() const", asMETHODPR(Font, GetTypeName, () const, const String&), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "const String& get_typeName() const", asMETHODPR(Font, GetTypeName, () const, const String&), asCALL_THISCALL); // unsigned Resource::GetUseTimer() | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "uint GetUseTimer()", asMETHODPR(Font, GetUseTimer, (), unsigned), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "uint get_useTimer()", asMETHODPR(Font, GetUseTimer, (), unsigned), asCALL_THISCALL); // bool Object::HasEventHandlers() const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "bool HasEventHandlers() const", asMETHODPR(Font, HasEventHandlers, () const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "bool HasSubscribedToEvent(StringHash) const", asMETHODPR(Font, HasSubscribedToEvent, (StringHash) const, bool), asCALL_THISCALL); // bool Object::HasSubscribedToEvent(Object* sender, StringHash eventType) const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "bool HasSubscribedToEvent(Object@+, StringHash) const", asMETHODPR(Font, HasSubscribedToEvent, (Object*, StringHash) const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(StringHash type) const | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "bool IsInstanceOf(StringHash) const", asMETHODPR(Font, IsInstanceOf, (StringHash) const, bool), asCALL_THISCALL); // bool Object::IsInstanceOf(const TypeInfo* typeInfo) const | File: ../Core/Object.h // Error: type "TypeInfo" can not automatically bind bacause have @nobind mark // template<typename T> bool Object::IsInstanceOf() const | File: ../Core/Object.h // Not registered because template // bool Font::IsSDFFont() const | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "bool IsSDFFont() const", asMETHODPR(Font, IsSDFFont, () const, bool), asCALL_THISCALL); // bool Resource::Load(Deserializer& source) | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "bool Load(Deserializer&)", asMETHODPR(Font, Load, (Deserializer&), bool), asCALL_THISCALL); // bool Resource::LoadFile(const String& fileName) | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "bool LoadFile(const String&in)", asMETHODPR(Font, LoadFile, (const String&), bool), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "bool Load(const String&in)", asMETHODPR(Font, LoadFile, (const String&), bool), asCALL_THISCALL); // virtual void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void OnEvent(Object@+, StringHash, VariantMap&)", asMETHODPR(Font, OnEvent, (Object*, StringHash, VariantMap&), void), asCALL_THISCALL); // RefCount* RefCounted::RefCountPtr() | File: ../Container/RefCounted.h // Error: type "RefCount*" can not automatically bind // int RefCounted::Refs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("Font", "int Refs() const", asMETHODPR(Font, Refs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "int get_refs() const", asMETHODPR(Font, Refs, () const, int), asCALL_THISCALL); // static void Font::RegisterObject(Context* context) | File: ../UI/Font.h // Context can be used as firs parameter of constructors only // void Font::ReleaseFaces() | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "void ReleaseFaces()", asMETHODPR(Font, ReleaseFaces, (), void), asCALL_THISCALL); // void RefCounted::ReleaseRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("Font", asBEHAVE_RELEASE, "void f()", asMETHODPR(Font, ReleaseRef, (), void), asCALL_THISCALL); // void Resource::ResetUseTimer() | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "void ResetUseTimer()", asMETHODPR(Font, ResetUseTimer, (), void), asCALL_THISCALL); // virtual bool Resource::Save(Serializer& dest) const | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "bool Save(Serializer&) const", asMETHODPR(Font, Save, (Serializer&) const, bool), asCALL_THISCALL); // virtual bool Resource::SaveFile(const String& fileName) const | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "bool SaveFile(const String&in) const", asMETHODPR(Font, SaveFile, (const String&) const, bool), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "bool Save(const String&in) const", asMETHODPR(Font, SaveFile, (const String&) const, bool), asCALL_THISCALL); // bool Font::SaveXML(Serializer& dest, int pointSize, bool usedGlyphs=false, const String& indentation="\t") | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "bool SaveXML(Serializer&, int, bool = false, const String&in = \"\t\")", asMETHODPR(Font, SaveXML, (Serializer&, int, bool, const String&), bool), asCALL_THISCALL); // void Object::SendEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void SendEvent(StringHash)", asMETHODPR(Font, SendEvent, (StringHash), void), asCALL_THISCALL); // void Object::SendEvent(StringHash eventType, VariantMap& eventData) | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void SendEvent(StringHash, VariantMap&)", asMETHODPR(Font, SendEvent, (StringHash, VariantMap&), void), asCALL_THISCALL); // template<typename... Args> void Object::SendEvent(StringHash eventType, Args... args) | File: ../Core/Object.h // Not registered because template // void Font::SetAbsoluteGlyphOffset(const IntVector2& offset) | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "void SetAbsoluteGlyphOffset(const IntVector2&in)", asMETHODPR(Font, SetAbsoluteGlyphOffset, (const IntVector2&), void), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "void set_absoluteGlyphOffset(const IntVector2&in)", asMETHODPR(Font, SetAbsoluteGlyphOffset, (const IntVector2&), void), asCALL_THISCALL); // void Resource::SetAsyncLoadState(AsyncLoadState newState) | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "void SetAsyncLoadState(AsyncLoadState)", asMETHODPR(Font, SetAsyncLoadState, (AsyncLoadState), void), asCALL_THISCALL); // void Object::SetBlockEvents(bool block) | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void SetBlockEvents(bool)", asMETHODPR(Font, SetBlockEvents, (bool), void), asCALL_THISCALL); // void Object::SetGlobalVar(StringHash key, const Variant& value) | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void SetGlobalVar(StringHash, const Variant&in)", asMETHODPR(Font, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "void set_globalVar(StringHash, const Variant&in)", asMETHODPR(Font, SetGlobalVar, (StringHash, const Variant&), void), asCALL_THISCALL); // void Resource::SetMemoryUse(unsigned size) | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "void SetMemoryUse(uint)", asMETHODPR(Font, SetMemoryUse, (unsigned), void), asCALL_THISCALL); // void Resource::SetName(const String& name) | File: ../Resource/Resource.h engine->RegisterObjectMethod("Font", "void SetName(const String&in)", asMETHODPR(Font, SetName, (const String&), void), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "void set_name(const String&in)", asMETHODPR(Font, SetName, (const String&), void), asCALL_THISCALL); // void Font::SetScaledGlyphOffset(const Vector2& offset) | File: ../UI/Font.h engine->RegisterObjectMethod("Font", "void SetScaledGlyphOffset(const Vector2&in)", asMETHODPR(Font, SetScaledGlyphOffset, (const Vector2&), void), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "void set_scaledGlyphOffset(const Vector2&in)", asMETHODPR(Font, SetScaledGlyphOffset, (const Vector2&), void), asCALL_THISCALL); // void Object::SubscribeToEvent(StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler) | File: ../Core/Object.h // Error: type "EventHandler*" can not automatically bind // void Object::SubscribeToEvent(StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // void Object::SubscribeToEvent(Object* sender, StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=nullptr) | File: ../Core/Object.h // Error: type "const std::function<void(StringHash, VariantMap&)>&" can not automatically bind // void Object::UnsubscribeFromAllEvents() | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void UnsubscribeFromAllEvents()", asMETHODPR(Font, UnsubscribeFromAllEvents, (), void), asCALL_THISCALL); // void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData) | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void UnsubscribeFromAllEventsExcept(Array<StringHash>@+, bool)", asFUNCTION(Font_UnsubscribeFromAllEventsExcept_PODVectorStringHash_bool), asCALL_CDECL_OBJFIRST); // void Object::UnsubscribeFromEvent(StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void UnsubscribeFromEvent(StringHash)", asMETHODPR(Font, UnsubscribeFromEvent, (StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvent(Object* sender, StringHash eventType) | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void UnsubscribeFromEvent(Object@+, StringHash)", asMETHODPR(Font, UnsubscribeFromEvent, (Object*, StringHash), void), asCALL_THISCALL); // void Object::UnsubscribeFromEvents(Object* sender) | File: ../Core/Object.h engine->RegisterObjectMethod("Font", "void UnsubscribeFromEvents(Object@+)", asMETHODPR(Font, UnsubscribeFromEvents, (Object*), void), asCALL_THISCALL); // int RefCounted::WeakRefs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("Font", "int WeakRefs() const", asMETHODPR(Font, WeakRefs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("Font", "int get_weakRefs() const", asMETHODPR(Font, WeakRefs, () const, int), asCALL_THISCALL); #ifdef REGISTER_MANUAL_PART_Resource REGISTER_MANUAL_PART_Resource(Font, "Font") #endif #ifdef REGISTER_MANUAL_PART_Object REGISTER_MANUAL_PART_Object(Font, "Font") #endif #ifdef REGISTER_MANUAL_PART_RefCounted REGISTER_MANUAL_PART_RefCounted(Font, "Font") #endif #ifdef REGISTER_MANUAL_PART_Font REGISTER_MANUAL_PART_Font(Font, "Font") #endif RegisterSubclass<Resource, Font>(engine, "Resource", "Font"); RegisterSubclass<Object, Font>(engine, "Object", "Font"); RegisterSubclass<RefCounted, Font>(engine, "RefCounted", "Font"); // void RefCounted::AddRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FontFace", asBEHAVE_ADDREF, "void f()", asMETHODPR(FontFace, AddRef, (), void), asCALL_THISCALL); // virtual const FontGlyph* FontFace::GetGlyph(unsigned c) | File: ../UI/FontFace.h // Error: type "const FontGlyph*" can not automatically bind // float FontFace::GetKerning(unsigned c, unsigned d) const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFace", "float GetKerning(uint, uint) const", asMETHODPR(FontFace, GetKerning, (unsigned, unsigned) const, float), asCALL_THISCALL); // float FontFace::GetPointSize() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFace", "float GetPointSize() const", asMETHODPR(FontFace, GetPointSize, () const, float), asCALL_THISCALL); // float FontFace::GetRowHeight() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFace", "float GetRowHeight() const", asMETHODPR(FontFace, GetRowHeight, () const, float), asCALL_THISCALL); // const Vector<SharedPtr<Texture2D>>& FontFace::GetTextures() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFace", "Array<Texture2D@>@ GetTextures() const", asFUNCTION(FontFace_GetTextures_void), asCALL_CDECL_OBJFIRST); // virtual bool FontFace::HasMutableGlyphs() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFace", "bool HasMutableGlyphs() const", asMETHODPR(FontFace, HasMutableGlyphs, () const, bool), asCALL_THISCALL); // bool FontFace::IsDataLost() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFace", "bool IsDataLost() const", asMETHODPR(FontFace, IsDataLost, () const, bool), asCALL_THISCALL); // virtual bool FontFace::Load(const unsigned char* fontData, unsigned fontDataSize, float pointSize)=0 | File: ../UI/FontFace.h // Error: type "const unsigned char*" can not automatically bind // RefCount* RefCounted::RefCountPtr() | File: ../Container/RefCounted.h // Error: type "RefCount*" can not automatically bind // int RefCounted::Refs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FontFace", "int Refs() const", asMETHODPR(FontFace, Refs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FontFace", "int get_refs() const", asMETHODPR(FontFace, Refs, () const, int), asCALL_THISCALL); // void RefCounted::ReleaseRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FontFace", asBEHAVE_RELEASE, "void f()", asMETHODPR(FontFace, ReleaseRef, (), void), asCALL_THISCALL); // int RefCounted::WeakRefs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FontFace", "int WeakRefs() const", asMETHODPR(FontFace, WeakRefs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FontFace", "int get_weakRefs() const", asMETHODPR(FontFace, WeakRefs, () const, int), asCALL_THISCALL); #ifdef REGISTER_MANUAL_PART_RefCounted REGISTER_MANUAL_PART_RefCounted(FontFace, "FontFace") #endif #ifdef REGISTER_MANUAL_PART_FontFace REGISTER_MANUAL_PART_FontFace(FontFace, "FontFace") #endif RegisterSubclass<RefCounted, FontFace>(engine, "RefCounted", "FontFace"); // void RefCounted::AddRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FontFaceBitmap", asBEHAVE_ADDREF, "void f()", asMETHODPR(FontFaceBitmap, AddRef, (), void), asCALL_THISCALL); // explicit FontFaceBitmap::FontFaceBitmap(Font* font) | File: ../UI/FontFaceBitmap.h engine->RegisterObjectBehaviour("FontFaceBitmap", asBEHAVE_FACTORY, "FontFaceBitmap@+ f(Font@+)", asFUNCTION(FontFaceBitmap_FontFaceBitmap_Font), asCALL_CDECL); // virtual const FontGlyph* FontFace::GetGlyph(unsigned c) | File: ../UI/FontFace.h // Error: type "const FontGlyph*" can not automatically bind // float FontFace::GetKerning(unsigned c, unsigned d) const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceBitmap", "float GetKerning(uint, uint) const", asMETHODPR(FontFaceBitmap, GetKerning, (unsigned, unsigned) const, float), asCALL_THISCALL); // float FontFace::GetPointSize() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceBitmap", "float GetPointSize() const", asMETHODPR(FontFaceBitmap, GetPointSize, () const, float), asCALL_THISCALL); // float FontFace::GetRowHeight() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceBitmap", "float GetRowHeight() const", asMETHODPR(FontFaceBitmap, GetRowHeight, () const, float), asCALL_THISCALL); // const Vector<SharedPtr<Texture2D>>& FontFace::GetTextures() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceBitmap", "Array<Texture2D@>@ GetTextures() const", asFUNCTION(FontFaceBitmap_GetTextures_void), asCALL_CDECL_OBJFIRST); // virtual bool FontFace::HasMutableGlyphs() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceBitmap", "bool HasMutableGlyphs() const", asMETHODPR(FontFaceBitmap, HasMutableGlyphs, () const, bool), asCALL_THISCALL); // bool FontFace::IsDataLost() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceBitmap", "bool IsDataLost() const", asMETHODPR(FontFaceBitmap, IsDataLost, () const, bool), asCALL_THISCALL); // bool FontFaceBitmap::Load(const unsigned char* fontData, unsigned fontDataSize, float pointSize) override | File: ../UI/FontFaceBitmap.h // Error: type "const unsigned char*" can not automatically bind // bool FontFaceBitmap::Load(FontFace* fontFace, bool usedGlyphs) | File: ../UI/FontFaceBitmap.h engine->RegisterObjectMethod("FontFaceBitmap", "bool Load(FontFace@+, bool)", asMETHODPR(FontFaceBitmap, Load, (FontFace*, bool), bool), asCALL_THISCALL); // RefCount* RefCounted::RefCountPtr() | File: ../Container/RefCounted.h // Error: type "RefCount*" can not automatically bind // int RefCounted::Refs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FontFaceBitmap", "int Refs() const", asMETHODPR(FontFaceBitmap, Refs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FontFaceBitmap", "int get_refs() const", asMETHODPR(FontFaceBitmap, Refs, () const, int), asCALL_THISCALL); // void RefCounted::ReleaseRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FontFaceBitmap", asBEHAVE_RELEASE, "void f()", asMETHODPR(FontFaceBitmap, ReleaseRef, (), void), asCALL_THISCALL); // bool FontFaceBitmap::Save(Serializer& dest, int pointSize, const String& indentation="\t") | File: ../UI/FontFaceBitmap.h engine->RegisterObjectMethod("FontFaceBitmap", "bool Save(Serializer&, int, const String&in = \"\t\")", asMETHODPR(FontFaceBitmap, Save, (Serializer&, int, const String&), bool), asCALL_THISCALL); // int RefCounted::WeakRefs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FontFaceBitmap", "int WeakRefs() const", asMETHODPR(FontFaceBitmap, WeakRefs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FontFaceBitmap", "int get_weakRefs() const", asMETHODPR(FontFaceBitmap, WeakRefs, () const, int), asCALL_THISCALL); #ifdef REGISTER_MANUAL_PART_FontFace REGISTER_MANUAL_PART_FontFace(FontFaceBitmap, "FontFaceBitmap") #endif #ifdef REGISTER_MANUAL_PART_RefCounted REGISTER_MANUAL_PART_RefCounted(FontFaceBitmap, "FontFaceBitmap") #endif #ifdef REGISTER_MANUAL_PART_FontFaceBitmap REGISTER_MANUAL_PART_FontFaceBitmap(FontFaceBitmap, "FontFaceBitmap") #endif RegisterSubclass<FontFace, FontFaceBitmap>(engine, "FontFace", "FontFaceBitmap"); RegisterSubclass<RefCounted, FontFaceBitmap>(engine, "RefCounted", "FontFaceBitmap"); // void RefCounted::AddRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FontFaceFreeType", asBEHAVE_ADDREF, "void f()", asMETHODPR(FontFaceFreeType, AddRef, (), void), asCALL_THISCALL); // explicit FontFaceFreeType::FontFaceFreeType(Font* font) | File: ../UI/FontFaceFreeType.h engine->RegisterObjectBehaviour("FontFaceFreeType", asBEHAVE_FACTORY, "FontFaceFreeType@+ f(Font@+)", asFUNCTION(FontFaceFreeType_FontFaceFreeType_Font), asCALL_CDECL); // const FontGlyph* FontFaceFreeType::GetGlyph(unsigned c) override | File: ../UI/FontFaceFreeType.h // Error: type "const FontGlyph*" can not automatically bind // float FontFace::GetKerning(unsigned c, unsigned d) const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceFreeType", "float GetKerning(uint, uint) const", asMETHODPR(FontFaceFreeType, GetKerning, (unsigned, unsigned) const, float), asCALL_THISCALL); // float FontFace::GetPointSize() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceFreeType", "float GetPointSize() const", asMETHODPR(FontFaceFreeType, GetPointSize, () const, float), asCALL_THISCALL); // float FontFace::GetRowHeight() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceFreeType", "float GetRowHeight() const", asMETHODPR(FontFaceFreeType, GetRowHeight, () const, float), asCALL_THISCALL); // const Vector<SharedPtr<Texture2D>>& FontFace::GetTextures() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceFreeType", "Array<Texture2D@>@ GetTextures() const", asFUNCTION(FontFaceFreeType_GetTextures_void), asCALL_CDECL_OBJFIRST); // bool FontFaceFreeType::HasMutableGlyphs() const override | File: ../UI/FontFaceFreeType.h engine->RegisterObjectMethod("FontFaceFreeType", "bool HasMutableGlyphs() const", asMETHODPR(FontFaceFreeType, HasMutableGlyphs, () const, bool), asCALL_THISCALL); // bool FontFace::IsDataLost() const | File: ../UI/FontFace.h engine->RegisterObjectMethod("FontFaceFreeType", "bool IsDataLost() const", asMETHODPR(FontFaceFreeType, IsDataLost, () const, bool), asCALL_THISCALL); // bool FontFaceFreeType::Load(const unsigned char* fontData, unsigned fontDataSize, float pointSize) override | File: ../UI/FontFaceFreeType.h // Error: type "const unsigned char*" can not automatically bind // RefCount* RefCounted::RefCountPtr() | File: ../Container/RefCounted.h // Error: type "RefCount*" can not automatically bind // int RefCounted::Refs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FontFaceFreeType", "int Refs() const", asMETHODPR(FontFaceFreeType, Refs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FontFaceFreeType", "int get_refs() const", asMETHODPR(FontFaceFreeType, Refs, () const, int), asCALL_THISCALL); // void RefCounted::ReleaseRef() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("FontFaceFreeType", asBEHAVE_RELEASE, "void f()", asMETHODPR(FontFaceFreeType, ReleaseRef, (), void), asCALL_THISCALL); // int RefCounted::WeakRefs() const | File: ../Container/RefCounted.h engine->RegisterObjectMethod("FontFaceFreeType", "int WeakRefs() const", asMETHODPR(FontFaceFreeType, WeakRefs, () const, int), asCALL_THISCALL); engine->RegisterObjectMethod("FontFaceFreeType", "int get_weakRefs() const", asMETHODPR(FontFaceFreeType, WeakRefs, () const, int), asCALL_THISCALL); #ifdef REGISTER_MANUAL_PART_FontFace REGISTER_MANUAL_PART_FontFace(FontFaceFreeType, "FontFaceFreeType") #endif #ifdef REGISTER_MANUAL_PART_RefCounted REGISTER_MANUAL_PART_RefCounted(FontFaceFreeType, "FontFaceFreeType") #endif #ifdef REGISTER_MANUAL_PART_FontFaceFreeType REGISTER_MANUAL_PART_FontFaceFreeType(FontFaceFreeType, "FontFaceFreeType") #endif RegisterSubclass<FontFace, FontFaceFreeType>(engine, "FontFace", "FontFaceFreeType"); RegisterSubclass<RefCounted, FontFaceFreeType>(engine, "RefCounted", "FontFaceFreeType"); // Plane Frustum::planes_[NUM_FRUSTUM_PLANES] | File: ../Math/Frustum.h // Not registered because array // Vector3 Frustum::vertices_[NUM_FRUSTUM_VERTICES] | File: ../Math/Frustum.h // Not registered because array // void Frustum::Define(float fov, float aspectRatio, float zoom, float nearZ, float farZ, const Matrix3x4& transform=Matrix3x4::IDENTITY) | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "void Define(float, float, float, float, float, const Matrix3x4&in = Matrix3x4::IDENTITY)", asMETHODPR(Frustum, Define, (float, float, float, float, float, const Matrix3x4&), void), asCALL_THISCALL); // void Frustum::Define(const Vector3& near, const Vector3& far, const Matrix3x4& transform=Matrix3x4::IDENTITY) | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "void Define(const Vector3&in, const Vector3&in, const Matrix3x4&in = Matrix3x4::IDENTITY)", asMETHODPR(Frustum, Define, (const Vector3&, const Vector3&, const Matrix3x4&), void), asCALL_THISCALL); // void Frustum::Define(const BoundingBox& box, const Matrix3x4& transform=Matrix3x4::IDENTITY) | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "void Define(const BoundingBox&in, const Matrix3x4&in = Matrix3x4::IDENTITY)", asMETHODPR(Frustum, Define, (const BoundingBox&, const Matrix3x4&), void), asCALL_THISCALL); // void Frustum::Define(const Matrix4& projection) | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "void Define(const Matrix4&in)", asMETHODPR(Frustum, Define, (const Matrix4&), void), asCALL_THISCALL); // void Frustum::DefineOrtho(float orthoSize, float aspectRatio, float zoom, float nearZ, float farZ, const Matrix3x4& transform=Matrix3x4::IDENTITY) | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "void DefineOrtho(float, float, float, float, float, const Matrix3x4&in = Matrix3x4::IDENTITY)", asMETHODPR(Frustum, DefineOrtho, (float, float, float, float, float, const Matrix3x4&), void), asCALL_THISCALL); // void Frustum::DefineSplit(const Matrix4& projection, float near, float far) | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "void DefineSplit(const Matrix4&in, float, float)", asMETHODPR(Frustum, DefineSplit, (const Matrix4&, float, float), void), asCALL_THISCALL); // float Frustum::Distance(const Vector3& point) const | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "float Distance(const Vector3&in) const", asMETHODPR(Frustum, Distance, (const Vector3&) const, float), asCALL_THISCALL); // Frustum::Frustum(const Frustum& frustum) noexcept | File: ../Math/Frustum.h engine->RegisterObjectBehaviour("Frustum", asBEHAVE_CONSTRUCT, "void f(const Frustum&in)", asFUNCTION(Frustum_Frustum_Frustum), asCALL_CDECL_OBJFIRST); // Intersection Frustum::IsInside(const Vector3& point) const | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "Intersection IsInside(const Vector3&in) const", asMETHODPR(Frustum, IsInside, (const Vector3&) const, Intersection), asCALL_THISCALL); // Intersection Frustum::IsInside(const Sphere& sphere) const | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "Intersection IsInside(const Sphere&in) const", asMETHODPR(Frustum, IsInside, (const Sphere&) const, Intersection), asCALL_THISCALL); // Intersection Frustum::IsInside(const BoundingBox& box) const | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "Intersection IsInside(const BoundingBox&in) const", asMETHODPR(Frustum, IsInside, (const BoundingBox&) const, Intersection), asCALL_THISCALL); // Intersection Frustum::IsInsideFast(const Sphere& sphere) const | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "Intersection IsInsideFast(const Sphere&in) const", asMETHODPR(Frustum, IsInsideFast, (const Sphere&) const, Intersection), asCALL_THISCALL); // Intersection Frustum::IsInsideFast(const BoundingBox& box) const | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "Intersection IsInsideFast(const BoundingBox&in) const", asMETHODPR(Frustum, IsInsideFast, (const BoundingBox&) const, Intersection), asCALL_THISCALL); // Frustum& Frustum::operator=(const Frustum& rhs) noexcept | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "Frustum& opAssign(const Frustum&in)", asMETHODPR(Frustum, operator=, (const Frustum&), Frustum&), asCALL_THISCALL); // Rect Frustum::Projected(const Matrix4& projection) const | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "Rect Projected(const Matrix4&in) const", asMETHODPR(Frustum, Projected, (const Matrix4&) const, Rect), asCALL_THISCALL); // void Frustum::Transform(const Matrix3& transform) | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "void Transform(const Matrix3&in)", asMETHODPR(Frustum, Transform, (const Matrix3&), void), asCALL_THISCALL); // void Frustum::Transform(const Matrix3x4& transform) | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "void Transform(const Matrix3x4&in)", asMETHODPR(Frustum, Transform, (const Matrix3x4&), void), asCALL_THISCALL); // Frustum Frustum::Transformed(const Matrix3& transform) const | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "Frustum Transformed(const Matrix3&in) const", asMETHODPR(Frustum, Transformed, (const Matrix3&) const, Frustum), asCALL_THISCALL); // Frustum Frustum::Transformed(const Matrix3x4& transform) const | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "Frustum Transformed(const Matrix3x4&in) const", asMETHODPR(Frustum, Transformed, (const Matrix3x4&) const, Frustum), asCALL_THISCALL); // void Frustum::UpdatePlanes() | File: ../Math/Frustum.h engine->RegisterObjectMethod("Frustum", "void UpdatePlanes()", asMETHODPR(Frustum, UpdatePlanes, (), void), asCALL_THISCALL); // Frustum::~Frustum() | Implicitly-declared engine->RegisterObjectBehaviour("Frustum", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(Frustum_Destructor), asCALL_CDECL_OBJFIRST); #ifdef REGISTER_MANUAL_PART_Frustum REGISTER_MANUAL_PART_Frustum(Frustum, "Frustum") #endif // bool FileSelectorEntry::directory_ | File: ../UI/FileSelector.h engine->RegisterObjectProperty("FileSelectorEntry", "bool directory", offsetof(FileSelectorEntry, directory_)); // String FileSelectorEntry::name_ | File: ../UI/FileSelector.h engine->RegisterObjectProperty("FileSelectorEntry", "String name", offsetof(FileSelectorEntry, name_)); // FileSelectorEntry::~FileSelectorEntry() | Implicitly-declared engine->RegisterObjectBehaviour("FileSelectorEntry", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(FileSelectorEntry_Destructor), asCALL_CDECL_OBJFIRST); // FileSelectorEntry& FileSelectorEntry::operator=(const FileSelectorEntry&) | Possible implicitly-declared RegisterImplicitlyDeclaredAssignOperatorIfPossible<FileSelectorEntry>(engine, "FileSelectorEntry"); #ifdef REGISTER_MANUAL_PART_FileSelectorEntry REGISTER_MANUAL_PART_FileSelectorEntry(FileSelectorEntry, "FileSelectorEntry") #endif // bool FocusParameters::autoSize_ | File: ../Graphics/Light.h engine->RegisterObjectProperty("FocusParameters", "bool autoSize", offsetof(FocusParameters, autoSize_)); // bool FocusParameters::focus_ | File: ../Graphics/Light.h engine->RegisterObjectProperty("FocusParameters", "bool focus", offsetof(FocusParameters, focus_)); // float FocusParameters::minView_ | File: ../Graphics/Light.h engine->RegisterObjectProperty("FocusParameters", "float minView", offsetof(FocusParameters, minView_)); // bool FocusParameters::nonUniform_ | File: ../Graphics/Light.h engine->RegisterObjectProperty("FocusParameters", "bool nonUniform", offsetof(FocusParameters, nonUniform_)); // float FocusParameters::quantize_ | File: ../Graphics/Light.h engine->RegisterObjectProperty("FocusParameters", "float quantize", offsetof(FocusParameters, quantize_)); // FocusParameters::FocusParameters(bool focus, bool nonUniform, bool autoSize, float quantize, float minView) | File: ../Graphics/Light.h engine->RegisterObjectBehaviour("FocusParameters", asBEHAVE_CONSTRUCT, "void f(bool, bool, bool, float, float)", asFUNCTION(FocusParameters_FocusParameters_bool_bool_bool_float_float), asCALL_CDECL_OBJFIRST); // void FocusParameters::Validate() | File: ../Graphics/Light.h engine->RegisterObjectMethod("FocusParameters", "void Validate()", asMETHODPR(FocusParameters, Validate, (), void), asCALL_THISCALL); // FocusParameters& FocusParameters::operator=(const FocusParameters&) | Possible implicitly-declared RegisterImplicitlyDeclaredAssignOperatorIfPossible<FocusParameters>(engine, "FocusParameters"); #ifdef REGISTER_MANUAL_PART_FocusParameters REGISTER_MANUAL_PART_FocusParameters(FocusParameters, "FocusParameters") #endif // float FontGlyph::advanceX_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "float advanceX", offsetof(FontGlyph, advanceX_)); // float FontGlyph::height_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "float height", offsetof(FontGlyph, height_)); // float FontGlyph::offsetX_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "float offsetX", offsetof(FontGlyph, offsetX_)); // float FontGlyph::offsetY_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "float offsetY", offsetof(FontGlyph, offsetY_)); // unsigned FontGlyph::page_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "uint page", offsetof(FontGlyph, page_)); // short FontGlyph::texHeight_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "int16 texHeight", offsetof(FontGlyph, texHeight_)); // short FontGlyph::texWidth_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "int16 texWidth", offsetof(FontGlyph, texWidth_)); // bool FontGlyph::used_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "bool used", offsetof(FontGlyph, used_)); // float FontGlyph::width_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "float width", offsetof(FontGlyph, width_)); // short FontGlyph::x_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "int16 x", offsetof(FontGlyph, x_)); // short FontGlyph::y_ | File: ../UI/FontFace.h engine->RegisterObjectProperty("FontGlyph", "int16 y", offsetof(FontGlyph, y_)); // FontGlyph::~FontGlyph() | Implicitly-declared engine->RegisterObjectBehaviour("FontGlyph", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(FontGlyph_Destructor), asCALL_CDECL_OBJFIRST); // FontGlyph& FontGlyph::operator=(const FontGlyph&) | Possible implicitly-declared RegisterImplicitlyDeclaredAssignOperatorIfPossible<FontGlyph>(engine, "FontGlyph"); #ifdef REGISTER_MANUAL_PART_FontGlyph REGISTER_MANUAL_PART_FontGlyph(FontGlyph, "FontGlyph") #endif // Camera* FrameInfo::camera_ | File: ../Graphics/Drawable.h // Camera* can not be registered // unsigned FrameInfo::frameNumber_ | File: ../Graphics/Drawable.h engine->RegisterObjectProperty("FrameInfo", "uint frameNumber", offsetof(FrameInfo, frameNumber_)); // float FrameInfo::timeStep_ | File: ../Graphics/Drawable.h engine->RegisterObjectProperty("FrameInfo", "float timeStep", offsetof(FrameInfo, timeStep_)); // IntVector2 FrameInfo::viewSize_ | File: ../Graphics/Drawable.h engine->RegisterObjectProperty("FrameInfo", "IntVector2 viewSize", offsetof(FrameInfo, viewSize_)); // FrameInfo::~FrameInfo() | Implicitly-declared engine->RegisterObjectBehaviour("FrameInfo", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(FrameInfo_Destructor), asCALL_CDECL_OBJFIRST); // FrameInfo& FrameInfo::operator=(const FrameInfo&) | Possible implicitly-declared RegisterImplicitlyDeclaredAssignOperatorIfPossible<FrameInfo>(engine, "FrameInfo"); #ifdef REGISTER_MANUAL_PART_FrameInfo REGISTER_MANUAL_PART_FrameInfo(FrameInfo, "FrameInfo") #endif } }
henu/Urho3D
Source/Urho3D/AngelScript/Generated_Members_F.cpp
C++
mit
138,861
export default { props: { cats: [ { name: 'cat 0', checked: false }, { name: 'cat 1', checked: false } ] }, html: ` <input type="checkbox"> <input type="checkbox"> `, test({ assert, component, target, window }) { const { cats } = component; const newCats = cats.slice(); newCats.push({ name: 'cat ' + cats.length, checked: false }); component.cats = newCats; let inputs = target.querySelectorAll('input'); assert.equal(inputs.length, 3); const event = new window.Event('change'); inputs[0].checked = true; inputs[0].dispatchEvent(event); inputs = target.querySelectorAll('input'); assert.equal(inputs.length, 3); } };
sveltejs/svelte
test/runtime/samples/binding-input-checkbox-with-event-in-each/_config.js
JavaScript
mit
695
class Cloudrider::Apiv1::CookieSplashComponent < Cloudrider::Apiv1::Base class Context def icon_image_url "assets/cookie-splash/california.png" end def splash_style :wechat end end private def _context Context.new end end
foxnewsnetwork/cloudrider
lib/cloudrider/apiv1/cookie_splash_component.rb
Ruby
mit
263
using System; using System.IO; namespace CodeEval.LongestLines { /// <summary> /// Longest Lines Challenge /// Difficulty: Medium /// Description: find the 'N' longest lines and return them from longest to smallest. /// Problem Statement: https://www.codeeval.com/open_challenges/2/ /// </summary> class LongestLines { /// <summary> /// Entry Point for the Challenge /// Possible Optimization: Implement a Cycle buffer that keeps track of the n longest lines, and sort that at the end. /// That way we only need to store and sort n lines. /// </summary> /// <param name="args">Command line Arguments</param> public static void Main(string[] args) { string[] lines = File.ReadAllLines(args[0]); int n = int.Parse(lines[0]); Comparison<string> lengthDescending = (x, y) => x.Length > y.Length ? -1 : x.Length < y.Length ? 1 : 0; Array.Sort(lines, lengthDescending); for (int i = 0; i < n; i++) { Console.WriteLine(lines[i]); } } } }
joshimoo/Challenges
CodeEval/Medium/LongestLines/LongestLines.cs
C#
mit
1,145
<?php $data = $this->registration->get_tourist_info($this->session->userdata('uid')); ?> <form class="form" action="/insert_spot" method="post" enctype="multipart/form-data"> <div class="col-md-12"> <div class="fileinput fileinput-new" data-provides="fileinput"> <div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;"> <img src="<?php echo "../assets/images/touristspot/" . $data['filename'] ?>" alt="" /> </div> <div> <span class="btn btn-info btn-file"><span class="fileinput-new">Select image</span><span class="fileinput-exists">Change</span><input type="file" name="picture"></span> <a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a> </div> </div> </div> <div class="col-md-12"> <label for="">Tourist Name</label> <input type="text" class="form-control" name="touristspot" value="<?php echo $data['tourist'] ?>"> <label for="">City</label> <select class="form-control" name="city"> <?php foreach ($this->registration->select_city() as $key => $value): extract($value); ?> <?php if ($city == $id): ?> <option value="<?php echo $data['id'] ?>" selected><?php echo $city ?></option> <?php else: ?> <option value="<?php echo $id ?>"><?php echo $city ?></option> <?php endif; ?> <?php endforeach; ?> </select> </div> <div class="col-md-12"> <label for="">Contact</label> <input type="text" class="form-control" name="contact" value="<?php echo $data['contact'] ?>"> <label for="">Address</label> <input type="text" class="form-control" name="address" value="<?php echo $data['address'] ?>"> </div> <div class="col-md-12"> <label for="">Information</label> <textarea name="description" class="form-control" style="width:100%;height:150px;resize:none"><?php echo $data['information'] ?></textarea> <br /> <button type="submit" class="btn btn-success pull-right" name="button">Save</button> <br /> <br /> </div> </form>
sonitgregorio/leytetourismportal
application/views/tourist/setting_tourist.php
PHP
mit
2,175
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('code-system-property-1', 'Unit | Model | CodeSystem_Property1', { needs: [ 'model:meta', 'model:narrative', 'model:resource', 'model:extension', 'model:coding' ] }); test('it exists', function(assert) { const model = this.subject(); assert.ok(!!model); });
davekago/ember-fhir
tests/unit/models/code-system-property-1-test.js
JavaScript
mit
354
import _plotly_utils.basevalidators class DataValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="data", parent_name="layout.template", **kwargs): super(DataValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Data"), data_docs=kwargs.pop( "data_docs", """ area A tuple of :class:`plotly.graph_objects.Area` instances or dicts with compatible properties barpolar A tuple of :class:`plotly.graph_objects.Barpolar` instances or dicts with compatible properties bar A tuple of :class:`plotly.graph_objects.Bar` instances or dicts with compatible properties box A tuple of :class:`plotly.graph_objects.Box` instances or dicts with compatible properties candlestick A tuple of :class:`plotly.graph_objects.Candlestick` instances or dicts with compatible properties carpet A tuple of :class:`plotly.graph_objects.Carpet` instances or dicts with compatible properties choroplethmapbox A tuple of :class:`plotly.graph_objects.Choroplethmapbox` instances or dicts with compatible properties choropleth A tuple of :class:`plotly.graph_objects.Choropleth` instances or dicts with compatible properties cone A tuple of :class:`plotly.graph_objects.Cone` instances or dicts with compatible properties contourcarpet A tuple of :class:`plotly.graph_objects.Contourcarpet` instances or dicts with compatible properties contour A tuple of :class:`plotly.graph_objects.Contour` instances or dicts with compatible properties densitymapbox A tuple of :class:`plotly.graph_objects.Densitymapbox` instances or dicts with compatible properties funnelarea A tuple of :class:`plotly.graph_objects.Funnelarea` instances or dicts with compatible properties funnel A tuple of :class:`plotly.graph_objects.Funnel` instances or dicts with compatible properties heatmapgl A tuple of :class:`plotly.graph_objects.Heatmapgl` instances or dicts with compatible properties heatmap A tuple of :class:`plotly.graph_objects.Heatmap` instances or dicts with compatible properties histogram2dcontour A tuple of :class:`plotly.graph_objects.Histogr am2dContour` instances or dicts with compatible properties histogram2d A tuple of :class:`plotly.graph_objects.Histogram2d` instances or dicts with compatible properties histogram A tuple of :class:`plotly.graph_objects.Histogram` instances or dicts with compatible properties image A tuple of :class:`plotly.graph_objects.Image` instances or dicts with compatible properties indicator A tuple of :class:`plotly.graph_objects.Indicator` instances or dicts with compatible properties isosurface A tuple of :class:`plotly.graph_objects.Isosurface` instances or dicts with compatible properties mesh3d A tuple of :class:`plotly.graph_objects.Mesh3d` instances or dicts with compatible properties ohlc A tuple of :class:`plotly.graph_objects.Ohlc` instances or dicts with compatible properties parcats A tuple of :class:`plotly.graph_objects.Parcats` instances or dicts with compatible properties parcoords A tuple of :class:`plotly.graph_objects.Parcoords` instances or dicts with compatible properties pie A tuple of :class:`plotly.graph_objects.Pie` instances or dicts with compatible properties pointcloud A tuple of :class:`plotly.graph_objects.Pointcloud` instances or dicts with compatible properties sankey A tuple of :class:`plotly.graph_objects.Sankey` instances or dicts with compatible properties scatter3d A tuple of :class:`plotly.graph_objects.Scatter3d` instances or dicts with compatible properties scattercarpet A tuple of :class:`plotly.graph_objects.Scattercarpet` instances or dicts with compatible properties scattergeo A tuple of :class:`plotly.graph_objects.Scattergeo` instances or dicts with compatible properties scattergl A tuple of :class:`plotly.graph_objects.Scattergl` instances or dicts with compatible properties scattermapbox A tuple of :class:`plotly.graph_objects.Scattermapbox` instances or dicts with compatible properties scatterpolargl A tuple of :class:`plotly.graph_objects.Scatterpolargl` instances or dicts with compatible properties scatterpolar A tuple of :class:`plotly.graph_objects.Scatterpolar` instances or dicts with compatible properties scatter A tuple of :class:`plotly.graph_objects.Scatter` instances or dicts with compatible properties scatterternary A tuple of :class:`plotly.graph_objects.Scatterternary` instances or dicts with compatible properties splom A tuple of :class:`plotly.graph_objects.Splom` instances or dicts with compatible properties streamtube A tuple of :class:`plotly.graph_objects.Streamtube` instances or dicts with compatible properties sunburst A tuple of :class:`plotly.graph_objects.Sunburst` instances or dicts with compatible properties surface A tuple of :class:`plotly.graph_objects.Surface` instances or dicts with compatible properties table A tuple of :class:`plotly.graph_objects.Table` instances or dicts with compatible properties treemap A tuple of :class:`plotly.graph_objects.Treemap` instances or dicts with compatible properties violin A tuple of :class:`plotly.graph_objects.Violin` instances or dicts with compatible properties volume A tuple of :class:`plotly.graph_objects.Volume` instances or dicts with compatible properties waterfall A tuple of :class:`plotly.graph_objects.Waterfall` instances or dicts with compatible properties """, ), **kwargs )
plotly/python-api
packages/python/plotly/plotly/validators/layout/template/_data.py
Python
mit
8,076
require 'assert' require 'qs/io_pipe' require 'thread' class Qs::IOPipe class UnitTests < Assert::Context desc "Qs::IOPipe" setup do # mimic how IO.select responds @io_select_response = Factory.boolean ? [[NULL], [], []] : nil @io_select_called_with = nil Assert.stub(IO, :select) do |*args| @io_select_called_with = args @io_select_response end @io_pipe = Qs::IOPipe.new end subject{ @io_pipe } should have_readers :reader, :writer should have_imeths :setup, :teardown should have_imeths :read, :write, :wait should "default its reader and writer" do assert_same NULL, subject.reader assert_same NULL, subject.writer end should "change its reader/writer to an IO pipe when setup" do subject.setup assert_not_same NULL, subject.reader assert_not_same NULL, subject.writer assert_instance_of IO, subject.reader assert_instance_of IO, subject.writer end should "close its reader/writer and set them to defaults when torn down" do subject.setup reader = subject.reader writer = subject.writer subject.teardown assert_true reader.closed? assert_true writer.closed? assert_same NULL, subject.reader assert_same NULL, subject.writer end should "be able to read/write values" do subject.setup value = Factory.string(NUMBER_OF_BYTES) subject.write(value) assert_equal value, subject.read end should "only read/write a fixed number of bytes" do subject.setup value = Factory.string subject.write(value) assert_equal value[0, NUMBER_OF_BYTES], subject.read end should "be able to wait until there is something to read" do subject.setup result = subject.wait exp = [[subject.reader], nil, nil, nil] assert_equal exp, @io_select_called_with assert_equal !!@io_select_response, result timeout = Factory.integer subject.wait(timeout) exp = [[subject.reader], nil, nil, timeout] assert_equal exp, @io_select_called_with end end end
redding/qs
test/unit/io_pipe_tests.rb
Ruby
mit
2,162
import io.grpc.BindableService; import io.grpc.ServerInterceptors; import io.grpc.ServerServiceDefinition; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; import heartbeat.HeartBeatService; import services.FileSystemAuthService; import services.FileSystemMetaService; import services.interceptors.FileSystemAuthInterceptor; import utils.AbstractGRPCServer; /** * Created by Shunjie Ding on 10/12/2016. */ class MasterNodeServer extends AbstractGRPCServer { private static final Logger logger = Logger.getLogger(MasterNodeServer.class.getName()); /** * serviceList is a list of {@link BindableService} which will be used for this server. * This should be initialized before any {@code buildServer} is called. */ private List<BindableService> serviceList = new LinkedList<>(); MasterNodeServer(int port, Config config) { super(logger); RedissonClient redissonClient = Redisson.create(config); serviceList.add(new HeartBeatService()); serviceList.add(new BindableService() { @Override public ServerServiceDefinition bindService() { return ServerInterceptors.intercept(new FileSystemMetaService(redissonClient), new FileSystemAuthInterceptor(redissonClient)); } }); serviceList.add(new FileSystemAuthService(redissonClient)); buildServer(port); } @Override protected List<BindableService> getServiceList() { return serviceList; } }
arkbriar/nju_ds_lab2
nodes/src/main/java/MasterNodeServer.java
Java
mit
1,660
function /*like here*/ * foo() { yield /*or here*/* [42]; }
Microsoft/TypeScript-TmLanguage
tests/cases/Issue572.ts
TypeScript
mit
65
<?php namespace WaddlingCo\StreamPerk\Bundle\ForumBundle\Repository; /** * ForumThreadRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ForumThreadRepository extends \Doctrine\ORM\EntityRepository { }
WaddlingCo/streamperk-bundle
ForumBundle/Repository/ForumThreadRepository.php
PHP
mit
276
from apscheduler.schedulers.blocking import BlockingScheduler from manage import update_live_points, update_for_gw, update_test, update_epl_players from tweetbot import TweetBot sched = BlockingScheduler() # @sched.scheduled_job('cron', day_of_week='wed-sun', hour='22', minute='50-59/1', timezone='America/New_York') # def test_job(): # update_test() # @sched.scheduled_job('cron', day_of_week='fri', hour='15', timezone='America/New_York') # def update_gw_data(): # update_for_gw() # @sched.scheduled_job('cron', day_of_week='fri', hour='15-17', minute='10-59/10', timezone='America/New_York') # def update_live(): # update_live_points() @sched.scheduled_job('cron', hour='20', minute='32', timezone='America/New_York') def update_gw_data(): update_epl_players() twt_bot = TweetBot() twt_bot.tweet_price_changes() @sched.scheduled_job('cron', day_of_week='sat', hour='9', timezone='America/New_York') def update_gw_data(): update_for_gw() @sched.scheduled_job('cron', day_of_week='sat-sun', hour='9-15', minute='10-59/10', timezone='America/New_York') def update_live(): update_live_points() sched.start()
code247/FPL_FFC
jobs.py
Python
mit
1,124
import React, { Component } from 'react' import { Modal, Button, message } from 'antd' import LinkSelect from '../../Resource/LinkSelect' import { BAIKE } from '../../../constants' class BaikeButton extends Component { constructor(props) { super(props) this.state = { visible: false, record: {} } this.toggleVisible = this.toggleVisible.bind(this) this.changeHandler = this.changeHandler.bind(this) this.okHandler = this.okHandler.bind(this) } toggleVisible() { this.setState(prevState => ({ visible: !prevState.visible })) } changeHandler(record) { this.setState({ record }) } okHandler() { if (this.state.record.id > 0) { this.props.okHandler(this.state.record) this.toggleVisible() } else { message.error('请选择一项!') } } render() { const { visible } = this.state return ( <Button style={{ marginLeft: '5px' }} onClick={this.toggleVisible}> <Modal visible={visible} title="选择百科" onOk={this.okHandler} onCancel={this.toggleVisible} maskClosable={false} width={720} > <LinkSelect category={BAIKE} onChange={this.changeHandler} /> </Modal> 添加百科</Button> ) } } export default BaikeButton
yiweimatou/admin-antd
src/components/ReactQuill/tool/bk.js
JavaScript
mit
1,612
from __future__ import absolute_import, division, print_function import warnings import re import py import pytest from _pytest.recwarn import WarningsRecorder def test_recwarn_functional(testdir): reprec = testdir.inline_runsource(""" import warnings def test_method(recwarn): warnings.warn("hello") warn = recwarn.pop() assert isinstance(warn.message, UserWarning) """) res = reprec.countoutcomes() assert tuple(res) == (1, 0, 0), res class TestWarningsRecorderChecker(object): def test_recording(self): rec = WarningsRecorder() with rec: assert not rec.list py.std.warnings.warn_explicit("hello", UserWarning, "xyz", 13) assert len(rec.list) == 1 py.std.warnings.warn(DeprecationWarning("hello")) assert len(rec.list) == 2 warn = rec.pop() assert str(warn.message) == "hello" l = rec.list rec.clear() assert len(rec.list) == 0 assert l is rec.list pytest.raises(AssertionError, "rec.pop()") def test_typechecking(self): from _pytest.recwarn import WarningsChecker with pytest.raises(TypeError): WarningsChecker(5) with pytest.raises(TypeError): WarningsChecker(('hi', RuntimeWarning)) with pytest.raises(TypeError): WarningsChecker([DeprecationWarning, RuntimeWarning]) def test_invalid_enter_exit(self): # wrap this test in WarningsRecorder to ensure warning state gets reset with WarningsRecorder(): with pytest.raises(RuntimeError): rec = WarningsRecorder() rec.__exit__(None, None, None) # can't exit before entering with pytest.raises(RuntimeError): rec = WarningsRecorder() with rec: with rec: pass # can't enter twice class TestDeprecatedCall(object): """test pytest.deprecated_call()""" def dep(self, i, j=None): if i == 0: py.std.warnings.warn("is deprecated", DeprecationWarning, stacklevel=1) return 42 def dep_explicit(self, i): if i == 0: py.std.warnings.warn_explicit("dep_explicit", category=DeprecationWarning, filename="hello", lineno=3) def test_deprecated_call_raises(self): with pytest.raises(AssertionError) as excinfo: pytest.deprecated_call(self.dep, 3, 5) assert 'Did not produce' in str(excinfo) def test_deprecated_call(self): pytest.deprecated_call(self.dep, 0, 5) def test_deprecated_call_ret(self): ret = pytest.deprecated_call(self.dep, 0) assert ret == 42 def test_deprecated_call_preserves(self): onceregistry = py.std.warnings.onceregistry.copy() filters = py.std.warnings.filters[:] warn = py.std.warnings.warn warn_explicit = py.std.warnings.warn_explicit self.test_deprecated_call_raises() self.test_deprecated_call() assert onceregistry == py.std.warnings.onceregistry assert filters == py.std.warnings.filters assert warn is py.std.warnings.warn assert warn_explicit is py.std.warnings.warn_explicit def test_deprecated_explicit_call_raises(self): with pytest.raises(AssertionError): pytest.deprecated_call(self.dep_explicit, 3) def test_deprecated_explicit_call(self): pytest.deprecated_call(self.dep_explicit, 0) pytest.deprecated_call(self.dep_explicit, 0) @pytest.mark.parametrize('mode', ['context_manager', 'call']) def test_deprecated_call_no_warning(self, mode): """Ensure deprecated_call() raises the expected failure when its block/function does not raise a deprecation warning. """ def f(): pass msg = 'Did not produce DeprecationWarning or PendingDeprecationWarning' with pytest.raises(AssertionError, matches=msg): if mode == 'call': pytest.deprecated_call(f) else: with pytest.deprecated_call(): f() @pytest.mark.parametrize('warning_type', [PendingDeprecationWarning, DeprecationWarning]) @pytest.mark.parametrize('mode', ['context_manager', 'call']) @pytest.mark.parametrize('call_f_first', [True, False]) @pytest.mark.filterwarnings('ignore') def test_deprecated_call_modes(self, warning_type, mode, call_f_first): """Ensure deprecated_call() captures a deprecation warning as expected inside its block/function. """ def f(): warnings.warn(warning_type("hi")) return 10 # ensure deprecated_call() can capture the warning even if it has already been triggered if call_f_first: assert f() == 10 if mode == 'call': assert pytest.deprecated_call(f) == 10 else: with pytest.deprecated_call(): assert f() == 10 @pytest.mark.parametrize('mode', ['context_manager', 'call']) def test_deprecated_call_exception_is_raised(self, mode): """If the block of the code being tested by deprecated_call() raises an exception, it must raise the exception undisturbed. """ def f(): raise ValueError('some exception') with pytest.raises(ValueError, match='some exception'): if mode == 'call': pytest.deprecated_call(f) else: with pytest.deprecated_call(): f() def test_deprecated_call_specificity(self): other_warnings = [Warning, UserWarning, SyntaxWarning, RuntimeWarning, FutureWarning, ImportWarning, UnicodeWarning] for warning in other_warnings: def f(): warnings.warn(warning("hi")) with pytest.raises(AssertionError): pytest.deprecated_call(f) with pytest.raises(AssertionError): with pytest.deprecated_call(): f() class TestWarns(object): def test_strings(self): # different messages, b/c Python suppresses multiple identical warnings source1 = "warnings.warn('w1', RuntimeWarning)" source2 = "warnings.warn('w2', RuntimeWarning)" source3 = "warnings.warn('w3', RuntimeWarning)" pytest.warns(RuntimeWarning, source1) pytest.raises(pytest.fail.Exception, lambda: pytest.warns(UserWarning, source2)) pytest.warns(RuntimeWarning, source3) def test_function(self): pytest.warns(SyntaxWarning, lambda msg: warnings.warn(msg, SyntaxWarning), "syntax") def test_warning_tuple(self): pytest.warns((RuntimeWarning, SyntaxWarning), lambda: warnings.warn('w1', RuntimeWarning)) pytest.warns((RuntimeWarning, SyntaxWarning), lambda: warnings.warn('w2', SyntaxWarning)) pytest.raises(pytest.fail.Exception, lambda: pytest.warns( (RuntimeWarning, SyntaxWarning), lambda: warnings.warn('w3', UserWarning))) def test_as_contextmanager(self): with pytest.warns(RuntimeWarning): warnings.warn("runtime", RuntimeWarning) with pytest.warns(UserWarning): warnings.warn("user", UserWarning) with pytest.raises(pytest.fail.Exception) as excinfo: with pytest.warns(RuntimeWarning): warnings.warn("user", UserWarning) excinfo.match(r"DID NOT WARN. No warnings of type \(.+RuntimeWarning.+,\) was emitted. " r"The list of emitted warnings is: \[UserWarning\('user',\)\].") with pytest.raises(pytest.fail.Exception) as excinfo: with pytest.warns(UserWarning): warnings.warn("runtime", RuntimeWarning) excinfo.match(r"DID NOT WARN. No warnings of type \(.+UserWarning.+,\) was emitted. " r"The list of emitted warnings is: \[RuntimeWarning\('runtime',\)\].") with pytest.raises(pytest.fail.Exception) as excinfo: with pytest.warns(UserWarning): pass excinfo.match(r"DID NOT WARN. No warnings of type \(.+UserWarning.+,\) was emitted. " r"The list of emitted warnings is: \[\].") warning_classes = (UserWarning, FutureWarning) with pytest.raises(pytest.fail.Exception) as excinfo: with pytest.warns(warning_classes) as warninfo: warnings.warn("runtime", RuntimeWarning) warnings.warn("import", ImportWarning) message_template = ("DID NOT WARN. No warnings of type {0} was emitted. " "The list of emitted warnings is: {1}.") excinfo.match(re.escape(message_template.format(warning_classes, [each.message for each in warninfo]))) def test_record(self): with pytest.warns(UserWarning) as record: warnings.warn("user", UserWarning) assert len(record) == 1 assert str(record[0].message) == "user" def test_record_only(self): with pytest.warns(None) as record: warnings.warn("user", UserWarning) warnings.warn("runtime", RuntimeWarning) assert len(record) == 2 assert str(record[0].message) == "user" assert str(record[1].message) == "runtime" def test_record_by_subclass(self): with pytest.warns(Warning) as record: warnings.warn("user", UserWarning) warnings.warn("runtime", RuntimeWarning) assert len(record) == 2 assert str(record[0].message) == "user" assert str(record[1].message) == "runtime" class MyUserWarning(UserWarning): pass class MyRuntimeWarning(RuntimeWarning): pass with pytest.warns((UserWarning, RuntimeWarning)) as record: warnings.warn("user", MyUserWarning) warnings.warn("runtime", MyRuntimeWarning) assert len(record) == 2 assert str(record[0].message) == "user" assert str(record[1].message) == "runtime" def test_double_test(self, testdir): """If a test is run again, the warning should still be raised""" testdir.makepyfile(''' import pytest import warnings @pytest.mark.parametrize('run', [1, 2]) def test(run): with pytest.warns(RuntimeWarning): warnings.warn("runtime", RuntimeWarning) ''') result = testdir.runpytest() result.stdout.fnmatch_lines(['*2 passed in*'])
MichaelAquilina/pytest
testing/test_recwarn.py
Python
mit
10,978
using System; using System.Collections.Generic; using System.Text; namespace stack_queue { class LinkedList { public Node head = new Node("head"); public Node FindTail() { Node curr = head; while (curr.Next != null) { curr = curr.Next; } Node last = curr.Prev; return curr; } public void Print() { Node curr = head; while(curr != null) { Console.Write("->"); Console.Write(curr.Data); curr = curr.Next; } Console.Write("->:end"); } } }
drkrieger1/data-structures
stack_queue/stack_queue/LinkedList.cs
C#
mit
772
<?php define('DS', '/'); define('ROOT', dirname(dirname(__FILE__))); $url = $_GET['url']; require_once (ROOT . DS . 'include' . DS . 'main.inc.php');
neinderthal/river
public/index.php
PHP
mit
157
from scudcloud.resources import Resources from PyQt5 import QtCore from PyQt5.QtCore import QUrl from PyQt5.QtWebKit import QWebSettings from PyQt5.QtWebKitWidgets import QWebView class LeftPane(QWebView): def __init__(self, window): QWebView.__init__(self) self.window = window with open(Resources.get_path("leftpane.js"), "r") as f: self.js = f.read() # We don't want plugins for this simple pane self.settings().setAttribute(QWebSettings.PluginsEnabled, False) self.reset() def reset(self): self.setFixedWidth(0) self.setVisible(False) self.setUrl(QUrl.fromLocalFile(Resources.get_path("leftpane.html"))) self.page().currentFrame().addToJavaScriptWindowObject("leftPane", self) self.page().currentFrame().evaluateJavaScript(self.js) def show(self): self.setFixedWidth(65) self.setVisible(True) def hide(self): self.setFixedWidth(0) self.setVisible(False) def addTeam(self, id, name, url, icon, active=False): if active is True: checked = "true" else: checked = "false" self.page().currentFrame().evaluateJavaScript('LeftPane.addTeam("{}","{}","{}","{}","{}");'.format(id, name, url, icon, checked)) def click(self, i): self.page().currentFrame().evaluateJavaScript('LeftPane.click({});'.format(i)) def alert(self, teamId, messages): if teamId is not None: self.page().currentFrame().evaluateJavaScript('LeftPane.alert("{}","{}");'.format(teamId, messages)) def unread(self, teamId): self.page().currentFrame().evaluateJavaScript('LeftPane.unread("{}");'.format(teamId)) def stopAlert(self, team): if team is not None: self.page().currentFrame().evaluateJavaScript('LeftPane.stopAlert("{}");'.format(team)) def stopUnread(self, teamId): self.page().currentFrame().evaluateJavaScript('LeftPane.stopUnread("{}");'.format(teamId)) def clickNext(self, direction): self.page().currentFrame().evaluateJavaScript('LeftPane.clickNext("{}");'.format(direction)) @QtCore.pyqtSlot(str) def switchTo(self, url): self.window.switchTo(url) def contextMenuEvent(self, event): if self.window.debug: menu = self.page().createStandardContextMenu() menu.exec_(event.globalPos())
raelgc/scudcloud
scudcloud/leftpane.py
Python
mit
2,425
<section class="content"> <?php echo form_open_multipart( site_url('/admin/save_room'), array( 'class' => 'admin-form' ), array( 'id' => isset($room->id)? $room->id : null ) ); ?> <?php echo foundation_form_input( 'number', array( 'default_value' => isset($room->number)? $room->number : null ) ); ?> <?php echo foundation_form_input( 'name', array( 'default_value' => isset($room->name)? $room->name : null ) ); ?> <?php echo foundation_form_input( 'rate', array( 'default_value' => isset($room->rate)? $room->rate : null ) ); ?> <?php echo foundation_form_input( 'description' , array( 'as' => 'text', 'default_value' => isset($room->description)? $room->description : null ) ); ?> <?php if( isset($room->image) ) : ?> <label>Current Featured Image</label> <img src="<?php echo uploads_url($room->image); ?>" /> <label>Upload New Featured Image <input type="file" name="image" /></label> <?php else : ?> <label>Upload Featured Image <input type="file" name="image" /></label> <?php endif; ?> <?php echo form_submit( array( 'class' => 'button' ), 'Submit' ) ?> <?php echo form_close(); ?> </section> <script src="//cdn.ckeditor.com/4.4.5/standard/ckeditor.js"></script> <script> CKEDITOR.replace( 'description' , { filebrowserImageUploadUrl: '../../../uploader.php' }); </script>
chloereimer/sleepy-me-hotel
application/views/admin/room_form.php
PHP
mit
1,360
require "yml_object/version" require 'yaml' module YmlObject def self.say_hi 'Hi' end def self.load(file_path) YmlObject::Object.new(YAML.load_file(file_path)) end class Object def initialize(yml_hash) @my_object = yml_hash end def method_missing(method_name, *args, &block) if @my_object.include?(method_name.to_s) value = @my_object[method_name.to_s] if value.class == Hash value = YmlObject::Object.new value end return value end super(method_name, *args, &block) end end end
JasonHeylon/yml_object
lib/yml_object.rb
Ruby
mit
584
$(document).ready(function(){ $('#px-product-product_list-form').validate({ rules: { name: { required: true }, product_category_id: { required: true }, price: { required: true }, special_product: { required: true } }, submitHandler: function(form) { var target = $(form).attr('action'); $('#px-product-product_list-form .alert-warning').removeClass('hidden'); $('#px-product-product_list-form .alert-success').addClass('hidden'); $('#px-product-product_list-form .alert-danger').addClass('hidden'); $('.px-summernote').each(function() { $(this).val($(this).code()); }); $.ajax({ url : target, type : 'POST', dataType : 'json', data : $(form).serialize(), success : function(response){ $('#px-product-product_list-form .alert-warning').addClass('hidden'); if(response.status == 'ok'){ $('#px-product-product_list-form .alert-success').removeClass('hidden').children('span').text(response.msg); window.location.href = response.redirect; } else $('#px-product-product_list-form .alert-danger').removeClass('hidden').children('span').text(response.msg); }, error : function(jqXHR, textStatus, errorThrown) { alert(textStatus, errorThrown); } }); } }); $('#px-product-product_list-form-short_description,#px-product-product_list-form-description,#px-product-product_list-form-specification').summernote({ toolbar: [ ['font', ['bold', 'italic', 'underline', 'clear']], ['insert', ['link']] ], height: '50px' }); })
ilhamudzakir/hijab-master
assets/backend_assets/page/product/product_list_form.js
JavaScript
mit
1,683
<?php namespace Pcic; use Exception; class PcicException extends Exception {};
guojikai/captcha-image-creator
src/PcicException.php
PHP
mit
83
 using System.Collections.Generic; namespace PortableRSS.Interfaces { public interface IChannel { string Title { set; get; } string Link { set; get; } string Description { set; get; } string Language { set; get; } string Copyright { set; get; } string PubDate { set; get; } string LastBuildDate { set; get; } string Category { set; get; } string Generator { set; get; } string TTL { set; get; } IImage Image { set; get; } IList<IItem> Items { set; get; } } }
waltersoto/PortableRSS
PortableRSS/Interfaces/IChannel.cs
C#
mit
571
<?php use Mouf\Mvc\Splash\Controllers\HttpErrorsController; use Mouf\Mvc\Splash\Utils\ExceptionUtils; /* @var $this HttpErrorsController */ ?> <h1>An error occured</h1> <div>An error occured in the application. Please try again, or contact an administrator.</div> <?php if ($this->debugMode) { echo '<div>'.nl2br($this->exception->getMessage()).'</div>'; echo '<div>'.ExceptionUtils::getHtmlForException($this->exception).'</div>'; } ?>
thecodingmachine/mvc.splash-common
src/views/500.php
PHP
mit
448