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
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Extensions { public static class IEnumerableExtensions { public static T Sum<T>(this IEnumerable<T> enumerable) { dynamic sum = 0; foreach (var element in enumerable) { sum += element; } return sum; } public static T Product<T>(this IEnumerable<T> enumerable) { dynamic Prod = 1; foreach (var element in enumerable) { Prod *= element; } return Prod; } public static T Min<T>(this IEnumerable<T> enumerable) where T : IComparable<T> { T result = enumerable.First(); foreach (var element in enumerable) { if (result.CompareTo(element) > 0) { result = element; } } return result; } public static T Max<T>(this IEnumerable<T> enumerable) where T : IComparable<T> { T result = enumerable.First(); foreach (var element in enumerable) { if (result.CompareTo(element) < 0) { result = element; } } return result; } public static T Average<T>(this IEnumerable<T> enumerable) { return (dynamic)enumerable.Sum() / enumerable.Count(); } } }
SHAMMY1/Telerik-Academy-2016
OOP/Homeworks/03.ExtensionsDelegatesLambda/ExtensionsDelegatesLambdaHW/Extensions/IEnumerableExtensions.cs
C#
mit
1,214
using System; using System.Collections; using UnityEngine; using VRStandardAssets.Common; using VRStandardAssets.Utils; namespace VRStandardAssets.ShootingGallery { // This script handles a target in the shooter scenes. // It includes what should happen when it is hit and // how long before it despawns. public class ShootingTarget : MonoBehaviour { public event Action<ShootingTarget> OnRemove; // This event is triggered when the target needs to be removed. [SerializeField] private int m_Score = 1; // This is the amount added to the users score when the target is hit. [SerializeField] private float m_TimeOutDuration = 2f; // How long the target lasts before it disappears. [SerializeField] private float m_DestroyTimeOutDuration = 2f; // When the target is hit, it shatters. This is how long before the shattered pieces disappear. [SerializeField] private GameObject m_DestroyPrefab; // The prefab for the shattered target. [SerializeField] private AudioClip m_DestroyClip; // The audio clip to play when the target shatters. [SerializeField] private AudioClip m_SpawnClip; // The audio clip that plays when the target appears. [SerializeField] private AudioClip m_MissedClip; // The audio clip that plays when the target disappears without being hit. private Transform m_CameraTransform; // Used to make sure the target is facing the camera. private VRInteractiveItem m_InteractiveItem; // Used to handle the user clicking whilst looking at the target. private AudioSource m_Audio; // Used to play the various audio clips. private Renderer m_Renderer; // Used to make the target disappear before it is removed. private Collider m_Collider; // Used to make sure the target doesn't interupt other shots happening. private bool m_IsEnding; // Whether the target is currently being removed by another source. private void Awake() { // Setup the references. m_CameraTransform = Camera.main.transform; m_Audio = GetComponent<AudioSource> (); m_InteractiveItem = GetComponent<VRInteractiveItem>(); m_Renderer = GetComponent<Renderer>(); m_Collider = GetComponent<Collider>(); } private void OnEnable () { m_InteractiveItem.OnDown += HandleDown; } private void OnDisable () { m_InteractiveItem.OnDown -= HandleDown; } private void OnDestroy() { // Ensure the event is completely unsubscribed when the target is destroyed. OnRemove = null; } public void Restart (float gameTimeRemaining) { // When the target is spawned turn the visual and physical aspects on. m_Renderer.enabled = true; m_Collider.enabled = true; // Since the target has just spawned, it's not ending yet. m_IsEnding = false; // Play the spawn clip. m_Audio.clip = m_SpawnClip; m_Audio.Play(); // Make sure the target is facing the camera. transform.LookAt(m_CameraTransform); // Start the time out for when the target would naturally despawn. StartCoroutine (MissTarget()); // Start the time out for when the game ends. // Note this will only come into effect if the game time remaining is less than the time out duration. StartCoroutine (GameOver (gameTimeRemaining)); } private IEnumerator MissTarget() { // Wait for the target to disappear naturally. yield return new WaitForSeconds (m_TimeOutDuration); // If by this point it's already ending, do nothing else. if(m_IsEnding) yield break; // Otherwise this is ending the target's lifetime. m_IsEnding = true; // Turn off the visual and physical aspects. m_Renderer.enabled = false; m_Collider.enabled = false; // Play the clip of the target being missed. m_Audio.clip = m_MissedClip; m_Audio.Play(); // Wait for the clip to finish. yield return new WaitForSeconds(m_MissedClip.length); // Tell subscribers that this target is ready to be removed. if (OnRemove != null) OnRemove(this); } private IEnumerator GameOver (float gameTimeRemaining) { // Wait for the game to end. yield return new WaitForSeconds (gameTimeRemaining); // If by this point it's already ending, do nothing else. if(m_IsEnding) yield break; // Otherwise this is ending the target's lifetime. m_IsEnding = true; // Turn off the visual and physical aspects. m_Renderer.enabled = false; m_Collider.enabled = false; // Tell subscribers that this target is ready to be removed. if (OnRemove != null) OnRemove (this); } private void HandleDown() { // If it's already ending, do nothing else. if (m_IsEnding) return; // Otherwise this is ending the target's lifetime. m_IsEnding = true; // Turn off the visual and physical aspects. m_Renderer.enabled = false; m_Collider.enabled = false; // Play the clip of the target being hit. m_Audio.clip = m_DestroyClip; m_Audio.Play(); // Add to the player's score. SessionData.AddScore(m_Score); // Instantiate the shattered target prefab in place of this target. GameObject destroyedTarget = Instantiate(m_DestroyPrefab, transform.position, transform.rotation) as GameObject; // Destroy the shattered target after it's time out duration. Destroy(destroyedTarget, m_DestroyTimeOutDuration); // Tell subscribers that this target is ready to be removed. if (OnRemove != null) OnRemove(this); } } }
SerKale/voxyl
Voxyl/Assets/VRSampleScenes/Scripts/ShootingGallery/ShootingTarget.cs
C#
mit
6,853
//@flow const {foo, Bar, baz, qux} = require('./jsdoc-exports'); const { DefaultedStringEnum, InitializedStringEnum, NumberEnum, BooleanEnum, SymbolEnum, } = require('./jsdoc-objects'); /** a JSDoc in the same file */ function x() {} ( ); // ^
mroch/flow
tests/autocomplete/jsdoc.js
JavaScript
mit
261
ace.define("ace/mode/tex_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var TexHighlightRules = function(textClass) { if (!textClass) textClass = "text"; this.$rules = { "start" : [ { token : "comment", regex : "%.*$" }, { token : textClass, // non-command regex : "\\\\[$&%#\\{\\}]" }, { token : "keyword", // command regex : "\\\\(?:documentclass|usepackage|newcounter|setcounter|addtocounter|value|arabic|stepcounter|newenvironment|renewenvironment|ref|vref|eqref|pageref|label|cite[a-zA-Z]*|tag|begin|end|bibitem)\\b", next : "nospell" }, { token : "keyword", // command regex : "\\\\(?:[a-zA-Z0-9]+|[^a-zA-Z0-9])" }, { token : "paren.keyword.operator", regex : "[[({]" }, { token : "paren.keyword.operator", regex : "[\\])}]" }, { token : textClass, regex : "\\s+" } ], "nospell" : [ { token : "comment", regex : "%.*$", next : "start" }, { token : "nospell." + textClass, // non-command regex : "\\\\[$&%#\\{\\}]" }, { token : "keyword", // command regex : "\\\\(?:documentclass|usepackage|newcounter|setcounter|addtocounter|value|arabic|stepcounter|newenvironment|renewenvironment|ref|vref|eqref|pageref|label|cite[a-zA-Z]*|tag|begin|end|bibitem)\\b" }, { token : "keyword", // command regex : "\\\\(?:[a-zA-Z0-9]+|[^a-zA-Z0-9])", next : "start" }, { token : "paren.keyword.operator", regex : "[[({]" }, { token : "paren.keyword.operator", regex : "[\\])]" }, { token : "paren.keyword.operator", regex : "}", next : "start" }, { token : "nospell." + textClass, regex : "\\s+" }, { token : "nospell." + textClass, regex : "\\w+" } ] }; }; oop.inherits(TexHighlightRules, TextHighlightRules); exports.TexHighlightRules = TexHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/tex",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/text_highlight_rules","ace/mode/tex_highlight_rules","ace/mode/matching_brace_outdent"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var TexHighlightRules = require("./tex_highlight_rules").TexHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Mode = function(suppressHighlighting) { if (suppressHighlighting) this.HighlightRules = TextHighlightRules; else this.HighlightRules = TexHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = this.$defaultBehaviour; }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "%"; this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.allowAutoInsert = function() { return false; }; this.$id = "ace/mode/tex"; }).call(Mode.prototype); exports.Mode = Mode; }); (function() { ace.require(["ace/mode/tex"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
NPellet/jsGraph
web/site/js/ace-builds/src-noconflict/mode-tex.js
JavaScript
mit
5,261
module Hello module Business module Management class ResetPassword < Base attr_reader :password_credential def initialize(password_credential) @password_credential = password_credential end def update_password(plain_text_password) if @password_credential.update(password: plain_text_password) @password_credential.reset_verifying_token! return true else merge_errors_to_self return false end end def user password_credential.user end private def merge_errors_to_self hash = @password_credential.errors.to_hash hash.each { |k, v| v.each { |v1| errors.add(k, v1) } } end end end end end
brodock/hello
lib/hello/business/management/reset_password.rb
Ruby
mit
812
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2016 // by DotNetNuke Corporation // // 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. #endregion #region Usings using Telerik.Web.UI; #endregion namespace DotNetNuke.Web.UI.WebControls { public class DnnInputManager : RadInputManager { } }
yiji/Dnn.Platform
DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnInputManager.cs
C#
mit
1,363
(function(){ 'use strict'; angular .module('app') .factory('ceUsers', ceUsers); ceUsers.$inject = ['$resource']; function ceUsers ($resource) { console.log('ok'); return $resource('https://mysterious-eyrie-9135.herokuapp.com/users/:username', {username: '@username'}, {'update': { method: 'PUT'}} ); } })();
ArnaudBertrand/CookeasyWeb
src/app/resources/users.resource.js
JavaScript
mit
351
<?php /** * Version : 1.2.0 * Author : inc2734 * Author URI : http://2inc.org * Created : April 17, 2015 * Modified : July 31, 2015 * License : GPLv2 or later * License URI: license.txt */ ?> <div class="container"> <div class="row"> <div class="col-md-9"> <main id="main" role="main"> <?php Habakiri::the_bread_crumb(); ?> <?php $name = ( is_search() ) ? 'search' : 'archive'; get_template_part( 'content', $name ); ?> <!-- end #main --></main> <!-- end .col-md-9 --></div> <div class="col-md-3"> <?php get_sidebar(); ?> <!-- end .col-md-3 --></div> <!-- end .row --></div> <!-- end .container --></div>
OopsMouse/mori.site
www/wordpress/wp-content/themes/habakiri/blog_templates/archive/right-sidebar.php
PHP
mit
670
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Db * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $ */ /** * Zend_Exception */ /** * @category Zend * @package Zend_Db * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Db_Exception extends Zend_Exception { }
musicsnap/LearnCode
php/code/yaf/application/library/Zend/Db/Exception.php
PHP
mit
1,039
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using Newtonsoft.Json.Linq; using ReactNative.Bridge; using System; using System.Threading; using System.Threading.Tasks; namespace ReactNative.Tests.Bridge { [TestClass] public class ReactInstanceTests { [TestMethod] public async Task ReactInstance_GetModules() { var module = new TestNativeModule(); var reactContext = new ReactContext(); var registry = new NativeModuleRegistry.Builder(reactContext) .Add(module) .Build(); var executor = new MockJavaScriptExecutor { OnCallFunctionReturnFlushedQueue = (_, __, ___) => JValue.CreateNull(), OnFlushQueue = () => JValue.CreateNull(), OnInvokeCallbackAndReturnFlushedQueue = (_, __) => JValue.CreateNull() }; var builder = new ReactInstance.Builder() { QueueConfiguration = TestReactQueueConfiguration.Create(_ => { }), Registry = registry, JavaScriptExecutorFactory = () => executor, BundleLoader = JavaScriptBundleLoader.CreateFileLoader("ms-appx:///Resources/test.js"), }; var instance = await DispatcherHelpers.CallOnDispatcherAsync(() => builder.Build()); reactContext.InitializeWithInstance(instance); var actualModule = instance.GetNativeModule<TestNativeModule>(); Assert.AreSame(module, actualModule); var firstJSModule = instance.GetJavaScriptModule<TestJavaScriptModule>(); var secondJSModule = instance.GetJavaScriptModule<TestJavaScriptModule>(); Assert.AreSame(firstJSModule, secondJSModule); await DispatcherHelpers.CallOnDispatcherAsync(instance.DisposeAsync); } [TestMethod] public async Task ReactInstance_Initialize_Dispose() { var mre = new ManualResetEvent(false); var module = new TestNativeModule { OnInitialized = () => mre.Set(), }; var reactContext = new ReactContext(); var registry = new NativeModuleRegistry.Builder(reactContext) .Add(module) .Build(); var executor = new MockJavaScriptExecutor { OnCallFunctionReturnFlushedQueue = (_, __, ___) => JValue.CreateNull(), OnFlushQueue = () => JValue.CreateNull(), OnInvokeCallbackAndReturnFlushedQueue = (_, __) => JValue.CreateNull() }; var builder = new ReactInstance.Builder() { QueueConfiguration = TestReactQueueConfiguration.Create(_ => { }), Registry = registry, JavaScriptExecutorFactory = () => executor, BundleLoader = JavaScriptBundleLoader.CreateFileLoader("ms-appx:///Resources/test.js"), }; var instance = await DispatcherHelpers.CallOnDispatcherAsync(() => builder.Build()); reactContext.InitializeWithInstance(instance); await DispatcherHelpers.CallOnDispatcherAsync(async () => await instance.InitializeAsync()); var caught = false; await DispatcherHelpers.CallOnDispatcherAsync(async () => { try { await instance.InitializeAsync(); } catch (InvalidOperationException) { caught = true; } }); Assert.IsTrue(caught); mre.WaitOne(); Assert.AreEqual(1, module.InitializeCalls); await DispatcherHelpers.CallOnDispatcherAsync(instance.DisposeAsync); Assert.AreEqual(1, module.OnReactInstanceDisposeCalls); // Dispose is idempotent await DispatcherHelpers.CallOnDispatcherAsync(instance.DisposeAsync); Assert.AreEqual(1, module.OnReactInstanceDisposeCalls); Assert.IsTrue(instance.IsDisposed); } [TestMethod] public async Task ReactInstance_ExceptionHandled_DoesNotDispose() { var eventHandler = new AutoResetEvent(false); var module = new OnDisposeNativeModule(() => eventHandler.Set()); var registry = new NativeModuleRegistry.Builder(new ReactContext()) .Add(module) .Build(); var executor = new MockJavaScriptExecutor { OnCallFunctionReturnFlushedQueue = (_, __, ___) => JValue.CreateNull(), OnFlushQueue = () => JValue.CreateNull(), OnInvokeCallbackAndReturnFlushedQueue = (_, __) => JValue.CreateNull() }; var exception = new Exception(); var tcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously); var builder = new ReactInstance.Builder() { QueueConfiguration = TestReactQueueConfiguration.Create(tcs.SetResult), Registry = registry, JavaScriptExecutorFactory = () => executor, BundleLoader = JavaScriptBundleLoader.CreateFileLoader("ms-appx:///Resources/test.js"), }; var instance = await DispatcherHelpers.CallOnDispatcherAsync(() => builder.Build()); instance.QueueConfiguration.JavaScriptQueue.Dispatch(() => { throw exception; }); var actualException = await tcs.Task; Assert.AreSame(exception, actualException); Assert.IsFalse(eventHandler.WaitOne(500)); Assert.IsFalse(instance.IsDisposed); } class TestNativeModule : NativeModuleBase { public Action OnInitialized { get; set; } public int InitializeCalls { get; set; } public int OnReactInstanceDisposeCalls { get; set; } public override string Name { get { return "Test"; } } public override void Initialize() { InitializeCalls++; OnInitialized?.Invoke(); } public override Task OnReactInstanceDisposeAsync() { OnReactInstanceDisposeCalls++; return Task.CompletedTask; } } class OnDisposeNativeModule : NativeModuleBase { private readonly Action _onDispose; public OnDisposeNativeModule(Action onDispose) { _onDispose = onDispose; } public override string Name { get { return "Test"; } } public override Task OnReactInstanceDisposeAsync() { _onDispose(); return Task.CompletedTask; } } class TestJavaScriptModule : JavaScriptModuleBase { } } }
bluejeans/react-native-windows
ReactWindows/ReactNative.Tests/Bridge/ReactInstanceTests.cs
C#
mit
7,510
using System; using Machine.Specifications; namespace FactoryGirl.NET.Specs { [Subject(typeof(FactoryGirl))] public class FactoryGirlSpecs : ICleanupAfterEveryContextInAssembly { [Subject(typeof(FactoryGirl))] public class When_we_define_a_factory { Establish context = () => { }; Because of = () => FactoryGirl.Define(() => new Dummy()); It should_contain_the_definition = () => FactoryGirl.DefinedFactories.ShouldContain(typeof(Dummy)); } [Subject(typeof(FactoryGirl))] public class When_a_factory_has_been_defined { Establish context = () => FactoryGirl.Define(() => new Dummy()); [Subject(typeof(FactoryGirl))] public class When_we_define_the_same_factory_again { Because of = () => exception = Catch.Exception(() => FactoryGirl.Define(() => new Dummy())); It should_throw_a_DuplicateFactoryException = () => exception.ShouldBeOfType<DuplicateFactoryException>(); static Exception exception; } [Subject(typeof(FactoryGirl))] public class When_we_build_a_default_object { Because of = () => builtObject = FactoryGirl.Build<Dummy>(); It should_build_the_object = () => builtObject.ShouldNotBeNull(); It should_assign_the_default_value_for_the_property = () => builtObject.Value.ShouldEqual(Dummy.DefaultValue); static Dummy builtObject; } [Subject(typeof(FactoryGirl))] public class When_we_build_a_customized_object { Because of = () => builtObject = FactoryGirl.Build<Dummy>(x => x.Value = 42); It should_update_the_specified_value = () => builtObject.Value.ShouldEqual(42); static Dummy builtObject; } } public void AfterContextCleanup() { FactoryGirl.ClearFactoryDefinitions(); } } }
junshao/FactoryGirl.NET
FactoryGirl.NET.Specs/FactoryGirlSpecs.cs
C#
mit
2,054
""" A Pygments lexer for Magpie. """ from setuptools import setup __author__ = 'Robert Nystrom' setup( name='Magpie', version='1.0', description=__doc__, author=__author__, packages=['magpie'], entry_points=''' [pygments.lexers] magpielexer = magpie:MagpieLexer ''' )
munificent/magpie-optionally-typed
doc/site/magpie/setup.py
Python
mit
305
'use strict'; import gulp from 'gulp'; import gutil from 'gulp-util'; import uglify from 'gulp-uglify'; import stylus from 'gulp-stylus'; import watch from 'gulp-watch'; import plumber from 'gulp-plumber'; import cleanCss from 'gulp-clean-css'; import imagemin from 'gulp-imagemin'; import concat from 'gulp-concat'; import babel from 'gulp-babel'; // Minificação dos arquivos .js gulp.task('minjs', () => { return gulp // Define a origem dos arquivos .js .src(['src/js/**/*.js']) // Prevençãao de erros .pipe(plumber()) // Suporte para o padrão ES6 .pipe(babel({ presets: ['es2015'] })) // Realiza minificação .pipe(uglify()) // Altera a extenção do arquivo .pipe(concat('app.min.js')) // Salva os arquivos minificados na pasta de destino .pipe(gulp.dest('dist/js')); }); gulp.task('stylus', () => { return gulp // Define a origem dos arquivos .scss .src('src/stylus/**/*.styl') // Prevençãao de erros .pipe(plumber()) // Realiza o pré-processamento para css .pipe(stylus()) // Realiza a minificação do css .pipe(cleanCss()) // Altera a extenção do arquivo .pipe(concat('style.min.css')) // Salva os arquivos processados na pasta de destino .pipe(gulp.dest('dist/css')); }); gulp.task('images', () => gulp.src('src/assets/*') .pipe(imagemin()) .pipe(gulp.dest('dist/assets')) ); gulp.task('watch', function() { gulp.start('default') gulp.watch('src/js/**/*.js', ['minjs']) gulp.watch('src/stylus/**/*.styl', ['stylus']) gulp.watch('src/assets/*', ['images']) }); gulp.task('default', ['minjs', 'stylus', 'images']);
davidalves1/missas-sao-pedro
gulpfile.babel.js
JavaScript
mit
1,796
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateEveCorporationMemberSecurityLog extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('corporation_msec_log', function(Blueprint $table) { $table->increments('id'); $table->integer('corporationID'); $table->integer('characterID'); $table->string('characterName'); $table->dateTime('changeTime'); $table->integer('issuerID'); $table->string('issuerName'); $table->string('roleLocationType'); $table->string('hash')->unique(); // Indexes $table->index('characterID'); $table->index('corporationID'); $table->index('hash'); $table->timestamps(); }); } // changeTime,characterID,issuerID,roleLocationType /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('corporation_msec_log'); } }
omgninjaz/seat
app/database/migrations/2014_04_03_071610_CreateEveCorporationMemberSecurityLog.php
PHP
mit
959
require 'shellwords' require 'fileutils' module Hibiki class Downloading CH_NAME = 'hibiki' def initialize @a = Mechanize.new @a.user_agent_alias = 'Windows Chrome' end def download(program) infos = get_infos(program) if infos['episode']['id'] != program.episode_id Rails.logger.error("episode outdated. title=#{program.title} expected_episode_id=#{program.episode_id} actual_episode_id=#{infos['episode']['id']}") program.state = HibikiProgramV2::STATE[:outdated] return end live_flg = infos['episode'].try(:[], 'video').try(:[], 'live_flg') if live_flg == nil || live_flg == true program.state = HibikiProgramV2::STATE[:not_downloadable] return end url = get_m3u8_url(infos['episode']['video']['id']) unless download_hls(program, url) program.state = HibikiProgramV2::STATE[:failed] return end program.state = HibikiProgramV2::STATE[:done] end def get_infos(program) res = get_api("https://vcms-api.hibiki-radio.jp/api/v1/programs/#{program.access_id}") infos = JSON.parse(res.body) end def get_m3u8_url(video_id) res = get_api("https://vcms-api.hibiki-radio.jp/api/v1/videos/play_check?video_id=#{video_id}") play_infos = JSON.parse(res.body) play_infos['playlist_url'] end def download_hls(program, m3u8_url) file_path = Main::file_path_working(CH_NAME, title(program), 'mp4') arg = "\ -loglevel error \ -y \ -i #{Shellwords.escape(m3u8_url)} \ -vcodec copy -acodec copy -bsf:a aac_adtstoasc \ #{Shellwords.escape(file_path)}" Main::prepare_working_dir(CH_NAME) exit_status, output = Main::ffmpeg(arg) unless exit_status.success? Rails.logger.error "rec failed. program:#{program}, exit_status:#{exit_status}, output:#{output}" return false end if output.present? Rails.logger.warn "hibiki ffmpeg command:#{arg} output:#{output}" end Main::move_to_archive_dir(CH_NAME, program.created_at, file_path) true end def get_api(url) @a.get( url, [], "http://hibiki-radio.jp/", 'X-Requested-With' => 'XMLHttpRequest', 'Origin' => 'http://hibiki-radio.jp' ) end def title(program) date = program.created_at.strftime('%Y_%m_%d') title = "#{date}_#{program.title}_#{program.episode_name}" if program.cast.present? cast = program.cast.gsub(',', ' ') title += "_#{cast}" end title end end end
t-ashula/net-radio-archive
lib/hibiki/downloading.rb
Ruby
mit
2,639
<?xml version="1.0" ?><!DOCTYPE TS><TS language="bs" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About buynowcoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;buynowcoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The buynowcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your buynowcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a buynowcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified buynowcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>buynowcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show information about buynowcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a buynowcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for buynowcoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-202"/> <source>buynowcoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+180"/> <source>&amp;About buynowcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+60"/> <source>buynowcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to buynowcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About buynowcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about buynowcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid buynowcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. buynowcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid buynowcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>buynowcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start buynowcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start buynowcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the buynowcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the buynowcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting buynowcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show buynowcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting buynowcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the buynowcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the buynowcoin-Qt help message to get a list with possible buynowcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>buynowcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>buynowcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the buynowcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the buynowcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 BTC</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a buynowcoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid buynowcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a buynowcoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this buynowcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified buynowcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a buynowcoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter buynowcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Sve</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Danas</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ovaj mjesec</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Prošli mjesec</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ove godine</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>buynowcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to -server or buynowcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify configuration file (default: buynowcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: buynowcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong buynowcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=buynowcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;buynowcoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. buynowcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>buynowcoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of buynowcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart buynowcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. buynowcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
buynowcoin/buynowcoin
src/qt/locale/bitcoin_bs.ts
TypeScript
mit
108,053
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M21 17h-1v-6c0-1.1-.9-2-2-2H7v-.74c0-.46-.56-.7-.89-.37L4.37 9.63c-.2.2-.2.53 0 .74l1.74 1.74c.33.33.89.1.89-.37V11h4v3H5c-.55 0-1 .45-1 1v2c0 1.1.9 2 2 2h2c0 1.66 1.34 3 3 3s3-1.34 3-3h7c.55 0 1-.45 1-1s-.45-1-1-1zm-10 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm7-6h-4v-3h3c.55 0 1 .45 1 1v2zm-8-8h7v.74c0 .46.56.7.89.37l1.74-1.74c.2-.2.2-.53 0-.74l-1.74-1.74c-.33-.33-.89-.1-.89.37V4h-7c-.55 0-1 .45-1 1s.45 1 1 1z" }), 'RvHookupRounded'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/RvHookupRounded.js
JavaScript
mit
894
import { set } from 'ember-metal'; import { jQuery } from 'ember-views'; import { moduleFor, RenderingTest } from '../../utils/test-case'; import { Component, compile } from '../../utils/helpers'; import { strip } from '../../utils/abstract-test-case'; class AbstractAppendTest extends RenderingTest { constructor() { super(); this.components = []; this.ids = []; } teardown() { this.component = null; this.components.forEach(component => { this.runTask(() => component.destroy()); }); this.ids.forEach(id => { let $element = jQuery(id).remove(); this.assert.strictEqual($element.length, 0, `Should not leak element: #${id}`); }); super(); } /* abstract append(component): Element; */ didAppend(component) { this.components.push(component); this.ids.push(component.elementId); } ['@test lifecycle hooks during component append'](assert) { let hooks = []; let oldRegisterComponent = this.registerComponent; let componentsByName = {}; // TODO: refactor/combine with other life-cycle tests this.registerComponent = function(name, _options) { function pushHook(hookName) { hooks.push([name, hookName]); } let options = { ComponentClass: _options.ComponentClass.extend({ init() { expectDeprecation(() => { this._super(...arguments); }, /didInitAttrs called/); if (name in componentsByName) { throw new TypeError('Component named: ` ' + name + ' ` already registered'); } componentsByName[name] = this; pushHook('init'); this.on('init', () => pushHook('on(init)')); }, didInitAttrs(options) { pushHook('didInitAttrs', options); }, didReceiveAttrs() { pushHook('didReceiveAttrs'); }, willInsertElement() { pushHook('willInsertElement'); }, willRender() { pushHook('willRender'); }, didInsertElement() { pushHook('didInsertElement'); }, didRender() { pushHook('didRender'); }, didUpdateAttrs() { pushHook('didUpdateAttrs'); }, willUpdate() { pushHook('willUpdate'); }, didUpdate() { pushHook('didUpdate'); }, willDestroyElement() { pushHook('willDestroyElement'); }, willClearRender() { pushHook('willClearRender'); }, didDestroyElement() { pushHook('didDestroyElement'); }, willDestroy() { pushHook('willDestroy'); this._super(...arguments); } }), template: _options.template }; oldRegisterComponent.call(this, name, options); }; this.registerComponent('x-parent', { ComponentClass: Component.extend({ layoutName: 'components/x-parent' }), template: '[parent: {{foo}}]{{#x-child bar=foo}}[yielded: {{foo}}]{{/x-child}}' }); this.registerComponent('x-child', { ComponentClass: Component.extend({ tagName: '' }), template: '[child: {{bar}}]{{yield}}' }); let XParent = this.owner._lookupFactory('component:x-parent'); this.component = XParent.create({ foo: 'zomg' }); assert.deepEqual(hooks, [ ['x-parent', 'init'], ['x-parent', 'didInitAttrs'], ['x-parent', 'didReceiveAttrs'], ['x-parent', 'on(init)'] ], 'creation of x-parent'); hooks.length = 0; this.element = this.append(this.component); assert.deepEqual(hooks, [ ['x-parent', 'willInsertElement'], ['x-child', 'init'], ['x-child', 'didInitAttrs'], ['x-child', 'didReceiveAttrs'], ['x-child', 'on(init)'], ['x-child', 'willRender'], ['x-child', 'willInsertElement'], ['x-child', 'didInsertElement'], ['x-child', 'didRender'], ['x-parent', 'didInsertElement'], ['x-parent', 'didRender'] ], 'appending of x-parent'); hooks.length = 0; this.runTask(() => componentsByName['x-parent'].rerender()); assert.deepEqual(hooks, [ ['x-parent', 'willUpdate'], ['x-parent', 'willRender'], ['x-parent', 'didUpdate'], ['x-parent', 'didRender'] ], 'rerender x-parent'); hooks.length = 0; this.runTask(() => componentsByName['x-child'].rerender()); assert.deepEqual(hooks, [ ['x-parent', 'willUpdate'], ['x-parent', 'willRender'], ['x-child', 'willUpdate'], ['x-child', 'willRender'], ['x-child', 'didUpdate'], ['x-child', 'didRender'], ['x-parent', 'didUpdate'], ['x-parent', 'didRender'] ], 'rerender x-child'); hooks.length = 0; this.runTask(() => set(this.component, 'foo', 'wow')); assert.deepEqual(hooks, [ ['x-parent', 'willUpdate'], ['x-parent', 'willRender'], ['x-child', 'didUpdateAttrs'], ['x-child', 'didReceiveAttrs'], ['x-child', 'willUpdate'], ['x-child', 'willRender'], ['x-child', 'didUpdate'], ['x-child', 'didRender'], ['x-parent', 'didUpdate'], ['x-parent', 'didRender'] ], 'set foo = wow'); hooks.length = 0; this.runTask(() => set(this.component, 'foo', 'zomg')); assert.deepEqual(hooks, [ ['x-parent', 'willUpdate'], ['x-parent', 'willRender'], ['x-child', 'didUpdateAttrs'], ['x-child', 'didReceiveAttrs'], ['x-child', 'willUpdate'], ['x-child', 'willRender'], ['x-child', 'didUpdate'], ['x-child', 'didRender'], ['x-parent', 'didUpdate'], ['x-parent', 'didRender'] ], 'set foo = zomg'); hooks.length = 0; this.runTask(() => this.component.destroy()); assert.deepEqual(hooks, [ ['x-parent', 'willDestroyElement'], ['x-parent', 'willClearRender'], ['x-child', 'willDestroyElement'], ['x-child', 'willClearRender'], ['x-child', 'didDestroyElement'], ['x-parent', 'didDestroyElement'], ['x-parent', 'willDestroy'], ['x-child', 'willDestroy'] ], 'destroy'); } ['@test appending, updating and destroying a single component'](assert) { let willDestroyCalled = 0; this.registerComponent('x-parent', { ComponentClass: Component.extend({ layoutName: 'components/x-parent', willDestroyElement() { willDestroyCalled++; } }), template: '[parent: {{foo}}]{{#x-child bar=foo}}[yielded: {{foo}}]{{/x-child}}' }); this.registerComponent('x-child', { ComponentClass: Component.extend({ tagName: '' }), template: '[child: {{bar}}]{{yield}}' }); let XParent = this.owner._lookupFactory('component:x-parent'); this.component = XParent.create({ foo: 'zomg' }); assert.ok(!this.component.element, 'precond - should not have an element'); this.element = this.append(this.component); let componentElement = this.component.element; this.assertComponentElement(componentElement, { content: '[parent: zomg][child: zomg][yielded: zomg]' }); assert.equal(componentElement.parentElement, this.element, 'It should be attached to the target'); this.runTask(() => this.rerender()); this.assertComponentElement(componentElement, { content: '[parent: zomg][child: zomg][yielded: zomg]' }); assert.equal(componentElement.parentElement, this.element, 'It should be attached to the target'); this.runTask(() => set(this.component, 'foo', 'wow')); this.assertComponentElement(componentElement, { content: '[parent: wow][child: wow][yielded: wow]' }); assert.equal(componentElement.parentElement, this.element, 'It should be attached to the target'); this.runTask(() => set(this.component, 'foo', 'zomg')); this.assertComponentElement(componentElement, { content: '[parent: zomg][child: zomg][yielded: zomg]' }); assert.equal(componentElement.parentElement, this.element, 'It should be attached to the target'); this.runTask(() => this.component.destroy()); if (this.isHTMLBars) { // Bug in Glimmer – component should not have .element at this point assert.ok(!this.component.element, 'It should not have an element'); } assert.ok(!componentElement.parentElement, 'The component element should be detached'); this.assert.equal(willDestroyCalled, 1); } ['@test appending, updating and destroying multiple components'](assert) { let willDestroyCalled = 0; this.registerComponent('x-first', { ComponentClass: Component.extend({ layoutName: 'components/x-first', willDestroyElement() { willDestroyCalled++; } }), template: 'x-first {{foo}}!' }); this.registerComponent('x-second', { ComponentClass: Component.extend({ layoutName: 'components/x-second', willDestroyElement() { willDestroyCalled++; } }), template: 'x-second {{bar}}!' }); let First = this.owner._lookupFactory('component:x-first'); let Second = this.owner._lookupFactory('component:x-second'); let first = First.create({ foo: 'foo' }); let second = Second.create({ bar: 'bar' }); this.assert.ok(!first.element, 'precond - should not have an element'); this.assert.ok(!second.element, 'precond - should not have an element'); let wrapper1, wrapper2; this.runTask(() => wrapper1 = this.append(first)); this.runTask(() => wrapper2 = this.append(second)); let componentElement1 = first.element; let componentElement2 = second.element; this.assertComponentElement(componentElement1, { content: 'x-first foo!' }); this.assertComponentElement(componentElement2, { content: 'x-second bar!' }); assert.equal(componentElement1.parentElement, wrapper1, 'The first component should be attached to the target'); assert.equal(componentElement2.parentElement, wrapper2, 'The second component should be attached to the target'); this.runTask(() => set(first, 'foo', 'FOO')); this.assertComponentElement(componentElement1, { content: 'x-first FOO!' }); this.assertComponentElement(componentElement2, { content: 'x-second bar!' }); assert.equal(componentElement1.parentElement, wrapper1, 'The first component should be attached to the target'); assert.equal(componentElement2.parentElement, wrapper2, 'The second component should be attached to the target'); this.runTask(() => set(second, 'bar', 'BAR')); this.assertComponentElement(componentElement1, { content: 'x-first FOO!' }); this.assertComponentElement(componentElement2, { content: 'x-second BAR!' }); assert.equal(componentElement1.parentElement, wrapper1, 'The first component should be attached to the target'); assert.equal(componentElement2.parentElement, wrapper2, 'The second component should be attached to the target'); this.runTask(() => { set(first, 'foo', 'foo'); set(second, 'bar', 'bar'); }); this.assertComponentElement(componentElement1, { content: 'x-first foo!' }); this.assertComponentElement(componentElement2, { content: 'x-second bar!' }); assert.equal(componentElement1.parentElement, wrapper1, 'The first component should be attached to the target'); assert.equal(componentElement2.parentElement, wrapper2, 'The second component should be attached to the target'); this.runTask(() => { first.destroy(); second.destroy(); }); if (this.isHTMLBars) { // Bug in Glimmer – component should not have .element at this point assert.ok(!first.element, 'The first component should not have an element'); assert.ok(!second.element, 'The second component should not have an element'); } assert.ok(!componentElement1.parentElement, 'The first component element should be detached'); assert.ok(!componentElement2.parentElement, 'The second component element should be detached'); this.assert.equal(willDestroyCalled, 2); } ['@test can appendTo while rendering'](assert) { let owner = this.owner; let append = (component) => { return this.append(component); }; let element1, element2; this.registerComponent('first-component', { ComponentClass: Component.extend({ layout: compile('component-one'), didInsertElement() { element1 = this.element; let SecondComponent = owner._lookupFactory('component:second-component'); append(SecondComponent.create()); } }) }); this.registerComponent('second-component', { ComponentClass: Component.extend({ layout: compile(`component-two`), didInsertElement() { element2 = this.element; } }) }); let FirstComponent = this.owner._lookupFactory('component:first-component'); this.runTask(() => append(FirstComponent.create())); this.assertComponentElement(element1, { content: 'component-one' }); this.assertComponentElement(element2, { content: 'component-two' }); } ['@test can appendTo and remove while rendering'](assert) { let owner = this.owner; let append = (component) => { return this.append(component); }; let element1, element2, element3, element4, component1, component2; this.registerComponent('foo-bar', { ComponentClass: Component.extend({ layout: compile('foo-bar'), init() { this._super(...arguments); component1 = this; }, didInsertElement() { element1 = this.element; let OtherRoot = owner._lookupFactory('component:other-root'); this._instance = OtherRoot.create({ didInsertElement() { element2 = this.element; } }); append(this._instance); }, willDestroy() { this._instance.destroy(); } }) }); this.registerComponent('baz-qux', { ComponentClass: Component.extend({ layout: compile('baz-qux'), init() { this._super(...arguments); component2 = this; }, didInsertElement() { element3 = this.element; let OtherRoot = owner._lookupFactory('component:other-root'); this._instance = OtherRoot.create({ didInsertElement() { element4 = this.element; } }); append(this._instance); }, willDestroy() { this._instance.destroy(); } }) }); let instantiatedRoots = 0; let destroyedRoots = 0; this.registerComponent('other-root', { ComponentClass: Component.extend({ layout: compile(`fake-thing: {{counter}}`), init() { this._super(...arguments); this.counter = instantiatedRoots++; }, willDestroy() { destroyedRoots++; this._super(...arguments); } }) }); this.render(strip` {{#if showFooBar}} {{foo-bar}} {{else}} {{baz-qux}} {{/if}} `, { showFooBar: true }); this.assertComponentElement(element1, { }); this.assertComponentElement(element2, { content: 'fake-thing: 0' }); assert.equal(instantiatedRoots, 1); this.assertStableRerender(); this.runTask(() => set(this.context, 'showFooBar', false)); assert.equal(instantiatedRoots, 2); assert.equal(destroyedRoots, 1); this.assertComponentElement(element3, { }); this.assertComponentElement(element4, { content: 'fake-thing: 1' }); this.runTask(() => { component1.destroy(); component2.destroy(); }); assert.equal(instantiatedRoots, 2); assert.equal(destroyedRoots, 2); } } moduleFor('append: no arguments (attaching to document.body)', class extends AbstractAppendTest { append(component) { this.runTask(() => component.append()); this.didAppend(component); return document.body; } }); moduleFor('appendTo: a selector', class extends AbstractAppendTest { append(component) { this.runTask(() => component.appendTo('#qunit-fixture')); this.didAppend(component); return jQuery('#qunit-fixture')[0]; } ['@test raises an assertion when the target does not exist in the DOM'](assert) { this.registerComponent('foo-bar', { ComponentClass: Component.extend({ layoutName: 'components/foo-bar' }), template: 'FOO BAR!' }); let FooBar = this.owner._lookupFactory('component:foo-bar'); this.component = FooBar.create(); assert.ok(!this.component.element, 'precond - should not have an element'); this.runTask(() => { expectAssertion(() => { this.component.appendTo('#does-not-exist-in-dom'); }, /You tried to append to \(#does-not-exist-in-dom\) but that isn't in the DOM/); }); assert.ok(!this.component.element, 'component should not have an element'); } }); moduleFor('appendTo: an element', class extends AbstractAppendTest { append(component) { let element = jQuery('#qunit-fixture')[0]; this.runTask(() => component.appendTo(element)); this.didAppend(component); return element; } }); moduleFor('appendTo: with multiple components', class extends AbstractAppendTest { append(component) { this.runTask(() => component.appendTo('#qunit-fixture')); this.didAppend(component); return jQuery('#qunit-fixture')[0]; } }); moduleFor('renderToElement: no arguments (defaults to a body context)', class extends AbstractAppendTest { append(component) { expectDeprecation(/Using the `renderToElement` is deprecated in favor of `appendTo`. Called in/); let wrapper; this.runTask(() => wrapper = component.renderToElement()); this.didAppend(component); this.assert.equal(wrapper.tagName, 'BODY', 'wrapper is a body element'); this.assert.notEqual(wrapper, document.body, 'wrapper is not document.body'); this.assert.ok(!wrapper.parentNode, 'wrapper is detached'); return wrapper; } }); moduleFor('renderToElement: a div', class extends AbstractAppendTest { append(component) { expectDeprecation(/Using the `renderToElement` is deprecated in favor of `appendTo`. Called in/); let wrapper; this.runTask(() => wrapper = component.renderToElement('div')); this.didAppend(component); this.assert.equal(wrapper.tagName, 'DIV', 'wrapper is a body element'); this.assert.ok(!wrapper.parentNode, 'wrapper is detached'); return wrapper; } });
Leooo/ember.js
packages/ember-glimmer/tests/integration/components/append-test.js
JavaScript
mit
18,760
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FlatRedBall.Content.Scene; using FlatRedBall; using FlatRedBall.IO; namespace EditorObjects.EditorSettings { public class AIEditorPropertiesSave { public const string Extension = "aiep"; public CameraSave BoundsCamera; public CameraSave Camera = new CameraSave(); public bool BoundsVisible = false; // For loading. public AIEditorPropertiesSave() { Camera.Z = 40; // do nothing } public void SetFromRuntime(Camera camera, Camera boundsCamera, bool boundsVisible) { Camera = CameraSave.FromCamera(camera); if (boundsCamera != null) { BoundsCamera = CameraSave.FromCamera(boundsCamera, true); } BoundsVisible = boundsVisible; // Gui.GuiData.listWindow } public static AIEditorPropertiesSave Load(string fileName) { AIEditorPropertiesSave toReturn = new AIEditorPropertiesSave(); FileManager.XmlDeserialize(fileName, out toReturn); return toReturn; } public void Save(string fileName) { FileManager.XmlSerialize(this, fileName); } } }
GorillaOne/FlatRedBall
FRBDK/FRBDK Supporting Projects/EditorObjects/EditorSettings/AIEditorPropertiesSave.cs
C#
mit
1,372
require 'spec_helper' try_spec do require './spec/fixtures/bookmark' describe DataMapper::TypesFixtures::Bookmark do supported_by :all do before :all do DataMapper::TypesFixtures::Bookmark.auto_migrate! end let(:resource) do DataMapper::TypesFixtures::Bookmark.create( :title => 'Check this out', :uri => uri, :shared => false, :tags => %w[ misc ] ) end before do resource.should be_saved end context 'without URI' do let(:uri) { nil } it 'can be found by uri' do DataMapper::TypesFixtures::Bookmark.first(:uri => uri).should eql(resource) end describe 'when reloaded' do before do resource.reload end it 'has no uri' do resource.uri.should be(nil) end end end describe 'with a blank URI' do let(:uri) { '' } it 'can be found by uri' do DataMapper::TypesFixtures::Bookmark.first(:uri => uri).should eql(resource) end describe 'when reloaded' do before do resource.reload end it 'is loaded as URI object' do resource.uri.should be_an_instance_of(Addressable::URI) end it 'has the same original URI' do resource.uri.to_s.should eql(uri) end end end describe 'with invalid URI' do let(:uri) { 'this is def. not URI' } it 'is perfectly valid (URI type does not provide auto validations)' do resource.save.should be(true) end end %w[ http://apple.com http://www.apple.com http://apple.com/ http://apple.com/iphone http://www.google.com/search?client=safari&rls=en-us&q=LED&ie=UTF-8&oe=UTF-8 http://books.google.com http://books.google.com/ http://db2.clouds.megacorp.net:8080 https://github.com https://github.com/ http://www.example.com:8088/never/ending/path/segments/ http://db2.clouds.megacorp.net:8080/resources/10 http://www.example.com:8088/never/ending/path/segments http://books.google.com/books?id=uSUJ3VhH4BsC&printsec=frontcover&dq=subject:%22+Linguistics+%22&as_brr=3&ei=DAHPSbGQE5rEzATk1sShAQ&rview=1 http://books.google.com:80/books?uid=14472359158468915761&rview=1 http://books.google.com/books?id=Ar3-TXCYXUkC&printsec=frontcover&rview=1 http://books.google.com/books/vp6ae081e454d30f89b6bca94e0f96fc14.js http://www.google.com/images/cleardot.gif http://books.google.com:80/books?id=Ar3-TXCYXUkC&printsec=frontcover&rview=1#PPA5,M1 http://www.hulu.com/watch/64923/terminator-the-sarah-connor-chronicles-to-the-lighthouse http://hulu.com:80/browse/popular/tv http://www.hulu.com/watch/62475/the-simpsons-gone-maggie-gone#s-p1-so-i0 ].each do |uri| describe "with URI set to '#{uri}'" do let(:uri) { uri } it 'can be found by uri' do DataMapper::TypesFixtures::Bookmark.first(:uri => uri).should_not be(nil) end describe 'when reloaded' do before do resource.reload end it 'matches a normalized form of the original URI' do resource.uri.should eql(Addressable::URI.parse(uri).normalize) end end end end end end end
troygnichols/dm-types
spec/integration/uri_spec.rb
Ruby
mit
3,551
import readdirRecursive from "fs-readdir-recursive"; import * as babel from "@babel/core"; import path from "path"; import fs from "fs"; import * as watcher from "./watcher"; export function chmod(src: string, dest: string): void { try { fs.chmodSync(dest, fs.statSync(src).mode); } catch (err) { console.warn(`Cannot change permissions of ${dest}`); } } type ReaddirFilter = (filename: string) => boolean; export function readdir( dirname: string, includeDotfiles: boolean, filter?: ReaddirFilter, ): Array<string> { return readdirRecursive(dirname, (filename, _index, currentDirectory) => { const stat = fs.statSync(path.join(currentDirectory, filename)); if (stat.isDirectory()) return true; return ( (includeDotfiles || filename[0] !== ".") && (!filter || filter(filename)) ); }); } export function readdirForCompilable( dirname: string, includeDotfiles: boolean, altExts?: Array<string>, ): Array<string> { return readdir(dirname, includeDotfiles, function (filename) { return isCompilableExtension(filename, altExts); }); } /** * Test if a filename ends with a compilable extension. */ export function isCompilableExtension( filename: string, altExts?: readonly string[], ): boolean { const exts = altExts || babel.DEFAULT_EXTENSIONS; const ext = path.extname(filename); return exts.includes(ext); } export function addSourceMappingUrl(code: string, loc: string): string { return code + "\n//# sourceMappingURL=" + path.basename(loc); } const CALLER = { name: "@babel/cli", }; export function transformRepl( filename: string, code: string, opts: any, ): Promise<any> { opts = { ...opts, caller: CALLER, filename, }; return new Promise((resolve, reject) => { babel.transform(code, opts, (err, result) => { if (err) reject(err); else resolve(result); }); }); } export async function compile( filename: string, opts: any | Function, ): Promise<any> { opts = { ...opts, caller: CALLER, }; // TODO (Babel 8): Use `babel.transformFileAsync` const result: any = await new Promise((resolve, reject) => { babel.transformFile(filename, opts, (err, result) => { if (err) reject(err); else resolve(result); }); }); if (result) { if (!process.env.BABEL_8_BREAKING) { if (!result.externalDependencies) return result; } watcher.updateExternalDependencies(filename, result.externalDependencies); } return result; } export function deleteDir(path: string): void { if (fs.existsSync(path)) { fs.readdirSync(path).forEach(function (file) { const curPath = path + "/" + file; if (fs.lstatSync(curPath).isDirectory()) { // recurse deleteDir(curPath); } else { // delete file fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } } process.on("uncaughtException", function (err) { console.error(err); process.exitCode = 1; }); export function withExtension(filename: string, ext: string = ".js") { const newBasename = path.basename(filename, path.extname(filename)) + ext; return path.join(path.dirname(filename), newBasename); } export function debounce(fn: () => void, time: number) { let timer; function debounced() { clearTimeout(timer); timer = setTimeout(fn, time); } debounced.flush = () => { clearTimeout(timer); fn(); }; return debounced; }
babel/babel
packages/babel-cli/src/babel/util.ts
TypeScript
mit
3,448
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\ApiBundle\DependencyInjection; use Sylius\Bundle\ApiBundle\Form\Type\ClientType; use Sylius\Bundle\ApiBundle\Model\AccessToken; use Sylius\Bundle\ApiBundle\Model\AccessTokenInterface; use Sylius\Bundle\ApiBundle\Model\AuthCode; use Sylius\Bundle\ApiBundle\Model\AuthCodeInterface; use Sylius\Bundle\ApiBundle\Model\Client; use Sylius\Bundle\ApiBundle\Model\ClientInterface; use Sylius\Bundle\ApiBundle\Model\RefreshToken; use Sylius\Bundle\ApiBundle\Model\RefreshTokenInterface; use Sylius\Bundle\ApiBundle\Model\UserInterface; use Sylius\Bundle\ResourceBundle\Controller\ResourceController; use Sylius\Bundle\ResourceBundle\SyliusResourceBundle; use Sylius\Component\Resource\Factory\Factory; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This class contains the configuration information for the bundle. * * This information is solely responsible for how the different configuration * sections are normalized, and merged. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('sylius_api'); $rootNode ->children() ->scalarNode('driver')->defaultValue(SyliusResourceBundle::DRIVER_DOCTRINE_ORM)->end() ->end() ; $this->addResourcesSection($rootNode); return $treeBuilder; } /** * @param ArrayNodeDefinition $node */ private function addResourcesSection(ArrayNodeDefinition $node) { $node ->children() ->arrayNode('resources') ->addDefaultsIfNotSet() ->children() ->arrayNode('api_user') ->addDefaultsIfNotSet() ->children() ->variableNode('options')->end() ->arrayNode('classes') ->addDefaultsIfNotSet() ->children() ->scalarNode('model')->isRequired()->cannotBeEmpty()->end() ->scalarNode('interface')->defaultValue(UserInterface::class)->cannotBeEmpty()->end() ->end() ->end() ->end() ->end() ->arrayNode('api_client') ->addDefaultsIfNotSet() ->children() ->variableNode('options')->end() ->arrayNode('classes') ->addDefaultsIfNotSet() ->children() ->scalarNode('model')->defaultValue(Client::class)->cannotBeEmpty()->end() ->scalarNode('interface')->defaultValue(ClientInterface::class)->cannotBeEmpty()->end() ->scalarNode('controller')->defaultValue(ResourceController::class)->cannotBeEmpty()->end() ->scalarNode('repository')->cannotBeEmpty()->end() ->scalarNode('factory')->defaultValue(Factory::class)->cannotBeEmpty()->end() ->arrayNode('form') ->addDefaultsIfNotSet() ->children() ->scalarNode('default')->defaultValue(ClientType::class)->cannotBeEmpty()->end() ->end() ->end() ->end() ->end() ->arrayNode('validation_groups') ->addDefaultsIfNotSet() ->children() ->arrayNode('default') ->prototype('scalar')->end() ->defaultValue(['sylius']) ->end() ->end() ->end() ->end() ->end() ->arrayNode('api_access_token') ->addDefaultsIfNotSet() ->children() ->variableNode('options')->end() ->arrayNode('classes') ->addDefaultsIfNotSet() ->children() ->scalarNode('model')->defaultValue(AccessToken::class)->cannotBeEmpty()->end() ->scalarNode('interface')->defaultValue(AccessTokenInterface::class)->cannotBeEmpty()->end() ->scalarNode('controller')->defaultValue(ResourceController::class)->cannotBeEmpty()->end() ->scalarNode('repository')->cannotBeEmpty()->end() ->scalarNode('factory')->defaultValue(Factory::class)->cannotBeEmpty()->end() ->end() ->end() ->arrayNode('validation_groups') ->addDefaultsIfNotSet() ->children() ->arrayNode('default') ->prototype('scalar')->end() ->defaultValue(['sylius']) ->end() ->end() ->end() ->end() ->end() ->arrayNode('api_refresh_token') ->addDefaultsIfNotSet() ->children() ->variableNode('options')->end() ->arrayNode('classes') ->addDefaultsIfNotSet() ->children() ->scalarNode('model')->defaultValue(RefreshToken::class)->cannotBeEmpty()->end() ->scalarNode('interface')->defaultValue(RefreshTokenInterface::class)->cannotBeEmpty()->end() ->scalarNode('controller')->defaultValue(ResourceController::class)->cannotBeEmpty()->end() ->scalarNode('repository')->cannotBeEmpty()->end() ->scalarNode('factory')->defaultValue(Factory::class)->cannotBeEmpty()->end() ->end() ->end() ->arrayNode('validation_groups') ->addDefaultsIfNotSet() ->children() ->arrayNode('default') ->prototype('scalar')->end() ->defaultValue(['sylius']) ->end() ->end() ->end() ->end() ->end() ->arrayNode('api_auth_code') ->addDefaultsIfNotSet() ->children() ->variableNode('options')->end() ->arrayNode('classes') ->addDefaultsIfNotSet() ->children() ->scalarNode('model')->defaultValue(AuthCode::class)->cannotBeEmpty()->end() ->scalarNode('interface')->defaultValue(AuthCodeInterface::class)->cannotBeEmpty()->end() ->scalarNode('controller')->defaultValue(ResourceController::class)->cannotBeEmpty()->end() ->scalarNode('repository')->cannotBeEmpty()->end() ->scalarNode('factory')->defaultValue(Factory::class)->cannotBeEmpty()->end() ->end() ->end() ->arrayNode('validation_groups') ->addDefaultsIfNotSet() ->children() ->arrayNode('default') ->prototype('scalar')->end() ->defaultValue(['sylius']) ->end() ->end() ->end() ->end() ->end() ->end() ->end() ->end() ; } }
adamelso/Sylius
src/Sylius/Bundle/ApiBundle/DependencyInjection/Configuration.php
PHP
mit
9,956
using System.Collections.Generic; using System; using UnityEngine; public class EventService { public delegate void EventDelegate<T>(T e) where T : GameEvent; Dictionary<Type, Delegate> delegates = new Dictionary<Type, Delegate>(); public void AddListener<T>(EventDelegate<T> listener) where T : GameEvent { Type type = typeof(T); Delegate d; if (delegates.TryGetValue(type, out d)) { delegates[type] = Delegate.Combine(d, listener); } else { delegates[type] = listener; } } public void RemoveListener<T>(EventDelegate<T> listener) where T : GameEvent { Type type = typeof(T); Delegate d; if (delegates.TryGetValue(type, out d)) { Delegate currentDel = Delegate.Remove(d, listener); if (currentDel == null) { delegates.Remove(type); } else { delegates[type] = currentDel; } } } public void Dispatch<T>(T e) where T : GameEvent { if (e == null) { Debug.Log("Invalid event argument: " + e.GetType()); return; } Type type = e.GetType(); Delegate d; if (delegates.TryGetValue(type, out d)) { EventDelegate<T> callback = d as EventDelegate<T>; if (callback != null) { callback(e); } else { Debug.Log("Not removed callback: " + type); } } } } public class GameEvent { }
kicholen/GamePrototype
Assets/Script/Controller/Service/EventService/EventService.cs
C#
mit
1,277
(function () { var g = void 0, k = !0, m = null, o = !1, p, q = this, r = function (a) { var b = typeof a; if ("object" == b) if (a) { if (a instanceof Array) return "array"; if (a instanceof Object) return b; var c = Object.prototype.toString.call(a); if ("[object Window]" == c) return "object"; if ("[object Array]" == c || "number" == typeof a.length && "undefined" != typeof a.splice && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("splice")) return "array"; if ("[object Function]" == c || "undefined" != typeof a.call && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("call")) return "function" } else return "null"; else if ("function" == b && "undefined" == typeof a.call) return "object"; return b }, aa = function (a) { var b = r(a); return "array" == b || "object" == b && "number" == typeof a.length }, u = function (a) { return "string" == typeof a }, ba = function (a) { a = r(a); return "object" == a || "array" == a || "function" == a }, ca = function (a, b, c) { return a.call.apply(a.bind, arguments) }, da = function (a, b, c) { if (!a) throw Error(); if (2 < arguments.length) { var d = Array.prototype.slice.call(arguments, 2); return function () { var c = Array.prototype.slice.call(arguments); Array.prototype.unshift.apply(c, d); return a.apply(b, c) } } return function () { return a.apply(b, arguments) } }, v = function (a, b, c) { v = Function.prototype.bind && -1 != Function.prototype.bind.toString().indexOf("native code") ? ca : da; return v.apply(m, arguments) }, ea = function (a, b) { function c() {} c.prototype = b.prototype; a.Sa = b.prototype; a.prototype = new c }; Function.prototype.bind = Function.prototype.bind || function (a, b) { if (1 < arguments.length) { var c = Array.prototype.slice.call(arguments, 1); c.unshift(this, a); return v.apply(m, c) } return v(this, a) }; var w = function (a) { this.stack = Error().stack || ""; if (a) this.message = "" + a }; ea(w, Error); w.prototype.name = "CustomError"; var fa = function (a, b) { for (var c = 1; c < arguments.length; c++) var d = ("" + arguments[c]).replace(/\$/g, "$$$$"), a = a.replace(/\%s/, d); return a }, ma = function (a) { if (!ga.test(a)) return a; - 1 != a.indexOf("&") && (a = a.replace(ha, "&amp;")); - 1 != a.indexOf("<") && (a = a.replace(ia, "&lt;")); - 1 != a.indexOf(">") && (a = a.replace(ka, "&gt;")); - 1 != a.indexOf('"') && (a = a.replace(la, "&quot;")); return a }, ha = /&/g, ia = /</g, ka = />/g, la = /\"/g, ga = /[&<>\"]/; var x = function (a, b) { b.unshift(a); w.call(this, fa.apply(m, b)); b.shift(); this.Ra = a }; ea(x, w); x.prototype.name = "AssertionError"; var y = function (a, b, c) { if (!a) { var d = Array.prototype.slice.call(arguments, 2), f = "Assertion failed"; if (b) var f = f + (": " + b), e = d; throw new x("" + f, e || []); } }; var z = Array.prototype, na = z.indexOf ? function (a, b, c) { y(a.length != m); return z.indexOf.call(a, b, c) } : function (a, b, c) { c = c == m ? 0 : 0 > c ? Math.max(0, a.length + c) : c; if (u(a)) return !u(b) || 1 != b.length ? -1 : a.indexOf(b, c); for (; c < a.length; c++) if (c in a && a[c] === b) return c; return -1 }, oa = z.forEach ? function (a, b, c) { y(a.length != m); z.forEach.call(a, b, c) } : function (a, b, c) { for (var d = a.length, f = u(a) ? a.split("") : a, e = 0; e < d; e++) e in f && b.call(c, f[e], e, a) }, pa = function (a) { return z.concat.apply(z, arguments) }, qa = function (a) { if ("array" == r(a)) return pa(a); for (var b = [], c = 0, d = a.length; c < d; c++) b[c] = a[c]; return b }, ra = function (a, b, c) { y(a.length != m); return 2 >= arguments.length ? z.slice.call(a, b) : z.slice.call(a, b, c) }; var A = function (a, b) { this.x = a !== g ? a : 0; this.y = b !== g ? b : 0 }; A.prototype.toString = function () { return "(" + this.x + ", " + this.y + ")" }; var sa = function (a, b) { for (var c in a) b.call(g, a[c], c, a) }, ta = "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","), ua = function (a, b) { for (var c, d, f = 1; f < arguments.length; f++) { d = arguments[f]; for (c in d) a[c] = d[c]; for (var e = 0; e < ta.length; e++) c = ta[e], Object.prototype.hasOwnProperty.call(d, c) && (a[c] = d[c]) } }; var B, va, C, wa, xa = function () { return q.navigator ? q.navigator.userAgent : m }; wa = C = va = B = o; var D; if (D = xa()) { var ya = q.navigator; B = 0 == D.indexOf("Opera"); va = !B && -1 != D.indexOf("MSIE"); C = !B && -1 != D.indexOf("WebKit"); wa = !B && !C && "Gecko" == ya.product } var za = B, E = va, F = wa, G = C, Aa; a: { var H = "", I; if (za && q.opera) var Ba = q.opera.version, H = "function" == typeof Ba ? Ba() : Ba; else if (F ? I = /rv\:([^\);]+)(\)|;)/ : E ? I = /MSIE\s+([^\);]+)(\)|;)/ : G && (I = /WebKit\/(\S+)/), I) var Ca = I.exec(xa()), H = Ca ? Ca[1] : ""; if (E) { var Da, Ea = q.document; Da = Ea ? Ea.documentMode : g; if (Da > parseFloat(H)) { Aa = "" + Da; break a } } Aa = H } var Fa = Aa, Ga = {}, Ha = function (a) { var b; if (!(b = Ga[a])) { b = 0; for (var c = ("" + Fa).replace(/^[\s\xa0]+|[\s\xa0]+$/g, "").split("."), d = ("" + a).replace(/^[\s\xa0]+|[\s\xa0]+$/g, "").split("."), f = Math.max(c.length, d.length), e = 0; 0 == b && e < f; e++) { var h = c[e] || "", n = d[e] || "", j = RegExp("(\\d*)(\\D*)", "g"), t = RegExp("(\\d*)(\\D*)", "g"); do { var i = j.exec(h) || ["", "", ""], l = t.exec(n) || ["", "", ""]; if (0 == i[0].length && 0 == l[0].length) break; b = ((0 == i[1].length ? 0 : parseInt(i[1], 10)) < (0 == l[1].length ? 0 : parseInt(l[1], 10)) ? -1 : (0 == i[1].length ? 0 : parseInt(i[1], 10)) > (0 == l[1].length ? 0 : parseInt(l[1], 10)) ? 1 : 0) || ((0 == i[2].length) < (0 == l[2].length) ? -1 : (0 == i[2].length) > (0 == l[2].length) ? 1 : 0) || (i[2] < l[2] ? -1 : i[2] > l[2] ? 1 : 0) } while (0 == b) } b = Ga[a] = 0 <= b } return b }, Ia = {}, J = function (a) { return Ia[a] || (Ia[a] = E && document.documentMode && document.documentMode >= a) }; var Ja, Ka = !E || J(9); !F && !E || E && J(9) || F && Ha("1.9.1"); E && Ha("9"); var La = function (a, b) { var c; c = (c = a.className) && "function" == typeof c.split ? c.split(/\s+/) : []; var d = ra(arguments, 1), f; f = c; for (var e = 0, h = 0; h < d.length; h++) 0 <= na(f, d[h]) || (f.push(d[h]), e++); f = e == d.length; a.className = c.join(" "); return f }; var Ma = function (a) { return a ? new K(L(a)) : Ja || (Ja = new K) }, Na = function (a, b) { var c = b && "*" != b ? b.toUpperCase() : ""; return a.querySelectorAll && a.querySelector && (!G || "CSS1Compat" == document.compatMode || Ha("528")) && c ? a.querySelectorAll(c + "") : a.getElementsByTagName(c || "*") }, Pa = function (a, b) { sa(b, function (b, d) { "style" == d ? a.style.cssText = b : "class" == d ? a.className = b : "for" == d ? a.htmlFor = b : d in Oa ? a.setAttribute(Oa[d], b) : 0 == d.lastIndexOf("aria-", 0) ? a.setAttribute(d, b) : a[d] = b }) }, Oa = { cellpadding: "cellPadding", cellspacing: "cellSpacing", colspan: "colSpan", rowspan: "rowSpan", valign: "vAlign", height: "height", width: "width", usemap: "useMap", frameborder: "frameBorder", maxlength: "maxLength", type: "type" }, Qa = function (a, b, c) { function d(c) { c && b.appendChild(u(c) ? a.createTextNode(c) : c) } for (var f = 2; f < c.length; f++) { var e = c[f]; if (aa(e) && !(ba(e) && 0 < e.nodeType)) { var h; a: { if (e && "number" == typeof e.length) { if (ba(e)) { h = "function" == typeof e.item || "string" == typeof e.item; break a } if ("function" == r(e)) { h = "function" == typeof e.item; break a } } h = o } oa(h ? qa(e) : e, d) } else d(e) } }, L = function (a) { return 9 == a.nodeType ? a : a.ownerDocument || a.document }, K = function (a) { this.C = a || q.document || document }; K.prototype.za = function (a, b, c) { var d = this.C, f = arguments, e = f[0], h = f[1]; if (!Ka && h && (h.name || h.type)) { e = ["<", e]; h.name && e.push(' name="', ma(h.name), '"'); if (h.type) { e.push(' type="', ma(h.type), '"'); var n = {}; ua(n, h); h = n; delete h.type } e.push(">"); e = e.join("") } e = d.createElement(e); if (h) u(h) ? e.className = h : "array" == r(h) ? La.apply(m, [e].concat(h)) : Pa(e, h); 2 < f.length && Qa(d, e, f); return e }; K.prototype.createElement = function (a) { return this.C.createElement(a) }; K.prototype.createTextNode = function (a) { return this.C.createTextNode(a) }; K.prototype.appendChild = function (a, b) { a.appendChild(b) }; var M = function (a) { var b; a: { b = L(a); if (b.defaultView && b.defaultView.getComputedStyle && (b = b.defaultView.getComputedStyle(a, m))) { b = b.position || b.getPropertyValue("position"); break a } b = "" } return b || (a.currentStyle ? a.currentStyle.position : m) || a.style && a.style.position }, Ra = function (a) { if (E && !J(8)) return a.offsetParent; for (var b = L(a), c = M(a), d = "fixed" == c || "absolute" == c, a = a.parentNode; a && a != b; a = a.parentNode) if (c = M(a), d = d && "static" == c && a != b.documentElement && a != b.body, !d && (a.scrollWidth > a.clientWidth || a.scrollHeight > a.clientHeight || "fixed" == c || "absolute" == c || "relative" == c)) return a; return m }, N = function (a) { var b, c = L(a), d = M(a), f = F && c.getBoxObjectFor && !a.getBoundingClientRect && "absolute" == d && (b = c.getBoxObjectFor(a)) && (0 > b.screenX || 0 > b.screenY), e = new A(0, 0), h; b = c ? 9 == c.nodeType ? c : L(c) : document; if (h = E) if (h = !J(9)) h = "CSS1Compat" != Ma(b).C.compatMode; h = h ? b.body : b.documentElement; if (a == h) return e; if (a.getBoundingClientRect) { b = a.getBoundingClientRect(); if (E) a = a.ownerDocument, b.left -= a.documentElement.clientLeft + a.body.clientLeft, b.top -= a.documentElement.clientTop + a.body.clientTop; a = Ma(c).C; c = !G && "CSS1Compat" == a.compatMode ? a.documentElement : a.body; a = a.parentWindow || a.defaultView; c = new A(a.pageXOffset || c.scrollLeft, a.pageYOffset || c.scrollTop); e.x = b.left + c.x; e.y = b.top + c.y } else if (c.getBoxObjectFor && !f) b = c.getBoxObjectFor(a), c = c.getBoxObjectFor(h), e.x = b.screenX - c.screenX, e.y = b.screenY - c.screenY; else { b = a; do { e.x += b.offsetLeft; e.y += b.offsetTop; b != a && (e.x += b.clientLeft || 0, e.y += b.clientTop || 0); if (G && "fixed" == M(b)) { e.x += c.body.scrollLeft; e.y += c.body.scrollTop; break } b = b.offsetParent } while (b && b != a); if (za || G && "absolute" == d) e.y -= c.body.offsetTop; for (b = a; (b = Ra(b)) && b != c.body && b != h;) if (e.x -= b.scrollLeft, !za || "TR" != b.tagName) e.y -= b.scrollTop } return e }, Ta = function () { var a = Ma(g), b = m; if (E) b = a.C.createStyleSheet(), Sa(b); else { var c = Na(a.C, "head")[0]; c || (b = Na(a.C, "body")[0], c = a.za("head"), b.parentNode.insertBefore(c, b)); b = a.za("style"); Sa(b); a.appendChild(c, b) } }, Sa = function (a) { E ? a.cssText = "canvas:active{cursor:pointer}" : a[G ? "innerText" : "innerHTML"] = "canvas:active{cursor:pointer}" }; var O = function (a, b) { var c = {}, d; for (d in b) c[d] = a.style[d], a.style[d] = b[d]; return c }, P = function (a, b) { this.M = a || m; this.fa = m; this.ya = b || function () {}; this.Q = 0; this.ta = 0.05 }, Ua = function (a, b) { a.ya = b }; P.prototype.s = function () { if (this.M && this.ta) { this.Q += this.ta; if (1 < this.Q) this.Q = 1, this.ta = 0, this.ya(); var a = "0 0 2px rgba(255,0,0," + this.Q + ")", a = O(this.M, { boxShadow: a, MozBoxShadow: a, webkitBoxShadow: a, oBoxShadow: a, msBoxShadow: a, opacity: this.Q }); if (!this.fa) this.fa = a } }; P.prototype.restore = function () { this.M && this.fa && O(this.M, this.fa) }; var Va = function () { this.H = [] }; Va.prototype.k = function (a, b, c) { if (a) { this.H.push(arguments); var d = a, f = b, e = c; d.addEventListener ? d.addEventListener(f, e, o) : d.attachEvent("on" + f, e) } }; var Wa = function (a, b, c) { a && (a.removeEventListener ? a.removeEventListener(b, c, o) : a.detachEvent("on" + b, c)) }; var Xa = Math.PI / 2, Q = function (a, b, c) { this.ca = a; this.P = document.createElement("div"); this.P.style.position = "absolute"; var a = Math.floor(3 * Math.random() + 0), d = "\u2744"; 1 < a ? d = "\u2745" : 2 < a && (d = "\u2746"); this.P.innerHTML = d; this.ca.appendChild(this.P); this.Y = c; this.X = b; this.reset() }; Q.prototype.reset = function () { this.x = Math.random() * this.X; this.ea = 4.5 * Math.random() + 1; this.y = -this.ea; this.B = 2 * Math.random() + -1; this.xa = this.ea; var a = Math.floor(255 * (0.4 * Math.random() + 0.5)).toString(16); O(this.P, { fontSize: 2.5 * this.ea + "px", left: this.x + "px", top: this.y + "px", color: "#" + a + a + a }) }; Q.prototype.move = function (a, b) { this.y += this.B * b + this.xa * a; this.B += 0.2 * Math.random() + -0.1; if (-1 > this.B) this.B = -1; else if (1 < this.B) this.B = 1; this.x += this.B * a + this.xa * b; this.y > this.Y + this.ea && this.reset() }; Q.prototype.s = function () { this.P.style.left = this.x + "px"; this.P.style.top = this.y + "px" }; var R = function (a) { this.ca = a; this.X = a.offsetWidth; this.Y = a.offsetHeight; this.da = []; this.ra = 1; this.sa = 0; this.Ma = !! navigator.userAgent.match(/(iPod|iPhone|iPad)/) }; R.prototype.s = function () { 200 > this.da.length && 0.5 > Math.random() && this.da.push(new Q(this.ca, this.X, this.Y)); for (var a = 0, b; b = this.da[a]; a++) b.move(this.ra, this.sa), b.s() }; R.prototype.Ca = function (a) { if (this.Ma) { var b = window.orientation & 2, c = b ? a.beta : a.gamma / 2, a = b ? 0 > a.gamma ? 1 : -1 : 0 > a.beta ? -1 : 1; if (c && 45 > Math.abs(c)) c = a * Xa * (c / 45), this.ra = Math.cos(c), this.sa = Math.sin(c) } else { if (!a.gamma && a.x) a.gamma = -(a.x * (180 / Math.PI)); if (a.gamma && 90 > Math.abs(a.gamma)) c = Xa * (a.gamma / 90), this.ra = Math.cos(c), this.sa = Math.sin(c) } }; R.prototype.N = function (a, b) { O(this.ca, { width: a + "px", height: b + "px" }); this.X = a; this.Y = b; for (var c = 0, d; d = this.da[c]; c++) { var f = b; d.X = a; d.Y = f } }; var Ya = function (a, b, c, d) { this.oa = b; this.g = a; this.x = c; this.y = d; this.width = b.width; this.height = b.height; this.la = (this.width + 120) / 88; this.Ea = (this.height + 120) / 66; this.ga = 0; this.$ = o; this.w = []; this.G = []; for (a = 0; 66 > a; a++) { this.w[a] = []; this.G[a] = []; b = Math.min(a, 65 - a); for (c = 0; 88 > c; c++) d = Math.min(c, 87 - c), 8 > d || 8 > b ? (d = 1 - Math.min(d, b) / 8, this.G[a].push(4 * Math.random() * d * d)) : this.G[a].push(0), this.w[a].push(0) } this.S = 0; this.L = []; this.v = m; this.ka = []; this.W = this.aa = 0; this.I = m; this.ma = o }, Za = function (a, b, c) { b = (b + 60) / a.la | 0; c = (c + 60) / a.Ea | 0; return [b, c] }, $a = function (a, b, c) { for (var d = 0, f = c - 1; f <= c + 1; f++) for (var e = b - 1; e <= b + 1; e++) var h = a, n = e, j = f, n = Math.max(0, Math.min(87, n)), j = Math.max(0, Math.min(65, j)), d = d + h.w[j][n]; return d / 9 }, ab = function (a, b) { a.$ = k; b.fillStyle = "rgba(240,246,246,0.8)"; b.fillRect(0, 0, b.canvas.width, b.canvas.height) }; Ya.prototype.s = function (a) { if (!(this.$ || 88 < this.ga || 5808 < this.S)) { a.fillStyle = "rgba(240,246,246,0.08)"; for (var b = 0; 200 > b; b++) { var c = Math.random() * (this.width + 120) - 60, d = Math.random() * (this.height + 120) - 60, f = Za(this, c, d), e = this.w[f[1]][f[0]]; e >= 4 * (1 + Math.random()) / 2 && (c |= 0, d |= 0, a.beginPath(), a.arc(c, d, e / 4 * this.la | 0, 0, 2 * Math.PI, k), a.fill(), a.closePath(), this.S++) } for (b = 0; 200 > b; b++) if (c = Math.random() * (this.width + 120) - 60, d = Math.random() * (this.height + 120) - 60, f = Za(this, c, d), e = this.w[f[1]][f[0]], f = this.G[f[1]][f[0]], e = 2 > e ? Math.max(e, f) : f, e >= Math.random()) e = 3 * Math.min(1, e) * this.la | 0, c |= 0, d |= 0, f = a.createRadialGradient(c, d, 0, c, d, e), f.addColorStop(0, "rgba(240,246,246,0.16)"), f.addColorStop(1, "rgba(240,246,246,0)"), a.fillStyle = f, a.fillRect(c - e + 1, d - e + 1, 2 * e - 1, 2 * e - 1), this.S++ } bb(this); bb(this); for (b = 0; b < this.L.length; b++) this.L[b].s(a) }; var cb = function (a, b) { a.ka = b; a.aa = 0; a.W = 0; a.I = m }, bb = function (a) { if (!(a.v || a.aa >= a.ka.length)) { var b = a.ka[a.aa].O; if (!a.I) a.I = new S, a.L.push(a.I); a.I.ba.apply(a.I, b[a.W]); a.W++; if (a.W >= b.length) a.W = 0, a.aa++, a.I = m } }, T = function (a, b) { a.v && a.v.ba(b[0], b[1]) }, db = function (a) { a.g.k(window, "touchmove", v(a.Ka, a)); a.g.k(window, "touchstart", v(a.La, a)); a.g.k(window, "touchend", v(a.Ja, a)); a.g.k(window, "mousemove", v(a.Ha, a)); a.g.k(window, "mousedown", v(a.Ga, a)); a.g.k(window, "mouseup", v(a.Ia, a)) }; p = Ya.prototype; p.Ha = function (a) { this.v && !this.ma && T(this, [a.clientX - this.x | 0, a.clientY - this.y | 0]) }; p.Ga = function (a) { if ((a.target || a.srcElement) == this.oa && (0 == a.button || 1 == a.button)) { var b = [a.clientX - this.x | 0, a.clientY - this.y | 0]; this.v = new S; this.L.push(this.v); T(this, b); a.preventDefault(); return o } }; p.Ia = function () { this.v = m }; p.La = function (a) { this.ma = k; a = a.touches.item(0); a = [a.clientX - this.x | 0, a.clientY - this.y | 0]; this.v = new S; this.L.push(this.v); T(this, a) }; p.Ja = function (a) { this.ma = o; this.v = m; a.preventDefault(); return o }; p.Ka = function (a) { var b = a.touches.item(0); T(this, [b.clientX - this.x | 0, b.clientY - this.y | 0]); a.preventDefault(); return o }; p.N = function (a, b, c) { this.oa.width = a; this.oa.height = b; this.width = a; this.height = b; ab(this, c) }; var S = function () { this.Qa = this.Oa = 30; this.O = [] }; S.prototype.ba = function (a, b) { this.O.push([a, b]) }; S.prototype.s = function (a) { if (0 != this.O.length) { var b = a.globalCompositeOperation; a.globalCompositeOperation = "destination-out"; a.lineWidth = this.Oa; a.lineCap = "round"; a.lineJoin = "round"; a.beginPath(); var c = this.O[0]; a.moveTo(c[0], c[1] - 1); for (var d = 0; c = this.O[d]; d++) a.lineTo(c[0], c[1]); a.stroke(); a.globalCompositeOperation = b } }; var U = function (a) { this.n = this.o = m; this.g = a; this.D = new P }, eb = function (a) { if (!a.o) return m; var b = document.createElement("button"), c = N(a.o), d = a.o.offsetWidth, a = a.o.offsetHeight; navigator.userAgent.match(/iPad/) && (d = 86, a = 40); document.getElementById("skb") ? (b.className = "lsbb", O(b, { fontSize: "15px", background: "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAmCAYAAAAFvPEHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAl2cEFnAAAAJgAAACYAB/nYBgAAADFJREFUCNd9jDEKACAQw0L//17BKW4iR3ErbVL20ihE4EkgdVAIo7swBe6av7+pWYcD6Xg4BFIWHrsAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTEtMTItMTNUMTA6MTE6MjctMDg6MDD1wN6AAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDExLTEyLTEzVDEwOjExOjI3LTA4OjAwhJ1mPAAAAABJRU5ErkJggg==') repeat-x", color: "#374A82" }), b.innerHTML = "\u2652", c.y -= 1) : (b.innerHTML = "Defrost", O(b, { backgroundColor: "#4d90fe", backgroundImage: "-webkit-,-moz-,-ms-,-o-,,".split(",").join("linear-gradient(top,#4d90fe,#4787ed);"), filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#4d90fe',EndColorStr='#4787ed')", border: "1px solid #3079ed", borderRadius: "2px", webkitBorderRadius: "2px", mozBorderRadius: "2px", color: "white", fontSize: "11px", fontWeight: "bold", textAlign: "center", position: "fixed", top: c.y + "px", left: c.x + "px", width: d + "px", height: a + "px", padding: "0 8px", zIndex: 1201, opacity: 0 }), 30 < a && O(b, { fontSize: "15px" })); return b }; U.prototype.qa = function (a) { var b = this.o = document.getElementById("gbqfb") || document.getElementById("sblsbb") || document.getElementsByName("btnG")[0]; if (this.o) { this.n = eb(this); this.D.M = this.n; Ua(this.D, function () { b.style.visibility = "hidden" }); var c = this.o.parentNode; if (c && "sbds" == c.id) c.style.width = c.offsetWidth + "px"; this.g.k(this.n, "click", a); document.body.insertBefore(this.n, document.body.firstChild) } }; U.prototype.detach = function () { if (this.o && this.n) this.n.parentNode.removeChild(this.n), this.n = m, this.o.style.visibility = "visible" }; U.prototype.pa = function () { if (this.o && this.n) { var a = N(this.o); this.n.style.top = a.y + "px"; this.n.style.left = a.x + "px" } }; var V = function (a, b) { this.i = b; this.g = a; this.U = this.V = this.a = m; this.va = {}; this.ua = {}; this.p = m; this.D = new P; this.m = m }, fb = function (a) { function b(a) { return d.charAt(a >> 6 & 63) + d.charAt(a & 63) } function c(a) { var c = 0; 0 > a && (c = 32, a = -a); return b(c | a & 31).charAt(1) } for (var d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", a = a.i.L, f = [], e = 0, h; h = a[e]; ++e) { var n = []; h = h.O; for (var j = m, t = 0, i; i = h[t]; t++) j && 32 > Math.abs(i[0] - j[0]) && 32 > Math.abs(i[1] - j[1]) ? (j = [i[0] - j[0], i[1] - j[1]], n.push(c(j[0]) + c(j[1]))) : n.push((0 == t ? "" : ";") + (b(i[0]) + b(i[1]))), j = i; f.push(n.join("")) } return "1;" + f.join("!") }, gb = function (a) { function b(a) { var b = String.fromCharCode(a); return "A" <= b && "Z" >= b ? a - 65 : "a" <= b && "z" >= b ? a - 97 + 26 : "0" <= b && "9" >= b ? a - 48 + 52 : "-" == b ? 62 : "_" == b ? 63 : m } function c(a, c) { var d = b(a.charCodeAt(c)), e = b(a.charCodeAt(c + 1)); return d === m || e === m ? m : d << 6 | e } function d(a, c) { var d = b(a.charCodeAt(c)); if (d === m) return m; d & 32 && (d = -(d & 31)); return d } var f = /&frostwriting=([A-Za-z0-9-_!;]+)/.exec(window.location.href); if (!f) return o; var f = f[1].split("!"), e = [], h = 0; 0 < f.length && "1;" == f[0].substr(0, 2) && (f[0] = f[0].substr(2), h = 1); for (var n = 0, j; j = f[n]; ++n) { for (var t = new S, i = m, l = 0; l < j.length;) { var s = o; if (";" == j.charAt(l)) { if (0 == h) return o; l++; s = k } if (0 == h || !i || s) { if (l + 3 >= j.length) return o; i = c(j, l); s = c(j, l + 2); if (i === m || s === m) return o; t.ba(i, s); i = [i, s]; l += 4 } else { if (l + 1 >= j.length) return o; var s = d(j, l), ja = d(j, l + 1); if (s === m || ja === m) return o; t.ba(i[0] + s, i[1] + ja); i = [i[0] + s, i[1] + ja]; l += 2 } } e.push(t) } cb(a.i, e); return k }, hb = function () { return -1 == window.location.hash.indexOf("&fp=") ? window.location.href : window.location.protocol + "//" + window.location.host + "/search?" + window.location.hash.substr(1).replace(/&fp=[0-9a-z]+/, "") }; V.prototype.wa = function (a) { a.stopPropagation(); a.preventDefault(); return o }; V.prototype.Fa = function (a) { var b = fb(this), c = hb() + "&frostwriting=" + b; if ("1;" == b) W(this, hb(), "Draw something on your window. #letitsnow"); else if (480 < c.length) { if (this.m !== m) clearTimeout(this.m), this.m = m; google.letitsnowGCO = v(this.Na, this); ib(c); this.m = setTimeout(v(function () { W(this, window.location.href, "My drawing is too complex to share, but you should try this out and have fun, anyway. #letitsnow"); this.m = m }, this), 5E3) } else W(this, c, "Check out what I drew. #letitsnow"); return this.wa(a) }; var W = function (a, b, c) { if (a.m !== m) clearTimeout(a.m), a.m = m; gbar.asmc(function () { return { items: [{ properties: { url: [b], name: ["Google - Let it snow!"], image: ["http://www.google.com/images/logos/google_logo_41.png"], description: [c] } }] } }); if (document.createEvent) { var d = document.createEvent("MouseEvents"); d.initEvent("click", k, o); a.V.dispatchEvent(d) } else a.V.fireEvent && a.V.fireEvent("onclick") }; V.prototype.qa = function () { this.a = document.getElementById("gbgs3"); this.U = document.getElementById("gbwc"); this.V = document.getElementById("gbg3"); if (this.a && this.U && this.V) { this.p = document.createElement("div"); O(this.p, { height: this.a.offsetHeight + "px", width: this.a.offsetWidth + "px" }); this.a.parentNode.insertBefore(this.p, this.a); var a = N(this.a); this.va = O(this.a, { font: "13px/27px Arial,sans-serif", left: a.x + "px", position: "fixed", top: a.y - this.a.offsetHeight + "px", zIndex: 1201 }); this.ua = O(this.U, { background: "#fff", zIndex: 1201 }); this.a.parentNode.removeChild(this.a); document.body.appendChild(this.a); "SPAN" == this.a.tagName ? this.a.style.lineHeight = "20px" : this.D.M = this.a; this.g.k(this.a, "click", v(this.Fa, this)); this.g.k(this.a, "mousedown", v(this.wa, this)) } }; V.prototype.detach = function () { if (this.a && this.U) { this.m !== m && clearTimeout(this.m); O(this.a, this.va); O(this.U, this.ua); this.D.restore(); for (var a = this.g, b = this.a, c = 0; c < a.H.length; ++c) { var d = a.H[c]; d && d[0] == b && (Wa.apply(m, d), a.H[c] = m) } this.a.parentNode.removeChild(this.a); this.p.parentNode.insertBefore(this.a, this.p); this.p.parentNode.removeChild(this.p); this.p = this.a = m } }; V.prototype.pa = function () { if (this.a && this.p) this.a.style.left = N(this.p).x + "px" }; V.prototype.Na = function (a) { a && "OK" == a.status && !a.error && a.id && (clearTimeout(this.m), W(this, a.id, "Check out what I drew. #letitsnow")) }; var ib = function (a) { var a = a.replace(window.location.host, "www.google.com"), b = document.createElement("script"); b.src = "//google-doodles.appspot.com/?callback=google.letitsnowGCO&url=" + encodeURIComponent(a); document.body.appendChild(b) }; var jb = Math.floor(60), kb = Math.floor(300), X = function () { this.J = this.i = this.K = this.h = this.A = m; this.Z = this.ia = o; this.g = this.F = m; this.ha = o; this.T = 0; this.ja = this.R = m; this.Da = window.opera || navigator.userAgent.match(/MSIE/) ? jb : kb }, Y = "goog.egg.snowyfog.Snowyfog".split("."), Z = q; !(Y[0] in Z) && Z.execScript && Z.execScript("var " + Y[0]); for (var $; Y.length && ($ = Y.shift());)!Y.length && X !== g ? Z[$] = X : Z = Z[$] ? Z[$] : Z[$] = {}; X.prototype.init = function () { var a = this, b = function () { document.getElementById("snfloader_script") && (!document.getElementById("foot") && !document.getElementById("bfoot") ? window.setTimeout(b, 50) : (google.rein && google.dstr && (google.rein.push(v(a.Aa, a)), google.dstr.push(v(a.Pa, a))), a.Aa())) }; b() }; X.prototype.init = X.prototype.init; X.prototype.Aa = function () { if (!google || !google.snowyfogInited) { google.snowyfogInited = k; var a = document.createElement("canvas"); document.body.insertBefore(a, document.body.firstChild); this.h = a; O(this.h, { pointerEvents: "none", position: "fixed", top: "0", left: "0", zIndex: 1200 }); this.h.width = window.innerWidth; this.h.height = window.innerHeight; this.T = 0; this.ha = this.Z = this.ia = o; this.g = new Va; this.A = document.createElement("div"); a = window.opera || navigator.userAgent.match(/MSIE/) ? 0 : 800; O(this.A, { pointerEvents: "none", position: "absolute", zIndex: a, width: document.body.clientWidth + "px", height: Math.max(window.innerHeight, document.body.clientHeight) + "px", overflow: "hidden" }); document.body.insertBefore(this.A, document.body.firstChild); this.K = new R(this.A); this.i = new Ya(this.g, this.h, 0, 0); this.F = new V(this.g, this.i); this.J = new U(this.g); a = v(this.K.Ca, this.K); this.g.k(window, "resize", v(this.N, this)); this.g.k(window, "deviceorientation", a); this.g.k(window, "MozOrientation", a); this.R = this.h.getContext("2d"); gb(this.F) && (ab(this.i, this.R), lb(this)); this.ja = v(this.Ba, this); window.setTimeout(this.ja, 50) } }; X.prototype.Pa = function () { this.ha = k; for (var a = this.g, b = 0; b < a.H.length; ++b) { var c = a.H[b]; c && (Wa.apply(m, c), a.H[b] = m) } this.J.detach(); this.F.detach(); if (this.h) this.h.parentNode.removeChild(this.h), this.h = m; if (this.A) this.A.parentNode.removeChild(this.A), this.A = m }; var lb = function (a) { if (!a.ia) a.ia = k, a.h.style.pointerEvents = "auto", Ta(), db(a.i), a.F.qa(), a.J.qa(v(function (a) { this.Z = o; this.i = m; this.h && this.h.parentNode.removeChild(this.h); this.h = m; this.J.detach(); this.F.detach(); a.stopPropagation() }, a)) }, mb = function (a) { a.K.s(); if (a.Z) { var b = a.i; if (!(580.8 > b.S) && !(b.$ || 88 < b.ga)) { for (var c = b.S = 0, d = 0; 66 > d; d++) for (var f = 0; 88 > f; f++) b.w[d][f] += b.G[d][f], 3.5 <= b.w[d][f] && c++; b.ga++; if (c >= 70.4 * 66) b.$ = k; else for (d = 0; 66 > d; d++) for (f = 0; 88 > f; f++) if (c = 4 - b.w[d][f], c > 4 * Math.random() && 0.7 < Math.random()) { var e = Math.min(1, 3 * $a(b, f, d)) * Math.random(); b.G[d][f] = c * e } else b.G[d][f] = 0 } a.i.s(a.R); a.J.D.s(); a.F.D.s() } }; X.prototype.Ba = function () { if (!this.ha) { window.setTimeout(this.ja, 50); this.T++; if (this.T == jb) this.Z = k; this.T == this.Da && lb(this); mb(this) } }; X.prototype.N = function () { this.K && this.K.N(document.body.offsetWidth, Math.max(document.body.offsetHeight, window.innerHeight)); this.i && (!navigator.userAgent.match(/iPad/) || this.T > jb) && this.i.N(window.innerWidth, window.innerHeight, this.R); lb(this); this.J.pa(); this.F.pa(); this.A && this.R && mb(this) }; X.prototype.resize = X.prototype.N; })();
coolspring1293/coolspring1293.github.io
snow.js
JavaScript
mit
41,004
import { Type } from '@ephox/katamari'; // some elements, such as mathml, don't have style attributes // others, such as angular elements, have style attributes that aren't a CSSStyleDeclaration const isSupported = (dom: Node): dom is HTMLStyleElement => // eslint-disable-next-line @typescript-eslint/unbound-method (dom as HTMLStyleElement).style !== undefined && Type.isFunction((dom as HTMLStyleElement).style.getPropertyValue); export { isSupported };
tinymce/tinymce
modules/sugar/src/main/ts/ephox/sugar/impl/Style.ts
TypeScript
mit
463
<?php namespace Backend\Modules\MediaLibrary\Actions; use Backend\Core\Language\Language; use Backend\Modules\MediaLibrary\Domain\MediaFolder\MediaFolder; use Backend\Modules\MediaLibrary\Domain\MediaGroup\MediaGroupType; use Backend\Modules\MediaLibrary\Domain\MediaItem\MediaItemSelectionDataGrid; use Backend\Modules\MediaLibrary\Domain\MediaItem\Type; class MediaBrowserImages extends MediaBrowser { public function display(string $template = null): void { parent::display($template ?? '/' . $this->getModule() . '/Layout/Templates/MediaBrowser.html.twig'); } protected function parse(): void { // Parse files necessary for the media upload helper MediaGroupType::parseFiles(); parent::parseDataGrids($this->mediaFolder); /** @var int|null $mediaFolderId */ $mediaFolderId = ($this->mediaFolder instanceof MediaFolder) ? $this->mediaFolder->getId() : null; $this->template->assign('folderId', $mediaFolderId); $this->template->assign('tree', $this->get('media_library.manager.tree_media_browser_images')->getHTML()); $this->header->addJsData('MediaLibrary', 'openedFolderId', $mediaFolderId); } protected function getDataGrids(MediaFolder $mediaFolder = null): array { return array_map( function ($type) use ($mediaFolder) { $dataGrid = MediaItemSelectionDataGrid::getDataGrid( Type::fromString($type), ($mediaFolder !== null) ? $mediaFolder->getId() : null ); return [ 'label' => Language::lbl('MediaMultiple' . ucfirst($type)), 'tabName' => 'tab' . ucfirst($type), 'mediaType' => $type, 'html' => $dataGrid->getContent(), 'numberOfResults' => $dataGrid->getNumResults(), ]; }, [Type::IMAGE] ); } }
jeroendesloovere/forkcms
src/Backend/Modules/MediaLibrary/Actions/MediaBrowserImages.php
PHP
mit
1,977
import HomeRoute from 'routes/Home'; describe('(Route) Home', () => { let _component; beforeEach(() => { _component = HomeRoute.component(); }); it('Should return a route configuration object', () => { expect(typeof HomeRoute).to.equal('object'); }); it('Should define a route component', () => { expect(_component.type).to.equal('div'); }); });
krizkasper/react-redux-kriz
tests/routes/Home/index.spec.js
JavaScript
mit
402
using GE.WebUI.ViewModels.Abstracts; using SX.WebCore.MvcControllers; namespace GE.WebUI.Controllers { public sealed class RssController : SxRssController<VMMaterial> { } }
simlex-titul2005/game-exe.com
GE.WebUI/Controllers/RssController.cs
C#
mit
188
import 'docs/src/modules/components/bootstrap'; // --- Post bootstrap ----- import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './input.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default Page;
Kagami/material-ui
pages/api/input.js
JavaScript
mit
297
var searchData= [ ['clear',['clear',['../d8/d84/a00001.html#a11dc3b617f2fedbb3b499971493b9c4f',1,'ArrayBase']]] ];
bdfoster/cpp-templates
docs/html/search/functions_1.js
JavaScript
mit
117
/* Copyright 2006 by Sean Luke Licensed under the Academic Free License version 3.0 See the file "LICENSE" for more information */ package ec.app.parity.func; import ec.*; import ec.app.parity.*; import ec.gp.*; import ec.util.*; /* * D31.java * * Created: Wed Nov 3 18:31:38 1999 * By: Sean Luke */ /** * @author Sean Luke * @version 1.0 */ public class D31 extends GPNode { public String toString() { return "D31"; } /* public void checkConstraints(final EvolutionState state, final int tree, final GPIndividual typicalIndividual, final Parameter individualBase) { super.checkConstraints(state,tree,typicalIndividual,individualBase); if (children.length!=0) state.output.error("Incorrect number of children for node " + toStringForError() + " at " + individualBase); } */ public int expectedChildren() { return 0; } public void eval(final EvolutionState state, final int thread, final GPData input, final ADFStack stack, final GPIndividual individual, final Problem problem) { ((ParityData)input).x = ((((Parity)problem).bits >>> 31 ) & 1); } }
meiyi1986/GPJSS
src/ec/app/parity/func/D31.java
Java
mit
1,195
// Copyright (c) 2015 ZZZ Projects. All rights reserved // Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) // Website: http://www.zzzprojects.com/ // Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 // All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library public static partial class Extensions { /// <summary> /// A string extension method that get the string between the two specified string. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="before">The string before to search.</param> /// <param name="after">The string after to search.</param> /// <returns>The string between the two specified string.</returns> public static string GetBetween(this string @this, string before, string after) { int beforeStartIndex = @this.IndexOf(before); int startIndex = beforeStartIndex + before.Length; int afterStartIndex = @this.IndexOf(after, startIndex); if (beforeStartIndex == -1 || afterStartIndex == -1) { return ""; } return @this.Substring(startIndex, afterStartIndex - startIndex); } }
huoxudong125/Z.ExtensionMethods
src/Z.Core/System.String/String.GetBetween.cs
C#
mit
1,266
using System; using System.Threading.Tasks; using Orleans; using Tester.CodeGenTests; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace DefaultCluster.Tests.General { [TestCategory("CodeGen")] public class CodeGeneratorTests_AccessibilityChecks : HostedTestClusterEnsureDefaultStarted { /// <summary> /// Tests that compile-time code generation supports classes marked as internal and that /// runtime code generation does not. /// </summary> /// <returns>A <see cref="Task"/> representing the work performed.</returns> [Fact, TestCategory("BVT")] public async Task CodeGenInterfaceAccessibilityCheckTest() { // Runtime codegen does not support internal interfaces. Assert.Throws<InvalidOperationException>(() => GrainFactory.GetGrain<IRuntimeInternalPingGrain>(9)); // Compile-time codegen supports internal interfaces. var grain = GrainFactory.GetGrain<IInternalPingGrain>(0); await grain.Ping(); } } internal interface IRuntimeInternalPingGrain : IGrainWithIntegerKey { Task Ping(); } internal class InternalPingGrain : Grain, IInternalPingGrain, IRuntimeInternalPingGrain { public Task Ping() => Task.FromResult(0); } }
rrector/orleans
test/DefaultCluster.Tests/CodeGeneratorTests_AccessibilityChecks.cs
C#
mit
1,347
#include "macros.h" #include "thread.h" using namespace std; ndb_thread::~ndb_thread() { } void ndb_thread::start() { thd_ = std::move(thread(&ndb_thread::run, this)); if (daemon_) thd_.detach(); } void ndb_thread::join() { ALWAYS_ASSERT(!daemon_); thd_.join(); } // can be overloaded by subclasses void ndb_thread::run() { ALWAYS_ASSERT(body_); body_(); }
stephentu/silo
thread.cc
C++
mit
378
/*jslint node: true, vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 2, maxerr: 50*/ /*global define, $, brackets, Mustache, window, appshell*/ define(function (require, exports, module) { "use strict"; // HEADER >> var NodeConnection = brackets.getModule("utils/NodeConnection"), Menus = brackets.getModule("command/Menus"), CommandManager = brackets.getModule("command/CommandManager"), Commands = brackets.getModule("command/Commands"), PreferencesManager = brackets.getModule("preferences/PreferencesManager"), _ = brackets.getModule("thirdparty/lodash"), KeyBindingManager = brackets.getModule("command/KeyBindingManager"); var ExtensionDiagnosis = require("modules/ExtensionDiagnosis"), Log = require("modules/Log"), Panel = require("modules/Panel"), FileTreeView = require("modules/FileTreeView"), Strings = require("strings"); var treeViewContextMenu = null; var _nodeConnection = null; var showMainPanel, initTreeViewContextMenu, setRootMenu, setDebugMenu, reloadBrackets, treeViewContextMenuState; var _disableTreeViewContextMenuAllItem; //<< var ContextMenuIds = { TREEVIEW_CTX_MENU: "kohei-synapse-treeview-context-menu" }; var ContextMenuCommandIds = { SYNAPSE_FILE_NEW: "kohei.synapse.file_new", SYNAPSE_DIRECTORY_NEW: "kohei.synapse.directory_new", SYNAPSE_FILE_REFRESH: "kohei.synapse.file_refresh", SYNAPSE_FILE_RENAME: "kohei.synapse.file_rename", SYNAPSE_DELETE: "kohei.synapse.delete" }; var MenuText = { SYNAPSE_CTX_FILE_NEW: Strings.SYNAPSE_CTX_FILE_NEW, SYNAPSE_CTX_DIRECTORY_NEW: Strings.SYNAPSE_CTX_DIRECTORY_NEW, SYNAPSE_CTX_FILE_REFRESH: Strings.SYNAPSE_CTX_FILE_REFRESH, SYNAPSE_CTX_FILE_RENAME: Strings.SYNAPSE_CTX_FILE_RENAME, SYNAPSE_CTX_DELETE: Strings.SYNAPSE_CTX_DELETE }; var Open_TreeView_Context_Menu_On_Directory_State = [ ContextMenuCommandIds.SYNAPSE_FILE_NEW, ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, ContextMenuCommandIds.SYNAPSE_DELETE, ContextMenuCommandIds.SYNAPSE_FILE_REFRESH, ContextMenuCommandIds.SYNAPSE_FILE_RENAME ]; var Open_TreeView_Context_Menu_On_Linked_Directory_State = [ ContextMenuCommandIds.SYNAPSE_FILE_NEW, ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, ContextMenuCommandIds.SYNAPSE_DELETE, ContextMenuCommandIds.SYNAPSE_FILE_REFRESH ]; var Open_TreeView_Context_Menu_On_File_State = [ ContextMenuCommandIds.SYNAPSE_FILE_RENAME, ContextMenuCommandIds.SYNAPSE_DELETE ]; var Open_TreeView_Context_Menu_On_Linked_File_State = [ ContextMenuCommandIds.SYNAPSE_FILE_RENAME, ContextMenuCommandIds.SYNAPSE_DELETE ]; var Open_TreeView_Context_Menu_On_Root_State = [ ContextMenuCommandIds.SYNAPSE_FILE_NEW, ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, ContextMenuCommandIds.SYNAPSE_FILE_REFRESH ]; showMainPanel = function () { CommandManager.execute("kohei.synapse.mainPanel"); }; treeViewContextMenuState = function (entity) { _disableTreeViewContextMenuAllItem(); if (entity.class === "treeview-root") { Open_TreeView_Context_Menu_On_Root_State.forEach(function (id) { CommandManager.get(id).setEnabled(true); }); return; } if (entity.class === "treeview-directory") { Open_TreeView_Context_Menu_On_Directory_State.forEach(function (id) { CommandManager.get(id).setEnabled(true); }); return; } else if (entity.class === "treeview-ldirectory") { Open_TreeView_Context_Menu_On_Linked_Directory_State.forEach(function (id) { CommandManager.get(id).setEnabled(true); }); return; } else if (entity.class === "treeview-file") { Open_TreeView_Context_Menu_On_File_State.forEach(function (id) { CommandManager.get(id).setEnabled(true); }); return; } }; setRootMenu = function (domain) { var menu = CommandManager.register( "Synapse", "kohei.synapse.mainPanel", Panel.showMain); var topMenu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU); topMenu.addMenuDivider(); topMenu.addMenuItem(menu, { key: "Ctrl-Shift-Alt-Enter", displayKey: "Ctrl-Shift-Alt-Enter" }); //For Debug > //Panel.showMain(); setDebugMenu(); return new $.Deferred().resolve(domain).promise(); }; setDebugMenu = function () { var menu = CommandManager.register( "Reload App wiz Node", "kohei.syanpse.reloadBrackets", reloadBrackets); var topMenu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU); topMenu.addMenuDivider(); topMenu.addMenuItem(menu, { key: "Ctrl-Shift-F6", displeyKey: "Ctrl-Shift-F6" }); }; reloadBrackets = function () { try { _nodeConnection.domains.base.restartNode(); CommandManager.execute(Commands.APP_RELOAD); } catch (e) { console.log("SYNAPSE ERROR - Failed trying to restart Node", e); } }; initTreeViewContextMenu = function () { var d = new $.Deferred(); CommandManager .register(MenuText.SYNAPSE_CTX_FILE_REFRESH, ContextMenuCommandIds.SYNAPSE_FILE_REFRESH, FileTreeView.refresh); CommandManager .register(MenuText.SYNAPSE_CTX_FILE_RENAME, ContextMenuCommandIds.SYNAPSE_FILE_RENAME, FileTreeView.rename); CommandManager .register(MenuText.SYNAPSE_CTX_FILE_NEW, ContextMenuCommandIds.SYNAPSE_FILE_NEW, FileTreeView.newFile); CommandManager .register(MenuText.SYNAPSE_CTX_DIRECTORY_NEW, ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, FileTreeView.newDirectory); CommandManager .register(MenuText.SYNAPSE_CTX_DELETE, ContextMenuCommandIds.SYNAPSE_DELETE, FileTreeView.removeFile); treeViewContextMenu = Menus.registerContextMenu(ContextMenuIds.TREEVIEW_CTX_MENU); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_FILE_REFRESH); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_FILE_RENAME, null, Menus.LAST, null); treeViewContextMenu .addMenuDivider(); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_FILE_NEW, null, Menus.LAST, null); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, null, Menus.LAST, null); treeViewContextMenu .addMenuDivider(); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_DELETE, null, Menus.LAST, null); $("#synapse-treeview-container").contextmenu(function (e) { FileTreeView.onTreeViewContextMenu(e, treeViewContextMenu); }); return d.resolve().promise(); }; /* Private Methods */ _disableTreeViewContextMenuAllItem = function () { if (treeViewContextMenu === null) { return; } _.forIn(ContextMenuCommandIds, function (val, key) { CommandManager.get(val).setEnabled(false); }); }; /* for Debug */ _nodeConnection = new NodeConnection(); _nodeConnection.connect(true); exports.showMainPanel = showMainPanel; exports.setRootMenu = setRootMenu; exports.initTreeViewContextMenu = initTreeViewContextMenu; exports.ContextMenuCommandIds = ContextMenuCommandIds; exports.ContextMenuIds = ContextMenuIds; exports.treeViewContextMenuState = treeViewContextMenuState; exports.getModuleName = function () { return module.id; }; });
marcandrews/brackets-synapse
modules/Menu.js
JavaScript
mit
7,210
'output dimensionalities for each column' import csv import sys import re import math from collections import defaultdict def get_words( text ): text = text.replace( "'", "" ) text = re.sub( r'\W+', ' ', text ) text = text.lower() text = text.split() words = [] for w in text: if w in words: continue words.append( w ) return words ### csv.field_size_limit( 1000000 ) input_file = sys.argv[1] target_col = 'SalaryNormalized' cols2tokenize = [ 'Title', 'FullDescription' ] cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ] cols2drop = [ 'SalaryRaw' ] ### i_f = open( input_file ) reader = csv.reader( i_f ) headers = reader.next() target_index = headers.index( target_col ) indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize ) indexes2binarize = map( lambda x: headers.index( x ), cols2binarize ) indexes2drop = map( lambda x: headers.index( x ), cols2drop ) n = 0 unique_values = defaultdict( set ) for line in reader: for i in indexes2binarize: value = line[i] unique_values[i].add( value ) for i in indexes2tokenize: words = get_words( line[i] ) unique_values[i].update( words ) n += 1 if n % 10000 == 0: print n # print counts for i in sorted( unique_values ): l = len( unique_values[i] ) print "index: %s, count: %s" % ( i, l ) if l < 100: pass # print unique_values[i]
zygmuntz/kaggle-advertised-salaries
optional/cols_dimensionality.py
Python
mit
1,451
#include <seqan/sequence.h> #include <seqan/basic.h> #include <seqan/find_motif.h> #include <seqan/file.h> #include <iostream> using namespace seqan; template<typename TString>//String<char> void countOneMers(TString const& str){ Iterator<TString>::Type StringIterator = begin(str); Iterator<TString>::Type EndIterator = end(str); String<unsigned int> counter; resize(counter, 26,0);//26 = AlphSize unsigned int normalize =ordValue('a'); unsigned int a=0; while(StringIterator != EndIterator){ a= ordValue(*StringIterator); std::cout<<a-normalize<<std::endl; ++value(counter,(a-normalize)); ++StringIterator; } StringIterator = begin(str); //Iterator<String<unsigned int> >::Type countIterator = begin(counter); int i=0; while(i<26){ if(counter[i]>0) std::cout<<char(i+'a')<<" "<<counter[i]<<std::endl; ++i; } } void replaceAs(String<char>& str){ str="hi"; } int main(){ String<char> str = "helloworld"; //countOneMers(str); replaceAs(str); std::cout<<str; return 0; }
bkahlert/seqan-research
raw/pmbs12/pmsb13-data-20120615/sources/brbym28nz827lxic/93/sandbox/meyerclp/demos/Sequences.cpp
C++
mit
1,018
package dbfiles import ( "encoding/csv" "io" "github.com/juju/errgo" ) type Driver interface { Extention() string Write(io.Writer, []string) error Read(io.Reader) ([][]string, error) } type CSV struct{} func (driver CSV) Extention() string { return "csv" } func (driver CSV) Write(writer io.Writer, values []string) error { csvwriter := csv.NewWriter(writer) err := csvwriter.WriteAll([][]string{values}) if err != nil { return errgo.Notef(err, "can not write to csv writer") } return nil } func (driver CSV) Read(reader io.Reader) ([][]string, error) { csvreader := csv.NewReader(reader) csvreader.FieldsPerRecord = -1 var values [][]string values, err := csvreader.ReadAll() if err != nil { return nil, errgo.Notef(err, "can not read all records from file") } return values, nil }
AlexanderThaller/lablog
vendor/github.com/AlexanderThaller/dbfiles/driver.go
GO
mit
818
const ASSETS_MODS_LENGTH = 13;//'/assets/mods/'.length; const CONTENT_TYPES = { 'css': 'text/css', 'js': 'text/javascript', 'json': 'application/json', 'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'html': 'text/html', 'htm': 'text/html' }; /** * @type {Map<string, JSZip>} */ const jszipCache = new Map(); //Not exported because serviceworkers can't use es6 modules // eslint-disable-next-line no-unused-vars class PackedManager { /** * * @param {string} url */ async get(url) { try { const zip = await this._openZip(url); const file = zip.file(this._assetPath(url)); if (file === null) { return new Response(new Blob(), { status: 404, statusText: 'not found' }); } return new Response(await file.async('blob'), { headers: { 'Content-Type': this._contentType(url) }, status: 200, statusText: 'ok' }); } catch (e) { console.error('An error occured while reading a packed mod', e); return e; } } /** * * @param {string} url * @returns {Promise<string[]>} */ async getFiles(url) { const zip = await this._openZip(url); const folder = this._openFolder(zip, this._assetPath(url)); const result = []; folder.forEach((relativePath, file) => { if (!file.dir) { result.push(relativePath); } }); return result; } /** * * @param {string} url * @returns {Promise<boolean>} */ async isDirectory(url) { const zip = await this._openZip(url); const file = zip.file(this._assetPath(url)); return file && file.dir; } /** * * @param {string} url * @returns {Promise<boolean>} */ async isFile(url) { const zip = await this._openZip(url); const file = zip.file(this._assetPath(url)); return !!file; } /** * * @param {string} url */ packedName(url) { url = this._normalize(url); return decodeURIComponent(url.substring(ASSETS_MODS_LENGTH, url.indexOf('/', ASSETS_MODS_LENGTH))); } /** * * @param {string} url */ async _openZip(url) { const zip = this._zipPath(url); const cached = jszipCache.get(zip); if (cached) { return cached; } const request = new Request('http://' + location.hostname + '.cc' + zip); const cache = await caches.open('zips'); let response = await cache.match(request); if (!response) { response = await fetch(zip); cache.put(request, response.clone()); } const result = await JSZip.loadAsync(response.blob()); jszipCache.set(zip, result); return result; } /** * * @param {JSZip} root * @param {string} path */ _openFolder(root, path) { const folders = path.split(/\//g); for (const folder of folders) { root = root.folder(folder); } return root; } /** * @param {string} url * @returns {string} */ _contentType(url) { url = this._normalize(url); return CONTENT_TYPES[url.substr(url.lastIndexOf('.') + 1)] || 'text/plain'; } /** * * @param {string} url */ _zipPath(url) { url = this._normalize(url); return url.substr(0, url.indexOf('/', ASSETS_MODS_LENGTH)); } /** * * @param {string} url */ _assetPath(url) { url = this._normalize(url); return url.substr(url.indexOf('/', ASSETS_MODS_LENGTH) + 1); } /** * * @param {string} url */ _normalize(url) { url = url.replace(/\\/g, '/').replace(/\/\//, '/'); //TODO: resolve absolute paths if (!url.startsWith('/')) { url = '/' + url; } if (url.startsWith('/ccloader')) { url = url.substr(9); // '/ccloader'.length } return url; } }
2767mr/CCLoader
ccloader/js/packed.js
JavaScript
mit
3,555
<?php /** * Author: Nil Portugués Calderó <contact@nilportugues.com> * Date: 12/18/15 * Time: 11:36 PM. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace NilPortugues\SchemaOrg\Classes; use NilPortugues\SchemaOrg\SchemaClass; /** * METHODSTART. * * @method static \NilPortugues\SchemaOrg\Properties\BranchOfProperty branchOf() * @method static \NilPortugues\SchemaOrg\Properties\BranchCodeProperty branchCode() * @method static \NilPortugues\SchemaOrg\Properties\CurrenciesAcceptedProperty currenciesAccepted() * @method static \NilPortugues\SchemaOrg\Properties\OpeningHoursProperty openingHours() * @method static \NilPortugues\SchemaOrg\Properties\PaymentAcceptedProperty paymentAccepted() * @method static \NilPortugues\SchemaOrg\Properties\PriceRangeProperty priceRange() * @method static \NilPortugues\SchemaOrg\Properties\HasOfferCatalogProperty hasOfferCatalog() * @method static \NilPortugues\SchemaOrg\Properties\AddressProperty address() * @method static \NilPortugues\SchemaOrg\Properties\AggregateRatingProperty aggregateRating() * @method static \NilPortugues\SchemaOrg\Properties\AlumniProperty alumni() * @method static \NilPortugues\SchemaOrg\Properties\AreaServedProperty areaServed() * @method static \NilPortugues\SchemaOrg\Properties\AwardProperty award() * @method static \NilPortugues\SchemaOrg\Properties\AwardsProperty awards() * @method static \NilPortugues\SchemaOrg\Properties\ParentOrganizationProperty parentOrganization() * @method static \NilPortugues\SchemaOrg\Properties\BrandProperty brand() * @method static \NilPortugues\SchemaOrg\Properties\ContactPointProperty contactPoint() * @method static \NilPortugues\SchemaOrg\Properties\ContactPointsProperty contactPoints() * @method static \NilPortugues\SchemaOrg\Properties\DepartmentProperty department() * @method static \NilPortugues\SchemaOrg\Properties\DunsProperty duns() * @method static \NilPortugues\SchemaOrg\Properties\EmailProperty email() * @method static \NilPortugues\SchemaOrg\Properties\EmployeeProperty employee() * @method static \NilPortugues\SchemaOrg\Properties\EmployeesProperty employees() * @method static \NilPortugues\SchemaOrg\Properties\EventProperty event() * @method static \NilPortugues\SchemaOrg\Properties\EventsProperty events() * @method static \NilPortugues\SchemaOrg\Properties\FaxNumberProperty faxNumber() * @method static \NilPortugues\SchemaOrg\Properties\FounderProperty founder() * @method static \NilPortugues\SchemaOrg\Properties\FoundersProperty founders() * @method static \NilPortugues\SchemaOrg\Properties\DissolutionDateProperty dissolutionDate() * @method static \NilPortugues\SchemaOrg\Properties\FoundingDateProperty foundingDate() * @method static \NilPortugues\SchemaOrg\Properties\GlobalLocationNumberProperty globalLocationNumber() * @method static \NilPortugues\SchemaOrg\Properties\HasPOSProperty hasPOS() * @method static \NilPortugues\SchemaOrg\Properties\IsicV4Property isicV4() * @method static \NilPortugues\SchemaOrg\Properties\LegalNameProperty legalName() * @method static \NilPortugues\SchemaOrg\Properties\LocationProperty location() * @method static \NilPortugues\SchemaOrg\Properties\LogoProperty logo() * @method static \NilPortugues\SchemaOrg\Properties\MakesOfferProperty makesOffer() * @method static \NilPortugues\SchemaOrg\Properties\MemberProperty member() * @method static \NilPortugues\SchemaOrg\Properties\MemberOfProperty memberOf() * @method static \NilPortugues\SchemaOrg\Properties\MembersProperty members() * @method static \NilPortugues\SchemaOrg\Properties\NaicsProperty naics() * @method static \NilPortugues\SchemaOrg\Properties\NumberOfEmployeesProperty numberOfEmployees() * @method static \NilPortugues\SchemaOrg\Properties\OwnsProperty owns() * @method static \NilPortugues\SchemaOrg\Properties\ReviewProperty review() * @method static \NilPortugues\SchemaOrg\Properties\ReviewsProperty reviews() * @method static \NilPortugues\SchemaOrg\Properties\SeeksProperty seeks() * @method static \NilPortugues\SchemaOrg\Properties\ServiceAreaProperty serviceArea() * @method static \NilPortugues\SchemaOrg\Properties\SubOrganizationProperty subOrganization() * @method static \NilPortugues\SchemaOrg\Properties\TaxIDProperty taxID() * @method static \NilPortugues\SchemaOrg\Properties\TelephoneProperty telephone() * @method static \NilPortugues\SchemaOrg\Properties\VatIDProperty vatID() * @method static \NilPortugues\SchemaOrg\Properties\AdditionalTypeProperty additionalType() * @method static \NilPortugues\SchemaOrg\Properties\AlternateNameProperty alternateName() * @method static \NilPortugues\SchemaOrg\Properties\DescriptionProperty description() * @method static \NilPortugues\SchemaOrg\Properties\ImageProperty image() * @method static \NilPortugues\SchemaOrg\Properties\MainEntityOfPageProperty mainEntityOfPage() * @method static \NilPortugues\SchemaOrg\Properties\NameProperty name() * @method static \NilPortugues\SchemaOrg\Properties\SameAsProperty sameAs() * @method static \NilPortugues\SchemaOrg\Properties\UrlProperty url() * @method static \NilPortugues\SchemaOrg\Properties\PotentialActionProperty potentialAction() * @method static \NilPortugues\SchemaOrg\Properties\ContainedInPlaceProperty containedInPlace() * @method static \NilPortugues\SchemaOrg\Properties\ContainsPlaceProperty containsPlace() * @method static \NilPortugues\SchemaOrg\Properties\ContainedInProperty containedIn() * @method static \NilPortugues\SchemaOrg\Properties\GeoProperty geo() * @method static \NilPortugues\SchemaOrg\Properties\HasMapProperty hasMap() * @method static \NilPortugues\SchemaOrg\Properties\MapProperty map() * @method static \NilPortugues\SchemaOrg\Properties\MapsProperty maps() * @method static \NilPortugues\SchemaOrg\Properties\OpeningHoursSpecificationProperty openingHoursSpecification() * @method static \NilPortugues\SchemaOrg\Properties\PhotoProperty photo() * @method static \NilPortugues\SchemaOrg\Properties\PhotosProperty photos() * @method static \NilPortugues\SchemaOrg\Properties\AdditionalPropertyProperty additionalProperty() * METHODEND. * * An electrician. */ class Electrician extends SchemaClass { /** * @var string */ protected static $schemaUrl = 'http://schema.org/Electrician'; /** * @var array */ protected static $supportedMethods = [ 'additionalProperty' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AdditionalPropertyProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'additionalType' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AdditionalTypeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'address' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AddressProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'aggregateRating' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AggregateRatingProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'alternateName' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AlternateNameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'alumni' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AlumniProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'areaServed' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AreaServedProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'award' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AwardProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'awards' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AwardsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'branchCode' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\BranchCodeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'branchOf' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\BranchOfProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'brand' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\BrandProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'contactPoint' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContactPointProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'contactPoints' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContactPointsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'containedIn' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContainedInProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'containedInPlace' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContainedInPlaceProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'containsPlace' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContainsPlaceProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'currenciesAccepted' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\CurrenciesAcceptedProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'department' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DepartmentProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'description' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DescriptionProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'dissolutionDate' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DissolutionDateProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'duns' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DunsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'email' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EmailProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'employee' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EmployeeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'employees' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EmployeesProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'event' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EventProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'events' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EventsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'faxNumber' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FaxNumberProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'founder' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FounderProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'founders' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FoundersProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'foundingDate' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FoundingDateProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'geo' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\GeoProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'globalLocationNumber' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\GlobalLocationNumberProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'hasMap' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\HasMapProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'hasOfferCatalog' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\HasOfferCatalogProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'hasPOS' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\HasPOSProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'image' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ImageProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'isicV4' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\IsicV4Property', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'legalName' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\LegalNameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'location' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\LocationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'logo' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\LogoProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'mainEntityOfPage' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MainEntityOfPageProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'makesOffer' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MakesOfferProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'map' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MapProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'maps' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MapsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'member' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MemberProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'memberOf' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MemberOfProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'members' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MembersProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'naics' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NaicsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'name' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'numberOfEmployees' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NumberOfEmployeesProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'openingHours' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\OpeningHoursProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'openingHoursSpecification' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\OpeningHoursSpecificationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'owns' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\OwnsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'parentOrganization' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ParentOrganizationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'paymentAccepted' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PaymentAcceptedProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'photo' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PhotoProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'photos' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PhotosProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'potentialAction' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PotentialActionProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'priceRange' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PriceRangeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'review' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ReviewProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'reviews' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ReviewsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'sameAs' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SameAsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'seeks' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SeeksProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'serviceArea' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ServiceAreaProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'subOrganization' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SubOrganizationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'taxID' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\TaxIDProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'telephone' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\TelephoneProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'url' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\UrlProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'vatID' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\VatIDProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], ]; }
nilportugues/schema.org-mapping
src/Classes/Electrician.php
PHP
mit
20,303
/* micropolisJS. Adapted by Graeme McCutcheon from Micropolis. * * This code is released under the GNU GPL v3, with some additional terms. * Please see the files LICENSE and COPYING for details. Alternatively, * consult http://micropolisjs.graememcc.co.uk/LICENSE and * http://micropolisjs.graememcc.co.uk/COPYING * */ Micro.GameTools = function (map) { return { airport: new Micro.BuildingTool(10000, Tile.AIRPORT, map, 6, false), bulldozer: new Micro.BulldozerTool(map), coal: new Micro.BuildingTool(3000, Tile.POWERPLANT, map, 4, false), commercial: new Micro.BuildingTool(100, Tile.COMCLR, map, 3, false), fire: new Micro.BuildingTool(500, Tile.FIRESTATION, map, 3, false), industrial: new Micro.BuildingTool(100, Tile.INDCLR, map, 3, false), nuclear: new Micro.BuildingTool(5000, Tile.NUCLEAR, map, 4, true), park: new Micro.ParkTool(map), police: new Micro.BuildingTool(500, Tile.POLICESTATION, map, 3, false), port: new Micro.BuildingTool(3000, Tile.PORT, map, 4, false), rail: new Micro.RailTool(map), residential: new Micro.BuildingTool(100, Tile.FREEZ, map, 3, false), road: new Micro.RoadTool(map), query: new Micro.QueryTool(map), stadium: new Micro.BuildingTool(5000, Tile.STADIUM, map, 4, false), wire: new Micro.WireTool(map), }; };
ArcherSys/ArcherSys
game/3d.city-gh-pages/src/tool/GameTools.js
JavaScript
mit
1,390
export { default as createShallow } from './createShallow'; export { default as createMount } from './createMount'; export { default as createRender } from './createRender'; export { default as findOutermostIntrinsic, wrapsIntrinsicElement } from './findOutermostIntrinsic'; export { default as getClasses } from './getClasses'; export { default as unwrap } from './unwrap';
lgollut/material-ui
packages/material-ui/src/test-utils/index.js
JavaScript
mit
375
var expect = require("chai").expect; var reindeerRace = require("../../src/day-14/reindeer-race"); describe("--- Day 14: (1/2) distance traveled --- ", () => { it("counts the distance traveled after 1000s", () => { var reindeerSpecs = [ "Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.", "Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds." ]; expect(reindeerRace.race(reindeerSpecs, 1000).winnerByDistance.distanceTraveled).to.equal(1120); }); }); describe("--- Day 14: (2/2) points awarded --- ", () => { it("counts the points awarded for being in the lead after 1000s", () => { var reindeerSpecs = [ "Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.", "Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds." ]; expect(reindeerRace.race(reindeerSpecs, 1000).winnerByPoints.pointsAwarded).to.equal(689); }); });
gbranchaudrubenovitch/advent-of-code
test/day-14/reindeer-race-test.js
JavaScript
mit
969
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var jsdom = require("jsdom"); var chai_1 = require("chai"); var ColorManager_1 = require("./ColorManager"); describe('ColorManager', function () { var cm; var dom; var document; var window; beforeEach(function () { dom = new jsdom.JSDOM(''); window = dom.window; document = window.document; window.HTMLCanvasElement.prototype.getContext = function () { return ({ createLinearGradient: function () { return null; }, fillRect: function () { }, getImageData: function () { return { data: [0, 0, 0, 0xFF] }; } }); }; cm = new ColorManager_1.ColorManager(document, false); }); describe('constructor', function () { it('should fill all colors with values', function () { for (var _i = 0, _a = Object.keys(cm.colors); _i < _a.length; _i++) { var key = _a[_i]; if (key !== 'ansi') { chai_1.assert.ok(cm.colors[key].css.length >= 7); } } chai_1.assert.equal(cm.colors.ansi.length, 256); }); it('should fill 240 colors with expected values', function () { chai_1.assert.equal(cm.colors.ansi[16].css, '#000000'); chai_1.assert.equal(cm.colors.ansi[17].css, '#00005f'); chai_1.assert.equal(cm.colors.ansi[18].css, '#000087'); chai_1.assert.equal(cm.colors.ansi[19].css, '#0000af'); chai_1.assert.equal(cm.colors.ansi[20].css, '#0000d7'); chai_1.assert.equal(cm.colors.ansi[21].css, '#0000ff'); chai_1.assert.equal(cm.colors.ansi[22].css, '#005f00'); chai_1.assert.equal(cm.colors.ansi[23].css, '#005f5f'); chai_1.assert.equal(cm.colors.ansi[24].css, '#005f87'); chai_1.assert.equal(cm.colors.ansi[25].css, '#005faf'); chai_1.assert.equal(cm.colors.ansi[26].css, '#005fd7'); chai_1.assert.equal(cm.colors.ansi[27].css, '#005fff'); chai_1.assert.equal(cm.colors.ansi[28].css, '#008700'); chai_1.assert.equal(cm.colors.ansi[29].css, '#00875f'); chai_1.assert.equal(cm.colors.ansi[30].css, '#008787'); chai_1.assert.equal(cm.colors.ansi[31].css, '#0087af'); chai_1.assert.equal(cm.colors.ansi[32].css, '#0087d7'); chai_1.assert.equal(cm.colors.ansi[33].css, '#0087ff'); chai_1.assert.equal(cm.colors.ansi[34].css, '#00af00'); chai_1.assert.equal(cm.colors.ansi[35].css, '#00af5f'); chai_1.assert.equal(cm.colors.ansi[36].css, '#00af87'); chai_1.assert.equal(cm.colors.ansi[37].css, '#00afaf'); chai_1.assert.equal(cm.colors.ansi[38].css, '#00afd7'); chai_1.assert.equal(cm.colors.ansi[39].css, '#00afff'); chai_1.assert.equal(cm.colors.ansi[40].css, '#00d700'); chai_1.assert.equal(cm.colors.ansi[41].css, '#00d75f'); chai_1.assert.equal(cm.colors.ansi[42].css, '#00d787'); chai_1.assert.equal(cm.colors.ansi[43].css, '#00d7af'); chai_1.assert.equal(cm.colors.ansi[44].css, '#00d7d7'); chai_1.assert.equal(cm.colors.ansi[45].css, '#00d7ff'); chai_1.assert.equal(cm.colors.ansi[46].css, '#00ff00'); chai_1.assert.equal(cm.colors.ansi[47].css, '#00ff5f'); chai_1.assert.equal(cm.colors.ansi[48].css, '#00ff87'); chai_1.assert.equal(cm.colors.ansi[49].css, '#00ffaf'); chai_1.assert.equal(cm.colors.ansi[50].css, '#00ffd7'); chai_1.assert.equal(cm.colors.ansi[51].css, '#00ffff'); chai_1.assert.equal(cm.colors.ansi[52].css, '#5f0000'); chai_1.assert.equal(cm.colors.ansi[53].css, '#5f005f'); chai_1.assert.equal(cm.colors.ansi[54].css, '#5f0087'); chai_1.assert.equal(cm.colors.ansi[55].css, '#5f00af'); chai_1.assert.equal(cm.colors.ansi[56].css, '#5f00d7'); chai_1.assert.equal(cm.colors.ansi[57].css, '#5f00ff'); chai_1.assert.equal(cm.colors.ansi[58].css, '#5f5f00'); chai_1.assert.equal(cm.colors.ansi[59].css, '#5f5f5f'); chai_1.assert.equal(cm.colors.ansi[60].css, '#5f5f87'); chai_1.assert.equal(cm.colors.ansi[61].css, '#5f5faf'); chai_1.assert.equal(cm.colors.ansi[62].css, '#5f5fd7'); chai_1.assert.equal(cm.colors.ansi[63].css, '#5f5fff'); chai_1.assert.equal(cm.colors.ansi[64].css, '#5f8700'); chai_1.assert.equal(cm.colors.ansi[65].css, '#5f875f'); chai_1.assert.equal(cm.colors.ansi[66].css, '#5f8787'); chai_1.assert.equal(cm.colors.ansi[67].css, '#5f87af'); chai_1.assert.equal(cm.colors.ansi[68].css, '#5f87d7'); chai_1.assert.equal(cm.colors.ansi[69].css, '#5f87ff'); chai_1.assert.equal(cm.colors.ansi[70].css, '#5faf00'); chai_1.assert.equal(cm.colors.ansi[71].css, '#5faf5f'); chai_1.assert.equal(cm.colors.ansi[72].css, '#5faf87'); chai_1.assert.equal(cm.colors.ansi[73].css, '#5fafaf'); chai_1.assert.equal(cm.colors.ansi[74].css, '#5fafd7'); chai_1.assert.equal(cm.colors.ansi[75].css, '#5fafff'); chai_1.assert.equal(cm.colors.ansi[76].css, '#5fd700'); chai_1.assert.equal(cm.colors.ansi[77].css, '#5fd75f'); chai_1.assert.equal(cm.colors.ansi[78].css, '#5fd787'); chai_1.assert.equal(cm.colors.ansi[79].css, '#5fd7af'); chai_1.assert.equal(cm.colors.ansi[80].css, '#5fd7d7'); chai_1.assert.equal(cm.colors.ansi[81].css, '#5fd7ff'); chai_1.assert.equal(cm.colors.ansi[82].css, '#5fff00'); chai_1.assert.equal(cm.colors.ansi[83].css, '#5fff5f'); chai_1.assert.equal(cm.colors.ansi[84].css, '#5fff87'); chai_1.assert.equal(cm.colors.ansi[85].css, '#5fffaf'); chai_1.assert.equal(cm.colors.ansi[86].css, '#5fffd7'); chai_1.assert.equal(cm.colors.ansi[87].css, '#5fffff'); chai_1.assert.equal(cm.colors.ansi[88].css, '#870000'); chai_1.assert.equal(cm.colors.ansi[89].css, '#87005f'); chai_1.assert.equal(cm.colors.ansi[90].css, '#870087'); chai_1.assert.equal(cm.colors.ansi[91].css, '#8700af'); chai_1.assert.equal(cm.colors.ansi[92].css, '#8700d7'); chai_1.assert.equal(cm.colors.ansi[93].css, '#8700ff'); chai_1.assert.equal(cm.colors.ansi[94].css, '#875f00'); chai_1.assert.equal(cm.colors.ansi[95].css, '#875f5f'); chai_1.assert.equal(cm.colors.ansi[96].css, '#875f87'); chai_1.assert.equal(cm.colors.ansi[97].css, '#875faf'); chai_1.assert.equal(cm.colors.ansi[98].css, '#875fd7'); chai_1.assert.equal(cm.colors.ansi[99].css, '#875fff'); chai_1.assert.equal(cm.colors.ansi[100].css, '#878700'); chai_1.assert.equal(cm.colors.ansi[101].css, '#87875f'); chai_1.assert.equal(cm.colors.ansi[102].css, '#878787'); chai_1.assert.equal(cm.colors.ansi[103].css, '#8787af'); chai_1.assert.equal(cm.colors.ansi[104].css, '#8787d7'); chai_1.assert.equal(cm.colors.ansi[105].css, '#8787ff'); chai_1.assert.equal(cm.colors.ansi[106].css, '#87af00'); chai_1.assert.equal(cm.colors.ansi[107].css, '#87af5f'); chai_1.assert.equal(cm.colors.ansi[108].css, '#87af87'); chai_1.assert.equal(cm.colors.ansi[109].css, '#87afaf'); chai_1.assert.equal(cm.colors.ansi[110].css, '#87afd7'); chai_1.assert.equal(cm.colors.ansi[111].css, '#87afff'); chai_1.assert.equal(cm.colors.ansi[112].css, '#87d700'); chai_1.assert.equal(cm.colors.ansi[113].css, '#87d75f'); chai_1.assert.equal(cm.colors.ansi[114].css, '#87d787'); chai_1.assert.equal(cm.colors.ansi[115].css, '#87d7af'); chai_1.assert.equal(cm.colors.ansi[116].css, '#87d7d7'); chai_1.assert.equal(cm.colors.ansi[117].css, '#87d7ff'); chai_1.assert.equal(cm.colors.ansi[118].css, '#87ff00'); chai_1.assert.equal(cm.colors.ansi[119].css, '#87ff5f'); chai_1.assert.equal(cm.colors.ansi[120].css, '#87ff87'); chai_1.assert.equal(cm.colors.ansi[121].css, '#87ffaf'); chai_1.assert.equal(cm.colors.ansi[122].css, '#87ffd7'); chai_1.assert.equal(cm.colors.ansi[123].css, '#87ffff'); chai_1.assert.equal(cm.colors.ansi[124].css, '#af0000'); chai_1.assert.equal(cm.colors.ansi[125].css, '#af005f'); chai_1.assert.equal(cm.colors.ansi[126].css, '#af0087'); chai_1.assert.equal(cm.colors.ansi[127].css, '#af00af'); chai_1.assert.equal(cm.colors.ansi[128].css, '#af00d7'); chai_1.assert.equal(cm.colors.ansi[129].css, '#af00ff'); chai_1.assert.equal(cm.colors.ansi[130].css, '#af5f00'); chai_1.assert.equal(cm.colors.ansi[131].css, '#af5f5f'); chai_1.assert.equal(cm.colors.ansi[132].css, '#af5f87'); chai_1.assert.equal(cm.colors.ansi[133].css, '#af5faf'); chai_1.assert.equal(cm.colors.ansi[134].css, '#af5fd7'); chai_1.assert.equal(cm.colors.ansi[135].css, '#af5fff'); chai_1.assert.equal(cm.colors.ansi[136].css, '#af8700'); chai_1.assert.equal(cm.colors.ansi[137].css, '#af875f'); chai_1.assert.equal(cm.colors.ansi[138].css, '#af8787'); chai_1.assert.equal(cm.colors.ansi[139].css, '#af87af'); chai_1.assert.equal(cm.colors.ansi[140].css, '#af87d7'); chai_1.assert.equal(cm.colors.ansi[141].css, '#af87ff'); chai_1.assert.equal(cm.colors.ansi[142].css, '#afaf00'); chai_1.assert.equal(cm.colors.ansi[143].css, '#afaf5f'); chai_1.assert.equal(cm.colors.ansi[144].css, '#afaf87'); chai_1.assert.equal(cm.colors.ansi[145].css, '#afafaf'); chai_1.assert.equal(cm.colors.ansi[146].css, '#afafd7'); chai_1.assert.equal(cm.colors.ansi[147].css, '#afafff'); chai_1.assert.equal(cm.colors.ansi[148].css, '#afd700'); chai_1.assert.equal(cm.colors.ansi[149].css, '#afd75f'); chai_1.assert.equal(cm.colors.ansi[150].css, '#afd787'); chai_1.assert.equal(cm.colors.ansi[151].css, '#afd7af'); chai_1.assert.equal(cm.colors.ansi[152].css, '#afd7d7'); chai_1.assert.equal(cm.colors.ansi[153].css, '#afd7ff'); chai_1.assert.equal(cm.colors.ansi[154].css, '#afff00'); chai_1.assert.equal(cm.colors.ansi[155].css, '#afff5f'); chai_1.assert.equal(cm.colors.ansi[156].css, '#afff87'); chai_1.assert.equal(cm.colors.ansi[157].css, '#afffaf'); chai_1.assert.equal(cm.colors.ansi[158].css, '#afffd7'); chai_1.assert.equal(cm.colors.ansi[159].css, '#afffff'); chai_1.assert.equal(cm.colors.ansi[160].css, '#d70000'); chai_1.assert.equal(cm.colors.ansi[161].css, '#d7005f'); chai_1.assert.equal(cm.colors.ansi[162].css, '#d70087'); chai_1.assert.equal(cm.colors.ansi[163].css, '#d700af'); chai_1.assert.equal(cm.colors.ansi[164].css, '#d700d7'); chai_1.assert.equal(cm.colors.ansi[165].css, '#d700ff'); chai_1.assert.equal(cm.colors.ansi[166].css, '#d75f00'); chai_1.assert.equal(cm.colors.ansi[167].css, '#d75f5f'); chai_1.assert.equal(cm.colors.ansi[168].css, '#d75f87'); chai_1.assert.equal(cm.colors.ansi[169].css, '#d75faf'); chai_1.assert.equal(cm.colors.ansi[170].css, '#d75fd7'); chai_1.assert.equal(cm.colors.ansi[171].css, '#d75fff'); chai_1.assert.equal(cm.colors.ansi[172].css, '#d78700'); chai_1.assert.equal(cm.colors.ansi[173].css, '#d7875f'); chai_1.assert.equal(cm.colors.ansi[174].css, '#d78787'); chai_1.assert.equal(cm.colors.ansi[175].css, '#d787af'); chai_1.assert.equal(cm.colors.ansi[176].css, '#d787d7'); chai_1.assert.equal(cm.colors.ansi[177].css, '#d787ff'); chai_1.assert.equal(cm.colors.ansi[178].css, '#d7af00'); chai_1.assert.equal(cm.colors.ansi[179].css, '#d7af5f'); chai_1.assert.equal(cm.colors.ansi[180].css, '#d7af87'); chai_1.assert.equal(cm.colors.ansi[181].css, '#d7afaf'); chai_1.assert.equal(cm.colors.ansi[182].css, '#d7afd7'); chai_1.assert.equal(cm.colors.ansi[183].css, '#d7afff'); chai_1.assert.equal(cm.colors.ansi[184].css, '#d7d700'); chai_1.assert.equal(cm.colors.ansi[185].css, '#d7d75f'); chai_1.assert.equal(cm.colors.ansi[186].css, '#d7d787'); chai_1.assert.equal(cm.colors.ansi[187].css, '#d7d7af'); chai_1.assert.equal(cm.colors.ansi[188].css, '#d7d7d7'); chai_1.assert.equal(cm.colors.ansi[189].css, '#d7d7ff'); chai_1.assert.equal(cm.colors.ansi[190].css, '#d7ff00'); chai_1.assert.equal(cm.colors.ansi[191].css, '#d7ff5f'); chai_1.assert.equal(cm.colors.ansi[192].css, '#d7ff87'); chai_1.assert.equal(cm.colors.ansi[193].css, '#d7ffaf'); chai_1.assert.equal(cm.colors.ansi[194].css, '#d7ffd7'); chai_1.assert.equal(cm.colors.ansi[195].css, '#d7ffff'); chai_1.assert.equal(cm.colors.ansi[196].css, '#ff0000'); chai_1.assert.equal(cm.colors.ansi[197].css, '#ff005f'); chai_1.assert.equal(cm.colors.ansi[198].css, '#ff0087'); chai_1.assert.equal(cm.colors.ansi[199].css, '#ff00af'); chai_1.assert.equal(cm.colors.ansi[200].css, '#ff00d7'); chai_1.assert.equal(cm.colors.ansi[201].css, '#ff00ff'); chai_1.assert.equal(cm.colors.ansi[202].css, '#ff5f00'); chai_1.assert.equal(cm.colors.ansi[203].css, '#ff5f5f'); chai_1.assert.equal(cm.colors.ansi[204].css, '#ff5f87'); chai_1.assert.equal(cm.colors.ansi[205].css, '#ff5faf'); chai_1.assert.equal(cm.colors.ansi[206].css, '#ff5fd7'); chai_1.assert.equal(cm.colors.ansi[207].css, '#ff5fff'); chai_1.assert.equal(cm.colors.ansi[208].css, '#ff8700'); chai_1.assert.equal(cm.colors.ansi[209].css, '#ff875f'); chai_1.assert.equal(cm.colors.ansi[210].css, '#ff8787'); chai_1.assert.equal(cm.colors.ansi[211].css, '#ff87af'); chai_1.assert.equal(cm.colors.ansi[212].css, '#ff87d7'); chai_1.assert.equal(cm.colors.ansi[213].css, '#ff87ff'); chai_1.assert.equal(cm.colors.ansi[214].css, '#ffaf00'); chai_1.assert.equal(cm.colors.ansi[215].css, '#ffaf5f'); chai_1.assert.equal(cm.colors.ansi[216].css, '#ffaf87'); chai_1.assert.equal(cm.colors.ansi[217].css, '#ffafaf'); chai_1.assert.equal(cm.colors.ansi[218].css, '#ffafd7'); chai_1.assert.equal(cm.colors.ansi[219].css, '#ffafff'); chai_1.assert.equal(cm.colors.ansi[220].css, '#ffd700'); chai_1.assert.equal(cm.colors.ansi[221].css, '#ffd75f'); chai_1.assert.equal(cm.colors.ansi[222].css, '#ffd787'); chai_1.assert.equal(cm.colors.ansi[223].css, '#ffd7af'); chai_1.assert.equal(cm.colors.ansi[224].css, '#ffd7d7'); chai_1.assert.equal(cm.colors.ansi[225].css, '#ffd7ff'); chai_1.assert.equal(cm.colors.ansi[226].css, '#ffff00'); chai_1.assert.equal(cm.colors.ansi[227].css, '#ffff5f'); chai_1.assert.equal(cm.colors.ansi[228].css, '#ffff87'); chai_1.assert.equal(cm.colors.ansi[229].css, '#ffffaf'); chai_1.assert.equal(cm.colors.ansi[230].css, '#ffffd7'); chai_1.assert.equal(cm.colors.ansi[231].css, '#ffffff'); chai_1.assert.equal(cm.colors.ansi[232].css, '#080808'); chai_1.assert.equal(cm.colors.ansi[233].css, '#121212'); chai_1.assert.equal(cm.colors.ansi[234].css, '#1c1c1c'); chai_1.assert.equal(cm.colors.ansi[235].css, '#262626'); chai_1.assert.equal(cm.colors.ansi[236].css, '#303030'); chai_1.assert.equal(cm.colors.ansi[237].css, '#3a3a3a'); chai_1.assert.equal(cm.colors.ansi[238].css, '#444444'); chai_1.assert.equal(cm.colors.ansi[239].css, '#4e4e4e'); chai_1.assert.equal(cm.colors.ansi[240].css, '#585858'); chai_1.assert.equal(cm.colors.ansi[241].css, '#626262'); chai_1.assert.equal(cm.colors.ansi[242].css, '#6c6c6c'); chai_1.assert.equal(cm.colors.ansi[243].css, '#767676'); chai_1.assert.equal(cm.colors.ansi[244].css, '#808080'); chai_1.assert.equal(cm.colors.ansi[245].css, '#8a8a8a'); chai_1.assert.equal(cm.colors.ansi[246].css, '#949494'); chai_1.assert.equal(cm.colors.ansi[247].css, '#9e9e9e'); chai_1.assert.equal(cm.colors.ansi[248].css, '#a8a8a8'); chai_1.assert.equal(cm.colors.ansi[249].css, '#b2b2b2'); chai_1.assert.equal(cm.colors.ansi[250].css, '#bcbcbc'); chai_1.assert.equal(cm.colors.ansi[251].css, '#c6c6c6'); chai_1.assert.equal(cm.colors.ansi[252].css, '#d0d0d0'); chai_1.assert.equal(cm.colors.ansi[253].css, '#dadada'); chai_1.assert.equal(cm.colors.ansi[254].css, '#e4e4e4'); chai_1.assert.equal(cm.colors.ansi[255].css, '#eeeeee'); }); }); describe('setTheme', function () { it('should not throw when not setting all colors', function () { chai_1.assert.doesNotThrow(function () { cm.setTheme({}); }); }); it('should set a partial set of colors, using the default if not present', function () { chai_1.assert.equal(cm.colors.background.css, '#000000'); chai_1.assert.equal(cm.colors.foreground.css, '#ffffff'); cm.setTheme({ background: '#FF0000', foreground: '#00FF00' }); chai_1.assert.equal(cm.colors.background.css, '#FF0000'); chai_1.assert.equal(cm.colors.foreground.css, '#00FF00'); cm.setTheme({ background: '#0000FF' }); chai_1.assert.equal(cm.colors.background.css, '#0000FF'); chai_1.assert.equal(cm.colors.foreground.css, '#ffffff'); }); }); }); //# sourceMappingURL=ColorManager.test.js.map
SpawnTree/SpawnTree.github.io
js/xterm/lib/renderer/ColorManager.test.js
JavaScript
mit
18,828
/** * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint maxlen: false */ 'use strict'; var createAPIRequest = require('../../lib/apirequest'); /** * Admin Directory API * * @classdesc The Admin SDK Directory API lets you view and manage enterprise resources such as users and groups, administrative notifications, security features, and more. * @namespace admin * @version directory_v1 * @variation directory_v1 * @this Admin * @param {object=} options Options for Admin */ function Admin(options) { var self = this; this._options = options || {}; this.asps = { /** * directory.asps.delete * * @desc Delete an ASP issued by a user. * * @alias directory.asps.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {integer} params.codeId - The unique ID of the ASP to be deleted. * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps/{codeId}', method: 'DELETE' }, params: params, requiredParams: ['userKey', 'codeId'], pathParams: ['codeId', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.asps.get * * @desc Get information about an ASP issued by a user. * * @alias directory.asps.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {integer} params.codeId - The unique ID of the ASP. * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps/{codeId}', method: 'GET' }, params: params, requiredParams: ['userKey', 'codeId'], pathParams: ['codeId', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.asps.list * * @desc List the ASPs issued by a user. * * @alias directory.asps.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } }; this.channels = { /** * admin.channels.stop * * @desc Stop watching resources through this channel * * @alias admin.channels.stop * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ stop: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/admin/directory_v1/channels/stop', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.chromeosdevices = { /** * directory.chromeosdevices.get * * @desc Retrieve Chrome OS Device * * @alias directory.chromeosdevices.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.deviceId - Immutable id of Chrome OS Device * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}', method: 'GET' }, params: params, requiredParams: ['customerId', 'deviceId'], pathParams: ['customerId', 'deviceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.chromeosdevices.list * * @desc Retrieve all Chrome OS Devices of a customer (paginated) * * @alias directory.chromeosdevices.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {integer=} params.maxResults - Maximum number of results to return. Default is 100 * @param {string=} params.orderBy - Column to use for sorting results * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {string=} params.query - Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?hl=en&answer=1698333 * @param {string=} params.sortOrder - Whether to return results in ascending or descending order. Only of use when orderBy is also used * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos', method: 'GET' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.chromeosdevices.patch * * @desc Update Chrome OS Device. This method supports patch semantics. * * @alias directory.chromeosdevices.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.deviceId - Immutable id of Chrome OS Device * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}', method: 'PATCH' }, params: params, requiredParams: ['customerId', 'deviceId'], pathParams: ['customerId', 'deviceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.chromeosdevices.update * * @desc Update Chrome OS Device * * @alias directory.chromeosdevices.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.deviceId - Immutable id of Chrome OS Device * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}', method: 'PUT' }, params: params, requiredParams: ['customerId', 'deviceId'], pathParams: ['customerId', 'deviceId'], context: self }; return createAPIRequest(parameters, callback); } }; this.groups = { /** * directory.groups.delete * * @desc Delete Group * * @alias directory.groups.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}', method: 'DELETE' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.get * * @desc Retrieve Group * * @alias directory.groups.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}', method: 'GET' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.insert * * @desc Create Group * * @alias directory.groups.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.list * * @desc Retrieve all groups in a domain (paginated) * * @alias directory.groups.list * @memberOf! admin(directory_v1) * * @param {object=} params - Parameters for request * @param {string=} params.customer - Immutable id of the Google Apps account. In case of multi-domain, to fetch all groups for a customer, fill this field instead of domain. * @param {string=} params.domain - Name of the domain. Fill this field to get groups from only this domain. To return all groups in a multi-domain fill customer field instead. * @param {integer=} params.maxResults - Maximum number of results to return. Default is 200 * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.userKey - Email or immutable Id of the user if only those groups are to be listed, the given user is a member of. If Id, it should match with id of user object * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups', method: 'GET' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.patch * * @desc Update Group. This method supports patch semantics. * * @alias directory.groups.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}', method: 'PATCH' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.update * * @desc Update Group * * @alias directory.groups.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}', method: 'PUT' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, aliases: { /** * directory.groups.aliases.delete * * @desc Remove a alias for the group * * @alias directory.groups.aliases.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.alias - The alias to be removed * @param {string} params.groupKey - Email or immutable Id of the group * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases/{alias}', method: 'DELETE' }, params: params, requiredParams: ['groupKey', 'alias'], pathParams: ['alias', 'groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.aliases.insert * * @desc Add a alias for the group * * @alias directory.groups.aliases.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases', method: 'POST' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.aliases.list * * @desc List all aliases for a group * * @alias directory.groups.aliases.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases', method: 'GET' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); } } }; this.members = { /** * directory.members.delete * * @desc Remove membership. * * @alias directory.members.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {string} params.memberKey - Email or immutable Id of the member * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}', method: 'DELETE' }, params: params, requiredParams: ['groupKey', 'memberKey'], pathParams: ['groupKey', 'memberKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.get * * @desc Retrieve Group Member * * @alias directory.members.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {string} params.memberKey - Email or immutable Id of the member * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}', method: 'GET' }, params: params, requiredParams: ['groupKey', 'memberKey'], pathParams: ['groupKey', 'memberKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.insert * * @desc Add user to the specified group. * * @alias directory.members.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members', method: 'POST' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.list * * @desc Retrieve all members in a group (paginated) * * @alias directory.members.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {integer=} params.maxResults - Maximum number of results to return. Default is 200 * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.roles - Comma separated role values to filter list results on. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members', method: 'GET' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.patch * * @desc Update membership of a user in the specified group. This method supports patch semantics. * * @alias directory.members.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object * @param {string} params.memberKey - Email or immutable Id of the user. If Id, it should match with id of member object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}', method: 'PATCH' }, params: params, requiredParams: ['groupKey', 'memberKey'], pathParams: ['groupKey', 'memberKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.update * * @desc Update membership of a user in the specified group. * * @alias directory.members.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object * @param {string} params.memberKey - Email or immutable Id of the user. If Id, it should match with id of member object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}', method: 'PUT' }, params: params, requiredParams: ['groupKey', 'memberKey'], pathParams: ['groupKey', 'memberKey'], context: self }; return createAPIRequest(parameters, callback); } }; this.mobiledevices = { /** * directory.mobiledevices.action * * @desc Take action on Mobile Device * * @alias directory.mobiledevices.action * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.resourceId - Immutable id of Mobile Device * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ action: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}/action', method: 'POST' }, params: params, requiredParams: ['customerId', 'resourceId'], pathParams: ['customerId', 'resourceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.mobiledevices.delete * * @desc Delete Mobile Device * * @alias directory.mobiledevices.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.resourceId - Immutable id of Mobile Device * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}', method: 'DELETE' }, params: params, requiredParams: ['customerId', 'resourceId'], pathParams: ['customerId', 'resourceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.mobiledevices.get * * @desc Retrieve Mobile Device * * @alias directory.mobiledevices.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {string} params.resourceId - Immutable id of Mobile Device * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}', method: 'GET' }, params: params, requiredParams: ['customerId', 'resourceId'], pathParams: ['customerId', 'resourceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.mobiledevices.list * * @desc Retrieve all Mobile Devices of a customer (paginated) * * @alias directory.mobiledevices.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {integer=} params.maxResults - Maximum number of results to return. Default is 100 * @param {string=} params.orderBy - Column to use for sorting results * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {string=} params.query - Search string in the format given at http://support.google.com/a/bin/answer.py?hl=en&answer=1408863#search * @param {string=} params.sortOrder - Whether to return results in ascending or descending order. Only of use when orderBy is also used * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile', method: 'GET' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); } }; this.notifications = { /** * directory.notifications.delete * * @desc Deletes a notification * * @alias directory.notifications.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. * @param {string} params.notificationId - The unique ID of the notification. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}', method: 'DELETE' }, params: params, requiredParams: ['customer', 'notificationId'], pathParams: ['customer', 'notificationId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.notifications.get * * @desc Retrieves a notification. * * @alias directory.notifications.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. * @param {string} params.notificationId - The unique ID of the notification. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}', method: 'GET' }, params: params, requiredParams: ['customer', 'notificationId'], pathParams: ['customer', 'notificationId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.notifications.list * * @desc Retrieves a list of notifications. * * @alias directory.notifications.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. * @param {string=} params.language - The ISO 639-1 code of the language notifications are returned in. The default is English (en). * @param {integer=} params.maxResults - Maximum number of notifications to return per page. The default is 100. * @param {string=} params.pageToken - The token to specify the page of results to retrieve. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications', method: 'GET' }, params: params, requiredParams: ['customer'], pathParams: ['customer'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.notifications.patch * * @desc Updates a notification. This method supports patch semantics. * * @alias directory.notifications.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. * @param {string} params.notificationId - The unique ID of the notification. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}', method: 'PATCH' }, params: params, requiredParams: ['customer', 'notificationId'], pathParams: ['customer', 'notificationId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.notifications.update * * @desc Updates a notification. * * @alias directory.notifications.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. * @param {string} params.notificationId - The unique ID of the notification. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}', method: 'PUT' }, params: params, requiredParams: ['customer', 'notificationId'], pathParams: ['customer', 'notificationId'], context: self }; return createAPIRequest(parameters, callback); } }; this.orgunits = { /** * directory.orgunits.delete * * @desc Remove Organization Unit * * @alias directory.orgunits.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.orgUnitPath - Full path of the organization unit * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}', method: 'DELETE' }, params: params, requiredParams: ['customerId', 'orgUnitPath'], pathParams: ['customerId', 'orgUnitPath'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.get * * @desc Retrieve Organization Unit * * @alias directory.orgunits.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.orgUnitPath - Full path of the organization unit * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}', method: 'GET' }, params: params, requiredParams: ['customerId', 'orgUnitPath'], pathParams: ['customerId', 'orgUnitPath'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.insert * * @desc Add Organization Unit * * @alias directory.orgunits.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits', method: 'POST' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.list * * @desc Retrieve all Organization Units * * @alias directory.orgunits.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string=} params.orgUnitPath - the URL-encoded organization unit * @param {string=} params.type - Whether to return all sub-organizations or just immediate children * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits', method: 'GET' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.patch * * @desc Update Organization Unit. This method supports patch semantics. * * @alias directory.orgunits.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.orgUnitPath - Full path of the organization unit * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}', method: 'PATCH' }, params: params, requiredParams: ['customerId', 'orgUnitPath'], pathParams: ['customerId', 'orgUnitPath'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.update * * @desc Update Organization Unit * * @alias directory.orgunits.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.orgUnitPath - Full path of the organization unit * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}', method: 'PUT' }, params: params, requiredParams: ['customerId', 'orgUnitPath'], pathParams: ['customerId', 'orgUnitPath'], context: self }; return createAPIRequest(parameters, callback); } }; this.schemas = { /** * directory.schemas.delete * * @desc Delete schema * * @alias directory.schemas.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.schemaKey - Name or immutable Id of the schema * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}', method: 'DELETE' }, params: params, requiredParams: ['customerId', 'schemaKey'], pathParams: ['customerId', 'schemaKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.get * * @desc Retrieve schema * * @alias directory.schemas.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.schemaKey - Name or immutable Id of the schema * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}', method: 'GET' }, params: params, requiredParams: ['customerId', 'schemaKey'], pathParams: ['customerId', 'schemaKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.insert * * @desc Create schema. * * @alias directory.schemas.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas', method: 'POST' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.list * * @desc Retrieve all schemas for a customer * * @alias directory.schemas.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas', method: 'GET' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.patch * * @desc Update schema. This method supports patch semantics. * * @alias directory.schemas.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.schemaKey - Name or immutable Id of the schema. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}', method: 'PATCH' }, params: params, requiredParams: ['customerId', 'schemaKey'], pathParams: ['customerId', 'schemaKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.update * * @desc Update schema * * @alias directory.schemas.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.schemaKey - Name or immutable Id of the schema. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}', method: 'PUT' }, params: params, requiredParams: ['customerId', 'schemaKey'], pathParams: ['customerId', 'schemaKey'], context: self }; return createAPIRequest(parameters, callback); } }; this.tokens = { /** * directory.tokens.delete * * @desc Delete all access tokens issued by a user for an application. * * @alias directory.tokens.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.clientId - The Client ID of the application the token is issued to. * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens/{clientId}', method: 'DELETE' }, params: params, requiredParams: ['userKey', 'clientId'], pathParams: ['clientId', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.tokens.get * * @desc Get information about an access token issued by a user. * * @alias directory.tokens.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.clientId - The Client ID of the application the token is issued to. * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens/{clientId}', method: 'GET' }, params: params, requiredParams: ['userKey', 'clientId'], pathParams: ['clientId', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.tokens.list * * @desc Returns the set of tokens specified user has issued to 3rd party applications. * * @alias directory.tokens.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } }; this.users = { /** * directory.users.delete * * @desc Delete user * * @alias directory.users.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}', method: 'DELETE' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.get * * @desc retrieve user * * @alias directory.users.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string=} params.customFieldMask - Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. * @param {string=} params.projection - What subset of fields to fetch for this user. * @param {string} params.userKey - Email or immutable Id of the user * @param {string=} params.viewType - Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.insert * * @desc create user. * * @alias directory.users.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.list * * @desc Retrieve either deleted users or all users in a domain (paginated) * * @alias directory.users.list * @memberOf! admin(directory_v1) * * @param {object=} params - Parameters for request * @param {string=} params.customFieldMask - Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. * @param {string=} params.customer - Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain. * @param {string=} params.domain - Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead. * @param {string=} params.event - Event on which subscription is intended (if subscribing) * @param {integer=} params.maxResults - Maximum number of results to return. Default is 100. Max allowed is 500 * @param {string=} params.orderBy - Column to use for sorting results * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.projection - What subset of fields to fetch for this user. * @param {string=} params.query - Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users * @param {string=} params.showDeleted - If set to true retrieves the list of deleted users. Default is false * @param {string=} params.sortOrder - Whether to return results in ascending or descending order. * @param {string=} params.viewType - Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users', method: 'GET' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.makeAdmin * * @desc change admin status of a user * * @alias directory.users.makeAdmin * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user as admin * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ makeAdmin: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/makeAdmin', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.patch * * @desc update user. This method supports patch semantics. * * @alias directory.users.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user. If Id, it should match with id of user object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}', method: 'PATCH' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.undelete * * @desc Undelete a deleted user * * @alias directory.users.undelete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - The immutable id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ undelete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/undelete', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.update * * @desc update user * * @alias directory.users.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user. If Id, it should match with id of user object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}', method: 'PUT' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.watch * * @desc Watch for changes in users list * * @alias directory.users.watch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string=} params.customFieldMask - Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. * @param {string=} params.customer - Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain. * @param {string=} params.domain - Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead. * @param {string=} params.event - Event on which subscription is intended (if subscribing) * @param {integer=} params.maxResults - Maximum number of results to return. Default is 100. Max allowed is 500 * @param {string=} params.orderBy - Column to use for sorting results * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.projection - What subset of fields to fetch for this user. * @param {string=} params.query - Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users * @param {string=} params.showDeleted - If set to true retrieves the list of deleted users. Default is false * @param {string=} params.sortOrder - Whether to return results in ascending or descending order. * @param {string=} params.viewType - Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ watch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/watch', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, aliases: { /** * directory.users.aliases.delete * * @desc Remove a alias for the user * * @alias directory.users.aliases.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.alias - The alias to be removed * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases/{alias}', method: 'DELETE' }, params: params, requiredParams: ['userKey', 'alias'], pathParams: ['alias', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.aliases.insert * * @desc Add a alias for the user * * @alias directory.users.aliases.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.aliases.list * * @desc List all aliases for a user * * @alias directory.users.aliases.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string=} params.event - Event on which subscription is intended (if subscribing) * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.aliases.watch * * @desc Watch for changes in user aliases list * * @alias directory.users.aliases.watch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string=} params.event - Event on which subscription is intended (if subscribing) * @param {string} params.userKey - Email or immutable Id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ watch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases/watch', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } }, photos: { /** * directory.users.photos.delete * * @desc Remove photos for the user * * @alias directory.users.photos.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail', method: 'DELETE' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.photos.get * * @desc Retrieve photo of a user * * @alias directory.users.photos.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.photos.patch * * @desc Add a photo for the user. This method supports patch semantics. * * @alias directory.users.photos.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail', method: 'PATCH' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.photos.update * * @desc Add a photo for the user * * @alias directory.users.photos.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail', method: 'PUT' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } } }; this.verificationCodes = { /** * directory.verificationCodes.generate * * @desc Generate new backup verification codes for the user. * * @alias directory.verificationCodes.generate * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ generate: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes/generate', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.verificationCodes.invalidate * * @desc Invalidate the current backup verification codes for the user. * * @alias directory.verificationCodes.invalidate * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ invalidate: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes/invalidate', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.verificationCodes.list * * @desc Returns the current set of valid backup verification codes for the specified user. * * @alias directory.verificationCodes.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } }; } /** * Exports Admin object * @type Admin */ module.exports = Admin;
MonoHearted/Flowerbless
node_modules/google-api/apis/admin/directory_v1.js
JavaScript
mit
71,632
// sol2 // The MIT License (MIT) // Copyright (c) 2013-2021 Rapptz, ThePhD and contributors // 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. #include <sol/protected_function_result.hpp>
ThePhD/sol2
tests/inclusion/source/protected_function_result.cpp
C++
mit
1,206
<?php class Admin_Page_Scraper_Facebook extends Admin_Page_Abstract { public function prepare(CM_Frontend_Environment $environment, CM_Frontend_ViewResponse $viewResponse) { /** @var Denkmal_Site_Default $site */ $site = $environment->getSite(); $region = $site->hasRegion() ? $site->getRegion() : null; $page = $this->_params->getPage(); $facebookPageList = new Denkmal_Paging_FacebookPage_ListScraper($region); $facebookPageList->setPage($page, 50); $viewResponse->set('region', $region); $viewResponse->set('facebookPageList', $facebookPageList); } public function ajax_removeFacebookPage(CM_Params $params, CM_Frontend_JavascriptContainer_View $handler, CM_Http_Response_View_Ajax $response) { /** @var Denkmal_Params $params */ /** @var Denkmal_Site_Default $site */ $site = $response->getSite(); $region = $site->hasRegion() ? $site->getRegion() : null; $facebookPage = $params->getFacebookPage('facebookPage'); $facebookPageList = new Denkmal_Paging_FacebookPage_ListScraper($region); $facebookPageList->remove($facebookPage); $response->reloadComponent(); } }
njam/denkmal.org
library/Admin/library/Admin/Page/Scraper/Facebook.php
PHP
mit
1,220
package common import ( "testing" "github.com/stretchr/testify/assert" ) // Matasano 2.1 func Test_Pad_PKCS7(t *testing.T) { input := []byte("YELLOW SUBMARINE") received := Pad_PKCS7(input, 4) expected := []byte("YELLOW SUBMARINE\x04\x04\x04\x04") assert.Equal(t, expected, received) }
cngkaygusuz/matasano-challenges
golang/common/pad_test.go
GO
mit
295
using Scripts.Game.Defined.Characters; using Scripts.Game.Defined.Serialized.Statistics; using Scripts.Game.Dungeons; using Scripts.Game.Serialized; using Scripts.Game.Undefined.Characters; using Scripts.Model.Acts; using Scripts.Model.Buffs; using Scripts.Model.Characters; using Scripts.Model.Interfaces; using Scripts.Model.Pages; using Scripts.Model.Processes; using Scripts.Model.Spells; using Scripts.Model.Stats; using Scripts.Model.TextBoxes; using Scripts.Presenter; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Scripts.Game.Pages { /// <summary> /// The hub of the game, from which all other parts can be visited. /// </summary> public class Camp : Model.Pages.PageGroup { /// <summary> /// Missing percentage to restore when resting /// </summary> private const float MISSING_REST_RESTORE_PERCENTAGE = .2f; private Flags flags; private Party party; /// <summary> /// Main /// </summary> /// <param name="party">Party for this particular game.</param> /// <param name="flags">Flags for this particular game.</param> public Camp(Party party, Flags flags) : base(new Page("Campsite")) { this.party = party; this.flags = flags; SetupCamp(); } /// <summary> /// Setup on enter events. /// </summary> private void SetupCamp() { Page root = Get(ROOT_INDEX); root.OnEnter = () => { root.Location = flags.CurrentArea.GetDescription(); root.Icon = Areas.AreaList.AREA_SPRITES[flags.CurrentArea]; // If this isn't first Resting will advance to wrong time if (flags.ShouldAdvanceTimeInCamp) { AdvanceTime(root); flags.ShouldAdvanceTimeInCamp = false; } foreach (Character partyMember in party.Collection) { if (partyMember.Stats.HasUnassignedStatPoints) { root.AddText( string.Format( "<color=cyan>{0}</color> has unallocated stat points. Points can be allocated in the <color=yellow>Party</color> page.", partyMember.Look.DisplayName)); } } Model.Pages.PageGroup dungeonSelectionPage = new StagePages(root, party, flags); root.AddCharacters(Side.LEFT, party.Collection); root.Actions = new IButtonable[] { SubPageWrapper(dungeonSelectionPage, "Visit the stages for this World. When all stages are completed, the next World is unlocked."), SubPageWrapper(new PlacePages(root, flags, party), "Visit a place in this World. Places are unique to a world and can offer you a place to spend your wealth."), SubPageWrapper(new WorldPages(root, flags, party), "Return to a previously unlocked World. Worlds consist of unique Stages and Places."), SubPageWrapper(new LevelUpPages(Root, party), "View party member stats and distribute stat points."), PageUtil.GenerateGroupSpellBooks(root, root, party.Collection), SubPageWrapper(new InventoryPages(root, party), "View the party's shared inventory and use items."), SubPageWrapper(new EquipmentPages(root, party), "View and manage the equipment of your party members."), RestProcess(root), SubPageWrapper(new SavePages(root, party, flags), "Save and exit the game.") }; PostTime(root); }; } private Process SubPageWrapper(PageGroup pg, string description) { return new Process( pg.ButtonText, pg.Sprite, description, () => pg.Invoke(), () => pg.IsInvokable ); } /// <summary> /// Posts the time onto the textholder. /// </summary> /// <param name="current"></param> private void PostTime(Page current) { current.AddText(string.Format("{0} of day {1}.", flags.Time.GetDescription(), flags.DayCount)); if (flags.Time == TimeOfDay.NIGHT) { current.AddText("It is too dark to leave camp."); } } /// <summary> /// Creates the process for resting. /// </summary> /// <param name="current">Current page</param> /// <returns>A rest process.</returns> private Process RestProcess(Page current) { TimeOfDay[] times = Util.EnumAsArray<TimeOfDay>(); int currentIndex = (int)flags.Time; int newIndex = (currentIndex + 1) % times.Length; bool isLastTime = (currentIndex == (times.Length - 1)); return new Process( isLastTime ? "Sleep" : "Rest", isLastTime ? Util.GetSprite("bed") : Util.GetSprite("health-normal"), isLastTime ? string.Format("Sleep to the next day ({0}).\nFully restores most stats and removes most status conditions.", flags.DayCount + 1) : string.Format("Take a short break, advancing the time of day to {0}.\nSomewhat restores most stats.", times[newIndex].GetDescription()), () => { foreach (Character c in party) { c.Stats.RestoreResourcesByMissingPercentage(isLastTime ? 1 : MISSING_REST_RESTORE_PERCENTAGE); if (isLastTime) { c.Buffs.DispelAllBuffs(); } } if (isLastTime) { flags.DayCount %= int.MaxValue; flags.DayCount++; } flags.Time = times[newIndex]; current.AddText(string.Format("The party {0}s.", isLastTime ? "sleep" : "rest")); current.OnEnter(); } ); } /// <summary> /// Makes time go forward in camp. From visiting places. /// </summary> /// <param name="current">The current page.</param> private void AdvanceTime(Page current) { TimeOfDay[] times = Util.EnumAsArray<TimeOfDay>(); int currentIndex = (int)flags.Time; int newIndex = (currentIndex + 1) % times.Length; flags.Time = times[newIndex]; current.AddText("Some time has passed."); } } }
Cinnamon18/runityscape
Assets/Scripts/Game/Camp/Camp.cs
C#
mit
6,751
package org.jinstagram.auth.model; import org.jinstagram.http.Request; import org.jinstagram.http.Verbs; import java.util.HashMap; import java.util.Map; /** * The representation of an OAuth HttpRequest. * * Adds OAuth-related functionality to the {@link Request} */ public class OAuthRequest extends Request { private static final String OAUTH_PREFIX = "oauth_"; private Map<String, String> oauthParameters; /** * Default constructor. * * @param verb Http verb/method * @param url resource URL */ public OAuthRequest(Verbs verb, String url) { super(verb, url); this.oauthParameters = new HashMap<String, String>(); } /** * Adds an OAuth parameter. * * @param key name of the parameter * @param value value of the parameter * * @throws IllegalArgumentException if the parameter is not an OAuth * parameter */ public void addOAuthParameter(String key, String value) { oauthParameters.put(checkKey(key), value); } private static String checkKey(String key) { if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE)) { return key; } else { throw new IllegalArgumentException(String.format( "OAuth parameters must either be '%s' or start with '%s'", OAuthConstants.SCOPE, OAUTH_PREFIX)); } } /** * Returns the {@link Map} containing the key-value pair of parameters. * * @return parameters as map */ public Map<String, String> getOauthParameters() { return oauthParameters; } @Override public String toString() { return String.format("@OAuthRequest(%s, %s)", getVerb(), getUrl()); } }
zauberlabs/jInstagram
src/main/java/org/jinstagram/auth/model/OAuthRequest.java
Java
mit
1,596
package tracker.message.handlers; import elasta.composer.message.handlers.MessageHandler; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; /** * Created by sohan on 2017-07-26. */ public interface ReplayMessageHandler extends MessageHandler<JsonObject> { @Override void handle(Message<JsonObject> event); }
codefacts/Elastic-Components
tracker/src/main/java/tracker/message/handlers/ReplayMessageHandler.java
Java
mit
347
# -*- coding: utf-8 -*- import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore import numpy as np import csv, gzip, os from pyqtgraph import Point class GlassDB: """ Database of dispersion coefficients for Schott glasses + Corning 7980 """ def __init__(self, fileName='schott_glasses.csv'): path = os.path.dirname(__file__) fh = gzip.open(os.path.join(path, 'schott_glasses.csv.gz'), 'rb') r = csv.reader(map(str, fh.readlines())) lines = [x for x in r] self.data = {} header = lines[0] for l in lines[1:]: info = {} for i in range(1, len(l)): info[header[i]] = l[i] self.data[l[0]] = info self.data['Corning7980'] = { ## Thorlabs UV fused silica--not in schott catalog. 'B1': 0.68374049400, 'B2': 0.42032361300, 'B3': 0.58502748000, 'C1': 0.00460352869, 'C2': 0.01339688560, 'C3': 64.49327320000, 'TAUI25/250': 0.95, ## transmission data is fabricated, but close. 'TAUI25/1400': 0.98, } for k in self.data: self.data[k]['ior_cache'] = {} def ior(self, glass, wl): """ Return the index of refraction for *glass* at wavelength *wl*. The *glass* argument must be a key in self.data. """ info = self.data[glass] cache = info['ior_cache'] if wl not in cache: B = list(map(float, [info['B1'], info['B2'], info['B3']])) C = list(map(float, [info['C1'], info['C2'], info['C3']])) w2 = (wl/1000.)**2 n = np.sqrt(1.0 + (B[0]*w2 / (w2-C[0])) + (B[1]*w2 / (w2-C[1])) + (B[2]*w2 / (w2-C[2]))) cache[wl] = n return cache[wl] def transmissionCurve(self, glass): data = self.data[glass] keys = [int(x[7:]) for x in data.keys() if 'TAUI25' in x] keys.sort() curve = np.empty((2,len(keys))) for i in range(len(keys)): curve[0][i] = keys[i] key = 'TAUI25/%d' % keys[i] val = data[key] if val == '': val = 0 else: val = float(val) curve[1][i] = val return curve GLASSDB = GlassDB() def wlPen(wl): """Return a pen representing the given wavelength""" l1 = 400 l2 = 700 hue = np.clip(((l2-l1) - (wl-l1)) * 0.8 / (l2-l1), 0, 0.8) val = 1.0 if wl > 700: val = 1.0 * (((700-wl)/700.) + 1) elif wl < 400: val = wl * 1.0/400. #print hue, val color = pg.hsvColor(hue, 1.0, val) pen = pg.mkPen(color) return pen class ParamObj(object): # Just a helper for tracking parameters and responding to changes def __init__(self): self.__params = {} def __setitem__(self, item, val): self.setParam(item, val) def setParam(self, param, val): self.setParams(**{param:val}) def setParams(self, **params): """Set parameters for this optic. This is a good function to override for subclasses.""" self.__params.update(params) self.paramStateChanged() def paramStateChanged(self): pass def __getitem__(self, item): # bug in pyside 1.2.2 causes getitem to be called inside QGraphicsObject.parentItem: return self.getParam(item) # PySide bug: https://bugreports.qt.io/browse/PYSIDE-441 def getParam(self, param): return self.__params[param] class Optic(pg.GraphicsObject, ParamObj): sigStateChanged = QtCore.Signal() def __init__(self, gitem, **params): ParamObj.__init__(self) pg.GraphicsObject.__init__(self) #, [0,0], [1,1]) self.gitem = gitem self.surfaces = gitem.surfaces gitem.setParentItem(self) self.roi = pg.ROI([0,0], [1,1]) self.roi.addRotateHandle([1, 1], [0.5, 0.5]) self.roi.setParentItem(self) defaults = { 'pos': Point(0,0), 'angle': 0, } defaults.update(params) self._ior_cache = {} self.roi.sigRegionChanged.connect(self.roiChanged) self.setParams(**defaults) def updateTransform(self): self.resetTransform() self.setPos(0, 0) self.translate(Point(self['pos'])) self.rotate(self['angle']) def setParam(self, param, val): ParamObj.setParam(self, param, val) def paramStateChanged(self): """Some parameters of the optic have changed.""" # Move graphics item self.gitem.setPos(Point(self['pos'])) self.gitem.resetTransform() self.gitem.rotate(self['angle']) # Move ROI to match try: self.roi.sigRegionChanged.disconnect(self.roiChanged) br = self.gitem.boundingRect() o = self.gitem.mapToParent(br.topLeft()) self.roi.setAngle(self['angle']) self.roi.setPos(o) self.roi.setSize([br.width(), br.height()]) finally: self.roi.sigRegionChanged.connect(self.roiChanged) self.sigStateChanged.emit() def roiChanged(self, *args): pos = self.roi.pos() # rotate gitem temporarily so we can decide where it will need to move self.gitem.resetTransform() self.gitem.rotate(self.roi.angle()) br = self.gitem.boundingRect() o1 = self.gitem.mapToParent(br.topLeft()) self.setParams(angle=self.roi.angle(), pos=pos + (self.gitem.pos() - o1)) def boundingRect(self): return QtCore.QRectF() def paint(self, p, *args): pass def ior(self, wavelength): return GLASSDB.ior(self['glass'], wavelength) class Lens(Optic): def __init__(self, **params): defaults = { 'dia': 25.4, ## diameter of lens 'r1': 50., ## positive means convex, use 0 for planar 'r2': 0, ## negative means convex 'd': 4.0, 'glass': 'N-BK7', 'reflect': False, } defaults.update(params) d = defaults.pop('d') defaults['x1'] = -d/2. defaults['x2'] = d/2. gitem = CircularSolid(brush=(100, 100, 130, 100), **defaults) Optic.__init__(self, gitem, **defaults) def propagateRay(self, ray): """Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays""" """ NOTE:: We can probably use this to compute refractions faster: (from GLSL 120 docs) For the incident vector I and surface normal N, and the ratio of indices of refraction eta, return the refraction vector. The result is computed by k = 1.0 - eta * eta * (1.0 - dot(N, I) * dot(N, I)) if (k < 0.0) return genType(0.0) else return eta * I - (eta * dot(N, I) + sqrt(k)) * N The input parameters for the incident vector I and the surface normal N must already be normalized to get the desired results. eta == ratio of IORs For reflection: For the incident vector I and surface orientation N, returns the reflection direction: I – 2 ∗ dot(N, I) ∗ N N must already be normalized in order to achieve the desired result. """ iors = [self.ior(ray['wl']), 1.0] for i in [0,1]: surface = self.surfaces[i] ior = iors[i] p1, ai = surface.intersectRay(ray) #print "surface intersection:", p1, ai*180/3.14159 #trans = self.sceneTransform().inverted()[0] * surface.sceneTransform() #p1 = trans.map(p1) if p1 is None: ray.setEnd(None) break p1 = surface.mapToItem(ray, p1) #print "adjusted position:", p1 #ior = self.ior(ray['wl']) rd = ray['dir'] a1 = np.arctan2(rd[1], rd[0]) ar = a1 - ai + np.arcsin((np.sin(ai) * ray['ior'] / ior)) #print [x for x in [a1, ai, (np.sin(ai) * ray['ior'] / ior), ar]] #print ai, np.sin(ai), ray['ior'], ior ray.setEnd(p1) dp = Point(np.cos(ar), np.sin(ar)) #p2 = p1+dp #p1p = self.mapToScene(p1) #p2p = self.mapToScene(p2) #dpp = Point(p2p-p1p) ray = Ray(parent=ray, ior=ior, dir=dp) return [ray] class Mirror(Optic): def __init__(self, **params): defaults = { 'r1': 0, 'r2': 0, 'd': 0.01, } defaults.update(params) d = defaults.pop('d') defaults['x1'] = -d/2. defaults['x2'] = d/2. gitem = CircularSolid(brush=(100,100,100,255), **defaults) Optic.__init__(self, gitem, **defaults) def propagateRay(self, ray): """Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays""" surface = self.surfaces[0] p1, ai = surface.intersectRay(ray) if p1 is not None: p1 = surface.mapToItem(ray, p1) rd = ray['dir'] a1 = np.arctan2(rd[1], rd[0]) ar = a1 + np.pi - 2*ai ray.setEnd(p1) dp = Point(np.cos(ar), np.sin(ar)) ray = Ray(parent=ray, dir=dp) else: ray.setEnd(None) return [ray] class CircularSolid(pg.GraphicsObject, ParamObj): """GraphicsObject with two circular or flat surfaces.""" def __init__(self, pen=None, brush=None, **opts): """ Arguments for each surface are: x1,x2 - position of center of _physical surface_ r1,r2 - radius of curvature d1,d2 - diameter of optic """ defaults = dict(x1=-2, r1=100, d1=25.4, x2=2, r2=100, d2=25.4) defaults.update(opts) ParamObj.__init__(self) self.surfaces = [CircleSurface(defaults['r1'], defaults['d1']), CircleSurface(-defaults['r2'], defaults['d2'])] pg.GraphicsObject.__init__(self) for s in self.surfaces: s.setParentItem(self) if pen is None: self.pen = pg.mkPen((220,220,255,200), width=1, cosmetic=True) else: self.pen = pg.mkPen(pen) if brush is None: self.brush = pg.mkBrush((230, 230, 255, 30)) else: self.brush = pg.mkBrush(brush) self.setParams(**defaults) def paramStateChanged(self): self.updateSurfaces() def updateSurfaces(self): self.surfaces[0].setParams(self['r1'], self['d1']) self.surfaces[1].setParams(-self['r2'], self['d2']) self.surfaces[0].setPos(self['x1'], 0) self.surfaces[1].setPos(self['x2'], 0) self.path = QtGui.QPainterPath() self.path.connectPath(self.surfaces[0].path.translated(self.surfaces[0].pos())) self.path.connectPath(self.surfaces[1].path.translated(self.surfaces[1].pos()).toReversed()) self.path.closeSubpath() def boundingRect(self): return self.path.boundingRect() def shape(self): return self.path def paint(self, p, *args): p.setRenderHints(p.renderHints() | p.Antialiasing) p.setPen(self.pen) p.fillPath(self.path, self.brush) p.drawPath(self.path) class CircleSurface(pg.GraphicsObject): def __init__(self, radius=None, diameter=None): """center of physical surface is at 0,0 radius is the radius of the surface. If radius is None, the surface is flat. diameter is of the optic's edge.""" pg.GraphicsObject.__init__(self) self.r = radius self.d = diameter self.mkPath() def setParams(self, r, d): self.r = r self.d = d self.mkPath() def mkPath(self): self.prepareGeometryChange() r = self.r d = self.d h2 = d/2. self.path = QtGui.QPainterPath() if r == 0: ## flat surface self.path.moveTo(0, h2) self.path.lineTo(0, -h2) else: ## half-height of surface can't be larger than radius h2 = min(h2, abs(r)) #dx = abs(r) - (abs(r)**2 - abs(h2)**2)**0.5 #p.moveTo(-d*w/2.+ d*dx, d*h2) arc = QtCore.QRectF(0, -r, r*2, r*2) #self.surfaces.append((arc.center(), r, h2)) a1 = np.arcsin(h2/r) * 180. / np.pi a2 = -2*a1 a1 += 180. self.path.arcMoveTo(arc, a1) self.path.arcTo(arc, a1, a2) #if d == -1: #p1 = QtGui.QPainterPath() #p1.addRect(arc) #self.paths.append(p1) self.h2 = h2 def boundingRect(self): return self.path.boundingRect() def paint(self, p, *args): return ## usually we let the optic draw. #p.setPen(pg.mkPen('r')) #p.drawPath(self.path) def intersectRay(self, ray): ## return the point of intersection and the angle of incidence #print "intersect ray" h = self.h2 r = self.r p, dir = ray.currentState(relativeTo=self) # position and angle of ray in local coords. #print " ray: ", p, dir p = p - Point(r, 0) ## move position so center of circle is at 0,0 #print " adj: ", p, r if r == 0: #print " flat" if dir[0] == 0: y = 0 else: y = p[1] - p[0] * dir[1]/dir[0] if abs(y) > h: return None, None else: return (Point(0, y), np.arctan2(dir[1], dir[0])) else: #print " curve" ## find intersection of circle and line (quadratic formula) dx = dir[0] dy = dir[1] dr = (dx**2 + dy**2) ** 0.5 D = p[0] * (p[1]+dy) - (p[0]+dx) * p[1] idr2 = 1.0 / dr**2 disc = r**2 * dr**2 - D**2 if disc < 0: return None, None disc2 = disc**0.5 if dy < 0: sgn = -1 else: sgn = 1 br = self.path.boundingRect() x1 = (D*dy + sgn*dx*disc2) * idr2 y1 = (-D*dx + abs(dy)*disc2) * idr2 if br.contains(x1+r, y1): pt = Point(x1, y1) else: x2 = (D*dy - sgn*dx*disc2) * idr2 y2 = (-D*dx - abs(dy)*disc2) * idr2 pt = Point(x2, y2) if not br.contains(x2+r, y2): return None, None raise Exception("No intersection!") norm = np.arctan2(pt[1], pt[0]) if r < 0: norm += np.pi #print " norm:", norm*180/3.1415 dp = p - pt #print " dp:", dp ang = np.arctan2(dp[1], dp[0]) #print " ang:", ang*180/3.1415 #print " ai:", (ang-norm)*180/3.1415 #print " intersection:", pt return pt + Point(r, 0), ang-norm class Ray(pg.GraphicsObject, ParamObj): """Represents a single straight segment of a ray""" sigStateChanged = QtCore.Signal() def __init__(self, **params): ParamObj.__init__(self) defaults = { 'ior': 1.0, 'wl': 500, 'end': None, 'dir': Point(1,0), } self.params = {} pg.GraphicsObject.__init__(self) self.children = [] parent = params.get('parent', None) if parent is not None: defaults['start'] = parent['end'] defaults['wl'] = parent['wl'] self['ior'] = parent['ior'] self['dir'] = parent['dir'] parent.addChild(self) defaults.update(params) defaults['dir'] = Point(defaults['dir']) self.setParams(**defaults) self.mkPath() def clearChildren(self): for c in self.children: c.clearChildren() c.setParentItem(None) self.scene().removeItem(c) self.children = [] def paramStateChanged(self): pass def addChild(self, ch): self.children.append(ch) ch.setParentItem(self) def currentState(self, relativeTo=None): pos = self['start'] dir = self['dir'] if relativeTo is None: return pos, dir else: trans = self.itemTransform(relativeTo)[0] p1 = trans.map(pos) p2 = trans.map(pos + dir) return Point(p1), Point(p2-p1) def setEnd(self, end): self['end'] = end self.mkPath() def boundingRect(self): return self.path.boundingRect() def paint(self, p, *args): #p.setPen(pg.mkPen((255,0,0, 150))) p.setRenderHints(p.renderHints() | p.Antialiasing) p.setCompositionMode(p.CompositionMode_Plus) p.setPen(wlPen(self['wl'])) p.drawPath(self.path) def mkPath(self): self.prepareGeometryChange() self.path = QtGui.QPainterPath() self.path.moveTo(self['start']) if self['end'] is not None: self.path.lineTo(self['end']) else: self.path.lineTo(self['start']+500*self['dir']) def trace(rays, optics): if len(optics) < 1 or len(rays) < 1: return for r in rays: r.clearChildren() o = optics[0] r2 = o.propagateRay(r) trace(r2, optics[1:]) class Tracer(QtCore.QObject): """ Simple ray tracer. Initialize with a list of rays and optics; calling trace() will cause rays to be extended by propagating them through each optic in sequence. """ def __init__(self, rays, optics): QtCore.QObject.__init__(self) self.optics = optics self.rays = rays for o in self.optics: o.sigStateChanged.connect(self.trace) self.trace() def trace(self): trace(self.rays, self.optics)
pmaunz/pyqtgraph
examples/optics/pyoptic.py
Python
mit
18,598
import logging from urllib.parse import urljoin import lxml.etree # noqa: S410 import requests from django.conf import settings as django_settings from django.utils import timezone logger = logging.getLogger(__name__) class ClientError(Exception): pass class ResponseParseError(ClientError): pass class ResponseStatusError(ClientError): pass class RequestError(ClientError): def __init__(self, message, response=None): super(RequestError, self).__init__(message) self.response = response class UnknownStatusError(ResponseParseError): pass class Response: ns_namespace = 'http://uri.etsi.org/TS102204/v1.1.2#' def __init__(self, content): etree = lxml.etree.fromstring(content) # noqa: S320 self.init_response_attributes(etree) def init_response_attributes(self, etree): """ Define response attributes based on valimo request content """ raise NotImplementedError class Request: url = NotImplemented template = NotImplemented response_class = NotImplemented settings = getattr(django_settings, 'WALDUR_AUTH_VALIMO', {}) @classmethod def execute(cls, **kwargs): url = cls._get_url() headers = { 'content-type': 'text/xml', 'SOAPAction': url, } data = cls.template.strip().format( AP_ID=cls.settings['AP_ID'], AP_PWD=cls.settings['AP_PWD'], Instant=cls._format_datetime(timezone.now()), DNSName=cls.settings['DNSName'], **kwargs ) cert = (cls.settings['cert_path'], cls.settings['key_path']) # TODO: add verification logger.debug( 'Executing POST request to %s with data:\n %s \nheaders: %s', url, data, headers, ) response = requests.post( url, data=data, headers=headers, cert=cert, verify=cls.settings['verify_ssl'], ) if response.ok: return cls.response_class(response.content) else: message = ( 'Failed to execute POST request against %s endpoint. Response [%s]: %s' % (url, response.status_code, response.content) ) raise RequestError(message, response) @classmethod def _format_datetime(cls, d): return d.strftime('%Y-%m-%dT%H:%M:%S.000Z') @classmethod def _format_transaction_id(cls, transaction_id): return ('_' + transaction_id)[:32] # such formation is required by server. @classmethod def _get_url(cls): return urljoin(cls.settings['URL'], cls.url) class SignatureResponse(Response): def init_response_attributes(self, etree): try: self.backend_transaction_id = etree.xpath('//MSS_SignatureResp')[0].attrib[ 'MSSP_TransID' ] self.status = etree.xpath( '//ns6:StatusCode', namespaces={'ns6': self.ns_namespace} )[0].attrib['Value'] except (IndexError, KeyError, lxml.etree.XMLSchemaError) as e: raise ResponseParseError( 'Cannot parse signature response: %s. Response content: %s' % (e, lxml.etree.tostring(etree)) ) class SignatureRequest(Request): url = '/MSSP/services/MSS_Signature' template = """ <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <MSS_Signature xmlns=""> <MSS_SignatureReq MajorVersion="1" MessagingMode="{MessagingMode}" MinorVersion="1" TimeOut="300"> <ns1:AP_Info AP_ID="{AP_ID}" AP_PWD="{AP_PWD}" AP_TransID="{AP_TransID}" Instant="{Instant}" xmlns:ns1="http://uri.etsi.org/TS102204/v1.1.2#"/> <ns2:MSSP_Info xmlns:ns2="http://uri.etsi.org/TS102204/v1.1.2#"> <ns2:MSSP_ID> <ns2:DNSName>{DNSName}</ns2:DNSName> </ns2:MSSP_ID> </ns2:MSSP_Info> <ns3:MobileUser xmlns:ns3="http://uri.etsi.org/TS102204/v1.1.2#"> <ns3:MSISDN>{MSISDN}</ns3:MSISDN> </ns3:MobileUser> <ns4:DataToBeSigned Encoding="UTF-8" MimeType="text/plain" xmlns:ns4="http://uri.etsi.org/TS102204/v1.1.2#"> {DataToBeSigned} </ns4:DataToBeSigned> <ns5:SignatureProfile xmlns:ns5="http://uri.etsi.org/TS102204/v1.1.2#"> <ns5:mssURI>{SignatureProfile}</ns5:mssURI> </ns5:SignatureProfile> <ns6:MSS_Format xmlns:ns6="http://uri.etsi.org/TS102204/v1.1.2#"> <ns6:mssURI>http://uri.etsi.org/TS102204/v1.1.2#PKCS7</ns6:mssURI> </ns6:MSS_Format> </MSS_SignatureReq> </MSS_Signature> </soapenv:Body> </soapenv:Envelope> """ response_class = SignatureResponse @classmethod def execute(cls, transaction_id, phone, message): kwargs = { 'MessagingMode': 'asynchClientServer', 'AP_TransID': cls._format_transaction_id(transaction_id), 'MSISDN': phone, 'DataToBeSigned': '%s %s' % (cls.settings['message_prefix'], message), 'SignatureProfile': cls.settings['SignatureProfile'], } return super(SignatureRequest, cls).execute(**kwargs) class Statuses: OK = 'OK' PROCESSING = 'Processing' ERRED = 'Erred' @classmethod def map(cls, status_code): if status_code == '502': return cls.OK elif status_code == '504': return cls.PROCESSING else: raise UnknownStatusError( 'Received unsupported status in response: %s' % status_code ) class StatusResponse(Response): def init_response_attributes(self, etree): try: status_code = etree.xpath( '//ns5:StatusCode', namespaces={'ns5': self.ns_namespace} )[0].attrib['Value'] except (IndexError, KeyError, lxml.etree.XMLSchemaError) as e: raise ResponseParseError( 'Cannot parse status response: %s. Response content: %s' % (e, lxml.etree.tostring(etree)) ) self.status = Statuses.map(status_code) try: civil_number_tag = etree.xpath( '//ns4:UserIdentifier', namespaces={'ns4': self.ns_namespace} )[0] except IndexError: # civil number tag does not exist - this is possible if request is still processing return else: try: self.civil_number = civil_number_tag.text.split('=')[1] except IndexError: raise ResponseParseError( 'Cannot get civil_number from tag text: %s' % civil_number_tag.text ) class ErredStatusResponse(Response): soapenv_namespace = 'http://www.w3.org/2003/05/soap-envelope' def init_response_attributes(self, etree): self.status = Statuses.ERRED try: self.details = etree.xpath( '//soapenv:Text', namespaces={'soapenv': self.soapenv_namespace} )[0].text except (IndexError, lxml.etree.XMLSchemaError) as e: raise ResponseParseError( 'Cannot parse error status response: %s. Response content: %s' % (e, lxml.etree.tostring(etree)) ) class StatusRequest(Request): url = '/MSSP/services/MSS_StatusPort' template = """ <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <MSS_StatusQuery xmlns=""> <MSS_StatusReq MajorVersion="1" MinorVersion="1"> <ns1:AP_Info AP_ID="{AP_ID}" AP_PWD="{AP_PWD}" AP_TransID="{AP_TransID}" Instant="{Instant}" xmlns:ns1="http://uri.etsi.org/TS102204/v1.1.2#"/> <ns2:MSSP_Info xmlns:ns2="http://uri.etsi.org/TS102204/v1.1.2#"> <ns2:MSSP_ID> <ns2:DNSName>{DNSName}</ns2:DNSName> </ns2:MSSP_ID> </ns2:MSSP_Info> <ns3:MSSP_TransID xmlns:ns3="http://uri.etsi.org/TS102204/v1.1.2#">{MSSP_TransID}</ns3:MSSP_TransID> </MSS_StatusReq> </MSS_StatusQuery> </soapenv:Body> </soapenv:Envelope> """ response_class = StatusResponse @classmethod def execute(cls, transaction_id, backend_transaction_id): kwargs = { 'AP_TransID': cls._format_transaction_id(transaction_id), 'MSSP_TransID': backend_transaction_id, } try: return super(StatusRequest, cls).execute(**kwargs) except RequestError as e: # If request was timed out or user canceled login - Valimo would return response with status 500 return ErredStatusResponse(e.response.content)
opennode/nodeconductor-assembly-waldur
src/waldur_auth_valimo/client.py
Python
mit
9,636
<?php namespace Yandex\Locator\Exception; /** * Class ServerError * @package Yandex\Locator\Exception * @author Dmitry Kuznetsov <kuznetsov2d@gmail.com> * @license The MIT License (MIT) */ class ServerError extends \Yandex\Locator\Exception { }
dmkuznetsov/php-yandex-locator
source/Yandex/Locator/Exception/ServerError.php
PHP
mit
250
/* * Copyright 2017 Hewlett Packard Enterprise Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'underscore', 'jquery', 'find/idol/app/page/dashboard/widgets/updating-widget', 'find/idol/app/page/dashboard/update-tracker-model' ], function(_, $, UpdatingWidget, UpdateTrackerModel) { 'use strict'; const spies = jasmine.createSpyObj('spies', ['onComplete', 'onIncrement', 'onCancelled', 'doUpdate']); const TestUpdatingWidget = UpdatingWidget.extend(spies); describe('Updating Widget', function() { beforeEach(function() { jasmine.addMatchers({ toShowLoadingSpinner: function() { return { compare: function(actual) { const pass = !actual.$loadingSpinner.hasClass('hide'); return { pass: pass, message: 'Expected the view ' + (pass ? 'not ' : '') + 'to show a loading spinner' }; } } } }); this.widget = new TestUpdatingWidget({ name: 'Test Widget' }); this.widget.render(); this.updateDeferred = $.Deferred(); this.updateTrackerModel = new UpdateTrackerModel(); }); afterEach(function() { _.each(spies, function(spy) { spy.calls.reset(); }) }); describe('when the update is synchronous', function() { beforeEach(function() { this.widget.doUpdate.and.callFake(function(done) { done(); }); this.widget.update(this.updateTrackerModel); }); it('it should increment the model when the done callback is called', function() { expect(this.updateTrackerModel.get('count')).toBe(1); }); it('should call onIncrement when the count increases', function() { // count increased when the widget updated expect(this.widget.onIncrement.calls.count()).toBe(1); }); it('should call onComplete when the model is set to complete', function() { this.updateTrackerModel.set('complete', true); expect(this.widget.onComplete.calls.count()).toBe(1); }); it('should call onCancelled when the model is set to cancelled', function() { this.updateTrackerModel.set('cancelled', true); expect(this.widget.onCancelled.calls.count()).toBe(1); }); }); describe('when the update is asynchronous', function() { beforeEach(function() { // when a test resolves the deferred, call the done callback this.widget.doUpdate.and.callFake(function(done) { this.updateDeferred.done(done); }.bind(this)); }); describe('and the update is called', function() { beforeEach(function() { this.widget.update(this.updateTrackerModel); }); it('should show the loading spinner until the update completes', function() { expect(this.widget).toShowLoadingSpinner(); this.updateDeferred.resolve(); expect(this.widget).not.toShowLoadingSpinner(); }); it('should not increment the model until the update is complete', function() { expect(this.updateTrackerModel.get('count')).toBe(0); this.updateDeferred.resolve(); expect(this.updateTrackerModel.get('count')).toBe(1); }); it('should call onIncrement when the count increases', function() { this.updateTrackerModel.increment(); expect(this.widget.onIncrement.calls.count()).toBe(1); }); it('should call onComplete when the model is set to complete', function() { this.updateTrackerModel.set('complete', true); expect(this.widget.onComplete.calls.count()).toBe(1); }); it('should call onCancelled when the model is set to cancelled', function() { this.updateTrackerModel.set('cancelled', true); expect(this.widget.onCancelled.calls.count()).toBe(1); }); }); }) }); });
hpe-idol/find
webapp/idol/src/test/js/spec/app/page/dashboard/widgets/updating-widget.js
JavaScript
mit
4,835
import 'rxjs/add/operator/map'; import {Injectable} from '@angular/core'; import {Http, RequestMethod} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {Cube} from '../models/cube'; import 'rxjs/add/operator/mergeMap'; import {Algorithm} from '../models/analysis/algorithm'; import {Input, InputTypes} from '../models/analysis/input'; import {Output, OutputTypes} from '../models/analysis/output'; import {environment} from '../../environments/environment'; import {ExecutionConfiguration} from '../models/analysis/executionConfiguration'; import {Configuration} from 'jasmine-spec-reporter/built/configuration'; @Injectable() export class AlgorithmsService { private API_DAM_PATH: string = environment.DAMUrl ; constructor(private http: Http) { } getActualCompatibleAlgorithms(): Observable<Algorithm[]> { // console.log(JSON.stringify({time_series: AlgorithmsService.dummyTimeSeries().serialize(), descriptive_statistics: AlgorithmsService.dummyDescriptiveStatistics().serialize(), clustering: AlgorithmsService.dummyClustering().serialize()})); return this.http.get(`${environment.DAMUrl}/services/meta/all`) .map(res => { let algorithms = []; let response = res.json(); for (let key of Object.keys(response)){ let algorithm = new Algorithm().deserialize(response[key]); algorithms.push(algorithm); } return algorithms; }); } getActualCompatibleAlgorithm( algorithmName): Observable<Algorithm> { return this.http.get(`${environment.DAMUrl}/services/meta/${algorithmName}`) .map(res => { let response = res.json(); return new Algorithm().deserialize(response); }); } getTimeSeriesAlgorithm(): Observable<Algorithm> { let that = this; return this.getActualCompatibleAlgorithm('time_series'); } getDescriptiveStatisticsAlgorithm(): Observable<Algorithm> { return this.getActualCompatibleAlgorithm('descriptive_statistics'); } getClusteringAlgorithm(): Observable<Algorithm> { return this.getActualCompatibleAlgorithm('clustering'); } getOutlierDetectionAlgorithm(): Observable<Algorithm> { let that = this; return this.getActualCompatibleAlgorithm('outlier_detection'); /*return Observable.create(function (observer: any) { observer.next(AlgorithmsService.dummyOutlierDetection()); });*/ } getRuleMiningAlgorithm(): Observable<Algorithm> { let that = this; return this.getActualCompatibleAlgorithm('rule_mining'); /*return Observable.create(function (observer: any) { observer.next(AlgorithmsService.dummyOutlierDetection()); });*/ } getAlgorithm(name, cube: Cube): Observable<Algorithm> { switch (name) { case 'time_series': return this.getTimeSeriesAlgorithm(); case 'descriptive_statistics': return this.getDescriptiveStatisticsAlgorithm(); case 'clustering': return this.getClusteringAlgorithm(); case 'outlier_detection': return this.getOutlierDetectionAlgorithm(); case 'rule_mining': return this.getRuleMiningAlgorithm(); default: return this.http.get(`${this.API_DAM_PATH}/${name}`) .map(res => { let response = res.json(); return new Algorithm().deserialize(response); }); } } }
okgreece/indigo
src/app/services/algorithms.ts
TypeScript
mit
3,392
<?php namespace Nathanmac\Utilities\Parser\Formats; use Nathanmac\Utilities\Parser\Exceptions\ParserException; /** * XML Formatter * * @package Nathanmac\Utilities\Parser\Formats * @author Nathan Macnamara <nathan.macnamara@outlook.com> * @license https://github.com/nathanmac/Parser/blob/master/LICENSE.md MIT */ class XML implements FormatInterface { /** * Parse Payload Data * * @param string $payload * * @throws ParserException * @return array * */ public function parse($payload) { if ($payload) { try { $xml = simplexml_load_string($payload, 'SimpleXMLElement', LIBXML_NOCDATA); $ns = ['' => null] + $xml->getDocNamespaces(true); return $this->recursive_parse($xml, $ns); } catch (\Exception $ex) { throw new ParserException('Failed To Parse XML'); } } return []; } protected function recursive_parse($xml, $ns) { $xml_string = (string)$xml; if ($xml->count() == 0 and $xml_string != '') { if (count($xml->attributes()) == 0) { if (trim($xml_string) == '') { $result = null; } else { $result = $xml_string; } } else { $result = array('#text' => $xml_string); } } else { $result = null; } foreach ($ns as $nsName => $nsUri) { foreach ($xml->attributes($nsUri) as $attName => $attValue) { if (!empty($nsName)) { $attName = "{$nsName}:{$attName}"; } $result["@{$attName}"] = (string)$attValue; } foreach ($xml->children($nsUri) as $childName => $child) { if (!empty($nsName)) { $childName = "{$nsName}:{$childName}"; } $child = $this->recursive_parse($child, $ns); if (is_array($result) and array_key_exists($childName, $result)) { if (is_array($result[$childName]) and is_numeric(key($result[$childName]))) { $result[$childName][] = $child; } else { $temp = $result[$childName]; $result[$childName] = [$temp, $child]; } } else { $result[$childName] = $child; } } } return $result; } }
tgoettel9401/Homepage-Schachclub-Niedermohr
vendor/nathanmac/parser/src/Formats/XML.php
PHP
mit
2,603
import PropTypes from 'prop-types' import React from 'react' import { List } from 'immutable' import Modal from './warningmodal.js' import Path from 'path' const FilesList = ({ folders, folderPathToRemove, actions }) => { const addStorageLocation = () => actions.addFolderAskPathSize() const removeStorageLocation = folder => () => { actions.removeFolder(folder) actions.updateFolderToRemove() } const onResizeStorageLocationClick = folder => () => actions.resizeFolder(folder) const onRemoveStorageLocationClick = folder => () => actions.updateFolderToRemove(folder.get('path')) const hideRemoveStorageModal = () => actions.updateFolderToRemove() // sort folders by their name const sortedFolders = folders.sortBy(folder => folder.get('path')) const FileList = sortedFolders.map((folder, key) => ( <div className='property pure-g' key={key}> <div className='pure-u-3-4'> <div className='name'>{folder.get('path')}</div> </div> <div className='pure-u-1-12'> <div>{Math.floor(folder.get('free')).toString()} GB</div> </div> <div className='pure-u-1-12'> <div>{Math.floor(folder.get('size')).toString()} GB</div> </div> <div className='pure-u-1-24' onClick={onResizeStorageLocationClick(folder)} > <div> <i className='fa fa-edit button' /> </div> </div> <div className='pure-u-1-24' onClick={onRemoveStorageLocationClick(folder)} > <div> <i className='fa fa-remove button' /> </div> </div> {folderPathToRemove && folderPathToRemove === folder.get('path') ? ( <Modal title={`Remove "${Path.basename(folder.get('path'))}"?`} message='No longer use this folder for storage? You may lose collateral if you do not have enough space to fill all contracts.' actions={{ acceptModal: removeStorageLocation(folder), declineModal: hideRemoveStorageModal }} /> ) : null} </div> )) return ( <div className='files section'> <div className='property row'> <div className='title' /> <div className='controls full'> <div className='button left' id='edit' onClick={addStorageLocation}> <i className='fa fa-folder-open' /> Add Storage Folder </div> <div className='pure-u-1-12' style={{ textAlign: 'left' }}> Free </div> <div className='pure-u-1-12' style={{ textAlign: 'left' }}> Max </div> <div className='pure-u-1-12' /> </div> </div> {FileList} </div> ) } FilesList.propTypes = { folderPathToRemove: PropTypes.string, folders: PropTypes.instanceOf(List).isRequired } export default FilesList
NebulousLabs/Sia-UI
plugins/Hosting/js/components/fileslist.js
JavaScript
mit
2,874
from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure()
tropp/acq4
acq4/analysis/scripts/beamProfiler.py
Python
mit
976
import {browser, by, element, ExpectedConditions} from 'protractor'; import { ProjectsPage } from './projects.page'; export class BellowsProjectSettingsPage { private readonly projectsPage = new ProjectsPage(); conditionTimeout: number = 3000; settingsMenuLink = element(by.id('settings-dropdown-button')); projectSettingsLink = element(by.id('dropdown-project-settings')); // Get the projectSettings for project projectName get(projectName: string) { this.projectsPage.get(); this.projectsPage.clickOnProject(projectName); browser.wait(ExpectedConditions.visibilityOf(this.settingsMenuLink), this.conditionTimeout); this.settingsMenuLink.click(); browser.wait(ExpectedConditions.visibilityOf(this.projectSettingsLink), this.conditionTimeout); this.projectSettingsLink.click(); } noticeList = element.all(by.repeater('notice in $ctrl.notices()')); firstNoticeCloseButton = this.noticeList.first().element(by.buttonText('×')); tabDivs = element.all(by.className('tab-pane')); activePane = element(by.css('div.tab-pane.active')); /* Would like to use id locators, but the pui-tab directive that is used in the project settingsPage in scripture forge is currently making it hard to assign an id to the tab element. This should be updated, but due to time shortage, it will be left as is. - Mark W 2018-01-15 */ tabs = { project: element(by.linkText('Project Properties')), // reports: element(by.linkText('Reports')), // This feature is never tested // archive: element(by.linkText('Archive')), // This is a disabled feature remove: element(by.linkText('Delete')) }; projectTab = { name: element(by.model('project.projectName')), code: element(by.model('project.projectCode')), projectOwner: element(by.binding('project.ownerRef.username')), saveButton: element(by.id('project-properties-save-button')) }; // placeholder since we don't have Reports tests reportsTab = { }; // Archive tab currently disabled // this.archiveTab = { // archiveButton: this.activePane.element(by.buttonText('Archive this project')) // }; deleteTab = { deleteBoxText: this.activePane.element(by.id('deletebox')), deleteButton: this.activePane.element(by.id('deleteProject')) }; }
ermshiperete/web-languageforge
test/app/bellows/shared/project-settings.page.ts
TypeScript
mit
2,290
/** * Framework APIs (global - app.*) * * Note: View APIs are in view.js (view - view.*) * * @author Tim Lauv * @created 2015.07.29 * @updated 2017.04.04 */ ;(function(app){ /** * Universal app object creation api entry point * ---------------------------------------------------- * @deprecated Use the detailed apis instead. */ app.create = function(type, config){ console.warn('DEV::Application::create() method is deprecated, use methods listed in ', app._apis, ' for alternatives'); }; /** * Detailed api entry point * ------------------------ * If you don't want to use .create() there you go: */ _.extend(app, { //----------------view------------------ //pass in [name,] options to define view (named view will be registered) //pass in name to get registered view def //pass in options, true to create anonymous view view: function(name /*or options*/, options /*or instance flag*/){ if(_.isString(name) && _.isPlainObject(options)){ return app.Core.View.register(name, options); } if(_.isPlainObject(name)){ var instance = options; options = name; var Def = app.Core.View.register(options); if(_.isBoolean(instance) && instance) return Def.create(); return Def; } return app.Core.View.get(name); }, //@deprecated--------------------- //pass in [name,] options to register (always requires a name) //pass in [name] to get (name can be of path form) context: function(name /*or options*/, options){ if(!options) { if(_.isString(name) || !name) return app.Core.Context.get(name); else options = name; } else _.extend(options, {name: name}); console.warn('DEV::Application::context() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/); return app.Core.Context.register(options); }, //-------------------------------- //pass in name, factory to register //pass in name, options to create //pass in [name] to get (name can be of path form) widget: function(name, options /*or factory*/){ if(!options) return app.Core.Widget.get(name); if(_.isFunction(options)) //register return app.Core.Widget.register(name, options); return app.Core.Widget.create(name, options); //you can not register the definition when providing name, options. }, //pass in name, factory to register //pass in name, options to create //pass in [name] to get (name can be of path form) editor: function(name, options /*or factory*/){ if(!options) return app.Core.Editor.get(name); if(_.isFunction(options)) //register return app.Core.Editor.register(name, options); return app.Core.Editor.create(name, options); //you can not register the definition when providing name, options. }, //@deprecated--------------------- regional: function(name, options){ options = options || {}; if(_.isString(name)) _.extend(options, {name: name}); else _.extend(options, name); console.warn('DEV::Application::regional() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/); return app.view(options, !options.name); }, //-------------------------------- //(name can be of path form) has: function(name, type){ type = type || 'View'; if(name) return app.Core[type] && app.Core[type].has(name); _.each(['Context', 'View', 'Widget', 'Editor'], function(t){ if(!type && app.Core[t].has(name)) type = t; }); return type; }, //(name can be of path form) //always return View definition. get: function(name, type, options){ if(!name) return { 'Context': app.Core.Context.get(), 'View': app.Core.View.get(), 'Widget': app.Core.Widget.get(), 'Editor': app.Core.Editor.get() }; if(_.isPlainObject(type)){ options = type; type = undefined; } var Reusable, t = type || 'View'; options = _.extend({fallback: false, override: false}, options); //try local if(!options.override) Reusable = (app.Core[t] && app.Core[t].get(name)) || (options.fallback && app.Core['View'].get(name)); //try remote, if we have app.viewSrcs set to load the View def dynamically if(!Reusable && app.config && app.config.viewSrcs){ var targetJS = _.compact([app.config.viewSrcs, t.toLowerCase()/*not view.category yet*/, app.nameToPath(name)]).join('/') + '.js'; app.inject.js( targetJS, true //sync ).done(function(){ app.debug(t, name, 'injected', 'from', app.config.viewSrcs); if(app.has(name, t) || (options.fallback && app.has(name))) Reusable = app.get(name, t, {fallback: true}); else throw new Error('DEV::Application::get() loaded definitions other than required ' + name + ' of type ' + t + ' from ' + targetJS + ', please check your view name in that file!'); }).fail(function(jqXHR, settings, e){ if(!options.fallback || (t === 'View')) throw new Error('DEV::Application::get() can NOT load definition for ' + name + ' - [' + e + ']'); else Reusable = app.get(name, 'View'); }); } return Reusable; }, //**Caveat**: spray returns the region (created on $anchor), upon returning, its 'show' event has already passed. spray: function($anchor, View /*or template or name or instance or options or svg draw(paper){} func */, options, parentCt){ var $el = $($anchor); parentCt = parentCt || app.mainView; //check if $anchor is already a region var region = $el.data('region'); var regionName = region && region._name; if(!regionName){ regionName = $el.attr('region') || _.uniqueId('anonymous-region-'); $el.attr('region', regionName); region = parentCt.addRegion(regionName, '[region="' + regionName + '"]'); region.ensureEl(parentCt); } else parentCt = region.parentCt; //see if it is an svg draw(paper){} function if(_.isFunction(View) && View.length === 1){ //svg return parentCt.show(regionName, { template: '<div svg="canvas"></div>', data: options && options.data, //only honor options.data if passed in. svg: { canvas: View }, onPaperCleared: function(paper){ paper._fit($el); }, }); }else //view return parentCt.show(regionName, View, options); //returns the sub-regional view. }, icing: function(name, flag, View, options){ if(_.isBoolean(name)){ options = View; View = flag; flag = name; name = 'default'; } var regionName = ['icing', 'region', name].join('-'); if(!app.mainView.getRegion(regionName) && !_.isBoolean(name)){ options = flag; View = name; flag = true; name = 'default'; } regionName = ['icing', 'region', name].join('-'); var ir = app.mainView.getRegion(regionName); if(flag === false){ ir.$el.hide(); ir.currentView && ir.currentView.close(); } else { ir.$el.show(); app.mainView.show(regionName, View, options); } }, coop: function(event){ var args = _.toArray(arguments); args.unshift('app:coop'); app.trigger.apply(app, args); args = args.slice(2); args.unshift('app:coop-' + event); app.trigger.apply(app, args); return app; }, pathToName: function(path){ if(!_.isString(path)) throw new Error('DEV::Application::pathToName() You must pass in a valid path string.'); if(_.contains(path, '.')) return path; return path.split('/').map(_.string.humanize).map(_.string.classify).join('.'); }, nameToPath: function(name){ if(!_.isString(name)) throw new Error('DEV::Application::nameToPath() You must pass in a Reusable view name.'); if(_.contains(name, '/')) return name; return name.split('.').map(_.string.humanize).map(_.string.slugify).join('/'); }, //----------------navigation----------- navigate: function(options, silent){ return app.trigger('app:navigate', options, silent); }, navPathArray: function(){ return _.compact(window.location.hash.replace('#navigate', '').split('/')); }, //-----------------mutex--------------- lock: function(topic){ return app.Core.Lock.lock(topic); }, unlock: function(topic){ return app.Core.Lock.unlock(topic); }, available: function(topic){ return app.Core.Lock.available(topic); }, //-----------------remote data------------ //returns jqXHR object (use promise pls) remote: function(options /*or url*/, payload, restOpt){ options = options || {}; if(options.payload || payload){ payload = options.payload || payload; return app.Core.Remote.change(options, _.extend({payload: payload}, restOpt)); } else return app.Core.Remote.get(options, restOpt); }, download: function(ticket /*or url*/, options /*{params:{...}} only*/){ return app.Util.download(ticket, options); }, upload: function(url, options){ return app.Util.upload(url, options); }, //data push //(ws channels) _websockets: {}, /** * returns a promise. * * Usage * ----- * register: app.config.defaultWebsocket or app.ws(socketPath); * receive (e): view.coop['ws-data-[channel]'] or app.onWsData = custom fn; * send (json): app.ws(socketPath) * .then(function(ws){ws.channel(...).json({...});}); default per channel data * .then(function(ws){ws.send(); or ws.json();}); anything by any contract * e.websocket = ws in .then(function(ws){}) * * Default messaging contract * -------------------------- * Nodejs /devserver: json {channel: '..:..', payload: {..data..}} through ws.channel('..:..').json({..data..}) * Python ASGI: json {stream: '...', payload: {..data..}} through ws.stream('...').json({..data..}) * * Reconnecting websockets * ----------------------- * websocket path ends with '+' will be reconnecting websocket when created. * */ ws: function(socketPath, coopEvent /*or callback or options*/){ if(!app.detect('websockets')) throw new Error('DEV::Application::ws() Websocket is not supported by your browser!'); socketPath = socketPath || app.config.defaultWebsocket || '/ws'; var reconnect = false; if(_.string.endsWith(socketPath, '+')){ socketPath = socketPath.slice(0, socketPath.length - 1); reconnect = true; } var d = $.Deferred(); if(!app._websockets[socketPath]) { app._websockets[socketPath] = new WebSocket(location.protocol.replace('http', 'ws') + '//' + location.host + socketPath); app._websockets[socketPath].path = socketPath; app._websockets[socketPath].reconnect = reconnect; //events: 'open', 'error', 'close', 'message' = e.data //apis: send(), +json(), +channel().json(), close() app._websockets[socketPath].json = function(data){ app._websockets[socketPath].send(JSON.stringify(data)); }; app._websockets[socketPath].channel = function(channel){ return { name: channel, websocket: app._websockets[socketPath], json: function(data){ app._websockets[socketPath].json({ channel: channel, stream: channel, //alias for ASGI backends payload: data }); } }; }; app._websockets[socketPath].stream = app._websockets[socketPath].channel; //alias for ASGI backends app._websockets[socketPath].onclose = function(){ var ws = app._websockets[socketPath]; delete app._websockets[socketPath]; if(ws.reconnect) app.ws(ws.path + '+'); }; app._websockets[socketPath].onopen = function(){ return d.resolve(app._websockets[socketPath]); }; //general ws data stub //server need to always send default json contract string {"channel/stream": "...", "payload": "..."} //Opt: override this through app.ws(path).then(function(ws){ws.onmessage=...}); app._websockets[socketPath].onmessage = function(e){ //opt a. override app.onWsData to active otherwise app.trigger('app:ws-data', {websocket: app._websockets[socketPath], raw: e.data}); //opt b. use global coop event 'ws-data-[channel]' in views directly (default json contract) try { var data = JSON.parse(e.data); app.coop('ws-data-' + (data.channel || data.stream), data.payload, app._websockets[socketPath].channel(data.channel || data.stream)); }catch(ex){ console.warn('DEV::Application::ws() Websocket is getting non-default {channel: ..., payload: ...} json contract strings...'); } }; //register coopEvent or callback function or callback options if(coopEvent){ //onmessage callback function if(_.isFunction(coopEvent)){ //overwrite onmessage callback function defined by framework app._websockets[socketPath].onmessage = function(e){ coopEvent(e.data, e, app._websockets[socketPath]); }; } //object may contain onmessage, onerror, since onopen and onclose is done by the framework else if(_.isPlainObject(coopEvent)){ //traverse through object to register all callback events _.each(coopEvent, function(fn, eventName){ //guard events if(_.contains(['onmessage', 'onerror'], eventName)) app._websockets[socketPath][eventName] = fn; }); } //app coop event else if(_.isString(coopEvent)){ //trigger coop event with data from sse's onmessage callback app._websockets[socketPath].onmessage = function(e){ app.coop('ws-data-' + coopEvent, e.data, e, app._websockets[socketPath]); }; } //type is not right else console.warn('DEV::Application::ws() The coopEvent or callback function or callbacks\' options you give is not right.'); } }else d.resolve(app._websockets[socketPath]); return d.promise(); }, //data polling //(through later.js) and emit data events/or invoke callback _polls: {}, poll: function(url /*or {options} for app.remote()*/, occurrence, coopEvent /*or callback or options*/) { //stop everything if (url === false){ return _.map(this._polls, function(card) { return card.cancel(); }); } var schedule; if (_.isString(occurrence) && !Number.parseInt(occurrence)) { schedule = app.later.parse.text(occurrence); if (schedule.error !== -1) throw new Error('DEV::Application::poll() occurrence string unrecognizable...'); } else if (_.isPlainObject(occurrence)) schedule = occurrence; else //number schedule = Number(occurrence); //make a key from url, or {url: ..., params/querys} var key = url; if (_.isPlainObject(key)) key = [key.url, _.reduce((_.map(key.params || key.querys, function(qV, qKey) { return [qKey, qV].join('='); })).sort(), function(qSignature, more) { return [more, qSignature].join('&'); }, '')].join('?'); //cancel polling if (occurrence === false) { if (this._polls[key]) return this._polls[key].cancel(); console.warn('DEV::Application::poll() No polling card registered yet for ' + key); return; } //cancel previous polling if (this._polls[key]) this._polls[key].cancel(); //register polling card if (!occurrence || !coopEvent) throw new Error('DEV::Application::poll() You must specify an occurrence and a coop event or callback...'); var card = { _key: key, url: url, eof: coopEvent, timerId: undefined, failed: 0, valid: true, occurrence: occurrence, //info only }; this._polls[key] = card; var call = _.isNumber(schedule) ? window.setTimeout : app.later.setTimeout; //if coopEvent is an object. register options events before calling app.remote if(_.isPlainObject(coopEvent)){ //save url var temp = url; //build url as an object for app.remote url = { url: temp }; _.each(coopEvent, function(fn, eventName){ //guard for only allowing $.ajax events if(_.contains(['beforeSend', 'error', 'dataFilter', 'success', 'complete'], eventName)) url[eventName] = fn; }); } var worker = function() { app.remote(url).done(function(data) { //callback if (_.isFunction(card.eof)) card.eof(data, card); //coop event else app.coop('poll-data-' + card.eof, data, card); }).fail(function() { card.failed++; //Warning: Hardcoded 3 attemps here! if (card.failed >= 3) card.cancel(); }).always(function() { //go schedule the next call if (card.valid) card.timerId = call(worker, schedule); }); }; //+timerType card.timerType = (call === window.setTimeout) ? 'native' : 'later.js'; //+cancel() var that = this; card.cancel = function() { this.valid = false; if (this.timerType === 'native') !_.isUndefined(this.timerId) && window.clearTimeout(this.timerId); else !_.isUndefined(this.timerId) && this.timerId.clear(); delete that._polls[this._key]; return this; }; //make the 1st call (eagerly) worker(); }, //-----------------ee/observer with built-in state-machine---------------- //use start('stateB') or trigger('stateA-->stateB') to swap between states //use ['stateA-->stateB', 'stateC<-->stateB', 'stateA<--stateC', ...] in edges to constrain state changes. ee: function(data, evtmap, edges){ //+on/once, off, +start/reset/stop/getState/getEdges; +listenTo/Once, stopListening; +trigger*; var dispatcher; data = _.extend({}, data, {cid: _.uniqueId('ee')}); evtmap = _.extend({ 'initialize': _.noop, 'finalize': _.noop, }, evtmap); edges = _.reduce(edges || {}, function(mem, val, index){ var bi = val.match('(.*)<-->(.*)'), left = val.match('(.*)<--(.*)'), right = val.match('(.*)-->(.*)'); if(bi){ mem[bi[1] + '-->' + bi[2]] = true; mem[bi[2] + '-->' + bi[1]] = true; } else if (left) mem[left[2] + '-->' + left[1]] = true; else if (right) mem[val] = true; else console.warn('DEV::Application::ee() illegal edge format: ' + val); return mem; }, {}); if(!_.size(edges)) edges = undefined; dispatcher = _.extend(data, Backbone.Events); var oldTriggerFn = dispatcher.trigger; var currentState = ''; //add a state-machine friendly .trigger method; dispatcher.trigger = function(){ var changeOfStates = arguments[0] && arguments[0].match('(.*)-->(.*)'); if(changeOfStates && changeOfStates.length){ var from = _.string.trim(changeOfStates[1]), to = _.string.trim(changeOfStates[2]); //check edge constraints if(from && to && edges && !edges[arguments[0]]){ console.warn('DEV::Application::ee() edge constraint: ' + from + '-x->' + to); return this; } //check current state if(from != currentState){ console.warn('DEV::Application::ee() current state is ' + (currentState || '\'\'') + ' not ' + from); return this; } this.trigger('leave', {to: to}); //unregister event listeners in [from] state _.each(evtmap[from], function(listener, e){ dispatcher.off(from + ':' + e); }); //register event listeners in [to] state _.each(evtmap[to], function(listener, e){ dispatcher.on(to + ':' + e, listener); }); currentState = to; this.trigger('enter', {from: from}); } else { if(evtmap[currentState] && evtmap[currentState][arguments[0]]) arguments[0] = currentState + ':' + arguments[0]; oldTriggerFn.apply(this, arguments); } return this; }; //add an internal worker swap method; dispatcher._swap = function(targetState){ targetState = targetState || ''; this.trigger(currentState + '-->' + targetState); return this; }; //add a start method; (start at any state) dispatcher.start = function(targetState){ targetState = targetState || currentState; return this._swap(targetState); }; //add a reset method; (reset to '' state) dispatcher.reset = function(){ return this._swap(); }; //add a clean-up method; dispatcher.stop = function(){ this.trigger('finalize'); this.off(); this.stopListening(); }; //add some getters; dispatcher.getState = function(){ return currentState; }; dispatcher.getEdges = function(){ return edges; }; //mount shared events _.each(evtmap, function(listener, eOrStateName){ if(!_.isFunction(listener)) return; dispatcher.on(eOrStateName, listener); }); this.trigger('initialize'); return dispatcher; }, model: function(data, flat){ if(_.isBoolean(data)){ flat = data; data = undefined; } if(flat) return new Backbone.Model(data); //Warning: Possible performance impact...(default) return new Backbone.DeepModel(data); ///////////////////////////////////////// }, collection: function(data){ if(data && !_.isArray(data)) throw new Error('DEV::Application::collection You need to specify an array to init a collection'); return new Backbone.Collection(data); }, //bridge extract from app.Util.deepObjectKeys extract: function(keypath, from){ return app.Util.deepObjectKeys.extract(keypath, from); }, //bridge pack from app.Util.deepObjectKeys pack: function(keypathObj, to){ return app.Util.deepObjectKeys.pack(keypathObj, to); }, mock: function(schema, provider/*optional*/, url/*optional*/){ return app.Util.mock(schema, provider, url); }, //----------------url params--------------------------------- param: function(key, defaultVal){ var params = app.uri(window.location.href).search(true) || {}; if(key) return params[key] || defaultVal; return params; }, //----------------raw animation (DON'T mix with jQuery fx)--------------- //(specifically, don't call $.animate() inside updateFn) //(you also can NOT control the rate the browser calls updateFn, its 60 FPS all the time...) animation: function(updateFn, condition, ctx){ var id; var stepFn = function(t){ updateFn.call(ctx);//...update...(1 tick) if(!condition || (condition && condition.call(ctx)))//...condition...(to continue) move(); }; var move = function(){ if(id === undefined) return; id = app._nextFrame(stepFn); }; var stop = function(){ app._cancelFrame(id); id = undefined; }; return { start: function(){id = -1; move();}, stop: stop }; }, _nextFrame: function(stepFn){ //return request id return window.requestAnimationFrame(stepFn); }, _cancelFrame: function(id){ return window.cancelAnimationFrame(id); }, //effects see https://daneden.github.io/animate.css/ //sample usage: 'ready' --> app.animateItems(); animateItems: function(selector /*or $items*/, effect, stagger){ var $selector = $(selector); if(_.isNumber(effect)){ stagger = effect; effect = undefined; } effect = effect || 'flipInX'; stagger = stagger || 150; var inOrOut = /In/.test(effect)? 1: (/Out/.test(effect)? -1: 0); $selector.each(function(i, el){ var $el = $(el); //////////////////different than region.show effect because of stagger delay////////////////// if(inOrOut) if(inOrOut === 1) $el.css('opacity', 0); else $el.css('opacity', 1); ////////////////////////////////////////////////////////////////////////////////////////////// _.delay(function($el){ var fxName = effect + ' animated'; $el.anyone(app.ADE, function(){ $el.removeClass(fxName); }).addClass(fxName); ///////////////reset opacity immediately, not after ADE/////////////// if(inOrOut) if(inOrOut === 1) $el.css('opacity', 1); else $el.css('opacity', 0); ////////////////////////////////////////////////////////////////////// }, i * stagger, $el); }); }, //Built-in web worker utility, bridged from app.Util.worker. worker: function(name/*web worker's name*/, coopEOrCallbackOrOpts){ return app.Util.worker(name, coopEOrCallbackOrOpts); }, //Built-in Server-Sent Event(SSE) utility, bridged from app.Util.sse sse: function(url/*sse's url*/, topics/*['...', '...']*/, coopEOrCallbackOrOpts){ return app.Util.sse(url, topics, coopEOrCallbackOrOpts); }, //----------------config.rapidEventDelay wrapped util-------------------- //**Caveat**: if using cached version, pass `this` and other upper scope vars into fn as arguments, else //these in fn will be cached forever and might no longer exist or point to the right thing when called... throttle: function(fn, ms, cacheId){ ms = ms || app.config.rapidEventDelay; fn = _.throttle(fn, ms); if(!cacheId) return fn; //cached version (so you can call right after wrapping it) this._tamedFns = this._tamedFns || {}; var key = fn + cacheId + '-throttle' + ms; if(!this._tamedFns[key]) this._tamedFns[key] = fn; return this._tamedFns[key]; }, debounce: function(fn, ms, cacheId){ ms = ms || app.config.rapidEventDelay; fn = _.debounce(fn, ms); if(!cacheId) return fn; //cached version (so you can call right after wrapping it) this._tamedFns = this._tamedFns || {}; var key = fn + cacheId + '-debounce' + ms; if(!this._tamedFns[key]) this._tamedFns[key] = fn; return this._tamedFns[key]; }, //app wide e.preventDefault() util preventDefaultE: function(e){ var $el = $(e.target); //Caveat: this clumsy bit here is due to the in-ability to check on the 'action-*' attributes on e.target... if($el.is('label') || $el.is('i') || $el.is('img') || $el.is('span') || $el.is('input') || $el.is('textarea') || $el.is('select') || ($el.is('a') && $el.attr('href'))) return; e.preventDefault(); }, //wait until all targets fires e (asynchronously) then call the callback with targets (e.g [this.show(), ...], 'ready') until: function(targets, e, callback){ targets = _.compact(targets); cb = _.after(targets.length, function(){ callback(targets); }); _.each(targets, function(t){ t.once(e, cb); }); }, //----------------markdown------------------- //options.marked, options.hljs //https://guides.github.com/features/mastering-markdown/ //our addition: // ^^^class class2 class3 ... // ... // ^^^ markdown: function(md, $anchor /*or options*/, options){ options = options || (!_.isjQueryObject($anchor) && $anchor) || {}; //render content var html = marked(md, app.debug('marked options are', _.extend(app.config.marked, (options.marked && options.marked) || options, _.isjQueryObject($anchor) && $anchor.data('marked')))), hljs = window.hljs; //highlight code (use ```language to specify type) if(hljs){ hljs.configure(app.debug('hljs options are', _.extend(app.config.hljs, options.hljs, _.isjQueryObject($anchor) && $anchor.data('hljs')))); var $html = $('<div>' + html + '</div>'); $html.find('pre code').each(function(){ hljs.highlightBlock(this); }); html = $html.html(); } if(_.isjQueryObject($anchor)) return $anchor.html(html).addClass('md-content'); return html; }, //----------------notify/overlay/popover--------------------- notify: function(title /*or options*/, msg, type /*or otherOptions*/, otherOptions){ if(_.isString(title)){ if(_.isPlainObject(type)){ otherOptions = type; type = undefined; } if(otherOptions && otherOptions.icon){ //theme awesome ({.icon, .more}) $.amaran(_.extend({ theme: 'awesome ' + (type || 'ok'), //see http://ersu.me/article/amaranjs/amaranjs-themes for types content: { title: title, message: msg, info: otherOptions.more || ' ', icon: otherOptions.icon } }, otherOptions)); } else { //custom theme $.amaran(_.extend({ content: { themeName: 'stagejs', title: title, message: msg, type: type || 'info', }, themeTemplate: app.NOTIFYTPL }, otherOptions)); } } else $.amaran(title); }, //overlay or popover prompt: function(view, anchor, placement, options){ if(_.isFunction(view)) view = new view(); else if(_.isString(view)) view = app.get(view).create(); //is popover if(_.isString(placement)){ options = options || {}; options.placement = placement; return view.popover(anchor, options); } //is overlay options = placement; return view.overlay(anchor, options); }, //----------------i18n----------------------- i18n: function(key, ns){ if(key){ //insert translations to current locale if(_.isPlainObject(key)) return I18N.insertTrans(key); //return a translation for specified key, ns/module return String(key).i18n(ns); } //otherwise, collect available strings (so far) into an i18n object. return I18N.getResourceJSON(null, false); }, //----------------debug---------------------- //bridge app.debug() debug: function(){ return app.Util.debugHelper.debug.apply(null, arguments); }, //bridge app.locate() locate: function(name /*el or $el*/){ return app.Util.debugHelper.locate(name); }, //bridge app.profile() profile: function(name /*el or $el*/){ return app.Util.debugHelper.profile(name); }, //bridge app.mark() mark: function(name /*el or $el*/){ return app.Util.debugHelper.mark(name); }, //bridge app.reload() reload: function(name, override/*optional*/){ return app.Util.debugHelper.reload(name, override); }, inject: { js: function(){ return app.Util.inject.apply(null, arguments); }, tpl: function(){ return app.Util.Tpl.remote.apply(app.Util.Tpl, arguments); }, css: function(){ return loadCSS.apply(null, arguments); } }, detect: function(feature, provider/*optional*/){ if(!provider) provider = Modernizr; return app.extract(feature, provider) || false; }, //--------3rd party lib pass-through--------- // js-cookie (former jquery-cookie) //.set(), .get(), .remove() cookie: Cookies, // store.js (localStorage) //.set(), .get(), .getAll(), .remove(), .clear() store: store.enabled && store, // validator.js (var type and val validation, e.g form editor validation) validator: validator, // moment.js (date and time) moment: moment, // URI.js (uri,query and hash in the url, e.g in app.param()) uri: URI, // later.js (schedule repeated workers, e.g in app.poll()) later: later, // faker.js (mock data generator, e.g in app.mock()) faker: faker, }); //editor rules app.editor.validator = app.editor.rule = function(name, fn){ if(!_.isString(name)) throw new Error('DEV::Validator:: You must specify a validator/rule name to use.'); return app.Core.Editor.addRule(name, fn); }; //alias app.page = app.context; app.area = app.regional; app.curtain = app.icing; /** * API summary */ app._apis = [ 'ee', 'model', 'collection', 'mock', //view registery 'view', 'widget', 'editor', 'editor.validator - @alias:editor.rule', //global action locks 'lock', 'unlock', 'available', //utils 'has', 'get', 'spray', 'coop', 'navigate', 'navPathArray', 'icing/curtain', 'i18n', 'param', 'animation', 'animateItems', 'throttle', 'debounce', 'preventDefaultE', 'until', //com 'remote', 'download', 'upload', 'ws', 'poll', 'worker', 'sse', //3rd-party lib short-cut 'extract', 'markdown', 'notify', 'prompt', //wraps 'cookie', 'store', 'moment', 'uri', 'validator', 'later', 'faker', //direct refs //supportive 'debug', 'detect', 'reload', 'locate', 'profile', 'mark', 'nameToPath', 'pathToName', 'inject.js', 'inject.tpl', 'inject.css', //@deprecated 'create - @deprecated', 'regional - @deprecated', 'context - @alias:page - @deprecated' ]; /** * Statics */ //animation done events used in Animate.css //Caveat: if you use $el.one(app.ADE) but still got 2+ callback calls, the browser is firing the default and prefixed events at the same time... //use $el.anyone() to fix the problem in using $el.one() app.ADE = 'animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'; //notification template app.NOTIFYTPL = Handlebars.compile('<div class="alert alert-dismissable alert-{{type}}"><button data-dismiss="alert" class="close" type="button">×</button><strong>{{title}}</strong> {{{message}}}</div>'); })(Application);
mr-beaver/Stage.js
implementation/js/src/infrastructure/api.js
JavaScript
mit
32,954
// Base64 encoder/decoder with UTF-8 support // // Copyright (c) 2011 Vitaly Puzrin // Copyright (c) 2011 Aleksey V Zapparov // // Author: Aleksey V Zapparov AKA ixti (http://www.ixti.net/) // // 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. // Based on original artworks of base64 encoder/decoder by [Mozilla][1] // [1]: http://lxr.mozilla.org/mozilla/source/extensions/xml-rpc/src/nsXmlRpcClient.js 'use strict'; /* eslint-env browser */ /* eslint-disable no-bitwise */ function noop() {} var logger = { warn: noop, error: noop }, padding = '=', chrTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + '0123456789+/', binTable = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 ]; if (window.console) { logger = window.console; logger.warn = logger.warn || logger.error || logger.log || noop; logger.error = logger.error || logger.warn || logger.log || noop; } // internal helpers ////////////////////////////////////////////////////////// function utf8Encode(str) { var bytes = [], offset = 0, length, char; str = encodeURI(str); length = str.length; while (offset < length) { char = str.charAt(offset); offset += 1; if (char !== '%') { bytes.push(char.charCodeAt(0)); } else { char = str.charAt(offset) + str.charAt(offset + 1); bytes.push(parseInt(char, 16)); offset += 2; } } return bytes; } function utf8Decode(bytes) { var chars = [], offset = 0, length = bytes.length, c1, c2, c3; while (offset < length) { c1 = bytes[offset]; c2 = bytes[offset + 1]; c3 = bytes[offset + 2]; if (c1 < 128) { chars.push(String.fromCharCode(c1)); offset += 1; } else if (191 < c1 && c1 < 224) { chars.push(String.fromCharCode(((c1 & 31) << 6) | (c2 & 63))); offset += 2; } else { chars.push(String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))); offset += 3; } } return chars.join(''); } // public api //////////////////////////////////////////////////////////////// function encode(str) { var result = '', bytes = utf8Encode(str), length = bytes.length, i; // Convert every three bytes to 4 ascii characters. for (i = 0; i < (length - 2); i += 3) { result += chrTable[bytes[i] >> 2]; result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)]; result += chrTable[((bytes[i + 1] & 0x0f) << 2) + (bytes[i + 2] >> 6)]; result += chrTable[bytes[i + 2] & 0x3f]; } // Convert the remaining 1 or 2 bytes, pad out to 4 characters. if (length % 3) { i = length - (length % 3); result += chrTable[bytes[i] >> 2]; if ((length % 3) === 2) { result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)]; result += chrTable[(bytes[i + 1] & 0x0f) << 2]; result += padding; } else { result += chrTable[(bytes[i] & 0x03) << 4]; result += padding + padding; } } return result; } function decode(data) { var value, code, idx = 0, bytes = [], leftbits = 0, // number of bits decoded, but yet to be appended leftdata = 0; // bits decoded, but yet to be appended // Convert one by one. for (idx = 0; idx < data.length; idx += 1) { code = data.charCodeAt(idx); value = binTable[code & 0x7F]; if (value === -1) { // Skip illegal characters and whitespace logger.warn('Illegal characters (code=' + code + ') in position ' + idx); } else { // Collect data into leftdata, update bitcount leftdata = (leftdata << 6) | value; leftbits += 6; // If we have 8 or more bits, append 8 bits to the result if (leftbits >= 8) { leftbits -= 8; // Append if not padding. if (padding !== data.charAt(idx)) { bytes.push((leftdata >> leftbits) & 0xFF); } leftdata &= (1 << leftbits) - 1; } } } // If there are any bits left, the base64 string was corrupted if (leftbits) { logger.error('Corrupted base64 string'); return null; } return utf8Decode(bytes); } exports.encode = encode; exports.decode = decode;
minj/js-yaml
support/demo_template/base64.js
JavaScript
mit
5,692
module.exports = require("npm:acorn@2.4.0/dist/acorn");
TelerikFrenchConnection/JS-Applications-Teamwork
lib/npm/acorn@2.4.0.js
JavaScript
mit
55
require 'rr' require 'awesome_print' %w"xiki/core/core_ext xiki/core/ol".each {|o| require o} # RSpec::Runner.configure do |config| RSpec.configure do |config| config.mock_with :rr end module Xiki def self.dir File.expand_path("#{File.dirname(__FILE__)}/..") + "/" end end def stub_menu_path_dirs xiki_dir = Xiki.dir list = ["#{xiki_dir}spec/fixtures/menu", "#{xiki_dir}menu"] stub(Xiki).menu_path_dirs {list} end # Put this here until we can put it in a better place # - Maybe so it'll be used by main xiki and conf AwesomePrint.defaults = { :indent => -2, # left-align hash keys :index => false, :multiline => true, } include Xiki # Allows all specs to use classes in the Xiki module without "Xiki::"
stanwmusic/xiki
spec/spec_helper.rb
Ruby
mit
738
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create oauthclient tables.""" import sqlalchemy as sa import sqlalchemy_utils from alembic import op from sqlalchemy.engine.reflection import Inspector # revision identifiers, used by Alembic. revision = '97bbc733896c' down_revision = '44ab9963e8cf' branch_labels = () depends_on = '9848d0149abd' def upgrade(): """Upgrade database.""" op.create_table( 'oauthclient_remoteaccount', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column( 'extra_data', sqlalchemy_utils.JSONType(), nullable=False), sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('user_id', 'client_id') ) op.create_table( 'oauthclient_useridentity', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('method', sa.String(length=255), nullable=False), sa.Column('id_user', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ), sa.PrimaryKeyConstraint('id', 'method') ) op.create_index( 'useridentity_id_user_method', 'oauthclient_useridentity', ['id_user', 'method'], unique=True ) op.create_table( 'oauthclient_remotetoken', sa.Column('id_remote_account', sa.Integer(), nullable=False), sa.Column('token_type', sa.String(length=40), nullable=False), sa.Column( 'access_token', sqlalchemy_utils.EncryptedType(), nullable=False), sa.Column('secret', sa.Text(), nullable=False), sa.ForeignKeyConstraint( ['id_remote_account'], [u'oauthclient_remoteaccount.id'], name='fk_oauthclient_remote_token_remote_account' ), sa.PrimaryKeyConstraint('id_remote_account', 'token_type') ) def downgrade(): """Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) op.drop_table('oauthclient_remotetoken') for fk in insp.get_foreign_keys('oauthclient_useridentity'): if fk['referred_table'] == 'accounts_user': op.drop_constraint( op.f(fk['name']), 'oauthclient_useridentity', type_='foreignkey' ) op.drop_index( 'useridentity_id_user_method', table_name='oauthclient_useridentity') op.drop_table('oauthclient_useridentity') op.drop_table('oauthclient_remoteaccount')
tiborsimko/invenio-oauthclient
invenio_oauthclient/alembic/97bbc733896c_create_oauthclient_tables.py
Python
mit
2,898
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Platform; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.General { public class UpdateSettings : SettingsSubsection { protected override string Header => "Updates"; [BackgroundDependencyLoader] private void load(Storage storage, OsuConfigManager config) { Children = new Drawable[] { new SettingsEnumDropdown<ReleaseStream> { LabelText = "Release stream", Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream), }, new SettingsButton { Text = "Open osu! folder", Action = storage.OpenInNativeExplorer, } }; } } }
NeoAdonis/osu
osu.Game/Overlays/Settings/Sections/General/UpdateSettings.cs
C#
mit
1,060
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.eventhubs.v2017_04_01.implementation; import java.util.List; import org.joda.time.DateTime; import com.microsoft.azure.management.eventhubs.v2017_04_01.EntityStatus; import com.microsoft.azure.management.eventhubs.v2017_04_01.CaptureDescription; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.ProxyResource; /** * Single item in List or Get Event Hub operation. */ @JsonFlatten public class EventhubInner extends ProxyResource { /** * Current number of shards on the Event Hub. */ @JsonProperty(value = "properties.partitionIds", access = JsonProperty.Access.WRITE_ONLY) private List<String> partitionIds; /** * Exact time the Event Hub was created. */ @JsonProperty(value = "properties.createdAt", access = JsonProperty.Access.WRITE_ONLY) private DateTime createdAt; /** * The exact time the message was updated. */ @JsonProperty(value = "properties.updatedAt", access = JsonProperty.Access.WRITE_ONLY) private DateTime updatedAt; /** * Number of days to retain the events for this Event Hub, value should be * 1 to 7 days. */ @JsonProperty(value = "properties.messageRetentionInDays") private Long messageRetentionInDays; /** * Number of partitions created for the Event Hub, allowed values are from * 1 to 32 partitions. */ @JsonProperty(value = "properties.partitionCount") private Long partitionCount; /** * Enumerates the possible values for the status of the Event Hub. Possible * values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', * 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. */ @JsonProperty(value = "properties.status") private EntityStatus status; /** * Properties of capture description. */ @JsonProperty(value = "properties.captureDescription") private CaptureDescription captureDescription; /** * Get current number of shards on the Event Hub. * * @return the partitionIds value */ public List<String> partitionIds() { return this.partitionIds; } /** * Get exact time the Event Hub was created. * * @return the createdAt value */ public DateTime createdAt() { return this.createdAt; } /** * Get the exact time the message was updated. * * @return the updatedAt value */ public DateTime updatedAt() { return this.updatedAt; } /** * Get number of days to retain the events for this Event Hub, value should be 1 to 7 days. * * @return the messageRetentionInDays value */ public Long messageRetentionInDays() { return this.messageRetentionInDays; } /** * Set number of days to retain the events for this Event Hub, value should be 1 to 7 days. * * @param messageRetentionInDays the messageRetentionInDays value to set * @return the EventhubInner object itself. */ public EventhubInner withMessageRetentionInDays(Long messageRetentionInDays) { this.messageRetentionInDays = messageRetentionInDays; return this; } /** * Get number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. * * @return the partitionCount value */ public Long partitionCount() { return this.partitionCount; } /** * Set number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. * * @param partitionCount the partitionCount value to set * @return the EventhubInner object itself. */ public EventhubInner withPartitionCount(Long partitionCount) { this.partitionCount = partitionCount; return this; } /** * Get enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. * * @return the status value */ public EntityStatus status() { return this.status; } /** * Set enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. * * @param status the status value to set * @return the EventhubInner object itself. */ public EventhubInner withStatus(EntityStatus status) { this.status = status; return this; } /** * Get properties of capture description. * * @return the captureDescription value */ public CaptureDescription captureDescription() { return this.captureDescription; } /** * Set properties of capture description. * * @param captureDescription the captureDescription value to set * @return the EventhubInner object itself. */ public EventhubInner withCaptureDescription(CaptureDescription captureDescription) { this.captureDescription = captureDescription; return this; } }
selvasingh/azure-sdk-for-java
sdk/eventhubs/mgmt-v2017_04_01/src/main/java/com/microsoft/azure/management/eventhubs/v2017_04_01/implementation/EventhubInner.java
Java
mit
5,503
import actionTypes from '../../client/actions/types'; const defaultState = { data: {}, errors: 'Not Found', }; export default function domainDetailReducer(state = defaultState, action = {}) { switch (action.type) { case actionTypes.getDomainDetail: return Object.assign({}, state, { data: action.data.domain, errors: action.errors, }); default: return state; } }
willopez/domainsjs
shared/report/domain-detail.js
JavaScript
mit
415
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require_tree .
astjohn/cornerstone
app/assets/javascripts/cornerstone.js
JavaScript
mit
465
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcGloballyUniqueId.h" #include "ifcpp/IFC4/include/IfcIdentifier.h" #include "ifcpp/IFC4/include/IfcLabel.h" #include "ifcpp/IFC4/include/IfcMember.h" #include "ifcpp/IFC4/include/IfcMemberTypeEnum.h" #include "ifcpp/IFC4/include/IfcObjectPlacement.h" #include "ifcpp/IFC4/include/IfcOwnerHistory.h" #include "ifcpp/IFC4/include/IfcProductRepresentation.h" #include "ifcpp/IFC4/include/IfcRelAggregates.h" #include "ifcpp/IFC4/include/IfcRelAssigns.h" #include "ifcpp/IFC4/include/IfcRelAssignsToProduct.h" #include "ifcpp/IFC4/include/IfcRelAssociates.h" #include "ifcpp/IFC4/include/IfcRelConnectsElements.h" #include "ifcpp/IFC4/include/IfcRelConnectsWithRealizingElements.h" #include "ifcpp/IFC4/include/IfcRelContainedInSpatialStructure.h" #include "ifcpp/IFC4/include/IfcRelCoversBldgElements.h" #include "ifcpp/IFC4/include/IfcRelDeclares.h" #include "ifcpp/IFC4/include/IfcRelDefinesByObject.h" #include "ifcpp/IFC4/include/IfcRelDefinesByProperties.h" #include "ifcpp/IFC4/include/IfcRelDefinesByType.h" #include "ifcpp/IFC4/include/IfcRelFillsElement.h" #include "ifcpp/IFC4/include/IfcRelInterferesElements.h" #include "ifcpp/IFC4/include/IfcRelNests.h" #include "ifcpp/IFC4/include/IfcRelProjectsElement.h" #include "ifcpp/IFC4/include/IfcRelReferencedInSpatialStructure.h" #include "ifcpp/IFC4/include/IfcRelSpaceBoundary.h" #include "ifcpp/IFC4/include/IfcRelVoidsElement.h" #include "ifcpp/IFC4/include/IfcText.h" // ENTITY IfcMember IfcMember::IfcMember( int id ) { m_entity_id = id; } shared_ptr<BuildingObject> IfcMember::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcMember> copy_self( new IfcMember() ); if( m_GlobalId ) { if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = make_shared<IfcGloballyUniqueId>( createBase64Uuid_wstr().data() ); } else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); } } if( m_OwnerHistory ) { if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; } else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); } } if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); } if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); } if( m_ObjectType ) { copy_self->m_ObjectType = dynamic_pointer_cast<IfcLabel>( m_ObjectType->getDeepCopy(options) ); } if( m_ObjectPlacement ) { copy_self->m_ObjectPlacement = dynamic_pointer_cast<IfcObjectPlacement>( m_ObjectPlacement->getDeepCopy(options) ); } if( m_Representation ) { copy_self->m_Representation = dynamic_pointer_cast<IfcProductRepresentation>( m_Representation->getDeepCopy(options) ); } if( m_Tag ) { copy_self->m_Tag = dynamic_pointer_cast<IfcIdentifier>( m_Tag->getDeepCopy(options) ); } if( m_PredefinedType ) { copy_self->m_PredefinedType = dynamic_pointer_cast<IfcMemberTypeEnum>( m_PredefinedType->getDeepCopy(options) ); } return copy_self; } void IfcMember::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCMEMBER" << "("; if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectType ) { m_ObjectType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectPlacement ) { stream << "#" << m_ObjectPlacement->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Representation ) { stream << "#" << m_Representation->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Tag ) { m_Tag->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_PredefinedType ) { m_PredefinedType->getStepParameter( stream ); } else { stream << "$"; } stream << ");"; } void IfcMember::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; } const std::wstring IfcMember::toString() const { return L"IfcMember"; } void IfcMember::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 9 ){ std::stringstream err; err << "Wrong parameter count for entity IfcMember, expecting 9, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map ); readEntityReference( args[1], m_OwnerHistory, map ); m_Name = IfcLabel::createObjectFromSTEP( args[2], map ); m_Description = IfcText::createObjectFromSTEP( args[3], map ); m_ObjectType = IfcLabel::createObjectFromSTEP( args[4], map ); readEntityReference( args[5], m_ObjectPlacement, map ); readEntityReference( args[6], m_Representation, map ); m_Tag = IfcIdentifier::createObjectFromSTEP( args[7], map ); m_PredefinedType = IfcMemberTypeEnum::createObjectFromSTEP( args[8], map ); } void IfcMember::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcBuildingElement::getAttributes( vec_attributes ); vec_attributes.emplace_back( std::make_pair( "PredefinedType", m_PredefinedType ) ); } void IfcMember::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IfcBuildingElement::getAttributesInverse( vec_attributes_inverse ); } void IfcMember::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcBuildingElement::setInverseCounterparts( ptr_self_entity ); } void IfcMember::unlinkFromInverseCounterparts() { IfcBuildingElement::unlinkFromInverseCounterparts(); }
ifcquery/ifcplusplus
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcMember.cpp
C++
mit
6,494
/** * Copyright 2014 Pacific Controls Software Services LLC (PCSS). All Rights Reserved. * * This software is the property of Pacific Controls Software Services LLC and its * suppliers. The intellectual and technical concepts contained herein are proprietary * to PCSS. Dissemination of this information or reproduction of this material is * strictly forbidden unless prior written permission is obtained from Pacific * Controls Software Services. * * PCSS MAKES NO REPRESENTATION OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTANILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGMENT. PCSS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ /** * Version : 1.0 * User : pcseg306 * Function : Service for Super/client Admin Notification Functions */ gxMainApp.factory("adminFunctionsService", function($http,$rootScope,gxAPIServiceWrapper){ var _notificationArray = []; var _resultPromise; var _getNotificationArray = function() { _resultPromise = gxAPIServiceWrapper.get("models/superAdmin/dummySuperAdminNotification.json"); console.log(_resultPromise); return _resultPromise; } return{ notificationArray: _notificationArray, getNotificationArray: _getNotificationArray, resultPromise : _resultPromise }; });
dddomin3/angular-galaxy
services/adminNotification/adminNotificationDataService.js
JavaScript
mit
1,524
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com from thumbor.loaders import http_loader from tornado.concurrent import return_future from urllib import unquote def _normalize_url(url): url = http_loader.quote_url(unquote(url)) if url.startswith('http:'): url = url.replace('http:', 'https:', 1) return url if url.startswith('https://') else 'https://%s' % url def validate(context, url): if url.startswith('http://'): return False return http_loader.validate(context, url, normalize_url_func=_normalize_url) def return_contents(response, url, callback, context): return http_loader.return_contents(response, url, callback, context) @return_future def load(context, url, callback): return http_loader.load_sync(context, url, callback, normalize_url_func=_normalize_url) def encode(string): return http_loader.encode(string)
jdunaravich/thumbor
thumbor/loaders/strict_https_loader.py
Python
mit
1,086
<?php class device extends CI_Controller{ public function add_device(){ $this->load->model('device_model'); $device_name = $this->input->post('device_name'); $device_id = $this->input->post('device_id'); $about_device = $this->input->post('about_device'); $key = $this->session->userdata('id'); //later stages will take users key $passcode = rand($key,$key+10000); $data = array( 'device_name' => $device_name, 'device_id' => $device_id, 'about_device' => $about_device, 'key' => $key, 'passcode' => $passcode ); $this->device_model->add_device($data); $this->session->set_userdata('passcode', $passcode); redirect('user/device'); } public function edit_device($id){ $this->load->model('device_model'); $device_name = $this->input->post('device_name'); $device_id = $this->input->post('device_id'); $about_device = $this->input->post('about_device'); $key = $this->session->userdata('id');; //later stages will take users key $data = array( 'device_name' => $device_name, 'device_id' => $device_id, 'about_device' => $about_device, 'key' => $key ); $this->device_model->edit_device($id,$data); redirect('user/device'); } public function delete_device($id){ $this->load->model('device_model'); $this->device_model->delete_device($id); redirect('user/device'); } public function add_parameters($device_id){ $parameters = $this->input->post("parameter_name[]"); $this->load->model('device_model'); foreach ($parameters as $parameter_name) { $data = [ 'parameter_name' => $parameter_name, 'device_id' => $device_id ]; $this->device_model->add_parameter($data); } redirect("user/device"); } public function update_parameter(){ $this->load->model('device_model'); $parameter_names = $this->input->post('parameter_name[]'); $parameter_ids = $this->input->post('parameter_id[]'); $count = 0; foreach ($parameter_names as $parameter_name){ $id = $parameter_ids[$count]; $data = array('parameter_name' => $parameter_name); $this->device_model->edit_parameter($id,$data); $count = $count + 1; } redirect('user/device'); } } ?>
Chaitya62/IOT-Bridge-Final-name-not-comfirmed
application/controllers/device.php
PHP
mit
2,164
define(function(require) { var test = require('../../../test') var count = 0 require.async('./a', function(a) { test.assert(a.name === 'a', 'load CMD module file') done() }) require.async('./b.js', function() { test.assert(global.SPECS_MODULES_ASYNC === true, 'load normal script file') global.SPECS_MODULES_ASYNC = undefined done() }) require.async(['./c1', './c2'], function(c1, c2) { test.assert(c1.name === 'c1', c1.name) test.assert(c2.name === 'c2', c2.name) done() }) function done() { if (++count === 3) { test.next() } } });
007slm/seajs
tests/specs/module/require-async/main.js
JavaScript
mit
609
namespace AbpKendoDemo.Migrations { using System; using System.Data.Entity.Migrations; public partial class Upgrade_Abp_And_Module_Zero_To_0_8_1 : DbMigration { public override void Up() { CreateTable( "dbo.AbpBackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512), JobArgs = c.String(nullable: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false), LastTryTime = c.DateTime(), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.AbpNotifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 128), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 256), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 128), Severity = c.Byte(nullable: false), UserIds = c.String(), ExcludedUserIds = c.String(), TenantIds = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 128), EntityTypeName = c.String(maxLength: 256), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 128), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), UserId = c.Long(nullable: false), NotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); } public override void Down() { DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.AbpUserNotifications"); DropTable("dbo.AbpNotificationSubscriptions"); DropTable("dbo.AbpNotifications"); DropTable("dbo.AbpBackgroundJobs"); } } }
s-takatsu/aspnetboilerplate-samples
KendoUiDemo/src/AbpKendoDemo.EntityFramework/Migrations/201602161446590_Upgrade_Abp_And_Module_Zero_To_0_8_1.cs
C#
mit
4,104
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.advisor.v2017_04_19; import com.microsoft.azure.arm.collection.SupportsCreating; import rx.Completable; import rx.Observable; import com.microsoft.azure.management.advisor.v2017_04_19.implementation.SuppressionsInner; import com.microsoft.azure.arm.model.HasInner; /** * Type representing Suppressions. */ public interface Suppressions extends SupportsCreating<SuppressionContract.DefinitionStages.Blank>, HasInner<SuppressionsInner> { /** * Retrieves the list of snoozed or dismissed suppressions for a subscription. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Observable<SuppressionContract> listAsync(); /** * Obtains the details of a suppression. * * @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. * @param recommendationId The recommendation ID. * @param name The name of the suppression. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Observable<SuppressionContract> getAsync(String resourceUri, String recommendationId, String name); /** * Enables the activation of a snoozed or dismissed recommendation. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. * * @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. * @param recommendationId The recommendation ID. * @param name The name of the suppression. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Completable deleteAsync(String resourceUri, String recommendationId, String name); }
selvasingh/azure-sdk-for-java
sdk/advisor/mgmt-v2017_04_19/src/main/java/com/microsoft/azure/management/advisor/v2017_04_19/Suppressions.java
Java
mit
2,252
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Serialization; using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Fungus { /** * Visual scripting controller for the Flowchart programming language. * Flowchart objects may be edited visually using the Flowchart editor window. */ [ExecuteInEditMode] public class Flowchart : MonoBehaviour { /** * Current version used to compare with the previous version so older versions can be custom-updated from previous versions. */ public const string CURRENT_VERSION = "1.0"; /** * The name of the initial block in a new flowchart. */ public const string DEFAULT_BLOCK_NAME = "New Block"; /** * Variable to track flowchart's version and if initial set up has completed. */ [HideInInspector] public string version; /** * Scroll position of Flowchart editor window. */ [HideInInspector] public Vector2 scrollPos; /** * Scroll position of Flowchart variables window. */ [HideInInspector] public Vector2 variablesScrollPos; /** * Show the variables pane. */ [HideInInspector] public bool variablesExpanded = true; /** * Height of command block view in inspector. */ [HideInInspector] public float blockViewHeight = 400; /** * Zoom level of Flowchart editor window */ [HideInInspector] public float zoom = 1f; /** * Scrollable area for Flowchart editor window. */ [HideInInspector] public Rect scrollViewRect; /** * Currently selected block in the Flowchart editor. */ [HideInInspector] [FormerlySerializedAs("selectedSequence")] public Block selectedBlock; /** * Currently selected command in the Flowchart editor. */ [HideInInspector] public List<Command> selectedCommands = new List<Command>(); /** * The list of variables that can be accessed by the Flowchart. */ [HideInInspector] public List<Variable> variables = new List<Variable>(); [TextArea(3, 5)] [Tooltip("Description text displayed in the Flowchart editor window")] public string description = ""; /** * Slow down execution in the editor to make it easier to visualise program flow. */ [Range(0f, 5f)] [Tooltip("Adds a pause after each execution step to make it easier to visualise program flow. Editor only, has no effect in platform builds.")] public float stepPause = 0f; /** * Use command color when displaying the command list in the inspector. */ [Tooltip("Use command color when displaying the command list in the Fungus Editor window")] public bool colorCommands = true; /** * Hides the Flowchart block and command components in the inspector. * Deselect to inspect the block and command components that make up the Flowchart. */ [Tooltip("Hides the Flowchart block and command components in the inspector")] public bool hideComponents = true; /** * Saves the selected block and commands when saving the scene. * Helps avoid version control conflicts if you've only changed the active selection. */ [Tooltip("Saves the selected block and commands when saving the scene.")] public bool saveSelection = true; /** * Unique identifier for identifying this flowchart in localized string keys. */ [Tooltip("Unique identifier for this flowchart in localized string keys. If no id is specified then the name of the Flowchart object will be used.")] public string localizationId = ""; /** * Cached list of flowchart objects in the scene for fast lookup */ public static List<Flowchart> cachedFlowcharts = new List<Flowchart>(); protected static bool eventSystemPresent; /** * Returns the next id to assign to a new flowchart item. * Item ids increase monotically so they are guaranteed to * be unique within a Flowchart. */ public int NextItemId() { int maxId = -1; Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { maxId = Math.Max(maxId, block.itemId); } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { maxId = Math.Max(maxId, command.itemId); } return maxId + 1; } protected virtual void OnLevelWasLoaded(int level) { // Reset the flag for checking for an event system as there may not be one in the newly loaded scene. eventSystemPresent = false; } protected virtual void Start() { CheckEventSystem(); } // There must be an Event System in the scene for Say and Menu input to work. // This method will automatically instantiate one if none exists. protected virtual void CheckEventSystem() { if (eventSystemPresent) { return; } EventSystem eventSystem = GameObject.FindObjectOfType<EventSystem>(); if (eventSystem == null) { // Auto spawn an Event System from the prefab GameObject prefab = Resources.Load<GameObject>("EventSystem"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.name = "EventSystem"; } } eventSystemPresent = true; } public virtual void OnEnable() { if (!cachedFlowcharts.Contains(this)) { cachedFlowcharts.Add(this); } CheckItemIds(); CleanupComponents(); UpdateVersion(); } public virtual void OnDisable() { cachedFlowcharts.Remove(this); } protected virtual void CheckItemIds() { // Make sure item ids are unique and monotonically increasing. // This should always be the case, but some legacy Flowcharts may have issues. List<int> usedIds = new List<int>(); Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.itemId == -1 || usedIds.Contains(block.itemId)) { block.itemId = NextItemId(); } usedIds.Add(block.itemId); } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { if (command.itemId == -1 || usedIds.Contains(command.itemId)) { command.itemId = NextItemId(); } usedIds.Add(command.itemId); } } protected virtual void CleanupComponents() { // Delete any unreferenced components which shouldn't exist any more // Unreferenced components don't have any effect on the flowchart behavior, but // they waste memory so should be cleared out periodically. Block[] blocks = GetComponentsInChildren<Block>(); foreach (Variable variable in GetComponents<Variable>()) { if (!variables.Contains(variable)) { DestroyImmediate(variable); } } foreach (Command command in GetComponents<Command>()) { bool found = false; foreach (Block block in blocks) { if (block.commandList.Contains(command)) { found = true; break; } } if (!found) { DestroyImmediate(command); } } foreach (EventHandler eventHandler in GetComponents<EventHandler>()) { bool found = false; foreach (Block block in blocks) { if (block.eventHandler == eventHandler) { found = true; break; } } if (!found) { DestroyImmediate(eventHandler); } } } private void UpdateVersion() { // If versions match, then we are already using the latest. if (version == CURRENT_VERSION) return; switch (version) { // Version never set, so we are initializing on first creation or this flowchart is pre-versioning. case null: case "": Initialize(); break; } version = CURRENT_VERSION; } protected virtual void Initialize() { // If there are other flowcharts in the scene and the selected block has the default name, then this is probably a new block. // Reset the event handler of the new flowchart's default block to avoid crashes. if (selectedBlock && cachedFlowcharts.Count > 1 && selectedBlock.blockName == DEFAULT_BLOCK_NAME) { selectedBlock.eventHandler = null; } } protected virtual Block CreateBlockComponent(GameObject parent) { Block block = parent.AddComponent<Block>(); return block; } /** * Create a new block node which you can then add commands to. */ public virtual Block CreateBlock(Vector2 position) { Block b = CreateBlockComponent(gameObject); b.nodeRect.x = position.x; b.nodeRect.y = position.y; b.blockName = GetUniqueBlockKey(b.blockName, b); b.itemId = NextItemId(); return b; } /** * Returns the named Block in the flowchart, or null if not found. */ public virtual Block FindBlock(string blockName) { Block [] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.blockName == blockName) { return block; } } return null; } /** * Start running another Flowchart by executing a specific child block. * The block must be in an idle state to be executed. * You can use this method in a UI event. e.g. to handle a button click. */ public virtual void ExecuteBlock(string blockName) { Block [] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.blockName == blockName) { ExecuteBlock(block); } } } /** * Sends a message to this Flowchart only. * Any block with a matching MessageReceived event handler will start executing. */ public virtual void SendFungusMessage(string messageName) { MessageReceived[] eventHandlers = GetComponentsInChildren<MessageReceived>(); foreach (MessageReceived eventHandler in eventHandlers) { eventHandler.OnSendFungusMessage(messageName); } } /** * Sends a message to all Flowchart objects in the current scene. * Any block with a matching MessageReceived event handler will start executing. */ public static void BroadcastFungusMessage(string messageName) { MessageReceived[] eventHandlers = GameObject.FindObjectsOfType<MessageReceived>(); foreach (MessageReceived eventHandler in eventHandlers) { eventHandler.OnSendFungusMessage(messageName); } } /** * Start executing a specific child block in the flowchart. * The block must be in an idle state to be executed. * Returns true if the Block started execution. */ public virtual bool ExecuteBlock(Block block, Action onComplete = null) { // Block must be a component of the Flowchart game object if (block == null || block.gameObject != gameObject) { return false; } // Can't restart a running block, have to wait until it's idle again if (block.IsExecuting()) { return false; } // Execute the first command in the command list block.Execute(onComplete); return true; } /** * Returns a new variable key that is guaranteed not to clash with any existing variable in the list. */ public virtual string GetUniqueVariableKey(string originalKey, Variable ignoreVariable = null) { int suffix = 0; string baseKey = originalKey; // Only letters and digits allowed char[] arr = baseKey.Where(c => (char.IsLetterOrDigit(c) || c == '_')).ToArray(); baseKey = new string(arr); // No leading digits allowed baseKey = baseKey.TrimStart('0','1','2','3','4','5','6','7','8','9'); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "Var"; } string key = baseKey; while (true) { bool collision = false; foreach(Variable variable in variables) { if (variable == null || variable == ignoreVariable || variable.key == null) { continue; } if (variable.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns a new Block key that is guaranteed not to clash with any existing Block in the Flowchart. */ public virtual string GetUniqueBlockKey(string originalKey, Block ignoreBlock = null) { int suffix = 0; string baseKey = originalKey.Trim(); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "New Block"; } Block[] blocks = GetComponentsInChildren<Block>(); string key = baseKey; while (true) { bool collision = false; foreach(Block block in blocks) { if (block == ignoreBlock || block.blockName == null) { continue; } if (block.blockName.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns a new Label key that is guaranteed not to clash with any existing Label in the Block. */ public virtual string GetUniqueLabelKey(string originalKey, Label ignoreLabel) { int suffix = 0; string baseKey = originalKey.Trim(); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "New Label"; } Block block = ignoreLabel.parentBlock; string key = baseKey; while (true) { bool collision = false; foreach(Command command in block.commandList) { Label label = command as Label; if (label == null || label == ignoreLabel) { continue; } if (label.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns the variable with the specified key, or null if the key is not found. * You can then access the variable's value using the Value property. e.g. * BooleanVariable boolVar = flowchart.GetVariable<BooleanVariable>("MyBool"); * boolVar.Value = false; */ public T GetVariable<T>(string key) where T : Variable { foreach (Variable variable in variables) { if (variable.key == key) { return variable as T; } } return null; } /** * Gets a list of all variables with public scope in this Flowchart. */ public virtual List<Variable> GetPublicVariables() { List<Variable> publicVariables = new List<Variable>(); foreach (Variable v in variables) { if (v.scope == VariableScope.Public) { publicVariables.Add(v); } } return publicVariables; } /** * Gets the value of a boolean variable. * Returns false if the variable key does not exist. */ public virtual bool GetBooleanVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { BooleanVariable variable = v as BooleanVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Boolean variable " + key + " not found."); return false; } /** * Sets the value of a boolean variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetBooleanVariable(string key, bool value) { foreach (Variable v in variables) { if (v.key == key) { BooleanVariable variable = v as BooleanVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Boolean variable " + key + " not found."); } /** * Gets the value of an integer variable. * Returns 0 if the variable key does not exist. */ public virtual int GetIntegerVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { IntegerVariable variable = v as IntegerVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Integer variable " + key + " not found."); return 0; } /** * Sets the value of an integer variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetIntegerVariable(string key, int value) { foreach (Variable v in variables) { if (v.key == key) { IntegerVariable variable = v as IntegerVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Integer variable " + key + " not found."); } /** * Gets the value of a float variable. * Returns 0 if the variable key does not exist. */ public virtual float GetFloatVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { FloatVariable variable = v as FloatVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Float variable " + key + " not found."); return 0f; } /** * Sets the value of a float variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetFloatVariable(string key, float value) { foreach (Variable v in variables) { if (v.key == key) { FloatVariable variable = v as FloatVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Float variable " + key + " not found."); } /** * Gets the value of a string variable. * Returns the empty string if the variable key does not exist. */ public virtual string GetStringVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { StringVariable variable = v as StringVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("String variable " + key + " not found."); return ""; } /** * Sets the value of a string variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetStringVariable(string key, string value) { foreach (Variable v in variables) { if (v.key == key) { StringVariable variable = v as StringVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("String variable " + key + " not found."); } /** * Set the block objects to be hidden or visible depending on the hideComponents property. */ public virtual void UpdateHideFlags() { if (hideComponents) { Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { block.hideFlags = HideFlags.HideInInspector; if (block.gameObject != gameObject) { block.gameObject.hideFlags = HideFlags.HideInHierarchy; } } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { command.hideFlags = HideFlags.HideInInspector; } EventHandler[] eventHandlers = GetComponentsInChildren<EventHandler>(); foreach (EventHandler eventHandler in eventHandlers) { eventHandler.hideFlags = HideFlags.HideInInspector; } } else { MonoBehaviour[] monoBehaviours = GetComponentsInChildren<MonoBehaviour>(); foreach (MonoBehaviour monoBehaviour in monoBehaviours) { if (monoBehaviour == null) { continue; } monoBehaviour.hideFlags = HideFlags.None; monoBehaviour.gameObject.hideFlags = HideFlags.None; } } } public virtual void ClearSelectedCommands() { selectedCommands.Clear(); } public virtual void AddSelectedCommand(Command command) { if (!selectedCommands.Contains(command)) { selectedCommands.Add(command); } } public virtual void Reset(bool resetCommands, bool resetVariables) { if (resetCommands) { Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { command.OnReset(); } } if (resetVariables) { foreach (Variable variable in variables) { variable.OnReset(); } } } public virtual string SubstituteVariables(string text) { string subbedText = text; // Instantiate the regular expression object. Regex r = new Regex("{\\$.*?}"); // Match the regular expression pattern against a text string. var results = r.Matches(text); foreach (Match match in results) { string key = match.Value.Substring(2, match.Value.Length - 3); // Look for any matching variables in this Flowchart first (public or private) foreach (Variable variable in variables) { if (variable.key == key) { string value = variable.ToString(); subbedText = subbedText.Replace(match.Value, value); } } // Now search all public variables in all scene Flowcharts in the scene foreach (Flowchart flowchart in cachedFlowcharts) { if (flowchart == this) { // We've already searched this flowchart continue; } foreach (Variable variable in flowchart.variables) { if (variable.scope == VariableScope.Public && variable.key == key) { string value = variable.ToString(); subbedText = subbedText.Replace(match.Value, value); } } } // Next look for matching localized string string localizedString = Localization.GetLocalizedString(key); if (localizedString != null) { subbedText = subbedText.Replace(match.Value, localizedString); } } return subbedText; } } }
tapiralec/Fungus
Assets/Fungus/Flowchart/Scripts/Flowchart.cs
C#
mit
21,856
// Copyright 2016 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package gitutil import ( "html/template" "testing" dmp "github.com/sergi/go-diff/diffmatchpatch" "github.com/stretchr/testify/assert" "github.com/gogs/git-module" ) func Test_diffsToHTML(t *testing.T) { tests := []struct { diffs []dmp.Diff lineType git.DiffLineType expHTML template.HTML }{ { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffInsert, Text: "bar"}, {Type: dmp.DiffDelete, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineAdd, expHTML: template.HTML(`+foo <span class="added-code">bar</span> biz`), }, { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffDelete, Text: "bar"}, {Type: dmp.DiffInsert, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineDelete, expHTML: template.HTML(`-foo <span class="removed-code">bar</span> biz`), }, } for _, test := range tests { t.Run("", func(t *testing.T) { assert.Equal(t, test.expHTML, diffsToHTML(test.diffs, test.lineType)) }) } }
gogits/gogs
internal/gitutil/diff_test.go
GO
mit
1,244
<?php include 'Vehicle.php'; include 'Car.php'; $car = new Car(4, 'Red', 'Audi', 'A4', 2016); print_r($car); echo "<br>"; $car->setColor('Green'); print_r($car);
stoyantodorovbg/PHP-Web-Development-Basics
Lab OOP Encapsulation and Inheritance/problem6/index.php
PHP
mit
166
#ifdef HAVE_WINRT #define ICustomStreamSink StreamSink #ifndef __cplusplus_winrt #define __is_winrt_array(type) (type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt8Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_Int16Array ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt16Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_Int32Array ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt32Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_Int64Array ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt64Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_SingleArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_DoubleArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_Char16Array ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_BooleanArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_StringArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_InspectableArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_DateTimeArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_TimeSpanArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_GuidArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_PointArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_SizeArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_RectArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_OtherTypeArray) template<typename _Type, bool bUnknown = std::is_base_of<IUnknown, _Type>::value> struct winrt_type { }; template<typename _Type> struct winrt_type<_Type, true> { static IUnknown* create(_Type* _ObjInCtx) { return reinterpret_cast<IUnknown*>(_ObjInCtx); } static IID getuuid() { return __uuidof(_Type); } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_OtherType; }; template <typename _Type> struct winrt_type<_Type, false> { static IUnknown* create(_Type* _ObjInCtx) { Microsoft::WRL::ComPtr<IInspectable> _PObj; Microsoft::WRL::ComPtr<IActivationFactory> objFactory; HRESULT hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Foundation_PropertyValue).Get(), objFactory.ReleaseAndGetAddressOf()); if (FAILED(hr)) return nullptr; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValueStatics> spPropVal; if (SUCCEEDED(hr)) hr = objFactory.As(&spPropVal); if (SUCCEEDED(hr)) { hr = winrt_type<_Type>::create(spPropVal.Get(), _ObjInCtx, _PObj.GetAddressOf()); if (SUCCEEDED(hr)) return reinterpret_cast<IUnknown*>(_PObj.Detach()); } return nullptr; } static IID getuuid() { return __uuidof(ABI::Windows::Foundation::IPropertyValue); } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_OtherType; }; template<> struct winrt_type<void> { static HRESULT create(ABI::Windows::Foundation::IPropertyValueStatics* spPropVal, void* _ObjInCtx, IInspectable** ppInsp) { (void)_ObjInCtx; return spPropVal->CreateEmpty(ppInsp); } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_Empty; }; #define MAKE_TYPE(Type, Name) template<>\ struct winrt_type<Type>\ {\ static HRESULT create(ABI::Windows::Foundation::IPropertyValueStatics* spPropVal, Type* _ObjInCtx, IInspectable** ppInsp) {\ return spPropVal->Create##Name(*_ObjInCtx, ppInsp);\ }\ static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_##Name;\ }; template<typename _Type> struct winrt_array_type { static IUnknown* create(_Type* _ObjInCtx, size_t N) { Microsoft::WRL::ComPtr<IInspectable> _PObj; Microsoft::WRL::ComPtr<IActivationFactory> objFactory; HRESULT hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Foundation_PropertyValue).Get(), objFactory.ReleaseAndGetAddressOf()); if (FAILED(hr)) return nullptr; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValueStatics> spPropVal; if (SUCCEEDED(hr)) hr = objFactory.As(&spPropVal); if (SUCCEEDED(hr)) { hr = winrt_array_type<_Type>::create(spPropVal.Get(), N, _ObjInCtx, _PObj.GetAddressOf()); if (SUCCEEDED(hr)) return reinterpret_cast<IUnknown*>(_PObj.Detach()); } return nullptr; } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_OtherTypeArray; }; template<int> struct winrt_prop_type {}; template <> struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_Empty> { typedef void _Type; }; template <> struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_OtherType> { typedef void _Type; }; template <> struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_OtherTypeArray> { typedef void _Type; }; #define MAKE_PROP(Prop, Type) template <>\ struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_##Prop> {\ typedef Type _Type;\ }; #define MAKE_ARRAY_TYPE(Type, Name) MAKE_PROP(Name, Type)\ MAKE_PROP(Name##Array, Type*)\ MAKE_TYPE(Type, Name)\ template<>\ struct winrt_array_type<Type*>\ {\ static HRESULT create(ABI::Windows::Foundation::IPropertyValueStatics* spPropVal, UINT32 __valueSize, Type** _ObjInCtx, IInspectable** ppInsp) {\ return spPropVal->Create##Name##Array(__valueSize, *_ObjInCtx, ppInsp);\ }\ static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_##Name##Array;\ static std::vector<Type> PropertyValueToVector(ABI::Windows::Foundation::IPropertyValue* propValue)\ {\ UINT32 uLen = 0;\ Type* pArray = nullptr;\ propValue->Get##Name##Array(&uLen, &pArray);\ return std::vector<Type>(pArray, pArray + uLen);\ }\ }; MAKE_ARRAY_TYPE(BYTE, UInt8) MAKE_ARRAY_TYPE(INT16, Int16) MAKE_ARRAY_TYPE(UINT16, UInt16) MAKE_ARRAY_TYPE(INT32, Int32) MAKE_ARRAY_TYPE(UINT32, UInt32) MAKE_ARRAY_TYPE(INT64, Int64) MAKE_ARRAY_TYPE(UINT64, UInt64) MAKE_ARRAY_TYPE(FLOAT, Single) MAKE_ARRAY_TYPE(DOUBLE, Double) MAKE_ARRAY_TYPE(WCHAR, Char16) //MAKE_ARRAY_TYPE(boolean, Boolean) //conflict with identical type in C++ of BYTE/UInt8 MAKE_ARRAY_TYPE(HSTRING, String) MAKE_ARRAY_TYPE(IInspectable*, Inspectable) MAKE_ARRAY_TYPE(GUID, Guid) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::DateTime, DateTime) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::TimeSpan, TimeSpan) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Point, Point) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Size, Size) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Rect, Rect) template < typename T > struct DerefHelper { typedef T DerefType; }; template < typename T > struct DerefHelper<T*> { typedef T DerefType; }; #define __is_valid_winrt_type(_Type) (std::is_void<_Type>::value || \ std::is_same<_Type, BYTE>::value || \ std::is_same<_Type, INT16>::value || \ std::is_same<_Type, UINT16>::value || \ std::is_same<_Type, INT32>::value || \ std::is_same<_Type, UINT32>::value || \ std::is_same<_Type, INT64>::value || \ std::is_same<_Type, UINT64>::value || \ std::is_same<_Type, FLOAT>::value || \ std::is_same<_Type, DOUBLE>::value || \ std::is_same<_Type, WCHAR>::value || \ std::is_same<_Type, boolean>::value || \ std::is_same<_Type, HSTRING>::value || \ std::is_same<_Type, IInspectable *>::value || \ std::is_base_of<Microsoft::WRL::Details::RuntimeClassBase, _Type>::value || \ std::is_base_of<IInspectable, typename DerefHelper<_Type>::DerefType>::value || \ std::is_same<_Type, GUID>::value || \ std::is_same<_Type, ABI::Windows::Foundation::DateTime>::value || \ std::is_same<_Type, ABI::Windows::Foundation::TimeSpan>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Point>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Size>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Rect>::value || \ std::is_same<_Type, BYTE*>::value || \ std::is_same<_Type, INT16*>::value || \ std::is_same<_Type, UINT16*>::value || \ std::is_same<_Type, INT32*>::value || \ std::is_same<_Type, UINT32*>::value || \ std::is_same<_Type, INT64*>::value || \ std::is_same<_Type, UINT64*>::value || \ std::is_same<_Type, FLOAT*>::value || \ std::is_same<_Type, DOUBLE*>::value || \ std::is_same<_Type, WCHAR*>::value || \ std::is_same<_Type, boolean*>::value || \ std::is_same<_Type, HSTRING*>::value || \ std::is_same<_Type, IInspectable **>::value || \ std::is_same<_Type, GUID*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::DateTime*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::TimeSpan*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Point*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Size*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Rect*>::value) #endif #else EXTERN_C const IID IID_ICustomStreamSink; class DECLSPEC_UUID("4F8A1939-2FD3-46DB-AE70-DB7E0DD79B73") DECLSPEC_NOVTABLE ICustomStreamSink : public IUnknown { public: virtual HRESULT Initialize() = 0; virtual HRESULT Shutdown() = 0; virtual HRESULT Start(MFTIME start) = 0; virtual HRESULT Pause() = 0; virtual HRESULT Restart() = 0; virtual HRESULT Stop() = 0; }; #endif #define MF_PROP_SAMPLEGRABBERCALLBACK L"samplegrabbercallback" #define MF_PROP_VIDTYPE L"vidtype" #define MF_PROP_VIDENCPROPS L"videncprops" #include <initguid.h> // MF_MEDIASINK_SAMPLEGRABBERCALLBACK: {26957AA7-AFF4-464c-BB8B-07BA65CE11DF} // Type: IUnknown* DEFINE_GUID(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, 0x26957aa7, 0xaff4, 0x464c, 0xbb, 0x8b, 0x7, 0xba, 0x65, 0xce, 0x11, 0xdf); // {4BD133CC-EB9B-496E-8865-0813BFBC6FAA} DEFINE_GUID(MF_STREAMSINK_ID, 0x4bd133cc, 0xeb9b, 0x496e, 0x88, 0x65, 0x8, 0x13, 0xbf, 0xbc, 0x6f, 0xaa); // {C9E22A8C-6A50-4D78-9183-0834A02A3780} DEFINE_GUID(MF_STREAMSINK_MEDIASINKINTERFACE, 0xc9e22a8c, 0x6a50, 0x4d78, 0x91, 0x83, 0x8, 0x34, 0xa0, 0x2a, 0x37, 0x80); // {DABD13AB-26B7-47C2-97C1-4B04C187B838} DEFINE_GUID(MF_MEDIASINK_PREFERREDTYPE, 0xdabd13ab, 0x26b7, 0x47c2, 0x97, 0xc1, 0x4b, 0x4, 0xc1, 0x87, 0xb8, 0x38); #include <utility> #ifdef _UNICODE #define MAKE_MAP(e) std::map<e, std::wstring> #define MAKE_ENUM(e) std::pair<e, std::wstring> #define MAKE_ENUM_PAIR(e, str) std::pair<e, std::wstring>(str, L#str) #else #define MAKE_MAP(e) std::map<e, std::string> #define MAKE_ENUM(e) std::pair<e, std::string> #define MAKE_ENUM_PAIR(e, str) std::pair<e, std::string>(str, #str) #endif MAKE_ENUM(MediaEventType) MediaEventTypePairs[] = { MAKE_ENUM_PAIR(MediaEventType, MEUnknown), MAKE_ENUM_PAIR(MediaEventType, MEError), MAKE_ENUM_PAIR(MediaEventType, MEExtendedType), MAKE_ENUM_PAIR(MediaEventType, MENonFatalError), MAKE_ENUM_PAIR(MediaEventType, MEGenericV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MESessionUnknown), MAKE_ENUM_PAIR(MediaEventType, MESessionTopologySet), MAKE_ENUM_PAIR(MediaEventType, MESessionTopologiesCleared), MAKE_ENUM_PAIR(MediaEventType, MESessionStarted), MAKE_ENUM_PAIR(MediaEventType, MESessionPaused), MAKE_ENUM_PAIR(MediaEventType, MESessionStopped), MAKE_ENUM_PAIR(MediaEventType, MESessionClosed), MAKE_ENUM_PAIR(MediaEventType, MESessionEnded), MAKE_ENUM_PAIR(MediaEventType, MESessionRateChanged), MAKE_ENUM_PAIR(MediaEventType, MESessionScrubSampleComplete), MAKE_ENUM_PAIR(MediaEventType, MESessionCapabilitiesChanged), MAKE_ENUM_PAIR(MediaEventType, MESessionTopologyStatus), MAKE_ENUM_PAIR(MediaEventType, MESessionNotifyPresentationTime), MAKE_ENUM_PAIR(MediaEventType, MENewPresentation), MAKE_ENUM_PAIR(MediaEventType, MELicenseAcquisitionStart), MAKE_ENUM_PAIR(MediaEventType, MELicenseAcquisitionCompleted), MAKE_ENUM_PAIR(MediaEventType, MEIndividualizationStart), MAKE_ENUM_PAIR(MediaEventType, MEIndividualizationCompleted), MAKE_ENUM_PAIR(MediaEventType, MEEnablerProgress), MAKE_ENUM_PAIR(MediaEventType, MEEnablerCompleted), MAKE_ENUM_PAIR(MediaEventType, MEPolicyError), MAKE_ENUM_PAIR(MediaEventType, MEPolicyReport), MAKE_ENUM_PAIR(MediaEventType, MEBufferingStarted), MAKE_ENUM_PAIR(MediaEventType, MEBufferingStopped), MAKE_ENUM_PAIR(MediaEventType, MEConnectStart), MAKE_ENUM_PAIR(MediaEventType, MEConnectEnd), MAKE_ENUM_PAIR(MediaEventType, MEReconnectStart), MAKE_ENUM_PAIR(MediaEventType, MEReconnectEnd), MAKE_ENUM_PAIR(MediaEventType, MERendererEvent), MAKE_ENUM_PAIR(MediaEventType, MESessionStreamSinkFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MESessionV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MESourceUnknown), MAKE_ENUM_PAIR(MediaEventType, MESourceStarted), MAKE_ENUM_PAIR(MediaEventType, MEStreamStarted), MAKE_ENUM_PAIR(MediaEventType, MESourceSeeked), MAKE_ENUM_PAIR(MediaEventType, MEStreamSeeked), MAKE_ENUM_PAIR(MediaEventType, MENewStream), MAKE_ENUM_PAIR(MediaEventType, MEUpdatedStream), MAKE_ENUM_PAIR(MediaEventType, MESourceStopped), MAKE_ENUM_PAIR(MediaEventType, MEStreamStopped), MAKE_ENUM_PAIR(MediaEventType, MESourcePaused), MAKE_ENUM_PAIR(MediaEventType, MEStreamPaused), MAKE_ENUM_PAIR(MediaEventType, MEEndOfPresentation), MAKE_ENUM_PAIR(MediaEventType, MEEndOfStream), MAKE_ENUM_PAIR(MediaEventType, MEMediaSample), MAKE_ENUM_PAIR(MediaEventType, MEStreamTick), MAKE_ENUM_PAIR(MediaEventType, MEStreamThinMode), MAKE_ENUM_PAIR(MediaEventType, MEStreamFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MESourceRateChanged), MAKE_ENUM_PAIR(MediaEventType, MEEndOfPresentationSegment), MAKE_ENUM_PAIR(MediaEventType, MESourceCharacteristicsChanged), MAKE_ENUM_PAIR(MediaEventType, MESourceRateChangeRequested), MAKE_ENUM_PAIR(MediaEventType, MESourceMetadataChanged), MAKE_ENUM_PAIR(MediaEventType, MESequencerSourceTopologyUpdated), MAKE_ENUM_PAIR(MediaEventType, MESourceV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MESinkUnknown), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStarted), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStopped), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkPaused), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkRateChanged), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkRequestSample), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkMarker), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkPrerolled), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkScrubSampleComplete), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkDeviceChanged), MAKE_ENUM_PAIR(MediaEventType, MEQualityNotify), MAKE_ENUM_PAIR(MediaEventType, MESinkInvalidated), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionNameChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionVolumeChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionDeviceRemoved), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionServerShutdown), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionGroupingParamChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionIconChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionDisconnected), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionExclusiveModeOverride), MAKE_ENUM_PAIR(MediaEventType, MESinkV1Anchor), #if (WINVER >= 0x0602) // Available since Win 8 MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionVolumeChanged), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionDeviceRemoved), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionDisconnected), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionExclusiveModeOverride), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionServerShutdown), MAKE_ENUM_PAIR(MediaEventType, MESinkV2Anchor), #endif MAKE_ENUM_PAIR(MediaEventType, METrustUnknown), MAKE_ENUM_PAIR(MediaEventType, MEPolicyChanged), MAKE_ENUM_PAIR(MediaEventType, MEContentProtectionMessage), MAKE_ENUM_PAIR(MediaEventType, MEPolicySet), MAKE_ENUM_PAIR(MediaEventType, METrustV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseBackupCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseBackupProgress), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseRestoreCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseRestoreProgress), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseAcquisitionCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMIndividualizationCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMIndividualizationProgress), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMProximityCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseStoreCleaned), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMRevocationDownloadCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMV1Anchor), MAKE_ENUM_PAIR(MediaEventType, METransformUnknown), MAKE_ENUM_PAIR(MediaEventType, METransformNeedInput), MAKE_ENUM_PAIR(MediaEventType, METransformHaveOutput), MAKE_ENUM_PAIR(MediaEventType, METransformDrainComplete), MAKE_ENUM_PAIR(MediaEventType, METransformMarker), #if (WINVER >= 0x0602) // Available since Win 8 MAKE_ENUM_PAIR(MediaEventType, MEByteStreamCharacteristicsChanged), MAKE_ENUM_PAIR(MediaEventType, MEVideoCaptureDeviceRemoved), MAKE_ENUM_PAIR(MediaEventType, MEVideoCaptureDevicePreempted), #endif MAKE_ENUM_PAIR(MediaEventType, MEReservedMax) }; MAKE_MAP(MediaEventType) MediaEventTypeMap(MediaEventTypePairs, MediaEventTypePairs + sizeof(MediaEventTypePairs) / sizeof(MediaEventTypePairs[0])); MAKE_ENUM(MFSTREAMSINK_MARKER_TYPE) StreamSinkMarkerTypePairs[] = { MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_DEFAULT), MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_ENDOFSEGMENT), MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_TICK), MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_EVENT) }; MAKE_MAP(MFSTREAMSINK_MARKER_TYPE) StreamSinkMarkerTypeMap(StreamSinkMarkerTypePairs, StreamSinkMarkerTypePairs + sizeof(StreamSinkMarkerTypePairs) / sizeof(StreamSinkMarkerTypePairs[0])); #ifdef HAVE_WINRT #ifdef __cplusplus_winrt #define _ContextCallback Concurrency::details::_ContextCallback #define BEGIN_CALL_IN_CONTEXT(hr, var, ...) hr = S_OK;\ var._CallInContext([__VA_ARGS__]() { #define END_CALL_IN_CONTEXT(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\ }); #define END_CALL_IN_CONTEXT_BASE }); #else #define _ContextCallback Concurrency_winrt::details::_ContextCallback #define BEGIN_CALL_IN_CONTEXT(hr, var, ...) hr = var._CallInContext([__VA_ARGS__]() -> HRESULT { #define END_CALL_IN_CONTEXT(hr) return hr;\ }); #define END_CALL_IN_CONTEXT_BASE return S_OK;\ }); #endif #define GET_CURRENT_CONTEXT _ContextCallback::_CaptureCurrent() #define SAVE_CURRENT_CONTEXT(var) _ContextCallback var = GET_CURRENT_CONTEXT #define COMMA , #ifdef __cplusplus_winrt #define _Object Platform::Object^ #define _ObjectObj Platform::Object^ #define _String Platform::String^ #define _StringObj Platform::String^ #define _StringReference ref new Platform::String #define _StringReferenceObj Platform::String^ #define _DeviceInformationCollection Windows::Devices::Enumeration::DeviceInformationCollection #define _MediaCapture Windows::Media::Capture::MediaCapture #define _MediaCaptureVideoPreview Windows::Media::Capture::MediaCapture #define _MediaCaptureInitializationSettings Windows::Media::Capture::MediaCaptureInitializationSettings #define _VideoDeviceController Windows::Media::Devices::VideoDeviceController #define _MediaDeviceController Windows::Media::Devices::VideoDeviceController #define _MediaEncodingProperties Windows::Media::MediaProperties::IMediaEncodingProperties #define _VideoEncodingProperties Windows::Media::MediaProperties::VideoEncodingProperties #define _MediaStreamType Windows::Media::Capture::MediaStreamType #define _AsyncInfo Windows::Foundation::IAsyncInfo #define _AsyncAction Windows::Foundation::IAsyncAction #define _AsyncOperation Windows::Foundation::IAsyncOperation #define _DeviceClass Windows::Devices::Enumeration::DeviceClass #define _IDeviceInformation Windows::Devices::Enumeration::DeviceInformation #define _DeviceInformation Windows::Devices::Enumeration::DeviceInformation #define _DeviceInformationStatics Windows::Devices::Enumeration::DeviceInformation #define _MediaEncodingProfile Windows::Media::MediaProperties::MediaEncodingProfile #define _StreamingCaptureMode Windows::Media::Capture::StreamingCaptureMode #define _PropertySet Windows::Foundation::Collections::PropertySet #define _Map Windows::Foundation::Collections::PropertySet #define _PropertyValueStatics Windows::Foundation::PropertyValue #define _VectorView Windows::Foundation::Collections::IVectorView #define _StartPreviewToCustomSinkIdAsync StartPreviewToCustomSinkAsync #define _InitializeWithSettingsAsync InitializeAsync #define _FindAllAsyncDeviceClass FindAllAsync #define _MediaExtension Windows::Media::IMediaExtension #define BEGIN_CREATE_ASYNC(type, ...) (Concurrency::create_async([__VA_ARGS__]() { #define END_CREATE_ASYNC(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\ })) #define DEFINE_TASK Concurrency::task #define CREATE_TASK Concurrency::create_task #define CREATE_OR_CONTINUE_TASK(_task, rettype, func) _task = (_task == Concurrency::task<rettype>()) ? Concurrency::create_task(func) : _task.then([func](rettype) -> rettype { return func(); }); #define CREATE_OR_CONTINUE_TASK_RET(_task, rettype, func) _task = (_task == Concurrency::task<rettype>()) ? Concurrency::create_task(func) : _task.then([func](rettype) -> rettype { return func(); }); #define DEFINE_RET_VAL(x) #define DEFINE_RET_TYPE(x) #define DEFINE_RET_FORMAL(x) x #define RET_VAL(x) return x; #define RET_VAL_BASE #define MAKE_STRING(str) str #define GET_STL_STRING(str) std::wstring(str->Data()) #define GET_STL_STRING_RAW(str) std::wstring(str->Data()) #define MAKE_WRL_OBJ(x) x^ #define MAKE_WRL_REF(x) x^ #define MAKE_OBJ_REF(x) x^ #define MAKE_WRL_AGILE_REF(x) Platform::Agile<x^> #define MAKE_WRL_AGILE_OBJ(x) Platform::Agile<x^> #define MAKE_PROPERTY_BACKING(Type, PropName) property Type PropName; #define MAKE_PROPERTY(Type, PropName, PropValue) #define MAKE_PROPERTY_STRING(Type, PropName, PropValue) #define MAKE_READONLY_PROPERTY(Type, PropName, PropValue) property Type PropName\ {\ Type get() { return PropValue; }\ } #define THROW_INVALID_ARG throw ref new Platform::InvalidArgumentException(); #define RELEASE_AGILE_WRL(x) x = nullptr; #define RELEASE_WRL(x) x = nullptr; #define GET_WRL_OBJ_FROM_REF(objtype, obj, orig, hr) objtype^ obj = orig;\ hr = S_OK; #define GET_WRL_OBJ_FROM_OBJ(objtype, obj, orig, hr) objtype^ obj = safe_cast<objtype^>(orig);\ hr = S_OK; #define WRL_ENUM_GET(obj, prefix, prop) obj::##prop #define WRL_PROP_GET(obj, prop, arg, hr) arg = obj->##prop;\ hr = S_OK; #define WRL_PROP_PUT(obj, prop, arg, hr) obj->##prop = arg;\ hr = S_OK; #define WRL_METHOD_BASE(obj, method, ret, hr) ret = obj->##method();\ hr = S_OK; #define WRL_METHOD(obj, method, ret, hr, ...) ret = obj->##method(__VA_ARGS__);\ hr = S_OK; #define WRL_METHOD_NORET_BASE(obj, method, hr) obj->##method();\ hr = S_OK; #define WRL_METHOD_NORET(obj, method, hr, ...) obj->##method(__VA_ARGS__);\ hr = S_OK; #define REF_WRL_OBJ(obj) &obj #define DEREF_WRL_OBJ(obj) obj #define DEREF_AGILE_WRL_MADE_OBJ(obj) obj.Get() #define DEREF_AGILE_WRL_OBJ(obj) obj.Get() #define DEREF_AS_NATIVE_WRL_OBJ(type, obj) reinterpret_cast<type*>(obj) #define PREPARE_TRANSFER_WRL_OBJ(obj) obj #define ACTIVATE_LOCAL_OBJ_BASE(objtype) ref new objtype() #define ACTIVATE_LOCAL_OBJ(objtype, ...) ref new objtype(__VA_ARGS__) #define ACTIVATE_EVENT_HANDLER(objtype, ...) ref new objtype(__VA_ARGS__) #define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj = ref new objtype();\ hr = S_OK; #define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\ hr = S_OK; #else #define _Object IInspectable* #define _ObjectObj Microsoft::WRL::ComPtr<IInspectable> #define _String HSTRING #define _StringObj Microsoft::WRL::Wrappers::HString #define _StringReference Microsoft::WRL::Wrappers::HStringReference #define _StringReferenceObj Microsoft::WRL::Wrappers::HStringReference #define _DeviceInformationCollection ABI::Windows::Devices::Enumeration::DeviceInformationCollection #define _MediaCapture ABI::Windows::Media::Capture::IMediaCapture #define _MediaCaptureVideoPreview ABI::Windows::Media::Capture::IMediaCaptureVideoPreview #define _MediaCaptureInitializationSettings ABI::Windows::Media::Capture::IMediaCaptureInitializationSettings #define _VideoDeviceController ABI::Windows::Media::Devices::IVideoDeviceController #define _MediaDeviceController ABI::Windows::Media::Devices::IMediaDeviceController #define _MediaEncodingProperties ABI::Windows::Media::MediaProperties::IMediaEncodingProperties #define _VideoEncodingProperties ABI::Windows::Media::MediaProperties::IVideoEncodingProperties #define _MediaStreamType ABI::Windows::Media::Capture::MediaStreamType #define _AsyncInfo ABI::Windows::Foundation::IAsyncInfo #define _AsyncAction ABI::Windows::Foundation::IAsyncAction #define _AsyncOperation ABI::Windows::Foundation::IAsyncOperation #define _DeviceClass ABI::Windows::Devices::Enumeration::DeviceClass #define _IDeviceInformation ABI::Windows::Devices::Enumeration::IDeviceInformation #define _DeviceInformation ABI::Windows::Devices::Enumeration::DeviceInformation #define _DeviceInformationStatics ABI::Windows::Devices::Enumeration::IDeviceInformationStatics #define _MediaEncodingProfile ABI::Windows::Media::MediaProperties::IMediaEncodingProfile #define _StreamingCaptureMode ABI::Windows::Media::Capture::StreamingCaptureMode #define _PropertySet ABI::Windows::Foundation::Collections::IPropertySet #define _Map ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *> #define _PropertyValueStatics ABI::Windows::Foundation::IPropertyValueStatics #define _VectorView ABI::Windows::Foundation::Collections::IVectorView #define _StartPreviewToCustomSinkIdAsync StartPreviewToCustomSinkIdAsync #define _InitializeWithSettingsAsync InitializeWithSettingsAsync #define _FindAllAsyncDeviceClass FindAllAsyncDeviceClass #define _MediaExtension ABI::Windows::Media::IMediaExtension #define BEGIN_CREATE_ASYNC(type, ...) Concurrency_winrt::create_async<type>([__VA_ARGS__]() -> HRESULT { #define END_CREATE_ASYNC(hr) return hr;\ }) #define DEFINE_TASK Concurrency_winrt::task #define CREATE_TASK Concurrency_winrt::create_task #define CREATE_OR_CONTINUE_TASK(_task, rettype, func) _task = (_task == Concurrency_winrt::task<rettype>()) ? Concurrency_winrt::create_task<rettype>(func) : _task.then(func); #define CREATE_OR_CONTINUE_TASK_RET(_task, rettype, func) _task = (_task == Concurrency_winrt::task<rettype>()) ? Concurrency_winrt::create_task<rettype>(func) : _task.then([func](rettype, rettype* retVal) -> HRESULT { return func(retVal); }); #define DEFINE_RET_VAL(x) x* retVal #define DEFINE_RET_TYPE(x) <x> #define DEFINE_RET_FORMAL(x) HRESULT #define RET_VAL(x) *retVal = x;\ return S_OK; #define RET_VAL_BASE return S_OK; #define MAKE_STRING(str) Microsoft::WRL::Wrappers::HStringReference(L##str) #define GET_STL_STRING(str) std::wstring(str.GetRawBuffer(NULL)) #define GET_STL_STRING_RAW(str) WindowsGetStringRawBuffer(str, NULL) #define MAKE_WRL_OBJ(x) Microsoft::WRL::ComPtr<x> #define MAKE_WRL_REF(x) x* #define MAKE_OBJ_REF(x) x #define MAKE_WRL_AGILE_REF(x) x* #define MAKE_WRL_AGILE_OBJ(x) Microsoft::WRL::ComPtr<x> #define MAKE_PROPERTY_BACKING(Type, PropName) Type PropName; #define MAKE_PROPERTY(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; }\ STDMETHODIMP put_##PropName(Type Val) { PropValue = Val; return S_OK; } #define MAKE_PROPERTY_STRING(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { return ::WindowsDuplicateString(PropValue.Get(), pVal); } else { return E_INVALIDARG; } }\ STDMETHODIMP put_##PropName(Type Val) { return PropValue.Set(Val); } #define MAKE_READONLY_PROPERTY(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; } #define THROW_INVALID_ARG RoOriginateError(E_INVALIDARG, nullptr); #define RELEASE_AGILE_WRL(x) if (x) { (x)->Release(); x = nullptr; } #define RELEASE_WRL(x) if (x) { (x)->Release(); x = nullptr; } #define GET_WRL_OBJ_FROM_REF(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\ hr = orig->QueryInterface(__uuidof(objtype), &obj); #define GET_WRL_OBJ_FROM_OBJ(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\ hr = orig.As(&obj); #define WRL_ENUM_GET(obj, prefix, prop) obj::prefix##_##prop #define WRL_PROP_GET(obj, prop, arg, hr) hr = obj->get_##prop(&arg); #define WRL_PROP_PUT(obj, prop, arg, hr) hr = obj->put_##prop(arg); #define WRL_METHOD_BASE(obj, method, ret, hr) hr = obj->##method(&ret); #define WRL_METHOD(obj, method, ret, hr, ...) hr = obj->##method(__VA_ARGS__, &ret); #define WRL_METHOD_NORET_BASE(obj, method, hr) hr = obj->##method(); #define REF_WRL_OBJ(obj) obj.GetAddressOf() #define DEREF_WRL_OBJ(obj) obj.Get() #define DEREF_AGILE_WRL_MADE_OBJ(obj) obj.Get() #define DEREF_AGILE_WRL_OBJ(obj) obj #define DEREF_AS_NATIVE_WRL_OBJ(type, obj) obj.Get() #define PREPARE_TRANSFER_WRL_OBJ(obj) obj.Detach() #define ACTIVATE_LOCAL_OBJ_BASE(objtype) Microsoft::WRL::Make<objtype>() #define ACTIVATE_LOCAL_OBJ(objtype, ...) Microsoft::WRL::Make<objtype>(__VA_ARGS__) #define ACTIVATE_EVENT_HANDLER(objtype, ...) Microsoft::WRL::Callback<objtype>(__VA_ARGS__).Get() #define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj;\ {\ Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\ hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.ReleaseAndGetAddressOf());\ if (SUCCEEDED(hr)) {\ Microsoft::WRL::ComPtr<IInspectable> pInsp;\ hr = objFactory->ActivateInstance(pInsp.GetAddressOf());\ if (SUCCEEDED(hr)) hr = pInsp.As(&obj);\ }\ } #define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\ {\ Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\ hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.ReleaseAndGetAddressOf());\ if (SUCCEEDED(hr)) {\ if (SUCCEEDED(hr)) hr = objFactory.As(&obj);\ }\ } #endif #define _ComPtr Microsoft::WRL::ComPtr #else #define _COM_SMARTPTR_DECLARE(T,var) T ## Ptr var template <class T> class ComPtr { public: ComPtr() throw() { } ComPtr(T* lp) throw() { p = lp; } ComPtr(_In_ const ComPtr<T>& lp) throw() { p = lp.p; } virtual ~ComPtr() { } T** operator&() throw() { assert(p == NULL); return p.operator&(); } T* operator->() const throw() { assert(p != NULL); return p.operator->(); } bool operator!() const throw() { return p.operator==(NULL); } bool operator==(_In_opt_ T* pT) const throw() { return p.operator==(pT); } bool operator!=(_In_opt_ T* pT) const throw() { return p.operator!=(pT); } operator bool() { return p.operator!=(NULL); } T* const* GetAddressOf() const throw() { return &p; } T** GetAddressOf() throw() { return &p; } T** ReleaseAndGetAddressOf() throw() { p.Release(); return &p; } T* Get() const throw() { return p; } // Attach to an existing interface (does not AddRef) void Attach(_In_opt_ T* p2) throw() { p.Attach(p2); } // Detach the interface (does not Release) T* Detach() throw() { return p.Detach(); } _Check_return_ HRESULT CopyTo(_Deref_out_opt_ T** ppT) throw() { assert(ppT != NULL); if (ppT == NULL) return E_POINTER; *ppT = p; if (p != NULL) p->AddRef(); return S_OK; } void Reset() { p.Release(); } // query for U interface template<typename U> HRESULT As(_Inout_ U** lp) const throw() { return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp)); } // query for U interface template<typename U> HRESULT As(_Out_ ComPtr<U>* lp) const throw() { return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp->ReleaseAndGetAddressOf())); } private: _COM_SMARTPTR_TYPEDEF(T, __uuidof(T)); _COM_SMARTPTR_DECLARE(T, p); }; #define _ComPtr ComPtr #endif template <class TBase=IMFAttributes> class CBaseAttributes : public TBase { protected: // This version of the constructor does not initialize the // attribute store. The derived class must call Initialize() in // its own constructor. CBaseAttributes() { } // This version of the constructor initializes the attribute // store, but the derived class must pass an HRESULT parameter // to the constructor. CBaseAttributes(HRESULT& hr, UINT32 cInitialSize = 0) { hr = Initialize(cInitialSize); } // The next version of the constructor uses a caller-provided // implementation of IMFAttributes. // (Sometimes you want to delegate IMFAttributes calls to some // other object that implements IMFAttributes, rather than using // MFCreateAttributes.) CBaseAttributes(HRESULT& hr, IUnknown *pUnk) { hr = Initialize(pUnk); } virtual ~CBaseAttributes() { } // Initializes the object by creating the standard Media Foundation attribute store. HRESULT Initialize(UINT32 cInitialSize = 0) { if (_spAttributes.Get() == nullptr) { return MFCreateAttributes(&_spAttributes, cInitialSize); } else { return S_OK; } } // Initializes this object from a caller-provided attribute store. // pUnk: Pointer to an object that exposes IMFAttributes. HRESULT Initialize(IUnknown *pUnk) { if (_spAttributes) { _spAttributes.Reset(); _spAttributes = nullptr; } return pUnk->QueryInterface(IID_PPV_ARGS(&_spAttributes)); } public: // IMFAttributes methods STDMETHODIMP GetItem(REFGUID guidKey, PROPVARIANT* pValue) { assert(_spAttributes); return _spAttributes->GetItem(guidKey, pValue); } STDMETHODIMP GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE* pType) { assert(_spAttributes); return _spAttributes->GetItemType(guidKey, pType); } STDMETHODIMP CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL* pbResult) { assert(_spAttributes); return _spAttributes->CompareItem(guidKey, Value, pbResult); } STDMETHODIMP Compare( IMFAttributes* pTheirs, MF_ATTRIBUTES_MATCH_TYPE MatchType, BOOL* pbResult ) { assert(_spAttributes); return _spAttributes->Compare(pTheirs, MatchType, pbResult); } STDMETHODIMP GetUINT32(REFGUID guidKey, UINT32* punValue) { assert(_spAttributes); return _spAttributes->GetUINT32(guidKey, punValue); } STDMETHODIMP GetUINT64(REFGUID guidKey, UINT64* punValue) { assert(_spAttributes); return _spAttributes->GetUINT64(guidKey, punValue); } STDMETHODIMP GetDouble(REFGUID guidKey, double* pfValue) { assert(_spAttributes); return _spAttributes->GetDouble(guidKey, pfValue); } STDMETHODIMP GetGUID(REFGUID guidKey, GUID* pguidValue) { assert(_spAttributes); return _spAttributes->GetGUID(guidKey, pguidValue); } STDMETHODIMP GetStringLength(REFGUID guidKey, UINT32* pcchLength) { assert(_spAttributes); return _spAttributes->GetStringLength(guidKey, pcchLength); } STDMETHODIMP GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32* pcchLength) { assert(_spAttributes); return _spAttributes->GetString(guidKey, pwszValue, cchBufSize, pcchLength); } STDMETHODIMP GetAllocatedString(REFGUID guidKey, LPWSTR* ppwszValue, UINT32* pcchLength) { assert(_spAttributes); return _spAttributes->GetAllocatedString(guidKey, ppwszValue, pcchLength); } STDMETHODIMP GetBlobSize(REFGUID guidKey, UINT32* pcbBlobSize) { assert(_spAttributes); return _spAttributes->GetBlobSize(guidKey, pcbBlobSize); } STDMETHODIMP GetBlob(REFGUID guidKey, UINT8* pBuf, UINT32 cbBufSize, UINT32* pcbBlobSize) { assert(_spAttributes); return _spAttributes->GetBlob(guidKey, pBuf, cbBufSize, pcbBlobSize); } STDMETHODIMP GetAllocatedBlob(REFGUID guidKey, UINT8** ppBuf, UINT32* pcbSize) { assert(_spAttributes); return _spAttributes->GetAllocatedBlob(guidKey, ppBuf, pcbSize); } STDMETHODIMP GetUnknown(REFGUID guidKey, REFIID riid, LPVOID* ppv) { assert(_spAttributes); return _spAttributes->GetUnknown(guidKey, riid, ppv); } STDMETHODIMP SetItem(REFGUID guidKey, REFPROPVARIANT Value) { assert(_spAttributes); return _spAttributes->SetItem(guidKey, Value); } STDMETHODIMP DeleteItem(REFGUID guidKey) { assert(_spAttributes); return _spAttributes->DeleteItem(guidKey); } STDMETHODIMP DeleteAllItems() { assert(_spAttributes); return _spAttributes->DeleteAllItems(); } STDMETHODIMP SetUINT32(REFGUID guidKey, UINT32 unValue) { assert(_spAttributes); return _spAttributes->SetUINT32(guidKey, unValue); } STDMETHODIMP SetUINT64(REFGUID guidKey,UINT64 unValue) { assert(_spAttributes); return _spAttributes->SetUINT64(guidKey, unValue); } STDMETHODIMP SetDouble(REFGUID guidKey, double fValue) { assert(_spAttributes); return _spAttributes->SetDouble(guidKey, fValue); } STDMETHODIMP SetGUID(REFGUID guidKey, REFGUID guidValue) { assert(_spAttributes); return _spAttributes->SetGUID(guidKey, guidValue); } STDMETHODIMP SetString(REFGUID guidKey, LPCWSTR wszValue) { assert(_spAttributes); return _spAttributes->SetString(guidKey, wszValue); } STDMETHODIMP SetBlob(REFGUID guidKey, const UINT8* pBuf, UINT32 cbBufSize) { assert(_spAttributes); return _spAttributes->SetBlob(guidKey, pBuf, cbBufSize); } STDMETHODIMP SetUnknown(REFGUID guidKey, IUnknown* pUnknown) { assert(_spAttributes); return _spAttributes->SetUnknown(guidKey, pUnknown); } STDMETHODIMP LockStore() { assert(_spAttributes); return _spAttributes->LockStore(); } STDMETHODIMP UnlockStore() { assert(_spAttributes); return _spAttributes->UnlockStore(); } STDMETHODIMP GetCount(UINT32* pcItems) { assert(_spAttributes); return _spAttributes->GetCount(pcItems); } STDMETHODIMP GetItemByIndex(UINT32 unIndex, GUID* pguidKey, PROPVARIANT* pValue) { assert(_spAttributes); return _spAttributes->GetItemByIndex(unIndex, pguidKey, pValue); } STDMETHODIMP CopyAllItems(IMFAttributes* pDest) { assert(_spAttributes); return _spAttributes->CopyAllItems(pDest); } // Helper functions HRESULT SerializeToStream(DWORD dwOptions, IStream* pStm) // dwOptions: Flags from MF_ATTRIBUTE_SERIALIZE_OPTIONS { assert(_spAttributes); return MFSerializeAttributesToStream(_spAttributes.Get(), dwOptions, pStm); } HRESULT DeserializeFromStream(DWORD dwOptions, IStream* pStm) { assert(_spAttributes); return MFDeserializeAttributesFromStream(_spAttributes.Get(), dwOptions, pStm); } // SerializeToBlob: Stores the attributes in a byte array. // // ppBuf: Receives a pointer to the byte array. // pcbSize: Receives the size of the byte array. // // The caller must free the array using CoTaskMemFree. HRESULT SerializeToBlob(UINT8 **ppBuffer, UINT *pcbSize) { assert(_spAttributes); if (ppBuffer == NULL) { return E_POINTER; } if (pcbSize == NULL) { return E_POINTER; } HRESULT hr = S_OK; UINT32 cbSize = 0; BYTE *pBuffer = NULL; CHECK_HR(hr = MFGetAttributesAsBlobSize(_spAttributes.Get(), &cbSize)); pBuffer = (BYTE*)CoTaskMemAlloc(cbSize); if (pBuffer == NULL) { CHECK_HR(hr = E_OUTOFMEMORY); } CHECK_HR(hr = MFGetAttributesAsBlob(_spAttributes.Get(), pBuffer, cbSize)); *ppBuffer = pBuffer; *pcbSize = cbSize; done: if (FAILED(hr)) { *ppBuffer = NULL; *pcbSize = 0; CoTaskMemFree(pBuffer); } return hr; } HRESULT DeserializeFromBlob(const UINT8* pBuffer, UINT cbSize) { assert(_spAttributes); return MFInitAttributesFromBlob(_spAttributes.Get(), pBuffer, cbSize); } HRESULT GetRatio(REFGUID guidKey, UINT32* pnNumerator, UINT32* punDenominator) { assert(_spAttributes); return MFGetAttributeRatio(_spAttributes.Get(), guidKey, pnNumerator, punDenominator); } HRESULT SetRatio(REFGUID guidKey, UINT32 unNumerator, UINT32 unDenominator) { assert(_spAttributes); return MFSetAttributeRatio(_spAttributes.Get(), guidKey, unNumerator, unDenominator); } // Gets an attribute whose value represents the size of something (eg a video frame). HRESULT GetSize(REFGUID guidKey, UINT32* punWidth, UINT32* punHeight) { assert(_spAttributes); return MFGetAttributeSize(_spAttributes.Get(), guidKey, punWidth, punHeight); } // Sets an attribute whose value represents the size of something (eg a video frame). HRESULT SetSize(REFGUID guidKey, UINT32 unWidth, UINT32 unHeight) { assert(_spAttributes); return MFSetAttributeSize (_spAttributes.Get(), guidKey, unWidth, unHeight); } protected: _ComPtr<IMFAttributes> _spAttributes; }; class StreamSink : #ifdef HAVE_WINRT public Microsoft::WRL::RuntimeClass< Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::ClassicCom>, IMFStreamSink, IMFMediaEventGenerator, IMFMediaTypeHandler, CBaseAttributes<> > #else public IMFStreamSink, public IMFMediaTypeHandler, public CBaseAttributes<>, public ICustomStreamSink #endif { public: // IUnknown methods #if defined(_MSC_VER) && _MSC_VER >= 1700 // '_Outptr_result_nullonfailure_' SAL is avaialable since VS 2012 STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppv) #else STDMETHOD(QueryInterface)(REFIID riid, void **ppv) #endif { if (ppv == nullptr) { return E_POINTER; } (*ppv) = nullptr; HRESULT hr = S_OK; if (riid == IID_IMarshal) { return MarshalQI(riid, ppv); } else { #ifdef HAVE_WINRT hr = RuntimeClassT::QueryInterface(riid, ppv); #else if (riid == IID_IUnknown || riid == IID_IMFStreamSink) { *ppv = static_cast<IMFStreamSink*>(this); AddRef(); } else if (riid == IID_IMFMediaEventGenerator) { *ppv = static_cast<IMFMediaEventGenerator*>(this); AddRef(); } else if (riid == IID_IMFMediaTypeHandler) { *ppv = static_cast<IMFMediaTypeHandler*>(this); AddRef(); } else if (riid == IID_IMFAttributes) { *ppv = static_cast<IMFAttributes*>(this); AddRef(); } else if (riid == IID_ICustomStreamSink) { *ppv = static_cast<ICustomStreamSink*>(this); AddRef(); } else hr = E_NOINTERFACE; #endif } return hr; } #ifdef HAVE_WINRT STDMETHOD(RuntimeClassInitialize)() { return S_OK; } #else ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&m_cRef); } ULONG STDMETHODCALLTYPE Release() { ULONG cRef = InterlockedDecrement(&m_cRef); if (cRef == 0) { delete this; } return cRef; } #endif HRESULT MarshalQI(REFIID riid, LPVOID* ppv) { HRESULT hr = S_OK; if (m_spFTM == nullptr) { EnterCriticalSection(&m_critSec); if (m_spFTM == nullptr) { hr = CoCreateFreeThreadedMarshaler((IMFStreamSink*)this, &m_spFTM); } LeaveCriticalSection(&m_critSec); } if (SUCCEEDED(hr)) { if (m_spFTM == nullptr) { hr = E_UNEXPECTED; } else { hr = m_spFTM.Get()->QueryInterface(riid, ppv); } } return hr; } enum State { State_TypeNotSet = 0, // No media type is set State_Ready, // Media type is set, Start has never been called. State_Started, State_Stopped, State_Paused, State_Count // Number of states }; StreamSink() : m_IsShutdown(false), m_StartTime(0), m_fGetStartTimeFromSample(false), m_fWaitingForFirstSample(false), m_state(State_TypeNotSet), m_pParent(nullptr), m_imageWidthInPixels(0), m_imageHeightInPixels(0) { #ifdef HAVE_WINRT m_token.value = 0; #else m_bConnected = false; #endif InitializeCriticalSectionEx(&m_critSec, 3000, 0); ZeroMemory(&m_guiCurrentSubtype, sizeof(m_guiCurrentSubtype)); CBaseAttributes::Initialize(0U); DebugPrintOut(L"StreamSink::StreamSink\n"); } virtual ~StreamSink() { DeleteCriticalSection(&m_critSec); assert(m_IsShutdown); DebugPrintOut(L"StreamSink::~StreamSink\n"); } HRESULT Initialize() { HRESULT hr; // Create the event queue helper. hr = MFCreateEventQueue(&m_spEventQueue); if (SUCCEEDED(hr)) { _ComPtr<IMFMediaSink> pMedSink; hr = CBaseAttributes<>::GetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf()); assert(pMedSink.Get() != NULL); if (SUCCEEDED(hr)) { hr = pMedSink.Get()->QueryInterface(IID_PPV_ARGS(&m_pParent)); } } return hr; } HRESULT CheckShutdown() const { if (m_IsShutdown) { return MF_E_SHUTDOWN; } else { return S_OK; } } // Called when the presentation clock starts. HRESULT Start(MFTIME start) { HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); if (m_state != State_TypeNotSet) { if (start != PRESENTATION_CURRENT_POSITION) { m_StartTime = start; // Cache the start time. m_fGetStartTimeFromSample = false; } else { m_fGetStartTimeFromSample = true; } m_state = State_Started; GUID guiMajorType; m_fWaitingForFirstSample = SUCCEEDED(m_spCurrentType->GetMajorType(&guiMajorType)) && (guiMajorType == MFMediaType_Video); hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL); if (SUCCEEDED(hr)) { hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, hr, NULL); } } else hr = MF_E_NOT_INITIALIZED; LeaveCriticalSection(&m_critSec); return hr; } // Called when the presentation clock pauses. HRESULT Pause() { EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state != State_Stopped && m_state != State_TypeNotSet) { m_state = State_Paused; hr = QueueEvent(MEStreamSinkPaused, GUID_NULL, hr, NULL); } else if (hr == State_TypeNotSet) hr = MF_E_NOT_INITIALIZED; else hr = MF_E_INVALIDREQUEST; LeaveCriticalSection(&m_critSec); return hr; } // Called when the presentation clock restarts. HRESULT Restart() { EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state == State_Paused) { m_state = State_Started; hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL); if (SUCCEEDED(hr)) { hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, hr, NULL); } } else if (hr == State_TypeNotSet) hr = MF_E_NOT_INITIALIZED; else hr = MF_E_INVALIDREQUEST; LeaveCriticalSection(&m_critSec); return hr; } // Called when the presentation clock stops. HRESULT Stop() { EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state != State_TypeNotSet) { m_state = State_Stopped; hr = QueueEvent(MEStreamSinkStopped, GUID_NULL, hr, NULL); } else hr = MF_E_NOT_INITIALIZED; LeaveCriticalSection(&m_critSec); return hr; } // Shuts down the stream sink. HRESULT Shutdown() { _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; HRESULT hr = S_OK; assert(!m_IsShutdown); hr = m_pParent->GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) { hr = pSampleCallback->OnShutdown(); } if (m_spEventQueue) { hr = m_spEventQueue->Shutdown(); } if (m_pParent) m_pParent->Release(); m_spCurrentType.Reset(); m_IsShutdown = TRUE; return hr; } //IMFStreamSink HRESULT STDMETHODCALLTYPE GetMediaSink( /* [out] */ __RPC__deref_out_opt IMFMediaSink **ppMediaSink) { if (ppMediaSink == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { _ComPtr<IMFMediaSink> pMedSink; hr = CBaseAttributes<>::GetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf()); if (SUCCEEDED(hr)) { *ppMediaSink = pMedSink.Detach(); } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaSink: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetIdentifier( /* [out] */ __RPC__out DWORD *pdwIdentifier) { if (pdwIdentifier == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = GetUINT32(MF_STREAMSINK_ID, (UINT32*)pdwIdentifier); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetIdentifier: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetMediaTypeHandler( /* [out] */ __RPC__deref_out_opt IMFMediaTypeHandler **ppHandler) { if (ppHandler == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); // This stream object acts as its own type handler, so we QI ourselves. if (SUCCEEDED(hr)) { hr = QueryInterface(IID_IMFMediaTypeHandler, (void**)ppHandler); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaTypeHandler: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE ProcessSample(IMFSample *pSample) { _ComPtr<IMFMediaBuffer> pInput; _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; BYTE *pSrc = NULL; // Source buffer. // Stride if the buffer does not support IMF2DBuffer LONGLONG hnsTime = 0; LONGLONG hnsDuration = 0; DWORD cbMaxLength; DWORD cbCurrentLength = 0; GUID guidMajorType; if (pSample == NULL) { return E_INVALIDARG; } HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); if (m_state != State_Started && m_state != State_Paused) { if (m_state == State_TypeNotSet) hr = MF_E_NOT_INITIALIZED; else hr = MF_E_INVALIDREQUEST; } if (SUCCEEDED(hr)) hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = pSample->ConvertToContiguousBuffer(&pInput); if (SUCCEEDED(hr)) { hr = pSample->GetSampleTime(&hnsTime); } if (SUCCEEDED(hr)) { hr = pSample->GetSampleDuration(&hnsDuration); } if (SUCCEEDED(hr)) { hr = GetMajorType(&guidMajorType); } if (SUCCEEDED(hr)) { hr = m_pParent->GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); } if (SUCCEEDED(hr)) { hr = pInput->Lock(&pSrc, &cbMaxLength, &cbCurrentLength); } if (SUCCEEDED(hr)) { hr = pSampleCallback->OnProcessSample(guidMajorType, 0, hnsTime, hnsDuration, pSrc, cbCurrentLength); pInput->Unlock(); } if (SUCCEEDED(hr)) { hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, NULL); } } LeaveCriticalSection(&m_critSec); return hr; } HRESULT STDMETHODCALLTYPE PlaceMarker( /* [in] */ MFSTREAMSINK_MARKER_TYPE eMarkerType, /* [in] */ __RPC__in const PROPVARIANT * /*pvarMarkerValue*/, /* [in] */ __RPC__in const PROPVARIANT * /*pvarContextValue*/) { eMarkerType; EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state == State_TypeNotSet) hr = MF_E_NOT_INITIALIZED; if (SUCCEEDED(hr)) hr = CheckShutdown(); if (SUCCEEDED(hr)) { //at shutdown will receive MFSTREAMSINK_MARKER_ENDOFSEGMENT hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, NULL); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::PlaceMarker: HRESULT=%i %s\n", hr, StreamSinkMarkerTypeMap.at(eMarkerType).c_str()); return hr; } HRESULT STDMETHODCALLTYPE Flush(void) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::Flush: HRESULT=%i\n", hr); return hr; } //IMFMediaEventGenerator HRESULT STDMETHODCALLTYPE GetEvent( DWORD dwFlags, IMFMediaEvent **ppEvent) { // NOTE: // GetEvent can block indefinitely, so we don't hold the lock. // This requires some juggling with the event queue pointer. HRESULT hr = S_OK; _ComPtr<IMFMediaEventQueue> pQueue; { EnterCriticalSection(&m_critSec); // Check shutdown hr = CheckShutdown(); // Get the pointer to the event queue. if (SUCCEEDED(hr)) { pQueue = m_spEventQueue.Get(); } LeaveCriticalSection(&m_critSec); } // Now get the event. if (SUCCEEDED(hr)) { hr = pQueue->GetEvent(dwFlags, ppEvent); } MediaEventType meType = MEUnknown; if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) { } HRESULT hrStatus = S_OK; if (SUCCEEDED(hr)) hr = (*ppEvent)->GetStatus(&hrStatus); if (SUCCEEDED(hr)) DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str()); else DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE BeginGetEvent( IMFAsyncCallback *pCallback, IUnknown *punkState) { HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = m_spEventQueue->BeginGetEvent(pCallback, punkState); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::BeginGetEvent: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE EndGetEvent( IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) { HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = m_spEventQueue->EndGetEvent(pResult, ppEvent); } MediaEventType meType = MEUnknown; if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) { } LeaveCriticalSection(&m_critSec); HRESULT hrStatus = S_OK; if (SUCCEEDED(hr)) hr = (*ppEvent)->GetStatus(&hrStatus); if (SUCCEEDED(hr)) DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str()); else DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE QueueEvent( MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT *pvValue) { HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = m_spEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(met).c_str()); DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i\n", hr); return hr; } /// IMFMediaTypeHandler methods // Check if a media type is supported. STDMETHODIMP IsMediaTypeSupported( /* [in] */ IMFMediaType *pMediaType, /* [out] */ IMFMediaType **ppMediaType) { if (pMediaType == nullptr) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); GUID majorType = GUID_NULL; HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = pMediaType->GetGUID(MF_MT_MAJOR_TYPE, &majorType); } // First make sure it's video or audio type. if (SUCCEEDED(hr)) { if (majorType != MFMediaType_Video && majorType != MFMediaType_Audio) { hr = MF_E_INVALIDTYPE; } } if (SUCCEEDED(hr) && m_spCurrentType != nullptr) { GUID guiNewSubtype; if (FAILED(pMediaType->GetGUID(MF_MT_SUBTYPE, &guiNewSubtype)) || guiNewSubtype != m_guiCurrentSubtype) { hr = MF_E_INVALIDTYPE; } } // We don't return any "close match" types. if (ppMediaType) { *ppMediaType = nullptr; } if (ppMediaType && SUCCEEDED(hr)) { _ComPtr<IMFMediaType> pType; hr = MFCreateMediaType(ppMediaType); if (SUCCEEDED(hr)) { hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType); } if (SUCCEEDED(hr)) { hr = pType->LockStore(); } bool bLocked = false; if (SUCCEEDED(hr)) { bLocked = true; UINT32 uiCount; UINT32 uiTotal; hr = pType->GetCount(&uiTotal); for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) { GUID guid; PROPVARIANT propval; hr = pType->GetItemByIndex(uiCount, &guid, &propval); if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == MF_MT_PIXEL_ASPECT_RATIO || guid == MF_MT_ALL_SAMPLES_INDEPENDENT || guid == MF_MT_INTERLACE_MODE || guid == MF_MT_SUBTYPE)) { hr = (*ppMediaType)->SetItem(guid, propval); PropVariantClear(&propval); } } } if (bLocked) { hr = pType->UnlockStore(); } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::IsMediaTypeSupported: HRESULT=%i\n", hr); return hr; } // Return the number of preferred media types. STDMETHODIMP GetMediaTypeCount(DWORD *pdwTypeCount) { if (pdwTypeCount == nullptr) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { // We've got only one media type *pdwTypeCount = 1; } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaTypeCount: HRESULT=%i\n", hr); return hr; } // Return a preferred media type by index. STDMETHODIMP GetMediaTypeByIndex( /* [in] */ DWORD dwIndex, /* [out] */ IMFMediaType **ppType) { if (ppType == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (dwIndex > 0) { hr = MF_E_NO_MORE_TYPES; } else { //return preferred type based on media capture library 6 elements preferred preview type //hr = m_spCurrentType.CopyTo(ppType); if (SUCCEEDED(hr)) { _ComPtr<IMFMediaType> pType; hr = MFCreateMediaType(ppType); if (SUCCEEDED(hr)) { hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType); } if (SUCCEEDED(hr)) { hr = pType->LockStore(); } bool bLocked = false; if (SUCCEEDED(hr)) { bLocked = true; UINT32 uiCount; UINT32 uiTotal; hr = pType->GetCount(&uiTotal); for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) { GUID guid; PROPVARIANT propval; hr = pType->GetItemByIndex(uiCount, &guid, &propval); if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == MF_MT_PIXEL_ASPECT_RATIO || guid == MF_MT_ALL_SAMPLES_INDEPENDENT || guid == MF_MT_INTERLACE_MODE || guid == MF_MT_SUBTYPE)) { hr = (*ppType)->SetItem(guid, propval); PropVariantClear(&propval); } } } if (bLocked) { hr = pType->UnlockStore(); } } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaTypeByIndex: HRESULT=%i\n", hr); return hr; } // Set the current media type. STDMETHODIMP SetCurrentMediaType(IMFMediaType *pMediaType) { if (pMediaType == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state != State_TypeNotSet && m_state != State_Ready) hr = MF_E_INVALIDREQUEST; if (SUCCEEDED(hr)) hr = CheckShutdown(); // We don't allow format changes after streaming starts. // We set media type already if (m_state >= State_Ready) { if (SUCCEEDED(hr)) { hr = IsMediaTypeSupported(pMediaType, NULL); } } if (SUCCEEDED(hr)) { hr = MFCreateMediaType(m_spCurrentType.ReleaseAndGetAddressOf()); if (SUCCEEDED(hr)) { hr = pMediaType->CopyAllItems(m_spCurrentType.Get()); } if (SUCCEEDED(hr)) { hr = m_spCurrentType->GetGUID(MF_MT_SUBTYPE, &m_guiCurrentSubtype); } GUID guid; if (SUCCEEDED(hr)) { hr = m_spCurrentType->GetMajorType(&guid); } if (SUCCEEDED(hr) && guid == MFMediaType_Video) { hr = MFGetAttributeSize(m_spCurrentType.Get(), MF_MT_FRAME_SIZE, &m_imageWidthInPixels, &m_imageHeightInPixels); } if (SUCCEEDED(hr)) { m_state = State_Ready; } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::SetCurrentMediaType: HRESULT=%i\n", hr); return hr; } // Return the current media type, if any. STDMETHODIMP GetCurrentMediaType(IMFMediaType **ppMediaType) { if (ppMediaType == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { if (m_spCurrentType == nullptr) { hr = MF_E_NOT_INITIALIZED; } } if (SUCCEEDED(hr)) { hr = m_spCurrentType.CopyTo(ppMediaType); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetCurrentMediaType: HRESULT=%i\n", hr); return hr; } // Return the major type GUID. STDMETHODIMP GetMajorType(GUID *pguidMajorType) { HRESULT hr; if (pguidMajorType == nullptr) { return E_INVALIDARG; } _ComPtr<IMFMediaType> pType; hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType); if (SUCCEEDED(hr)) { hr = pType->GetMajorType(pguidMajorType); } DebugPrintOut(L"StreamSink::GetMajorType: HRESULT=%i\n", hr); return hr; } private: #ifdef HAVE_WINRT EventRegistrationToken m_token; #else bool m_bConnected; #endif bool m_IsShutdown; // Flag to indicate if Shutdown() method was called. CRITICAL_SECTION m_critSec; #ifndef HAVE_WINRT long m_cRef; #endif IMFAttributes* m_pParent; _ComPtr<IMFMediaType> m_spCurrentType; _ComPtr<IMFMediaEventQueue> m_spEventQueue; // Event queue _ComPtr<IUnknown> m_spFTM; State m_state; bool m_fGetStartTimeFromSample; bool m_fWaitingForFirstSample; MFTIME m_StartTime; // Presentation time when the clock started. GUID m_guiCurrentSubtype; UINT32 m_imageWidthInPixels; UINT32 m_imageHeightInPixels; }; // Notes: // // The List class template implements a simple double-linked list. // It uses STL's copy semantics. // There are two versions of the Clear() method: // Clear(void) clears the list w/out cleaning up the object. // Clear(FN fn) takes a functor object that releases the objects, if they need cleanup. // The List class supports enumeration. Example of usage: // // List<T>::POSIITON pos = list.GetFrontPosition(); // while (pos != list.GetEndPosition()) // { // T item; // hr = list.GetItemPos(&item); // pos = list.Next(pos); // } // The ComPtrList class template derives from List<> and implements a list of COM pointers. template <class T> struct NoOp { void operator()(T& /*t*/) { } }; template <class T> class List { protected: // Nodes in the linked list struct Node { Node *prev; Node *next; T item; Node() : prev(nullptr), next(nullptr) { } Node(T item) : prev(nullptr), next(nullptr) { this->item = item; } T Item() const { return item; } }; public: // Object for enumerating the list. class POSITION { friend class List<T>; public: POSITION() : pNode(nullptr) { } bool operator==(const POSITION &p) const { return pNode == p.pNode; } bool operator!=(const POSITION &p) const { return pNode != p.pNode; } private: const Node *pNode; POSITION(Node *p) : pNode(p) { } }; protected: Node m_anchor; // Anchor node for the linked list. DWORD m_count; // Number of items in the list. Node* Front() const { return m_anchor.next; } Node* Back() const { return m_anchor.prev; } virtual HRESULT InsertAfter(T item, Node *pBefore) { if (pBefore == nullptr) { return E_POINTER; } Node *pNode = new Node(item); if (pNode == nullptr) { return E_OUTOFMEMORY; } Node *pAfter = pBefore->next; pBefore->next = pNode; pAfter->prev = pNode; pNode->prev = pBefore; pNode->next = pAfter; m_count++; return S_OK; } virtual HRESULT GetItem(const Node *pNode, T* ppItem) { if (pNode == nullptr || ppItem == nullptr) { return E_POINTER; } *ppItem = pNode->item; return S_OK; } // RemoveItem: // Removes a node and optionally returns the item. // ppItem can be nullptr. virtual HRESULT RemoveItem(Node *pNode, T *ppItem) { if (pNode == nullptr) { return E_POINTER; } assert(pNode != &m_anchor); // We should never try to remove the anchor node. if (pNode == &m_anchor) { return E_INVALIDARG; } T item; // The next node's previous is this node's previous. pNode->next->prev = pNode->prev; // The previous node's next is this node's next. pNode->prev->next = pNode->next; item = pNode->item; delete pNode; m_count--; if (ppItem) { *ppItem = item; } return S_OK; } public: List() { m_anchor.next = &m_anchor; m_anchor.prev = &m_anchor; m_count = 0; } virtual ~List() { Clear(); } // Insertion functions HRESULT InsertBack(T item) { return InsertAfter(item, m_anchor.prev); } HRESULT InsertFront(T item) { return InsertAfter(item, &m_anchor); } HRESULT InsertPos(POSITION pos, T item) { if (pos.pNode == nullptr) { return InsertBack(item); } return InsertAfter(item, pos.pNode->prev); } // RemoveBack: Removes the tail of the list and returns the value. // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.) HRESULT RemoveBack(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return RemoveItem(Back(), ppItem); } } // RemoveFront: Removes the head of the list and returns the value. // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.) HRESULT RemoveFront(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return RemoveItem(Front(), ppItem); } } // GetBack: Gets the tail item. HRESULT GetBack(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return GetItem(Back(), ppItem); } } // GetFront: Gets the front item. HRESULT GetFront(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return GetItem(Front(), ppItem); } } // GetCount: Returns the number of items in the list. DWORD GetCount() const { return m_count; } bool IsEmpty() const { return (GetCount() == 0); } // Clear: Takes a functor object whose operator() // frees the object on the list. template <class FN> void Clear(FN& clear_fn) { Node *n = m_anchor.next; // Delete the nodes while (n != &m_anchor) { clear_fn(n->item); Node *tmp = n->next; delete n; n = tmp; } // Reset the anchor to point at itself m_anchor.next = &m_anchor; m_anchor.prev = &m_anchor; m_count = 0; } // Clear: Clears the list. (Does not delete or release the list items.) virtual void Clear() { NoOp<T> clearOp; Clear<>(clearOp); } // Enumerator functions POSITION FrontPosition() { if (IsEmpty()) { return POSITION(nullptr); } else { return POSITION(Front()); } } POSITION EndPosition() const { return POSITION(); } HRESULT GetItemPos(POSITION pos, T *ppItem) { if (pos.pNode) { return GetItem(pos.pNode, ppItem); } else { return E_FAIL; } } POSITION Next(const POSITION pos) { if (pos.pNode && (pos.pNode->next != &m_anchor)) { return POSITION(pos.pNode->next); } else { return POSITION(nullptr); } } // Remove an item at a position. // The item is returns in ppItem, unless ppItem is nullptr. // NOTE: This method invalidates the POSITION object. HRESULT Remove(POSITION& pos, T *ppItem) { if (pos.pNode) { // Remove const-ness temporarily... Node *pNode = const_cast<Node*>(pos.pNode); pos = POSITION(); return RemoveItem(pNode, ppItem); } else { return E_INVALIDARG; } } }; // Typical functors for Clear method. // ComAutoRelease: Releases COM pointers. // MemDelete: Deletes pointers to new'd memory. class ComAutoRelease { public: void operator()(IUnknown *p) { if (p) { p->Release(); } } }; class MemDelete { public: void operator()(void *p) { if (p) { delete p; } } }; // ComPtrList class // Derived class that makes it safer to store COM pointers in the List<> class. // It automatically AddRef's the pointers that are inserted onto the list // (unless the insertion method fails). // // T must be a COM interface type. // example: ComPtrList<IUnknown> // // NULLABLE: If true, client can insert nullptr pointers. This means GetItem can // succeed but return a nullptr pointer. By default, the list does not allow nullptr // pointers. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4127) // constant expression #endif template <class T, bool NULLABLE = FALSE> class ComPtrList : public List<T*> { public: typedef T* Ptr; void Clear() { ComAutoRelease car; List<Ptr>::Clear(car); } ~ComPtrList() { Clear(); } protected: HRESULT InsertAfter(Ptr item, Node *pBefore) { // Do not allow nullptr item pointers unless NULLABLE is true. if (item == nullptr && !NULLABLE) { return E_POINTER; } if (item) { item->AddRef(); } HRESULT hr = List<Ptr>::InsertAfter(item, pBefore); if (FAILED(hr) && item != nullptr) { item->Release(); } return hr; } HRESULT GetItem(const Node *pNode, Ptr* ppItem) { Ptr pItem = nullptr; // The base class gives us the pointer without AddRef'ing it. // If we return the pointer to the caller, we must AddRef(). HRESULT hr = List<Ptr>::GetItem(pNode, &pItem); if (SUCCEEDED(hr)) { assert(pItem || NULLABLE); if (pItem) { *ppItem = pItem; (*ppItem)->AddRef(); } } return hr; } HRESULT RemoveItem(Node *pNode, Ptr *ppItem) { // ppItem can be nullptr, but we need to get the // item so that we can release it. // If ppItem is not nullptr, we will AddRef it on the way out. Ptr pItem = nullptr; HRESULT hr = List<Ptr>::RemoveItem(pNode, &pItem); if (SUCCEEDED(hr)) { assert(pItem || NULLABLE); if (ppItem && pItem) { *ppItem = pItem; (*ppItem)->AddRef(); } if (pItem) { pItem->Release(); pItem = nullptr; } } return hr; } }; #ifdef _MSC_VER #pragma warning(pop) #endif /* Be sure to declare webcam device capability in manifest For better media capture support, add the following snippet with correct module name to the project manifest (highgui needs DLL activation class factoryentry points): <Extensions> <Extension Category="windows.activatableClass.inProcessServer"> <InProcessServer> <Path>modulename</Path> <ActivatableClass ActivatableClassId="cv.MediaSink" ThreadingModel="both" /> </InProcessServer> </Extension> </Extensions>*/ extern const __declspec(selectany) WCHAR RuntimeClass_CV_MediaSink[] = L"cv.MediaSink"; class MediaSink : #ifdef HAVE_WINRT public Microsoft::WRL::RuntimeClass< Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >, Microsoft::WRL::Implements<ABI::Windows::Media::IMediaExtension>, IMFMediaSink, IMFClockStateSink, Microsoft::WRL::FtmBase, CBaseAttributes<>> #else public IMFMediaSink, public IMFClockStateSink, public CBaseAttributes<> #endif { #ifdef HAVE_WINRT InspectableClass(RuntimeClass_CV_MediaSink, BaseTrust) public: #else public: ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&m_cRef); } ULONG STDMETHODCALLTYPE Release() { ULONG cRef = InterlockedDecrement(&m_cRef); if (cRef == 0) { delete this; } return cRef; } #if defined(_MSC_VER) && _MSC_VER >= 1700 // '_Outptr_result_nullonfailure_' SAL is avaialable since VS 2012 STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppv) #else STDMETHOD(QueryInterface)(REFIID riid, void **ppv) #endif { if (ppv == nullptr) { return E_POINTER; } (*ppv) = nullptr; HRESULT hr = S_OK; if (riid == IID_IUnknown || riid == IID_IMFMediaSink) { (*ppv) = static_cast<IMFMediaSink*>(this); AddRef(); } else if (riid == IID_IMFClockStateSink) { (*ppv) = static_cast<IMFClockStateSink*>(this); AddRef(); } else if (riid == IID_IMFAttributes) { (*ppv) = static_cast<IMFAttributes*>(this); AddRef(); } else { hr = E_NOINTERFACE; } return hr; } #endif MediaSink() : m_IsShutdown(false), m_llStartTime(0) { CBaseAttributes<>::Initialize(0U); InitializeCriticalSectionEx(&m_critSec, 3000, 0); DebugPrintOut(L"MediaSink::MediaSink\n"); } virtual ~MediaSink() { DebugPrintOut(L"MediaSink::~MediaSink\n"); DeleteCriticalSection(&m_critSec); assert(m_IsShutdown); } HRESULT CheckShutdown() const { if (m_IsShutdown) { return MF_E_SHUTDOWN; } else { return S_OK; } } #ifdef HAVE_WINRT STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration) { HRESULT hr = S_OK; if (pConfiguration) { Microsoft::WRL::ComPtr<IInspectable> spInsp; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *>> spSetting; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropVal; Microsoft::WRL::ComPtr<ABI::Windows::Media::MediaProperties::IMediaEncodingProperties> pMedEncProps; UINT32 uiType = ABI::Windows::Media::Capture::MediaStreamType_VideoPreview; hr = pConfiguration->QueryInterface(IID_PPV_ARGS(&spSetting)); if (FAILED(hr)) { hr = E_FAIL; } if (SUCCEEDED(hr)) { hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_SAMPLEGRABBERCALLBACK).Get(), spInsp.ReleaseAndGetAddressOf()); if (FAILED(hr)) { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { hr = SetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, spInsp.Get()); } } if (SUCCEEDED(hr)) { hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDTYPE).Get(), spInsp.ReleaseAndGetAddressOf()); if (FAILED(hr)) { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { if (SUCCEEDED(hr = spInsp.As(&spPropVal))) { hr = spPropVal->GetUInt32(&uiType); } } } if (SUCCEEDED(hr)) { hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDENCPROPS).Get(), spInsp.ReleaseAndGetAddressOf()); if (FAILED(hr)) { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { hr = spInsp.As(&pMedEncProps); } } if (SUCCEEDED(hr)) { hr = SetMediaStreamProperties((ABI::Windows::Media::Capture::MediaStreamType)uiType, pMedEncProps.Get()); } } return hr; } static DWORD GetStreamId(ABI::Windows::Media::Capture::MediaStreamType mediaStreamType) { return 3 - mediaStreamType; } static HRESULT AddAttribute(_In_ GUID guidKey, _In_ ABI::Windows::Foundation::IPropertyValue *pValue, _In_ IMFAttributes* pAttr) { HRESULT hr = S_OK; PROPVARIANT var; ABI::Windows::Foundation::PropertyType type; hr = pValue->get_Type(&type); ZeroMemory(&var, sizeof(var)); if (SUCCEEDED(hr)) { switch (type) { case ABI::Windows::Foundation::PropertyType_UInt8Array: { UINT32 cbBlob; BYTE *pbBlog = nullptr; hr = pValue->GetUInt8Array(&cbBlob, &pbBlog); if (SUCCEEDED(hr)) { if (pbBlog == nullptr) { hr = E_INVALIDARG; } else { hr = pAttr->SetBlob(guidKey, pbBlog, cbBlob); } } CoTaskMemFree(pbBlog); } break; case ABI::Windows::Foundation::PropertyType_Double: { DOUBLE value; hr = pValue->GetDouble(&value); if (SUCCEEDED(hr)) { hr = pAttr->SetDouble(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_Guid: { GUID value; hr = pValue->GetGuid(&value); if (SUCCEEDED(hr)) { hr = pAttr->SetGUID(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_String: { Microsoft::WRL::Wrappers::HString value; hr = pValue->GetString(value.GetAddressOf()); if (SUCCEEDED(hr)) { UINT32 len = 0; LPCWSTR szValue = WindowsGetStringRawBuffer(value.Get(), &len); hr = pAttr->SetString(guidKey, szValue); } } break; case ABI::Windows::Foundation::PropertyType_UInt32: { UINT32 value; hr = pValue->GetUInt32(&value); if (SUCCEEDED(hr)) { pAttr->SetUINT32(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_UInt64: { UINT64 value; hr = pValue->GetUInt64(&value); if (SUCCEEDED(hr)) { hr = pAttr->SetUINT64(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_Inspectable: { Microsoft::WRL::ComPtr<IInspectable> value; hr = TYPE_E_TYPEMISMATCH; if (SUCCEEDED(hr)) { pAttr->SetUnknown(guidKey, value.Get()); } } break; // ignore unknown values } } return hr; } static HRESULT ConvertPropertiesToMediaType(_In_ ABI::Windows::Media::MediaProperties::IMediaEncodingProperties *pMEP, _Outptr_ IMFMediaType **ppMT) { HRESULT hr = S_OK; _ComPtr<IMFMediaType> spMT; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<GUID, IInspectable*>> spMap; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterable<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterable; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterator<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterator; if (pMEP == nullptr || ppMT == nullptr) { return E_INVALIDARG; } *ppMT = nullptr; hr = pMEP->get_Properties(spMap.GetAddressOf()); if (SUCCEEDED(hr)) { hr = spMap.As(&spIterable); } if (SUCCEEDED(hr)) { hr = spIterable->First(&spIterator); } if (SUCCEEDED(hr)) { MFCreateMediaType(spMT.ReleaseAndGetAddressOf()); } boolean hasCurrent = false; if (SUCCEEDED(hr)) { hr = spIterator->get_HasCurrent(&hasCurrent); } while (hasCurrent) { Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*> > spKeyValuePair; Microsoft::WRL::ComPtr<IInspectable> spValue; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue; GUID guidKey; hr = spIterator->get_Current(&spKeyValuePair); if (FAILED(hr)) { break; } hr = spKeyValuePair->get_Key(&guidKey); if (FAILED(hr)) { break; } hr = spKeyValuePair->get_Value(&spValue); if (FAILED(hr)) { break; } hr = spValue.As(&spPropValue); if (FAILED(hr)) { break; } hr = AddAttribute(guidKey, spPropValue.Get(), spMT.Get()); if (FAILED(hr)) { break; } hr = spIterator->MoveNext(&hasCurrent); if (FAILED(hr)) { break; } } if (SUCCEEDED(hr)) { Microsoft::WRL::ComPtr<IInspectable> spValue; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue; GUID guiMajorType; hr = spMap->Lookup(MF_MT_MAJOR_TYPE, spValue.GetAddressOf()); if (SUCCEEDED(hr)) { hr = spValue.As(&spPropValue); } if (SUCCEEDED(hr)) { hr = spPropValue->GetGuid(&guiMajorType); } if (SUCCEEDED(hr)) { if (guiMajorType != MFMediaType_Video && guiMajorType != MFMediaType_Audio) { hr = E_UNEXPECTED; } } } if (SUCCEEDED(hr)) { *ppMT = spMT.Detach(); } return hr; } //this should be passed through SetProperties! HRESULT SetMediaStreamProperties(ABI::Windows::Media::Capture::MediaStreamType MediaStreamType, _In_opt_ ABI::Windows::Media::MediaProperties::IMediaEncodingProperties *mediaEncodingProperties) { HRESULT hr = S_OK; _ComPtr<IMFMediaType> spMediaType; if (MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_VideoPreview && MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_VideoRecord && MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_Audio) { return E_INVALIDARG; } RemoveStreamSink(GetStreamId(MediaStreamType)); if (mediaEncodingProperties != nullptr) { _ComPtr<IMFStreamSink> spStreamSink; hr = ConvertPropertiesToMediaType(mediaEncodingProperties, &spMediaType); if (SUCCEEDED(hr)) { hr = AddStreamSink(GetStreamId(MediaStreamType), nullptr, spStreamSink.GetAddressOf()); } if (SUCCEEDED(hr)) { hr = SetUnknown(MF_MEDIASINK_PREFERREDTYPE, spMediaType.Detach()); } } return hr; } #endif //IMFMediaSink HRESULT STDMETHODCALLTYPE GetCharacteristics( /* [out] */ __RPC__out DWORD *pdwCharacteristics) { HRESULT hr; if (pdwCharacteristics == NULL) return E_INVALIDARG; EnterCriticalSection(&m_critSec); if (SUCCEEDED(hr = CheckShutdown())) { //if had an activation object for the sink, shut down would be managed and MF_STREAM_SINK_SUPPORTS_ROTATION appears to be setable to TRUE *pdwCharacteristics = MEDIASINK_FIXED_STREAMS;// | MEDIASINK_REQUIRE_REFERENCE_MEDIATYPE; } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetCharacteristics: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE AddStreamSink( DWORD dwStreamSinkIdentifier, IMFMediaType * /*pMediaType*/, IMFStreamSink **ppStreamSink) { _ComPtr<IMFStreamSink> spMFStream; _ComPtr<ICustomStreamSink> pStream; EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = GetStreamSinkById(dwStreamSinkIdentifier, &spMFStream); } if (SUCCEEDED(hr)) { hr = MF_E_STREAMSINK_EXISTS; } else { hr = S_OK; } if (SUCCEEDED(hr)) { #ifdef HAVE_WINRT pStream = Microsoft::WRL::Make<StreamSink>(); if (pStream == nullptr) { hr = E_OUTOFMEMORY; } if (SUCCEEDED(hr)) hr = pStream.As<IMFStreamSink>(&spMFStream); #else StreamSink* pSink = new StreamSink(); if (pSink) { hr = pSink->QueryInterface(IID_IMFStreamSink, (void**)spMFStream.GetAddressOf()); if (SUCCEEDED(hr)) { hr = spMFStream.As(&pStream); } if (FAILED(hr)) delete pSink; } #endif } // Initialize the stream. _ComPtr<IMFAttributes> pAttr; if (SUCCEEDED(hr)) { hr = pStream.As(&pAttr); } if (SUCCEEDED(hr)) { hr = pAttr->SetUINT32(MF_STREAMSINK_ID, dwStreamSinkIdentifier); if (SUCCEEDED(hr)) { hr = pAttr->SetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, (IMFMediaSink*)this); } } if (SUCCEEDED(hr)) { hr = pStream->Initialize(); } if (SUCCEEDED(hr)) { ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION posEnd = m_streams.EndPosition(); // Insert in proper position for (; pos != posEnd; pos = m_streams.Next(pos)) { DWORD dwCurrId; _ComPtr<IMFStreamSink> spCurr; hr = m_streams.GetItemPos(pos, &spCurr); if (FAILED(hr)) { break; } hr = spCurr->GetIdentifier(&dwCurrId); if (FAILED(hr)) { break; } if (dwCurrId > dwStreamSinkIdentifier) { break; } } if (SUCCEEDED(hr)) { hr = m_streams.InsertPos(pos, spMFStream.Get()); } } if (SUCCEEDED(hr)) { *ppStreamSink = spMFStream.Detach(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::AddStreamSink: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE RemoveStreamSink(DWORD dwStreamSinkIdentifier) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition(); _ComPtr<IMFStreamSink> spStream; if (SUCCEEDED(hr)) { for (; pos != endPos; pos = m_streams.Next(pos)) { hr = m_streams.GetItemPos(pos, &spStream); DWORD dwId; if (FAILED(hr)) { break; } hr = spStream->GetIdentifier(&dwId); if (FAILED(hr) || dwId == dwStreamSinkIdentifier) { break; } } if (pos == endPos) { hr = MF_E_INVALIDSTREAMNUMBER; } } if (SUCCEEDED(hr)) { hr = m_streams.Remove(pos, nullptr); _ComPtr<ICustomStreamSink> spCustomSink; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(spStream.Get()); hr = S_OK; #else hr = spStream.As(&spCustomSink); #endif if (SUCCEEDED(hr)) hr = spCustomSink->Shutdown(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::RemoveStreamSink: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetStreamSinkCount(DWORD *pStreamSinkCount) { if (pStreamSinkCount == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { *pStreamSinkCount = m_streams.GetCount(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetStreamSinkCount: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetStreamSinkByIndex( DWORD dwIndex, IMFStreamSink **ppStreamSink) { if (ppStreamSink == NULL) { return E_INVALIDARG; } _ComPtr<IMFStreamSink> spStream; EnterCriticalSection(&m_critSec); DWORD cStreams = m_streams.GetCount(); if (dwIndex >= cStreams) { return MF_E_INVALIDINDEX; } HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition(); DWORD dwCurrent = 0; for (; pos != endPos && dwCurrent < dwIndex; pos = m_streams.Next(pos), ++dwCurrent) { // Just move to proper position } if (pos == endPos) { hr = MF_E_UNEXPECTED; } else { hr = m_streams.GetItemPos(pos, &spStream); } } if (SUCCEEDED(hr)) { *ppStreamSink = spStream.Detach(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetStreamSinkByIndex: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetStreamSinkById( DWORD dwStreamSinkIdentifier, IMFStreamSink **ppStreamSink) { if (ppStreamSink == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); _ComPtr<IMFStreamSink> spResult; if (SUCCEEDED(hr)) { ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition(); for (; pos != endPos; pos = m_streams.Next(pos)) { _ComPtr<IMFStreamSink> spStream; hr = m_streams.GetItemPos(pos, &spStream); DWORD dwId; if (FAILED(hr)) { break; } hr = spStream->GetIdentifier(&dwId); if (FAILED(hr)) { break; } else if (dwId == dwStreamSinkIdentifier) { spResult = spStream; break; } } if (pos == endPos) { hr = MF_E_INVALIDSTREAMNUMBER; } } if (SUCCEEDED(hr)) { assert(spResult); *ppStreamSink = spResult.Detach(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetStreamSinkById: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE SetPresentationClock( IMFPresentationClock *pPresentationClock) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); // If we already have a clock, remove ourselves from that clock's // state notifications. if (SUCCEEDED(hr)) { if (m_spClock) { hr = m_spClock->RemoveClockStateSink(this); } } // Register ourselves to get state notifications from the new clock. if (SUCCEEDED(hr)) { if (pPresentationClock) { hr = pPresentationClock->AddClockStateSink(this); } } _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; if (SUCCEEDED(hr)) { // Release the pointer to the old clock. // Store the pointer to the new clock. m_spClock = pPresentationClock; hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); } LeaveCriticalSection(&m_critSec); if (SUCCEEDED(hr)) hr = pSampleCallback->OnSetPresentationClock(pPresentationClock); DebugPrintOut(L"MediaSink::SetPresentationClock: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetPresentationClock( IMFPresentationClock **ppPresentationClock) { if (ppPresentationClock == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { if (!m_spClock) { hr = MF_E_NO_CLOCK; // There is no presentation clock. } else { // Return the pointer to the caller. hr = m_spClock.CopyTo(ppPresentationClock); } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetPresentationClock: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE Shutdown(void) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { ForEach(m_streams, ShutdownFunc()); m_streams.Clear(); m_spClock.ReleaseAndGetAddressOf(); _ComPtr<IMFMediaType> pType; hr = CBaseAttributes<>::GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)pType.GetAddressOf()); if (SUCCEEDED(hr)) { hr = DeleteItem(MF_MEDIASINK_PREFERREDTYPE); } m_IsShutdown = true; } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::Shutdown: HRESULT=%i\n", hr); return hr; } class ShutdownFunc { public: HRESULT operator()(IMFStreamSink *pStream) const { _ComPtr<ICustomStreamSink> spCustomSink; HRESULT hr; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(pStream); #else hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf())); if (FAILED(hr)) return hr; #endif hr = spCustomSink->Shutdown(); return hr; } }; class StartFunc { public: StartFunc(LONGLONG llStartTime) : _llStartTime(llStartTime) { } HRESULT operator()(IMFStreamSink *pStream) const { _ComPtr<ICustomStreamSink> spCustomSink; HRESULT hr; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(pStream); #else hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf())); if (FAILED(hr)) return hr; #endif hr = spCustomSink->Start(_llStartTime); return hr; } LONGLONG _llStartTime; }; class StopFunc { public: HRESULT operator()(IMFStreamSink *pStream) const { _ComPtr<ICustomStreamSink> spCustomSink; HRESULT hr; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(pStream); #else hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf())); if (FAILED(hr)) return hr; #endif hr = spCustomSink->Stop(); return hr; } }; template <class T, class TFunc> HRESULT ForEach(ComPtrList<T> &col, TFunc fn) { ComPtrList<T>::POSITION pos = col.FrontPosition(); ComPtrList<T>::POSITION endPos = col.EndPosition(); HRESULT hr = S_OK; for (; pos != endPos; pos = col.Next(pos)) { _ComPtr<T> spStream; hr = col.GetItemPos(pos, &spStream); if (FAILED(hr)) { break; } hr = fn(spStream.Get()); } return hr; } //IMFClockStateSink HRESULT STDMETHODCALLTYPE OnClockStart( MFTIME hnsSystemTime, LONGLONG llClockStartOffset) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { // Start each stream. m_llStartTime = llClockStartOffset; hr = ForEach(m_streams, StartFunc(llClockStartOffset)); } _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; if (SUCCEEDED(hr)) hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); LeaveCriticalSection(&m_critSec); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockStart(hnsSystemTime, llClockStartOffset); DebugPrintOut(L"MediaSink::OnClockStart: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockStop( MFTIME hnsSystemTime) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { // Stop each stream hr = ForEach(m_streams, StopFunc()); } _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; if (SUCCEEDED(hr)) hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); LeaveCriticalSection(&m_critSec); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockStop(hnsSystemTime); DebugPrintOut(L"MediaSink::OnClockStop: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockPause( MFTIME hnsSystemTime) { HRESULT hr; _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockPause(hnsSystemTime); DebugPrintOut(L"MediaSink::OnClockPause: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockRestart( MFTIME hnsSystemTime) { HRESULT hr; _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockRestart(hnsSystemTime); DebugPrintOut(L"MediaSink::OnClockRestart: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockSetRate( MFTIME hnsSystemTime, float flRate) { HRESULT hr; _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockSetRate(hnsSystemTime, flRate); DebugPrintOut(L"MediaSink::OnClockSetRate: HRESULT=%i\n", hr); return hr; } private: #ifndef HAVE_WINRT long m_cRef; #endif CRITICAL_SECTION m_critSec; bool m_IsShutdown; ComPtrList<IMFStreamSink> m_streams; _ComPtr<IMFPresentationClock> m_spClock; LONGLONG m_llStartTime; }; #ifdef HAVE_WINRT ActivatableClass(MediaSink); #endif
liangfu/dnn
modules/highgui/src/cap_msmf.hpp
C++
mit
111,855
angular.module('starter.controllers', []) // A simple controller that fetches a list of data from a service .controller('PetIndexCtrl', function($scope, PetService) { // "Pets" is a service returning mock data (services.js) $scope.pets = PetService.all(); }) // A simple controller that shows a tapped item's data .controller('PetDetailCtrl', function($scope, $stateParams, PetService) { // "Pets" is a service returning mock data (services.js) $scope.pet = PetService.get($stateParams.petId); }) // getting fake favor data .controller('FavorIndexCtrl', function($scope, FavorService) { $scope.favors = FavorService.all(); }) // A simple controller that shows a tapped item's data .controller('FavorDetailCtrl', function($scope, $stateParams, FavorService) { // "Pets" is a service returning mock data (services.js) $scope.favor = FavorService.get($stateParams.favorId); });
robwormald/favor-app
www/js/controllers.js
JavaScript
mit
899
// Copyright 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. var kDefaultNumberOfResampleRanges = 11; function WaveTable(name, context) { this.name = name; this.context = context; this.sampleRate = context.sampleRate; this.url = "wave-tables/" + this.name; this.waveTableSize = 4096; // hard-coded for now this.buffer = 0; this.numberOfResampleRanges = kDefaultNumberOfResampleRanges; } WaveTable.prototype.getWaveDataForPitch = function(pitchFrequency) { var nyquist = 0.5 * this.sampleRate; var lowestNumPartials = this.getNumberOfPartialsForRange(0); var lowestFundamental = nyquist / lowestNumPartials; // Find out pitch range var ratio = pitchFrequency / lowestFundamental; var pitchRange = ratio == 0.0 ? 0 : Math.floor(Math.log(ratio) / Math.LN2); if (pitchRange < 0) pitchRange = 0; // Too bad, we'll alias if pitch is greater than around 5KHz :) if (pitchRange >= this.numberOfResampleRanges) pitchRange = this.numberOfResampleRanges - 1; return this.buffers[pitchRange]; } WaveTable.prototype.getNumberOfPartialsForRange = function(j) { // goes from 1024 -> 4 @ 44.1KHz (and do same for 48KHz) // goes from 2048 -> 8 @ 96KHz var npartials = Math.pow(2, 1 + this.numberOfResampleRanges - j); if (this.getSampleRate() > 48000.0) npartials *= 2; // high sample rate allows more harmonics at given fundamental return npartials; } WaveTable.prototype.getWaveTableSize = function() { return this.waveTableSize; } WaveTable.prototype.getSampleRate = function() { return this.sampleRate; } WaveTable.prototype.getRateScale = function() { return this.getWaveTableSize() / this.getSampleRate(); } WaveTable.prototype.getNumberOfResampleRanges = function() { this.numberOfResampleRanges; } WaveTable.prototype.getName = function() { return this.name; } WaveTable.prototype.load = function(callback) { var request = new XMLHttpRequest(); request.open("GET", this.url, true); var wave = this; request.onload = function() { // Get the frequency-domain waveform data. var f = eval('(' + request.responseText + ')'); // Copy into more efficient Float32Arrays. var n = f.real.length; frequencyData = { "real": new Float32Array(n), "imag": new Float32Array(n) }; wave.frequencyData = frequencyData; for (var i = 0; i < n; ++i) { frequencyData.real[i] = f.real[i]; frequencyData.imag[i] = f.imag[i]; } wave.createBuffers(); if (callback) callback(wave); }; request.onerror = function() { alert("error loading: " + wave.url); }; request.send(); } WaveTable.prototype.print = function() { var f = this.frequencyData; var info = document.getElementById("info"); var s = ""; for (var i = 0; i < 2048; ++i) { s += "{" + f.real[i] + ", " + f.imag[i] + "}, <br>"; } info.innerHTML = s; } WaveTable.prototype.printBuffer = function(buffer) { var info = document.getElementById("info"); var s = ""; for (var i = 0; i < 4096; ++i) { s += buffer[i] + "<br>"; } info.innerHTML = s; } // WaveTable.prototype.createBuffers = function() { // var f = this.frequencyData; // // var n = 4096; // // var fft = new FFT(n, 44100); // // // Copy from loaded frequency data and scale. // for (var i = 0; i < n / 2; ++i) { // fft.real[i] = 4096 * f.real[i]; // fft.imag[i] = 4096 * f.imag[i]; // } // // // Now do inverse FFT // this.data = fft.inverse(); // var data = this.data; // // this.buffer = context.createBuffer(1, data.length, 44100); // // // Copy data to the buffer. // var p = this.buffer.getChannelData(0); // for (var i = 0; i < data.length; ++i) { // p[i] = data[i]; // } // } // Convert into time-domain wave tables. // We actually create several of them for non-aliasing playback at different playback rates. WaveTable.prototype.createBuffers = function() { // resample ranges // // let's divide up versions of our waves based on the maximum fundamental frequency we're // resampling at. Let's use fundamental frequencies based on dividing Nyquist by powers of two. // For example for 44.1KHz sample-rate we have: // // ranges // ---------------------------------- // 21Hz, 43Hz, 86Hz, 172Hz, 344Hz, 689Hz, 1378Hz, 2756Hz, 5512Hz, 11025Hz, 22050Hz <-- 44.1KHz // 23Hz, 47Hz, 94Hz, 187Hz, 375Hz, 750Hz, 1500Hz, 3000Hz, 6000Hz, 12000Hz, 24000Hz, 48000Hz <-- 96KHz // // and number of partials: // // 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1 // 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1 // // But it's probably OK if we skip the very highest fundamental frequencies and only // go up to 5512Hz, so we have a total of 9 resample ranges // // 0 1 2 3 4 5 6 7 8 // The FFT size needs to be at least 2048 @ 44.1KHz and 4096 @ 96KHz // // So let's try to use FFT size of 4096 all the time and pull out the harmonics we want // this.buffers = new Array(); var finalScale = 1.0; for (var j = 0; j < this.numberOfResampleRanges; ++j) { var n = this.waveTableSize; var frame = new FFT(n, this.sampleRate); // Copy from loaded frequency data and scale. var f = this.frequencyData; var scale = n; for (var i = 0; i < n / 2; ++i) { frame.real[i] = scale * f.real[i]; frame.imag[i] = scale * f.imag[i]; } var realP = frame.real; var imagP = frame.imag; // Find the starting bin where we should start clearing out // (we need to clear out the highest frequencies to band-limit the waveform) var fftSize = n; var halfSize = fftSize / 2; var npartials = this.getNumberOfPartialsForRange(j); // Now, go through and cull out the aliasing harmonics... for (var i = npartials + 1; i < halfSize; i++) { realP[i] = 0.0; imagP[i] = 0.0; } // Clear packed-nyquist if necessary if (npartials < halfSize) imagP[0] = 0.0; // Clear any DC-offset realP[0] = 0.0; // For the first resample range, find power and compute scale. if (j == 0) { var power = 0; for (var i = 1; i < halfSize; ++i) { x = realP[i]; y = imagP[i]; power += x * x + y * y; } power = Math.sqrt(power) / fftSize; finalScale = 0.5 / power; // window.console.log("power = " + power); } // Great, now do inverse FFT into our wavetable... var data = frame.inverse(); // Create mono AudioBuffer. var buffer = this.context.createBuffer(1, data.length, this.sampleRate); // Copy data to the buffer. var p = buffer.getChannelData(0); for (var i = 0; i < data.length; ++i) { p[i] = finalScale * data[i]; } this.buffers[j] = buffer; } } WaveTable.prototype.displayWaveData = function() { var data = this.data; var n = data.length; var s = ""; for (var i = 0; i < n; ++i) { s += data[i].toFixed(3) + "<br> "; } var info = document.getElementById("info"); info.innerHTML = s; }
hems/-labs
examples/audio/lib/wavetable.js
JavaScript
mit
8,974
/** * Created by maomao on 2020/4/20. */ Java.perform(function() { var cn = "android.telephony.SubscriptionManager"; var target = Java.use(cn); if (target) { target.addOnSubscriptionsChangedListener.overloads[0].implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "addOnSubscriptionsChangedListener"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.addOnSubscriptionsChangedListener.overloads[0].apply(this, arguments); }; // target.addOnSubscriptionsChangedListener.overloads[1].implementation = function(dest) { // var myArray=new Array() // myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE // myArray[1] = cn + "." + "addOnSubscriptionsChangedListener"; // myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); // send(myArray); // return this.addOnSubscriptionsChangedListener.overloads[1].apply(this, arguments); // }; target.getActiveSubscriptionInfo.overloads[0].implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "getActiveSubscriptionInfo"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.getActiveSubscriptionInfo.overloads[0].apply(this, arguments); }; // target.getActiveSubscriptionInfo.overloads[1].implementation = function(dest) { // var myArray=new Array() // myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE // myArray[1] = cn + "." + "getActiveSubscriptionInfo"; // myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); // send(myArray); // return this.getActiveSubscriptionInfo.overloads[1].apply(this, arguments); // }; target.getActiveSubscriptionInfoCount.implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "getActiveSubscriptionInfoCount"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.getActiveSubscriptionInfoCount.apply(this, arguments); }; target.getActiveSubscriptionInfoForSimSlotIndex.implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "getActiveSubscriptionInfoForSimSlotIndex"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.getActiveSubscriptionInfoForSimSlotIndex.apply(this, arguments); }; target.getActiveSubscriptionInfoList.implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "getActiveSubscriptionInfoList"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.getActiveSubscriptionInfoList.apply(this, arguments); }; } });
honeynet/droidbot
droidbot/resources/scripts/telephony/SubscriptionManager.js
JavaScript
mit
3,831
"use strict"; const chalk = require("chalk"); const readline = require("readline"); /** * Fill screen with blank lines, move to "0" afterwards and clear screen afterwards. * Note that it is still possible to "scroll back" afterwards. * * Function performs nothing in case the stdout is NOT a TTY. */ exports.cls = function() { if (process.stdout.isTTY) { const blank = "\n".repeat(process.stdout.rows); console.log(blank); readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); } }; /** * A less soft version of `cls` above which completely clears out the screen, * without leaving the option to scroll up again. * * Function performs nothing in case the stdout is NOT a TTY. */ exports.hardCls = function() { if (process.stdout.isTTY) { process.stdout.write( process.platform === "win32" ? "\x1Bc" : "\x1B[2J\x1B[3J\x1B[H" ); } }; exports.formatFirstLineMessage = function(text) { return chalk.bgWhite.black(text); };
DorianGrey/ng2-webpack-template
scripts/util/formatUtil.js
JavaScript
mit
1,001
module Locomotive class SitePolicy < ApplicationPolicy class Scope < Scope def resolve if membership.account.super_admin? scope.all else membership.account.sites end end end def index? true end def show? true end def create? true end def update? super_admin? || site_staff? end def destroy? super_admin? || site_admin? end def point? super_admin? || site_admin? end def update_advanced? super_admin? || site_admin? end def show_developers_documentation? super_admin? || site_admin? end def permitted_attributes plain = [:name, :handle, :picture, :remove_picture, :seo_title, :meta_keywords, :meta_description, :timezone_name, :robots_txt] hash = { domains: [], locales: [] } unless update_advanced? plain -= [:timezone_name, :robots_txt] hash.delete(:locales) end unless point? plain -= [:handle] hash.delete(:domains) end plain << hash end end end
slavajacobson/engine
app/policies/locomotive/site_policy.rb
Ruby
mit
1,128
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time import string import json import config import helper import busses def log_message(msg): #log format: time type message time_str = str(time.time()) line = time_str[:time_str.find(".")] line = line.rjust(10, str(" ")) line += " " busses.status_bus["latest_messages"][msg.chat_id] = msg msg_type = helper.get_message_type(msg) if msg_type == "text" and msg.text.startswith("/"): msg_type = "command" appendix = "ERROR" if msg_type == "text": appendix = msg.text elif msg_type == "command": appendix = msg.text[1:] elif msg_type == "location": location_data = msg.location.to_dict() appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°" elif msg_type == "contact": appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name elif msg_type == "new_user": appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name) elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]: appendix = "" msg_type = msg_type.rjust(10, str(" ")) appendix = appendix.replace("\n", "\\n").rjust(40, str(" ")) line += msg_type + " " + appendix + " " line += str(msg.chat_id) + "," + str(msg.message_id) line += "\n" with open(config.msg_log_file_path, "a") as log_file: log_file.write(line.encode("utf-8")) def complete_log(update): with open(config.complete_log_file_path, "a") as log_file: data = update.to_dict() data.update({"time": time.time()}) json_data = json.dumps(data) log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
Pixdigit/Saufbot
logger.py
Python
mit
1,904
public class LeetCode0363 { public int maxSumSubmatrix(int[][] matrix, int k) { int m = matrix.length, n = matrix[0].length, ans = Integer.MIN_VALUE; long[] sum = new long[m + 1]; for (int i = 0; i < n; ++i) { long[] sumInRow = new long[m]; for (int j = i; j < n; ++j) { for (int p = 0; p < m; ++p) { sumInRow[p] += matrix[p][j]; sum[p + 1] = sum[p] + sumInRow[p]; } ans = Math.max(ans, mergeSort(sum, 0, m + 1, k)); if (ans == k) return k; } } return ans; } int mergeSort(long[] sum, int start, int end, int k) { if (end == start + 1) return Integer.MIN_VALUE; int mid = start + (end - start) / 2, cnt = 0; int ans = mergeSort(sum, start, mid, k); if (ans == k) return k; ans = Math.max(ans, mergeSort(sum, mid, end, k)); if (ans == k) return k; long[] cache = new long[end - start]; for (int i = start, j = mid, p = mid; i < mid; ++i) { while (j < end && sum[j] - sum[i] <= k){ ++j; } if (j - 1 >= mid) { ans = Math.max(ans, (int) (sum[j - 1] - sum[i])); if (ans == k){ return k; } } while (p < end && sum[p] < sum[i]){ cache[cnt++] = sum[p++]; } cache[cnt++] = sum[i]; } System.arraycopy(cache, 0, sum, start, cnt); return ans; } }
dunso/algorithm
Java/Devide/LeetCode0363.java
Java
mit
1,278
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class FilmBoxContentSequence extends AbstractTag { protected $Id = '2130,0030'; protected $Name = 'FilmBoxContentSequence'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Film Box Content Sequence'; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/DICOM/FilmBoxContentSequence.php
PHP
mit
820
<?php namespace Cascade\Mapper\Map; use Cascade\Mapper\Mapping\MappingInterface; class Map implements MapInterface { /** * @var MappingInterface[] */ private $mappings = []; /** * @param MappingInterface[] $mappings */ public function __construct($mappings) { foreach ($mappings as $mapping) { $this->addMapping($mapping); } } public function getMappings() { return $this->mappings; } /** * @param MappingInterface $mapping */ private function addMapping(MappingInterface $mapping) { $this->mappings[] = $mapping; } }
cascademedia/php-object-mapper
src/Map/Map.php
PHP
mit
650
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import numpy as np import matplotlib matplotlib.use('GTKAgg') from matplotlib import pyplot as plt from koheron import connect from drivers import Spectrum from drivers import Laser host = os.getenv('HOST','192.168.1.100') client = connect(host, name='spectrum') driver = Spectrum(client) laser = Laser(client) laser.start() current = 30 # mA laser.set_current(current) # driver.reset_acquisition() wfm_size = 4096 decimation_factor = 1 index_low = 0 index_high = wfm_size / 2 signal = driver.get_decimated_data(decimation_factor, index_low, index_high) print('Signal') print(signal) mhz = 1e6 sampling_rate = 125e6 freq_min = 0 freq_max = sampling_rate / mhz / 2 # Plot parameters fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(freq_min, freq_max, (wfm_size / 2)) print('X') print(len(x)) y = 10*np.log10(signal) print('Y') print(len(y)) li, = ax.plot(x, y) fig.canvas.draw() ax.set_xlim((x[0],x[-1])) ax.set_ylim((0,200)) ax.set_xlabel('Frequency (MHz)') ax.set_ylabel('Power spectral density (dB)') while True: try: signal = driver.get_decimated_data(decimation_factor, index_low, index_high) li.set_ydata(10*np.log10(signal)) fig.canvas.draw() plt.pause(0.001) except KeyboardInterrupt: # Save last spectrum in a csv file np.savetxt("psd.csv", signal, delimiter=",") laser.stop() driver.close() break
Koheron/lase
examples/spectrum_analyzer.py
Python
mit
1,482
const assert = require('assert') const crypto = require('crypto') const { createRequest } = require("../util/util") describe('测试搜索是否正常', () => { it('获取到的数据的 name 应该和搜索关键词一致', done => { const keywords = "海阔天空" const type = 1 const limit = 30 const data = 's=' + keywords + '&limit=' + limit + '&type=' + type + '&offset=0' createRequest('/api/search/pc/', 'POST', data) .then(result => { console.log(JSON.parse(result).result.songs[0].mp3Url) assert(JSON.parse(result).result.songs[0].name === '海阔天空') done() }) .catch(err => { done(err) }) }) })
linguokang/NeteaseCloudMusic
test/search.test.js
JavaScript
mit
692
export default function collapseDuplicateDeclarations() { return (root) => { root.walkRules((node) => { let seen = new Map() let droppable = new Set([]) node.walkDecls((decl) => { // This could happen if we have nested selectors. In that case the // parent will loop over all its declarations but also the declarations // of nested rules. With this we ensure that we are shallowly checking // declarations. if (decl.parent !== node) { return } if (seen.has(decl.prop)) { droppable.add(seen.get(decl.prop)) } seen.set(decl.prop, decl) }) for (let decl of droppable) { decl.remove() } }) } }
tailwindcss/tailwindcss
src/lib/collapseDuplicateDeclarations.js
JavaScript
mit
742
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true, "jasmine" : true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "no-mixed-spaces-and-tabs": [2, "smart-tabs"], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };
raavr/angularjs-todo-webpack
.eslintrc.js
JavaScript
mit
536
import * as debug from 'debug'; import Resolver from '../../resolver'; import { IRemoteUser } from '../../../../models/user'; import acceptFollow from './follow'; import { IAccept, IFollow } from '../../type'; const log = debug('misskey:activitypub'); export default async (actor: IRemoteUser, activity: IAccept): Promise<void> => { const uri = activity.id || activity; log(`Accept: ${uri}`); const resolver = new Resolver(); let object; try { object = await resolver.resolve(activity.object); } catch (e) { log(`Resolution failed: ${e}`); throw e; } switch (object.type) { case 'Follow': acceptFollow(actor, object as IFollow); break; default: console.warn(`Unknown accept type: ${object.type}`); break; } };
ha-dai/Misskey
src/remote/activitypub/kernel/accept/index.ts
TypeScript
mit
744
version https://git-lfs.github.com/spec/v1 oid sha256:42fcecf8fdabe110af986ac81bb56b598f5a3fa59c6d0c4cc8b80daa2dca0473 size 1121
yogeshsaroya/new-cdnjs
ajax/libs/dojo/1.4.6/_base/_loader/hostenv_spidermonkey.js
JavaScript
mit
129
$(document).ready(function(){ var Previewer = { preview: function(content, output) { $.ajax({ type: 'POST', url: "/govspeak", data: { govspeak: content.val() }, dataType: 'json' }).success(function(data){ output.html(data['govspeak']); }); } }; $("[data-preview]").each(function(){ var source_field = $($(this).data('preview-for')); var render_area = $(this); source_field.keyup(function() { Previewer.preview(source_field, render_area); }) }); $('textarea').autosize(); });
alphagov/trade-tariff-admin
app/assets/javascripts/preview.js
JavaScript
mit
576
__version__ = '0.8.1' __author__ = "Massimiliano Pippi & Federico Frenguelli" VERSION = __version__ # synonym
ramcn/demo3
venv/lib/python3.4/site-packages/oauth2_provider/__init__.py
Python
mit
113
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * @namespace Phaser.Structs */ module.exports = { List: require('./List'), Map: require('./Map'), ProcessQueue: require('./ProcessQueue'), RTree: require('./RTree'), Set: require('./Set'), Size: require('./Size') };
TukekeSoft/phaser
src/structs/index.js
JavaScript
mit
425
#! /usr/bin/env python """Show file statistics by extension.""" import os import sys class Stats: def __init__(self): self.stats = {} def statargs(self, args): for arg in args: if os.path.isdir(arg): self.statdir(arg) elif os.path.isfile(arg): self.statfile(arg) else: sys.stderr.write("Can't find %s\n" % file) self.addstats("<???>", "unknown", 1) def statdir(self, dir): self.addstats("<dir>", "dirs", 1) try: names = os.listdir(dir) except os.error, err: sys.stderr.write("Can't list %s: %s\n" % (file, err)) self.addstats(ext, "unlistable", 1) return names.sort() for name in names: if name.startswith(".#"): continue # Skip CVS temp files if name.endswith("~"): continue# Skip Emacs backup files full = os.path.join(dir, name) if os.path.islink(full): self.addstats("<lnk>", "links", 1) elif os.path.isdir(full): self.statdir(full) else: self.statfile(full) def statfile(self, file): head, ext = os.path.splitext(file) head, base = os.path.split(file) if ext == base: ext = "" # E.g. .cvsignore is deemed not to have an extension ext = os.path.normcase(ext) if not ext: ext = "<none>" self.addstats(ext, "files", 1) try: f = open(file, "rb") except IOError, err: sys.stderr.write("Can't open %s: %s\n" % (file, err)) self.addstats(ext, "unopenable", 1) return data = f.read() f.close() self.addstats(ext, "bytes", len(data)) if '\0' in data: self.addstats(ext, "binary", 1) return if not data: self.addstats(ext, "empty", 1) #self.addstats(ext, "chars", len(data)) lines = data.splitlines() self.addstats(ext, "lines", len(lines)) del lines words = data.split() self.addstats(ext, "words", len(words)) def addstats(self, ext, key, n): d = self.stats.setdefault(ext, {}) d[key] = d.get(key, 0) + n def report(self): exts = self.stats.keys() exts.sort() # Get the column keys columns = {} for ext in exts: columns.update(self.stats[ext]) cols = columns.keys() cols.sort() colwidth = {} colwidth["ext"] = max([len(ext) for ext in exts]) minwidth = 6 self.stats["TOTAL"] = {} for col in cols: total = 0 cw = max(minwidth, len(col)) for ext in exts: value = self.stats[ext].get(col) if value is None: w = 0 else: w = len("%d" % value) total += value cw = max(cw, w) cw = max(cw, len(str(total))) colwidth[col] = cw self.stats["TOTAL"][col] = total exts.append("TOTAL") for ext in exts: self.stats[ext]["ext"] = ext cols.insert(0, "ext") def printheader(): for col in cols: print "%*s" % (colwidth[col], col), print printheader() for ext in exts: for col in cols: value = self.stats[ext].get(col, "") print "%*s" % (colwidth[col], value), print printheader() # Another header at the bottom def main(): args = sys.argv[1:] if not args: args = [os.curdir] s = Stats() s.statargs(args) s.report() if __name__ == "__main__": main()
OS2World/APP-INTERNET-torpak_2
Tools/scripts/byext.py
Python
mit
3,894
package com.ocdsoft.bacta.swg.shared.localization; /** * Created by crush on 11/21/2015. */ public class LocalizedString { }
bacta/pre-cu
src/main/java/com/ocdsoft/bacta/swg/shared/localization/LocalizedString.java
Java
mit
128