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 |
|---|---|---|---|---|---|
'use strict';
describe('angular', function() {
var element;
afterEach(function(){
dealoc(element);
});
describe('case', function() {
it('should change case', function() {
expect(lowercase('ABC90')).toEqual('abc90');
expect(manualLowercase('ABC90')).toEqual('abc90');
expect(uppercase('abc90')).toEqual('ABC90');
expect(manualUppercase('abc90')).toEqual('ABC90');
});
});
describe("copy", function() {
it("should return same object", function () {
var obj = {};
var arr = [];
expect(copy({}, obj)).toBe(obj);
expect(copy([], arr)).toBe(arr);
});
it("should copy Date", function() {
var date = new Date(123);
expect(copy(date) instanceof Date).toBeTruthy();
expect(copy(date).getTime()).toEqual(123);
expect(copy(date) === date).toBeFalsy();
});
it("should deeply copy an array into an existing array", function() {
var src = [1, {name:"value"}];
var dst = [{key:"v"}];
expect(copy(src, dst)).toBe(dst);
expect(dst).toEqual([1, {name:"value"}]);
expect(dst[1]).toEqual({name:"value"});
expect(dst[1]).not.toBe(src[1]);
});
it("should deeply copy an array into a new array", function() {
var src = [1, {name:"value"}];
var dst = copy(src);
expect(src).toEqual([1, {name:"value"}]);
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
expect(dst[1]).not.toBe(src[1]);
});
it('should copy empty array', function() {
var src = [];
var dst = [{key: "v"}];
expect(copy(src, dst)).toEqual([]);
expect(dst).toEqual([]);
});
it("should deeply copy an object into an existing object", function() {
var src = {a:{name:"value"}};
var dst = {b:{key:"v"}};
expect(copy(src, dst)).toBe(dst);
expect(dst).toEqual({a:{name:"value"}});
expect(dst.a).toEqual(src.a);
expect(dst.a).not.toBe(src.a);
});
it("should deeply copy an object into an existing object", function() {
var src = {a:{name:"value"}};
var dst = copy(src, dst);
expect(src).toEqual({a:{name:"value"}});
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
expect(dst.a).toEqual(src.a);
expect(dst.a).not.toBe(src.a);
});
it("should copy primitives", function() {
expect(copy(null)).toEqual(null);
expect(copy('')).toBe('');
expect(copy('lala')).toBe('lala');
expect(copy(123)).toEqual(123);
expect(copy([{key:null}])).toEqual([{key:null}]);
});
it('should throw an exception if a Scope is being copied', inject(function($rootScope) {
expect(function() { copy($rootScope.$new()); }).
toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported.");
}));
it('should throw an exception if a Window is being copied', function() {
expect(function() { copy(window); }).
toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported.");
});
it('should throw an exception when source and destination are equivalent', function() {
var src, dst;
src = dst = {key: 'value'};
expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical.");
src = dst = [2, 4];
expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical.");
});
it('should not copy the private $$hashKey', function() {
var src,dst;
src = {};
hashKey(src);
dst = copy(src);
expect(hashKey(dst)).not.toEqual(hashKey(src));
});
it('should retain the previous $$hashKey', function() {
var src,dst,h;
src = {};
dst = {};
// force creation of a hashkey
h = hashKey(dst);
hashKey(src);
dst = copy(src,dst);
// make sure we don't copy the key
expect(hashKey(dst)).not.toEqual(hashKey(src));
// make sure we retain the old key
expect(hashKey(dst)).toEqual(h);
});
});
describe("extend", function() {
it('should not copy the private $$hashKey', function() {
var src,dst;
src = {};
dst = {};
hashKey(src);
dst = extend(dst,src);
expect(hashKey(dst)).not.toEqual(hashKey(src));
});
it('should retain the previous $$hashKey', function() {
var src,dst,h;
src = {};
dst = {};
h = hashKey(dst);
hashKey(src);
dst = extend(dst,src);
// make sure we don't copy the key
expect(hashKey(dst)).not.toEqual(hashKey(src));
// make sure we retain the old key
expect(hashKey(dst)).toEqual(h);
});
it('should work when extending with itself', function() {
var src,dst,h;
dst = src = {};
h = hashKey(dst);
dst = extend(dst,src);
// make sure we retain the old key
expect(hashKey(dst)).toEqual(h);
});
});
describe('shallow copy', function() {
it('should make a copy', function() {
var original = {key:{}};
var copy = shallowCopy(original);
expect(copy).toEqual(original);
expect(copy.key).toBe(original.key);
});
it('should not copy $$ properties nor prototype properties', function() {
var original = {$$some: true, $$: true};
var clone = {};
expect(shallowCopy(original, clone)).toBe(clone);
expect(clone.$$some).toBeUndefined();
expect(clone.$$).toBeUndefined();
});
});
describe('elementHTML', function() {
it('should dump element', function() {
expect(startingTag('<div attr="123">something<span></span></div>')).
toEqual('<div attr="123">');
});
});
describe('equals', function() {
it('should return true if same object', function() {
var o = {};
expect(equals(o, o)).toEqual(true);
expect(equals(o, {})).toEqual(true);
expect(equals(1, '1')).toEqual(false);
expect(equals(1, '2')).toEqual(false);
});
it('should recurse into object', function() {
expect(equals({}, {})).toEqual(true);
expect(equals({name:'misko'}, {name:'misko'})).toEqual(true);
expect(equals({name:'misko', age:1}, {name:'misko'})).toEqual(false);
expect(equals({name:'misko'}, {name:'misko', age:1})).toEqual(false);
expect(equals({name:'misko'}, {name:'adam'})).toEqual(false);
expect(equals(['misko'], ['misko'])).toEqual(true);
expect(equals(['misko'], ['adam'])).toEqual(false);
expect(equals(['misko'], ['misko', 'adam'])).toEqual(false);
});
it('should ignore undefined member variables during comparison', function() {
var obj1 = {name: 'misko'},
obj2 = {name: 'misko', undefinedvar: undefined};
expect(equals(obj1, obj2)).toBe(true);
expect(equals(obj2, obj1)).toBe(true);
});
it('should ignore $ member variables', function() {
expect(equals({name:'misko', $id:1}, {name:'misko', $id:2})).toEqual(true);
expect(equals({name:'misko'}, {name:'misko', $id:2})).toEqual(true);
expect(equals({name:'misko', $id:1}, {name:'misko'})).toEqual(true);
});
it('should ignore functions', function() {
expect(equals({func: function() {}}, {bar: function() {}})).toEqual(true);
});
it('should work well with nulls', function() {
expect(equals(null, '123')).toBe(false);
expect(equals('123', null)).toBe(false);
var obj = {foo:'bar'};
expect(equals(null, obj)).toBe(false);
expect(equals(obj, null)).toBe(false);
expect(equals(null, null)).toBe(true);
});
it('should work well with undefined', function() {
expect(equals(undefined, '123')).toBe(false);
expect(equals('123', undefined)).toBe(false);
var obj = {foo:'bar'};
expect(equals(undefined, obj)).toBe(false);
expect(equals(obj, undefined)).toBe(false);
expect(equals(undefined, undefined)).toBe(true);
});
it('should treat two NaNs as equal', function() {
expect(equals(NaN, NaN)).toBe(true);
});
it('should compare Scope instances only by identity', inject(function($rootScope) {
var scope1 = $rootScope.$new(),
scope2 = $rootScope.$new();
expect(equals(scope1, scope1)).toBe(true);
expect(equals(scope1, scope2)).toBe(false);
expect(equals($rootScope, scope1)).toBe(false);
expect(equals(undefined, scope1)).toBe(false);
}));
it('should compare Window instances only by identity', function() {
expect(equals(window, window)).toBe(true);
expect(equals(window, window.parent)).toBe(false);
expect(equals(window, undefined)).toBe(false);
});
it('should compare dates', function() {
expect(equals(new Date(0), new Date(0))).toBe(true);
expect(equals(new Date(0), new Date(1))).toBe(false);
expect(equals(new Date(0), 0)).toBe(false);
expect(equals(0, new Date(0))).toBe(false);
});
it('should correctly test for keys that are present on Object.prototype', function() {
// MS IE8 just doesn't work for this kind of thing, since "for ... in" doesn't return
// things like hasOwnProperty even if it is explicitly defined on the actual object!
if (msie<=8) return;
expect(equals({}, {hasOwnProperty: 1})).toBe(false);
expect(equals({}, {toString: null})).toBe(false);
});
});
describe('size', function() {
it('should return the number of items in an array', function() {
expect(size([])).toBe(0);
expect(size(['a', 'b', 'c'])).toBe(3);
});
it('should return the number of properties of an object', function() {
expect(size({})).toBe(0);
expect(size({a:1, b:'a', c:noop})).toBe(3);
});
it('should return the number of own properties of an object', function() {
var obj = inherit({protoProp: 'c', protoFn: noop}, {a:1, b:'a', c:noop});
expect(size(obj)).toBe(5);
expect(size(obj, true)).toBe(3);
});
it('should return the string length', function() {
expect(size('')).toBe(0);
expect(size('abc')).toBe(3);
});
it('should not rely on length property of an object to determine its size', function() {
expect(size({length:99})).toBe(1);
});
});
describe('parseKeyValue', function() {
it('should parse a string into key-value pairs', function() {
expect(parseKeyValue('')).toEqual({});
expect(parseKeyValue('simple=pair')).toEqual({simple: 'pair'});
expect(parseKeyValue('first=1&second=2')).toEqual({first: '1', second: '2'});
expect(parseKeyValue('escaped%20key=escaped%20value')).
toEqual({'escaped key': 'escaped value'});
expect(parseKeyValue('emptyKey=')).toEqual({emptyKey: ''});
expect(parseKeyValue('flag1&key=value&flag2')).
toEqual({flag1: true, key: 'value', flag2: true});
});
it('should ignore key values that are not valid URI components', function() {
expect(function() { parseKeyValue('%'); }).not.toThrow();
expect(parseKeyValue('%')).toEqual({});
expect(parseKeyValue('invalid=%')).toEqual({ invalid: undefined });
expect(parseKeyValue('invalid=%&valid=good')).toEqual({ invalid: undefined, valid: 'good' });
});
it('should parse a string into key-value pairs with duplicates grouped in an array', function() {
expect(parseKeyValue('')).toEqual({});
expect(parseKeyValue('duplicate=pair')).toEqual({duplicate: 'pair'});
expect(parseKeyValue('first=1&first=2')).toEqual({first: ['1','2']});
expect(parseKeyValue('escaped%20key=escaped%20value&&escaped%20key=escaped%20value2')).
toEqual({'escaped key': ['escaped value','escaped value2']});
expect(parseKeyValue('flag1&key=value&flag1')).
toEqual({flag1: [true,true], key: 'value'});
expect(parseKeyValue('flag1&flag1=value&flag1=value2&flag1')).
toEqual({flag1: [true,'value','value2',true]});
});
});
describe('toKeyValue', function() {
it('should serialize key-value pairs into string', function() {
expect(toKeyValue({})).toEqual('');
expect(toKeyValue({simple: 'pair'})).toEqual('simple=pair');
expect(toKeyValue({first: '1', second: '2'})).toEqual('first=1&second=2');
expect(toKeyValue({'escaped key': 'escaped value'})).
toEqual('escaped%20key=escaped%20value');
expect(toKeyValue({emptyKey: ''})).toEqual('emptyKey=');
});
it('should serialize true values into flags', function() {
expect(toKeyValue({flag1: true, key: 'value', flag2: true})).toEqual('flag1&key=value&flag2');
});
it('should serialize duplicates into duplicate param strings', function() {
expect(toKeyValue({key: [323,'value',true]})).toEqual('key=323&key=value&key');
expect(toKeyValue({key: [323,'value',true, 1234]})).
toEqual('key=323&key=value&key&key=1234');
});
});
describe('forEach', function() {
it('should iterate over *own* object properties', function() {
function MyObj() {
this.bar = 'barVal';
this.baz = 'bazVal';
}
MyObj.prototype.foo = 'fooVal';
var obj = new MyObj(),
log = [];
forEach(obj, function(value, key) { log.push(key + ':' + value)});
expect(log).toEqual(['bar:barVal', 'baz:bazVal']);
});
it('should handle JQLite and jQuery objects like arrays', function() {
var jqObject = jqLite("<p><span>s1</span><span>s2</span></p>").find("span"),
log = [];
forEach(jqObject, function(value, key) { log.push(key + ':' + value.innerHTML)});
expect(log).toEqual(['0:s1', '1:s2']);
});
it('should handle NodeList objects like arrays', function() {
var nodeList = jqLite("<p><span>a</span><span>b</span><span>c</span></p>")[0].childNodes,
log = [];
forEach(nodeList, function(value, key) { log.push(key + ':' + value.innerHTML)});
expect(log).toEqual(['0:a', '1:b', '2:c']);
});
it('should handle HTMLCollection objects like arrays', function() {
document.body.innerHTML = "<p>" +
"<a name='x'>a</a>" +
"<a name='y'>b</a>" +
"<a name='x'>c</a>" +
"</p>";
var htmlCollection = document.getElementsByName('x'),
log = [];
forEach(htmlCollection, function(value, key) { log.push(key + ':' + value.innerHTML)});
expect(log).toEqual(['0:a', '1:c']);
});
it('should handle arguments objects like arrays', function() {
var args,
log = [];
(function(){ args = arguments}('a', 'b', 'c'));
forEach(args, function(value, key) { log.push(key + ':' + value)});
expect(log).toEqual(['0:a', '1:b', '2:c']);
});
it('should handle objects with length property as objects', function() {
var obj = {
'foo' : 'bar',
'length': 2
},
log = [];
forEach(obj, function(value, key) { log.push(key + ':' + value)});
expect(log).toEqual(['foo:bar', 'length:2']);
});
it('should handle objects of custom types with length property as objects', function() {
function CustomType() {
this.length = 2;
this.foo = 'bar'
}
var obj = new CustomType(),
log = [];
forEach(obj, function(value, key) { log.push(key + ':' + value)});
expect(log).toEqual(['length:2', 'foo:bar']);
});
});
describe('sortedKeys', function() {
it('should collect keys from object', function() {
expect(sortedKeys({c:0, b:0, a:0})).toEqual(['a', 'b', 'c']);
});
});
describe('encodeUriSegment', function() {
it('should correctly encode uri segment and not encode chars defined as pchar set in rfc3986',
function() {
//don't encode alphanum
expect(encodeUriSegment('asdf1234asdf')).
toEqual('asdf1234asdf');
//don't encode unreserved'
expect(encodeUriSegment("-_.!~*'() -_.!~*'()")).
toEqual("-_.!~*'()%20-_.!~*'()");
//don't encode the rest of pchar'
expect(encodeUriSegment(':@&=+$, :@&=+$,')).
toEqual(':@&=+$,%20:@&=+$,');
//encode '/', ';' and ' ''
expect(encodeUriSegment('/; /;')).
toEqual('%2F%3B%20%2F%3B');
});
});
describe('encodeUriQuery', function() {
it('should correctly encode uri query and not encode chars defined as pchar set in rfc3986',
function() {
//don't encode alphanum
expect(encodeUriQuery('asdf1234asdf')).
toEqual('asdf1234asdf');
//don't encode unreserved
expect(encodeUriQuery("-_.!~*'() -_.!~*'()")).
toEqual("-_.!~*'()+-_.!~*'()");
//don't encode the rest of pchar
expect(encodeUriQuery(':@$, :@$,')).
toEqual(':@$,+:@$,');
//encode '&', ';', '=', '+', and '#'
expect(encodeUriQuery('&;=+# &;=+#')).
toEqual('%26%3B%3D%2B%23+%26%3B%3D%2B%23');
//encode ' ' as '+'
expect(encodeUriQuery(' ')).
toEqual('++');
//encode ' ' as '%20' when a flag is used
expect(encodeUriQuery(' ', true)).
toEqual('%20%20');
//do not encode `null` as '+' when flag is used
expect(encodeUriQuery('null', true)).
toEqual('null');
//do not encode `null` with no flag
expect(encodeUriQuery('null')).
toEqual('null');
});
});
describe('angularInit', function() {
var bootstrapSpy;
var element;
beforeEach(function() {
element = {
getElementById: function (id) {
return element.getElementById[id] || [];
},
querySelectorAll: function(arg) {
return element.querySelectorAll[arg] || [];
},
getAttribute: function(name) {
return element[name];
}
};
bootstrapSpy = jasmine.createSpy('bootstrapSpy');
});
it('should do nothing when not found', function() {
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).not.toHaveBeenCalled();
});
it('should look for ngApp directive as attr', function() {
var appElement = jqLite('<div ng-app="ABC"></div>')[0];
element.querySelectorAll['[ng-app]'] = [appElement];
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should look for ngApp directive in id', function() {
var appElement = jqLite('<div id="ng-app" data-ng-app="ABC"></div>')[0];
jqLite(document.body).append(appElement);
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should look for ngApp directive in className', function() {
var appElement = jqLite('<div data-ng-app="ABC"></div>')[0];
element.querySelectorAll['.ng\\:app'] = [appElement];
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should look for ngApp directive using querySelectorAll', function() {
var appElement = jqLite('<div x-ng-app="ABC"></div>')[0];
element.querySelectorAll['[ng\\:app]'] = [ appElement ];
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should bootstrap using class name', function() {
var appElement = jqLite('<div class="ng-app: ABC;"></div>')[0];
angularInit(jqLite('<div></div>').append(appElement)[0], bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should bootstrap anonymously', function() {
var appElement = jqLite('<div x-ng-app></div>')[0];
element.querySelectorAll['[x-ng-app]'] = [ appElement ];
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []);
});
it('should bootstrap anonymously using class only', function() {
var appElement = jqLite('<div class="ng-app"></div>')[0];
angularInit(jqLite('<div></div>').append(appElement)[0], bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []);
});
it('should bootstrap if the annotation is on the root element', function() {
var appElement = jqLite('<div class="ng-app"></div>')[0];
angularInit(appElement, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []);
});
it('should complain if app module cannot be found', function() {
var appElement = jqLite('<div ng-app="doesntexist"></div>')[0];
expect(function() {
angularInit(appElement, bootstrap);
}).toThrowMatching(
/\[\$injector:modulerr] Failed to instantiate module doesntexist due to:\n.*\[\$injector:nomod] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it\./
);
});
});
describe('angular service', function() {
it('should override services', function() {
module(function($provide){
$provide.value('fake', 'old');
$provide.value('fake', 'new');
});
inject(function(fake) {
expect(fake).toEqual('new');
});
});
it('should inject dependencies specified by $inject and ignore function argument name', function() {
expect(angular.injector([function($provide){
$provide.factory('svc1', function() { return 'svc1'; });
$provide.factory('svc2', ['svc1', function(s) { return 'svc2-' + s; }]);
}]).get('svc2')).toEqual('svc2-svc1');
});
});
describe('isDate', function() {
it('should return true for Date object', function() {
expect(isDate(new Date())).toBe(true);
});
it('should return false for non Date objects', function() {
expect(isDate([])).toBe(false);
expect(isDate('')).toBe(false);
expect(isDate(23)).toBe(false);
expect(isDate({})).toBe(false);
});
});
describe('compile', function() {
it('should link to existing node and create scope', inject(function($rootScope, $compile) {
var template = angular.element('<div>{{greeting = "hello world"}}</div>');
element = $compile(template)($rootScope);
$rootScope.$digest();
expect(template.text()).toEqual('hello world');
expect($rootScope.greeting).toEqual('hello world');
}));
it('should link to existing node and given scope', inject(function($rootScope, $compile) {
var template = angular.element('<div>{{greeting = "hello world"}}</div>');
element = $compile(template)($rootScope);
$rootScope.$digest();
expect(template.text()).toEqual('hello world');
}));
it('should link to new node and given scope', inject(function($rootScope, $compile) {
var template = jqLite('<div>{{greeting = "hello world"}}</div>');
var compile = $compile(template);
var templateClone = template.clone();
element = compile($rootScope, function(clone){
templateClone = clone;
});
$rootScope.$digest();
expect(template.text()).toEqual('{{greeting = "hello world"}}');
expect(element.text()).toEqual('hello world');
expect(element).toEqual(templateClone);
expect($rootScope.greeting).toEqual('hello world');
}));
it('should link to cloned node and create scope', inject(function($rootScope, $compile) {
var template = jqLite('<div>{{greeting = "hello world"}}</div>');
element = $compile(template)($rootScope, noop);
$rootScope.$digest();
expect(template.text()).toEqual('{{greeting = "hello world"}}');
expect(element.text()).toEqual('hello world');
expect($rootScope.greeting).toEqual('hello world');
}));
});
describe('nodeName_', function() {
it('should correctly detect node name with "namespace" when xmlns is defined', function() {
var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' +
'<ngtest:foo ngtest:attr="bar"></ngtest:foo>' +
'</div>')[0];
expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO');
expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar');
});
if (!msie || msie >= 9) {
it('should correctly detect node name with "namespace" when xmlns is NOT defined', function() {
var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' +
'<ngtest:foo ngtest:attr="bar"></ng-test>' +
'</div>')[0];
expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO');
expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar');
});
}
});
describe('nextUid()', function() {
it('should return new id per call', function() {
var seen = {};
var count = 100;
while(count--) {
var current = nextUid();
expect(current.match(/[\d\w]+/)).toBeTruthy();
expect(seen[current]).toBeFalsy();
seen[current] = true;
}
});
});
describe('version', function() {
it('version should have full/major/minor/dot/codeName properties', function() {
expect(version).toBeDefined();
expect(version.full).toBe('"NG_VERSION_FULL"');
expect(version.major).toBe("NG_VERSION_MAJOR");
expect(version.minor).toBe("NG_VERSION_MINOR");
expect(version.dot).toBe("NG_VERSION_DOT");
expect(version.codeName).toBe('"NG_VERSION_CODENAME"');
});
});
describe('bootstrap', function() {
it('should bootstrap app', function(){
var element = jqLite('<div>{{1+2}}</div>');
var injector = angular.bootstrap(element);
expect(injector).toBeDefined();
expect(element.injector()).toBe(injector);
dealoc(element);
});
it("should complain if app module can't be found", function() {
var element = jqLite('<div>{{1+2}}</div>');
expect(function() {
angular.bootstrap(element, ['doesntexist']);
}).toThrowMatching(
/\[\$injector:modulerr\] Failed to instantiate module doesntexist due to:\n.*\[\$injector:nomod\] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it\./);
expect(element.html()).toBe('{{1+2}}');
dealoc(element);
});
describe('deferred bootstrap', function() {
var originalName = window.name,
element;
beforeEach(function() {
window.name = '';
element = jqLite('<div>{{1+2}}</div>');
});
afterEach(function() {
dealoc(element);
window.name = originalName;
});
it('should wait for extra modules', function() {
window.name = 'NG_DEFER_BOOTSTRAP!';
angular.bootstrap(element);
expect(element.html()).toBe('{{1+2}}');
angular.resumeBootstrap();
expect(element.html()).toBe('3');
expect(window.name).toEqual('');
});
it('should load extra modules', function() {
element = jqLite('<div>{{1+2}}</div>');
window.name = 'NG_DEFER_BOOTSTRAP!';
var bootstrapping = jasmine.createSpy('bootstrapping');
angular.bootstrap(element, [bootstrapping]);
expect(bootstrapping).not.toHaveBeenCalled();
expect(element.injector()).toBeUndefined();
angular.module('addedModule', []).value('foo', 'bar');
angular.resumeBootstrap(['addedModule']);
expect(bootstrapping).toHaveBeenCalledOnce();
expect(element.injector().get('foo')).toEqual('bar');
});
it('should not defer bootstrap without window.name cue', function() {
angular.bootstrap(element, []);
angular.module('addedModule', []).value('foo', 'bar');
expect(function() {
element.injector().get('foo');
}).toThrow('[$injector:unpr] Unknown provider: fooProvider <- foo');
expect(element.injector().get('$http')).toBeDefined();
});
it('should restore the original window.name after bootstrap', function() {
window.name = 'NG_DEFER_BOOTSTRAP!my custom name';
angular.bootstrap(element);
expect(element.html()).toBe('{{1+2}}');
angular.resumeBootstrap();
expect(element.html()).toBe('3');
expect(window.name).toEqual('my custom name');
});
});
});
describe('startingElementHtml', function(){
it('should show starting element tag only', function(){
expect(startingTag('<ng-abc x="2A"><div>text</div></ng-abc>')).
toBe('<ng-abc x="2A">');
});
});
describe('startingTag', function() {
it('should allow passing in Nodes instead of Elements', function() {
var txtNode = document.createTextNode('some text');
expect(startingTag(txtNode)).toBe('some text');
});
});
describe('snake_case', function(){
it('should convert to snake_case', function() {
expect(snake_case('ABC')).toEqual('a_b_c');
expect(snake_case('alanBobCharles')).toEqual('alan_bob_charles');
});
});
describe('fromJson', function() {
it('should delegate to JSON.parse', function() {
var spy = spyOn(JSON, 'parse').andCallThrough();
expect(fromJson('{}')).toEqual({});
expect(spy).toHaveBeenCalled();
});
});
describe('toJson', function() {
it('should delegate to JSON.stringify', function() {
var spy = spyOn(JSON, 'stringify').andCallThrough();
expect(toJson({})).toEqual('{}');
expect(spy).toHaveBeenCalled();
});
it('should format objects pretty', function() {
expect(toJson({a: 1, b: 2}, true)).
toBeOneOf('{\n "a": 1,\n "b": 2\n}', '{\n "a":1,\n "b":2\n}');
expect(toJson({a: {b: 2}}, true)).
toBeOneOf('{\n "a": {\n "b": 2\n }\n}', '{\n "a":{\n "b":2\n }\n}');
});
it('should not serialize properties starting with $', function() {
expect(toJson({$few: 'v', $$some:'value'}, false)).toEqual('{}');
});
it('should not serialize $window object', function() {
expect(toJson(window)).toEqual('"$WINDOW"');
});
it('should not serialize $document object', function() {
expect(toJson(document)).toEqual('"$DOCUMENT"');
});
it('should not serialize scope instances', inject(function($rootScope) {
expect(toJson({key: $rootScope})).toEqual('{"key":"$SCOPE"}');
}));
});
});
| rpanjwani/angular.js | test/AngularSpec.js | JavaScript | mit | 30,438 |
package corehttp
// TODO: move to IPNS
const WebUIPath = "/ipfs/QmXc9raDM1M5G5fpBnVyQ71vR4gbnskwnB9iMEzBuLgvoZ"
// this is a list of all past webUI paths.
var WebUIPaths = []string{
WebUIPath,
"/ipfs/QmenEBWcAk3tN94fSKpKFtUMwty1qNwSYw3DMDFV6cPBXA",
"/ipfs/QmUnXcWZC5Ve21gUseouJsH5mLAyz5JPp8aHsg8qVUUK8e",
"/ipfs/QmSDgpiHco5yXdyVTfhKxr3aiJ82ynz8V14QcGKicM3rVh",
"/ipfs/QmRuvWJz1Fc8B9cTsAYANHTXqGmKR9DVfY5nvMD1uA2WQ8",
"/ipfs/QmQLXHs7K98JNQdWrBB2cQLJahPhmupbDjRuH1b9ibmwVa",
"/ipfs/QmXX7YRpU7nNBKfw75VG7Y1c3GwpSAGHRev67XVPgZFv9R",
"/ipfs/QmXdu7HWdV6CUaUabd9q2ZeA4iHZLVyDRj3Gi4dsJsWjbr",
"/ipfs/QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w",
"/ipfs/QmSHDxWsMPuJQKWmVA1rB5a3NX2Eme5fPqNb63qwaqiqSp",
"/ipfs/QmctngrQAt9fjpQUZr7Bx3BsXUcif52eZGTizWhvcShsjz",
"/ipfs/QmS2HL9v5YeKgQkkWMvs1EMnFtUowTEdFfSSeMT4pos1e6",
"/ipfs/QmR9MzChjp1MdFWik7NjEjqKQMzVmBkdK3dz14A6B5Cupm",
"/ipfs/QmRyWyKWmphamkMRnJVjUTzSFSAAZowYP4rnbgnfMXC9Mr",
"/ipfs/QmU3o9bvfenhTKhxUakbYrLDnZU7HezAVxPM6Ehjw9Xjqy",
"/ipfs/QmPhnvn747LqwPYMJmQVorMaGbMSgA7mRRoyyZYz3DoZRQ",
}
var WebUIOption = RedirectOption("webui", WebUIPath)
| OpenBazaar/openbazaar-go | vendor/github.com/ipfs/go-ipfs/core/corehttp/webui.go | GO | mit | 1,107 |
<?php
/* SonataAdminBundle:CRUD:base_acl_macro.html.twig */
class __TwigTemplate_f7bb38229ed8df4e133506255cce57f53a109aac1f79d839de0cea8756a1aaf0 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 11
echo "
";
}
// line 12
public function getrender_form($__form__ = null, $__permissions__ = null, $__td_type__ = null, $__admin__ = null, $__admin_pool__ = null, $__object__ = null)
{
$context = $this->env->mergeGlobals(array(
"form" => $__form__,
"permissions" => $__permissions__,
"td_type" => $__td_type__,
"admin" => $__admin__,
"admin_pool" => $__admin_pool__,
"object" => $__object__,
));
$blocks = array();
ob_start();
try {
// line 13
echo " <form class=\"form-horizontal\"
action=\"";
// line 14
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "generateUrl", array(0 => "acl", 1 => array("id" => $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "id", array(0 => (isset($context["object"]) ? $context["object"] : $this->getContext($context, "object"))), "method"), "uniqid" => $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "uniqid", array()), "subclass" => $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "request", array()), "get", array(0 => "subclass"), "method"))), "method"), "html", null, true);
echo "\" ";
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype');
echo "
method=\"POST\"
";
// line 16
if ( !$this->getAttribute((isset($context["admin_pool"]) ? $context["admin_pool"] : $this->getContext($context, "admin_pool")), "getOption", array(0 => "html5_validate"), "method")) {
echo "novalidate=\"novalidate\"";
}
// line 17
echo " >
";
// line 18
if ((twig_length_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "vars", array()), "errors", array())) > 0)) {
// line 19
echo " <div class=\"sonata-ba-form-error\">
";
// line 20
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'errors');
echo "
</div>
";
}
// line 23
echo "
<div class=\"box box-success\">
<div class=\"body table-responsive no-padding\">
<table class=\"table\">
<colgroup>
<col style=\"width: 100%;\"/>
";
// line 29
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["permissions"]) ? $context["permissions"] : $this->getContext($context, "permissions")));
foreach ($context['_seq'] as $context["_key"] => $context["permission"]) {
// line 30
echo " <col/>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['permission'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 32
echo " </colgroup>
";
// line 34
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "children", array()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
foreach ($context['_seq'] as $context["_key"] => $context["child"]) {
if (($this->getAttribute($this->getAttribute($context["child"], "vars", array()), "name", array()) != "_token")) {
// line 35
echo " ";
if ((($this->getAttribute($context["loop"], "index0", array()) == 0) || (($this->getAttribute($context["loop"], "index0", array()) % 10) == 0))) {
// line 36
echo " <tr>
<th>";
// line 37
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["td_type"]) ? $context["td_type"] : $this->getContext($context, "td_type")), array(), "SonataAdminBundle"), "html", null, true);
echo "</th>
";
// line 38
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["permissions"]) ? $context["permissions"] : $this->getContext($context, "permissions")));
foreach ($context['_seq'] as $context["_key"] => $context["permission"]) {
// line 39
echo " <th class=\"text-right\">";
echo twig_escape_filter($this->env, $context["permission"], "html", null, true);
echo "</th>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['permission'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 41
echo " </tr>
";
}
// line 43
echo "
<tr>
<td>
";
// line 46
$context["typeChild"] = (($this->getAttribute($context["child"], "role", array(), "array", true, true)) ? ($this->getAttribute($context["child"], "role", array(), "array")) : ($this->getAttribute($context["child"], "user", array(), "array")));
// line 47
echo " ";
echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["typeChild"]) ? $context["typeChild"] : $this->getContext($context, "typeChild")), "vars", array()), "value", array()), "html", null, true);
echo "
";
// line 48
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["typeChild"]) ? $context["typeChild"] : $this->getContext($context, "typeChild")), 'widget');
echo "
</td>
";
// line 50
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["permissions"]) ? $context["permissions"] : $this->getContext($context, "permissions")));
foreach ($context['_seq'] as $context["_key"] => $context["permission"]) {
// line 51
echo " <td class=\"text-right\">";
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($context["child"], $context["permission"], array(), "array"), 'widget', array("label" => false));
echo "</td>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['permission'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 53
echo " </tr>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['child'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 55
echo " </table>
</div>
</div>
";
// line 59
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "_token", array()), 'row');
echo "
<div class=\"well well-small form-actions\">
<input class=\"btn btn-primary\" type=\"submit\" name=\"btn_create_and_edit\" value=\"";
// line 62
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("btn_update_acl", array(), "SonataAdminBundle"), "html", null, true);
echo "\">
</div>
</form>
";
} catch (Exception $e) {
ob_end_clean();
throw $e;
}
return ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
}
public function getTemplateName()
{
return "SonataAdminBundle:CRUD:base_acl_macro.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 182 => 62, 176 => 59, 170 => 55, 159 => 53, 150 => 51, 146 => 50, 141 => 48, 136 => 47, 134 => 46, 129 => 43, 125 => 41, 116 => 39, 112 => 38, 108 => 37, 105 => 36, 102 => 35, 91 => 34, 87 => 32, 80 => 30, 76 => 29, 68 => 23, 62 => 20, 59 => 19, 57 => 18, 54 => 17, 50 => 16, 43 => 14, 40 => 13, 24 => 12, 19 => 11,);
}
}
| chicho2114/Proy_Frameworks | app/cache/dev/twig/f7/bb/38229ed8df4e133506255cce57f53a109aac1f79d839de0cea8756a1aaf0.php | PHP | mit | 11,223 |
/*****************************************************************************
* This file is part of the Prolog Development Tool (PDT)
*
* Author: Lukas Degener (among others)
* WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start
* Mail: pdt@lists.iai.uni-bonn.de
* Copyright (C): 2004-2012, CS Dept. III, University of Bonn
*
* All rights reserved. This program is made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
****************************************************************************/
package org.cs3.prolog.connector.cterm;
import org.cs3.prolog.connector.internal.cterm.parser.ASTNode;
/**
* Represents a Prolog string.
*/
public class CString extends CTerm {
public CString(ASTNode node) {
super(node);
}
}
| TeamSPoon/logicmoo_base | prolog/logicmoo/pdt_server/prolog.connector/src/org/cs3/prolog/connector/cterm/CString.java | Java | mit | 870 |
//
// Created by eran on 01/04/2015.
//
#include <unordered_set>
#include "fakeit/Invocation.hpp"
namespace fakeit {
struct ActualInvocationsContainer {
virtual void clear() = 0;
virtual ~ActualInvocationsContainer() NO_THROWS { }
};
struct ActualInvocationsSource {
virtual void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const = 0;
virtual ~ActualInvocationsSource() NO_THROWS { }
};
struct InvocationsSourceProxy : public ActualInvocationsSource {
InvocationsSourceProxy(ActualInvocationsSource *inner) :
_inner(inner) {
}
void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const override {
_inner->getActualInvocations(into);
}
private:
std::shared_ptr<ActualInvocationsSource> _inner;
};
struct UnverifiedInvocationsSource : public ActualInvocationsSource {
UnverifiedInvocationsSource(InvocationsSourceProxy decorated) : _decorated(decorated) {
}
void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const override {
std::unordered_set<fakeit::Invocation *> all;
_decorated.getActualInvocations(all);
for (fakeit::Invocation *i : all) {
if (!i->isVerified()) {
into.insert(i);
}
}
}
private:
InvocationsSourceProxy _decorated;
};
struct AggregateInvocationsSource : public ActualInvocationsSource {
AggregateInvocationsSource(std::vector<ActualInvocationsSource *> &sources) : _sources(sources) {
}
void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const override {
std::unordered_set<fakeit::Invocation *> tmp;
for (ActualInvocationsSource *source : _sources) {
source->getActualInvocations(tmp);
}
filter(tmp, into);
}
protected:
bool shouldInclude(fakeit::Invocation *) const {
return true;
}
private:
std::vector<ActualInvocationsSource *> _sources;
void filter(std::unordered_set<Invocation *> &source, std::unordered_set<Invocation *> &target) const {
for (Invocation *i:source) {
if (shouldInclude(i)) {
target.insert(i);
}
}
}
};
}
| helmesjo/hello-ci | src/external/fakeit/fakeit-repo/include/fakeit/ActualInvocationsSource.hpp | C++ | mit | 2,462 |
#!/usr/bin/python
# Copyright 2014 Steven Watanabe
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or https://www.bfgroup.xyz/b2/LICENSE.txt)
# Test the handling of toolset.add-requirements
import BoostBuild
t = BoostBuild.Tester(pass_toolset=0, ignore_toolset_requirements=False)
t.write('jamroot.jam', '''
import toolset ;
import errors ;
rule test-rule ( properties * )
{
return <define>TEST_INDIRECT_CONDITIONAL ;
}
toolset.add-requirements
<define>TEST_MACRO
<conditional>@test-rule
<link>shared:<define>TEST_CONDITIONAL
;
rule check-requirements ( target : sources * : properties * )
{
local macros = TEST_MACRO TEST_CONDITIONAL TEST_INDIRECT_CONDITIONAL ;
for local m in $(macros)
{
if ! <define>$(m) in $(properties)
{
errors.error $(m) not defined ;
}
}
}
make test : : @check-requirements ;
''')
t.run_build_system()
t.cleanup()
| davehorton/drachtio-server | deps/boost_1_77_0/tools/build/test/toolset_requirements.py | Python | mit | 933 |
/* Copyright (c) 2018 lib4j
*
* 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.
*
* You should have received a copy of The MIT License (MIT) along with this
* program. If not, see <http://opensource.org/licenses/MIT/>.
*/
package org.lib4j.test;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.junit.Assert;
import org.junit.ComparisonFailure;
import org.lib4j.xml.dom.DOMStyle;
import org.lib4j.xml.dom.DOMs;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlunit.builder.Input;
import org.xmlunit.diff.Comparison;
import org.xmlunit.diff.ComparisonListener;
import org.xmlunit.diff.ComparisonResult;
import org.xmlunit.diff.DOMDifferenceEngine;
import org.xmlunit.diff.DifferenceEngine;
public class AssertXml {
private XPath newXPath() {
final XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new SimpleNamespaceContext(prefixToNamespaceURI));
return xPath;
}
public static AssertXml compare(final Element controlElement, final Element testElement) {
final Map<String,String> prefixToNamespaceURI = new HashMap<>();
prefixToNamespaceURI.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
final NamedNodeMap attributes = controlElement.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
final Attr attribute = (Attr)attributes.item(i);
if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI()) && "xmlns".equals(attribute.getPrefix()))
prefixToNamespaceURI.put(attribute.getLocalName(), attribute.getNodeValue());
}
return new AssertXml(prefixToNamespaceURI, controlElement, testElement);
}
private final Map<String,String> prefixToNamespaceURI;
private final Element controlElement;
private final Element testElement;
private AssertXml(final Map<String,String> prefixToNamespaceURI, final Element controlElement, final Element testElement) {
if (!controlElement.getPrefix().equals(testElement.getPrefix()))
throw new IllegalArgumentException("Prefixes of control and test elements must be the same: " + controlElement.getPrefix() + " != " + testElement.getPrefix());
this.prefixToNamespaceURI = prefixToNamespaceURI;
this.controlElement = controlElement;
this.testElement = testElement;
}
public void addAttribute(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (!(node instanceof Element))
throw new UnsupportedOperationException("Only support addition of attributes to elements");
final Element target = (Element)node;
final int colon = name.indexOf(':');
final String namespaceURI = colon == -1 ? node.getNamespaceURI() : node.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
target.setAttributeNS(namespaceURI, name, value);
}
}
public void remove(final Element element, final String ... xpaths) throws XPathExpressionException {
for (final String xpath : xpaths) {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (node instanceof Attr) {
final Attr attribute = (Attr)node;
attribute.getOwnerElement().removeAttributeNode(attribute);
}
else {
node.getParentNode().removeChild(node);
}
}
}
}
public void replace(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (node instanceof Attr) {
final Attr attribute = (Attr)node;
if (name == null) {
attribute.setValue(value);
}
else {
final int colon = name.indexOf(':');
final String namespaceURI = colon == -1 ? attribute.getNamespaceURI() : attribute.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
final Element owner = attribute.getOwnerElement();
owner.removeAttributeNode(attribute);
owner.setAttributeNS(namespaceURI, name, value);
}
}
else {
throw new UnsupportedOperationException("Only support replacement of attribute values");
}
}
}
public void replace(final Element element, final String xpath, final String value) throws XPathExpressionException {
replace(element, xpath, null, value);
}
public void assertEqual() {
final String prefix = controlElement.getPrefix();
final String controlXml = DOMs.domToString(controlElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);
final String testXml = DOMs.domToString(testElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);
final Source controlSource = Input.fromString(controlXml).build();
final Source testSource = Input.fromString(testXml).build();
final DifferenceEngine diffEngine = new DOMDifferenceEngine();
diffEngine.addDifferenceListener(new ComparisonListener() {
@Override
public void comparisonPerformed(final Comparison comparison, final ComparisonResult result) {
final String controlXPath = comparison.getControlDetails().getXPath() == null ? null : comparison.getControlDetails().getXPath().replaceAll("/([^@])", "/" + prefix + ":$1");
if (controlXPath == null || controlXPath.matches("^.*\\/@[:a-z]+$") || controlXPath.contains("text()"))
return;
try {
Assert.assertEquals(controlXml, testXml);
}
catch (final ComparisonFailure e) {
final StackTraceElement[] stackTrace = e.getStackTrace();
int i;
for (i = 3; i < stackTrace.length; i++)
if (!stackTrace[i].getClassName().startsWith("org.xmlunit.diff"))
break;
final StackTraceElement[] filtered = new StackTraceElement[stackTrace.length - ++i];
System.arraycopy(stackTrace, i, filtered, 0, stackTrace.length - i);
e.setStackTrace(filtered);
throw e;
}
Assert.fail(comparison.toString());
}
});
diffEngine.compare(controlSource, testSource);
}
} | safris-src/org | lib4j/test/src/main/java/org/lib4j/test/AssertXml.java | Java | mit | 7,601 |
#include "src/OgreExternalTextureSourceManager.cpp"
#include "src/OgreFileSystem.cpp"
#include "src/OgreFont.cpp"
#include "src/OgreFontManager.cpp"
#include "src/OgreFrustum.cpp"
#include "src/OgreGpuProgram.cpp"
#include "src/OgreGpuProgramManager.cpp"
#include "src/OgreGpuProgramParams.cpp"
#include "src/OgreGpuProgramUsage.cpp"
#include "src/OgreHardwareBufferManager.cpp"
#include "src/OgreHardwareIndexBuffer.cpp"
#include "src/OgreHardwareOcclusionQuery.cpp"
#include "src/OgreHardwarePixelBuffer.cpp"
#include "src/OgreHardwareVertexBuffer.cpp"
#include "src/OgreHighLevelGpuProgram.cpp"
#include "src/OgreHighLevelGpuProgramManager.cpp"
#include "src/OgreImage.cpp"
#include "src/OgreInstanceBatch.cpp"
#include "src/OgreInstanceBatchHW.cpp"
#include "src/OgreInstanceBatchHW_VTF.cpp"
#include "src/OgreInstanceBatchShader.cpp"
#include "src/OgreInstanceBatchVTF.cpp"
#include "src/OgreInstancedGeometry.cpp"
#include "src/OgreInstancedEntity.cpp"
#include "src/OgreInstanceManager.cpp"
#include "src/OgreKeyFrame.cpp"
#include "src/OgreLight.cpp"
#include "src/OgreLodStrategy.cpp"
#include "src/OgreLodStrategyManager.cpp"
#include "src/OgreLog.cpp"
#include "src/OgreLogManager.cpp"
#include "src/OgreManualObject.cpp"
#include "src/OgreMaterial.cpp"
#include "src/OgreMaterialManager.cpp"
#include "src/OgreMaterialSerializer.cpp"
#include "src/OgreMath.cpp"
#include "src/OgreMatrix3.cpp"
#include "src/OgreMatrix4.cpp"
#include "src/OgreMemoryAllocatedObject.cpp"
#include "src/OgreMemoryNedAlloc.cpp"
| airgames/vuforia-gamekit-integration | Gamekit/compilation/OgreMain/compile_OgreMain_1.cpp | C++ | mit | 1,519 |
# frozen_string_literal: true
require_relative 'helper'
describe 'Digest class' do
it 'raises error with invalid digest_class' do
assert_raises ArgumentError do
Dalli::Client.new('foo', { expires_in: 10, digest_class: Object })
end
end
end
| mperham/dalli | test/test_digest_class.rb | Ruby | mit | 260 |
using UnityEngine;
using System.Collections;
using System.Runtime.Serialization;
namespace StrumpyShaderEditor
{
[DataContract(Namespace = "http://strumpy.net/ShaderEditor/")]
public abstract class ChannelReference {
[DataMember] private string nodeIdentifier;
[DataMember] private uint channelId;
public ChannelReference( string nodeIdentifier, uint channelId )
{
this.nodeIdentifier = nodeIdentifier;
this.channelId = channelId;
}
public string NodeIdentifier
{
get{ return nodeIdentifier; }
set{ nodeIdentifier = value; }
}
public uint ChannelId
{
get{ return channelId; }
}
}
} | ahito89/SSE | ShaderEditor/Assets/StrumpyShaderEditor/Editor/Graph/Nodes/Channels/ChannelReference.cs | C# | mit | 631 |
var partialsTemp = [
"login",
"profile"
];
exports.partialRender = function (req, res) {
var pageIndex = req.params[0];
if (partialsTemp.indexOf("" + pageIndex) > -1) {
res.render("partials/" + pageIndex, {});
} else {
res.render("common/404", {});
}
}; | ManGroup/jsEasy | controllers/partials.js | JavaScript | mit | 296 |
/*
* The MIT License
*
* Copyright 2015 Eduardo Weiland.
*
* 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.
*/
define(['knockout', 'grammar', 'productionrule', 'utils'], function(ko, Grammar, ProductionRule, utils) {
'use strict';
/**
* Encontra todos os símbolos não-terminais inalcançáveis dentro de uma gramática.
*
* @param {Grammar} grammar Gramática para ser verificada.
* @return {string[]} Lista de símbolos inalcançáveis.
*/
function findUnreachableSymbols(grammar) {
var unreachable = [],
nt = grammar.nonTerminalSymbols(),
s = grammar.productionStartSymbol();
for (var i = 0, l = nt.length; i < l; ++i) {
// Ignora símbolo de início de produção
if (nt[i] === s) {
continue;
}
var found = false;
for (var j = 0, k = nt.length; j < k && !found; ++j) {
if (i === j) {
// Ignora produções do próprio símbolo
continue;
}
var prods = grammar.getProductions(nt[j]);
for (var x = 0, y = prods.length; x < y; ++x) {
if (prods[x].indexOf(nt[i]) !== -1) {
found = true;
break;
}
}
}
if (!found) {
unreachable.push(nt[i]);
}
}
return unreachable;
}
function findSterileSymbols(grammar) {
var steriles = [],
rules = grammar.productionRules();
for (var i = 0, l = rules.length; i < l; ++i) {
var found = false,
left = rules[i].leftSide(),
right = rules[i].rightSide();
for (var j = 0, k = right.length; j < k && !found; ++j) {
if (right[j].indexOf(left) === -1) {
found = true;
break;
}
}
if (!found) {
steriles.push(left);
}
}
return steriles;
}
/**
* Substitui símbolos não terminais no começo de todas as produções pelas suas produções.
*
* @param {Grammar} grammar Gramática para ser modificada.
* @return {ProductionRule[]} Regras de produção modificadas.
*/
function replaceStartingSymbols(grammar) {
var rules = grammar.productionRules();
var nt = grammar.nonTerminalSymbols();
var s = grammar.productionStartSymbol();
for (var i = 0, l = rules.length; i < l; ++i) {
var left = rules[i].leftSide();
if (left === s) {
// Ignora produção inicial
continue;
}
var prods = rules[i].rightSide();
// Não usa cache do length porque o array é modificado internamente
for (var j = 0; j < prods.length; ++j) {
if ( (prods[j][0] === left) || (nt.indexOf(prods[j][0]) === -1) ) {
// Produção começa com o próprio símbolo não-terminal (recursivo) ou
// não começa com nenhum símbolo não-terminal, ignora as substituições
continue;
}
var otherProds = grammar.getProductions(prods[j][0]);
var rest = prods[j].substr(1);
for (var k = 0, m = otherProds.length; k < m; ++k) {
otherProds[k] = otherProds[k] + rest;
}
// Remove a produção que começa com não-terminal e adiciona as novas produções no lugar
prods.splice.apply(prods, [j--, 1].concat(otherProds));
}
}
return rules;
}
return {
/**
* Remove símbolos inúteis de uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática sem os simbolos inúteis.
*/
removeUselessSymbols: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var sterile = findSterileSymbols(newGrammar),
unreachable = findUnreachableSymbols(newGrammar),
useless = utils.arrayUnion(sterile, unreachable),
nt = newGrammar.nonTerminalSymbols();
// Remove os símbolos inalcançáveis...
newGrammar.nonTerminalSymbols(utils.arrayRemove(nt, utils.arrayUnion(sterile, unreachable)));
newGrammar.removeSymbolRules(useless);
// .. e as produções em que eles aparecem
var rules = newGrammar.productionRules();
for (var i = 0, l = rules.length; i < l; ++i) {
var right = rules[i].rightSide();
for (var j = 0, m = useless.length; j < m; ++j) {
for (var k = 0; k < right.length; ++k) {
if (right[k].indexOf(useless[j]) !== -1) {
right.splice(k--, 1);
}
}
}
rules[i].rightSide(utils.arrayUnique(right));
}
newGrammar.productionRules(rules);
return newGrammar;
},
/**
* Remove produções vazias de uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática sem as produções vazias.
*/
removeEmptyProductions: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var newStart;
var rules = newGrammar.productionRules();
for (var i = 0, l = rules.length; i < l; ++i) {
var left = rules[i].leftSide();
var right = rules[i].rightSide();
var emptyIndex = right.indexOf(ProductionRule.EPSILON);
if (emptyIndex === -1) {
// Essa regra não possui produção vazia, ignora e testa a próxima
continue;
}
if (left === newGrammar.productionStartSymbol()) {
// Início de produção pode gerar sentença vazia, então trata o caso especial
newStart = new ProductionRule(newGrammar, {
leftSide: left + "'",
rightSide: [left, ProductionRule.EPSILON]
});
}
// Encontra todas as outras regras que produzem esse símbolo e adiciona uma nova
// produção sem esse símbolo
for (var j = 0; j < l; ++j) {
var rightOther = rules[j].rightSide();
for (var k = 0, m = rightOther.length; k < m; ++k) {
if (rightOther[k].indexOf(left) !== -1) {
rightOther.push(rightOther[k].replace(new RegExp(left, 'g'), ''));
}
}
rules[j].rightSide(utils.arrayUnique(rightOther));
}
right.splice(emptyIndex, 1);
rules[i].rightSide(utils.arrayUnique(right));
}
if (newStart) {
rules.unshift(newStart);
newGrammar.productionStartSymbol(newStart.leftSide());
newGrammar.nonTerminalSymbols([newStart.leftSide()].concat(newGrammar.nonTerminalSymbols()));
}
newGrammar.productionRules(rules);
return newGrammar;
},
/**
* Fatora uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática fatorada.
*/
factor: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var rules = replaceStartingSymbols(newGrammar);
var newRules = [];
for (var i = 0; i < rules.length; ++i) {
var left = rules[i].leftSide();
var right = rules[i].rightSide();
var newRight = [];
var firstSymbolGrouped = {};
// Percorre todos as produções verificando quais precisam ser fatoradas
for (var j = 0, l = right.length; j < l; ++j) {
if (right[j].length === 1) {
// Produções com apenas um símbolo são deixadas como estão
newRight.push(right[j]);
}
else {
// Agrupa todas as produções que começam com o mesmo símbolo terminal
var firstSymbol = right[j][0];
if (!firstSymbolGrouped[firstSymbol]) {
firstSymbolGrouped[firstSymbol] = [];
}
firstSymbolGrouped[firstSymbol].push(right[j].substr(1));
}
}
// Adiciona a produção na mesma ordem que estava antes, antes das novas produções serem adicionadas
newRules.push(rules[i]);
for (var j in firstSymbolGrouped) {
if (firstSymbolGrouped[j].length > 1) {
// Mais de uma produção começando com o mesmo símbolo terminal
var newSymbol = newGrammar.createNonTerminalSymbol(left);
newRight.push(j + newSymbol);
newRules.push(new ProductionRule(newGrammar, {
leftSide: newSymbol,
rightSide: firstSymbolGrouped[j]
}));
}
else {
// Senão, é apenas uma produção (índice 0), mantém ela no mesmo lugar
newRight.push(j + firstSymbolGrouped[j][0]);
}
}
// Atualiza as produções para o símbolo existente
rules[i].rightSide(utils.arrayUnique(newRight));
}
newGrammar.productionRules(newRules);
return newGrammar;
},
/**
* Remove recursão à esquerda de uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática sem recursão à esquerda.
*/
removeLeftRecursion: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var rules = newGrammar.productionRules();
var newRules = [];
for (var i = 0, l = rules.length; i < l; ++i) {
var left = rules[i].leftSide();
var prods = rules[i].rightSide();
var recursives = [];
// Adiciona a produção na mesma ordem que estava antes, antes das nova produção ser adicionada
newRules.push(rules[i]);
// Não usa cache do length porque o array é modificado internamente
for (var j = 0; j < prods.length; ++j) {
if (prods[j][0] === left && prods[j].length > 1) {
// Encontrou produção recursiva, cria uma nova regra
var newSymbol = newGrammar.createNonTerminalSymbol(left);
recursives.push(newSymbol);
newRules.push(new ProductionRule(newGrammar, {
leftSide: newSymbol,
rightSide: [prods[j].substr(1) + newSymbol, ProductionRule.EPSILON]
}));
// Remove essa produção
prods.splice(j--, 1);
}
}
var newProds = [];
if (recursives.length === 0) {
newProds = prods.slice();
}
else {
for (var j = 0; j < prods.length; ++j) {
for (var k = 0; k < recursives.length; ++k) {
newProds.push(prods[j] + recursives[k]);
}
}
}
rules[i].rightSide(newProds);
}
newGrammar.productionRules(newRules);
return newGrammar;
}
};
});
| eduardoweiland/transformacoes-glc | app/js/transformations.js | JavaScript | mit | 13,493 |
/**
* Uploader implementation - with the Connection object in ExtJS 4
*
*/
Ext.define('MyApp.ux.panel.upload.uploader.ExtJsUploader', {
extend : 'MyApp.ux.panel.upload.uploader.AbstractXhrUploader',
requires : [ 'MyApp.ux.panel.upload.data.Connection' ],
config : {
/**
* @cfg {String} [method='PUT']
*
* The HTTP method to be used.
*/
method : 'PUT',
/**
* @cfg {Ext.data.Connection}
*
* If set, this connection object will be used when uploading files.
*/
connection : null
},
/**
* @property
* @private
*
* The connection object.
*/
conn : null,
/**
* @private
*
* Initializes and returns the connection object.
*
* @return {MyApp.ux.panel.upload.data.Connection}
*/
initConnection : function() {
var conn, url = this.url;
console.log('[ExtJsUploader initConnection params', this.params);
if (this.connection instanceof Ext.data.Connection) {
console.log('[ExtJsUploader] instanceof Connection');
conn = this.connection;
} else {
console.log('[ExtJsUploader] !! instanceof Connection');
if (this.params) {
url = Ext.urlAppend(url, Ext.urlEncode(this.params));
}
conn = Ext.create('MyApp.ux.panel.upload.data.Connection', {
disableCaching : true,
method : this.method,
url : url,
timeout : this.timeout,
defaultHeaders : {
'Content-Type' : this.contentType,
'X-Requested-With' : 'XMLHttpRequest'
}
});
}
return conn;
},
/**
* @protected
*/
initHeaders : function(item) {
console.log('[ExtJsUploader] initHeaders', item);
var headers = this.callParent(arguments);
headers['Content-Type'] = item.getType();
return headers;
},
/**
* Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#uploadItem}
*
* @param {MyApp.ux.panel.upload.Item}
* item
*/
uploadItem : function(item) {
console.log('ExtJsUploader uploadItem', item);
var file = item.getFileApiObject();
if (!file) {
return;
}
item.setUploading();
// tony
this.params = {
folder : item.getRemoteFolder()
};
this.conn = this.initConnection();
/*
* Passing the File object directly as the "rawData" option. Specs: https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#the-send()-method
* http://dev.w3.org/2006/webapi/FileAPI/#blob
*/
console.log('ExtJsUploader conn', this.conn);
this.conn.request({
scope : this,
headers : this.initHeaders(item),
rawData : file,
timeout : MyApp.Const.JAVASCRIPT_MAX_NUMBER, // tony
success : Ext.Function.bind(this.onUploadSuccess, this, [ item ], true),
failure : Ext.Function.bind(this.onUploadFailure, this, [ item ], true),
progress : Ext.Function.bind(this.onUploadProgress, this, [ item ], true)
});
},
/**
* Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#abortUpload}
*/
abortUpload : function() {
if (this.conn) {
/*
* If we don't suspend the events, the connection abortion will cause a failure event.
*/
this.suspendEvents();
console.log('abort conn', conn);
this.conn.abort();
this.resumeEvents();
}
}
});
| cwtuan/ExtJSTutorial-HiCloud | src/main/webapp/app/ux/panel/upload/uploader/ExtJsUploader.js | JavaScript | mit | 3,140 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using NSubstitute;
using Nancy;
using Nancy.Routing;
using PactNet.Logging;
using PactNet.Mocks.MockHttpService;
using PactNet.Mocks.MockHttpService.Nancy;
using Xunit;
namespace PactNet.Tests.Mocks.MockHttpService.Nancy
{
public class MockProviderNancyRequestDispatcherTests
{
private IMockProviderRequestHandler _mockRequestHandler;
private IMockProviderAdminRequestHandler _mockAdminRequestHandler;
private ILog _log;
private IRequestDispatcher GetSubject()
{
_mockRequestHandler = Substitute.For<IMockProviderRequestHandler>();
_mockAdminRequestHandler = Substitute.For<IMockProviderAdminRequestHandler>();
_log = Substitute.For<ILog>();
return new MockProviderNancyRequestDispatcher(_mockRequestHandler, _mockAdminRequestHandler, _log, new PactConfig());
}
[Fact]
public void Dispatch_WithNancyContext_CallsRequestHandlerWithContext()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(new Response());
requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
_mockRequestHandler.Received(1).Handle(nancyContext);
}
[Fact]
public void Dispatch_WithNancyContextThatContainsAdminHeader_CallsAdminRequestHandlerWithContext()
{
var headers = new Dictionary<string, IEnumerable<string>>
{
{ Constants.AdministrativeRequestHeaderKey, new List<string> { "true" } }
};
var nancyContext = new NancyContext
{
Request = new Request("GET", new Url
{
Path = "/Test",
Scheme = "HTTP"
}, null, headers)
};
var requestDispatcher = GetSubject();
_mockAdminRequestHandler.Handle(nancyContext).Returns(new Response());
requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
_mockAdminRequestHandler.Received(1).Handle(nancyContext);
}
[Fact]
public void Dispatch_WithNullNancyContext_ArgumentExceptionIsSetOnTask()
{
var requestDispatcher = GetSubject();
var response = requestDispatcher.Dispatch(null, CancellationToken.None);
Assert.Equal(typeof(ArgumentException), response.Exception.InnerExceptions.First().GetType());
}
[Fact]
public void Dispatch_WithNancyContext_SetsContextResponse()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var nancyResponse = new Response
{
StatusCode = HttpStatusCode.OK
};
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(nancyResponse);
requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
Assert.Equal(nancyResponse, nancyContext.Response);
}
[Fact]
public void Dispatch_WithNancyContext_ReturnsResponse()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var nancyResponse = new Response
{
StatusCode = HttpStatusCode.OK
};
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(nancyResponse);
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
Assert.Equal(nancyResponse, response.Result);
}
[Fact]
public void Dispatch_WithNancyContext_NoExceptionIsSetOnTask()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var nancyResponse = new Response
{
StatusCode = HttpStatusCode.OK
};
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(nancyResponse);
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
Assert.Null(response.Exception);
}
[Fact]
public void Dispatch_WithCanceledCancellationToken_OperationCanceledExceptionIsSetOnTask()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var nancyResponse = new Response
{
StatusCode = HttpStatusCode.OK
};
var cancellationToken = new CancellationToken(true);
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(nancyResponse);
var response = requestDispatcher.Dispatch(nancyContext, cancellationToken);
Assert.Equal(typeof(OperationCanceledException), response.Exception.InnerExceptions.First().GetType());
}
[Fact]
public void Dispatch_WhenRequestHandlerThrows_InternalServerErrorResponseIsReturned()
{
var exception = new InvalidOperationException("Something failed.");
const string expectedMessage = "Something failed. See logs for details.";
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler
.When(x => x.Handle(Arg.Any<NancyContext>()))
.Do(x => { throw exception; });
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result;
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.Equal(expectedMessage, response.ReasonPhrase);
Assert.Equal(expectedMessage, ReadResponseContent(response));
}
[Fact]
public void Dispatch_WhenRequestHandlerThrowsWithMessageThatContainsSlashes_ResponseContentAndReasonPhrasesIsReturnedWithoutSlashes()
{
var exception = new InvalidOperationException("Something\r\n \t \\ failed.");
const string expectedMessage = @"Something\r\n \t \\ failed. See logs for details.";
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler
.When(x => x.Handle(Arg.Any<NancyContext>()))
.Do(x => { throw exception; });
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result;
Assert.Equal(expectedMessage, response.ReasonPhrase);
Assert.Equal(expectedMessage, ReadResponseContent(response));
}
[Fact]
public void Dispatch_WhenRequestHandlerThrows_TheExceptionIsLogged()
{
var exception = new InvalidOperationException("Something failed.");
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler
.When(x => x.Handle(Arg.Any<NancyContext>()))
.Do(x => { throw exception; });
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result;
_log.Received(1).ErrorException(Arg.Any<string>(), exception);
}
[Fact]
public void Dispatch_WhenRequestHandlerThrowsAPactFailureException_TheExceptionIsNotLogged()
{
var exception = new PactFailureException("Something failed");
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler
.When(x => x.Handle(Arg.Any<NancyContext>()))
.Do(x => { throw exception; });
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result;
_log.DidNotReceive().ErrorException(Arg.Any<string>(), Arg.Any<Exception>());
}
private string ReadResponseContent(Response response)
{
string content;
using (var stream = new MemoryStream())
{
response.Contents(stream);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
}
return content;
}
}
}
| humblelistener/pact-net | PactNet.Tests/Mocks/MockHttpService/Nancy/MockProviderNancyRequestDispatcherTests.cs | C# | mit | 9,535 |
class Revista<ReferenciaBase
attr_reader :m_nombre_revista, :m_volumen, :m_paginas
def initialize(a_autores,a_titulo,a_anio,a_nombre_revista, a_volumen, a_paginas)
super(a_autores,a_titulo,a_anio)
@m_nombre_revista,@m_volumen, @m_paginas = a_nombre_revista, a_volumen, a_paginas
end
end | alu0100773408/prct10 | lib/referencia/revista.rb | Ruby | mit | 316 |
"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: "M9 10v4c0 .55.45 1 1 1s1-.45 1-1V4h2v10c0 .55.45 1 1 1s1-.45 1-1V4h1c.55 0 1-.45 1-1s-.45-1-1-1H9.17C7.08 2 5.22 3.53 5.02 5.61 4.79 7.99 6.66 10 9 10zm11.65 7.65-2.79-2.79c-.32-.32-.86-.1-.86.35V17H6c-.55 0-1 .45-1 1s.45 1 1 1h11v1.79c0 .45.54.67.85.35l2.79-2.79c.2-.19.2-.51.01-.7z"
}), 'FormatTextdirectionLToRRounded');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/FormatTextdirectionLToRRounded.js | JavaScript | mit | 769 |
var jazz = require("../lib/jazz");
var fs = require("fs");
var data = fs.readFileSync(__dirname + "/foreach_object.jazz", "utf8");
var template = jazz.compile(data);
template.eval({"doc": {
"title": "First",
"content": "Some content"
}}, function(data) { console.log(data); });
| shinetech/jazz | examples/foreach_object.js | JavaScript | mit | 288 |
/**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter Richter $
Copyright (c) Guenter Richter
$Log:map_GoogleV2.js,v $
**********************************************************************/
/**
* @fileoverview This is the interface to the Google maps API v2
*
* @author Guenter Richter guenter.richter@maptune.com
* @version 0.9
*/
/* ...................................................................*
* global vars *
* ...................................................................*/
/* ...................................................................*
* Google directions *
* ...................................................................*/
function __directions_handleErrors(){
var result = $("#directions-result")[0];
if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
result.innerHTML = ("Indirizzo sconosciuto. Forse è troppo nuovo o sbagliato.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
result.innerHTML = ("Richiesta non riuscita.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
result.innerHTML = ("Inserire indirizzi! \n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_KEY)
result.innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
result.innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
else result.innerHTML = ("Errore sconosciuto!");
}
function _map_setDirections(map,fromAddress, toAddress, toHidden, locale) {
var result = $("#directions-result")[0];
result.innerHTML = "";
gdir.loadFromWaypoints([fromAddress,toHidden],
{ "locale": locale, "preserveViewport":true });
}
function _map_setDestinationWaypoint(marker){
if ( marker ){
var form = $("#directionsform")[0];
if ( form ){
form.to.value = marker.data.name;
if ( marker.getLatLng ){
form.toHidden.value = marker.getLatLng();
}
else if( marker.getVertex ){
form.toHidden.value = marker.getVertex(0);
}
}
}
}
/**
* Is called 'onload' to start creating the map
*/
function _map_loadMap(target){
var __map = null;
// if google maps API v2 is loaded
if ( GMap2 ){
// check if browser can handle Google Maps
if ( !GBrowserIsCompatible()) {
alert("sorry - your browser cannot handle Google Maps !");
return null;
}
__map = new GMap2(target);
if ( __map ){
// configure user map interface
__map.addControl(new GMapTypeControl());
// map.addControl(new GMenuMapTypeControl());
__map.addControl(new GLargeMapControl3D());
__map.addControl(new GScaleControl());
__map.addMapType(G_PHYSICAL_MAP);
__map.addMapType(G_SATELLITE_3D_MAP);
__map.enableDoubleClickZoom();
__map.enableScrollWheelZoom();
}
}
return __map;
}
/**
* Is called to set up directions query
*/
function _map_addDirections(map,target){
if (map){
gdir = new GDirections(map,target);
GEvent.addListener(gdir, "error", __directions_handleErrors);
}
}
/**
* Is called to set up traffic information layer
*/
function _map_addTrafficLayer(map,target){
/* tbd */
}
/**
* Is called to set event handler
*/
function _map_addEventListner(map,szEvent,callback,mapUp){
if (map){
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
// set map center and zoom
//
function _map_setMapExtension(map,bBox){
if (map){
var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) };
var mapZoom = map.getBoundsZoomLevel(new GLatLngBounds( new GLatLng(bBox[2],bBox[0]),
new GLatLng(bBox[3],bBox[1]) ) );
map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lon), mapZoom);
}
}
// get map zoom
//
function _map_getZoom(map){
if (map){
return map.getZoom();
}
return 0;
}
// get map center
//
function _map_getCenter(map){
if (map){
return map.getCenter();
}
return null;
}
// set map zoom
//
function _map_setZoom(map,nZoom){
if (map){
map.setZoom(nZoom);
}
}
// set map center
//
function _map_setCenter(map,center){
if (map){
map.setCenter(center);
}
}
// set map center and zoom
//
function _map_setCenterAndZoom(map,center,nZoom){
if (map){
map.setCenter(center,nZoom);
}
}
// create custom tooltip
//
function _map_createMyTooltip(marker, text, padding){
var tooltip = new Tooltip(marker, text, padding);
marker.tooltip = tooltip;
map.addOverlay(tooltip);
}
function _map_createMyTooltipListener(element, tooltip){
GEvent.addDomListener(element,'mouseover',GEvent.callback(tooltip,
Tooltip.prototype.show));
GEvent.addDomListener(element,'mouseout',GEvent.callback(tooltip,
Tooltip.prototype.hide));
}
// -----------------------------
// EOF
// -----------------------------
| emergenzeHack/terremotocentro | maptune/js/maptune/maptune.GoogleV2.js | JavaScript | mit | 5,620 |
import InputValidator from "../../common/js/InputValidator.js";
import ObjectUtilities from "../../common/js/ObjectUtilities.js";
import Action from "./Action.js";
import DefaultFilters from "./DefaultFilters.js";
import InitialState from "./InitialState.js";
var Reducer = {};
Reducer.root = function(state, action)
{
LOGGER.debug("root() type = " + action.type);
if (typeof state === 'undefined')
{
return new InitialState();
}
var newFilters, newFilteredTableRow;
switch (action.type)
{
case Action.REMOVE_FILTERS:
newFilteredTableRow = [];
newFilteredTableRow = newFilteredTableRow.concat(state.tableRows);
return Object.assign(
{}, state,
{
filteredTableRows: newFilteredTableRow,
});
case Action.SET_DEFAULT_FILTERS:
newFilters = DefaultFilters.create();
return Object.assign(
{}, state,
{
filters: newFilters,
});
case Action.SET_FILTERS:
LOGGER.debug("Reducer filters = ");
Object.getOwnPropertyNames(action.filters).forEach(function(propertyName)
{
LOGGER.debug(propertyName + ": " + action.filters[propertyName]);
});
newFilters = Object.assign(
{}, state.filters);
newFilters = ObjectUtilities.merge(newFilters, action.filters);
newFilteredTableRow = Reducer.filterTableRow(state.tableRows, newFilters);
Reducer.saveToLocalStorage(newFilters);
return Object.assign(
{}, state,
{
filters: newFilters,
filteredTableRows: newFilteredTableRow,
});
case Action.TOGGLE_FILTER_SHOWN:
return Object.assign(
{}, state,
{
isFilterShown: !state.isFilterShown,
});
default:
LOGGER.warn("Reducer.root: Unhandled action type: " + action.type);
return state;
}
};
Reducer.filterTableRow = function(tableRows, filters)
{
InputValidator.validateNotNull("tableRows", tableRows);
InputValidator.validateNotNull("filters", filters);
var answer = [];
tableRows.forEach(function(data)
{
if (Reducer.passes(data, filters))
{
answer.push(data);
}
});
return answer;
};
Reducer.passes = function(data, filters)
{
InputValidator.validateNotNull("data", data);
InputValidator.validateNotNull("filters", filters);
var answer = true;
var propertyNames = Object.getOwnPropertyNames(filters);
for (var i = 0; i < propertyNames.length; i++)
{
var propertyName = propertyNames[i];
var filter = filters[propertyName];
if (!filter.passes(data))
{
answer = false;
break;
}
}
return answer;
};
Reducer.saveToLocalStorage = function(filters)
{
InputValidator.validateNotNull("filters", filters);
var filterObjects = [];
Object.getOwnPropertyNames(filters).forEach(function(columnKey)
{
var filter = filters[columnKey];
filterObjects.push(filter.toObject());
});
localStorage.filters = JSON.stringify(filterObjects);
};
export default Reducer; | jmthompson2015/lotr-card-game | src/accessory/player-card-table/Reducer.js | JavaScript | mit | 3,186 |
package com.github.mlk.queue.codex;
import com.github.mlk.queue.Queuify;
import com.github.mlk.queue.implementation.Module;
public class Utf8StringModule implements Module {
public static Utf8StringModule utfStrings() {
return new Utf8StringModule();
}
@Override
public void bind(Queuify.Builder builder) {
builder.encoder(new StringEncoder())
.decoder(new StringDecoder());
}
}
| mlk/miniature-queue | core/src/main/java/com/github/mlk/queue/codex/Utf8StringModule.java | Java | mit | 434 |
ig.module(
'plusplus.config-user'
)
.defines(function() {
/**
* User configuration of Impact++.
* <span class="alert alert-info"><strong>Tip:</strong> it is recommended to modify this configuration file!</span>
* @example
* // in order to add your own custom configuration to Impact++
* // edit the file defining ig.CONFIG_USER, 'plusplus/config-user.js'
* // ig.CONFIG_USER is never modified by Impact++ (it is strictly for your use)
* // ig.CONFIG_USER is automatically merged over Impact++'s config
* @static
* @readonly
* @memberof ig
* @namespace ig.CONFIG_USER
* @author Collin Hover - collinhover.com
**/
ig.CONFIG_USER = {
// no need to do force entity extended checks, we won't mess it up
// because we know to have our entities extend ig.EntityExtended
FORCE_ENTITY_EXTENDED: false,
// auto sort
AUTO_SORT_LAYERS: true,
// fullscreen!
GAME_WIDTH_PCT: 1,
GAME_HEIGHT_PCT: 1,
// dynamic scaling based on dimensions in view (resolution independence)
GAME_WIDTH_VIEW: 352,
GAME_HEIGHT_VIEW: 208,
// clamped scaling is still dynamic, but within a range
// so we can't get too big or too small
SCALE_MIN: 1,
SCALE_MAX: 4,
// camera flexibility and smoothness
CAMERA: {
// keep the camera within the level
// (whenever possible)
//KEEP_INSIDE_LEVEL: true,
KEEP_CENTERED: false,
LERP: 0.025,
// trap helps with motion sickness
BOUNDS_TRAP_AS_PCT: true,
BOUNDS_TRAP_PCT_MINX: -0.2,
BOUNDS_TRAP_PCT_MINY: -0.3,
BOUNDS_TRAP_PCT_MAXX: 0.2,
BOUNDS_TRAP_PCT_MAXY: 0.3
},
// font and text settings
FONT: {
MAIN_NAME: "font_helloplusplus_white_16.png",
ALT_NAME: "font_helloplusplus_white_8.png",
CHAT_NAME: "font_helloplusplus_black_8.png",
// we can have the font be scaled relative to system
SCALE_OF_SYSTEM_SCALE: 0.5,
// and force a min / max
SCALE_MIN: 1,
SCALE_MAX: 2
},
// text bubble settings
TEXT_BUBBLE: {
// match the visual style
PIXEL_PERFECT: true
},
UI: {
// sometimes, we want to keep things at a static scale
// for example, UI is a possible target
SCALE: 3,
IGNORE_SYSTEM_SCALE: true
},
/*
// to try dynamic clamped UI scaling
// uncomment below and delete the UI settings above
UI: {
SCALE_MIN: 2,
SCALE_MAX: 4
}
*/
// UI should persist across all levels
UI_LAYER_CLEAR_ON_LOAD: false,
CHARACTER: {
// add some depth using offset
SIZE_OFFSET_X: 8,
SIZE_OFFSET_Y: 4
}
};
});
| collinhover/impactplusplus | examples/supercollider/lib/plusplus/config-user.js | JavaScript | mit | 3,308 |
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Jean-Baptiste Quenot, id:cactusman
* 2015 Kanstantsin Shautsou
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.triggers;
import antlr.ANTLRException;
import com.google.common.base.Preconditions;
import hudson.Extension;
import hudson.Util;
import hudson.console.AnnotatedLargeText;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Item;
import hudson.model.Run;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.FlushProofOutputStream;
import hudson.util.FormValidation;
import hudson.util.IOUtils;
import hudson.util.NamingThreadFactory;
import hudson.util.SequentialExecutionQueue;
import hudson.util.StreamTaskListener;
import hudson.util.TimeUnit2;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import jenkins.model.RunAction2;
import jenkins.scm.SCMDecisionHandler;
import jenkins.triggers.SCMTriggerItem;
import jenkins.util.SystemProperties;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.jelly.XMLOutput;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import static java.util.logging.Level.WARNING;
/**
* {@link Trigger} that checks for SCM updates periodically.
*
* You can add UI elements under the SCM section by creating a
* config.jelly or config.groovy in the resources area for
* your class that inherits from SCMTrigger and has the
* @{@link hudson.model.Extension} annotation. The UI should
* be wrapped in an f:section element to denote it.
*
* @author Kohsuke Kawaguchi
*/
public class SCMTrigger extends Trigger<Item> {
private boolean ignorePostCommitHooks;
public SCMTrigger(String scmpoll_spec) throws ANTLRException {
this(scmpoll_spec, false);
}
@DataBoundConstructor
public SCMTrigger(String scmpoll_spec, boolean ignorePostCommitHooks) throws ANTLRException {
super(scmpoll_spec);
this.ignorePostCommitHooks = ignorePostCommitHooks;
}
/**
* This trigger wants to ignore post-commit hooks.
* <p>
* SCM plugins must respect this and not run this trigger for post-commit notifications.
*
* @since 1.493
*/
public boolean isIgnorePostCommitHooks() {
return this.ignorePostCommitHooks;
}
@Override
public void run() {
if (job == null) {
return;
}
run(null);
}
/**
* Run the SCM trigger with additional build actions. Used by SubversionRepositoryStatus
* to trigger a build at a specific revisionn number.
*
* @param additionalActions
* @since 1.375
*/
public void run(Action[] additionalActions) {
if (job == null) {
return;
}
DescriptorImpl d = getDescriptor();
LOGGER.fine("Scheduling a polling for "+job);
if (d.synchronousPolling) {
LOGGER.fine("Running the trigger directly without threading, " +
"as it's already taken care of by Trigger.Cron");
new Runner(additionalActions).run();
} else {
// schedule the polling.
// even if we end up submitting this too many times, that's OK.
// the real exclusion control happens inside Runner.
LOGGER.fine("scheduling the trigger to (asynchronously) run");
d.queue.execute(new Runner(additionalActions));
d.clogCheck();
}
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Override
public Collection<? extends Action> getProjectActions() {
if (job == null) {
return Collections.emptyList();
}
return Collections.singleton(new SCMAction());
}
/**
* Returns the file that records the last/current polling activity.
*/
public File getLogFile() {
return new File(job.getRootDir(),"scm-polling.log");
}
@Extension @Symbol("scm")
public static class DescriptorImpl extends TriggerDescriptor {
private static ThreadFactory threadFactory() {
return new NamingThreadFactory(Executors.defaultThreadFactory(), "SCMTrigger");
}
/**
* Used to control the execution of the polling tasks.
* <p>
* This executor implementation has a semantics suitable for polling. Namely, no two threads will try to poll the same project
* at once, and multiple polling requests to the same job will be combined into one. Note that because executor isn't aware
* of a potential workspace lock between a build and a polling, we may end up using executor threads unwisely --- they
* may block.
*/
private transient final SequentialExecutionQueue queue = new SequentialExecutionQueue(Executors.newSingleThreadExecutor(threadFactory()));
/**
* Whether the projects should be polled all in one go in the order of dependencies. The default behavior is
* that each project polls for changes independently.
*/
public boolean synchronousPolling = false;
/**
* Max number of threads for SCM polling.
* 0 for unbounded.
*/
private int maximumThreads;
public DescriptorImpl() {
load();
resizeThreadPool();
}
public boolean isApplicable(Item item) {
return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(item) != null;
}
public ExecutorService getExecutor() {
return queue.getExecutors();
}
/**
* Returns true if the SCM polling thread queue has too many jobs
* than it can handle.
*/
public boolean isClogged() {
return queue.isStarving(STARVATION_THRESHOLD);
}
/**
* Checks if the queue is clogged, and if so,
* activate {@link AdministrativeMonitorImpl}.
*/
public void clogCheck() {
AdministrativeMonitor.all().get(AdministrativeMonitorImpl.class).on = isClogged();
}
/**
* Gets the snapshot of {@link Runner}s that are performing polling.
*/
public List<Runner> getRunners() {
return Util.filter(queue.getInProgress(),Runner.class);
}
// originally List<SCMedItem> but known to be used only for logging, in which case the instances are not actually cast to SCMedItem anyway
public List<SCMTriggerItem> getItemsBeingPolled() {
List<SCMTriggerItem> r = new ArrayList<SCMTriggerItem>();
for (Runner i : getRunners())
r.add(i.getTarget());
return r;
}
public String getDisplayName() {
return Messages.SCMTrigger_DisplayName();
}
/**
* Gets the number of concurrent threads used for polling.
*
* @return
* 0 if unlimited.
*/
public int getPollingThreadCount() {
return maximumThreads;
}
/**
* Sets the number of concurrent threads used for SCM polling and resizes the thread pool accordingly
* @param n number of concurrent threads, zero or less means unlimited, maximum is 100
*/
public void setPollingThreadCount(int n) {
// fool proof
if(n<0) n=0;
if(n>100) n=100;
maximumThreads = n;
resizeThreadPool();
}
@Restricted(NoExternalUse.class)
public boolean isPollingThreadCountOptionVisible() {
// unless you have a fair number of projects, this option is likely pointless.
// so let's hide this option for new users to avoid confusing them
// unless it was already changed
// TODO switch to check for SCMTriggerItem
return Jenkins.getInstance().getAllItems(AbstractProject.class).size() > 10
|| getPollingThreadCount() != 0;
}
/**
* Update the {@link ExecutorService} instance.
*/
/*package*/ synchronized void resizeThreadPool() {
queue.setExecutors(
(maximumThreads==0 ? Executors.newCachedThreadPool(threadFactory()) : Executors.newFixedThreadPool(maximumThreads, threadFactory())));
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
String t = json.optString("pollingThreadCount",null);
if(t==null || t.length()==0)
setPollingThreadCount(0);
else
setPollingThreadCount(Integer.parseInt(t));
// Save configuration
save();
return true;
}
public FormValidation doCheckPollingThreadCount(@QueryParameter String value) {
if (value != null && "".equals(value.trim()))
return FormValidation.ok();
return FormValidation.validateNonNegativeInteger(value);
}
}
@Extension
public static final class AdministrativeMonitorImpl extends AdministrativeMonitor {
private boolean on;
public boolean isActivated() {
return on;
}
}
/**
* Associated with {@link Run} to show the polling log
* that triggered that build.
*
* @since 1.376
*/
public static class BuildAction implements RunAction2 {
private transient /*final*/ Run<?,?> run;
@Deprecated
public transient /*final*/ AbstractBuild build;
/**
* @since 1.568
*/
public BuildAction(Run<?,?> run) {
this.run = run;
build = run instanceof AbstractBuild ? (AbstractBuild) run : null;
}
@Deprecated
public BuildAction(AbstractBuild build) {
this((Run) build);
}
/**
* @since 1.568
*/
public Run<?,?> getRun() {
return run;
}
/**
* Polling log that triggered the build.
*/
public File getPollingLogFile() {
return new File(run.getRootDir(),"polling.log");
}
public String getIconFileName() {
return "clipboard.png";
}
public String getDisplayName() {
return Messages.SCMTrigger_BuildAction_DisplayName();
}
public String getUrlName() {
return "pollingLog";
}
/**
* Sends out the raw polling log output.
*/
public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException {
rsp.setContentType("text/plain;charset=UTF-8");
// Prevent jelly from flushing stream so Content-Length header can be added afterwards
FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req));
try {
getPollingLogText().writeLogTo(0, out);
} finally {
IOUtils.closeQuietly(out);
}
}
public AnnotatedLargeText getPollingLogText() {
return new AnnotatedLargeText<BuildAction>(getPollingLogFile(), Charset.defaultCharset(), true, this);
}
/**
* Used from <tt>polling.jelly</tt> to write annotated polling log to the given output.
*/
public void writePollingLogTo(long offset, XMLOutput out) throws IOException {
// TODO: resurrect compressed log file support
getPollingLogText().writeHtmlTo(offset, out.asWriter());
}
@Override public void onAttached(Run<?, ?> r) {
// unnecessary, existing constructor does this
}
@Override public void onLoad(Run<?, ?> r) {
run = r;
build = run instanceof AbstractBuild ? (AbstractBuild) run : null;
}
}
/**
* Action object for job. Used to display the last polling log.
*/
public final class SCMAction implements Action {
public AbstractProject<?,?> getOwner() {
Item item = getItem();
return item instanceof AbstractProject ? ((AbstractProject) item) : null;
}
/**
* @since 1.568
*/
public Item getItem() {
return job().asItem();
}
public String getIconFileName() {
return "clipboard.png";
}
public String getDisplayName() {
Set<SCMDescriptor<?>> descriptors = new HashSet<SCMDescriptor<?>>();
for (SCM scm : job().getSCMs()) {
descriptors.add(scm.getDescriptor());
}
return descriptors.size() == 1 ? Messages.SCMTrigger_getDisplayName(descriptors.iterator().next().getDisplayName()) : Messages.SCMTrigger_BuildAction_DisplayName();
}
public String getUrlName() {
return "scmPollLog";
}
public String getLog() throws IOException {
return Util.loadFile(getLogFile());
}
/**
* Writes the annotated log to the given output.
* @since 1.350
*/
public void writeLogTo(XMLOutput out) throws IOException {
new AnnotatedLargeText<SCMAction>(getLogFile(),Charset.defaultCharset(),true,this).writeHtmlTo(0,out.asWriter());
}
}
private static final Logger LOGGER = Logger.getLogger(SCMTrigger.class.getName());
/**
* {@link Runnable} that actually performs polling.
*/
public class Runner implements Runnable {
/**
* When did the polling start?
*/
private volatile long startTime;
private Action[] additionalActions;
public Runner() {
this(null);
}
public Runner(Action[] actions) {
Preconditions.checkNotNull(job, "Runner can't be instantiated when job is null");
if (actions == null) {
additionalActions = new Action[0];
} else {
additionalActions = actions;
}
}
/**
* Where the log file is written.
*/
public File getLogFile() {
return SCMTrigger.this.getLogFile();
}
/**
* For which {@link Item} are we polling?
* @since 1.568
*/
public SCMTriggerItem getTarget() {
return job();
}
/**
* When was this polling started?
*/
public long getStartTime() {
return startTime;
}
/**
* Human readable string of when this polling is started.
*/
public String getDuration() {
return Util.getTimeSpanString(System.currentTimeMillis()-startTime);
}
private boolean runPolling() {
try {
// to make sure that the log file contains up-to-date text,
// don't do buffering.
StreamTaskListener listener = new StreamTaskListener(getLogFile());
try {
PrintStream logger = listener.getLogger();
long start = System.currentTimeMillis();
logger.println("Started on "+ DateFormat.getDateTimeInstance().format(new Date()));
boolean result = job().poll(listener).hasChanges();
logger.println("Done. Took "+ Util.getTimeSpanString(System.currentTimeMillis()-start));
if(result)
logger.println("Changes found");
else
logger.println("No changes");
return result;
} catch (Error | RuntimeException e) {
e.printStackTrace(listener.error("Failed to record SCM polling for "+job));
LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e);
throw e;
} finally {
listener.close();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e);
return false;
}
}
public void run() {
if (job == null) {
return;
}
// we can pre-emtively check the SCMDecisionHandler instances here
// note that job().poll(listener) should also check this
SCMDecisionHandler veto = SCMDecisionHandler.firstShouldPollVeto(job);
if (veto != null) {
try (StreamTaskListener listener = new StreamTaskListener(getLogFile())) {
listener.getLogger().println(
"Skipping polling on " + DateFormat.getDateTimeInstance().format(new Date())
+ " due to veto from " + veto);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to record SCM polling for " + job, e);
}
LOGGER.log(Level.FINE, "Skipping polling for {0} due to veto from {1}",
new Object[]{job.getFullDisplayName(), veto}
);
return;
}
String threadName = Thread.currentThread().getName();
Thread.currentThread().setName("SCM polling for "+job);
try {
startTime = System.currentTimeMillis();
if(runPolling()) {
SCMTriggerItem p = job();
String name = " #"+p.getNextBuildNumber();
SCMTriggerCause cause;
try {
cause = new SCMTriggerCause(getLogFile());
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to parse the polling log",e);
cause = new SCMTriggerCause();
}
Action[] queueActions = new Action[additionalActions.length + 1];
queueActions[0] = new CauseAction(cause);
System.arraycopy(additionalActions, 0, queueActions, 1, additionalActions.length);
if (p.scheduleBuild2(p.getQuietPeriod(), queueActions) != null) {
LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Triggering "+name);
} else {
LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Job is already in the queue");
}
}
} finally {
Thread.currentThread().setName(threadName);
}
}
// as per the requirement of SequentialExecutionQueue, value equality is necessary
@Override
public boolean equals(Object that) {
return that instanceof Runner && job == ((Runner) that)._job();
}
private Item _job() {return job;}
@Override
public int hashCode() {
return job.hashCode();
}
}
@SuppressWarnings("deprecation")
private SCMTriggerItem job() {
return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job);
}
public static class SCMTriggerCause extends Cause {
/**
* Only used while ths cause is in the queue.
* Once attached to the build, we'll move this into a file to reduce the memory footprint.
*/
private String pollingLog;
private transient Run run;
public SCMTriggerCause(File logFile) throws IOException {
// TODO: charset of this log file?
this(FileUtils.readFileToString(logFile));
}
public SCMTriggerCause(String pollingLog) {
this.pollingLog = pollingLog;
}
/**
* @deprecated
* Use {@link SCMTrigger.SCMTriggerCause#SCMTriggerCause(String)}.
*/
@Deprecated
public SCMTriggerCause() {
this("");
}
@Override
public void onLoad(Run run) {
this.run = run;
}
@Override
public void onAddedTo(Run build) {
this.run = build;
try {
BuildAction a = new BuildAction(build);
FileUtils.writeStringToFile(a.getPollingLogFile(),pollingLog);
build.replaceAction(a);
} catch (IOException e) {
LOGGER.log(WARNING,"Failed to persist the polling log",e);
}
pollingLog = null;
}
@Override
public String getShortDescription() {
return Messages.SCMTrigger_SCMTriggerCause_ShortDescription();
}
@Restricted(DoNotUse.class)
public Run getRun() {
return this.run;
}
@Override
public boolean equals(Object o) {
return o instanceof SCMTriggerCause;
}
@Override
public int hashCode() {
return 3;
}
}
/**
* How long is too long for a polling activity to be in the queue?
*/
public static long STARVATION_THRESHOLD = SystemProperties.getLong(SCMTrigger.class.getName()+".starvationThreshold", TimeUnit2.HOURS.toMillis(1));
}
| SebastienGllmt/jenkins | core/src/main/java/hudson/triggers/SCMTrigger.java | Java | mit | 23,475 |
/*
* The MIT License
*
* Copyright 2019 Karus Labs.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.karuslabs.commons.command.synchronization;
import java.util.List;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandSendEvent;
import org.bukkit.scheduler.BukkitScheduler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SynchronizationTest {
Synchronizer synchronizer = mock(Synchronizer.class);
BukkitScheduler scheduler = mock(BukkitScheduler.class);
Synchronization synchronization = new Synchronization(synchronizer, scheduler, null);
PlayerCommandSendEvent event = mock(PlayerCommandSendEvent.class);
@Test
void add() {
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertTrue(synchronization.running);
verify(scheduler).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void add_duplicate() {
synchronization.events.add(event);
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertFalse(synchronization.running);
verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void add_running() {
synchronization.running = true;
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertTrue(synchronization.running);
verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void run() {
when(event.getPlayer()).thenReturn(mock(Player.class));
when(event.getCommands()).thenReturn(List.of("a"));
synchronization.add(event);
synchronization.run();
verify(synchronizer).synchronize(any(Player.class), any(List.class));
assertTrue(synchronization.events.isEmpty());
assertFalse(synchronization.running);
}
}
| Pante/Karus-Commons | commons/src/test/java/com/karuslabs/commons/command/synchronization/SynchronizationTest.java | Java | mit | 3,282 |
<?php
/*
* This file is part of the Omnipay package.
*
* (c) Adrian Macneil <adrian@adrianmacneil.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Omnipay\Common\Message;
use Mockery as m;
use Omnipay\TestCase;
class AbstractResponseTest extends TestCase
{
public function testDefaultMethods()
{
$response = m::mock('\Omnipay\Common\Message\AbstractResponse[isSuccessful]');
$this->assertFalse($response->isRedirect());
$this->assertNull($response->getData());
$this->assertNull($response->getTransactionReference());
$this->assertNull($response->getMessage());
}
}
| cleverage/omnipay | tests/Omnipay/Common/Message/AbstractResponseTest.php | PHP | mit | 726 |
# encoding: utf-8
require 'spec_helper'
describe Github::Authorization do
let(:client_id) { '234jl23j4l23j4l' }
let(:client_secret) { 'asasd79sdf9a7asfd7sfd97s' }
let(:code) { 'c9798sdf97df98ds'}
let(:site) { 'http://github-ent.example.com/' }
let(:options) { {:site => site} }
subject(:github) { Github.new(options) }
after do
reset_authentication_for(github)
end
context '.client' do
it { is_expected.to respond_to :client }
it "should return OAuth2::Client instance" do
expect(github.client).to be_a OAuth2::Client
end
it "should assign site from the options hash" do
expect(github.client.site).to eq site
end
it "should assign 'authorize_url" do
expect(github.client.authorize_url).to eq "#{site}login/oauth/authorize"
end
it "should assign 'token_url" do
expect(github.client.token_url).to eq "#{site}login/oauth/access_token"
end
end
context '.auth_code' do
let(:oauth) { OAuth2::Client.new(client_id, client_secret) }
it "should throw an error if no client_id" do
expect { github.auth_code }.to raise_error(ArgumentError)
end
it "should throw an error if no client_secret" do
expect { github.auth_code }.to raise_error(ArgumentError)
end
it "should return authentication token code" do
github.client_id = client_id
github.client_secret = client_secret
allow(github.client).to receive(:auth_code).and_return code
expect(github.auth_code).to eq code
end
end
context "authorize_url" do
let(:options) { {:client_id => client_id, :client_secret => client_secret} }
it { is_expected.to respond_to(:authorize_url) }
it "should return address containing client_id" do
expect(github.authorize_url).to match /client_id=#{client_id}/
end
it "should return address containing scopes" do
expect(github.authorize_url(:scope => 'user')).to match /scope=user/
end
it "should return address containing redirect_uri" do
expect(github.authorize_url(:redirect_uri => 'http://localhost')).to match /redirect_uri/
end
end
context "get_token" do
let(:options) { {:client_id => client_id, :client_secret => client_secret} }
before do
stub_request(:post, 'https://github.com/login/oauth/access_token').
to_return(:body => '', :status => 200, :headers => {})
end
it { is_expected.to respond_to(:get_token) }
it "should make the authorization request" do
expect {
github.get_token code
a_request(:post, expect("https://github.com/login/oauth/access_token")).to have_been_made
}.to raise_error(OAuth2::Error)
end
it "should fail to get_token without authorization code" do
expect { github.get_token }.to raise_error(ArgumentError)
end
end
context ".authenticated?" do
it { is_expected.to respond_to(:authenticated?) }
it "should return false if falied on basic authentication" do
allow(github).to receive(:basic_authed?).and_return false
expect(github.authenticated?).to be false
end
it "should return true if basic authentication performed" do
allow(github).to receive(:basic_authed?).and_return true
expect(github.authenticated?).to be true
end
it "should return true if basic authentication performed" do
allow(github).to receive(:oauth_token?).and_return true
expect(github.authenticated?).to be true
end
end
context ".basic_authed?" do
before do
allow(github).to receive(:basic_auth?).and_return false
end
it { is_expected.to respond_to(:basic_authed?) }
it "should return false if login is missing" do
allow(github).to receive(:login?).and_return false
expect(github.basic_authed?).to be false
end
it "should return true if login && password provided" do
allow(github).to receive(:login?).and_return true
allow(github).to receive(:password?).and_return true
expect(github.basic_authed?).to be true
end
end
context "authentication" do
it { is_expected.to respond_to(:authentication) }
it "should return empty hash if no basic authentication params available" do
allow(github).to receive(:login?).and_return false
allow(github).to receive(:basic_auth?).and_return false
expect(github.authentication).to be_empty
end
context 'basic_auth' do
let(:options) { { :basic_auth => 'github:pass' } }
it "should return hash with basic auth params" do
expect(github.authentication).to include({login: 'github'})
expect(github.authentication).to include({password: 'pass'})
end
end
context 'login & password' do
it "should return hash with login & password params" do
options = {login: 'github', password: 'pass'}
github = Github.new(options)
expect(github.authentication).to be_a(Hash)
expect(github.authentication).to include({login: 'github'})
expect(github.authentication).to include({password: 'pass'})
reset_authentication_for(github)
end
end
end # authentication
end # Github::Authorization
| peter-murach/github | spec/github/authorization_spec.rb | Ruby | mit | 5,177 |
require File.expand_path('../spec_helper', __FILE__)
module Danger
describe DangerProse do
it 'is a plugin' do
expect(Danger::DangerProse < Danger::Plugin).to be_truthy
end
describe 'with Dangerfile' do
before do
@dangerfile = testing_dangerfile
@prose = testing_dangerfile.prose
end
describe 'linter' do
it 'handles proselint not being installed' do
allow(@prose).to receive(:`).with('which proselint').and_return('')
expect(@prose.proselint_installed?).to be_falsy
end
it 'handles proselint being installed' do
allow(@prose).to receive(:`).with('which proselint').and_return('/bin/thing/proselint')
expect(@prose.proselint_installed?).to be_truthy
end
describe :lint_files do
before do
# So it doesn't try to install on your computer
allow(@prose).to receive(:`).with('which proselint').and_return('/bin/thing/proselint')
# Proselint returns JSON data, which is nice 👍
errors = '[{"start": 1441, "replacements": null, "end": 1445, "severity": "warning", "extent": 4, "column": 1, "message": "!!! is hyperbolic.", "line": 46, "check": "hyperbolic.misc"}]'
proselint_response = '{"status" : "success", "data" : { "errors" : ' + errors + '}}'
# This is where we generate our JSON
allow(@prose).to receive(:`).with('proselint "spec/fixtures/blog_post.md" --json').and_return(proselint_response)
# it's worth noting - you can call anything on your plugin that a Dangerfile responds to
# The request source's PR JSON typically looks like
# https://raw.githubusercontent.com/danger/danger/bffc246a11dac883d76fc6636319bd6c2acd58a3/spec/fixtures/pr_response.json
@prose.env.request_source.pr_json = { "head" => { "ref" => 'my_fake_branch' } }
end
it 'handles a known JSON report from proselint' do
@prose.lint_files('spec/fixtures/*.md')
output = @prose.status_report[:markdowns].first
# A title
expect(output.message).to include('Proselint found issues')
# A warning
expect(output.message).to include('!!! is hyperbolic. | warning')
# A link to the file inside the fixtures dir
expect(output.message).to include('[spec/fixtures/blog_post.md](/artsy/eigen/tree/my_fake_branch/spec/fixtures/blog_post.md)')
end
end
end
describe 'spell checking' do
it 'handles proselint not being installed' do
allow(@prose).to receive(:`).with('which mdspell').and_return('')
expect(@prose.mdspell_installed?).to be_falsy
end
it 'handles proselint being installed' do
allow(@prose).to receive(:`).with('which mdspell').and_return('/bin/thing/mdspell')
expect(@prose.mdspell_installed?).to be_truthy
end
describe 'full command' do
before do
# So it doesn't try to install on your computer
allow(@prose).to receive(:`).with('which mdspell').and_return('/bin/thing/mdspell')
# mdspell returns JSON data, which is nice 👍
proselint_response = " spec/fixtures/blog_post.md\n 1:27 | This post intentional left blank-ish.\n 4:84 | Here's a tpyo - it should registor.\n 4:101 | Here's a tpyo - it should registor.\n\n >> 3 spelling errors found in 1 file"
# This is where we generate our JSON
allow(@prose).to receive(:`).with('mdspell spec/fixtures/blog_post.md -r --en-gb').and_return(proselint_response)
# it's worth noting - you can call anything on your plugin that a Dangerfile responds to
# The request source's PR JSON typically looks like
# https://raw.githubusercontent.com/danger/danger/bffc246a11dac883d76fc6636319bd6c2acd58a3/spec/fixtures/pr_response.json
@prose.env.request_source.pr_json = { "head" => { "ref" => 'my_fake_branch' } }
end
it 'handles a known JSON report from mdspell' do
@prose.check_spelling('spec/fixtures/*.md')
output = @prose.status_report[:markdowns].first
# A title
expect(output.message).to include('Spell Checker found issues')
# A typo, in bold
expect(output.message).to include('**tpyo**')
# A link to the file inside the fixtures dir
expect(output.message).to include('[spec/fixtures/blog_post.md](/artsy/eigen/tree/my_fake_branch/spec/fixtures/blog_post.md)')
end
end
end
end
end
end
| dbgrandi/danger-proselint | spec/danger_plugin_spec.rb | Ruby | mit | 4,724 |
'use strict'
const path = require('path')
const hbs = require('express-hbs')
module.exports = function (app, express) {
hbs.registerHelper('asset', require('./helpers/asset'))
app.engine('hbs', hbs.express4({
partialsDir: path.resolve('app/client/views/partials'),
layoutsDir: path.resolve('app/client/views/layouts'),
beautify: app.locals.isProduction
}))
app.set('view engine', 'hbs')
app.set('views', path.resolve('app/client/views'))
app.use(express.static(path.resolve('app/public')))
return app
}
| finkhq/fink-www | app/server/views/index.js | JavaScript | mit | 535 |
// Polyfills
if ( Number.EPSILON === undefined ) {
Number.EPSILON = Math.pow( 2, - 52 );
}
if ( Number.isInteger === undefined ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Number.isInteger = function ( value ) {
return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
};
}
//
if ( Math.sign === undefined ) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
Math.sign = function ( x ) {
return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
};
}
if ( 'name' in Function.prototype === false ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
Object.defineProperty( Function.prototype, 'name', {
get: function () {
return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
}
} );
}
if ( Object.assign === undefined ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Object.assign = function ( target ) {
'use strict';
if ( target === undefined || target === null ) {
throw new TypeError( 'Cannot convert undefined or null to object' );
}
const output = Object( target );
for ( let index = 1; index < arguments.length; index ++ ) {
const source = arguments[ index ];
if ( source !== undefined && source !== null ) {
for ( const nextKey in source ) {
if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
output[ nextKey ] = source[ nextKey ];
}
}
}
}
return output;
};
}
| fraguada/three.js | src/polyfills.js | JavaScript | mit | 1,691 |
<?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\FlashPix;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class LockedPropertyList extends AbstractTag
{
protected $Id = 65538;
protected $Name = 'LockedPropertyList';
protected $FullName = 'mixed';
protected $GroupName = 'FlashPix';
protected $g0 = 'FlashPix';
protected $g1 = 'FlashPix';
protected $g2 = 'Other';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Locked Property List';
}
| bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/FlashPix/LockedPropertyList.php | PHP | mit | 807 |
import supertest from 'supertest';
import { publicChannelName, privateChannelName } from './channel.js';
import { roleNameUsers, roleNameSubscriptions, roleScopeUsers, roleScopeSubscriptions, roleDescription } from './role.js';
import { username, email, adminUsername, adminPassword } from './user.js';
export const request = supertest('http://localhost:3000');
const prefix = '/api/v1/';
export function wait(cb, time) {
return () => setTimeout(cb, time);
}
export const apiUsername = `api${ username }`;
export const apiEmail = `api${ email }`;
export const apiPublicChannelName = `api${ publicChannelName }`;
export const apiPrivateChannelName = `api${ privateChannelName }`;
export const apiRoleNameUsers = `api${ roleNameUsers }`;
export const apiRoleNameSubscriptions = `api${ roleNameSubscriptions }`;
export const apiRoleScopeUsers = `${ roleScopeUsers }`;
export const apiRoleScopeSubscriptions = `${ roleScopeSubscriptions }`;
export const apiRoleDescription = `api${ roleDescription }`;
export const reservedWords = [
'admin',
'administrator',
'system',
'user',
];
export const targetUser = {};
export const channel = {};
export const group = {};
export const message = {};
export const directMessage = {};
export const integration = {};
export const credentials = {
'X-Auth-Token': undefined,
'X-User-Id': undefined,
};
export const login = {
user: adminUsername,
password: adminPassword,
};
export function api(path) {
return prefix + path;
}
export function methodCall(methodName) {
return api(`method.call/${ methodName }`);
}
export function log(res) {
console.log(res.req.path);
console.log({
body: res.body,
headers: res.headers,
});
}
export function getCredentials(done = function() {}) {
request.post(api('login'))
.send(login)
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
credentials['X-Auth-Token'] = res.body.data.authToken;
credentials['X-User-Id'] = res.body.data.userId;
})
.end(done);
}
| VoiSmart/Rocket.Chat | tests/data/api-data.js | JavaScript | mit | 1,993 |
<?php
namespace Illuminate\Database\Eloquent;
use Exception;
use ArrayAccess;
use JsonSerializable;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Routing\UrlRoutable;
use Illuminate\Contracts\Queue\QueueableEntity;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Contracts\Queue\QueueableCollection;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
{
use Concerns\HasAttributes,
Concerns\HasEvents,
Concerns\HasGlobalScopes,
Concerns\HasRelationships,
Concerns\HasTimestamps,
Concerns\HidesAttributes,
Concerns\GuardsAttributes;
/**
* The connection name for the model.
*
* @var string
*/
protected $connection;
/**
* The table associated with the model.
*
* @var string
*/
protected $table;
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'int';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = true;
/**
* The relations to eager load on every query.
*
* @var array
*/
protected $with = [];
/**
* The relationship counts that should be eager loaded on every query.
*
* @var array
*/
protected $withCount = [];
/**
* The number of models to return for pagination.
*
* @var int
*/
protected $perPage = 15;
/**
* Indicates if the model exists.
*
* @var bool
*/
public $exists = false;
/**
* Indicates if the model was inserted during the current request lifecycle.
*
* @var bool
*/
public $wasRecentlyCreated = false;
/**
* The connection resolver instance.
*
* @var \Illuminate\Database\ConnectionResolverInterface
*/
protected static $resolver;
/**
* The event dispatcher instance.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
protected static $dispatcher;
/**
* The array of booted models.
*
* @var array
*/
protected static $booted = [];
/**
* The array of global scopes on the model.
*
* @var array
*/
protected static $globalScopes = [];
/**
* The name of the "created at" column.
*
* @var string
*/
const CREATED_AT = 'created_at';
/**
* The name of the "updated at" column.
*
* @var string
*/
const UPDATED_AT = 'updated_at';
/**
* Create a new Eloquent model instance.
*
* @param array $attributes
* @return void
*/
public function __construct(array $attributes = [])
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
/**
* Check if the model needs to be booted and if so, do it.
*
* @return void
*/
protected function bootIfNotBooted()
{
if (! isset(static::$booted[static::class])) {
static::$booted[static::class] = true;
$this->fireModelEvent('booting', false);
static::boot();
$this->fireModelEvent('booted', false);
}
}
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
static::bootTraits();
}
/**
* Boot all of the bootable traits on the model.
*
* @return void
*/
protected static function bootTraits()
{
$class = static::class;
foreach (class_uses_recursive($class) as $trait) {
if (method_exists($class, $method = 'boot'.class_basename($trait))) {
forward_static_call([$class, $method]);
}
}
}
/**
* Clear the list of booted models so they will be re-booted.
*
* @return void
*/
public static function clearBootedModels()
{
static::$booted = [];
static::$globalScopes = [];
}
/**
* Fill the model with an array of attributes.
*
* @param array $attributes
* @return $this
*
* @throws \Illuminate\Database\Eloquent\MassAssignmentException
*/
public function fill(array $attributes)
{
$totallyGuarded = $this->totallyGuarded();
foreach ($this->fillableFromArray($attributes) as $key => $value) {
$key = $this->removeTableFromKey($key);
// The developers may choose to place some attributes in the "fillable" array
// which means only those attributes may be set through mass assignment to
// the model, and all others will just get ignored for security reasons.
if ($this->isFillable($key)) {
$this->setAttribute($key, $value);
} elseif ($totallyGuarded) {
throw new MassAssignmentException(sprintf(
'Add [%s] to fillable property to allow mass assignment on [%s].',
$key, get_class($this)
));
}
}
return $this;
}
/**
* Fill the model with an array of attributes. Force mass assignment.
*
* @param array $attributes
* @return $this
*/
public function forceFill(array $attributes)
{
return static::unguarded(function () use ($attributes) {
return $this->fill($attributes);
});
}
/**
* Qualify the given column name by the model's table.
*
* @param string $column
* @return string
*/
public function qualifyColumn($column)
{
if (Str::contains($column, '.')) {
return $column;
}
return $this->getTable().'.'.$column;
}
/**
* Remove the table name from a given key.
*
* @param string $key
* @return string
*/
protected function removeTableFromKey($key)
{
return Str::contains($key, '.') ? last(explode('.', $key)) : $key;
}
/**
* Create a new instance of the given model.
*
* @param array $attributes
* @param bool $exists
* @return static
*/
public function newInstance($attributes = [], $exists = false)
{
// This method just provides a convenient way for us to generate fresh model
// instances of this current model. It is particularly useful during the
// hydration of new objects via the Eloquent query builder instances.
$model = new static((array) $attributes);
$model->exists = $exists;
$model->setConnection(
$this->getConnectionName()
);
return $model;
}
/**
* Create a new model instance that is existing.
*
* @param array $attributes
* @param string|null $connection
* @return static
*/
public function newFromBuilder($attributes = [], $connection = null)
{
$model = $this->newInstance([], true);
$model->setRawAttributes((array) $attributes, true);
$model->setConnection($connection ?: $this->getConnectionName());
$model->fireModelEvent('retrieved', false);
return $model;
}
/**
* Begin querying the model on a given connection.
*
* @param string|null $connection
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function on($connection = null)
{
// First we will just create a fresh instance of this model, and then we can
// set the connection on the model so that it is be used for the queries
// we execute, as well as being set on each relationship we retrieve.
$instance = new static;
$instance->setConnection($connection);
return $instance->newQuery();
}
/**
* Begin querying the model on the write connection.
*
* @return \Illuminate\Database\Query\Builder
*/
public static function onWriteConnection()
{
$instance = new static;
return $instance->newQuery()->useWritePdo();
}
/**
* Get all of the models from the database.
*
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Collection|static[]
*/
public static function all($columns = ['*'])
{
return (new static)->newQuery()->get(
is_array($columns) ? $columns : func_get_args()
);
}
/**
* Begin querying a model with eager loading.
*
* @param array|string $relations
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public static function with($relations)
{
return (new static)->newQuery()->with(
is_string($relations) ? func_get_args() : $relations
);
}
/**
* Eager load relations on the model.
*
* @param array|string $relations
* @return $this
*/
public function load($relations)
{
$query = $this->newQueryWithoutRelationships()->with(
is_string($relations) ? func_get_args() : $relations
);
$query->eagerLoadRelations([$this]);
return $this;
}
/**
* Eager load relations on the model if they are not already eager loaded.
*
* @param array|string $relations
* @return $this
*/
public function loadMissing($relations)
{
$relations = is_string($relations) ? func_get_args() : $relations;
return $this->load(array_filter($relations, function ($relation) {
return ! $this->relationLoaded($relation);
}));
}
/**
* Increment a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
protected function increment($column, $amount = 1, array $extra = [])
{
return $this->incrementOrDecrement($column, $amount, $extra, 'increment');
}
/**
* Decrement a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
protected function decrement($column, $amount = 1, array $extra = [])
{
return $this->incrementOrDecrement($column, $amount, $extra, 'decrement');
}
/**
* Run the increment or decrement method on the model.
*
* @param string $column
* @param int $amount
* @param array $extra
* @param string $method
* @return int
*/
protected function incrementOrDecrement($column, $amount, $extra, $method)
{
$query = $this->newQuery();
if (! $this->exists) {
return $query->{$method}($column, $amount, $extra);
}
$this->incrementOrDecrementAttributeValue($column, $amount, $extra, $method);
return $query->where(
$this->getKeyName(), $this->getKey()
)->{$method}($column, $amount, $extra);
}
/**
* Increment the underlying attribute value and sync with original.
*
* @param string $column
* @param int $amount
* @param array $extra
* @param string $method
* @return void
*/
protected function incrementOrDecrementAttributeValue($column, $amount, $extra, $method)
{
$this->{$column} = $this->{$column} + ($method == 'increment' ? $amount : $amount * -1);
$this->forceFill($extra);
$this->syncOriginalAttribute($column);
}
/**
* Update the model in the database.
*
* @param array $attributes
* @param array $options
* @return bool
*/
public function update(array $attributes = [], array $options = [])
{
if (! $this->exists) {
return false;
}
return $this->fill($attributes)->save($options);
}
/**
* Save the model and all of its relationships.
*
* @return bool
*/
public function push()
{
if (! $this->save()) {
return false;
}
// To sync all of the relationships to the database, we will simply spin through
// the relationships and save each model via this "push" method, which allows
// us to recurse into all of these nested relations for the model instance.
foreach ($this->relations as $models) {
$models = $models instanceof Collection
? $models->all() : [$models];
foreach (array_filter($models) as $model) {
if (! $model->push()) {
return false;
}
}
}
return true;
}
/**
* Save the model to the database.
*
* @param array $options
* @return bool
*/
public function save(array $options = [])
{
$query = $this->newQueryWithoutScopes();
// If the "saving" event returns false we'll bail out of the save and return
// false, indicating that the save failed. This provides a chance for any
// listeners to cancel save operations if validations fail or whatever.
if ($this->fireModelEvent('saving') === false) {
return false;
}
// If the model already exists in the database we can just update our record
// that is already in this database using the current IDs in this "where"
// clause to only update this model. Otherwise, we'll just insert them.
if ($this->exists) {
$saved = $this->isDirty() ?
$this->performUpdate($query) : true;
}
// If the model is brand new, we'll insert it into our database and set the
// ID attribute on the model to the value of the newly inserted row's ID
// which is typically an auto-increment value managed by the database.
else {
$saved = $this->performInsert($query);
if (! $this->getConnectionName() &&
$connection = $query->getConnection()) {
$this->setConnection($connection->getName());
}
}
// If the model is successfully saved, we need to do a few more things once
// that is done. We will call the "saved" method here to run any actions
// we need to happen after a model gets successfully saved right here.
if ($saved) {
$this->finishSave($options);
}
return $saved;
}
/**
* Save the model to the database using transaction.
*
* @param array $options
* @return bool
*
* @throws \Throwable
*/
public function saveOrFail(array $options = [])
{
return $this->getConnection()->transaction(function () use ($options) {
return $this->save($options);
});
}
/**
* Perform any actions that are necessary after the model is saved.
*
* @param array $options
* @return void
*/
protected function finishSave(array $options)
{
$this->fireModelEvent('saved', false);
if ($this->isDirty() && ($options['touch'] ?? true)) {
$this->touchOwners();
}
$this->syncOriginal();
}
/**
* Perform a model update operation.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return bool
*/
protected function performUpdate(Builder $query)
{
// If the updating event returns false, we will cancel the update operation so
// developers can hook Validation systems into their models and cancel this
// operation if the model does not pass validation. Otherwise, we update.
if ($this->fireModelEvent('updating') === false) {
return false;
}
// First we need to create a fresh query instance and touch the creation and
// update timestamp on the model which are maintained by us for developer
// convenience. Then we will just continue saving the model instances.
if ($this->usesTimestamps()) {
$this->updateTimestamps();
}
// Once we have run the update operation, we will fire the "updated" event for
// this model instance. This will allow developers to hook into these after
// models are updated, giving them a chance to do any special processing.
$dirty = $this->getDirty();
if (count($dirty) > 0) {
$this->setKeysForSaveQuery($query)->update($dirty);
$this->fireModelEvent('updated', false);
$this->syncChanges();
}
return true;
}
/**
* Set the keys for a save update query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function setKeysForSaveQuery(Builder $query)
{
$query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
return $query;
}
/**
* Get the primary key value for a save query.
*
* @return mixed
*/
protected function getKeyForSaveQuery()
{
return $this->original[$this->getKeyName()]
?? $this->getKey();
}
/**
* Perform a model insert operation.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return bool
*/
protected function performInsert(Builder $query)
{
if ($this->fireModelEvent('creating') === false) {
return false;
}
// First we'll need to create a fresh query instance and touch the creation and
// update timestamps on this model, which are maintained by us for developer
// convenience. After, we will just continue saving these model instances.
if ($this->usesTimestamps()) {
$this->updateTimestamps();
}
// If the model has an incrementing key, we can use the "insertGetId" method on
// the query builder, which will give us back the final inserted ID for this
// table from the database. Not all tables have to be incrementing though.
$attributes = $this->attributes;
if ($this->getIncrementing()) {
$this->insertAndSetId($query, $attributes);
}
// If the table isn't incrementing we'll simply insert these attributes as they
// are. These attribute arrays must contain an "id" column previously placed
// there by the developer as the manually determined key for these models.
else {
if (empty($attributes)) {
return true;
}
$query->insert($attributes);
}
// We will go ahead and set the exists property to true, so that it is set when
// the created event is fired, just in case the developer tries to update it
// during the event. This will allow them to do so and run an update here.
$this->exists = true;
$this->wasRecentlyCreated = true;
$this->fireModelEvent('created', false);
return true;
}
/**
* Insert the given attributes and set the ID on the model.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $attributes
* @return void
*/
protected function insertAndSetId(Builder $query, $attributes)
{
$id = $query->insertGetId($attributes, $keyName = $this->getKeyName());
$this->setAttribute($keyName, $id);
}
/**
* Destroy the models for the given IDs.
*
* @param array|int $ids
* @return int
*/
public static function destroy($ids)
{
// We'll initialize a count here so we will return the total number of deletes
// for the operation. The developers can then check this number as a boolean
// type value or get this total count of records deleted for logging, etc.
$count = 0;
$ids = is_array($ids) ? $ids : func_get_args();
// We will actually pull the models from the database table and call delete on
// each of them individually so that their events get fired properly with a
// correct set of attributes in case the developers wants to check these.
$key = ($instance = new static)->getKeyName();
foreach ($instance->whereIn($key, $ids)->get() as $model) {
if ($model->delete()) {
$count++;
}
}
return $count;
}
/**
* Delete the model from the database.
*
* @return bool|null
*
* @throws \Exception
*/
public function delete()
{
if (is_null($this->getKeyName())) {
throw new Exception('No primary key defined on model.');
}
// If the model doesn't exist, there is nothing to delete so we'll just return
// immediately and not do anything else. Otherwise, we will continue with a
// deletion process on the model, firing the proper events, and so forth.
if (! $this->exists) {
return;
}
if ($this->fireModelEvent('deleting') === false) {
return false;
}
// Here, we'll touch the owning models, verifying these timestamps get updated
// for the models. This will allow any caching to get broken on the parents
// by the timestamp. Then we will go ahead and delete the model instance.
$this->touchOwners();
$this->performDeleteOnModel();
// Once the model has been deleted, we will fire off the deleted event so that
// the developers may hook into post-delete operations. We will then return
// a boolean true as the delete is presumably successful on the database.
$this->fireModelEvent('deleted', false);
return true;
}
/**
* Force a hard delete on a soft deleted model.
*
* This method protects developers from running forceDelete when trait is missing.
*
* @return bool|null
*/
public function forceDelete()
{
return $this->delete();
}
/**
* Perform the actual delete query on this model instance.
*
* @return void
*/
protected function performDeleteOnModel()
{
$this->setKeysForSaveQuery($this->newQueryWithoutScopes())->delete();
$this->exists = false;
}
/**
* Begin querying the model.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function query()
{
return (new static)->newQuery();
}
/**
* Get a new query builder for the model's table.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQuery()
{
return $this->registerGlobalScopes($this->newQueryWithoutScopes());
}
/**
* Get a new query builder with no relationships loaded.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQueryWithoutRelationships()
{
return $this->registerGlobalScopes(
$this->newEloquentBuilder($this->newBaseQueryBuilder())->setModel($this)
);
}
/**
* Register the global scopes for this builder instance.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return \Illuminate\Database\Eloquent\Builder
*/
public function registerGlobalScopes($builder)
{
foreach ($this->getGlobalScopes() as $identifier => $scope) {
$builder->withGlobalScope($identifier, $scope);
}
return $builder;
}
/**
* Get a new query builder that doesn't have any global scopes.
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function newQueryWithoutScopes()
{
$builder = $this->newEloquentBuilder($this->newBaseQueryBuilder());
// Once we have the query builders, we will set the model instances so the
// builder can easily access any information it may need from the model
// while it is constructing and executing various queries against it.
return $builder->setModel($this)
->with($this->with)
->withCount($this->withCount);
}
/**
* Get a new query instance without a given scope.
*
* @param \Illuminate\Database\Eloquent\Scope|string $scope
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQueryWithoutScope($scope)
{
$builder = $this->newQuery();
return $builder->withoutGlobalScope($scope);
}
/**
* Get a new query to restore one or more models by their queueable IDs.
*
* @param array|int $ids
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQueryForRestoration($ids)
{
return is_array($ids)
? $this->newQueryWithoutScopes()->whereIn($this->getQualifiedKeyName(), $ids)
: $this->newQueryWithoutScopes()->whereKey($ids);
}
/**
* Create a new Eloquent query builder for the model.
*
* @param \Illuminate\Database\Query\Builder $query
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function newEloquentBuilder($query)
{
return new Builder($query);
}
/**
* Get a new query builder instance for the connection.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function newBaseQueryBuilder()
{
$connection = $this->getConnection();
return new QueryBuilder(
$connection, $connection->getQueryGrammar(), $connection->getPostProcessor()
);
}
/**
* Create a new Eloquent Collection instance.
*
* @param array $models
* @return \Illuminate\Database\Eloquent\Collection
*/
public function newCollection(array $models = [])
{
return new Collection($models);
}
/**
* Create a new pivot model instance.
*
* @param \Illuminate\Database\Eloquent\Model $parent
* @param array $attributes
* @param string $table
* @param bool $exists
* @param string|null $using
* @return \Illuminate\Database\Eloquent\Relations\Pivot
*/
public function newPivot(self $parent, array $attributes, $table, $exists, $using = null)
{
return $using ? $using::fromRawAttributes($parent, $attributes, $table, $exists)
: Pivot::fromAttributes($parent, $attributes, $table, $exists);
}
/**
* Convert the model instance to an array.
*
* @return array
*/
public function toArray()
{
return array_merge($this->attributesToArray(), $this->relationsToArray());
}
/**
* Convert the model instance to JSON.
*
* @param int $options
* @return string
*
* @throws \Illuminate\Database\Eloquent\JsonEncodingException
*/
public function toJson($options = 0)
{
$json = json_encode($this->jsonSerialize(), $options);
if (JSON_ERROR_NONE !== json_last_error()) {
throw JsonEncodingException::forModel($this, json_last_error_msg());
}
return $json;
}
/**
* Convert the object into something JSON serializable.
*
* @return array
*/
public function jsonSerialize()
{
return $this->toArray();
}
/**
* Reload a fresh model instance from the database.
*
* @param array|string $with
* @return static|null
*/
public function fresh($with = [])
{
if (! $this->exists) {
return;
}
return static::newQueryWithoutScopes()
->with(is_string($with) ? func_get_args() : $with)
->where($this->getKeyName(), $this->getKey())
->first();
}
/**
* Reload the current model instance with fresh attributes from the database.
*
* @return $this
*/
public function refresh()
{
if (! $this->exists) {
return $this;
}
$this->setRawAttributes(
static::newQueryWithoutScopes()->findOrFail($this->getKey())->attributes
);
$this->load(collect($this->relations)->except('pivot')->keys()->toArray());
$this->syncOriginal();
return $this;
}
/**
* Clone the model into a new, non-existing instance.
*
* @param array|null $except
* @return \Illuminate\Database\Eloquent\Model
*/
public function replicate(array $except = null)
{
$defaults = [
$this->getKeyName(),
$this->getCreatedAtColumn(),
$this->getUpdatedAtColumn(),
];
$attributes = Arr::except(
$this->attributes, $except ? array_unique(array_merge($except, $defaults)) : $defaults
);
return tap(new static, function ($instance) use ($attributes) {
$instance->setRawAttributes($attributes);
$instance->setRelations($this->relations);
});
}
/**
* Determine if two models have the same ID and belong to the same table.
*
* @param \Illuminate\Database\Eloquent\Model|null $model
* @return bool
*/
public function is($model)
{
return ! is_null($model) &&
$this->getKey() === $model->getKey() &&
$this->getTable() === $model->getTable() &&
$this->getConnectionName() === $model->getConnectionName();
}
/**
* Determine if two models are not the same.
*
* @param \Illuminate\Database\Eloquent\Model|null $model
* @return bool
*/
public function isNot($model)
{
return ! $this->is($model);
}
/**
* Get the database connection for the model.
*
* @return \Illuminate\Database\Connection
*/
public function getConnection()
{
return static::resolveConnection($this->getConnectionName());
}
/**
* Get the current connection name for the model.
*
* @return string
*/
public function getConnectionName()
{
return $this->connection;
}
/**
* Set the connection associated with the model.
*
* @param string $name
* @return $this
*/
public function setConnection($name)
{
$this->connection = $name;
return $this;
}
/**
* Resolve a connection instance.
*
* @param string|null $connection
* @return \Illuminate\Database\Connection
*/
public static function resolveConnection($connection = null)
{
return static::$resolver->connection($connection);
}
/**
* Get the connection resolver instance.
*
* @return \Illuminate\Database\ConnectionResolverInterface
*/
public static function getConnectionResolver()
{
return static::$resolver;
}
/**
* Set the connection resolver instance.
*
* @param \Illuminate\Database\ConnectionResolverInterface $resolver
* @return void
*/
public static function setConnectionResolver(Resolver $resolver)
{
static::$resolver = $resolver;
}
/**
* Unset the connection resolver for models.
*
* @return void
*/
public static function unsetConnectionResolver()
{
static::$resolver = null;
}
/**
* Get the table associated with the model.
*
* @return string
*/
public function getTable()
{
if (! isset($this->table)) {
return str_replace(
'\\', '', Str::snake(Str::plural(class_basename($this)))
);
}
return $this->table;
}
/**
* Set the table associated with the model.
*
* @param string $table
* @return $this
*/
public function setTable($table)
{
$this->table = $table;
return $this;
}
/**
* Get the primary key for the model.
*
* @return string
*/
public function getKeyName()
{
return $this->primaryKey;
}
/**
* Set the primary key for the model.
*
* @param string $key
* @return $this
*/
public function setKeyName($key)
{
$this->primaryKey = $key;
return $this;
}
/**
* Get the table qualified key name.
*
* @return string
*/
public function getQualifiedKeyName()
{
return $this->qualifyColumn($this->getKeyName());
}
/**
* Get the auto-incrementing key type.
*
* @return string
*/
public function getKeyType()
{
return $this->keyType;
}
/**
* Set the data type for the primary key.
*
* @param string $type
* @return $this
*/
public function setKeyType($type)
{
$this->keyType = $type;
return $this;
}
/**
* Get the value indicating whether the IDs are incrementing.
*
* @return bool
*/
public function getIncrementing()
{
return $this->incrementing;
}
/**
* Set whether IDs are incrementing.
*
* @param bool $value
* @return $this
*/
public function setIncrementing($value)
{
$this->incrementing = $value;
return $this;
}
/**
* Get the value of the model's primary key.
*
* @return mixed
*/
public function getKey()
{
return $this->getAttribute($this->getKeyName());
}
/**
* Get the queueable identity for the entity.
*
* @return mixed
*/
public function getQueueableId()
{
return $this->getKey();
}
/**
* Get the queueable relationships for the entity.
*
* @return array
*/
public function getQueueableRelations()
{
$relations = [];
foreach ($this->getRelations() as $key => $relation) {
if (method_exists($this, $key)) {
$relations[] = $key;
}
if ($relation instanceof QueueableCollection) {
foreach ($relation->getQueueableRelations() as $collectionValue) {
$relations[] = $key.'.'.$collectionValue;
}
}
if ($relation instanceof QueueableEntity) {
foreach ($relation->getQueueableRelations() as $entityKey => $entityValue) {
$relations[] = $key.'.'.$entityValue;
}
}
}
return array_unique($relations);
}
/**
* Get the queueable connection for the entity.
*
* @return mixed
*/
public function getQueueableConnection()
{
return $this->getConnectionName();
}
/**
* Get the value of the model's route key.
*
* @return mixed
*/
public function getRouteKey()
{
return $this->getAttribute($this->getRouteKeyName());
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return $this->getKeyName();
}
/**
* Retrieve the model for a bound value.
*
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function resolveRouteBinding($value)
{
return $this->where($this->getRouteKeyName(), $value)->first();
}
/**
* Get the default foreign key name for the model.
*
* @return string
*/
public function getForeignKey()
{
return Str::snake(class_basename($this)).'_'.$this->getKeyName();
}
/**
* Get the number of models to return per page.
*
* @return int
*/
public function getPerPage()
{
return $this->perPage;
}
/**
* Set the number of models to return per page.
*
* @param int $perPage
* @return $this
*/
public function setPerPage($perPage)
{
$this->perPage = $perPage;
return $this;
}
/**
* Dynamically retrieve attributes on the model.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->getAttribute($key);
}
/**
* Dynamically set attributes on the model.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function __set($key, $value)
{
$this->setAttribute($key, $value);
}
/**
* Determine if the given attribute exists.
*
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return ! is_null($this->getAttribute($offset));
}
/**
* Get the value for a given offset.
*
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset)
{
return $this->getAttribute($offset);
}
/**
* Set the value for a given offset.
*
* @param mixed $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value)
{
$this->setAttribute($offset, $value);
}
/**
* Unset the value for a given offset.
*
* @param mixed $offset
* @return void
*/
public function offsetUnset($offset)
{
unset($this->attributes[$offset], $this->relations[$offset]);
}
/**
* Determine if an attribute or relation exists on the model.
*
* @param string $key
* @return bool
*/
public function __isset($key)
{
return $this->offsetExists($key);
}
/**
* Unset an attribute on the model.
*
* @param string $key
* @return void
*/
public function __unset($key)
{
$this->offsetUnset($key);
}
/**
* Handle dynamic method calls into the model.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (in_array($method, ['increment', 'decrement'])) {
return $this->$method(...$parameters);
}
return $this->newQuery()->$method(...$parameters);
}
/**
* Handle dynamic static method calls into the method.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
return (new static)->$method(...$parameters);
}
/**
* Convert the model to its string representation.
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
/**
* When a model is being unserialized, check if it needs to be booted.
*
* @return void
*/
public function __wakeup()
{
$this->bootIfNotBooted();
}
}
| joecohens/framework | src/Illuminate/Database/Eloquent/Model.php | PHP | mit | 39,540 |
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using ECommon.Components;
using ECommon.Scheduling;
using ECommon.Socketing;
using EQueue.Protocols;
namespace EQueue.Broker.Client
{
public class ConsumerManager
{
private readonly ConcurrentDictionary<string, ConsumerGroup> _consumerGroupDict = new ConcurrentDictionary<string, ConsumerGroup>();
private readonly IScheduleService _scheduleService;
public ConsumerManager()
{
_scheduleService = ObjectContainer.Resolve<IScheduleService>();
}
public void Start()
{
_consumerGroupDict.Clear();
_scheduleService.StartTask("ScanNotActiveConsumer", ScanNotActiveConsumer, 1000, 1000);
}
public void Shutdown()
{
_consumerGroupDict.Clear();
_scheduleService.StopTask("ScanNotActiveConsumer");
}
public void RegisterConsumer(string groupName, string consumerId, IEnumerable<string> subscriptionTopics, IEnumerable<MessageQueueEx> consumingQueues, ITcpConnection connection)
{
var consumerGroup = _consumerGroupDict.GetOrAdd(groupName, key => new ConsumerGroup(key));
consumerGroup.RegisterConsumer(connection, consumerId, subscriptionTopics.ToList(), consumingQueues.ToList());
}
public void RemoveConsumer(string connectionId)
{
foreach (var consumerGroup in _consumerGroupDict.Values)
{
consumerGroup.RemoveConsumer(connectionId);
}
}
public int GetConsumerGroupCount()
{
return _consumerGroupDict.Count;
}
public IEnumerable<ConsumerGroup> GetAllConsumerGroups()
{
return _consumerGroupDict.Values.ToList();
}
public int GetAllConsumerCount()
{
return GetAllConsumerGroups().Sum(x => x.GetConsumerCount());
}
public ConsumerGroup GetConsumerGroup(string groupName)
{
ConsumerGroup consumerGroup;
if (_consumerGroupDict.TryGetValue(groupName, out consumerGroup))
{
return consumerGroup;
}
return null;
}
public int GetConsumerCount(string groupName)
{
ConsumerGroup consumerGroup;
if (_consumerGroupDict.TryGetValue(groupName, out consumerGroup))
{
return consumerGroup.GetConsumerCount();
}
return 0;
}
public int GetClientCacheMessageCount(string groupName, string topic, int queueId)
{
ConsumerGroup consumerGroup;
if (_consumerGroupDict.TryGetValue(groupName, out consumerGroup))
{
return consumerGroup.GetClientCacheMessageCount(topic, queueId);
}
return 0;
}
public bool IsConsumerActive(string consumerGroup, string consumerId)
{
var group = GetConsumerGroup(consumerGroup);
return group != null && group.IsConsumerActive(consumerId);
}
public bool IsConsumerExistForQueue(string topic, int queueId)
{
var groups = GetAllConsumerGroups();
foreach (var group in groups)
{
if (group.IsConsumerExistForQueue(topic, queueId))
{
return true;
}
}
return false;
}
private void ScanNotActiveConsumer()
{
foreach (var consumerGroup in _consumerGroupDict.Values)
{
consumerGroup.RemoveNotActiveConsumers();
}
}
}
}
| Aaron-Liu/equeue | src/EQueue/Broker/Client/ConsumerManager.cs | C# | mit | 3,773 |
<?php
namespace Phrest\Skeleton\v1\Requests\Users;
use Phrest\SDK\Request\AbstractRequest;
use Phrest\SDK\Request\RequestOptions;
use Phrest\SDK\PhrestSDK;
class CreateUserRequest extends AbstractRequest
{
/**
* @var string
*/
private $path = '/v1/users/';
/**
* @var string
*/
public $name = null;
/**
* @var string
*/
public $email = null;
/**
* @var string
*/
public $password = null;
/**
* @param string $name
* @param string $email
* @param string $password
*/
public function __construct($name = null, $email = null, $password = null)
{
$this->name = $name;
$this->email = $email;
$this->password = $password;
}
/**
*
*/
public function create()
{
$requestOptions = new RequestOptions();
$requestOptions->addPostParams(
[
'name' => $this->name,
'email' => $this->email,
'password' => $this->password,
]
);
return PhrestSDK::getResponse(
self::METHOD_POST,
$this->path,
$requestOptions
);
}
/**
* @param string $name
*
* @return static
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @param string $email
*
* @return static
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @param string $password
*
* @return static
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
}
| phrest/skeleton | src/v1/Requests/Users/CreateUserRequest.php | PHP | mit | 1,538 |
'use strict';
// https://github.com/betsol/gulp-require-tasks
// Require the module.
const gulpRequireTasks = require('gulp-require-tasks');
const gulp = require('gulp');
const env = require('../index');
// Call it when necessary.
gulpRequireTasks({
// Pass any options to it. Please see below.
path: env.inConfigs('gulp', 'tasks')// This is default
});
gulp.task('default', ['scripts:build', 'json-copy:build']);
| ilivebox/microsb | node/configs/gulp/gulpfile.js | JavaScript | mit | 421 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CacheCow.Server.EntityTagStore.SqlServer
{
internal class ColumnNames
{
public static string CacheKeyHash = "CacheKeyHash";
public static string RoutePattern = "RoutePattern";
public static string ResourceUri = "ResourceUri";
public static string ETag = "ETag";
public static string LastModified = "LastModified";
}
}
| Hotkey/CacheCow | src/CacheCow.Server.EntityTagStore.SqlServer/ColumnNames.cs | C# | mit | 445 |
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const Laptop24: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default Laptop24;
| mcliment/DefinitelyTyped | types/carbon__icons-react/lib/laptop/24.d.ts | TypeScript | mit | 214 |
/* @flow */
"use strict";
var _inherits = require("babel-runtime/helpers/inherits")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _getIterator = require("babel-runtime/core-js/get-iterator")["default"];
var _Object$assign = require("babel-runtime/core-js/object/assign")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _buffer = require("./buffer");
var _buffer2 = _interopRequireDefault(_buffer);
var _node = require("./node");
var _node2 = _interopRequireDefault(_node);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var Printer = (function (_Buffer) {
_inherits(Printer, _Buffer);
function Printer() {
_classCallCheck(this, Printer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_Buffer.call.apply(_Buffer, [this].concat(args));
this.insideAux = false;
this.printAuxAfterOnNextUserNode = false;
}
Printer.prototype.print = function print(node, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!node) return;
if (parent && parent._compact) {
node._compact = true;
}
var oldInAux = this.insideAux;
this.insideAux = !node.loc;
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
var printMethod = this[node.type];
if (!printMethod) {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
if (node.loc) this.printAuxAfterComment();
this.printAuxBeforeComment(oldInAux);
var needsParens = _node2["default"].needsParens(node, parent);
if (needsParens) this.push("(");
this.printLeadingComments(node, parent);
this.catchUp(node);
this._printNewline(true, node, parent, opts);
if (opts.before) opts.before();
this.map.mark(node, "start");
this._print(node, parent);
this.printTrailingComments(node, parent);
if (needsParens) this.push(")");
// end
this.map.mark(node, "end");
if (opts.after) opts.after();
this.format.concise = oldConcise;
this.insideAux = oldInAux;
this._printNewline(false, node, parent, opts);
};
Printer.prototype.printAuxBeforeComment = function printAuxBeforeComment(wasInAux) {
var comment = this.format.auxiliaryCommentBefore;
if (!wasInAux && this.insideAux) {
this.printAuxAfterOnNextUserNode = true;
if (comment) this.printComment({
type: "CommentBlock",
value: comment
});
}
};
Printer.prototype.printAuxAfterComment = function printAuxAfterComment() {
if (this.printAuxAfterOnNextUserNode) {
this.printAuxAfterOnNextUserNode = false;
var comment = this.format.auxiliaryCommentAfter;
if (comment) this.printComment({
type: "CommentBlock",
value: comment
});
}
};
Printer.prototype.getPossibleRaw = function getPossibleRaw(node) {
var extra = node.extra;
if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
return extra.raw;
}
};
Printer.prototype._print = function _print(node, parent) {
var extra = this.getPossibleRaw(node);
if (extra) {
this.push("");
this._push(extra);
} else {
var printMethod = this[node.type];
printMethod.call(this, node, parent);
}
};
Printer.prototype.printJoin = function printJoin(nodes /*: ?Array*/, parent /*: Object*/) {
// istanbul ignore next
var _this = this;
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!nodes || !nodes.length) return;
var len = nodes.length;
var node = undefined,
i = undefined;
if (opts.indent) this.indent();
var printOpts = {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: function after() {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
_this.push(opts.separator);
}
}
};
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
this.print(node, parent, printOpts);
}
if (opts.indent) this.dedent();
};
Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) {
var indent = !!node.leadingComments;
if (indent) this.indent();
this.print(node, parent);
if (indent) this.dedent();
};
Printer.prototype.printBlock = function printBlock(parent) {
var node = parent.body;
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
this.print(node, parent);
}
};
Printer.prototype.generateComment = function generateComment(comment) {
var val = comment.value;
if (comment.type === "CommentLine") {
val = "//" + val;
} else {
val = "/*" + val + "*/";
}
return val;
};
Printer.prototype.printTrailingComments = function printTrailingComments(node, parent) {
this.printComments(this.getComments("trailingComments", node, parent));
};
Printer.prototype.printLeadingComments = function printLeadingComments(node, parent) {
this.printComments(this.getComments("leadingComments", node, parent));
};
Printer.prototype.printInnerComments = function printInnerComments(node) {
var indent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
if (!node.innerComments) return;
if (indent) this.indent();
this.printComments(node.innerComments);
if (indent) this.dedent();
};
Printer.prototype.printSequence = function printSequence(nodes, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
opts.statement = true;
return this.printJoin(nodes, parent, opts);
};
Printer.prototype.printList = function printList(items, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (opts.separator == null) {
opts.separator = ",";
if (!this.format.compact) opts.separator += " ";
}
return this.printJoin(items, parent, opts);
};
Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) {
if (!opts.statement && !_node2["default"].isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace && this.tokens.length) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = _node2["default"].needsWhitespaceAfter;
if (leading) needs = _node2["default"].needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buf) lines = 0;
}
this.newline(lines);
};
Printer.prototype.getComments = function getComments(key, node) {
return node && node[key] || [];
};
Printer.prototype.shouldPrintComment = function shouldPrintComment(comment) {
if (this.format.shouldPrintComment) {
return this.format.shouldPrintComment(comment.value);
} else {
if (comment.value.indexOf("@license") >= 0 || comment.value.indexOf("@preserve") >= 0) {
return true;
} else {
return this.format.comments;
}
}
};
Printer.prototype.printComment = function printComment(comment) {
if (!this.shouldPrintComment(comment)) return;
if (comment.ignore) return;
comment.ignore = true;
if (comment.start != null) {
if (this.printedCommentStarts[comment.start]) return;
this.printedCommentStarts[comment.start] = true;
}
this.catchUp(comment);
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
var column = this.position.column;
var val = this.generateComment(comment);
if (column && !this.isLast(["\n", " ", "[", "{"])) {
this._push(" ");
column++;
}
//
if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc && comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, "\n" + _repeating2["default"](" ", indent));
}
if (column === 0) {
val = this.getIndent() + val;
}
// force a newline for line comments when retainLines is set in case the next printed node
// doesn't catch up
if ((this.format.compact || this.format.retainLines) && comment.type === "CommentLine") {
val += "\n";
}
//
this._push(val);
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
};
Printer.prototype.printComments = function printComments(comments /*:: ?: Array<Object>*/) {
if (!comments || !comments.length) return;
for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var comment = _ref;
this.printComment(comment);
}
};
return Printer;
})(_buffer2["default"]);
exports["default"] = Printer;
var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")];
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
var generator = _arr[_i2];
_Object$assign(Printer.prototype, generator);
}
module.exports = exports["default"]; | Shashank92/promises-demo | node_modules/gulp-babel/node_modules/babel-core/node_modules/babel-generator/lib/printer.js | JavaScript | mit | 10,786 |
using System;
using System.ComponentModel;
using System.Web;
using System.Web.Security;
using System.Xml.Linq;
using System.Xml.XPath;
using Umbraco.Core;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Models;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.Core.Xml;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Umbraco.Core.Cache;
namespace Umbraco.Web
{
/// <summary>
/// A helper class that provides many useful methods and functionality for using Umbraco in templates
/// </summary>
public class UmbracoHelper : IUmbracoComponentRenderer
{
private readonly UmbracoContext _umbracoContext;
private readonly IPublishedContent _currentPage;
private readonly ITypedPublishedContentQuery _typedQuery;
private readonly IDynamicPublishedContentQuery _dynamicQuery;
private readonly HtmlStringUtilities _stringUtilities = new HtmlStringUtilities();
private IUmbracoComponentRenderer _componentRenderer;
private PublishedContentQuery _query;
private MembershipHelper _membershipHelper;
private TagQuery _tag;
private IDataTypeService _dataTypeService;
private UrlProvider _urlProvider;
private ICultureDictionary _cultureDictionary;
/// <summary>
/// Lazy instantiates the tag context
/// </summary>
public TagQuery TagQuery
{
//TODO: Unfortunately we cannot change this return value to be ITagQuery
// since it's a breaking change, need to fix it for v8
// http://issues.umbraco.org/issue/U4-6899
get
{
return _tag ??
(_tag = new TagQuery(UmbracoContext.Application.Services.TagService,
_typedQuery ?? ContentQuery));
}
}
/// <summary>
/// Lazy instantiates the query context if not specified in the constructor
/// </summary>
public PublishedContentQuery ContentQuery
{
get
{
//If the content query doesn't exist it will either be created with the ITypedPublishedContentQuery, IDynamicPublishedContentQuery
// used to construct this instance or with the content caches of the UmbracoContext
return _query ??
(_query = _typedQuery != null
? new PublishedContentQuery(_typedQuery, _dynamicQuery)
: new PublishedContentQuery(UmbracoContext.ContentCache, UmbracoContext.MediaCache));
}
}
/// <summary>
/// Helper method to ensure an umbraco context is set when it is needed
/// </summary>
public UmbracoContext UmbracoContext
{
get
{
if (_umbracoContext == null)
{
throw new NullReferenceException("No " + typeof(UmbracoContext) + " reference has been set for this " + typeof(UmbracoHelper) + " instance");
}
return _umbracoContext;
}
}
/// <summary>
/// Lazy instantiates the membership helper if not specified in the constructor
/// </summary>
public MembershipHelper MembershipHelper
{
get { return _membershipHelper ?? (_membershipHelper = new MembershipHelper(UmbracoContext)); }
}
/// <summary>
/// Lazy instantiates the UrlProvider if not specified in the constructor
/// </summary>
public UrlProvider UrlProvider
{
get { return _urlProvider ?? (_urlProvider = UmbracoContext.UrlProvider); }
}
/// <summary>
/// Lazy instantiates the IDataTypeService if not specified in the constructor
/// </summary>
public IDataTypeService DataTypeService
{
get { return _dataTypeService ?? (_dataTypeService = UmbracoContext.Application.Services.DataTypeService); }
}
/// <summary>
/// Lazy instantiates the IUmbracoComponentRenderer if not specified in the constructor
/// </summary>
public IUmbracoComponentRenderer UmbracoComponentRenderer
{
get { return _componentRenderer ?? (_componentRenderer = new UmbracoComponentRenderer(UmbracoContext)); }
}
#region Constructors
/// <summary>
/// Empty constructor to create an umbraco helper for access to methods that don't have dependencies
/// </summary>
public UmbracoHelper()
{
}
/// <summary>
/// Constructor accepting all dependencies
/// </summary>
/// <param name="umbracoContext"></param>
/// <param name="content"></param>
/// <param name="typedQuery"></param>
/// <param name="dynamicQuery"></param>
/// <param name="tagQuery"></param>
/// <param name="dataTypeService"></param>
/// <param name="urlProvider"></param>
/// <param name="cultureDictionary"></param>
/// <param name="componentRenderer"></param>
/// <param name="membershipHelper"></param>
/// <remarks>
/// This constructor can be used to create a testable UmbracoHelper
/// </remarks>
public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content,
ITypedPublishedContentQuery typedQuery,
IDynamicPublishedContentQuery dynamicQuery,
ITagQuery tagQuery,
IDataTypeService dataTypeService,
UrlProvider urlProvider,
ICultureDictionary cultureDictionary,
IUmbracoComponentRenderer componentRenderer,
MembershipHelper membershipHelper)
{
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
if (content == null) throw new ArgumentNullException("content");
if (typedQuery == null) throw new ArgumentNullException("typedQuery");
if (dynamicQuery == null) throw new ArgumentNullException("dynamicQuery");
if (tagQuery == null) throw new ArgumentNullException("tagQuery");
if (dataTypeService == null) throw new ArgumentNullException("dataTypeService");
if (urlProvider == null) throw new ArgumentNullException("urlProvider");
if (cultureDictionary == null) throw new ArgumentNullException("cultureDictionary");
if (componentRenderer == null) throw new ArgumentNullException("componentRenderer");
if (membershipHelper == null) throw new ArgumentNullException("membershipHelper");
_umbracoContext = umbracoContext;
_tag = new TagQuery(tagQuery);
_dataTypeService = dataTypeService;
_urlProvider = urlProvider;
_cultureDictionary = cultureDictionary;
_componentRenderer = componentRenderer;
_membershipHelper = membershipHelper;
_currentPage = content;
_typedQuery = typedQuery;
_dynamicQuery = dynamicQuery;
}
[Obsolete("Use the constructor specifying all dependencies")]
[EditorBrowsable(EditorBrowsableState.Never)]
public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content, PublishedContentQuery query)
: this(umbracoContext)
{
if (content == null) throw new ArgumentNullException("content");
if (query == null) throw new ArgumentNullException("query");
_currentPage = content;
_query = query;
}
/// <summary>
/// Custom constructor setting the current page to the parameter passed in
/// </summary>
/// <param name="umbracoContext"></param>
/// <param name="content"></param>
public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content)
: this(umbracoContext)
{
if (content == null) throw new ArgumentNullException("content");
_currentPage = content;
}
/// <summary>
/// Standard constructor setting the current page to the page that has been routed to
/// </summary>
/// <param name="umbracoContext"></param>
public UmbracoHelper(UmbracoContext umbracoContext)
{
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
if (umbracoContext.RoutingContext == null) throw new NullReferenceException("The RoutingContext on the UmbracoContext cannot be null");
_umbracoContext = umbracoContext;
if (_umbracoContext.IsFrontEndUmbracoRequest)
{
_currentPage = _umbracoContext.PublishedContentRequest.PublishedContent;
}
}
[Obsolete("Use the constructor specifying all dependencies")]
[EditorBrowsable(EditorBrowsableState.Never)]
public UmbracoHelper(UmbracoContext umbracoContext, PublishedContentQuery query)
: this(umbracoContext)
{
if (query == null) throw new ArgumentNullException("query");
_query = query;
}
#endregion
/// <summary>
/// Returns the current IPublishedContent item assigned to the UmbracoHelper
/// </summary>
/// <remarks>
/// Note that this is the assigned IPublishedContent item to the UmbracoHelper, this is not necessarily the Current IPublishedContent item
/// being rendered. This IPublishedContent object is contextual to the current UmbracoHelper instance.
///
/// In some cases accessing this property will throw an exception if there is not IPublishedContent assigned to the Helper
/// this will only ever happen if the Helper is constructed with an UmbracoContext and it is not a front-end request
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if the UmbracoHelper is constructed with an UmbracoContext and it is not a front-end request</exception>
public IPublishedContent AssignedContentItem
{
get
{
if (_currentPage == null)
throw new InvalidOperationException("Cannot return the " + typeof(IPublishedContent).Name + " because the " + typeof(UmbracoHelper).Name + " was constructed with an " + typeof(UmbracoContext).Name + " and the current request is not a front-end request.");
return _currentPage;
}
}
/// <summary>
/// Renders the template for the specified pageId and an optional altTemplateId
/// </summary>
/// <param name="pageId"></param>
/// <param name="altTemplateId">If not specified, will use the template assigned to the node</param>
/// <returns></returns>
public IHtmlString RenderTemplate(int pageId, int? altTemplateId = null)
{
return UmbracoComponentRenderer.RenderTemplate(pageId, altTemplateId);
}
#region RenderMacro
/// <summary>
/// Renders the macro with the specified alias.
/// </summary>
/// <param name="alias">The alias.</param>
/// <returns></returns>
public IHtmlString RenderMacro(string alias)
{
return UmbracoComponentRenderer.RenderMacro(alias, new { });
}
/// <summary>
/// Renders the macro with the specified alias, passing in the specified parameters.
/// </summary>
/// <param name="alias">The alias.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public IHtmlString RenderMacro(string alias, object parameters)
{
return UmbracoComponentRenderer.RenderMacro(alias, parameters.ToDictionary<object>());
}
/// <summary>
/// Renders the macro with the specified alias, passing in the specified parameters.
/// </summary>
/// <param name="alias">The alias.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public IHtmlString RenderMacro(string alias, IDictionary<string, object> parameters)
{
return UmbracoComponentRenderer.RenderMacro(alias, parameters);
}
#endregion
#region Field
/// <summary>
/// Renders an field to the template
/// </summary>
/// <param name="fieldAlias"></param>
/// <param name="altFieldAlias"></param>
/// <param name="altText"></param>
/// <param name="insertBefore"></param>
/// <param name="insertAfter"></param>
/// <param name="recursive"></param>
/// <param name="convertLineBreaks"></param>
/// <param name="removeParagraphTags"></param>
/// <param name="casing"></param>
/// <param name="encoding"></param>
/// <param name="formatAsDate"></param>
/// <param name="formatAsDateWithTime"></param>
/// <param name="formatAsDateWithTimeSeparator"></param>
//// <param name="formatString"></param>
/// <returns></returns>
public IHtmlString Field(string fieldAlias,
string altFieldAlias = "", string altText = "", string insertBefore = "", string insertAfter = "",
bool recursive = false, bool convertLineBreaks = false, bool removeParagraphTags = false,
RenderFieldCaseType casing = RenderFieldCaseType.Unchanged,
RenderFieldEncodingType encoding = RenderFieldEncodingType.Unchanged,
bool formatAsDate = false,
bool formatAsDateWithTime = false,
string formatAsDateWithTimeSeparator = "")
{
return UmbracoComponentRenderer.Field(AssignedContentItem, fieldAlias, altFieldAlias,
altText, insertBefore, insertAfter, recursive, convertLineBreaks, removeParagraphTags,
casing, encoding, formatAsDate, formatAsDateWithTime, formatAsDateWithTimeSeparator);
}
/// <summary>
/// Renders an field to the template
/// </summary>
/// <param name="currentPage"></param>
/// <param name="fieldAlias"></param>
/// <param name="altFieldAlias"></param>
/// <param name="altText"></param>
/// <param name="insertBefore"></param>
/// <param name="insertAfter"></param>
/// <param name="recursive"></param>
/// <param name="convertLineBreaks"></param>
/// <param name="removeParagraphTags"></param>
/// <param name="casing"></param>
/// <param name="encoding"></param>
/// <param name="formatAsDate"></param>
/// <param name="formatAsDateWithTime"></param>
/// <param name="formatAsDateWithTimeSeparator"></param>
//// <param name="formatString"></param>
/// <returns></returns>
public IHtmlString Field(IPublishedContent currentPage, string fieldAlias,
string altFieldAlias = "", string altText = "", string insertBefore = "", string insertAfter = "",
bool recursive = false, bool convertLineBreaks = false, bool removeParagraphTags = false,
RenderFieldCaseType casing = RenderFieldCaseType.Unchanged,
RenderFieldEncodingType encoding = RenderFieldEncodingType.Unchanged,
bool formatAsDate = false,
bool formatAsDateWithTime = false,
string formatAsDateWithTimeSeparator = "")
{
return UmbracoComponentRenderer.Field(currentPage, fieldAlias, altFieldAlias,
altText, insertBefore, insertAfter, recursive, convertLineBreaks, removeParagraphTags,
casing, encoding, formatAsDate, formatAsDateWithTime, formatAsDateWithTimeSeparator);
}
#endregion
#region Dictionary
/// <summary>
/// Returns the dictionary value for the key specified
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetDictionaryValue(string key)
{
return CultureDictionary[key];
}
/// <summary>
/// Returns the dictionary value for the key specified, and if empty returns the specified default fall back value
/// </summary>
/// <param name="key">key of dictionary item</param>
/// <param name="altText">fall back text if dictionary item is empty - Name altText to match Umbraco.Field</param>
/// <returns></returns>
public string GetDictionaryValue(string key, string altText)
{
var dictionaryValue = GetDictionaryValue(key);
if (String.IsNullOrWhiteSpace(dictionaryValue))
{
dictionaryValue = altText;
}
return dictionaryValue;
}
/// <summary>
/// Returns the ICultureDictionary for access to dictionary items
/// </summary>
public ICultureDictionary CultureDictionary
{
get
{
if (_cultureDictionary == null)
{
var factory = CultureDictionaryFactoryResolver.Current.Factory;
_cultureDictionary = factory.CreateDictionary();
}
return _cultureDictionary;
}
}
#endregion
#region Membership
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the IsProtected method that only specifies path")]
public bool IsProtected(int documentId, string path)
{
return IsProtected(path.EnsureEndsWith("," + documentId));
}
/// <summary>
/// Check if a document object is protected by the "Protect Pages" functionality in umbraco
/// </summary>
/// <param name="path">The full path of the document object to check</param>
/// <returns>True if the document object is protected</returns>
public bool IsProtected(string path)
{
return UmbracoContext.Application.Services.PublicAccessService.IsProtected(path);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the MemberHasAccess method that only specifies path")]
public bool MemberHasAccess(int nodeId, string path)
{
return MemberHasAccess(path.EnsureEndsWith("," + nodeId));
}
/// <summary>
/// Check if the current user has access to a document
/// </summary>
/// <param name="path">The full path of the document object to check</param>
/// <returns>True if the current user has access or if the current document isn't protected</returns>
public bool MemberHasAccess(string path)
{
if (IsProtected(path))
{
return MembershipHelper.IsLoggedIn()
&& UmbracoContext.Application.Services.PublicAccessService.HasAccess(path, GetCurrentMember(), Roles.Provider);
}
return true;
}
/// <summary>
/// Gets (or adds) the current member from the current request cache
/// </summary>
private MembershipUser GetCurrentMember()
{
return UmbracoContext.Application.ApplicationCache.RequestCache
.GetCacheItem<MembershipUser>("UmbracoHelper.GetCurrentMember", () =>
{
var provider = Core.Security.MembershipProviderExtensions.GetMembersMembershipProvider();
return provider.GetCurrentUser();
});
}
/// <summary>
/// Whether or not the current member is logged in (based on the membership provider)
/// </summary>
/// <returns>True is the current user is logged in</returns>
public bool MemberIsLoggedOn()
{
return MembershipHelper.IsLoggedIn();
}
#endregion
#region NiceUrls
/// <summary>
/// Returns a string with a friendly url from a node.
/// IE.: Instead of having /482 (id) as an url, you can have
/// /screenshots/developer/macros (spoken url)
/// </summary>
/// <param name="nodeId">Identifier for the node that should be returned</param>
/// <returns>String with a friendly url from a node</returns>
public string NiceUrl(int nodeId)
{
return Url(nodeId);
}
/// <summary>
/// Gets the url of a content identified by its identifier.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <returns>The url for the content.</returns>
public string Url(int contentId)
{
return UrlProvider.GetUrl(contentId);
}
/// <summary>
/// Gets the url of a content identified by its identifier, in a specified mode.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="mode">The mode.</param>
/// <returns>The url for the content.</returns>
public string Url(int contentId, UrlProviderMode mode)
{
return UrlProvider.GetUrl(contentId, mode);
}
/// <summary>
/// This method will always add the domain to the path if the hostnames are set up correctly.
/// </summary>
/// <param name="nodeId">Identifier for the node that should be returned</param>
/// <returns>String with a friendly url with full domain from a node</returns>
public string NiceUrlWithDomain(int nodeId)
{
return UrlAbsolute(nodeId);
}
/// <summary>
/// Gets the absolute url of a content identified by its identifier.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <returns>The absolute url for the content.</returns>
public string UrlAbsolute(int contentId)
{
return UrlProvider.GetUrl(contentId, true);
}
#endregion
#region Members
public IPublishedContent TypedMember(object id)
{
var asInt = id.TryConvertTo<int>();
return asInt ? MembershipHelper.GetById(asInt.Result) : MembershipHelper.GetByProviderKey(id);
}
public IPublishedContent TypedMember(int id)
{
return MembershipHelper.GetById(id);
}
public IPublishedContent TypedMember(string id)
{
var asInt = id.TryConvertTo<int>();
return asInt ? MembershipHelper.GetById(asInt.Result) : MembershipHelper.GetByProviderKey(id);
}
public dynamic Member(object id)
{
var asInt = id.TryConvertTo<int>();
return asInt
? MembershipHelper.GetById(asInt.Result).AsDynamic()
: MembershipHelper.GetByProviderKey(id).AsDynamic();
}
public dynamic Member(int id)
{
return MembershipHelper.GetById(id).AsDynamic();
}
public dynamic Member(string id)
{
var asInt = id.TryConvertTo<int>();
return asInt
? MembershipHelper.GetById(asInt.Result).AsDynamic()
: MembershipHelper.GetByProviderKey(id).AsDynamic();
}
#endregion
#region Content
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier, or the key, of the content item.</param>
/// <returns>The content, or null of the content item is not in the cache.</returns>
public IPublishedContent TypedContent(object id)
{
return TypedContentForObject(id);
}
private IPublishedContent TypedContentForObject(object id)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
return ContentQuery.TypedContent(intId);
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
return ContentQuery.TypedContent(guidId);
return null;
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier of the content item.</param>
/// <returns>The content, or null of the content item is not in the cache.</returns>
public IPublishedContent TypedContent(int id)
{
return ContentQuery.TypedContent(id);
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The key of the content item.</param>
/// <returns>The content, or null of the content item is not in the cache.</returns>
public IPublishedContent TypedContent(Guid id)
{
return ContentQuery.TypedContent(id);
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier, or the key, of the content item.</param>
/// <returns>The content, or null of the content item is not in the cache.</returns>
public IPublishedContent TypedContent(string id)
{
return TypedContentForObject(id);
}
public IPublishedContent TypedContentSingleAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.TypedContentSingleAtXPath(xpath, vars);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public IEnumerable<IPublishedContent> TypedContent(params object[] ids)
{
return TypedContentForObjects(ids);
}
private IEnumerable<IPublishedContent> TypedContentForObjects(IEnumerable<object> ids)
{
var idsA = ids.ToArray();
IEnumerable<int> intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.TypedContent(intIds);
IEnumerable<Guid> guidIds;
if (ConvertIdsObjectToGuids(idsA, out guidIds))
return ContentQuery.TypedContent(guidIds);
return Enumerable.Empty<IPublishedContent>();
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
public IEnumerable<IPublishedContent> TypedContent(params int[] ids)
{
return ContentQuery.TypedContent(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The keys of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
public IEnumerable<IPublishedContent> TypedContent(params Guid[] ids)
{
return ContentQuery.TypedContent(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public IEnumerable<IPublishedContent> TypedContent(params string[] ids)
{
return TypedContentForObjects(ids);
}
/// <summary>
/// Gets the contents corresponding to the identifiers.
/// </summary>
/// <param name="ids">The content identifiers.</param>
/// <returns>The existing contents corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing content, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedContent(IEnumerable<object> ids)
{
return TypedContentForObjects(ids);
}
/// <summary>
/// Gets the contents corresponding to the identifiers.
/// </summary>
/// <param name="ids">The content identifiers.</param>
/// <returns>The existing contents corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing content, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedContent(IEnumerable<string> ids)
{
return TypedContentForObjects(ids);
}
/// <summary>
/// Gets the contents corresponding to the identifiers.
/// </summary>
/// <param name="ids">The content identifiers.</param>
/// <returns>The existing contents corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing content, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedContent(IEnumerable<int> ids)
{
return ContentQuery.TypedContent(ids);
}
public IEnumerable<IPublishedContent> TypedContentAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.TypedContentAtXPath(xpath, vars);
}
public IEnumerable<IPublishedContent> TypedContentAtXPath(XPathExpression xpath, params XPathVariable[] vars)
{
return ContentQuery.TypedContentAtXPath(xpath, vars);
}
public IEnumerable<IPublishedContent> TypedContentAtRoot()
{
return ContentQuery.TypedContentAtRoot();
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier, or the key, of the content item.</param>
/// <returns>The content, or DynamicNull of the content item is not in the cache.</returns>
public dynamic Content(object id)
{
return ContentForObject(id);
}
private dynamic ContentForObject(object id)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
return ContentQuery.Content(intId);
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
return ContentQuery.Content(guidId);
return DynamicNull.Null;
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier of the content item.</param>
/// <returns>The content, or DynamicNull of the content item is not in the cache.</returns>
public dynamic Content(int id)
{
return ContentQuery.Content(id);
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier, or the key, of the content item.</param>
/// <returns>The content, or DynamicNull of the content item is not in the cache.</returns>
public dynamic Content(string id)
{
return ContentForObject(id);
}
public dynamic ContentSingleAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentSingleAtXPath(xpath, vars);
}
public dynamic ContentSingleAtXPath(XPathExpression xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentSingleAtXPath(xpath, vars);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public dynamic Content(params object[] ids)
{
return ContentForObjects(ids);
}
private dynamic ContentForObjects(IEnumerable<object> ids)
{
var idsA = ids.ToArray();
IEnumerable<int> intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.Content(intIds);
IEnumerable<Guid> guidIds;
if (ConvertIdsObjectToGuids(idsA, out guidIds))
return ContentQuery.Content(guidIds);
return Enumerable.Empty<IPublishedContent>();
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
public dynamic Content(params int[] ids)
{
return ContentQuery.Content(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public dynamic Content(params string[] ids)
{
return ContentForObjects(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public dynamic Content(IEnumerable<object> ids)
{
return ContentForObjects(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
public dynamic Content(IEnumerable<int> ids)
{
return ContentQuery.Content(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public dynamic Content(IEnumerable<string> ids)
{
return ContentForObjects(ids);
}
public dynamic ContentAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentAtXPath(xpath, vars);
}
public dynamic ContentAtXPath(XPathExpression xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentAtXPath(xpath, vars);
}
public dynamic ContentAtRoot()
{
return ContentQuery.ContentAtRoot();
}
private static bool ConvertIdObjectToInt(object id, out int intId)
{
var s = id as string;
if (s != null)
{
return int.TryParse(s, out intId);
}
if (id is int)
{
intId = (int) id;
return true;
}
intId = default(int);
return false;
}
private static bool ConvertIdObjectToGuid(object id, out Guid guidId)
{
var s = id as string;
if (s != null)
{
return Guid.TryParse(s, out guidId);
}
if (id is Guid)
{
guidId = (Guid) id;
return true;
}
guidId = default(Guid);
return false;
}
private static bool ConvertIdsObjectToInts(IEnumerable<object> ids, out IEnumerable<int> intIds)
{
var list = new List<int>();
intIds = null;
foreach (var id in ids)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
list.Add(intId);
else
return false; // if one of them is not an int, fail
}
intIds = list;
return true;
}
private static bool ConvertIdsObjectToGuids(IEnumerable<object> ids, out IEnumerable<Guid> guidIds)
{
var list = new List<Guid>();
guidIds = null;
foreach (var id in ids)
{
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
list.Add(guidId);
else
return false; // if one of them is not a guid, fail
}
guidIds = list;
return true;
}
#endregion
#region Media
/// <summary>
/// Overloaded method accepting an 'object' type
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <remarks>
/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass
/// this result in to this method.
/// This method will throw an exception if the value is not of type int or string.
/// </remarks>
public IPublishedContent TypedMedia(object id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.TypedMedia(intId) : null;
}
public IPublishedContent TypedMedia(int id)
{
return ContentQuery.TypedMedia(id);
}
public IPublishedContent TypedMedia(string id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.TypedMedia(intId) : null;
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(params object[] ids)
{
return TypedMediaForObjects(ids);
}
private IEnumerable<IPublishedContent> TypedMediaForObjects(IEnumerable<object> ids)
{
var idsA = ids.ToArray();
IEnumerable<int> intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.TypedMedia(intIds);
//IEnumerable<Guid> guidIds;
//if (ConvertIdsObjectToGuids(idsA, out guidIds))
// return ContentQuery.TypedMedia(guidIds);
return Enumerable.Empty<IPublishedContent>();
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(params int[] ids)
{
return ContentQuery.TypedMedia(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(params string[] ids)
{
return TypedMediaForObjects(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<object> ids)
{
return TypedMediaForObjects(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<int> ids)
{
return ContentQuery.TypedMedia(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<string> ids)
{
return TypedMediaForObjects(ids);
}
public IEnumerable<IPublishedContent> TypedMediaAtRoot()
{
return ContentQuery.TypedMediaAtRoot();
}
public dynamic Media(object id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.Media(intId) : DynamicNull.Null;
}
public dynamic Media(int id)
{
return ContentQuery.Media(id);
}
public dynamic Media(string id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.Media(intId) : DynamicNull.Null;
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(params object[] ids)
{
return MediaForObjects(ids);
}
private dynamic MediaForObjects(IEnumerable<object> ids)
{
var idsA = ids.ToArray();
IEnumerable<int> intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.Media(intIds);
//IEnumerable<Guid> guidIds;
//if (ConvertIdsObjectToGuids(idsA, out guidIds))
// return ContentQuery.Media(guidIds);
return Enumerable.Empty<IPublishedContent>();
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(params int[] ids)
{
return ContentQuery.Media(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(params string[] ids)
{
return MediaForObjects(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(IEnumerable<object> ids)
{
return MediaForObjects(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(IEnumerable<int> ids)
{
return ContentQuery.Media(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(IEnumerable<string> ids)
{
return MediaForObjects(ids);
}
public dynamic MediaAtRoot()
{
return ContentQuery.MediaAtRoot();
}
#endregion
#region Search
/// <summary>
/// Searches content
/// </summary>
/// <param name="term"></param>
/// <param name="useWildCards"></param>
/// <param name="searchProvider"></param>
/// <returns></returns>
public dynamic Search(string term, bool useWildCards = true, string searchProvider = null)
{
return ContentQuery.Search(term, useWildCards, searchProvider);
}
/// <summary>
/// Searhes content
/// </summary>
/// <param name="criteria"></param>
/// <param name="searchProvider"></param>
/// <returns></returns>
public dynamic Search(Examine.SearchCriteria.ISearchCriteria criteria, Examine.Providers.BaseSearchProvider searchProvider = null)
{
return ContentQuery.Search(criteria, searchProvider);
}
/// <summary>
/// Searches content
/// </summary>
/// <param name="term"></param>
/// <param name="useWildCards"></param>
/// <param name="searchProvider"></param>
/// <returns></returns>
public IEnumerable<IPublishedContent> TypedSearch(string term, bool useWildCards = true, string searchProvider = null)
{
return ContentQuery.TypedSearch(term, useWildCards, searchProvider);
}
/// <summary>
/// Searhes content
/// </summary>
/// <param name="criteria"></param>
/// <param name="searchProvider"></param>
/// <returns></returns>
public IEnumerable<IPublishedContent> TypedSearch(Examine.SearchCriteria.ISearchCriteria criteria, Examine.Providers.BaseSearchProvider searchProvider = null)
{
return ContentQuery.TypedSearch(criteria, searchProvider);
}
#endregion
#region Xml
public dynamic ToDynamicXml(string xml)
{
if (string.IsNullOrWhiteSpace(xml)) return null;
var xElement = XElement.Parse(xml);
return new DynamicXml(xElement);
}
public dynamic ToDynamicXml(XElement xElement)
{
return new DynamicXml(xElement);
}
public dynamic ToDynamicXml(XPathNodeIterator xpni)
{
return new DynamicXml(xpni);
}
#endregion
#region Strings
/// <summary>
/// Replaces text line breaks with html line breaks
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The text with text line breaks replaced with html linebreaks (<br/>)</returns>
public string ReplaceLineBreaksForHtml(string text)
{
return _stringUtilities.ReplaceLineBreaksForHtml(text);
}
/// <summary>
/// Returns an MD5 hash of the string specified
/// </summary>
/// <param name="text">The text to create a hash from</param>
/// <returns>Md5 has of the string</returns>
public string CreateMd5Hash(string text)
{
return text.ToMd5();
}
/// <summary>
/// Strips all html tags from a given string, all contents of the tags will remain.
/// </summary>
public HtmlString StripHtml(IHtmlString html, params string[] tags)
{
return StripHtml(html.ToHtmlString(), tags);
}
/// <summary>
/// Strips all html tags from a given string, all contents of the tags will remain.
/// </summary>
public HtmlString StripHtml(DynamicNull html, params string[] tags)
{
return new HtmlString(string.Empty);
}
/// <summary>
/// Strips all html tags from a given string, all contents of the tags will remain.
/// </summary>
public HtmlString StripHtml(string html, params string[] tags)
{
return _stringUtilities.StripHtmlTags(html, tags);
}
/// <summary>
/// Will take the first non-null value in the collection and return the value of it.
/// </summary>
public string Coalesce(params object[] args)
{
return _stringUtilities.Coalesce<DynamicNull>(args);
}
/// <summary>
/// Will take the first non-null value in the collection and return the value of it.
/// </summary>
public string Concatenate(params object[] args)
{
return _stringUtilities.Concatenate<DynamicNull>(args);
}
/// <summary>
/// Joins any number of int/string/objects into one string and seperates them with the string seperator parameter.
/// </summary>
public string Join(string seperator, params object[] args)
{
return _stringUtilities.Join<DynamicNull>(seperator, args);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(IHtmlString html, int length)
{
return Truncate(html.ToHtmlString(), length, true, false);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(IHtmlString html, int length, bool addElipsis)
{
return Truncate(html.ToHtmlString(), length, addElipsis, false);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(IHtmlString html, int length, bool addElipsis, bool treatTagsAsContent)
{
return Truncate(html.ToHtmlString(), length, addElipsis, treatTagsAsContent);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(DynamicNull html, int length)
{
return new HtmlString(string.Empty);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(DynamicNull html, int length, bool addElipsis)
{
return new HtmlString(string.Empty);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(DynamicNull html, int length, bool addElipsis, bool treatTagsAsContent)
{
return new HtmlString(string.Empty);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(string html, int length)
{
return Truncate(html, length, true, false);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(string html, int length, bool addElipsis)
{
return Truncate(html, length, addElipsis, false);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(string html, int length, bool addElipsis, bool treatTagsAsContent)
{
return _stringUtilities.Truncate(html, length, addElipsis, treatTagsAsContent);
}
#endregion
#region If
/// <summary>
/// If the test is true, the string valueIfTrue will be returned, otherwise the valueIfFalse will be returned.
/// </summary>
public HtmlString If(bool test, string valueIfTrue, string valueIfFalse)
{
return test ? new HtmlString(valueIfTrue) : new HtmlString(valueIfFalse);
}
/// <summary>
/// If the test is true, the string valueIfTrue will be returned, otherwise the valueIfFalse will be returned.
/// </summary>
public HtmlString If(bool test, string valueIfTrue)
{
return test ? new HtmlString(valueIfTrue) : new HtmlString(string.Empty);
}
#endregion
#region Prevalues
/// <summary>
/// Gets a specific PreValue by its Id
/// </summary>
/// <param name="id">Id of the PreValue to retrieve the value from</param>
/// <returns>PreValue as a string</returns>
public string GetPreValueAsString(int id)
{
return DataTypeService.GetPreValueAsString(id);
}
#endregion
#region canvasdesigner
[Obsolete("Use EnableCanvasDesigner on the HtmlHelper extensions instead")]
public IHtmlString EnableCanvasDesigner()
{
return EnableCanvasDesigner(string.Empty, string.Empty);
}
[Obsolete("Use EnableCanvasDesigner on the HtmlHelper extensions instead")]
public IHtmlString EnableCanvasDesigner(string canvasdesignerConfigPath)
{
return EnableCanvasDesigner(canvasdesignerConfigPath, string.Empty);
}
[Obsolete("Use EnableCanvasDesigner on the HtmlHelper extensions instead")]
public IHtmlString EnableCanvasDesigner(string canvasdesignerConfigPath, string canvasdesignerPalettesPath)
{
var html = CreateHtmlHelper("");
var urlHelper = new UrlHelper(UmbracoContext.HttpContext.Request.RequestContext);
return html.EnableCanvasDesigner(urlHelper, UmbracoContext, canvasdesignerConfigPath, canvasdesignerPalettesPath);
}
[Obsolete("This shouldn't need to be used but because the obsolete extension methods above don't have access to the current HtmlHelper, we need to create a fake one, unfortunately however this will not pertain the current views viewdata, tempdata or model state so should not be used")]
private HtmlHelper CreateHtmlHelper(object model)
{
var cc = new ControllerContext
{
RequestContext = UmbracoContext.HttpContext.Request.RequestContext
};
var viewContext = new ViewContext(cc, new FakeView(), new ViewDataDictionary(model), new TempDataDictionary(), new StringWriter());
var htmlHelper = new HtmlHelper(viewContext, new ViewPage());
return htmlHelper;
}
[Obsolete("This shouldn't need to be used but because the obsolete extension methods above don't have access to the current HtmlHelper, we need to create a fake one, unfortunately however this will not pertain the current views viewdata, tempdata or model state so should not be used")]
private class FakeView : IView
{
public void Render(ViewContext viewContext, TextWriter writer)
{
}
}
#endregion
/// <summary>
/// This is used in methods like BeginUmbracoForm and SurfaceAction to generate an encrypted string which gets submitted in a request for which
/// Umbraco can decrypt during the routing process in order to delegate the request to a specific MVC Controller.
/// </summary>
/// <param name="controllerName"></param>
/// <param name="controllerAction"></param>
/// <param name="area"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
internal static string CreateEncryptedRouteString(string controllerName, string controllerAction, string area, object additionalRouteVals = null)
{
Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName");
Mandate.ParameterNotNullOrEmpty(controllerAction, "controllerAction");
Mandate.ParameterNotNull(area, "area");
//need to create a params string as Base64 to put into our hidden field to use during the routes
var surfaceRouteParams = string.Format("c={0}&a={1}&ar={2}",
HttpUtility.UrlEncode(controllerName),
HttpUtility.UrlEncode(controllerAction),
area);
//checking if the additional route values is already a dictionary and convert to querystring
string additionalRouteValsAsQuery;
if (additionalRouteVals != null)
{
var additionalRouteValsAsDictionary = additionalRouteVals as Dictionary<string, object>;
if (additionalRouteValsAsDictionary != null)
additionalRouteValsAsQuery = additionalRouteValsAsDictionary.ToQueryString();
else
additionalRouteValsAsQuery = additionalRouteVals.ToDictionary<object>().ToQueryString();
}
else
additionalRouteValsAsQuery = null;
if (additionalRouteValsAsQuery.IsNullOrWhiteSpace() == false)
surfaceRouteParams += "&" + additionalRouteValsAsQuery;
return surfaceRouteParams.EncryptWithMachineKey();
}
}
}
| gavinfaux/Umbraco-CMS | src/Umbraco.Web/UmbracoHelper.cs | C# | mit | 59,353 |
/**
* Gulp tasks for wrapping Browserify modules.
*/
const browserify = require("browserify");
const gulp = require("gulp");
const sourcemaps = require("gulp-sourcemaps");
const uglify = require("gulp-uglify");
const path = require("path");
const through2 = require("through2");
const buffer = require("vinyl-buffer");
const source = require("vinyl-source-stream");
const asyncUtil = require("../../util/async-util");
const clientPackages = require("../../util/client-packages");
const display = require("../../util/display");
const uc = require("../../util/unite-config");
gulp.task("build-bundle-app", async () => {
const uniteConfig = await uc.getUniteConfig();
const buildConfiguration = uc.getBuildConfiguration(uniteConfig, false);
if (buildConfiguration.bundle) {
display.info("Running", "Browserify for App");
const bApp = browserify({
debug: buildConfiguration.sourcemaps,
entries: `./${path.join(uniteConfig.dirs.www.dist, "entryPoint.js")}`
});
const vendorPackages = await clientPackages.getBundleVendorPackages(uniteConfig);
let hasStyleLoader = false;
Object.keys(vendorPackages).forEach((key) => {
bApp.exclude(key);
const idx = key.indexOf("systemjs");
if (idx >= 0 && !hasStyleLoader) {
hasStyleLoader = key === "systemjs-plugin-css";
}
});
bApp.transform("envify", {
NODE_ENV: buildConfiguration.minify ? "production" : "development",
global: true
});
bApp.transform("browserify-css", {
autoInject: hasStyleLoader
});
bApp.transform("stringify", {
appliesTo: {
includeExtensions: uniteConfig.viewExtensions.map(ext => `.${ext}`)
}
});
bApp.transform("babelify", {
global: true,
presets: ["@babel/preset-env"]
});
return asyncUtil.stream(bApp.bundle().on("error", (err) => {
display.error(err);
})
.pipe(source("app-bundle.js"))
.pipe(buffer())
.pipe(buildConfiguration.minify ? uglify()
.on("error", (err) => {
display.error(err.toString());
}) : through2.obj())
.pipe(buildConfiguration.sourcemaps ? sourcemaps.init({
loadMaps: true
}) : through2.obj())
.pipe(buildConfiguration.sourcemaps ?
sourcemaps.mapSources((sourcePath) => sourcePath.replace(/dist\//, "./")) : through2.obj())
.pipe(buildConfiguration.sourcemaps ? sourcemaps.write({
includeContent: true
}) : through2.obj())
.pipe(gulp.dest(uniteConfig.dirs.www.dist)));
}
});
// Generated by UniteJS
| unitejs/engine | assets/gulp/dist/tasks/bundler/browserify/build-bundle-app.js | JavaScript | mit | 2,848 |
// Commom Plugins
(function($) {
'use strict';
// Scroll to Top Button.
if (typeof theme.PluginScrollToTop !== 'undefined') {
theme.PluginScrollToTop.initialize();
}
// Tooltips
if ($.isFunction($.fn['tooltip'])) {
$('[data-tooltip]:not(.manual), [data-plugin-tooltip]:not(.manual)').tooltip();
}
// Popover
if ($.isFunction($.fn['popover'])) {
$(function() {
$('[data-plugin-popover]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.popover(opts);
});
});
}
// Validations
if (typeof theme.PluginValidation !== 'undefined') {
theme.PluginValidation.initialize();
}
// Match Height
if ($.isFunction($.fn['matchHeight'])) {
$('.match-height').matchHeight();
// Featured Boxes
$('.featured-boxes .featured-box').matchHeight();
// Featured Box Full
$('.featured-box-full').matchHeight();
}
}).apply(this, [jQuery]);
// Animate
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginAnimate'])) {
$(function() {
$('[data-plugin-animate], [data-appear-animation]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginAnimate(opts);
});
});
}
}).apply(this, [jQuery]);
// Carousel
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginCarousel'])) {
$(function() {
$('[data-plugin-carousel]:not(.manual), .owl-carousel:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginCarousel(opts);
});
});
}
}).apply(this, [jQuery]);
// Chart.Circular
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginChartCircular'])) {
$(function() {
$('[data-plugin-chart-circular]:not(.manual), .circular-bar-chart:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginChartCircular(opts);
});
});
}
}).apply(this, [jQuery]);
// Counter
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginCounter'])) {
$(function() {
$('[data-plugin-counter]:not(.manual), .counters [data-to]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginCounter(opts);
});
});
}
}).apply(this, [jQuery]);
// Lazy Load
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginLazyLoad'])) {
$(function() {
$('[data-plugin-lazyload]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginLazyLoad(opts);
});
});
}
}).apply(this, [jQuery]);
// Lightbox
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginLightbox'])) {
$(function() {
$('[data-plugin-lightbox]:not(.manual), .lightbox:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginLightbox(opts);
});
});
}
}).apply(this, [jQuery]);
// Masonry
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginMasonry'])) {
$(function() {
$('[data-plugin-masonry]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginMasonry(opts);
});
});
}
}).apply(this, [jQuery]);
// Match Height
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginMatchHeight'])) {
$(function() {
$('[data-plugin-match-height]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginMatchHeight(opts);
});
});
}
}).apply(this, [jQuery]);
// Parallax
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginParallax'])) {
$(function() {
$('[data-plugin-parallax]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginParallax(opts);
});
});
}
}).apply(this, [jQuery]);
// Progress Bar
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginProgressBar'])) {
$(function() {
$('[data-plugin-progress-bar]:not(.manual), [data-appear-progress-animation]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginProgressBar(opts);
});
});
}
}).apply(this, [jQuery]);
// Revolution Slider
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginRevolutionSlider'])) {
$(function() {
$('[data-plugin-revolution-slider]:not(.manual), .slider-container .slider:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginRevolutionSlider(opts);
});
});
}
}).apply(this, [jQuery]);
// Sort
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginSort'])) {
$(function() {
$('[data-plugin-sort]:not(.manual), .sort-source:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginSort(opts);
});
});
}
}).apply(this, [jQuery]);
// Sticky
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginSticky'])) {
$(function() {
$('[data-plugin-sticky]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginSticky(opts);
});
});
}
}).apply(this, [jQuery]);
// Toggle
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginToggle'])) {
$(function() {
$('[data-plugin-toggle]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginToggle(opts);
});
});
}
}).apply(this, [jQuery]);
// Tweets
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginTweets'])) {
$(function() {
$('[data-plugin-tweets]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginTweets(opts);
});
});
}
}).apply(this, [jQuery]);
// Video Background
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginVideoBackground'])) {
$(function() {
$('[data-plugin-video-background]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginVideoBackground(opts);
});
});
}
}).apply(this, [jQuery]);
// Word Rotate
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginWordRotate'])) {
$(function() {
$('[data-plugin-word-rotate]:not(.manual), .word-rotate:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginWordRotate(opts);
});
});
}
}).apply(this, [jQuery]);
// Commom Partials
(function($) {
'use strict';
// Sticky Header
if (typeof theme.StickyHeader !== 'undefined') {
theme.StickyHeader.initialize();
}
// Nav Menu
if (typeof theme.Nav !== 'undefined') {
theme.Nav.initialize();
}
// Search
if (typeof theme.Search !== 'undefined') {
theme.Search.initialize();
}
// Newsletter
if (typeof theme.Newsletter !== 'undefined') {
theme.Newsletter.initialize();
}
// Account
if (typeof theme.Account !== 'undefined') {
theme.Account.initialize();
}
}).apply(this, [jQuery]); | SupasitC/Pricetrolley | src/javascripts/theme.init.js | JavaScript | mit | 8,635 |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"strings"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
gmail "google.golang.org/api/gmail/v1"
"github.com/codegangsta/cli"
"github.com/davecgh/go-spew/spew"
)
var me = "me"
func main() {
app := cli.NewApp()
app.Name = "proto"
app.Usage = "test"
app.Version = "0.0.1"
app.Author = "Yusuke Komatsu"
app.Commands = []cli.Command{
{
Name: "cleanUp",
Usage: "---",
Description: "",
Action: cleanUp,
},
{
Name: "deleteAwaitingResponse",
Usage: "---",
Description: "",
Action: deleteAwaitingResponse,
},
{
Name: "getNoLabelSender",
Usage: "---",
Description: "",
Action: getNoLabelSender,
},
{
Name: "labelMessagesWithoutResponse",
Usage: "---",
Description: "",
Action: labelMessagesWithoutResponse,
},
{
Name: "setParentLabel",
Usage: "---",
Description: "",
Action: setParentLabel,
},
}
app.Run(os.Args)
}
func cleanUp(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Threads.List(me).Q("label:3day older_than:3d").Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if (len(req.Threads) > 0) {
for _, th := range req.Threads {
_, err := srv.Users.Threads.Trash(me, th.Id).Do()
if err != nil {
log.Fatalf("Unable to trash thread. ID:%v, %v", th.Id, err)
}
}
}
}
func labelMessagesWithoutResponse(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Threads.List(me).Q("in:Sent -label:AwaitingResponse newer_than:7d").Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if len(req.Threads) > 0 {
label_ar, err := getLabelByName("AwaitingResponse")
if err != nil {
log.Fatalf("Unable to retrieve AwaitingResponse label. %v", err)
}
label_fe, err := getLabelByName("FinishedExchange")
if err != nil {
log.Fatalf("Unable to retrieve FinishedExchange label. %v", err)
}
for _, th := range req.Threads {
mod := &gmail.ModifyThreadRequest{}
lbId := label_ar.Id
if len(th.Messages) > 1 {
lbId = label_fe.Id
}
mod.AddLabelIds = append(mod.AddLabelIds, lbId)
_, err := srv.Users.Threads.Modify(me, th.Id, mod).Do()
if err != nil {
log.Fatalf("Unable to set label. %v", err)
}
}
}
}
func deleteAwaitingResponse(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Threads.List(me).Q("label:AwaitingResponse older_than:7d newer_than:14d").Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if len(req.Threads) > 0 {
removelabel, err := getLabelByName("AwaitingResponse")
if err != nil {
log.Fatalf("Unable to retrieve AwaitingResponse label. %v", err)
}
addlabel, err := getLabelByName("FinishedExchange")
if err != nil {
log.Fatalf("Unable to retrieve FinishedExchange label. %v", err)
}
for _, th := range req.Threads {
mod := &gmail.ModifyThreadRequest{}
mod.RemoveLabelIds = append(mod.RemoveLabelIds, removelabel.Id)
if len(th.Messages) > 1 {
mod.AddLabelIds = append(mod.AddLabelIds, addlabel.Id)
}
_, err := srv.Users.Threads.Modify(me, th.Id, mod).Do()
if err != nil {
log.Fatalf("Unable to remove label. %v", err)
}
}
}
}
func setParentLabel(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Labels.List(me).Do()
if err != nil {
log.Fatalf("Unable to retrieve labels. %v", err)
}
if (len(req.Labels) > 0) {
parents := make(map[string]string)
for _, lb := range req.Labels {
if (strings.Contains(lb.Name, "/") == false) {
parents[lb.Name] = lb.Id
}
}
for _, l := range req.Labels {
lbName := l.Name
if (strings.Contains(lbName, "/")) {
splitedLabelNames := strings.Split(lbName, "/")
parent := splitedLabelNames[0]
query := fmt.Sprintf("label:%s -label:%s", lbName, parent)
r, err := srv.Users.Threads.List(me).Q(query).Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if parentId, ok := parents[parent]; ok {
mod := &gmail.ModifyThreadRequest{}
mod.AddLabelIds = append(mod.AddLabelIds, parentId)
for _, th := range r.Threads {
_, err := srv.Users.Threads.Modify(me, th.Id, mod).Do()
if err != nil {
log.Fatalf("Unable to set label. %v", err)
}
}
}
}
}
}
}
func getNoLabelSender(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Threads.List(me).Q("has:nouserlabels newer_than:1d").Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if len(req.Threads) > 0 {
sender := []string{}
for _, th := range req.Threads {
t, err := srv.Users.Threads.Get(me, th.Id).Fields("messages/payload").Do()
if err != nil {
log.Fatalf("Unable to retrieve a thread information. %v", err)
}
for _, msg := range t.Messages {
headers := msg.Payload.Headers
for _, header := range headers {
if header.Name == "From" {
sender = append(sender, header.Value)
}
}
}
}
spew.Dump(sender)
}
}
func getLabelByName(labelName string) (*gmail.Label, error) {
srv, err := getNewService()
if err != nil {
return nil, err
}
req, err := srv.Users.Labels.List(me).Do()
if err != nil {
return nil, err
}
if (len(req.Labels) > 0) {
for _, l := range req.Labels {
if (l.Name == labelName) {
return l, nil
}
}
}
return nil, nil
}
func getNewService() (*gmail.Service, error) {
b, err := ioutil.ReadFile("client_secret.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
config, err := google.ConfigFromJSON(b, gmail.MailGoogleComScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(context.Background(), config)
srv, err := gmail.New(client)
return srv, err
}
// getClient uses a Context and Config to retrieve a Token
// then generate a Client. It returns the generated Client.
func getClient(ctx context.Context, config *oauth2.Config) *http.Client {
cacheFile, err := tokenCacheFile()
if err != nil {
log.Fatalf("Unable to get path to cached credential file. %v", err)
}
tok, err := tokenFromFile(cacheFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(cacheFile, tok)
}
return config.Client(ctx, tok)
}
// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var code string
if _, err := fmt.Scan(&code); err != nil {
log.Fatalf("Unable to read authorization code %v", err)
}
tok, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatalf("Unable to retrieve token from web %v", err)
}
return tok
}
// tokenCacheFile generates credential file path/filename.
// It returns the generated credential path/filename.
func tokenCacheFile() (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
tokenCacheDir := filepath.Join(usr.HomeDir, ".credentials")
os.MkdirAll(tokenCacheDir, 0700)
return filepath.Join(tokenCacheDir,
url.QueryEscape("token_cache.json")), err
}
// tokenFromFile retrieves a Token from a given file path.
// It returns the retrieved Token and any read error encountered.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
t := &oauth2.Token{}
err = json.NewDecoder(f).Decode(t)
defer f.Close()
return t, err
}
// saveToken uses a file path to create a file and store the
// token in it.
func saveToken(file string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", file)
f, err := os.Create(file)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
} | usk81/shikigami | rei/rei.go | GO | mit | 10,099 |
// This file contains source that originates from:
// http://code.google.com/p/leveldbwin/source/browse/trunk/win32_impl_src/env_win32.h
// http://code.google.com/p/leveldbwin/source/browse/trunk/win32_impl_src/port_win32.cc
// Those files dont' have any explict license headers but the
// project (http://code.google.com/p/leveldbwin/) lists the 'New BSD License'
// as the license.
#if defined(LEVELDB_PLATFORM_WINDOWS)
#include <map>
#undef UNICODE
#include "leveldb/env.h"
#include "port/port.h"
#include "leveldb/slice.h"
#include "util/logging.h"
#include <shlwapi.h>
#include <process.h>
#include <cstring>
#include <stdio.h>
#include <errno.h>
#include <io.h>
#include <algorithm>
#ifdef max
#undef max
#endif
#ifndef va_copy
#define va_copy(d,s) ((d) = (s))
#endif
#if defined DeleteFile
#undef DeleteFile
#endif
//Declarations
namespace leveldb
{
namespace Win32
{
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
std::string GetCurrentDir();
std::wstring GetCurrentDirW();
static const std::string CurrentDir = GetCurrentDir();
static const std::wstring CurrentDirW = GetCurrentDirW();
std::string& ModifyPath(std::string& path);
std::wstring& ModifyPath(std::wstring& path);
std::string GetLastErrSz();
std::wstring GetLastErrSzW();
size_t GetPageSize();
typedef void (*ScheduleProc)(void*) ;
struct WorkItemWrapper
{
WorkItemWrapper(ScheduleProc proc_,void* content_);
ScheduleProc proc;
void* pContent;
};
DWORD WINAPI WorkItemWrapperProc(LPVOID pContent);
class Win32SequentialFile : public SequentialFile
{
public:
friend class Win32Env;
virtual ~Win32SequentialFile();
virtual Status Read(size_t n, Slice* result, char* scratch);
virtual Status Skip(uint64_t n);
BOOL isEnable();
private:
BOOL _Init();
void _CleanUp();
Win32SequentialFile(const std::string& fname);
std::string _filename;
::HANDLE _hFile;
DISALLOW_COPY_AND_ASSIGN(Win32SequentialFile);
};
class Win32RandomAccessFile : public RandomAccessFile
{
public:
friend class Win32Env;
virtual ~Win32RandomAccessFile();
virtual Status Read(uint64_t offset, size_t n, Slice* result,char* scratch) const;
BOOL isEnable();
private:
BOOL _Init(LPCWSTR path);
void _CleanUp();
Win32RandomAccessFile(const std::string& fname);
HANDLE _hFile;
const std::string _filename;
DISALLOW_COPY_AND_ASSIGN(Win32RandomAccessFile);
};
class Win32MapFile : public WritableFile
{
public:
Win32MapFile(const std::string& fname);
~Win32MapFile();
virtual Status Append(const Slice& data);
virtual Status Close();
virtual Status Flush();
virtual Status Sync();
BOOL isEnable();
private:
std::string _filename;
HANDLE _hFile;
size_t _page_size;
size_t _map_size; // How much extra memory to map at a time
char* _base; // The mapped region
HANDLE _base_handle;
char* _limit; // Limit of the mapped region
char* _dst; // Where to write next (in range [base_,limit_])
char* _last_sync; // Where have we synced up to
uint64_t _file_offset; // Offset of base_ in file
//LARGE_INTEGER file_offset_;
// Have we done an munmap of unsynced data?
bool _pending_sync;
// Roundup x to a multiple of y
static size_t _Roundup(size_t x, size_t y);
size_t _TruncateToPageBoundary(size_t s);
bool _UnmapCurrentRegion();
bool _MapNewRegion();
DISALLOW_COPY_AND_ASSIGN(Win32MapFile);
BOOL _Init(LPCWSTR Path);
};
class Win32FileLock : public FileLock
{
public:
friend class Win32Env;
virtual ~Win32FileLock();
BOOL isEnable();
private:
BOOL _Init(LPCWSTR path);
void _CleanUp();
Win32FileLock(const std::string& fname);
HANDLE _hFile;
std::string _filename;
DISALLOW_COPY_AND_ASSIGN(Win32FileLock);
};
class Win32Logger : public Logger
{
public:
friend class Win32Env;
virtual ~Win32Logger();
virtual void Logv(const char* format, va_list ap);
private:
explicit Win32Logger(WritableFile* pFile);
WritableFile* _pFileProxy;
DISALLOW_COPY_AND_ASSIGN(Win32Logger);
};
class Win32Env : public Env
{
public:
Win32Env();
virtual ~Win32Env();
virtual Status NewSequentialFile(const std::string& fname,
SequentialFile** result);
virtual Status NewRandomAccessFile(const std::string& fname,
RandomAccessFile** result);
virtual Status NewWritableFile(const std::string& fname,
WritableFile** result);
virtual bool FileExists(const std::string& fname);
virtual Status GetChildren(const std::string& dir,
std::vector<std::string>* result);
virtual Status DeleteFile(const std::string& fname);
virtual Status CreateDir(const std::string& dirname);
virtual Status DeleteDir(const std::string& dirname);
virtual Status GetFileSize(const std::string& fname, uint64_t* file_size);
virtual Status RenameFile(const std::string& src,
const std::string& target);
virtual Status LockFile(const std::string& fname, FileLock** lock);
virtual Status UnlockFile(FileLock* lock);
virtual void Schedule(
void (*function)(void* arg),
void* arg);
virtual void StartThread(void (*function)(void* arg), void* arg);
virtual Status GetTestDirectory(std::string* path);
//virtual void Logv(WritableFile* log, const char* format, va_list ap);
virtual Status NewLogger(const std::string& fname, Logger** result);
virtual uint64_t NowMicros();
virtual void SleepForMicroseconds(int micros);
};
void ToWidePath(const std::string& value, std::wstring& target) {
wchar_t buffer[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, value.c_str(), -1, buffer, MAX_PATH);
target = buffer;
}
void ToNarrowPath(const std::wstring& value, std::string& target) {
char buffer[MAX_PATH];
WideCharToMultiByte(CP_ACP, 0, value.c_str(), -1, buffer, MAX_PATH, NULL, NULL);
target = buffer;
}
std::string GetCurrentDir()
{
CHAR path[MAX_PATH];
::GetModuleFileNameA(::GetModuleHandleA(NULL),path,MAX_PATH);
*strrchr(path,'\\') = 0;
return std::string(path);
}
std::wstring GetCurrentDirW()
{
WCHAR path[MAX_PATH];
::GetModuleFileNameW(::GetModuleHandleW(NULL),path,MAX_PATH);
*wcsrchr(path,L'\\') = 0;
return std::wstring(path);
}
std::string& ModifyPath(std::string& path)
{
if(path[0] == '/' || path[0] == '\\'){
path = CurrentDir + path;
}
std::replace(path.begin(),path.end(),'/','\\');
return path;
}
std::wstring& ModifyPath(std::wstring& path)
{
if(path[0] == L'/' || path[0] == L'\\'){
path = CurrentDirW + path;
}
std::replace(path.begin(),path.end(),L'/',L'\\');
return path;
}
std::string GetLastErrSz()
{
LPWSTR lpMsgBuf;
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
0, // Default language
(LPWSTR) &lpMsgBuf,
0,
NULL
);
std::string Err;
ToNarrowPath(lpMsgBuf, Err);
LocalFree( lpMsgBuf );
return Err;
}
std::wstring GetLastErrSzW()
{
LPVOID lpMsgBuf;
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
0, // Default language
(LPWSTR) &lpMsgBuf,
0,
NULL
);
std::wstring Err = (LPCWSTR)lpMsgBuf;
LocalFree(lpMsgBuf);
return Err;
}
WorkItemWrapper::WorkItemWrapper( ScheduleProc proc_,void* content_ ) :
proc(proc_),pContent(content_)
{
}
DWORD WINAPI WorkItemWrapperProc(LPVOID pContent)
{
WorkItemWrapper* item = static_cast<WorkItemWrapper*>(pContent);
ScheduleProc TempProc = item->proc;
void* arg = item->pContent;
delete item;
TempProc(arg);
return 0;
}
size_t GetPageSize()
{
SYSTEM_INFO si;
GetSystemInfo(&si);
return std::max(si.dwPageSize,si.dwAllocationGranularity);
}
const size_t g_PageSize = GetPageSize();
Win32SequentialFile::Win32SequentialFile( const std::string& fname ) :
_filename(fname),_hFile(NULL)
{
_Init();
}
Win32SequentialFile::~Win32SequentialFile()
{
_CleanUp();
}
Status Win32SequentialFile::Read( size_t n, Slice* result, char* scratch )
{
Status sRet;
DWORD hasRead = 0;
if(_hFile && ReadFile(_hFile,scratch,n,&hasRead,NULL) ){
*result = Slice(scratch,hasRead);
} else {
sRet = Status::IOError(_filename, Win32::GetLastErrSz() );
}
return sRet;
}
Status Win32SequentialFile::Skip( uint64_t n )
{
Status sRet;
LARGE_INTEGER Move,NowPointer;
Move.QuadPart = n;
if(!SetFilePointerEx(_hFile,Move,&NowPointer,FILE_CURRENT)){
sRet = Status::IOError(_filename,Win32::GetLastErrSz());
}
return sRet;
}
BOOL Win32SequentialFile::isEnable()
{
return _hFile ? TRUE : FALSE;
}
BOOL Win32SequentialFile::_Init()
{
std::wstring path;
ToWidePath(_filename, path);
_hFile = CreateFileW(path.c_str(),
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
return _hFile ? TRUE : FALSE;
}
void Win32SequentialFile::_CleanUp()
{
if(_hFile){
CloseHandle(_hFile);
_hFile = NULL;
}
}
Win32RandomAccessFile::Win32RandomAccessFile( const std::string& fname ) :
_filename(fname),_hFile(NULL)
{
std::wstring path;
ToWidePath(fname, path);
_Init( path.c_str() );
}
Win32RandomAccessFile::~Win32RandomAccessFile()
{
_CleanUp();
}
Status Win32RandomAccessFile::Read(uint64_t offset,size_t n,Slice* result,char* scratch) const
{
Status sRet;
OVERLAPPED ol = {0};
ZeroMemory(&ol,sizeof(ol));
ol.Offset = (DWORD)offset;
ol.OffsetHigh = (DWORD)(offset >> 32);
DWORD hasRead = 0;
if(!ReadFile(_hFile,scratch,n,&hasRead,&ol))
sRet = Status::IOError(_filename,Win32::GetLastErrSz());
else
*result = Slice(scratch,hasRead);
return sRet;
}
BOOL Win32RandomAccessFile::_Init( LPCWSTR path )
{
BOOL bRet = FALSE;
if(!_hFile)
_hFile = ::CreateFileW(path,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,NULL);
if(!_hFile || _hFile == INVALID_HANDLE_VALUE )
_hFile = NULL;
else
bRet = TRUE;
return bRet;
}
BOOL Win32RandomAccessFile::isEnable()
{
return _hFile ? TRUE : FALSE;
}
void Win32RandomAccessFile::_CleanUp()
{
if(_hFile){
::CloseHandle(_hFile);
_hFile = NULL;
}
}
size_t Win32MapFile::_Roundup( size_t x, size_t y )
{
return ((x + y - 1) / y) * y;
}
size_t Win32MapFile::_TruncateToPageBoundary( size_t s )
{
s -= (s & (_page_size - 1));
assert((s % _page_size) == 0);
return s;
}
bool Win32MapFile::_UnmapCurrentRegion()
{
bool result = true;
if (_base != NULL) {
if (_last_sync < _limit) {
// Defer syncing this data until next Sync() call, if any
_pending_sync = true;
}
if (!UnmapViewOfFile(_base) || !CloseHandle(_base_handle))
result = false;
_file_offset += _limit - _base;
_base = NULL;
_base_handle = NULL;
_limit = NULL;
_last_sync = NULL;
_dst = NULL;
// Increase the amount we map the next time, but capped at 1MB
if (_map_size < (1<<20)) {
_map_size *= 2;
}
}
return result;
}
bool Win32MapFile::_MapNewRegion()
{
assert(_base == NULL);
//LONG newSizeHigh = (LONG)((file_offset_ + map_size_) >> 32);
//LONG newSizeLow = (LONG)((file_offset_ + map_size_) & 0xFFFFFFFF);
DWORD off_hi = (DWORD)(_file_offset >> 32);
DWORD off_lo = (DWORD)(_file_offset & 0xFFFFFFFF);
LARGE_INTEGER newSize;
newSize.QuadPart = _file_offset + _map_size;
SetFilePointerEx(_hFile, newSize, NULL, FILE_BEGIN);
SetEndOfFile(_hFile);
_base_handle = CreateFileMappingA(
_hFile,
NULL,
PAGE_READWRITE,
0,
0,
0);
if (_base_handle != NULL) {
_base = (char*) MapViewOfFile(_base_handle,
FILE_MAP_ALL_ACCESS,
off_hi,
off_lo,
_map_size);
if (_base != NULL) {
_limit = _base + _map_size;
_dst = _base;
_last_sync = _base;
return true;
}
}
return false;
}
Win32MapFile::Win32MapFile( const std::string& fname) :
_filename(fname),
_hFile(NULL),
_page_size(Win32::g_PageSize),
_map_size(_Roundup(65536, Win32::g_PageSize)),
_base(NULL),
_base_handle(NULL),
_limit(NULL),
_dst(NULL),
_last_sync(NULL),
_file_offset(0),
_pending_sync(false)
{
std::wstring path;
ToWidePath(fname, path);
_Init(path.c_str());
assert((Win32::g_PageSize & (Win32::g_PageSize - 1)) == 0);
}
Status Win32MapFile::Append( const Slice& data )
{
const char* src = data.data();
size_t left = data.size();
Status s;
while (left > 0) {
assert(_base <= _dst);
assert(_dst <= _limit);
size_t avail = _limit - _dst;
if (avail == 0) {
if (!_UnmapCurrentRegion() ||
!_MapNewRegion()) {
return Status::IOError("WinMmapFile.Append::UnmapCurrentRegion or MapNewRegion: ", Win32::GetLastErrSz());
}
}
size_t n = (left <= avail) ? left : avail;
memcpy(_dst, src, n);
_dst += n;
src += n;
left -= n;
}
return s;
}
Status Win32MapFile::Close()
{
Status s;
size_t unused = _limit - _dst;
if (!_UnmapCurrentRegion()) {
s = Status::IOError("WinMmapFile.Close::UnmapCurrentRegion: ",Win32::GetLastErrSz());
} else if (unused > 0) {
// Trim the extra space at the end of the file
LARGE_INTEGER newSize;
newSize.QuadPart = _file_offset - unused;
if (!SetFilePointerEx(_hFile, newSize, NULL, FILE_BEGIN)) {
s = Status::IOError("WinMmapFile.Close::SetFilePointer: ",Win32::GetLastErrSz());
} else
SetEndOfFile(_hFile);
}
if (!CloseHandle(_hFile)) {
if (s.ok()) {
s = Status::IOError("WinMmapFile.Close::CloseHandle: ", Win32::GetLastErrSz());
}
}
_hFile = INVALID_HANDLE_VALUE;
_base = NULL;
_base_handle = NULL;
_limit = NULL;
return s;
}
Status Win32MapFile::Sync()
{
Status s;
if (_pending_sync) {
// Some unmapped data was not synced
_pending_sync = false;
if (!FlushFileBuffers(_hFile)) {
s = Status::IOError("WinMmapFile.Sync::FlushFileBuffers: ",Win32::GetLastErrSz());
}
}
if (_dst > _last_sync) {
// Find the beginnings of the pages that contain the first and last
// bytes to be synced.
size_t p1 = _TruncateToPageBoundary(_last_sync - _base);
size_t p2 = _TruncateToPageBoundary(_dst - _base - 1);
_last_sync = _dst;
if (!FlushViewOfFile(_base + p1, p2 - p1 + _page_size)) {
s = Status::IOError("WinMmapFile.Sync::FlushViewOfFile: ",Win32::GetLastErrSz());
}
}
return s;
}
Status Win32MapFile::Flush()
{
return Status::OK();
}
Win32MapFile::~Win32MapFile()
{
if (_hFile != INVALID_HANDLE_VALUE) {
Win32MapFile::Close();
}
}
BOOL Win32MapFile::_Init( LPCWSTR Path )
{
DWORD Flag = PathFileExistsW(Path) ? OPEN_EXISTING : CREATE_ALWAYS;
_hFile = CreateFileW(Path,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
NULL,
Flag,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(!_hFile || _hFile == INVALID_HANDLE_VALUE)
return FALSE;
else
return TRUE;
}
BOOL Win32MapFile::isEnable()
{
return _hFile ? TRUE : FALSE;
}
Win32FileLock::Win32FileLock( const std::string& fname ) :
_hFile(NULL),_filename(fname)
{
std::wstring path;
ToWidePath(fname, path);
_Init(path.c_str());
}
Win32FileLock::~Win32FileLock()
{
_CleanUp();
}
BOOL Win32FileLock::_Init( LPCWSTR path )
{
BOOL bRet = FALSE;
if(!_hFile)
_hFile = ::CreateFileW(path,0,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if(!_hFile || _hFile == INVALID_HANDLE_VALUE ){
_hFile = NULL;
}
else
bRet = TRUE;
return bRet;
}
void Win32FileLock::_CleanUp()
{
::CloseHandle(_hFile);
_hFile = NULL;
}
BOOL Win32FileLock::isEnable()
{
return _hFile ? TRUE : FALSE;
}
Win32Logger::Win32Logger(WritableFile* pFile) : _pFileProxy(pFile)
{
assert(_pFileProxy);
}
Win32Logger::~Win32Logger()
{
if(_pFileProxy)
delete _pFileProxy;
}
void Win32Logger::Logv( const char* format, va_list ap )
{
uint64_t thread_id = ::GetCurrentThreadId();
// We try twice: the first time with a fixed-size stack allocated buffer,
// and the second time with a much larger dynamically allocated buffer.
char buffer[500];
for (int iter = 0; iter < 2; iter++) {
char* base;
int bufsize;
if (iter == 0) {
bufsize = sizeof(buffer);
base = buffer;
} else {
bufsize = 30000;
base = new char[bufsize];
}
char* p = base;
char* limit = base + bufsize;
SYSTEMTIME st;
GetLocalTime(&st);
p += snprintf(p, limit - p,
"%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx ",
int(st.wYear),
int(st.wMonth),
int(st.wDay),
int(st.wHour),
int(st.wMinute),
int(st.wMinute),
int(st.wMilliseconds),
static_cast<long long unsigned int>(thread_id));
// Print the message
if (p < limit) {
va_list backup_ap;
va_copy(backup_ap, ap);
p += vsnprintf(p, limit - p, format, backup_ap);
va_end(backup_ap);
}
// Truncate to available space if necessary
if (p >= limit) {
if (iter == 0) {
continue; // Try again with larger buffer
} else {
p = limit - 1;
}
}
// Add newline if necessary
if (p == base || p[-1] != '\n') {
*p++ = '\n';
}
assert(p <= limit);
DWORD hasWritten = 0;
if(_pFileProxy){
_pFileProxy->Append(Slice(base, p - base));
_pFileProxy->Flush();
}
if (base != buffer) {
delete[] base;
}
break;
}
}
bool Win32Env::FileExists(const std::string& fname)
{
std::string path = fname;
std::wstring wpath;
ToWidePath(ModifyPath(path), wpath);
return ::PathFileExistsW(wpath.c_str()) ? true : false;
}
Status Win32Env::GetChildren(const std::string& dir, std::vector<std::string>* result)
{
Status sRet;
::WIN32_FIND_DATAW wfd;
std::string path = dir;
ModifyPath(path);
path += "\\*.*";
std::wstring wpath;
ToWidePath(path, wpath);
::HANDLE hFind = ::FindFirstFileW(wpath.c_str() ,&wfd);
if(hFind && hFind != INVALID_HANDLE_VALUE){
BOOL hasNext = TRUE;
std::string child;
while(hasNext){
ToNarrowPath(wfd.cFileName, child);
if(child != ".." && child != ".") {
result->push_back(child);
}
hasNext = ::FindNextFileW(hFind,&wfd);
}
::FindClose(hFind);
}
else
sRet = Status::IOError(dir,"Could not get children.");
return sRet;
}
void Win32Env::SleepForMicroseconds( int micros )
{
::Sleep((micros + 999) /1000);
}
Status Win32Env::DeleteFile( const std::string& fname )
{
Status sRet;
std::string path = fname;
std::wstring wpath;
ToWidePath(ModifyPath(path), wpath);
if(!::DeleteFileW(wpath.c_str())) {
sRet = Status::IOError(path, "Could not delete file.");
}
return sRet;
}
Status Win32Env::GetFileSize( const std::string& fname, uint64_t* file_size )
{
Status sRet;
std::string path = fname;
std::wstring wpath;
ToWidePath(ModifyPath(path), wpath);
HANDLE file = ::CreateFileW(wpath.c_str(),
GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
LARGE_INTEGER li;
if(::GetFileSizeEx(file,&li)){
*file_size = (uint64_t)li.QuadPart;
}else
sRet = Status::IOError(path,"Could not get the file size.");
CloseHandle(file);
return sRet;
}
Status Win32Env::RenameFile( const std::string& src, const std::string& target )
{
Status sRet;
std::string src_path = src;
std::wstring wsrc_path;
ToWidePath(ModifyPath(src_path), wsrc_path);
std::string target_path = target;
std::wstring wtarget_path;
ToWidePath(ModifyPath(target_path), wtarget_path);
if(!MoveFileW(wsrc_path.c_str(), wtarget_path.c_str() ) ){
DWORD err = GetLastError();
if(err == 0x000000b7){
if(!::DeleteFileW(wtarget_path.c_str() ) )
sRet = Status::IOError(src, "Could not rename file.");
else if(!::MoveFileW(wsrc_path.c_str(),
wtarget_path.c_str() ) )
sRet = Status::IOError(src, "Could not rename file.");
}
}
return sRet;
}
Status Win32Env::LockFile( const std::string& fname, FileLock** lock )
{
Status sRet;
std::string path = fname;
ModifyPath(path);
Win32FileLock* _lock = new Win32FileLock(path);
if(!_lock->isEnable()){
delete _lock;
*lock = NULL;
sRet = Status::IOError(path, "Could not lock file.");
}
else
*lock = _lock;
return sRet;
}
Status Win32Env::UnlockFile( FileLock* lock )
{
Status sRet;
delete lock;
return sRet;
}
void Win32Env::Schedule( void (*function)(void* arg), void* arg )
{
QueueUserWorkItem(Win32::WorkItemWrapperProc,
new Win32::WorkItemWrapper(function,arg),
WT_EXECUTEDEFAULT);
}
void Win32Env::StartThread( void (*function)(void* arg), void* arg )
{
::_beginthread(function,0,arg);
}
Status Win32Env::GetTestDirectory( std::string* path )
{
Status sRet;
WCHAR TempPath[MAX_PATH];
::GetTempPathW(MAX_PATH,TempPath);
ToNarrowPath(TempPath, *path);
path->append("leveldb\\test\\");
ModifyPath(*path);
return sRet;
}
uint64_t Win32Env::NowMicros()
{
#ifndef USE_VISTA_API
#define GetTickCount64 GetTickCount
#endif
return (uint64_t)(GetTickCount64()*1000);
}
static Status CreateDirInner( const std::string& dirname )
{
Status sRet;
DWORD attr = ::GetFileAttributes(dirname.c_str());
if (attr == INVALID_FILE_ATTRIBUTES) { // doesn't exist:
std::size_t slash = dirname.find_last_of("\\");
if (slash != std::string::npos){
sRet = CreateDirInner(dirname.substr(0, slash));
if (!sRet.ok()) return sRet;
}
BOOL result = ::CreateDirectory(dirname.c_str(), NULL);
if (result == FALSE) {
sRet = Status::IOError(dirname, "Could not create directory.");
return sRet;
}
}
return sRet;
}
Status Win32Env::CreateDir( const std::string& dirname )
{
std::string path = dirname;
if(path[path.length() - 1] != '\\'){
path += '\\';
}
ModifyPath(path);
return CreateDirInner(path);
}
Status Win32Env::DeleteDir( const std::string& dirname )
{
Status sRet;
std::wstring path;
ToWidePath(dirname, path);
ModifyPath(path);
if(!::RemoveDirectoryW( path.c_str() ) ){
sRet = Status::IOError(dirname, "Could not delete directory.");
}
return sRet;
}
Status Win32Env::NewSequentialFile( const std::string& fname, SequentialFile** result )
{
Status sRet;
std::string path = fname;
ModifyPath(path);
Win32SequentialFile* pFile = new Win32SequentialFile(path);
if(pFile->isEnable()){
*result = pFile;
}else {
delete pFile;
sRet = Status::IOError(path, Win32::GetLastErrSz());
}
return sRet;
}
Status Win32Env::NewRandomAccessFile( const std::string& fname, RandomAccessFile** result )
{
Status sRet;
std::string path = fname;
Win32RandomAccessFile* pFile = new Win32RandomAccessFile(ModifyPath(path));
if(!pFile->isEnable()){
delete pFile;
*result = NULL;
sRet = Status::IOError(path, Win32::GetLastErrSz());
}else
*result = pFile;
return sRet;
}
Status Win32Env::NewLogger( const std::string& fname, Logger** result )
{
Status sRet;
std::string path = fname;
Win32MapFile* pMapFile = new Win32MapFile(ModifyPath(path));
if(!pMapFile->isEnable()){
delete pMapFile;
*result = NULL;
sRet = Status::IOError(path,"could not create a logger.");
}else
*result = new Win32Logger(pMapFile);
return sRet;
}
Status Win32Env::NewWritableFile( const std::string& fname, WritableFile** result )
{
Status sRet;
std::string path = fname;
Win32MapFile* pFile = new Win32MapFile(ModifyPath(path));
if(!pFile->isEnable()){
*result = NULL;
sRet = Status::IOError(fname,Win32::GetLastErrSz());
}else
*result = pFile;
return sRet;
}
Win32Env::Win32Env()
{
}
Win32Env::~Win32Env()
{
}
} // Win32 namespace
static port::OnceType once = LEVELDB_ONCE_INIT;
static Env* default_env;
static void InitDefaultEnv() { default_env = new Win32::Win32Env(); }
Env* Env::Default() {
port::InitOnce(&once, InitDefaultEnv);
return default_env;
}
} // namespace leveldb
#endif // defined(LEVELDB_PLATFORM_WINDOWS)
| jesuscoinproject/jesuscoin | src/leveldb/util/env_win.cc | C++ | mit | 25,974 |
'use strict';
const BitcrusherProps = {
bits: {
type: 'number',
bounds: [1, 16],
defaultValue: 4
},
normfreq: {
type: 'number',
bounds: [0, 1],
step: 0.1,
defaultValue: 0.1
},
bufferSize: {
type: 'number',
bounds: [256, 16384],
defaultValue: 4096
},
bypass: {
type: 'number',
bounds: [0, 1],
defaultValue: 0
}
};
export default BitcrusherProps;
| civa86/web-synth | lib/src/properties/BitcrusherProps.js | JavaScript | mit | 483 |
/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) **
** **
** 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 "HorizontalListWidget.hpp"
namespace Sn {
HorizontalListWidget::HorizontalListWidget(QWidget* parent) :
QListWidget(parent),
m_mouseDown(false)
{
setFocusPolicy(Qt::NoFocus);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setMovement(QListView::Static);
setResizeMode(QListView::Adjust);
setViewMode(QListView::IconMode);
setSelectionRectVisible(false);
}
void HorizontalListWidget::mousePressEvent(QMouseEvent* event)
{
m_mouseDown = true;
QListWidget::mousePressEvent(event);
}
void HorizontalListWidget::mouseMoveEvent(QMouseEvent* event)
{
if (!itemAt(event->pos()))
return;
QListWidget::mouseMoveEvent(event);
}
void HorizontalListWidget::mouseReleaseEvent(QMouseEvent* event)
{
m_mouseDown = false;
QListWidget::mouseReleaseEvent(event);
}
void HorizontalListWidget::wheelEvent(QWheelEvent* event)
{
Q_UNUSED(event);
}
} | Feldrise/Sielo-NavigateurV3-WebEngine | Core/Widgets/HorizontalListWidget.cpp | C++ | mit | 2,823 |
import os
import sys
from Bio import SeqIO
f = open(sys.argv[1], 'rU')
out = open(sys.argv[2], 'w')
for records in SeqIO.parse(f, 'fastq'):
SeqIO.write(records, out, 'fasta')
| chnops/code | fastq_to_fasta.py | Python | mit | 177 |
require 'strscan'
##
# Parses a gem.deps.rb.lock file and constructs a LockSet containing the
# dependencies found inside. If the lock file is missing no LockSet is
# constructed.
class Gem::RequestSet::Lockfile
##
# Raised when a lockfile cannot be parsed
class ParseError < Gem::Exception
##
# The column where the error was encountered
attr_reader :column
##
# The line where the error was encountered
attr_reader :line
##
# The location of the lock file
attr_reader :path
##
# Raises a ParseError with the given +message+ which was encountered at a
# +line+ and +column+ while parsing.
def initialize message, column, line, path
@line = line
@column = column
@path = path
super "#{message} (at line #{line} column #{column})"
end
end
##
# The platforms for this Lockfile
attr_reader :platforms
##
# Creates a new Lockfile for the given +request_set+ and +gem_deps_file+
# location.
def initialize request_set, gem_deps_file
@set = request_set
@gem_deps_file = File.expand_path(gem_deps_file)
@gem_deps_dir = File.dirname(@gem_deps_file)
@current_token = nil
@line = 0
@line_pos = 0
@platforms = []
@tokens = []
end
def add_DEPENDENCIES out # :nodoc:
out << "DEPENDENCIES"
@requests.sort_by { |r| r.name }.each do |request|
spec = request.spec
if [Gem::Resolver::VendorSpecification,
Gem::Resolver::GitSpecification].include? spec.class then
out << " #{request.name}!"
else
requirement = request.request.dependency.requirement
out << " #{request.name}#{requirement.for_lockfile}"
end
end
out << nil
end
def add_GEM out # :nodoc:
return if @spec_groups.empty?
source_groups = @spec_groups.values.flatten.group_by do |request|
request.spec.source.uri
end
source_groups.sort_by { |group,| group.to_s }.map do |group, requests|
out << "GEM"
out << " remote: #{group}"
out << " specs:"
requests.sort_by { |request| request.name }.each do |request|
platform = "-#{request.spec.platform}" unless
Gem::Platform::RUBY == request.spec.platform
out << " #{request.name} (#{request.version}#{platform})"
request.full_spec.dependencies.sort.each do |dependency|
requirement = dependency.requirement
out << " #{dependency.name}#{requirement.for_lockfile}"
end
end
out << nil
end
end
def add_GIT out
return unless git_requests =
@spec_groups.delete(Gem::Resolver::GitSpecification)
by_repository_revision = git_requests.group_by do |request|
source = request.spec.source
[source.repository, source.rev_parse]
end
out << "GIT"
by_repository_revision.each do |(repository, revision), requests|
out << " remote: #{repository}"
out << " revision: #{revision}"
out << " specs:"
requests.sort_by { |request| request.name }.each do |request|
out << " #{request.name} (#{request.version})"
dependencies = request.spec.dependencies.sort_by { |dep| dep.name }
dependencies.each do |dep|
out << " #{dep.name}#{dep.requirement.for_lockfile}"
end
end
end
out << nil
end
def relative_path_from dest, base # :nodoc:
dest = File.expand_path(dest)
base = File.expand_path(base)
if dest.index(base) == 0
return dest[base.size+1..-1]
else
dest
end
end
def add_PATH out # :nodoc:
return unless path_requests =
@spec_groups.delete(Gem::Resolver::VendorSpecification)
out << "PATH"
path_requests.each do |request|
directory = File.expand_path(request.spec.source.uri)
out << " remote: #{relative_path_from directory, @gem_deps_dir}"
out << " specs:"
out << " #{request.name} (#{request.version})"
end
out << nil
end
def add_PLATFORMS out # :nodoc:
out << "PLATFORMS"
platforms = @requests.map { |request| request.spec.platform }.uniq
platforms.delete Gem::Platform::RUBY if platforms.length > 1
platforms.each do |platform|
out << " #{platform}"
end
out << nil
end
##
# Gets the next token for a Lockfile
def get expected_types = nil, expected_value = nil # :nodoc:
@current_token = @tokens.shift
type, value, column, line = @current_token
if expected_types and not Array(expected_types).include? type then
unget
message = "unexpected token [#{type.inspect}, #{value.inspect}], " +
"expected #{expected_types.inspect}"
raise ParseError.new message, column, line, "#{@gem_deps_file}.lock"
end
if expected_value and expected_value != value then
unget
message = "unexpected token [#{type.inspect}, #{value.inspect}], " +
"expected [#{expected_types.inspect}, " +
"#{expected_value.inspect}]"
raise ParseError.new message, column, line, "#{@gem_deps_file}.lock"
end
@current_token
end
def parse # :nodoc:
tokenize
until @tokens.empty? do
type, data, column, line = get
case type
when :section then
skip :newline
case data
when 'DEPENDENCIES' then
parse_DEPENDENCIES
when 'GIT' then
parse_GIT
when 'GEM' then
parse_GEM
when 'PATH' then
parse_PATH
when 'PLATFORMS' then
parse_PLATFORMS
else
type, = get until @tokens.empty? or peek.first == :section
end
else
raise "BUG: unhandled token #{type} (#{data.inspect}) at line #{line} column #{column}"
end
end
end
def parse_DEPENDENCIES # :nodoc:
while not @tokens.empty? and :text == peek.first do
_, name, = get :text
requirements = []
case peek[0]
when :bang then
get :bang
spec = @set.sets.select { |set|
Gem::Resolver::GitSet === set or
Gem::Resolver::VendorSet === set
}.map { |set|
set.specs[name]
}.first
requirements << spec.version
when :l_paren then
get :l_paren
loop do
_, op, = get :requirement
_, version, = get :text
requirements << "#{op} #{version}"
break unless peek[0] == :comma
get :comma
end
get :r_paren
end
@set.gem name, *requirements
skip :newline
end
end
def parse_GEM # :nodoc:
get :entry, 'remote'
_, data, = get :text
source = Gem::Source.new data
skip :newline
get :entry, 'specs'
skip :newline
set = Gem::Resolver::LockSet.new source
last_spec = nil
while not @tokens.empty? and :text == peek.first do
_, name, column, = get :text
case peek[0]
when :newline then
last_spec.add_dependency Gem::Dependency.new name if column == 6
when :l_paren then
get :l_paren
type, data, = get [:text, :requirement]
if type == :text and column == 4 then
last_spec = set.add name, data, Gem::Platform::RUBY
else
dependency = parse_dependency name, data
last_spec.add_dependency dependency
end
get :r_paren
else
raise "BUG: unknown token #{peek}"
end
skip :newline
end
@set.sets << set
end
def parse_GIT # :nodoc:
get :entry, 'remote'
_, repository, = get :text
skip :newline
get :entry, 'revision'
_, revision, = get :text
skip :newline
get :entry, 'specs'
skip :newline
set = Gem::Resolver::GitSet.new
last_spec = nil
while not @tokens.empty? and :text == peek.first do
_, name, column, = get :text
case peek[0]
when :newline then
last_spec.add_dependency Gem::Dependency.new name if column == 6
when :l_paren then
get :l_paren
type, data, = get [:text, :requirement]
if type == :text and column == 4 then
last_spec = set.add_git_spec name, data, repository, revision, true
else
dependency = parse_dependency name, data
last_spec.spec.dependencies << dependency
end
get :r_paren
else
raise "BUG: unknown token #{peek}"
end
skip :newline
end
@set.sets << set
end
def parse_PATH # :nodoc:
get :entry, 'remote'
_, directory, = get :text
skip :newline
get :entry, 'specs'
skip :newline
set = Gem::Resolver::VendorSet.new
last_spec = nil
while not @tokens.empty? and :text == peek.first do
_, name, column, = get :text
case peek[0]
when :newline then
last_spec.add_dependency Gem::Dependency.new name if column == 6
when :l_paren then
get :l_paren
type, data, = get [:text, :requirement]
if type == :text and column == 4 then
last_spec = set.add_vendor_gem name, directory
else
dependency = parse_dependency name, data
last_spec.spec.dependencies << dependency
end
get :r_paren
else
raise "BUG: unknown token #{peek}"
end
skip :newline
end
@set.sets << set
end
def parse_PLATFORMS # :nodoc:
while not @tokens.empty? and :text == peek.first do
_, name, = get :text
@platforms << name
skip :newline
end
end
##
# Parses the requirements following the dependency +name+ and the +op+ for
# the first token of the requirements and returns a Gem::Dependency object.
def parse_dependency name, op # :nodoc:
return Gem::Dependency.new name unless peek[0] == :text
_, version, = get :text
requirements = ["#{op} #{version}"]
while peek[0] == :comma do
get :comma
_, op, = get :requirement
_, version, = get :text
requirements << "#{op} #{version}"
end
Gem::Dependency.new name, requirements
end
##
# Peeks at the next token for Lockfile
def peek # :nodoc:
@tokens.first || [:EOF]
end
def skip type # :nodoc:
get while not @tokens.empty? and peek.first == type
end
##
# The contents of the lock file.
def to_s
@set.resolve
out = []
@requests = @set.sorted_requests
@spec_groups = @requests.group_by do |request|
request.spec.class
end
add_PATH out
add_GIT out
add_GEM out
add_PLATFORMS out
add_DEPENDENCIES out
out.join "\n"
end
##
# Calculates the column (by byte) and the line of the current token based on
# +byte_offset+.
def token_pos byte_offset # :nodoc:
[byte_offset - @line_pos, @line]
end
##
# Converts a lock file into an Array of tokens. If the lock file is missing
# an empty Array is returned.
def tokenize # :nodoc:
@line = 0
@line_pos = 0
@platforms = []
@tokens = []
@current_token = nil
lock_file = "#{@gem_deps_file}.lock"
@input = File.read lock_file
s = StringScanner.new @input
until s.eos? do
pos = s.pos
pos = s.pos if leading_whitespace = s.scan(/ +/)
if s.scan(/[<|=>]{7}/) then
message = "your #{lock_file} contains merge conflict markers"
column, line = token_pos pos
raise ParseError.new message, column, line, lock_file
end
@tokens <<
case
when s.scan(/\r?\n/) then
token = [:newline, nil, *token_pos(pos)]
@line_pos = s.pos
@line += 1
token
when s.scan(/[A-Z]+/) then
if leading_whitespace then
text = s.matched
text += s.scan(/[^\s)]*/).to_s # in case of no match
[:text, text, *token_pos(pos)]
else
[:section, s.matched, *token_pos(pos)]
end
when s.scan(/([a-z]+):\s/) then
s.pos -= 1 # rewind for possible newline
[:entry, s[1], *token_pos(pos)]
when s.scan(/\(/) then
[:l_paren, nil, *token_pos(pos)]
when s.scan(/\)/) then
[:r_paren, nil, *token_pos(pos)]
when s.scan(/<=|>=|=|~>|<|>|!=/) then
[:requirement, s.matched, *token_pos(pos)]
when s.scan(/,/) then
[:comma, nil, *token_pos(pos)]
when s.scan(/!/) then
[:bang, nil, *token_pos(pos)]
when s.scan(/[^\s),!]*/) then
[:text, s.matched, *token_pos(pos)]
else
raise "BUG: can't create token for: #{s.string[s.pos..-1].inspect}"
end
end
@tokens
rescue Errno::ENOENT
@tokens
end
##
# Ungets the last token retrieved by #get
def unget # :nodoc:
@tokens.unshift @current_token
end
##
# Writes the lock file alongside the gem dependencies file
def write
open "#{@gem_deps_file}.lock", 'w' do |io|
io.write to_s
end
end
end
| justsml/docker-build-server | ruby-2.1.0/lib/ruby/site_ruby/2.1.0/rubygems/request_set/lockfile.rb | Ruby | mit | 13,070 |
define({
"_widgetLabel": "Tra cứu Địa lý",
"description": "Duyệt đến hoặc Kéo <a href='./widgets/GeoLookup/data/sample.csv' tooltip='Download an example sheet' target='_blank'> trang tính </a> tại đây để mô phỏng và thêm các dữ liệu bản đồ vào trang tính đó.",
"selectCSV": "Chọn một CSV",
"loadingCSV": "Đang tải CSV",
"savingCSV": "Xuất CSV",
"clearResults": "Xóa",
"downloadResults": "Tải xuống",
"plotOnly": "Chỉ các Điểm Vẽ bản đồ",
"plottingRows": "Hàng vẽ bản đồ",
"projectionChoice": "CSV trong",
"projectionLat": "Vĩ độ/Kinh độ",
"projectionMap": "Phép chiếu Bản đồ",
"messages": "Thông báo",
"error": {
"fetchingCSV": "Đã xảy ra lỗi khi truy xuất các mục từ kho lưu trữ CSV: ${0}",
"fileIssue": "Không xử lý được tệp.",
"notCSVFile": "Hiện chỉ hỗ trợ các tệp được ngăn cách bằng dấu phẩy (.csv).",
"invalidCoord": "Trường vị trí không hợp lệ. Vui lòng kiểm tra tệp .csv.",
"tooManyRecords": "Rất tiếc, hiện không được có quá ${0} bản ghi.",
"CSVNoRecords": "Tệp không chứa bất kỳ hồ sơ nào.",
"CSVEmptyFile": "Không có nội dung trong tệp."
},
"results": {
"csvLoaded": "Đã tải ${0} bản ghi từ tệp CSV",
"recordsPlotted": "Đã định vị ${0}/${1} bản ghi trên bản đồ",
"recordsEnriched": "Đã xử lý ${0}/${1}, đã bổ sung ${2} so với ${3}",
"recordsError": "${0} bản ghi có lỗi",
"recordsErrorList": "Hàng ${0} có sự cố",
"label": "Kết quả CSV"
}
}); | cmccullough2/cmv-wab-widgets | wab/2.3/widgets/GeoLookup/nls/vi/strings.js | JavaScript | mit | 1,683 |
var chai = require("chai")
var should = chai.should();
chai.use(require("chai-http"));
var request = chai.request(require("./server"))
var db = require("mongojs")("test")
describe("CRUD Handler", () => {
before(done => {
done()
})
beforeEach(done => {
db.dropDatabase(done);
})
after(done => {
db.dropDatabase(done)
})
it("should save a document", (done) => {
var data = {
name: "test"
}
request.post("/test")
.send(data)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(201);
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
res.body.data.name.should.be.eql("test")
res.body.data.should.have.property("_id");
done()
})
})
it("should list all documents", (done ) => {
var list = [
{name: 'test21'}, {name: 'test22'}
]
db.collection("test").insert(list, (err, result) => {
request.get("/test")
.end((err, res) => {
should.not.exist(err)
res.should.have.status(200)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
res.body.data.should.have.keys(['count', 'list'])
res.body.data.count.should.be.eql(2)
res.body.data.list.length.should.be.eql(2)
done()
})
})
})
it("should get a single document", done => {
var doc = {
name: 'test3'
}
db.collection('test').insert(doc, (err, result ) => {
request.get("/test/" + result._id)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(200)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
res.body.data.should.have.keys(['_id', 'name'])
res.body.data.name.should.be.eql(doc.name);
done()
})
})
})
it("should update an existing document", done => {
var doc = {
name: 'test3'
}
db.collection('test').insert(doc, (err, result ) => {
result.name = "test3_updated";
request.put("/test/" + result._id)
.send(result)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(202)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
db.collection('test').findOne({_id: db.ObjectId(result._id)}, (err, result1) => {
should.not.exist(err)
result1.name.should.be.eql(result.name);
done()
})
})
})
})
it("should remove a document", done => {
var doc = {
name: 'test3'
}
db.collection('test').insert(doc, (err, result ) => {
request.delete("/test/" + result._id)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(202)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
db.collection('test').findOne({_id: db.ObjectId(result._id)}, (err, result1) => {
should.not.exist(err)
should.not.exist(result1);
done()
})
})
})
})
}) | AkashBabu/server-helper | test/crudHandler/test.js | JavaScript | mit | 4,155 |
"use strict";
devdiv.directive('devDiv', [function () {
return {
restrict: 'E',
link: function (scope, iElement, iAttrs) {
iElement.addClass("dev-div");
iElement.addClass("row");
}
};
}])
devdiv.controller('NameCtrl', function ($scope, $watch) {
}); | abdurrahmanekr/devdiv | src/directive/devdiv.js | JavaScript | mit | 267 |
(function() {
'use strict';
/* Filters */
var md5 = function (s) {
if (!s) return '';
function L(k, d) {
return (k << d) | (k >>> (32 - d));
}
function K(G, k) {
var I, d, F, H, x;
F = (G & 2147483648);
H = (k & 2147483648);
I = (G & 1073741824);
d = (k & 1073741824);
x = (G & 1073741823) + (k & 1073741823);
if (I & d) {
return (x ^ 2147483648 ^ F ^ H);
}
if (I | d) {
if (x & 1073741824) {
return (x ^ 3221225472 ^ F ^ H);
} else {
return (x ^ 1073741824 ^ F ^ H);
}
} else {
return (x ^ F ^ H);
}
}
function r(d, F, k) {
return (d & F) | ((~d) & k);
}
function q(d, F, k) {
return (d & k) | (F & (~k));
}
function p(d, F, k) {
return (d ^ F ^ k);
}
function n(d, F, k) {
return (F ^ (d | (~k)));
}
function u(G, F, aa, Z, k, H, I) {
G = K(G, K(K(r(F, aa, Z), k), I));
return K(L(G, H), F);
}
function f(G, F, aa, Z, k, H, I) {
G = K(G, K(K(q(F, aa, Z), k), I));
return K(L(G, H), F);
}
function D(G, F, aa, Z, k, H, I) {
G = K(G, K(K(p(F, aa, Z), k), I));
return K(L(G, H), F);
}
function t(G, F, aa, Z, k, H, I) {
G = K(G, K(K(n(F, aa, Z), k), I));
return K(L(G, H), F);
}
function e(G) {
var Z;
var F = G.length;
var x = F + 8;
var k = (x - (x % 64)) / 64;
var I = (k + 1) * 16;
var aa = Array(I - 1);
var d = 0;
var H = 0;
while (H < F) {
Z = (H - (H % 4)) / 4;
d = (H % 4) * 8;
aa[Z] = (aa[Z] | (G.charCodeAt(H) << d));
H++;
}
Z = (H - (H % 4)) / 4;
d = (H % 4) * 8;
aa[Z] = aa[Z] | (128 << d);
aa[I - 2] = F << 3;
aa[I - 1] = F >>> 29;
return aa;
}
function B(x) {
var k = "",
F = "",
G, d;
for (d = 0; d <= 3; d++) {
G = (x >>> (d * 8)) & 255;
F = "0" + G.toString(16);
k = k + F.substr(F.length - 2, 2);
}
return k;
}
function J(k) {
k = k.replace(/rn/g, "n");
var d = "";
for (var F = 0; F < k.length; F++) {
var x = k.charCodeAt(F);
if (x < 128) {
d += String.fromCharCode(x);
} else {
if ((x > 127) && (x < 2048)) {
d += String.fromCharCode((x >> 6) | 192);
d += String.fromCharCode((x & 63) | 128);
} else {
d += String.fromCharCode((x >> 12) | 224);
d += String.fromCharCode(((x >> 6) & 63) | 128);
d += String.fromCharCode((x & 63) | 128);
}
}
}
return d;
}
var C = [];
var P, h, E, v, g, Y, X, W, V;
var S = 7,
Q = 12,
N = 17,
M = 22;
var A = 5,
z = 9,
y = 14,
w = 20;
var o = 4,
m = 11,
l = 16,
j = 23;
var U = 6,
T = 10,
R = 15,
O = 21;
s = J(s);
C = e(s);
Y = 1732584193;
X = 4023233417;
W = 2562383102;
V = 271733878;
for (P = 0; P < C.length; P += 16) {
h = Y;
E = X;
v = W;
g = V;
Y = u(Y, X, W, V, C[P + 0], S, 3614090360);
V = u(V, Y, X, W, C[P + 1], Q, 3905402710);
W = u(W, V, Y, X, C[P + 2], N, 606105819);
X = u(X, W, V, Y, C[P + 3], M, 3250441966);
Y = u(Y, X, W, V, C[P + 4], S, 4118548399);
V = u(V, Y, X, W, C[P + 5], Q, 1200080426);
W = u(W, V, Y, X, C[P + 6], N, 2821735955);
X = u(X, W, V, Y, C[P + 7], M, 4249261313);
Y = u(Y, X, W, V, C[P + 8], S, 1770035416);
V = u(V, Y, X, W, C[P + 9], Q, 2336552879);
W = u(W, V, Y, X, C[P + 10], N, 4294925233);
X = u(X, W, V, Y, C[P + 11], M, 2304563134);
Y = u(Y, X, W, V, C[P + 12], S, 1804603682);
V = u(V, Y, X, W, C[P + 13], Q, 4254626195);
W = u(W, V, Y, X, C[P + 14], N, 2792965006);
X = u(X, W, V, Y, C[P + 15], M, 1236535329);
Y = f(Y, X, W, V, C[P + 1], A, 4129170786);
V = f(V, Y, X, W, C[P + 6], z, 3225465664);
W = f(W, V, Y, X, C[P + 11], y, 643717713);
X = f(X, W, V, Y, C[P + 0], w, 3921069994);
Y = f(Y, X, W, V, C[P + 5], A, 3593408605);
V = f(V, Y, X, W, C[P + 10], z, 38016083);
W = f(W, V, Y, X, C[P + 15], y, 3634488961);
X = f(X, W, V, Y, C[P + 4], w, 3889429448);
Y = f(Y, X, W, V, C[P + 9], A, 568446438);
V = f(V, Y, X, W, C[P + 14], z, 3275163606);
W = f(W, V, Y, X, C[P + 3], y, 4107603335);
X = f(X, W, V, Y, C[P + 8], w, 1163531501);
Y = f(Y, X, W, V, C[P + 13], A, 2850285829);
V = f(V, Y, X, W, C[P + 2], z, 4243563512);
W = f(W, V, Y, X, C[P + 7], y, 1735328473);
X = f(X, W, V, Y, C[P + 12], w, 2368359562);
Y = D(Y, X, W, V, C[P + 5], o, 4294588738);
V = D(V, Y, X, W, C[P + 8], m, 2272392833);
W = D(W, V, Y, X, C[P + 11], l, 1839030562);
X = D(X, W, V, Y, C[P + 14], j, 4259657740);
Y = D(Y, X, W, V, C[P + 1], o, 2763975236);
V = D(V, Y, X, W, C[P + 4], m, 1272893353);
W = D(W, V, Y, X, C[P + 7], l, 4139469664);
X = D(X, W, V, Y, C[P + 10], j, 3200236656);
Y = D(Y, X, W, V, C[P + 13], o, 681279174);
V = D(V, Y, X, W, C[P + 0], m, 3936430074);
W = D(W, V, Y, X, C[P + 3], l, 3572445317);
X = D(X, W, V, Y, C[P + 6], j, 76029189);
Y = D(Y, X, W, V, C[P + 9], o, 3654602809);
V = D(V, Y, X, W, C[P + 12], m, 3873151461);
W = D(W, V, Y, X, C[P + 15], l, 530742520);
X = D(X, W, V, Y, C[P + 2], j, 3299628645);
Y = t(Y, X, W, V, C[P + 0], U, 4096336452);
V = t(V, Y, X, W, C[P + 7], T, 1126891415);
W = t(W, V, Y, X, C[P + 14], R, 2878612391);
X = t(X, W, V, Y, C[P + 5], O, 4237533241);
Y = t(Y, X, W, V, C[P + 12], U, 1700485571);
V = t(V, Y, X, W, C[P + 3], T, 2399980690);
W = t(W, V, Y, X, C[P + 10], R, 4293915773);
X = t(X, W, V, Y, C[P + 1], O, 2240044497);
Y = t(Y, X, W, V, C[P + 8], U, 1873313359);
V = t(V, Y, X, W, C[P + 15], T, 4264355552);
W = t(W, V, Y, X, C[P + 6], R, 2734768916);
X = t(X, W, V, Y, C[P + 13], O, 1309151649);
Y = t(Y, X, W, V, C[P + 4], U, 4149444226);
V = t(V, Y, X, W, C[P + 11], T, 3174756917);
W = t(W, V, Y, X, C[P + 2], R, 718787259);
X = t(X, W, V, Y, C[P + 9], O, 3951481745);
Y = K(Y, h);
X = K(X, E);
W = K(W, v);
V = K(V, g);
}
var i = B(Y) + B(X) + B(W) + B(V);
return i.toLowerCase();
};
angular.module('talis.filters.md5', []).
filter("md5", function(){
return md5;
});
}).call(this);
| chariotsolutions/reactive-quizzo-code-sample | public/moderator/bower_components/md5-angular-filter/js/md5.filter.js | JavaScript | mit | 6,722 |
#!/usr/bin/env python
#
# GrovePi Example for using the Grove Electricity Sensor (http://www.seeedstudio.com/wiki/Grove_-_Electricity_Sensor)
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
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.
'''
import time
import grovepi
# Connect the Grove Electricity Sensor to analog port A0
# SIG,NC,NC,GND
sensor = 0
grovepi.pinMode(sensor,"INPUT")
# Vcc of the grove interface is normally 5v
grove_vcc = 5
while True:
try:
# Get sensor value
sensor_value = grovepi.analogRead(sensor)
# Calculate amplitude current (mA)
amplitude_current = (float)(sensor_value / 1024 * grove_vcc / 800 * 2000000)
# Calculate effective value (mA)
effective_value = amplitude_current / 1.414
# minimum_current = 1 / 1024 * grove_vcc / 800 * 2000000 / 1.414 = 8.6(mA)
# Only for sinusoidal alternating current
print("sensor_value", sensor_value)
print("The amplitude of the current is", amplitude_current, "mA")
print("The effective value of the current is", effective_value, "mA")
time.sleep(1)
except IOError:
print ("Error")
| karan259/GrovePi | Software/Python/grove_electricity_sensor.py | Python | mit | 2,530 |
// 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
using System;
using System.IO;
public static partial class Extensions
{
/// <summary>
/// Changes the extension of a @this string.
/// </summary>
/// <param name="this">
/// The @this information to modify. The @this cannot contain any of the characters defined in
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .
/// </param>
/// <param name="extension">
/// The new extension (with or without a leading period). Specify null to remove an existing
/// extension from
/// <paramref
/// name="this" />
/// .
/// </param>
/// <returns>
/// The modified @this information.On Windows-based desktop platforms, if <paramref name="this" /> is null or an
/// empty string (""), the @this information is returned unmodified. If
/// <paramref
/// name="extension" />
/// is null, the returned string contains the specified @this with its extension removed. If
/// <paramref
/// name="this" />
/// has no extension, and <paramref name="extension" /> is not null, the returned @this string contains
/// <paramref
/// name="extension" />
/// appended to the end of <paramref name="this" />.
/// </returns>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this" /> contains one or more of the invalid
/// characters defined in
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .
/// </exception>
public static String ChangeExtension(this FileInfo @this, String extension)
{
return Path.ChangeExtension(@this.FullName, extension);
}
} | mario-loza/Z.ExtensionMethods | src/Z.IO/System.IO.FileInfo/FileInfo.ChangeExtension.cs | C# | mit | 2,160 |
require 'openssl'
require_relative 'app'
module Spaceship
module Portal
# Represents a certificate from the Apple Developer Portal.
#
# This can either be a code signing identity or a push profile
class Certificate < PortalBase
# @return (String) The ID given from the developer portal. You'll probably not need it.
# @example
# "P577TH3PAA"
attr_accessor :id
# @return (String) The name of the certificate
# @example Company
# "SunApps GmbH"
# @example Push Profile
# "Apple Push Services"
attr_accessor :name
# @return (String) Status of the certificate
# @example
# "Issued"
attr_accessor :status
# @return (Date) The date and time when the certificate was created
# @example
# 2015-04-01 21:24:00 UTC
attr_accessor :created
# @return (Date) The date and time when the certificate will expire
# @example
# 2016-04-01 21:24:00 UTC
attr_accessor :expires
# @return (String) The owner type that defines if it's a push profile
# or a code signing identity
#
# @example Code Signing Identity
# "team"
# @example Push Certificate
# "bundle"
attr_accessor :owner_type
# @return (String) The name of the owner
#
# @example Code Signing Identity (usually the company name)
# "SunApps Gmbh"
# @example Push Certificate (the bundle identifier)
# "tools.fastlane.app"
attr_accessor :owner_name
# @return (String) The ID of the owner, that can be used to
# fetch more information
# @example
# "75B83SPLAA"
attr_accessor :owner_id
# Indicates the type of this certificate
# which is automatically used to determine the class of
# the certificate. Available values listed in CERTIFICATE_TYPE_IDS
# @return (String) The type of the certificate
# @example Production Certificate
# "R58UK2EWSO"
# @example Development Certificate
# "5QPB9NHCEI"
attr_accessor :type_display_id
# @return (Bool) Whether or not the certificate can be downloaded
attr_accessor :can_download
attr_mapping({
'certificateId' => :id,
'name' => :name,
'statusString' => :status,
'dateCreated' => :created,
'expirationDate' => :expires,
'ownerType' => :owner_type,
'ownerName' => :owner_name,
'ownerId' => :owner_id,
'certificateTypeDisplayId' => :type_display_id,
'canDownload' => :can_download
})
#####################################################
# Certs are not associated with apps
#####################################################
# A development code signing certificate used for development environment
class Development < Certificate; end
# A production code signing certificate used for distribution environment
class Production < Certificate; end
# An In House code signing certificate used for enterprise distributions
class InHouse < Certificate; end
# A Mac development code signing certificate used for development environment
class MacDevelopment < Certificate; end
# A Mac production code signing certificate for building .app bundles
class MacAppDistribution < Certificate; end
# A Mac production code signing certificate for building .pkg installers
class MacInstallerDistribution < Certificate; end
# A Mac Developer ID signing certificate for building .app bundles
class DeveloperIDApplication < Certificate; end
# A Mac Developer ID signing certificate for building .pkg installers
class DeveloperIDInstaller < Certificate; end
#####################################################
# Certs that are specific for one app
#####################################################
# Abstract class for push certificates. Check out the subclasses
# DevelopmentPush, ProductionPush, WebsitePush and VoipPush
class PushCertificate < Certificate; end
# A push notification certificate for development environment
class DevelopmentPush < PushCertificate; end
# A push notification certificate for production environment
class ProductionPush < PushCertificate; end
# A push notification certificate for websites
class WebsitePush < PushCertificate; end
# A push notification certificate for the VOIP environment
class VoipPush < PushCertificate; end
# Passbook certificate
class Passbook < Certificate; end
# ApplePay certificate
class ApplePay < Certificate; end
# A Mac push notification certificate for development environment
class MacDevelopmentPush < PushCertificate; end
# A Mac push notification certificate for production environment
class MacProductionPush < PushCertificate; end
IOS_CERTIFICATE_TYPE_IDS = {
"5QPB9NHCEI" => Development,
"R58UK2EWSO" => Production,
"9RQEK7MSXA" => InHouse,
"LA30L5BJEU" => Certificate,
"BKLRAVXMGM" => DevelopmentPush,
"UPV3DW712I" => ProductionPush,
"Y3B2F3TYSI" => Passbook,
"3T2ZP62QW8" => WebsitePush,
"E5D663CMZW" => VoipPush,
"4APLUP237T" => ApplePay
}
OLDER_IOS_CERTIFICATE_TYPES = [
# those are also sent by the browser, but not sure what they represent
"T44PTHVNID",
"DZQUP8189Y",
"FGQUP4785Z",
"S5WE21TULA",
"3BQKVH9I2X", # ProductionPush,
"FUOY7LWJET"
]
MAC_CERTIFICATE_TYPE_IDS = {
"749Y1QAGU7" => MacDevelopment,
"HXZEUKP0FP" => MacAppDistribution,
"2PQI8IDXNH" => MacInstallerDistribution,
"OYVN2GW35E" => DeveloperIDInstaller,
"W0EURJRMC5" => DeveloperIDApplication,
"CDZ7EMXIZ1" => MacProductionPush,
"HQ4KP3I34R" => MacDevelopmentPush,
"DIVN2GW3XT" => DeveloperIDApplication
}
CERTIFICATE_TYPE_IDS = IOS_CERTIFICATE_TYPE_IDS.merge(MAC_CERTIFICATE_TYPE_IDS)
# Class methods
class << self
# Create a new code signing request that can be used to
# generate a new certificate
# @example
# Create a new certificate signing request
# csr, pkey = Spaceship.certificate.create_certificate_signing_request
#
# # Use the signing request to create a new distribution certificate
# Spaceship.certificate.production.create!(csr: csr)
def create_certificate_signing_request
key = OpenSSL::PKey::RSA.new(2048)
csr = OpenSSL::X509::Request.new
csr.version = 0
csr.subject = OpenSSL::X509::Name.new([
['CN', 'PEM', OpenSSL::ASN1::UTF8STRING]
])
csr.public_key = key.public_key
csr.sign(key, OpenSSL::Digest::SHA1.new)
return [csr, key]
end
# Create a new object based on a hash.
# This is used to create a new object based on the server response.
def factory(attrs)
# Example:
# => {"name"=>"iOS Distribution: SunApps GmbH",
# "certificateId"=>"XC5PH8DAAA",
# "serialNumber"=>"797E732CCE8B7AAA",
# "status"=>"Issued",
# "statusCode"=>0,
# "expirationDate"=>#<DateTime: 2015-11-25T22:45:50+00:00 ((2457352j,81950s,0n),+0s,2299161j)>,
# "certificatePlatform"=>"ios",
# "certificateType"=>
# {"certificateTypeDisplayId"=>"R58UK2EAAA",
# "name"=>"iOS Distribution",
# "platform"=>"ios",
# "permissionType"=>"distribution",
# "distributionType"=>"store",
# "distributionMethod"=>"app",
# "ownerType"=>"team",
# "daysOverlap"=>364,
# "maxActive"=>2}}
if attrs['certificateType']
# On some accounts this is nested, so we need to flatten it
attrs.merge!(attrs['certificateType'])
attrs.delete('certificateType')
end
# Parse the dates
# rubocop:disable Style/RescueModifier
attrs['expirationDate'] = (Time.parse(attrs['expirationDate']) rescue attrs['expirationDate'])
attrs['dateCreated'] = (Time.parse(attrs['dateCreated']) rescue attrs['dateCreated'])
# rubocop:enable Style/RescueModifier
# Here we go
klass = CERTIFICATE_TYPE_IDS[attrs['certificateTypeDisplayId']]
klass ||= Certificate
klass.client = @client
klass.new(attrs)
end
# @param mac [Bool] Fetches Mac certificates if true. (Ignored if callsed from a subclass)
# @return (Array) Returns all certificates of this account.
# If this is called from a subclass of Certificate, this will
# only include certificates matching the current type.
def all(mac: false)
if self == Certificate # are we the base-class?
type_ids = mac ? MAC_CERTIFICATE_TYPE_IDS : IOS_CERTIFICATE_TYPE_IDS
types = type_ids.keys
types += OLDER_IOS_CERTIFICATE_TYPES unless mac
else
types = [CERTIFICATE_TYPE_IDS.key(self)]
mac = MAC_CERTIFICATE_TYPE_IDS.values.include?(self)
end
client.certificates(types, mac: mac).map do |cert|
factory(cert)
end
end
# @param mac [Bool] Searches Mac certificates if true
# @return (Certificate) Find a certificate based on the ID of the certificate.
def find(certificate_id, mac: false)
all(mac: mac).find do |c|
c.id == certificate_id
end
end
# Generate a new certificate based on a code certificate signing request
# @param csr (OpenSSL::X509::Request) (required): The certificate signing request to use. Get one using
# `create_certificate_signing_request`
# @param bundle_id (String) (optional): The app identifier this certificate is for.
# This value is only needed if you create a push profile. For normal code signing
# certificates, you must only pass a certificate signing request.
# @example
# # Create a new certificate signing request
# csr, pkey = Spaceship::Certificate.create_certificate_signing_request
#
# # Use the signing request to create a new distribution certificate
# Spaceship::Certificate::Production.create!(csr: csr)
# @return (Certificate): The newly created certificate
def create!(csr: nil, bundle_id: nil)
type = CERTIFICATE_TYPE_IDS.key(self)
mac = MAC_CERTIFICATE_TYPE_IDS.include?(type)
# look up the app_id by the bundle_id
if bundle_id
app = Spaceship::Portal::App.set_client(client).find(bundle_id)
raise "Could not find app with bundle id '#{bundle_id}'" unless app
app_id = app.app_id
end
# ensure csr is a OpenSSL::X509::Request
csr = OpenSSL::X509::Request.new(csr) if csr.kind_of?(String)
# if this succeeds, we need to save the .cer and the private key in keychain access or wherever they go in linux
response = client.create_certificate!(type, csr.to_pem, app_id, mac)
# munge the response to make it work for the factory
response['certificateTypeDisplayId'] = response['certificateType']['certificateTypeDisplayId']
self.new(response)
end
end
# instance methods
# @return (String) Download the raw data of the certificate without parsing
def download_raw
client.download_certificate(id, type_display_id, mac: mac?)
end
# @return (OpenSSL::X509::Certificate) Downloads and parses the certificate
def download
OpenSSL::X509::Certificate.new(download_raw)
end
# Revoke the certificate. You shouldn't use this method probably.
def revoke!
client.revoke_certificate!(id, type_display_id, mac: mac?)
end
# @return (Bool): Is this certificate a push profile for apps?
def is_push?
self.kind_of?(PushCertificate)
end
# @return (Bool) Is this a Mac profile?
def mac?
MAC_CERTIFICATE_TYPE_IDS.include?(type_display_id)
end
end
end
end
| orta/fastlane | spaceship/lib/spaceship/portal/certificate.rb | Ruby | mit | 12,581 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConsoleApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1be8ecdc-8f75-490d-ba5b-1dc456c19a6c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| MilStancheva/Telerik-Academy-Projects | C# Fundamentals/OperatorsAndExpressions/11. 3rd Bit/Properties/AssemblyInfo.cs | C# | mit | 1,414 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./glyphMargin';
import { DynamicViewOverlay } from 'vs/editor/browser/view/dynamicViewOverlay';
import { ViewContext } from 'vs/editor/common/view/viewContext';
import { RenderingContext } from 'vs/editor/common/view/renderingContext';
import * as viewEvents from 'vs/editor/common/view/viewEvents';
import { editorBackground } from 'vs/platform/theme/common/colorRegistry';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
export class DecorationToRender {
_decorationToRenderBrand: void;
public startLineNumber: number;
public endLineNumber: number;
public className: string;
constructor(startLineNumber: number, endLineNumber: number, className: string) {
this.startLineNumber = +startLineNumber;
this.endLineNumber = +endLineNumber;
this.className = String(className);
}
}
export abstract class DedupOverlay extends DynamicViewOverlay {
protected _render(visibleStartLineNumber: number, visibleEndLineNumber: number, decorations: DecorationToRender[]): string[][] {
let output: string[][] = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
let lineIndex = lineNumber - visibleStartLineNumber;
output[lineIndex] = [];
}
if (decorations.length === 0) {
return output;
}
decorations.sort((a, b) => {
if (a.className === b.className) {
if (a.startLineNumber === b.startLineNumber) {
return a.endLineNumber - b.endLineNumber;
}
return a.startLineNumber - b.startLineNumber;
}
return (a.className < b.className ? -1 : 1);
});
let prevClassName: string = null;
let prevEndLineIndex = 0;
for (let i = 0, len = decorations.length; i < len; i++) {
let d = decorations[i];
let className = d.className;
let startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber;
let endLineIndex = Math.min(d.endLineNumber, visibleEndLineNumber) - visibleStartLineNumber;
if (prevClassName === className) {
startLineIndex = Math.max(prevEndLineIndex + 1, startLineIndex);
prevEndLineIndex = Math.max(prevEndLineIndex, endLineIndex);
} else {
prevClassName = className;
prevEndLineIndex = endLineIndex;
}
for (let i = startLineIndex; i <= prevEndLineIndex; i++) {
output[i].push(prevClassName);
}
}
return output;
}
}
export class GlyphMarginOverlay extends DedupOverlay {
private _context: ViewContext;
private _lineHeight: number;
private _glyphMargin: boolean;
private _glyphMarginLeft: number;
private _glyphMarginWidth: number;
private _renderResult: string[];
constructor(context: ViewContext) {
super();
this._context = context;
this._lineHeight = this._context.configuration.editor.lineHeight;
this._glyphMargin = this._context.configuration.editor.viewInfo.glyphMargin;
this._glyphMarginLeft = this._context.configuration.editor.layoutInfo.glyphMarginLeft;
this._glyphMarginWidth = this._context.configuration.editor.layoutInfo.glyphMarginWidth;
this._renderResult = null;
this._context.addEventHandler(this);
}
public dispose(): void {
this._context.removeEventHandler(this);
this._context = null;
this._renderResult = null;
}
// --- begin event handlers
public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {
if (e.lineHeight) {
this._lineHeight = this._context.configuration.editor.lineHeight;
}
if (e.viewInfo.glyphMargin) {
this._glyphMargin = this._context.configuration.editor.viewInfo.glyphMargin;
}
if (e.layoutInfo) {
this._glyphMarginLeft = this._context.configuration.editor.layoutInfo.glyphMarginLeft;
this._glyphMarginWidth = this._context.configuration.editor.layoutInfo.glyphMarginWidth;
}
return true;
}
public onCursorPositionChanged(e: viewEvents.ViewCursorPositionChangedEvent): boolean {
return false;
}
public onCursorSelectionChanged(e: viewEvents.ViewCursorSelectionChangedEvent): boolean {
return false;
}
public onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean {
return true;
}
public onFlushed(e: viewEvents.ViewFlushedEvent): boolean {
return true;
}
public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {
return true;
}
public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean {
return true;
}
public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean {
return true;
}
public onRevealRangeRequest(e: viewEvents.ViewRevealRangeRequestEvent): boolean {
return false;
}
public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {
return e.scrollTopChanged;
}
public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean {
return true;
}
// --- end event handlers
protected _getDecorations(ctx: RenderingContext): DecorationToRender[] {
let decorations = ctx.getDecorationsInViewport();
let r: DecorationToRender[] = [];
for (let i = 0, len = decorations.length; i < len; i++) {
let d = decorations[i];
let glyphMarginClassName = d.source.options.glyphMarginClassName;
if (glyphMarginClassName) {
r.push(new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, glyphMarginClassName));
}
}
return r;
}
public prepareRender(ctx: RenderingContext): void {
if (!this._glyphMargin) {
this._renderResult = null;
return;
}
let visibleStartLineNumber = ctx.visibleRange.startLineNumber;
let visibleEndLineNumber = ctx.visibleRange.endLineNumber;
let toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
let lineHeight = this._lineHeight.toString();
let left = this._glyphMarginLeft.toString();
let width = this._glyphMarginWidth.toString();
let common = '" style="left:' + left + 'px;width:' + width + 'px' + ';height:' + lineHeight + 'px;"></div>';
let output: string[] = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
let lineIndex = lineNumber - visibleStartLineNumber;
let classNames = toRender[lineIndex];
if (classNames.length === 0) {
output[lineIndex] = '';
} else {
output[lineIndex] = (
'<div class="cgmr '
+ classNames.join(' ')
+ common
);
}
}
this._renderResult = output;
}
public render(startLineNumber: number, lineNumber: number): string {
if (!this._renderResult) {
return '';
}
let lineIndex = lineNumber - startLineNumber;
if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
throw new Error('Unexpected render request');
}
return this._renderResult[lineIndex];
}
}
registerThemingParticipant((theme, collector) => {
let editorBackgroundColor = theme.getColor(editorBackground);
if (editorBackgroundColor) {
collector.addRule(`.monaco-editor.${theme.selector} .glyph-margin { background-color: ${editorBackgroundColor}; }`);
}
}); | hashhar/vscode | src/vs/editor/browser/viewParts/glyphMargin/glyphMargin.ts | TypeScript | mit | 7,276 |
package net.ontrack.core.security;
import lombok.Data;
import net.ontrack.core.model.AccountSummary;
@Data
public class ProjectAuthorization {
private final int project;
private final AccountSummary account;
private final ProjectRole role;
}
| joansmith/ontrack | ontrack-core/src/main/java/net/ontrack/core/security/ProjectAuthorization.java | Java | mit | 258 |
require 'set'
require 'sprockets/http_utils'
require 'sprockets/path_dependency_utils'
require 'sprockets/uri_utils'
module Sprockets
module Resolve
include HTTPUtils, PathDependencyUtils, URIUtils
# Public: Find Asset URI for given a logical path by searching the
# environment's load paths.
#
# resolve("application.js")
# # => "file:///path/to/app/javascripts/application.js?type=application/javascript"
#
# An accept content type can be given if the logical path doesn't have a
# format extension.
#
# resolve("application", accept: "application/javascript")
# # => "file:///path/to/app/javascripts/application.coffee?type=application/javascript"
#
# The String Asset URI is returned or nil if no results are found.
def resolve(path, load_paths: config[:paths], accept: nil, pipeline: nil, base_path: nil)
paths = load_paths
if valid_asset_uri?(path)
uri, deps = resolve_asset_uri(path)
elsif absolute_path?(path)
filename, type, deps = resolve_absolute_path(paths, path, accept)
elsif relative_path?(path)
filename, type, path_pipeline, deps, index_alias = resolve_relative_path(paths, path, base_path, accept)
else
filename, type, path_pipeline, deps, index_alias = resolve_logical_path(paths, path, accept)
end
if filename
uri = build_asset_uri(filename, type: type, pipeline: pipeline || path_pipeline, index_alias: index_alias)
end
return uri, deps
end
# Public: Same as resolve() but raises a FileNotFound exception instead of
# nil if no assets are found.
def resolve!(path, **kargs)
uri, deps = resolve(path, **kargs)
unless uri
message = "couldn't find file '#{path}'"
if relative_path?(path) && kargs[:base_path]
load_path, _ = paths_split(config[:paths], kargs[:base_path])
message << " under '#{load_path}'"
end
message << " with type '#{kargs[:accept]}'" if kargs[:accept]
raise FileNotFound, message
end
return uri, deps
end
protected
def resolve_asset_uri(uri)
filename, _ = parse_asset_uri(uri)
return uri, Set.new([build_file_digest_uri(filename)])
end
def resolve_absolute_path(paths, filename, accept)
deps = Set.new
filename = File.expand_path(filename)
# Ensure path is under load paths
return nil, nil, deps unless paths_split(paths, filename)
_, mime_type = match_path_extname(filename, config[:mime_exts])
type = resolve_transform_type(mime_type, accept)
return nil, nil, deps if accept && !type
return nil, nil, deps unless file?(filename)
deps << build_file_digest_uri(filename)
return filename, type, deps
end
def resolve_relative_path(paths, path, dirname, accept)
filename = File.expand_path(path, dirname)
load_path, _ = paths_split(paths, dirname)
if load_path && logical_path = split_subpath(load_path, filename)
resolve_logical_path([load_path], logical_path, accept)
else
return nil, nil, nil, Set.new
end
end
def resolve_logical_path(paths, logical_path, accept)
extname, mime_type = match_path_extname(logical_path, config[:mime_exts])
logical_name = logical_path.chomp(extname)
extname, pipeline = match_path_extname(logical_name, config[:pipeline_exts])
logical_name = logical_name.chomp(extname)
parsed_accept = parse_accept_options(mime_type, accept)
transformed_accepts = expand_transform_accepts(parsed_accept)
filename, mime_type, deps, index_alias = resolve_under_paths(paths, logical_name, transformed_accepts)
if filename
deps << build_file_digest_uri(filename)
type = resolve_transform_type(mime_type, parsed_accept)
return filename, type, pipeline, deps, index_alias
else
return nil, nil, nil, deps
end
end
def resolve_under_paths(paths, logical_name, accepts)
deps = Set.new
return nil, nil, deps if accepts.empty?
mime_exts = config[:mime_exts]
paths.each do |load_path|
# TODO: Allow new path resolves to be registered
fns = [
method(:resolve_main_under_path),
method(:resolve_alts_under_path),
method(:resolve_index_under_path)
]
candidates = []
fns.each do |fn|
result = fn.call(load_path, logical_name, mime_exts)
candidates.concat(result[0])
deps.merge(result[1])
end
candidate = find_best_q_match(accepts, candidates) do |c, matcher|
match_mime_type?(c[:type] || "application/octet-stream", matcher)
end
return candidate[:filename], candidate[:type], deps, candidate[:index_alias] if candidate
end
return nil, nil, deps
end
def resolve_main_under_path(load_path, logical_name, mime_exts)
dirname = File.dirname(File.join(load_path, logical_name))
candidates = find_matching_path_for_extensions(dirname, File.basename(logical_name), mime_exts)
return candidates.map { |c|
{ filename: c[0], type: c[1] }
}, [build_file_digest_uri(dirname)]
end
def resolve_alts_under_path(load_path, logical_name, mime_exts)
filenames, deps = self.resolve_alternates(load_path, logical_name)
return filenames.map { |fn|
_, mime_type = match_path_extname(fn, mime_exts)
{ filename: fn, type: mime_type }
}, deps
end
def resolve_index_under_path(load_path, logical_name, mime_exts)
dirname = File.join(load_path, logical_name)
deps = [build_file_digest_uri(dirname)]
candidates = []
if directory?(dirname)
candidates = find_matching_path_for_extensions(dirname, "index", mime_exts)
end
return candidates.map { |c|
{ filename: c[0], type: c[1], index_alias: c[0].gsub(/\/index(\.\w{2,4})$/, '\1') }
}, deps
end
def parse_accept_options(mime_type, types)
accepts = []
accepts += parse_q_values(types) if types
if mime_type
if accepts.empty? || accepts.any? { |accept, _| match_mime_type?(mime_type, accept) }
accepts = [[mime_type, 1.0]]
else
return []
end
end
if accepts.empty?
accepts << ['*/*', 1.0]
end
accepts
end
def resolve_alternates(load_path, logical_name)
return [], Set.new
end
end
end
| askl56/sprockets | lib/sprockets/resolve.rb | Ruby | mit | 6,764 |
(function (subdivision) {
'use strict';
var count = 0;
var builders;
var defaultBuilder;
function buildInternal(type, addin, options, meta) {
var builder = subdivision.getBuilder(type);
if (builder.preBuildTarget) {
addin = buildInternal(builder.preBuildTarget, addin, options, meta);
}
return builder.build(addin, options, meta);
}
function buildInternalAsync(type, addin, options, meta) {
try {
var builder = subdivision.getBuilder(type);
var promise = Promise.resolve(addin);
if (builder.preBuildTarget) {
promise = buildInternalAsync(builder.preBuildTarget, addin, options, meta);
}
return promise.then(function (addin) {
return builder.build(addin, options, meta);
});
}
catch (ex) {
return Promise.reject(ex);
}
}
subdivision.Builder = function (options) {
var builder = subdivision.Addin.$internalConstructor('builder', count++, options);
if (!_.isFunction(builder.build)) {
throw new Error('Builder options must contain the "build" function ' + JSON.stringify(options));
}
builder.target = builder.target === undefined ? '' : builder.target;
return builder;
};
subdivision.systemPaths.builders = subdivision.registry.joinPath(subdivision.systemPaths.prefix, 'builders');
subdivision.defaultManifest.paths.push({
path: subdivision.systemPaths.builders,
addins: [
{
///Update docs if this changes
id: 'subdivision.defaultBuilder',
type: 'subdivision.builder',
target: null,
order: subdivision.registry.$defaultOrder,
build: function (addin) {
return _.cloneDeep(addin);
}
}
]
});
/**
* Adds a new builder created from the options to the list of known builders.
* If a builder that builds the given type already exists then
* the new builder is added based on the forced option. If force is truthy it is added anyway otherwise does nothing
* Returns true if a builder was added and false otherwise
*
*/
subdivision.addBuilder = function (options, force) {
var builder = new subdivision.Builder(options);
if (builder.target === null) {
if (!defaultBuilder || force) {
defaultBuilder = builder;
return true;
} else {
return false;
}
}
if (!builders.hasOwnProperty(builder.target) || force) {
builders[builder.target] = builder;
return true;
} else {
return false;
}
};
/**
* Gets a builder for the appropriate type, if no builder of the given type is found returns the default builder (builder with type === null)
* @param type
*/
subdivision.getBuilder = function (type) {
if (type === null && defaultBuilder) {
return defaultBuilder;
} else {
if (builders.hasOwnProperty(type)) {
return builders[type];
}
if (defaultBuilder) {
return defaultBuilder;
}
}
throw new Error('No builder of type "' + type + '" was defined and no default builder was registered');
};
/**
* Returns all the addins in the path after applying the appropriate builder on each
* @param path - The path to build
* @param options - Custom options to be passed to the addin builder
* @param searchCriteria - The search criteria for the underscore filter function
* @param skipSort - If truthy the topological sort is skipped
* @returns {Array} = The built addins
*/
subdivision.build = function (path, options, searchCriteria, skipSort) {
var addins = subdivision.getAddins(path, searchCriteria, skipSort);
if (addins.length === 0) {
return addins;
}
return _.map(addins, function (addin) {
return buildInternal(addin.type, addin, options, {
path: path
});
});
};
/**
* Returns all the addins in the path after applying the appropriate builder on each
* @param path - The path to build
* @param options - Custom options to be passed to the addin builder
* @param searchCriteria - The search criteria for the underscore filter function
* @param skipSort - If truthy the topological sort is skipped
* @returns {Array} = A promise that resolves with an array of the built addins
*/
subdivision.build.async = function (path, options, searchCriteria, skipSort) {
var addins = subdivision.getAddins(path, searchCriteria, skipSort);
if (addins.length === 0) {
return Promise.resolve(addins);
}
var promises = _.map(addins, function (addin) {
//TODO: Optimization that tries to guess the builder from previous builder
return buildInternalAsync(addin.type, addin, options, {
path: path
});
});
return Promise.all(promises);
};
/**
* Builds a single addin based on its type
* @param addin The addin to build
* @param options The options to pass to the builder
*/
subdivision.buildAddin = function (addin, options) {
return buildInternal(addin.type, addin, options, {
path: null
});
};
/**
* The async version of buildAddin
* @param addin The addin to build
* @param options The options to pass to the builder
* @returns A promise that when resolved returns the built addin
*/
subdivision.buildAddin.async = function (addin, options) {
return buildInternalAsync(addin.type, addin, options, {
path: null
});
};
/**
* Builds a tree out of the given path. Each addin will have child elements at path+addin.id added
* to its items property (default $items).
* @param path
* @param options - Custom options to be passed to the addin builder
*/
subdivision.buildTree = function (path, options) {
var addins = subdivision.getAddins(path);
if (addins.length === 0) {
return addins;
}
return _.map(addins, function (addin) {
//TODO: Optimization that tries to guess the builder from previous builder
var result = buildInternal(addin.type, addin, options, {
path: path
});
var itemsProperty = addin.itemsProperty || '$items';
result[itemsProperty] = subdivision.buildTree(subdivision.registry.joinPath(path, addin.id), options);
return result;
});
};
/**
* Regenerates all the builders from the system builders path
*/
subdivision.$generateBuilders = function () {
subdivision.$clearBuilders();
var addins = subdivision.getAddins(subdivision.systemPaths.builders, {target: null});
if (addins.length > 0) {
defaultBuilder = new subdivision.Builder(addins[0]);
}
addins = subdivision.getAddins(subdivision.systemPaths.builders);
_.forEach(addins, function (addin) {
subdivision.addBuilder(addin);
});
};
subdivision.$clearBuilders = function () {
builders = {};
defaultBuilder = null;
};
subdivision.$clearBuilders();
Object.defineProperty(subdivision, 'builders', {
enumerable: true,
configurable: false,
get: function () {
return _.clone(builders);
}
});
})(subdivision); | BorisKozo/extensibility.js | app/lib/builder.js | JavaScript | mit | 7,868 |
import argparse
import asyncio
import gc
import os.path
import pathlib
import socket
import ssl
PRINT = 0
async def echo_server(loop, address, unix):
if unix:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(address)
sock.listen(5)
sock.setblocking(False)
if PRINT:
print('Server listening at', address)
with sock:
while True:
client, addr = await loop.sock_accept(sock)
if PRINT:
print('Connection from', addr)
loop.create_task(echo_client(loop, client))
async def echo_client(loop, client):
try:
client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except (OSError, NameError):
pass
with client:
while True:
data = await loop.sock_recv(client, 1000000)
if not data:
break
await loop.sock_sendall(client, data)
if PRINT:
print('Connection closed')
async def echo_client_streams(reader, writer):
sock = writer.get_extra_info('socket')
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except (OSError, NameError):
pass
if PRINT:
print('Connection from', sock.getpeername())
while True:
data = await reader.read(1000000)
if not data:
break
writer.write(data)
if PRINT:
print('Connection closed')
writer.close()
class EchoProtocol(asyncio.Protocol):
def connection_made(self, transport):
self.transport = transport
def connection_lost(self, exc):
self.transport = None
def data_received(self, data):
self.transport.write(data)
class EchoBufferedProtocol(asyncio.BufferedProtocol):
def connection_made(self, transport):
self.transport = transport
# Here the buffer is intended to be copied, so that the outgoing buffer
# won't be wrongly updated by next read
self.buffer = bytearray(256 * 1024)
def connection_lost(self, exc):
self.transport = None
def get_buffer(self, sizehint):
return self.buffer
def buffer_updated(self, nbytes):
self.transport.write(self.buffer[:nbytes])
async def print_debug(loop):
while True:
print(chr(27) + "[2J") # clear screen
loop.print_debug_info()
await asyncio.sleep(0.5)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--uvloop', default=False, action='store_true')
parser.add_argument('--streams', default=False, action='store_true')
parser.add_argument('--proto', default=False, action='store_true')
parser.add_argument('--addr', default='127.0.0.1:25000', type=str)
parser.add_argument('--print', default=False, action='store_true')
parser.add_argument('--ssl', default=False, action='store_true')
parser.add_argument('--buffered', default=False, action='store_true')
args = parser.parse_args()
if args.uvloop:
import uvloop
loop = uvloop.new_event_loop()
print('using UVLoop')
else:
loop = asyncio.new_event_loop()
print('using asyncio loop')
asyncio.set_event_loop(loop)
loop.set_debug(False)
if args.print:
PRINT = 1
if hasattr(loop, 'print_debug_info'):
loop.create_task(print_debug(loop))
PRINT = 0
unix = False
if args.addr.startswith('file:'):
unix = True
addr = args.addr[5:]
if os.path.exists(addr):
os.remove(addr)
else:
addr = args.addr.split(':')
addr[1] = int(addr[1])
addr = tuple(addr)
print('serving on: {}'.format(addr))
server_context = None
if args.ssl:
print('with SSL')
if hasattr(ssl, 'PROTOCOL_TLS'):
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
else:
server_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
server_context.load_cert_chain(
(pathlib.Path(__file__).parent.parent.parent /
'tests' / 'certs' / 'ssl_cert.pem'),
(pathlib.Path(__file__).parent.parent.parent /
'tests' / 'certs' / 'ssl_key.pem'))
if hasattr(server_context, 'check_hostname'):
server_context.check_hostname = False
server_context.verify_mode = ssl.CERT_NONE
if args.streams:
if args.proto:
print('cannot use --stream and --proto simultaneously')
exit(1)
if args.buffered:
print('cannot use --stream and --buffered simultaneously')
exit(1)
print('using asyncio/streams')
if unix:
coro = asyncio.start_unix_server(echo_client_streams,
addr,
ssl=server_context)
else:
coro = asyncio.start_server(echo_client_streams,
*addr,
ssl=server_context)
srv = loop.run_until_complete(coro)
elif args.proto:
if args.streams:
print('cannot use --stream and --proto simultaneously')
exit(1)
if args.buffered:
print('using buffered protocol')
protocol = EchoBufferedProtocol
else:
print('using simple protocol')
protocol = EchoProtocol
if unix:
coro = loop.create_unix_server(protocol, addr,
ssl=server_context)
else:
coro = loop.create_server(protocol, *addr,
ssl=server_context)
srv = loop.run_until_complete(coro)
else:
if args.ssl:
print('cannot use SSL for loop.sock_* methods')
exit(1)
print('using sock_recv/sock_sendall')
loop.create_task(echo_server(loop, addr, unix))
try:
loop.run_forever()
finally:
if hasattr(loop, 'print_debug_info'):
gc.collect()
print(chr(27) + "[2J")
loop.print_debug_info()
loop.close()
| 1st1/uvloop | examples/bench/echoserver.py | Python | mit | 6,317 |
<?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\MXF;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class EventStart extends AbstractTag
{
protected $Id = '060e2b34.0101.0102.07020103.03030000';
protected $Name = 'EventStart';
protected $FullName = 'MXF::Main';
protected $GroupName = 'MXF';
protected $g0 = 'MXF';
protected $g1 = 'MXF';
protected $g2 = 'Video';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Event Start';
}
| bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/MXF/EventStart.php | PHP | mit | 799 |
<?php
namespace Soda\Cms\Database\Repositories\Contracts;
use Illuminate\Http\Request;
use Soda\Cms\Database\Models\Contracts\ContentInterface;
interface ContentRepositoryInterface extends BaseRepositoryInterface
{
public function findBySlug($slug);
public function listFolder(Request $request, ContentInterface $contentFolder);
public function getBlockTypes();
public function getAvailableBlockTypes(ContentInterface $content);
public function getRoot();
public function getTypes($creatableOnly = false);
public function getShortcuts(ContentInterface $content);
public function getCreatableContentTypes($contentFolderId);
public function createStub($parentId = null, $contentTypeId = null);
}
| sodacms/sodacms | src/Database/Repositories/Contracts/ContentRepositoryInterface.php | PHP | mit | 741 |
/*!
* reveal.js
* http://lab.hakim.se/reveal-js
* MIT licensed
*
* Copyright (C) 2016 Hakim El Hattab, http://hakim.se
*/
(function( root, factory ) {
if( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define( function() {
root.Reveal = factory();
return root.Reveal;
} );
} else if( typeof exports === 'object' ) {
// Node. Does not work with strict CommonJS.
module.exports = factory();
} else {
// Browser globals.
root.Reveal = factory();
}
}( this, function() {
'use strict';
var Reveal;
// The reveal.js version
var VERSION = '3.3.0';
var SLIDES_SELECTOR = '.slides section',
HORIZONTAL_SLIDES_SELECTOR = '.slides>section',
VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section',
HOME_SLIDE_SELECTOR = '.slides>section:first-of-type',
UA = navigator.userAgent,
// Configuration defaults, can be overridden at initialization time
config = {
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions
width: 960,
height: 700,
// Factor of the display size that should remain empty around the content
margin: 0.1,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 1.5,
// Display controls in the bottom right corner
controls: true,
// Display a presentation progress bar
progress: true,
// Display the page number of the current slide
slideNumber: false,
// Push each slide change to the browser history
history: false,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Optional function that blocks keyboard events when retuning false
keyboardCondition: null,
// Enable the slide overview mode
overview: true,
// Vertical centering of slides
center: true,
// Enables touch navigation on devices with touch input
touch: true,
// Loop the presentation
loop: false,
// Change the presentation direction to be RTL
rtl: false,
// Randomizes the order of slides each time the presentation loads
shuffle: false,
// Turns fragments on and off globally
fragments: true,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
// Flags if we should show a help overlay when the questionmark
// key is pressed
help: true,
// Flags if it should be possible to pause the presentation (blackout)
pause: true,
// Flags if speaker notes should be visible to all viewers
showNotes: false,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
// Use this method for navigation when auto-sliding (defaults to navigateNext)
autoSlideMethod: null,
// Enable slide navigation via mouse wheel
mouseWheel: false,
// Apply a 3D roll to links on hover
rollingLinks: false,
// Hides the address bar on mobile devices
hideAddressBar: true,
// Opens links in an iframe preview overlay
previewLinks: false,
// Exposes the reveal.js API through window.postMessage
postMessage: true,
// Dispatches all reveal.js events to the parent window through postMessage
postMessageEvents: false,
// Focuses body when page changes visiblity to ensure keyboard shortcuts work
focusBodyOnPageVisibilityChange: true,
// Transition style
transition: 'fade', // none/fade/slide/convex/concave/zoom
// Transition speed
transitionSpeed: 'default', // default/fast/slow
// Transition style for full page slide backgrounds
backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom
// Parallax background image
parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg"
// Parallax background size
parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px"
// Amount of pixels to move the parallax background per slide step
parallaxBackgroundHorizontal: null,
parallaxBackgroundVertical: null,
// Number of slides away from the current that are visible
viewDistance: 3,
// Script dependencies to load
dependencies: []
},
// Flags if reveal.js is loaded (has dispatched the 'ready' event)
loaded = false,
// Flags if the overview mode is currently active
overview = false,
// Holds the dimensions of our overview slides, including margins
overviewSlideWidth = null,
overviewSlideHeight = null,
// The horizontal and vertical index of the currently active slide
indexh,
indexv,
// The previous and current slide HTML elements
previousSlide,
currentSlide,
previousBackground,
// Slides may hold a data-state attribute which we pick up and apply
// as a class to the body. This list contains the combined state of
// all current slides.
state = [],
// The current scale of the presentation (see width/height config)
scale = 1,
// CSS transform that is currently applied to the slides container,
// split into two groups
slidesTransform = { layout: '', overview: '' },
// Cached references to DOM elements
dom = {},
// Features supported by the browser, see #checkCapabilities()
features = {},
// Client is a mobile device, see #checkCapabilities()
isMobileDevice,
// Client is a desktop Chrome, see #checkCapabilities()
isChrome,
// Throttles mouse wheel navigation
lastMouseWheelStep = 0,
// Delays updates to the URL due to a Chrome thumbnailer bug
writeURLTimeout = 0,
// Flags if the interaction event listeners are bound
eventsAreBound = false,
// The current auto-slide duration
autoSlide = 0,
// Auto slide properties
autoSlidePlayer,
autoSlideTimeout = 0,
autoSlideStartTime = -1,
autoSlidePaused = false,
// Holds information about the currently ongoing touch input
touch = {
startX: 0,
startY: 0,
startSpan: 0,
startCount: 0,
captured: false,
threshold: 40
},
// Holds information about the keyboard shortcuts
keyboardShortcuts = {
'N , SPACE': 'Next slide',
'P': 'Previous slide',
'← , H': 'Navigate left',
'→ , L': 'Navigate right',
'↑ , K': 'Navigate up',
'↓ , J': 'Navigate down',
'Home': 'First slide',
'End': 'Last slide',
'B , .': 'Pause',
'F': 'Fullscreen',
'ESC, O': 'Slide overview'
};
/**
* Starts up the presentation if the client is capable.
*/
function initialize( options ) {
checkCapabilities();
if( !features.transforms2d && !features.transforms3d ) {
document.body.setAttribute( 'class', 'no-transforms' );
// Since JS won't be running any further, we load all lazy
// loading elements upfront
var images = toArray( document.getElementsByTagName( 'img' ) ),
iframes = toArray( document.getElementsByTagName( 'iframe' ) );
var lazyLoadable = images.concat( iframes );
for( var i = 0, len = lazyLoadable.length; i < len; i++ ) {
var element = lazyLoadable[i];
if( element.getAttribute( 'data-src' ) ) {
element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
element.removeAttribute( 'data-src' );
}
}
// If the browser doesn't support core features we won't be
// using JavaScript to control the presentation
return;
}
// Cache references to key DOM elements
dom.wrapper = document.querySelector( '.reveal' );
dom.slides = document.querySelector( '.reveal .slides' );
// Force a layout when the whole page, incl fonts, has loaded
window.addEventListener( 'load', layout, false );
var query = Reveal.getQueryHash();
// Do not accept new dependencies via query config to avoid
// the potential of malicious script injection
if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies'];
// Copy options over to our config object
extend( config, options );
extend( config, query );
// Hide the address bar in mobile browsers
hideAddressBar();
// Loads the dependencies and continues to #start() once done
load();
}
/**
* Inspect the client to see what it's capable of, this
* should only happens once per runtime.
*/
function checkCapabilities() {
isMobileDevice = /(iphone|ipod|ipad|android)/gi.test( UA );
isChrome = /chrome/i.test( UA ) && !/edge/i.test( UA );
var testElement = document.createElement( 'div' );
features.transforms3d = 'WebkitPerspective' in testElement.style ||
'MozPerspective' in testElement.style ||
'msPerspective' in testElement.style ||
'OPerspective' in testElement.style ||
'perspective' in testElement.style;
features.transforms2d = 'WebkitTransform' in testElement.style ||
'MozTransform' in testElement.style ||
'msTransform' in testElement.style ||
'OTransform' in testElement.style ||
'transform' in testElement.style;
features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function';
features.canvas = !!document.createElement( 'canvas' ).getContext;
// Transitions in the overview are disabled in desktop and
// Safari due to lag
features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test( UA );
// Flags if we should use zoom instead of transform to scale
// up slides. Zoom produces crisper results but has a lot of
// xbrowser quirks so we only use it in whitelsited browsers.
features.zoom = 'zoom' in testElement.style && !isMobileDevice &&
( isChrome || /Version\/[\d\.]+.*Safari/.test( UA ) );
}
/**
* Loads the dependencies of reveal.js. Dependencies are
* defined via the configuration option 'dependencies'
* and will be loaded prior to starting/binding reveal.js.
* Some dependencies may have an 'async' flag, if so they
* will load after reveal.js has been started up.
*/
function load() {
var scripts = [],
scriptsAsync = [],
scriptsToPreload = 0;
// Called once synchronous scripts finish loading
function proceed() {
if( scriptsAsync.length ) {
// Load asynchronous scripts
head.js.apply( null, scriptsAsync );
}
start();
}
function loadScript( s ) {
head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], function() {
// Extension may contain callback functions
if( typeof s.callback === 'function' ) {
s.callback.apply( this );
}
if( --scriptsToPreload === 0 ) {
proceed();
}
});
}
for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
var s = config.dependencies[i];
// Load if there's no condition or the condition is truthy
if( !s.condition || s.condition() ) {
if( s.async ) {
scriptsAsync.push( s.src );
}
else {
scripts.push( s.src );
}
loadScript( s );
}
}
if( scripts.length ) {
scriptsToPreload = scripts.length;
// Load synchronous scripts
head.js.apply( null, scripts );
}
else {
proceed();
}
}
/**
* Starts up reveal.js by binding input events and navigating
* to the current URL deeplink if there is one.
*/
function start() {
// Make sure we've got all the DOM elements we need
setupDOM();
// Listen to messages posted to this window
setupPostMessage();
// Prevent the slides from being scrolled out of view
setupScrollPrevention();
// Resets all vertical slides so that only the first is visible
resetVerticalSlides();
// Updates the presentation to match the current configuration values
configure();
// Read the initial hash
readURL();
// Update all backgrounds
updateBackground( true );
// Notify listeners that the presentation is ready but use a 1ms
// timeout to ensure it's not fired synchronously after #initialize()
setTimeout( function() {
// Enable transitions now that we're loaded
dom.slides.classList.remove( 'no-transition' );
loaded = true;
dispatchEvent( 'ready', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}, 1 );
// Special setup and config is required when printing to PDF
if( isPrintingPDF() ) {
removeEventListeners();
// The document needs to have loaded for the PDF layout
// measurements to be accurate
if( document.readyState === 'complete' ) {
setupPDF();
}
else {
window.addEventListener( 'load', setupPDF );
}
}
}
/**
* Finds and stores references to DOM elements which are
* required by the presentation. If a required element is
* not found, it is created.
*/
function setupDOM() {
// Prevent transitions while we're loading
dom.slides.classList.add( 'no-transition' );
// Background element
dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null );
// Progress bar
dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' );
dom.progressbar = dom.progress.querySelector( 'span' );
// Arrow controls
createSingletonNode( dom.wrapper, 'aside', 'controls',
'<button class="navigate-left" aria-label="previous slide"></button>' +
'<button class="navigate-right" aria-label="next slide"></button>' +
'<button class="navigate-up" aria-label="above slide"></button>' +
'<button class="navigate-down" aria-label="below slide"></button>' );
// Slide number
dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' );
// Element containing notes that are visible to the audience
dom.speakerNotes = createSingletonNode( dom.wrapper, 'div', 'speaker-notes', null );
dom.speakerNotes.setAttribute( 'data-prevent-swipe', '' );
// Overlay graphic which is displayed during the paused mode
createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null );
// Cache references to elements
dom.controls = document.querySelector( '.reveal .controls' );
dom.theme = document.querySelector( '#theme' );
dom.wrapper.setAttribute( 'role', 'application' );
// There can be multiple instances of controls throughout the page
dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
dom.statusDiv = createStatusDiv();
}
/**
* Creates a hidden div with role aria-live to announce the
* current slide content. Hide the div off-screen to make it
* available only to Assistive Technologies.
*/
function createStatusDiv() {
var statusDiv = document.getElementById( 'aria-status-div' );
if( !statusDiv ) {
statusDiv = document.createElement( 'div' );
statusDiv.style.position = 'absolute';
statusDiv.style.height = '1px';
statusDiv.style.width = '1px';
statusDiv.style.overflow ='hidden';
statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )';
statusDiv.setAttribute( 'id', 'aria-status-div' );
statusDiv.setAttribute( 'aria-live', 'polite' );
statusDiv.setAttribute( 'aria-atomic','true' );
dom.wrapper.appendChild( statusDiv );
}
return statusDiv;
}
/**
* Configures the presentation for printing to a static
* PDF.
*/
function setupPDF() {
var slideSize = getComputedSlideSize( window.innerWidth, window.innerHeight );
// Dimensions of the PDF pages
var pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ),
pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) );
// Dimensions of slides within the pages
var slideWidth = slideSize.width,
slideHeight = slideSize.height;
// Let the browser know what page size we want to print
injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0;}' );
// Limit the size of certain elements to the dimensions of the slide
injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' );
document.body.classList.add( 'print-pdf' );
document.body.style.width = pageWidth + 'px';
document.body.style.height = pageHeight + 'px';
// Add each slide's index as attributes on itself, we need these
// indices to generate slide numbers below
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
hslide.setAttribute( 'data-index-h', h );
if( hslide.classList.contains( 'stack' ) ) {
toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
vslide.setAttribute( 'data-index-h', h );
vslide.setAttribute( 'data-index-v', v );
} );
}
} );
// Slide and slide background layout
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) === false ) {
// Center the slide inside of the page, giving the slide some margin
var left = ( pageWidth - slideWidth ) / 2,
top = ( pageHeight - slideHeight ) / 2;
var contentHeight = getAbsoluteHeight( slide );
var numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 );
// Center slides vertically
if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) {
top = Math.max( ( pageHeight - contentHeight ) / 2, 0 );
}
// Position the slide inside of the page
slide.style.left = left + 'px';
slide.style.top = top + 'px';
slide.style.width = slideWidth + 'px';
// TODO Backgrounds need to be multiplied when the slide
// stretches over multiple pages
var background = slide.querySelector( '.slide-background' );
if( background ) {
background.style.width = pageWidth + 'px';
background.style.height = ( pageHeight * numberOfPages ) + 'px';
background.style.top = -top + 'px';
background.style.left = -left + 'px';
}
// Inject notes if `showNotes` is enabled
if( config.showNotes ) {
var notes = getSlideNotes( slide );
if( notes ) {
var notesSpacing = 8;
var notesElement = document.createElement( 'div' );
notesElement.classList.add( 'speaker-notes' );
notesElement.classList.add( 'speaker-notes-pdf' );
notesElement.innerHTML = notes;
notesElement.style.left = ( notesSpacing - left ) + 'px';
notesElement.style.bottom = ( notesSpacing - top ) + 'px';
notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px';
slide.appendChild( notesElement );
}
}
// Inject slide numbers if `slideNumbers` are enabled
if( config.slideNumber ) {
var slideNumberH = parseInt( slide.getAttribute( 'data-index-h' ), 10 ) + 1,
slideNumberV = parseInt( slide.getAttribute( 'data-index-v' ), 10 ) + 1;
var numberElement = document.createElement( 'div' );
numberElement.classList.add( 'slide-number' );
numberElement.classList.add( 'slide-number-pdf' );
numberElement.innerHTML = formatSlideNumber( slideNumberH, '.', slideNumberV );
background.appendChild( numberElement );
}
}
} );
// Show all fragments
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' .fragment' ) ).forEach( function( fragment ) {
fragment.classList.add( 'visible' );
} );
}
/**
* This is an unfortunate necessity. Some actions – such as
* an input field being focused in an iframe or using the
* keyboard to expand text selection beyond the bounds of
* a slide – can trigger our content to be pushed out of view.
* This scrolling can not be prevented by hiding overflow in
* CSS (we already do) so we have to resort to repeatedly
* checking if the slides have been offset :(
*/
function setupScrollPrevention() {
setInterval( function() {
if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) {
dom.wrapper.scrollTop = 0;
dom.wrapper.scrollLeft = 0;
}
}, 1000 );
}
/**
* Creates an HTML element and returns a reference to it.
* If the element already exists the existing instance will
* be returned.
*/
function createSingletonNode( container, tagname, classname, innerHTML ) {
// Find all nodes matching the description
var nodes = container.querySelectorAll( '.' + classname );
// Check all matches to find one which is a direct child of
// the specified container
for( var i = 0; i < nodes.length; i++ ) {
var testNode = nodes[i];
if( testNode.parentNode === container ) {
return testNode;
}
}
// If no node was found, create it now
var node = document.createElement( tagname );
node.classList.add( classname );
if( typeof innerHTML === 'string' ) {
node.innerHTML = innerHTML;
}
container.appendChild( node );
return node;
}
/**
* Creates the slide background elements and appends them
* to the background container. One element is created per
* slide no matter if the given slide has visible background.
*/
function createBackgrounds() {
var printMode = isPrintingPDF();
// Clear prior backgrounds
dom.background.innerHTML = '';
dom.background.classList.add( 'no-transition' );
// Iterate over all horizontal slides
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) {
var backgroundStack;
if( printMode ) {
backgroundStack = createBackground( slideh, slideh );
}
else {
backgroundStack = createBackground( slideh, dom.background );
}
// Iterate over all vertical slides
toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) {
if( printMode ) {
createBackground( slidev, slidev );
}
else {
createBackground( slidev, backgroundStack );
}
backgroundStack.classList.add( 'stack' );
} );
} );
// Add parallax background if specified
if( config.parallaxBackgroundImage ) {
dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")';
dom.background.style.backgroundSize = config.parallaxBackgroundSize;
// Make sure the below properties are set on the element - these properties are
// needed for proper transitions to be set on the element via CSS. To remove
// annoying background slide-in effect when the presentation starts, apply
// these properties after short time delay
setTimeout( function() {
dom.wrapper.classList.add( 'has-parallax-background' );
}, 1 );
}
else {
dom.background.style.backgroundImage = '';
dom.wrapper.classList.remove( 'has-parallax-background' );
}
}
/**
* Creates a background for the given slide.
*
* @param {HTMLElement} slide
* @param {HTMLElement} container The element that the background
* should be appended to
*/
function createBackground( slide, container ) {
var data = {
background: slide.getAttribute( 'data-background' ),
backgroundSize: slide.getAttribute( 'data-background-size' ),
backgroundImage: slide.getAttribute( 'data-background-image' ),
backgroundVideo: slide.getAttribute( 'data-background-video' ),
backgroundIframe: slide.getAttribute( 'data-background-iframe' ),
backgroundColor: slide.getAttribute( 'data-background-color' ),
backgroundRepeat: slide.getAttribute( 'data-background-repeat' ),
backgroundPosition: slide.getAttribute( 'data-background-position' ),
backgroundTransition: slide.getAttribute( 'data-background-transition' )
};
var element = document.createElement( 'div' );
// Carry over custom classes from the slide to the background
element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' );
if( data.background ) {
// Auto-wrap image urls in url(...)
if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) {
slide.setAttribute( 'data-background-image', data.background );
}
else {
element.style.background = data.background;
}
}
// Create a hash for this combination of background settings.
// This is used to determine when two slide backgrounds are
// the same.
if( data.background || data.backgroundColor || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) {
element.setAttribute( 'data-background-hash', data.background +
data.backgroundSize +
data.backgroundImage +
data.backgroundVideo +
data.backgroundIframe +
data.backgroundColor +
data.backgroundRepeat +
data.backgroundPosition +
data.backgroundTransition );
}
// Additional and optional background properties
if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize;
if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor;
if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat;
if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition;
if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition );
container.appendChild( element );
// If backgrounds are being recreated, clear old classes
slide.classList.remove( 'has-dark-background' );
slide.classList.remove( 'has-light-background' );
// If this slide has a background color, add a class that
// signals if it is light or dark. If the slide has no background
// color, no class will be set
var computedBackgroundColor = window.getComputedStyle( element ).backgroundColor;
if( computedBackgroundColor ) {
var rgb = colorToRgb( computedBackgroundColor );
// Ignore fully transparent backgrounds. Some browsers return
// rgba(0,0,0,0) when reading the computed background color of
// an element with no background
if( rgb && rgb.a !== 0 ) {
if( colorBrightness( computedBackgroundColor ) < 128 ) {
slide.classList.add( 'has-dark-background' );
}
else {
slide.classList.add( 'has-light-background' );
}
}
}
return element;
}
/**
* Registers a listener to postMessage events, this makes it
* possible to call all reveal.js API methods from another
* window. For example:
*
* revealWindow.postMessage( JSON.stringify({
* method: 'slide',
* args: [ 2 ]
* }), '*' );
*/
function setupPostMessage() {
if( config.postMessage ) {
window.addEventListener( 'message', function ( event ) {
var data = event.data;
// Make sure we're dealing with JSON
if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) {
data = JSON.parse( data );
// Check if the requested method can be found
if( data.method && typeof Reveal[data.method] === 'function' ) {
Reveal[data.method].apply( Reveal, data.args );
}
}
}, false );
}
}
/**
* Applies the configuration settings from the config
* object. May be called multiple times.
*/
function configure( options ) {
var numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length;
dom.wrapper.classList.remove( config.transition );
// New config options may be passed when this method
// is invoked through the API after initialization
if( typeof options === 'object' ) extend( config, options );
// Force linear transition based on browser capabilities
if( features.transforms3d === false ) config.transition = 'linear';
dom.wrapper.classList.add( config.transition );
dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed );
dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition );
dom.controls.style.display = config.controls ? 'block' : 'none';
dom.progress.style.display = config.progress ? 'block' : 'none';
dom.slideNumber.style.display = config.slideNumber && !isPrintingPDF() ? 'block' : 'none';
if( config.shuffle ) {
shuffle();
}
if( config.rtl ) {
dom.wrapper.classList.add( 'rtl' );
}
else {
dom.wrapper.classList.remove( 'rtl' );
}
if( config.center ) {
dom.wrapper.classList.add( 'center' );
}
else {
dom.wrapper.classList.remove( 'center' );
}
// Exit the paused mode if it was configured off
if( config.pause === false ) {
resume();
}
if( config.showNotes ) {
dom.speakerNotes.classList.add( 'visible' );
}
else {
dom.speakerNotes.classList.remove( 'visible' );
}
if( config.mouseWheel ) {
document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
else {
document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
// Rolling 3D links
if( config.rollingLinks ) {
enableRollingLinks();
}
else {
disableRollingLinks();
}
// Iframe link previews
if( config.previewLinks ) {
enablePreviewLinks();
}
else {
disablePreviewLinks();
enablePreviewLinks( '[data-preview-link]' );
}
// Remove existing auto-slide controls
if( autoSlidePlayer ) {
autoSlidePlayer.destroy();
autoSlidePlayer = null;
}
// Generate auto-slide controls if needed
if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) {
autoSlidePlayer = new Playback( dom.wrapper, function() {
return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 );
} );
autoSlidePlayer.on( 'click', onAutoSlidePlayerClick );
autoSlidePaused = false;
}
// When fragments are turned off they should be visible
if( config.fragments === false ) {
toArray( dom.slides.querySelectorAll( '.fragment' ) ).forEach( function( element ) {
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
} );
}
sync();
}
/**
* Binds all event listeners.
*/
function addEventListeners() {
eventsAreBound = true;
window.addEventListener( 'hashchange', onWindowHashChange, false );
window.addEventListener( 'resize', onWindowResize, false );
if( config.touch ) {
dom.wrapper.addEventListener( 'touchstart', onTouchStart, false );
dom.wrapper.addEventListener( 'touchmove', onTouchMove, false );
dom.wrapper.addEventListener( 'touchend', onTouchEnd, false );
// Support pointer-style touch interaction as well
if( window.navigator.pointerEnabled ) {
// IE 11 uses un-prefixed version of pointer events
dom.wrapper.addEventListener( 'pointerdown', onPointerDown, false );
dom.wrapper.addEventListener( 'pointermove', onPointerMove, false );
dom.wrapper.addEventListener( 'pointerup', onPointerUp, false );
}
else if( window.navigator.msPointerEnabled ) {
// IE 10 uses prefixed version of pointer events
dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false );
dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false );
dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false );
}
}
if( config.keyboard ) {
document.addEventListener( 'keydown', onDocumentKeyDown, false );
document.addEventListener( 'keypress', onDocumentKeyPress, false );
}
if( config.progress && dom.progress ) {
dom.progress.addEventListener( 'click', onProgressClicked, false );
}
if( config.focusBodyOnPageVisibilityChange ) {
var visibilityChange;
if( 'hidden' in document ) {
visibilityChange = 'visibilitychange';
}
else if( 'msHidden' in document ) {
visibilityChange = 'msvisibilitychange';
}
else if( 'webkitHidden' in document ) {
visibilityChange = 'webkitvisibilitychange';
}
if( visibilityChange ) {
document.addEventListener( visibilityChange, onPageVisibilityChange, false );
}
}
// Listen to both touch and click events, in case the device
// supports both
var pointerEvents = [ 'touchstart', 'click' ];
// Only support touch for Android, fixes double navigations in
// stock browser
if( UA.match( /android/gi ) ) {
pointerEvents = [ 'touchstart' ];
}
pointerEvents.forEach( function( eventName ) {
dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } );
dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } );
dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } );
dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } );
dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } );
dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } );
} );
}
/**
* Unbinds all event listeners.
*/
function removeEventListeners() {
eventsAreBound = false;
document.removeEventListener( 'keydown', onDocumentKeyDown, false );
document.removeEventListener( 'keypress', onDocumentKeyPress, false );
window.removeEventListener( 'hashchange', onWindowHashChange, false );
window.removeEventListener( 'resize', onWindowResize, false );
dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false );
dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false );
dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false );
// IE11
if( window.navigator.pointerEnabled ) {
dom.wrapper.removeEventListener( 'pointerdown', onPointerDown, false );
dom.wrapper.removeEventListener( 'pointermove', onPointerMove, false );
dom.wrapper.removeEventListener( 'pointerup', onPointerUp, false );
}
// IE10
else if( window.navigator.msPointerEnabled ) {
dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false );
dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false );
dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false );
}
if ( config.progress && dom.progress ) {
dom.progress.removeEventListener( 'click', onProgressClicked, false );
}
[ 'touchstart', 'click' ].forEach( function( eventName ) {
dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } );
dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } );
dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } );
dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } );
dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } );
dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } );
} );
}
/**
* Extend object a with the properties of object b.
* If there's a conflict, object b takes precedence.
*/
function extend( a, b ) {
for( var i in b ) {
a[ i ] = b[ i ];
}
}
/**
* Converts the target object to an array.
*/
function toArray( o ) {
return Array.prototype.slice.call( o );
}
/**
* Utility for deserializing a value.
*/
function deserialize( value ) {
if( typeof value === 'string' ) {
if( value === 'null' ) return null;
else if( value === 'true' ) return true;
else if( value === 'false' ) return false;
else if( value.match( /^\d+$/ ) ) return parseFloat( value );
}
return value;
}
/**
* Measures the distance in pixels between point a
* and point b.
*
* @param {Object} a point with x/y properties
* @param {Object} b point with x/y properties
*/
function distanceBetween( a, b ) {
var dx = a.x - b.x,
dy = a.y - b.y;
return Math.sqrt( dx*dx + dy*dy );
}
/**
* Applies a CSS transform to the target element.
*/
function transformElement( element, transform ) {
element.style.WebkitTransform = transform;
element.style.MozTransform = transform;
element.style.msTransform = transform;
element.style.transform = transform;
}
/**
* Applies CSS transforms to the slides container. The container
* is transformed from two separate sources: layout and the overview
* mode.
*/
function transformSlides( transforms ) {
// Pick up new transforms from arguments
if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout;
if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview;
// Apply the transforms to the slides container
if( slidesTransform.layout ) {
transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview );
}
else {
transformElement( dom.slides, slidesTransform.overview );
}
}
/**
* Injects the given CSS styles into the DOM.
*/
function injectStyleSheet( value ) {
var tag = document.createElement( 'style' );
tag.type = 'text/css';
if( tag.styleSheet ) {
tag.styleSheet.cssText = value;
}
else {
tag.appendChild( document.createTextNode( value ) );
}
document.getElementsByTagName( 'head' )[0].appendChild( tag );
}
/**
* Converts various color input formats to an {r:0,g:0,b:0} object.
*
* @param {String} color The string representation of a color,
* the following formats are supported:
* - #000
* - #000000
* - rgb(0,0,0)
*/
function colorToRgb( color ) {
var hex3 = color.match( /^#([0-9a-f]{3})$/i );
if( hex3 && hex3[1] ) {
hex3 = hex3[1];
return {
r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11,
g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11,
b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11
};
}
var hex6 = color.match( /^#([0-9a-f]{6})$/i );
if( hex6 && hex6[1] ) {
hex6 = hex6[1];
return {
r: parseInt( hex6.substr( 0, 2 ), 16 ),
g: parseInt( hex6.substr( 2, 2 ), 16 ),
b: parseInt( hex6.substr( 4, 2 ), 16 )
};
}
var rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i );
if( rgb ) {
return {
r: parseInt( rgb[1], 10 ),
g: parseInt( rgb[2], 10 ),
b: parseInt( rgb[3], 10 )
};
}
var rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i );
if( rgba ) {
return {
r: parseInt( rgba[1], 10 ),
g: parseInt( rgba[2], 10 ),
b: parseInt( rgba[3], 10 ),
a: parseFloat( rgba[4] )
};
}
return null;
}
/**
* Calculates brightness on a scale of 0-255.
*
* @param color See colorStringToRgb for supported formats.
*/
function colorBrightness( color ) {
if( typeof color === 'string' ) color = colorToRgb( color );
if( color ) {
return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000;
}
return null;
}
/**
* Retrieves the height of the given element by looking
* at the position and height of its immediate children.
*/
function getAbsoluteHeight( element ) {
var height = 0;
if( element ) {
var absoluteChildren = 0;
toArray( element.childNodes ).forEach( function( child ) {
if( typeof child.offsetTop === 'number' && child.style ) {
// Count # of abs children
if( window.getComputedStyle( child ).position === 'absolute' ) {
absoluteChildren += 1;
}
height = Math.max( height, child.offsetTop + child.offsetHeight );
}
} );
// If there are no absolute children, use offsetHeight
if( absoluteChildren === 0 ) {
height = element.offsetHeight;
}
}
return height;
}
/**
* Returns the remaining height within the parent of the
* target element.
*
* remaining height = [ configured parent height ] - [ current parent height ]
*/
function getRemainingHeight( element, height ) {
height = height || 0;
if( element ) {
var newHeight, oldHeight = element.style.height;
// Change the .stretch element height to 0 in order find the height of all
// the other elements
element.style.height = '0px';
newHeight = height - element.parentNode.offsetHeight;
// Restore the old height, just in case
element.style.height = oldHeight + 'px';
return newHeight;
}
return height;
}
/**
* Checks if this instance is being used to print a PDF.
*/
function isPrintingPDF() {
return ( /print-pdf/gi ).test( window.location.search );
}
/**
* Hides the address bar if we're on a mobile device.
*/
function hideAddressBar() {
if( config.hideAddressBar && isMobileDevice ) {
// Events that should trigger the address bar to hide
window.addEventListener( 'load', removeAddressBar, false );
window.addEventListener( 'orientationchange', removeAddressBar, false );
}
}
/**
* Causes the address bar to hide on mobile devices,
* more vertical space ftw.
*/
function removeAddressBar() {
setTimeout( function() {
window.scrollTo( 0, 1 );
}, 10 );
}
/**
* Dispatches an event of the specified type from the
* reveal DOM element.
*/
function dispatchEvent( type, args ) {
var event = document.createEvent( 'HTMLEvents', 1, 2 );
event.initEvent( type, true, true );
extend( event, args );
dom.wrapper.dispatchEvent( event );
// If we're in an iframe, post each reveal.js event to the
// parent window. Used by the notes plugin
if( config.postMessageEvents && window.parent !== window.self ) {
window.parent.postMessage( JSON.stringify({ namespace: 'reveal', eventName: type, state: getState() }), '*' );
}
}
/**
* Wrap all links in 3D goodness.
*/
function enableRollingLinks() {
if( features.transforms3d && !( 'msPerspective' in document.body.style ) ) {
var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a' );
for( var i = 0, len = anchors.length; i < len; i++ ) {
var anchor = anchors[i];
if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) {
var span = document.createElement('span');
span.setAttribute('data-title', anchor.text);
span.innerHTML = anchor.innerHTML;
anchor.classList.add( 'roll' );
anchor.innerHTML = '';
anchor.appendChild(span);
}
}
}
}
/**
* Unwrap all 3D links.
*/
function disableRollingLinks() {
var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a.roll' );
for( var i = 0, len = anchors.length; i < len; i++ ) {
var anchor = anchors[i];
var span = anchor.querySelector( 'span' );
if( span ) {
anchor.classList.remove( 'roll' );
anchor.innerHTML = span.innerHTML;
}
}
}
/**
* Bind preview frame links.
*/
function enablePreviewLinks( selector ) {
var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) );
anchors.forEach( function( element ) {
if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
element.addEventListener( 'click', onPreviewLinkClicked, false );
}
} );
}
/**
* Unbind preview frame links.
*/
function disablePreviewLinks() {
var anchors = toArray( document.querySelectorAll( 'a' ) );
anchors.forEach( function( element ) {
if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
element.removeEventListener( 'click', onPreviewLinkClicked, false );
}
} );
}
/**
* Opens a preview window for the target URL.
*/
function showPreview( url ) {
closeOverlay();
dom.overlay = document.createElement( 'div' );
dom.overlay.classList.add( 'overlay' );
dom.overlay.classList.add( 'overlay-preview' );
dom.wrapper.appendChild( dom.overlay );
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>',
'</header>',
'<div class="spinner"></div>',
'<div class="viewport">',
'<iframe src="'+ url +'"></iframe>',
'</div>'
].join('');
dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) {
dom.overlay.classList.add( 'loaded' );
}, false );
dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) {
closeOverlay();
event.preventDefault();
}, false );
dom.overlay.querySelector( '.external' ).addEventListener( 'click', function( event ) {
closeOverlay();
}, false );
setTimeout( function() {
dom.overlay.classList.add( 'visible' );
}, 1 );
}
/**
* Opens a overlay window with help material.
*/
function showHelp() {
if( config.help ) {
closeOverlay();
dom.overlay = document.createElement( 'div' );
dom.overlay.classList.add( 'overlay' );
dom.overlay.classList.add( 'overlay-help' );
dom.wrapper.appendChild( dom.overlay );
var html = '<p class="title">Keyboard Shortcuts</p><br/>';
html += '<table><th>KEY</th><th>ACTION</th>';
for( var key in keyboardShortcuts ) {
html += '<tr><td>' + key + '</td><td>' + keyboardShortcuts[ key ] + '</td></tr>';
}
html += '</table>';
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'</header>',
'<div class="viewport">',
'<div class="viewport-inner">'+ html +'</div>',
'</div>'
].join('');
dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) {
closeOverlay();
event.preventDefault();
}, false );
setTimeout( function() {
dom.overlay.classList.add( 'visible' );
}, 1 );
}
}
/**
* Closes any currently open overlay.
*/
function closeOverlay() {
if( dom.overlay ) {
dom.overlay.parentNode.removeChild( dom.overlay );
dom.overlay = null;
}
}
/**
* Applies JavaScript-controlled layout rules to the
* presentation.
*/
function layout() {
if( dom.wrapper && !isPrintingPDF() ) {
var size = getComputedSlideSize();
var slidePadding = 20; // TODO Dig this out of DOM
// Layout the contents of the slides
layoutSlideContents( config.width, config.height, slidePadding );
dom.slides.style.width = size.width + 'px';
dom.slides.style.height = size.height + 'px';
// Determine scale of content to fit within available space
scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height );
// Respect max/min scale settings
scale = Math.max( scale, config.minScale );
scale = Math.min( scale, config.maxScale );
// Don't apply any scaling styles if scale is 1
if( scale === 1 ) {
dom.slides.style.zoom = '';
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
else {
// Prefer zoom for scaling up so that content remains crisp.
// Don't use zoom to scale down since that can lead to shifts
// in text layout/line breaks.
if( scale > 1 && features.zoom ) {
dom.slides.style.zoom = scale;
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
// Apply scale transform as a fallback
else {
dom.slides.style.zoom = '';
dom.slides.style.left = '50%';
dom.slides.style.top = '50%';
dom.slides.style.bottom = 'auto';
dom.slides.style.right = 'auto';
transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } );
}
}
// Select all slides, vertical and horizontal
var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) );
for( var i = 0, len = slides.length; i < len; i++ ) {
var slide = slides[ i ];
// Don't bother updating invisible slides
if( slide.style.display === 'none' ) {
continue;
}
if( config.center || slide.classList.contains( 'center' ) ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) ) {
slide.style.top = 0;
}
else {
slide.style.top = Math.max( ( ( size.height - getAbsoluteHeight( slide ) ) / 2 ) - slidePadding, 0 ) + 'px';
}
}
else {
slide.style.top = '';
}
}
updateProgress();
updateParallax();
}
}
/**
* Applies layout logic to the contents of all slides in
* the presentation.
*/
function layoutSlideContents( width, height, padding ) {
// Handle sizing of elements with the 'stretch' class
toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) {
// Determine how much vertical space we can use
var remainingHeight = getRemainingHeight( element, height );
// Consider the aspect ratio of media elements
if( /(img|video)/gi.test( element.nodeName ) ) {
var nw = element.naturalWidth || element.videoWidth,
nh = element.naturalHeight || element.videoHeight;
var es = Math.min( width / nw, remainingHeight / nh );
element.style.width = ( nw * es ) + 'px';
element.style.height = ( nh * es ) + 'px';
}
else {
element.style.width = width + 'px';
element.style.height = remainingHeight + 'px';
}
} );
}
/**
* Calculates the computed pixel size of our slides. These
* values are based on the width and height configuration
* options.
*/
function getComputedSlideSize( presentationWidth, presentationHeight ) {
var size = {
// Slide size
width: config.width,
height: config.height,
// Presentation size
presentationWidth: presentationWidth || dom.wrapper.offsetWidth,
presentationHeight: presentationHeight || dom.wrapper.offsetHeight
};
// Reduce available space by margin
size.presentationWidth -= ( size.presentationWidth * config.margin );
size.presentationHeight -= ( size.presentationHeight * config.margin );
// Slide width may be a percentage of available width
if( typeof size.width === 'string' && /%$/.test( size.width ) ) {
size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth;
}
// Slide height may be a percentage of available height
if( typeof size.height === 'string' && /%$/.test( size.height ) ) {
size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight;
}
return size;
}
/**
* Stores the vertical index of a stack so that the same
* vertical slide can be selected when navigating to and
* from the stack.
*
* @param {HTMLElement} stack The vertical stack element
* @param {int} v Index to memorize
*/
function setPreviousVerticalIndex( stack, v ) {
if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) {
stack.setAttribute( 'data-previous-indexv', v || 0 );
}
}
/**
* Retrieves the vertical index which was stored using
* #setPreviousVerticalIndex() or 0 if no previous index
* exists.
*
* @param {HTMLElement} stack The vertical stack element
*/
function getPreviousVerticalIndex( stack ) {
if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) {
// Prefer manually defined start-indexv
var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv';
return parseInt( stack.getAttribute( attributeName ) || 0, 10 );
}
return 0;
}
/**
* Displays the overview of slides (quick nav) by scaling
* down and arranging all slide elements.
*/
function activateOverview() {
// Only proceed if enabled in config
if( config.overview && !isOverview() ) {
overview = true;
dom.wrapper.classList.add( 'overview' );
dom.wrapper.classList.remove( 'overview-deactivating' );
if( features.overviewTransitions ) {
setTimeout( function() {
dom.wrapper.classList.add( 'overview-animated' );
}, 1 );
}
// Don't auto-slide while in overview mode
cancelAutoSlide();
// Move the backgrounds element into the slide container to
// that the same scaling is applied
dom.slides.appendChild( dom.background );
// Clicking on an overview slide navigates to it
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
if( !slide.classList.contains( 'stack' ) ) {
slide.addEventListener( 'click', onOverviewSlideClicked, true );
}
} );
// Calculate slide sizes
var margin = 70;
var slideSize = getComputedSlideSize();
overviewSlideWidth = slideSize.width + margin;
overviewSlideHeight = slideSize.height + margin;
// Reverse in RTL mode
if( config.rtl ) {
overviewSlideWidth = -overviewSlideWidth;
}
updateSlidesVisibility();
layoutOverview();
updateOverview();
layout();
// Notify observers of the overview showing
dispatchEvent( 'overviewshown', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}
}
/**
* Uses CSS transforms to position all slides in a grid for
* display inside of the overview mode.
*/
function layoutOverview() {
// Layout slides
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
hslide.setAttribute( 'data-index-h', h );
transformElement( hslide, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
if( hslide.classList.contains( 'stack' ) ) {
toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
vslide.setAttribute( 'data-index-h', h );
vslide.setAttribute( 'data-index-v', v );
transformElement( vslide, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
} );
}
} );
// Layout slide backgrounds
toArray( dom.background.childNodes ).forEach( function( hbackground, h ) {
transformElement( hbackground, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
toArray( hbackground.querySelectorAll( '.slide-background' ) ).forEach( function( vbackground, v ) {
transformElement( vbackground, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
} );
} );
}
/**
* Moves the overview viewport to the current slides.
* Called each time the current slide changes.
*/
function updateOverview() {
transformSlides( {
overview: [
'translateX('+ ( -indexh * overviewSlideWidth ) +'px)',
'translateY('+ ( -indexv * overviewSlideHeight ) +'px)',
'translateZ('+ ( window.innerWidth < 400 ? -1000 : -2500 ) +'px)'
].join( ' ' )
} );
}
/**
* Exits the slide overview and enters the currently
* active slide.
*/
function deactivateOverview() {
// Only proceed if enabled in config
if( config.overview ) {
overview = false;
dom.wrapper.classList.remove( 'overview' );
dom.wrapper.classList.remove( 'overview-animated' );
// Temporarily add a class so that transitions can do different things
// depending on whether they are exiting/entering overview, or just
// moving from slide to slide
dom.wrapper.classList.add( 'overview-deactivating' );
setTimeout( function () {
dom.wrapper.classList.remove( 'overview-deactivating' );
}, 1 );
// Move the background element back out
dom.wrapper.appendChild( dom.background );
// Clean up changes made to slides
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
transformElement( slide, '' );
slide.removeEventListener( 'click', onOverviewSlideClicked, true );
} );
// Clean up changes made to backgrounds
toArray( dom.background.querySelectorAll( '.slide-background' ) ).forEach( function( background ) {
transformElement( background, '' );
} );
transformSlides( { overview: '' } );
slide( indexh, indexv );
layout();
cueAutoSlide();
// Notify observers of the overview hiding
dispatchEvent( 'overviewhidden', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}
}
/**
* Toggles the slide overview mode on and off.
*
* @param {Boolean} override Optional flag which overrides the
* toggle logic and forcibly sets the desired state. True means
* overview is open, false means it's closed.
*/
function toggleOverview( override ) {
if( typeof override === 'boolean' ) {
override ? activateOverview() : deactivateOverview();
}
else {
isOverview() ? deactivateOverview() : activateOverview();
}
}
/**
* Checks if the overview is currently active.
*
* @return {Boolean} true if the overview is active,
* false otherwise
*/
function isOverview() {
return overview;
}
/**
* Checks if the current or specified slide is vertical
* (nested within another slide).
*
* @param {HTMLElement} slide [optional] The slide to check
* orientation of
*/
function isVerticalSlide( slide ) {
// Prefer slide argument, otherwise use current slide
slide = slide ? slide : currentSlide;
return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i );
}
/**
* Handling the fullscreen functionality via the fullscreen API
*
* @see http://fullscreen.spec.whatwg.org/
* @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
*/
function enterFullscreen() {
var element = document.body;
// Check which implementation is available
var requestMethod = element.requestFullScreen ||
element.webkitRequestFullscreen ||
element.webkitRequestFullScreen ||
element.mozRequestFullScreen ||
element.msRequestFullscreen;
if( requestMethod ) {
requestMethod.apply( element );
}
}
/**
* Enters the paused mode which fades everything on screen to
* black.
*/
function pause() {
if( config.pause ) {
var wasPaused = dom.wrapper.classList.contains( 'paused' );
cancelAutoSlide();
dom.wrapper.classList.add( 'paused' );
if( wasPaused === false ) {
dispatchEvent( 'paused' );
}
}
}
/**
* Exits from the paused mode.
*/
function resume() {
var wasPaused = dom.wrapper.classList.contains( 'paused' );
dom.wrapper.classList.remove( 'paused' );
cueAutoSlide();
if( wasPaused ) {
dispatchEvent( 'resumed' );
}
}
/**
* Toggles the paused mode on and off.
*/
function togglePause( override ) {
if( typeof override === 'boolean' ) {
override ? pause() : resume();
}
else {
isPaused() ? resume() : pause();
}
}
/**
* Checks if we are currently in the paused mode.
*/
function isPaused() {
return dom.wrapper.classList.contains( 'paused' );
}
/**
* Toggles the auto slide mode on and off.
*
* @param {Boolean} override Optional flag which sets the desired state.
* True means autoplay starts, false means it stops.
*/
function toggleAutoSlide( override ) {
if( typeof override === 'boolean' ) {
override ? resumeAutoSlide() : pauseAutoSlide();
}
else {
autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide();
}
}
/**
* Checks if the auto slide mode is currently on.
*/
function isAutoSliding() {
return !!( autoSlide && !autoSlidePaused );
}
/**
* Steps from the current point in the presentation to the
* slide which matches the specified horizontal and vertical
* indices.
*
* @param {int} h Horizontal index of the target slide
* @param {int} v Vertical index of the target slide
* @param {int} f Optional index of a fragment within the
* target slide to activate
* @param {int} o Optional origin for use in multimaster environments
*/
function slide( h, v, f, o ) {
// Remember where we were at before
previousSlide = currentSlide;
// Query all horizontal slides in the deck
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
// If no vertical index is specified and the upcoming slide is a
// stack, resume at its previous vertical index
if( v === undefined && !isOverview() ) {
v = getPreviousVerticalIndex( horizontalSlides[ h ] );
}
// If we were on a vertical stack, remember what vertical index
// it was on so we can resume at the same position when returning
if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
setPreviousVerticalIndex( previousSlide.parentNode, indexv );
}
// Remember the state before this slide
var stateBefore = state.concat();
// Reset the state array
state.length = 0;
var indexhBefore = indexh || 0,
indexvBefore = indexv || 0;
// Activate and transition to the new slide
indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
// Update the visibility of slides now that the indices have changed
updateSlidesVisibility();
layout();
// Apply the new state
stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
// Check if this state existed on the previous slide. If it
// did, we will avoid adding it repeatedly
for( var j = 0; j < stateBefore.length; j++ ) {
if( stateBefore[j] === state[i] ) {
stateBefore.splice( j, 1 );
continue stateLoop;
}
}
document.documentElement.classList.add( state[i] );
// Dispatch custom event matching the state's name
dispatchEvent( state[i] );
}
// Clean up the remains of the previous state
while( stateBefore.length ) {
document.documentElement.classList.remove( stateBefore.pop() );
}
// Update the overview if it's currently active
if( isOverview() ) {
updateOverview();
}
// Find the current horizontal slide and any possible vertical slides
// within it
var currentHorizontalSlide = horizontalSlides[ indexh ],
currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
// Store references to the previous and current slides
currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
// Show fragment, if specified
if( typeof f !== 'undefined' ) {
navigateFragment( f );
}
// Dispatch an event if the slide changed
var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore );
if( slideChanged ) {
dispatchEvent( 'slidechanged', {
'indexh': indexh,
'indexv': indexv,
'previousSlide': previousSlide,
'currentSlide': currentSlide,
'origin': o
} );
}
else {
// Ensure that the previous slide is never the same as the current
previousSlide = null;
}
// Solves an edge case where the previous slide maintains the
// 'present' class when navigating between adjacent vertical
// stacks
if( previousSlide ) {
previousSlide.classList.remove( 'present' );
previousSlide.setAttribute( 'aria-hidden', 'true' );
// Reset all slides upon navigate to home
// Issue: #285
if ( dom.wrapper.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) {
// Launch async task
setTimeout( function () {
var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i;
for( i in slides ) {
if( slides[i] ) {
// Reset stack
setPreviousVerticalIndex( slides[i], 0 );
}
}
}, 0 );
}
}
// Handle embedded content
if( slideChanged || !previousSlide ) {
stopEmbeddedContent( previousSlide );
startEmbeddedContent( currentSlide );
}
// Announce the current slide contents, for screen readers
dom.statusDiv.textContent = currentSlide.textContent;
updateControls();
updateProgress();
updateBackground();
updateParallax();
updateSlideNumber();
updateNotes();
// Update the URL hash
writeURL();
cueAutoSlide();
}
/**
* Syncs the presentation with the current DOM. Useful
* when new slides or control elements are added or when
* the configuration has changed.
*/
function sync() {
// Subscribe to input
removeEventListeners();
addEventListeners();
// Force a layout to make sure the current config is accounted for
layout();
// Reflect the current autoSlide value
autoSlide = config.autoSlide;
// Start auto-sliding if it's enabled
cueAutoSlide();
// Re-create the slide backgrounds
createBackgrounds();
// Write the current hash to the URL
writeURL();
sortAllFragments();
updateControls();
updateProgress();
updateBackground( true );
updateSlideNumber();
updateSlidesVisibility();
updateNotes();
formatEmbeddedContent();
startEmbeddedContent( currentSlide );
if( isOverview() ) {
layoutOverview();
}
}
/**
* Resets all vertical slides so that only the first
* is visible.
*/
function resetVerticalSlides() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
horizontalSlides.forEach( function( horizontalSlide ) {
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
verticalSlides.forEach( function( verticalSlide, y ) {
if( y > 0 ) {
verticalSlide.classList.remove( 'present' );
verticalSlide.classList.remove( 'past' );
verticalSlide.classList.add( 'future' );
verticalSlide.setAttribute( 'aria-hidden', 'true' );
}
} );
} );
}
/**
* Sorts and formats all of fragments in the
* presentation.
*/
function sortAllFragments() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
horizontalSlides.forEach( function( horizontalSlide ) {
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
verticalSlides.forEach( function( verticalSlide, y ) {
sortFragments( verticalSlide.querySelectorAll( '.fragment' ) );
} );
if( verticalSlides.length === 0 ) sortFragments( horizontalSlide.querySelectorAll( '.fragment' ) );
} );
}
/**
* Randomly shuffles all slides in the deck.
*/
function shuffle() {
var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
slides.forEach( function( slide ) {
// Insert this slide next to another random slide. This may
// cause the slide to insert before itself but that's fine.
dom.slides.insertBefore( slide, slides[ Math.floor( Math.random() * slides.length ) ] );
} );
}
/**
* Updates one dimension of slides by showing the slide
* with the specified index.
*
* @param {String} selector A CSS selector that will fetch
* the group of slides we are working with
* @param {Number} index The index of the slide that should be
* shown
*
* @return {Number} The index of the slide that is now shown,
* might differ from the passed in index if it was out of
* bounds.
*/
function updateSlides( selector, index ) {
// Select all slides and convert the NodeList result to
// an array
var slides = toArray( dom.wrapper.querySelectorAll( selector ) ),
slidesLength = slides.length;
var printMode = isPrintingPDF();
if( slidesLength ) {
// Should the index loop?
if( config.loop ) {
index %= slidesLength;
if( index < 0 ) {
index = slidesLength + index;
}
}
// Enforce max and minimum index bounds
index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
for( var i = 0; i < slidesLength; i++ ) {
var element = slides[i];
var reverse = config.rtl && !isVerticalSlide( element );
element.classList.remove( 'past' );
element.classList.remove( 'present' );
element.classList.remove( 'future' );
// http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute
element.setAttribute( 'hidden', '' );
element.setAttribute( 'aria-hidden', 'true' );
// If this element contains vertical slides
if( element.querySelector( 'section' ) ) {
element.classList.add( 'stack' );
}
// If we're printing static slides, all slides are "present"
if( printMode ) {
element.classList.add( 'present' );
continue;
}
if( i < index ) {
// Any element previous to index is given the 'past' class
element.classList.add( reverse ? 'future' : 'past' );
if( config.fragments ) {
var pastFragments = toArray( element.querySelectorAll( '.fragment' ) );
// Show all fragments on prior slides
while( pastFragments.length ) {
var pastFragment = pastFragments.pop();
pastFragment.classList.add( 'visible' );
pastFragment.classList.remove( 'current-fragment' );
}
}
}
else if( i > index ) {
// Any element subsequent to index is given the 'future' class
element.classList.add( reverse ? 'past' : 'future' );
if( config.fragments ) {
var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) );
// No fragments in future slides should be visible ahead of time
while( futureFragments.length ) {
var futureFragment = futureFragments.pop();
futureFragment.classList.remove( 'visible' );
futureFragment.classList.remove( 'current-fragment' );
}
}
}
}
// Mark the current slide as present
slides[index].classList.add( 'present' );
slides[index].removeAttribute( 'hidden' );
slides[index].removeAttribute( 'aria-hidden' );
// If this slide has a state associated with it, add it
// onto the current state of the deck
var slideState = slides[index].getAttribute( 'data-state' );
if( slideState ) {
state = state.concat( slideState.split( ' ' ) );
}
}
else {
// Since there are no slides we can't be anywhere beyond the
// zeroth index
index = 0;
}
return index;
}
/**
* Optimization method; hide all slides that are far away
* from the present slide.
*/
function updateSlidesVisibility() {
// Select all slides and convert the NodeList result to
// an array
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ),
horizontalSlidesLength = horizontalSlides.length,
distanceX,
distanceY;
if( horizontalSlidesLength && typeof indexh !== 'undefined' ) {
// The number of steps away from the present slide that will
// be visible
var viewDistance = isOverview() ? 10 : config.viewDistance;
// Limit view distance on weaker devices
if( isMobileDevice ) {
viewDistance = isOverview() ? 6 : 2;
}
// All slides need to be visible when exporting to PDF
if( isPrintingPDF() ) {
viewDistance = Number.MAX_VALUE;
}
for( var x = 0; x < horizontalSlidesLength; x++ ) {
var horizontalSlide = horizontalSlides[x];
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ),
verticalSlidesLength = verticalSlides.length;
// Determine how far away this slide is from the present
distanceX = Math.abs( ( indexh || 0 ) - x ) || 0;
// If the presentation is looped, distance should measure
// 1 between the first and last slides
if( config.loop ) {
distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0;
}
// Show the horizontal slide if it's within the view distance
if( distanceX < viewDistance ) {
showSlide( horizontalSlide );
}
else {
hideSlide( horizontalSlide );
}
if( verticalSlidesLength ) {
var oy = getPreviousVerticalIndex( horizontalSlide );
for( var y = 0; y < verticalSlidesLength; y++ ) {
var verticalSlide = verticalSlides[y];
distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy );
if( distanceX + distanceY < viewDistance ) {
showSlide( verticalSlide );
}
else {
hideSlide( verticalSlide );
}
}
}
}
}
}
/**
* Pick up notes from the current slide and display tham
* to the viewer.
*
* @see `showNotes` config value
*/
function updateNotes() {
if( config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF() ) {
dom.speakerNotes.innerHTML = getSlideNotes() || '';
}
}
/**
* Updates the progress bar to reflect the current slide.
*/
function updateProgress() {
// Update progress if enabled
if( config.progress && dom.progressbar ) {
dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px';
}
}
/**
* Updates the slide number div to reflect the current slide.
*
* The following slide number formats are available:
* "h.v": horizontal . vertical slide number (default)
* "h/v": horizontal / vertical slide number
* "c": flattened slide number
* "c/t": flattened slide number / total slides
*/
function updateSlideNumber() {
// Update slide number if enabled
if( config.slideNumber && dom.slideNumber ) {
var value = [];
var format = 'h.v';
// Check if a custom number format is available
if( typeof config.slideNumber === 'string' ) {
format = config.slideNumber;
}
switch( format ) {
case 'c':
value.push( getSlidePastCount() + 1 );
break;
case 'c/t':
value.push( getSlidePastCount() + 1, '/', getTotalSlides() );
break;
case 'h/v':
value.push( indexh + 1 );
if( isVerticalSlide() ) value.push( '/', indexv + 1 );
break;
default:
value.push( indexh + 1 );
if( isVerticalSlide() ) value.push( '.', indexv + 1 );
}
dom.slideNumber.innerHTML = formatSlideNumber( value[0], value[1], value[2] );
}
}
/**
* Applies HTML formatting to a slide number before it's
* written to the DOM.
*/
function formatSlideNumber( a, delimiter, b ) {
if( typeof b === 'number' && !isNaN( b ) ) {
return '<span class="slide-number-a">'+ a +'</span>' +
'<span class="slide-number-delimiter">'+ delimiter +'</span>' +
'<span class="slide-number-b">'+ b +'</span>';
}
else {
return '<span class="slide-number-a">'+ a +'</span>';
}
}
/**
* Updates the state of all control/navigation arrows.
*/
function updateControls() {
var routes = availableRoutes();
var fragments = availableFragments();
// Remove the 'enabled' class from all directions
dom.controlsLeft.concat( dom.controlsRight )
.concat( dom.controlsUp )
.concat( dom.controlsDown )
.concat( dom.controlsPrev )
.concat( dom.controlsNext ).forEach( function( node ) {
node.classList.remove( 'enabled' );
node.classList.remove( 'fragmented' );
} );
// Add the 'enabled' class to the available routes
if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
// Prev/next buttons
if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
// Highlight fragment directions
if( currentSlide ) {
// Always apply fragment decorator to prev/next buttons
if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
// Apply fragment decorators to directional buttons based on
// what slide axis they are in
if( isVerticalSlide( currentSlide ) ) {
if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
}
else {
if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
}
}
}
/**
* Updates the background elements to reflect the current
* slide.
*
* @param {Boolean} includeAll If true, the backgrounds of
* all vertical slides (not just the present) will be updated.
*/
function updateBackground( includeAll ) {
var currentBackground = null;
// Reverse past/future classes when in RTL mode
var horizontalPast = config.rtl ? 'future' : 'past',
horizontalFuture = config.rtl ? 'past' : 'future';
// Update the classes of all backgrounds to match the
// states of their slides (past/present/future)
toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) {
backgroundh.classList.remove( 'past' );
backgroundh.classList.remove( 'present' );
backgroundh.classList.remove( 'future' );
if( h < indexh ) {
backgroundh.classList.add( horizontalPast );
}
else if ( h > indexh ) {
backgroundh.classList.add( horizontalFuture );
}
else {
backgroundh.classList.add( 'present' );
// Store a reference to the current background element
currentBackground = backgroundh;
}
if( includeAll || h === indexh ) {
toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) {
backgroundv.classList.remove( 'past' );
backgroundv.classList.remove( 'present' );
backgroundv.classList.remove( 'future' );
if( v < indexv ) {
backgroundv.classList.add( 'past' );
}
else if ( v > indexv ) {
backgroundv.classList.add( 'future' );
}
else {
backgroundv.classList.add( 'present' );
// Only if this is the present horizontal and vertical slide
if( h === indexh ) currentBackground = backgroundv;
}
} );
}
} );
// Stop any currently playing video background
if( previousBackground ) {
var previousVideo = previousBackground.querySelector( 'video' );
if( previousVideo ) previousVideo.pause();
}
if( currentBackground ) {
// Start video playback
var currentVideo = currentBackground.querySelector( 'video' );
if( currentVideo ) {
var startVideo = function() {
currentVideo.currentTime = 0;
currentVideo.play();
currentVideo.removeEventListener( 'loadeddata', startVideo );
};
if( currentVideo.readyState > 1 ) {
startVideo();
}
else {
currentVideo.addEventListener( 'loadeddata', startVideo );
}
}
var backgroundImageURL = currentBackground.style.backgroundImage || '';
// Restart GIFs (doesn't work in Firefox)
if( /\.gif/i.test( backgroundImageURL ) ) {
currentBackground.style.backgroundImage = '';
window.getComputedStyle( currentBackground ).opacity;
currentBackground.style.backgroundImage = backgroundImageURL;
}
// Don't transition between identical backgrounds. This
// prevents unwanted flicker.
var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null;
var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' );
if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) {
dom.background.classList.add( 'no-transition' );
}
previousBackground = currentBackground;
}
// If there's a background brightness flag for this slide,
// bubble it to the .reveal container
if( currentSlide ) {
[ 'has-light-background', 'has-dark-background' ].forEach( function( classToBubble ) {
if( currentSlide.classList.contains( classToBubble ) ) {
dom.wrapper.classList.add( classToBubble );
}
else {
dom.wrapper.classList.remove( classToBubble );
}
} );
}
// Allow the first background to apply without transition
setTimeout( function() {
dom.background.classList.remove( 'no-transition' );
}, 1 );
}
/**
* Updates the position of the parallax background based
* on the current slide index.
*/
function updateParallax() {
if( config.parallaxBackgroundImage ) {
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
var backgroundSize = dom.background.style.backgroundSize.split( ' ' ),
backgroundWidth, backgroundHeight;
if( backgroundSize.length === 1 ) {
backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 );
}
else {
backgroundWidth = parseInt( backgroundSize[0], 10 );
backgroundHeight = parseInt( backgroundSize[1], 10 );
}
var slideWidth = dom.background.offsetWidth,
horizontalSlideCount = horizontalSlides.length,
horizontalOffsetMultiplier,
horizontalOffset;
if( typeof config.parallaxBackgroundHorizontal === 'number' ) {
horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal;
}
else {
horizontalOffsetMultiplier = horizontalSlideCount > 1 ? ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) : 0;
}
horizontalOffset = horizontalOffsetMultiplier * indexh * -1;
var slideHeight = dom.background.offsetHeight,
verticalSlideCount = verticalSlides.length,
verticalOffsetMultiplier,
verticalOffset;
if( typeof config.parallaxBackgroundVertical === 'number' ) {
verticalOffsetMultiplier = config.parallaxBackgroundVertical;
}
else {
verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 );
}
verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv * 1 : 0;
dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px';
}
}
/**
* Called when the given slide is within the configured view
* distance. Shows the slide element and loads any content
* that is set to load lazily (data-src).
*/
function showSlide( slide ) {
// Show the slide element
slide.style.display = 'block';
// Media elements with data-src attributes
toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src]' ) ).forEach( function( element ) {
element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
element.removeAttribute( 'data-src' );
} );
// Media elements with <source> children
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) {
var sources = 0;
toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) {
source.setAttribute( 'src', source.getAttribute( 'data-src' ) );
source.removeAttribute( 'data-src' );
sources += 1;
} );
// If we rewrote sources for this video/audio element, we need
// to manually tell it to load from its new origin
if( sources > 0 ) {
media.load();
}
} );
// Show the corresponding background element
var indices = getIndices( slide );
var background = getSlideBackground( indices.h, indices.v );
if( background ) {
background.style.display = 'block';
// If the background contains media, load it
if( background.hasAttribute( 'data-loaded' ) === false ) {
background.setAttribute( 'data-loaded', 'true' );
var backgroundImage = slide.getAttribute( 'data-background-image' ),
backgroundVideo = slide.getAttribute( 'data-background-video' ),
backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ),
backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' ),
backgroundIframe = slide.getAttribute( 'data-background-iframe' );
// Images
if( backgroundImage ) {
background.style.backgroundImage = 'url('+ backgroundImage +')';
}
// Videos
else if ( backgroundVideo && !isSpeakerNotes() ) {
var video = document.createElement( 'video' );
if( backgroundVideoLoop ) {
video.setAttribute( 'loop', '' );
}
if( backgroundVideoMuted ) {
video.muted = true;
}
// Support comma separated lists of video sources
backgroundVideo.split( ',' ).forEach( function( source ) {
video.innerHTML += '<source src="'+ source +'">';
} );
background.appendChild( video );
}
// Iframes
else if( backgroundIframe ) {
var iframe = document.createElement( 'iframe' );
iframe.setAttribute( 'src', backgroundIframe );
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.maxHeight = '100%';
iframe.style.maxWidth = '100%';
background.appendChild( iframe );
}
}
}
}
/**
* Called when the given slide is moved outside of the
* configured view distance.
*/
function hideSlide( slide ) {
// Hide the slide element
slide.style.display = 'none';
// Hide the corresponding background element
var indices = getIndices( slide );
var background = getSlideBackground( indices.h, indices.v );
if( background ) {
background.style.display = 'none';
}
}
/**
* Determine what available routes there are for navigation.
*
* @return {Object} containing four booleans: left/right/up/down
*/
function availableRoutes() {
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
var routes = {
left: indexh > 0 || config.loop,
right: indexh < horizontalSlides.length - 1 || config.loop,
up: indexv > 0,
down: indexv < verticalSlides.length - 1
};
// reverse horizontal controls for rtl
if( config.rtl ) {
var left = routes.left;
routes.left = routes.right;
routes.right = left;
}
return routes;
}
/**
* Returns an object describing the available fragment
* directions.
*
* @return {Object} two boolean properties: prev/next
*/
function availableFragments() {
if( currentSlide && config.fragments ) {
var fragments = currentSlide.querySelectorAll( '.fragment' );
var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' );
return {
prev: fragments.length - hiddenFragments.length > 0,
next: !!hiddenFragments.length
};
}
else {
return { prev: false, next: false };
}
}
/**
* Enforces origin-specific format rules for embedded media.
*/
function formatEmbeddedContent() {
var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) {
toArray( dom.slides.querySelectorAll( 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ) ).forEach( function( el ) {
var src = el.getAttribute( sourceAttribute );
if( src && src.indexOf( param ) === -1 ) {
el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param );
}
});
};
// YouTube frames must include "?enablejsapi=1"
_appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' );
_appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' );
// Vimeo frames must include "?api=1"
_appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' );
_appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' );
}
/**
* Start playback of any embedded content inside of
* the targeted slide.
*/
function startEmbeddedContent( slide ) {
if( slide && !isSpeakerNotes() ) {
// Restart GIFs
toArray( slide.querySelectorAll( 'img[src$=".gif"]' ) ).forEach( function( el ) {
// Setting the same unchanged source like this was confirmed
// to work in Chrome, FF & Safari
el.setAttribute( 'src', el.getAttribute( 'src' ) );
} );
// HTML5 media elements
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( el.hasAttribute( 'data-autoplay' ) && typeof el.play === 'function' ) {
el.play();
}
} );
// Normal iframes
toArray( slide.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) {
startEmbeddedIframe( { target: el } );
} );
// Lazy loading iframes
toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) {
el.removeEventListener( 'load', startEmbeddedIframe ); // remove first to avoid dupes
el.addEventListener( 'load', startEmbeddedIframe );
el.setAttribute( 'src', el.getAttribute( 'data-src' ) );
}
} );
}
}
/**
* "Starts" the content of an embedded iframe using the
* postmessage API.
*/
function startEmbeddedIframe( event ) {
var iframe = event.target;
// YouTube postMessage API
if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) {
iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
}
// Vimeo postMessage API
else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) {
iframe.contentWindow.postMessage( '{"method":"play"}', '*' );
}
// Generic postMessage API
else {
iframe.contentWindow.postMessage( 'slide:start', '*' );
}
}
/**
* Stop playback of any embedded content inside of
* the targeted slide.
*/
function stopEmbeddedContent( slide ) {
if( slide && slide.parentNode ) {
// HTML5 media elements
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) {
el.pause();
}
} );
// Generic postMessage API for non-lazy loaded iframes
toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
el.contentWindow.postMessage( 'slide:stop', '*' );
el.removeEventListener( 'load', startEmbeddedIframe );
});
// YouTube postMessage API
toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' );
}
});
// Vimeo postMessage API
toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"method":"pause"}', '*' );
}
});
// Lazy loading iframes
toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
// Only removing the src doesn't actually unload the frame
// in all browsers (Firefox) so we set it to blank first
el.setAttribute( 'src', 'about:blank' );
el.removeAttribute( 'src' );
} );
}
}
/**
* Returns the number of past slides. This can be used as a global
* flattened index for slides.
*/
function getSlidePastCount() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
// The number of past slides
var pastCount = 0;
// Step through all slides and count the past ones
mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
var horizontalSlide = horizontalSlides[i];
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
for( var j = 0; j < verticalSlides.length; j++ ) {
// Stop as soon as we arrive at the present
if( verticalSlides[j].classList.contains( 'present' ) ) {
break mainLoop;
}
pastCount++;
}
// Stop as soon as we arrive at the present
if( horizontalSlide.classList.contains( 'present' ) ) {
break;
}
// Don't count the wrapping section for vertical slides
if( horizontalSlide.classList.contains( 'stack' ) === false ) {
pastCount++;
}
}
return pastCount;
}
/**
* Returns a value ranging from 0-1 that represents
* how far into the presentation we have navigated.
*/
function getProgress() {
// The number of past and total slides
var totalCount = getTotalSlides();
var pastCount = getSlidePastCount();
if( currentSlide ) {
var allFragments = currentSlide.querySelectorAll( '.fragment' );
// If there are fragments in the current slide those should be
// accounted for in the progress.
if( allFragments.length > 0 ) {
var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' );
// This value represents how big a portion of the slide progress
// that is made up by its fragments (0-1)
var fragmentWeight = 0.9;
// Add fragment progress to the past slide count
pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight;
}
}
return pastCount / ( totalCount - 1 );
}
/**
* Checks if this presentation is running inside of the
* speaker notes window.
*/
function isSpeakerNotes() {
return !!window.location.search.match( /receiver/gi );
}
/**
* Reads the current URL (hash) and navigates accordingly.
*/
function readURL() {
var hash = window.location.hash;
// Attempt to parse the hash as either an index or name
var bits = hash.slice( 2 ).split( '/' ),
name = hash.replace( /#|\//gi, '' );
// If the first bit is invalid and there is a name we can
// assume that this is a named link
if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
var element;
// Ensure the named link is a valid HTML ID attribute
if( /^[a-zA-Z][\w:.-]*$/.test( name ) ) {
// Find the slide with the specified ID
element = document.getElementById( name );
}
if( element ) {
// Find the position of the named slide and navigate to it
var indices = Reveal.getIndices( element );
slide( indices.h, indices.v );
}
// If the slide doesn't exist, navigate to the current slide
else {
slide( indexh || 0, indexv || 0 );
}
}
else {
// Read the index components of the hash
var h = parseInt( bits[0], 10 ) || 0,
v = parseInt( bits[1], 10 ) || 0;
if( h !== indexh || v !== indexv ) {
slide( h, v );
}
}
}
/**
* Updates the page URL (hash) to reflect the current
* state.
*
* @param {Number} delay The time in ms to wait before
* writing the hash
*/
function writeURL( delay ) {
if( config.history ) {
// Make sure there's never more than one timeout running
clearTimeout( writeURLTimeout );
// If a delay is specified, timeout this call
if( typeof delay === 'number' ) {
writeURLTimeout = setTimeout( writeURL, delay );
}
else if( currentSlide ) {
var url = '/';
// Attempt to create a named link based on the slide's ID
var id = currentSlide.getAttribute( 'id' );
if( id ) {
id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' );
}
// If the current slide has an ID, use that as a named link
if( typeof id === 'string' && id.length ) {
url = '/' + id;
}
// Otherwise use the /h/v index
else {
if( indexh > 0 || indexv > 0 ) url += indexh;
if( indexv > 0 ) url += '/' + indexv;
}
window.location.hash = url;
}
}
}
/**
* Retrieves the h/v location of the current, or specified,
* slide.
*
* @param {HTMLElement} slide If specified, the returned
* index will be for this slide rather than the currently
* active one
*
* @return {Object} { h: <int>, v: <int>, f: <int> }
*/
function getIndices( slide ) {
// By default, return the current indices
var h = indexh,
v = indexv,
f;
// If a slide is specified, return the indices of that slide
if( slide ) {
var isVertical = isVerticalSlide( slide );
var slideh = isVertical ? slide.parentNode : slide;
// Select all horizontal slides
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
// Now that we know which the horizontal slide is, get its index
h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
// Assume we're not vertical
v = undefined;
// If this is a vertical slide, grab the vertical index
if( isVertical ) {
v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
}
}
if( !slide && currentSlide ) {
var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0;
if( hasFragments ) {
var currentFragment = currentSlide.querySelector( '.current-fragment' );
if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) {
f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 );
}
else {
f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1;
}
}
}
return { h: h, v: v, f: f };
}
/**
* Retrieves the total number of slides in this presentation.
*/
function getTotalSlides() {
return dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
}
/**
* Returns the slide element matching the specified index.
*/
function getSlide( x, y ) {
var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
if( verticalSlides && verticalSlides.length && typeof y === 'number' ) {
return verticalSlides ? verticalSlides[ y ] : undefined;
}
return horizontalSlide;
}
/**
* Returns the background element for the given slide.
* All slides, even the ones with no background properties
* defined, have a background element so as long as the
* index is valid an element will be returned.
*/
function getSlideBackground( x, y ) {
// When printing to PDF the slide backgrounds are nested
// inside of the slides
if( isPrintingPDF() ) {
var slide = getSlide( x, y );
if( slide ) {
var background = slide.querySelector( '.slide-background' );
if( background && background.parentNode === slide ) {
return background;
}
}
return undefined;
}
var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[ x ];
var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' );
if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) {
return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined;
}
return horizontalBackground;
}
/**
* Retrieves the speaker notes from a slide. Notes can be
* defined in two ways:
* 1. As a data-notes attribute on the slide <section>
* 2. As an <aside class="notes"> inside of the slide
*/
function getSlideNotes( slide ) {
// Default to the current slide
slide = slide || currentSlide;
// Notes can be specified via the data-notes attribute...
if( slide.hasAttribute( 'data-notes' ) ) {
return slide.getAttribute( 'data-notes' );
}
// ... or using an <aside class="notes"> element
var notesElement = slide.querySelector( 'aside.notes' );
if( notesElement ) {
return notesElement.innerHTML;
}
return null;
}
/**
* Retrieves the current state of the presentation as
* an object. This state can then be restored at any
* time.
*/
function getState() {
var indices = getIndices();
return {
indexh: indices.h,
indexv: indices.v,
indexf: indices.f,
paused: isPaused(),
overview: isOverview()
};
}
/**
* Restores the presentation to the given state.
*
* @param {Object} state As generated by getState()
*/
function setState( state ) {
if( typeof state === 'object' ) {
slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) );
var pausedFlag = deserialize( state.paused ),
overviewFlag = deserialize( state.overview );
if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) {
togglePause( pausedFlag );
}
if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) {
toggleOverview( overviewFlag );
}
}
}
/**
* Return a sorted fragments list, ordered by an increasing
* "data-fragment-index" attribute.
*
* Fragments will be revealed in the order that they are returned by
* this function, so you can use the index attributes to control the
* order of fragment appearance.
*
* To maintain a sensible default fragment order, fragments are presumed
* to be passed in document order. This function adds a "fragment-index"
* attribute to each node if such an attribute is not already present,
* and sets that attribute to an integer value which is the position of
* the fragment within the fragments list.
*/
function sortFragments( fragments ) {
fragments = toArray( fragments );
var ordered = [],
unordered = [],
sorted = [];
// Group ordered and unordered elements
fragments.forEach( function( fragment, i ) {
if( fragment.hasAttribute( 'data-fragment-index' ) ) {
var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 );
if( !ordered[index] ) {
ordered[index] = [];
}
ordered[index].push( fragment );
}
else {
unordered.push( [ fragment ] );
}
} );
// Append fragments without explicit indices in their
// DOM order
ordered = ordered.concat( unordered );
// Manually count the index up per group to ensure there
// are no gaps
var index = 0;
// Push all fragments in their sorted order to an array,
// this flattens the groups
ordered.forEach( function( group ) {
group.forEach( function( fragment ) {
sorted.push( fragment );
fragment.setAttribute( 'data-fragment-index', index );
} );
index ++;
} );
return sorted;
}
/**
* Navigate to the specified slide fragment.
*
* @param {Number} index The index of the fragment that
* should be shown, -1 means all are invisible
* @param {Number} offset Integer offset to apply to the
* fragment index
*
* @return {Boolean} true if a change was made in any
* fragments visibility as part of this call
*/
function navigateFragment( index, offset ) {
if( currentSlide && config.fragments ) {
var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
if( fragments.length ) {
// If no index is specified, find the current
if( typeof index !== 'number' ) {
var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop();
if( lastVisibleFragment ) {
index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 );
}
else {
index = -1;
}
}
// If an offset is specified, apply it to the index
if( typeof offset === 'number' ) {
index += offset;
}
var fragmentsShown = [],
fragmentsHidden = [];
toArray( fragments ).forEach( function( element, i ) {
if( element.hasAttribute( 'data-fragment-index' ) ) {
i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 );
}
// Visible fragments
if( i <= index ) {
if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element );
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
// Announce the fragments one by one to the Screen Reader
dom.statusDiv.textContent = element.textContent;
if( i === index ) {
element.classList.add( 'current-fragment' );
}
}
// Hidden fragments
else {
if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element );
element.classList.remove( 'visible' );
element.classList.remove( 'current-fragment' );
}
} );
if( fragmentsHidden.length ) {
dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } );
}
if( fragmentsShown.length ) {
dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } );
}
updateControls();
updateProgress();
return !!( fragmentsShown.length || fragmentsHidden.length );
}
}
return false;
}
/**
* Navigate to the next slide fragment.
*
* @return {Boolean} true if there was a next fragment,
* false otherwise
*/
function nextFragment() {
return navigateFragment( null, 1 );
}
/**
* Navigate to the previous slide fragment.
*
* @return {Boolean} true if there was a previous fragment,
* false otherwise
*/
function previousFragment() {
return navigateFragment( null, -1 );
}
/**
* Cues a new automated slide if enabled in the config.
*/
function cueAutoSlide() {
cancelAutoSlide();
if( currentSlide ) {
var currentFragment = currentSlide.querySelector( '.current-fragment' );
var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null;
var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null;
var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' );
// Pick value in the following priority order:
// 1. Current fragment's data-autoslide
// 2. Current slide's data-autoslide
// 3. Parent slide's data-autoslide
// 4. Global autoSlide setting
if( fragmentAutoSlide ) {
autoSlide = parseInt( fragmentAutoSlide, 10 );
}
else if( slideAutoSlide ) {
autoSlide = parseInt( slideAutoSlide, 10 );
}
else if( parentAutoSlide ) {
autoSlide = parseInt( parentAutoSlide, 10 );
}
else {
autoSlide = config.autoSlide;
}
// If there are media elements with data-autoplay,
// automatically set the autoSlide duration to the
// length of that media. Not applicable if the slide
// is divided up into fragments.
if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) {
toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( el.hasAttribute( 'data-autoplay' ) ) {
if( autoSlide && el.duration * 1000 > autoSlide ) {
autoSlide = ( el.duration * 1000 ) + 1000;
}
}
} );
}
// Cue the next auto-slide if:
// - There is an autoSlide value
// - Auto-sliding isn't paused by the user
// - The presentation isn't paused
// - The overview isn't active
// - The presentation isn't over
if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || availableFragments().next || config.loop === true ) ) {
autoSlideTimeout = setTimeout( function() {
typeof config.autoSlideMethod === 'function' ? config.autoSlideMethod() : navigateNext();
cueAutoSlide();
}, autoSlide );
autoSlideStartTime = Date.now();
}
if( autoSlidePlayer ) {
autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 );
}
}
}
/**
* Cancels any ongoing request to auto-slide.
*/
function cancelAutoSlide() {
clearTimeout( autoSlideTimeout );
autoSlideTimeout = -1;
}
function pauseAutoSlide() {
if( autoSlide && !autoSlidePaused ) {
autoSlidePaused = true;
dispatchEvent( 'autoslidepaused' );
clearTimeout( autoSlideTimeout );
if( autoSlidePlayer ) {
autoSlidePlayer.setPlaying( false );
}
}
}
function resumeAutoSlide() {
if( autoSlide && autoSlidePaused ) {
autoSlidePaused = false;
dispatchEvent( 'autoslideresumed' );
cueAutoSlide();
}
}
function navigateLeft() {
// Reverse for RTL
if( config.rtl ) {
if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) {
slide( indexh + 1 );
}
}
// Normal navigation
else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) {
slide( indexh - 1 );
}
}
function navigateRight() {
// Reverse for RTL
if( config.rtl ) {
if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) {
slide( indexh - 1 );
}
}
// Normal navigation
else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) {
slide( indexh + 1 );
}
}
function navigateUp() {
// Prioritize hiding fragments
if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) {
slide( indexh, indexv - 1 );
}
}
function navigateDown() {
// Prioritize revealing fragments
if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) {
slide( indexh, indexv + 1 );
}
}
/**
* Navigates backwards, prioritized in the following order:
* 1) Previous fragment
* 2) Previous vertical slide
* 3) Previous horizontal slide
*/
function navigatePrev() {
// Prioritize revealing fragments
if( previousFragment() === false ) {
if( availableRoutes().up ) {
navigateUp();
}
else {
// Fetch the previous horizontal slide, if there is one
var previousSlide;
if( config.rtl ) {
previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.future' ) ).pop();
}
else {
previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.past' ) ).pop();
}
if( previousSlide ) {
var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;
var h = indexh - 1;
slide( h, v );
}
}
}
}
/**
* The reverse of #navigatePrev().
*/
function navigateNext() {
// Prioritize revealing fragments
if( nextFragment() === false ) {
if( availableRoutes().down ) {
navigateDown();
}
else if( config.rtl ) {
navigateLeft();
}
else {
navigateRight();
}
}
}
/**
* Checks if the target element prevents the triggering of
* swipe navigation.
*/
function isSwipePrevented( target ) {
while( target && typeof target.hasAttribute === 'function' ) {
if( target.hasAttribute( 'data-prevent-swipe' ) ) return true;
target = target.parentNode;
}
return false;
}
// --------------------------------------------------------------------//
// ----------------------------- EVENTS -------------------------------//
// --------------------------------------------------------------------//
/**
* Called by all event handlers that are based on user
* input.
*/
function onUserInput( event ) {
if( config.autoSlideStoppable ) {
pauseAutoSlide();
}
}
/**
* Handler for the document level 'keypress' event.
*/
function onDocumentKeyPress( event ) {
// Check if the pressed key is question mark
if( event.shiftKey && event.charCode === 63 ) {
if( dom.overlay ) {
closeOverlay();
}
else {
showHelp( true );
}
}
}
/**
* Handler for the document level 'keydown' event.
*/
function onDocumentKeyDown( event ) {
// If there's a condition specified and it returns false,
// ignore this event
if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) {
return true;
}
// Remember if auto-sliding was paused so we can toggle it
var autoSlideWasPaused = autoSlidePaused;
onUserInput( event );
// Check if there's a focused element that could be using
// the keyboard
var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit';
var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName );
// Disregard the event if there's a focused element or a
// keyboard modifier key is present
if( activeElementIsCE || activeElementIsInput || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
// While paused only allow resume keyboard events; 'b', '.''
var resumeKeyCodes = [66,190,191];
var key;
// Custom key bindings for togglePause should be able to resume
if( typeof config.keyboard === 'object' ) {
for( key in config.keyboard ) {
if( config.keyboard[key] === 'togglePause' ) {
resumeKeyCodes.push( parseInt( key, 10 ) );
}
}
}
if( isPaused() && resumeKeyCodes.indexOf( event.keyCode ) === -1 ) {
return false;
}
var triggered = false;
// 1. User defined key bindings
if( typeof config.keyboard === 'object' ) {
for( key in config.keyboard ) {
// Check if this binding matches the pressed key
if( parseInt( key, 10 ) === event.keyCode ) {
var value = config.keyboard[ key ];
// Callback function
if( typeof value === 'function' ) {
value.apply( null, [ event ] );
}
// String shortcuts to reveal.js API
else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) {
Reveal[ value ].call();
}
triggered = true;
}
}
}
// 2. System defined key bindings
if( triggered === false ) {
// Assume true and try to prove false
triggered = true;
switch( event.keyCode ) {
// p, page up
case 80: case 33: navigatePrev(); break;
// n, page down
case 78: case 34: navigateNext(); break;
// h, left
case 72: case 37: navigateLeft(); break;
// l, right
case 76: case 39: navigateRight(); break;
// k, up
case 75: case 38: navigateUp(); break;
// j, down
case 74: case 40: navigateDown(); break;
// home
case 36: slide( 0 ); break;
// end
case 35: slide( Number.MAX_VALUE ); break;
// space
case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break;
// return
case 13: isOverview() ? deactivateOverview() : triggered = false; break;
// two-spot, semicolon, b, period, Logitech presenter tools "black screen" button
case 58: case 59: case 66: case 190: case 191: togglePause(); break;
// f
case 70: enterFullscreen(); break;
// a
case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break;
default:
triggered = false;
}
}
// If the input resulted in a triggered action we should prevent
// the browsers default behavior
if( triggered ) {
event.preventDefault && event.preventDefault();
}
// ESC or O key
else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) {
if( dom.overlay ) {
closeOverlay();
}
else {
toggleOverview();
}
event.preventDefault && event.preventDefault();
}
// If auto-sliding is enabled we need to cue up
// another timeout
cueAutoSlide();
}
/**
* Handler for the 'touchstart' event, enables support for
* swipe and pinch gestures.
*/
function onTouchStart( event ) {
if( isSwipePrevented( event.target ) ) return true;
touch.startX = event.touches[0].clientX;
touch.startY = event.touches[0].clientY;
touch.startCount = event.touches.length;
// If there's two touches we need to memorize the distance
// between those two points to detect pinching
if( event.touches.length === 2 && config.overview ) {
touch.startSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
}
}
/**
* Handler for the 'touchmove' event.
*/
function onTouchMove( event ) {
if( isSwipePrevented( event.target ) ) return true;
// Each touch should only trigger one action
if( !touch.captured ) {
onUserInput( event );
var currentX = event.touches[0].clientX;
var currentY = event.touches[0].clientY;
// If the touch started with two points and still has
// two active touches; test for the pinch gesture
if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
// The current distance in pixels between the two touch points
var currentSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
// If the span is larger than the desire amount we've got
// ourselves a pinch
if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
touch.captured = true;
if( currentSpan < touch.startSpan ) {
activateOverview();
}
else {
deactivateOverview();
}
}
event.preventDefault();
}
// There was only one touch point, look for a swipe
else if( event.touches.length === 1 && touch.startCount !== 2 ) {
var deltaX = currentX - touch.startX,
deltaY = currentY - touch.startY;
if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.captured = true;
navigateLeft();
}
else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.captured = true;
navigateRight();
}
else if( deltaY > touch.threshold ) {
touch.captured = true;
navigateUp();
}
else if( deltaY < -touch.threshold ) {
touch.captured = true;
navigateDown();
}
// If we're embedded, only block touch events if they have
// triggered an action
if( config.embedded ) {
if( touch.captured || isVerticalSlide( currentSlide ) ) {
event.preventDefault();
}
}
// Not embedded? Block them all to avoid needless tossing
// around of the viewport in iOS
else {
event.preventDefault();
}
}
}
// There's a bug with swiping on some Android devices unless
// the default action is always prevented
else if( UA.match( /android/gi ) ) {
event.preventDefault();
}
}
/**
* Handler for the 'touchend' event.
*/
function onTouchEnd( event ) {
touch.captured = false;
}
/**
* Convert pointer down to touch start.
*/
function onPointerDown( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchStart( event );
}
}
/**
* Convert pointer move to touch move.
*/
function onPointerMove( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchMove( event );
}
}
/**
* Convert pointer up to touch end.
*/
function onPointerUp( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchEnd( event );
}
}
/**
* Handles mouse wheel scrolling, throttled to avoid skipping
* multiple slides.
*/
function onDocumentMouseScroll( event ) {
if( Date.now() - lastMouseWheelStep > 600 ) {
lastMouseWheelStep = Date.now();
var delta = event.detail || -event.wheelDelta;
if( delta > 0 ) {
navigateNext();
}
else {
navigatePrev();
}
}
}
/**
* Clicking on the progress bar results in a navigation to the
* closest approximate horizontal slide using this equation:
*
* ( clickX / presentationWidth ) * numberOfSlides
*/
function onProgressClicked( event ) {
onUserInput( event );
event.preventDefault();
var slidesTotal = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
if( config.rtl ) {
slideIndex = slidesTotal - slideIndex;
}
slide( slideIndex );
}
/**
* Event handler for navigation control buttons.
*/
function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); }
function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); }
function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); }
function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); }
function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); }
function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); }
/**
* Handler for the window level 'hashchange' event.
*/
function onWindowHashChange( event ) {
readURL();
}
/**
* Handler for the window level 'resize' event.
*/
function onWindowResize( event ) {
layout();
}
/**
* Handle for the window level 'visibilitychange' event.
*/
function onPageVisibilityChange( event ) {
var isHidden = document.webkitHidden ||
document.msHidden ||
document.hidden;
// If, after clicking a link or similar and we're coming back,
// focus the document.body to ensure we can use keyboard shortcuts
if( isHidden === false && document.activeElement !== document.body ) {
// Not all elements support .blur() - SVGs among them.
if( typeof document.activeElement.blur === 'function' ) {
document.activeElement.blur();
}
document.body.focus();
}
}
/**
* Invoked when a slide is and we're in the overview.
*/
function onOverviewSlideClicked( event ) {
// TODO There's a bug here where the event listeners are not
// removed after deactivating the overview.
if( eventsAreBound && isOverview() ) {
event.preventDefault();
var element = event.target;
while( element && !element.nodeName.match( /section/gi ) ) {
element = element.parentNode;
}
if( element && !element.classList.contains( 'disabled' ) ) {
deactivateOverview();
if( element.nodeName.match( /section/gi ) ) {
var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
slide( h, v );
}
}
}
}
/**
* Handles clicks on links that are set to preview in the
* iframe overlay.
*/
function onPreviewLinkClicked( event ) {
if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) {
var url = event.currentTarget.getAttribute( 'href' );
if( url ) {
showPreview( url );
event.preventDefault();
}
}
}
/**
* Handles click on the auto-sliding controls element.
*/
function onAutoSlidePlayerClick( event ) {
// Replay
if( Reveal.isLastSlide() && config.loop === false ) {
slide( 0, 0 );
resumeAutoSlide();
}
// Resume
else if( autoSlidePaused ) {
resumeAutoSlide();
}
// Pause
else {
pauseAutoSlide();
}
}
// --------------------------------------------------------------------//
// ------------------------ PLAYBACK COMPONENT ------------------------//
// --------------------------------------------------------------------//
/**
* Constructor for the playback component, which displays
* play/pause/progress controls.
*
* @param {HTMLElement} container The component will append
* itself to this
* @param {Function} progressCheck A method which will be
* called frequently to get the current progress on a range
* of 0-1
*/
function Playback( container, progressCheck ) {
// Cosmetics
this.diameter = 100;
this.diameter2 = this.diameter/2;
this.thickness = 6;
// Flags if we are currently playing
this.playing = false;
// Current progress on a 0-1 range
this.progress = 0;
// Used to loop the animation smoothly
this.progressOffset = 1;
this.container = container;
this.progressCheck = progressCheck;
this.canvas = document.createElement( 'canvas' );
this.canvas.className = 'playback';
this.canvas.width = this.diameter;
this.canvas.height = this.diameter;
this.canvas.style.width = this.diameter2 + 'px';
this.canvas.style.height = this.diameter2 + 'px';
this.context = this.canvas.getContext( '2d' );
this.container.appendChild( this.canvas );
this.render();
}
Playback.prototype.setPlaying = function( value ) {
var wasPlaying = this.playing;
this.playing = value;
// Start repainting if we weren't already
if( !wasPlaying && this.playing ) {
this.animate();
}
else {
this.render();
}
};
Playback.prototype.animate = function() {
var progressBefore = this.progress;
this.progress = this.progressCheck();
// When we loop, offset the progress so that it eases
// smoothly rather than immediately resetting
if( progressBefore > 0.8 && this.progress < 0.2 ) {
this.progressOffset = this.progress;
}
this.render();
if( this.playing ) {
features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) );
}
};
/**
* Renders the current progress and playback state.
*/
Playback.prototype.render = function() {
var progress = this.playing ? this.progress : 0,
radius = ( this.diameter2 ) - this.thickness,
x = this.diameter2,
y = this.diameter2,
iconSize = 28;
// Ease towards 1
this.progressOffset += ( 1 - this.progressOffset ) * 0.1;
var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) );
var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) );
this.context.save();
this.context.clearRect( 0, 0, this.diameter, this.diameter );
// Solid background color
this.context.beginPath();
this.context.arc( x, y, radius + 4, 0, Math.PI * 2, false );
this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )';
this.context.fill();
// Draw progress track
this.context.beginPath();
this.context.arc( x, y, radius, 0, Math.PI * 2, false );
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#666';
this.context.stroke();
if( this.playing ) {
// Draw progress on top of track
this.context.beginPath();
this.context.arc( x, y, radius, startAngle, endAngle, false );
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#fff';
this.context.stroke();
}
this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) );
// Draw play/pause icons
if( this.playing ) {
this.context.fillStyle = '#fff';
this.context.fillRect( 0, 0, iconSize / 2 - 4, iconSize );
this.context.fillRect( iconSize / 2 + 4, 0, iconSize / 2 - 4, iconSize );
}
else {
this.context.beginPath();
this.context.translate( 4, 0 );
this.context.moveTo( 0, 0 );
this.context.lineTo( iconSize - 4, iconSize / 2 );
this.context.lineTo( 0, iconSize );
this.context.fillStyle = '#fff';
this.context.fill();
}
this.context.restore();
};
Playback.prototype.on = function( type, listener ) {
this.canvas.addEventListener( type, listener, false );
};
Playback.prototype.off = function( type, listener ) {
this.canvas.removeEventListener( type, listener, false );
};
Playback.prototype.destroy = function() {
this.playing = false;
if( this.canvas.parentNode ) {
this.container.removeChild( this.canvas );
}
};
// --------------------------------------------------------------------//
// ------------------------------- API --------------------------------//
// --------------------------------------------------------------------//
Reveal = {
VERSION: VERSION,
initialize: initialize,
configure: configure,
sync: sync,
// Navigation methods
slide: slide,
left: navigateLeft,
right: navigateRight,
up: navigateUp,
down: navigateDown,
prev: navigatePrev,
next: navigateNext,
// Fragment methods
navigateFragment: navigateFragment,
prevFragment: previousFragment,
nextFragment: nextFragment,
// Deprecated aliases
navigateTo: slide,
navigateLeft: navigateLeft,
navigateRight: navigateRight,
navigateUp: navigateUp,
navigateDown: navigateDown,
navigatePrev: navigatePrev,
navigateNext: navigateNext,
// Forces an update in slide layout
layout: layout,
// Randomizes the order of slides
shuffle: shuffle,
// Returns an object with the available routes as booleans (left/right/top/bottom)
availableRoutes: availableRoutes,
// Returns an object with the available fragments as booleans (prev/next)
availableFragments: availableFragments,
// Toggles the overview mode on/off
toggleOverview: toggleOverview,
// Toggles the "black screen" mode on/off
togglePause: togglePause,
// Toggles the auto slide mode on/off
toggleAutoSlide: toggleAutoSlide,
// State checks
isOverview: isOverview,
isPaused: isPaused,
isAutoSliding: isAutoSliding,
// Adds or removes all internal event listeners (such as keyboard)
addEventListeners: addEventListeners,
removeEventListeners: removeEventListeners,
// Facility for persisting and restoring the presentation state
getState: getState,
setState: setState,
// Presentation progress on range of 0-1
getProgress: getProgress,
// Returns the indices of the current, or specified, slide
getIndices: getIndices,
getTotalSlides: getTotalSlides,
// Returns the slide element at the specified index
getSlide: getSlide,
// Returns the slide background element at the specified index
getSlideBackground: getSlideBackground,
// Returns the speaker notes string for a slide, or null
getSlideNotes: getSlideNotes,
// Returns the previous slide element, may be null
getPreviousSlide: function() {
return previousSlide;
},
// Returns the current slide element
getCurrentSlide: function() {
return currentSlide;
},
// Returns the current scale of the presentation content
getScale: function() {
return scale;
},
// Returns the current configuration object
getConfig: function() {
return config;
},
// Helper method, retrieves query string as a key/value hash
getQueryHash: function() {
var query = {};
location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) {
query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
} );
// Basic deserialization
for( var i in query ) {
var value = query[ i ];
query[ i ] = deserialize( unescape( value ) );
}
return query;
},
// Returns true if we're currently on the first slide
isFirstSlide: function() {
return ( indexh === 0 && indexv === 0 );
},
// Returns true if we're currently on the last slide
isLastSlide: function() {
if( currentSlide ) {
// Does this slide has next a sibling?
if( currentSlide.nextElementSibling ) return false;
// If it's vertical, does its parent have a next sibling?
if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false;
return true;
}
return false;
},
// Checks if reveal.js has been loaded and is ready for use
isReady: function() {
return loaded;
},
// Forward event binding to the reveal DOM element
addEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
}
},
removeEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
}
},
// Programatically triggers a keyboard event
triggerKey: function( keyCode ) {
onDocumentKeyDown( { keyCode: keyCode } );
},
// Registers a new shortcut to include in the help overlay
registerKeyboardShortcut: function( key, value ) {
keyboardShortcuts[key] = value;
}
};
return Reveal;
}));
| lihuma/lihuma.github.io | js/reveal.js | JavaScript | mit | 131,510 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
# @author : beaengine@gmail.com
from headers.BeaEnginePython import *
from nose.tools import *
class TestSuite:
def test(self):
# EVEX.256.66.0F3A.W0 25 /r ib
# vpternlogd ymm1{k1}{z}, ymm2, ymm3/m256/m32bcst, imm8
myEVEX = EVEX('EVEX.256.66.0F3A.W0')
Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x25)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd')
assert_equal(myDisasm.repr(), 'vpternlogd ymm28, ymm16, ymmword ptr [r8], 11h')
# EVEX.512.66.0F3A.W0 25 /r ib
# vpternlogd zmm1{k1}{z}, zmm2, zmm3/m512/m32bcst, imm8
myEVEX = EVEX('EVEX.512.66.0F3A.W0')
Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x25)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd')
assert_equal(myDisasm.repr(), 'vpternlogd zmm28, zmm16, zmmword ptr [r8], 11h')
# EVEX.256.66.0F3A.W1 25 /r ib
# vpternlogq ymm1{k1}{z}, ymm2, ymm3/m256/m64bcst, imm8
myEVEX = EVEX('EVEX.256.66.0F3A.W1')
Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x25)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq')
assert_equal(myDisasm.repr(), 'vpternlogq ymm28, ymm16, ymmword ptr [r8], 11h')
# EVEX.512.66.0F3A.W1 25 /r ib
# vpternlogq zmm1{k1}{z}, zmm2, zmm3/m512/m64bcst, imm8
myEVEX = EVEX('EVEX.512.66.0F3A.W1')
Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x25)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq')
assert_equal(myDisasm.repr(), 'vpternlogq zmm28, zmm16, zmmword ptr [r8], 11h')
| 0vercl0k/rp | src/third_party/beaengine/tests/0f3a25.py | Python | mit | 2,835 |
class Base {
public:
Resource *p;
Base() {
p = createResource();
}
virtual void f() { //has virtual function
//...
}
//...
~Base() { //wrong: is non-virtual
freeResource(p);
}
};
class Derived: public Base {
public:
Resource *dp;
Derived() {
dp = createResource2();
}
~Derived() {
freeResource2(dp);
}
};
int f() {
Base *b = new Derived(); //creates resources for both Base::p and Derived::dp
//...
//will only call Base::~Base(), leaking the resource dp.
//Change both destructors to virtual to ensure they are both called.
delete b;
}
| github/codeql | cpp/ql/src/jsf/4.10 Classes/AV Rule 78.cpp | C++ | mit | 568 |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// (3) Neither the name of the newtelligence AG 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.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using newtelligence.DasBlog.Runtime.Proxies;
using newtelligence.DasBlog.Util;
namespace newtelligence.DasBlog.Runtime
{
[Serializable]
[XmlRoot(Namespace=Data.NamespaceURI)]
[XmlType(Namespace=Data.NamespaceURI)]
public class DayEntry : IDayEntry
{
private object entriesLock = new object(); //the entries collection is shared and must be protected
private bool Loaded
{
[DebuggerStepThrough()] get { return _loaded; }
[DebuggerStepThrough()] set { _loaded = value; }
}
private bool _loaded = false;
public string FileName
{
get
{
// Use Invariant Culture, not host culture (or user override), for date formats.
return DateUtc.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + ".dayentry.xml";
}
}
[XmlIgnore]
public DateTime DateUtc
{
[DebuggerStepThrough()] get { return _date; }
[DebuggerStepThrough()] set { _date = value.Date; }
}
private DateTime _date;
[XmlElement("Date")]
public DateTime DateLocalTime
{
get { return (DateUtc==DateTime.MinValue||DateUtc==DateTime.MaxValue)?DateUtc:DateUtc.ToLocalTime(); }
set { DateUtc = (value==DateTime.MinValue||value==DateTime.MaxValue)?value:value.Date.ToUniversalTime(); }
}
[XmlArrayItem(typeof(Entry))]
public EntryCollection Entries
{
[DebuggerStepThrough()] get { return _entries; }
[DebuggerStepThrough()] set { _entries = value; }
}
private EntryCollection _entries = new EntryCollection();
[XmlAnyElement]
public XmlElement[] anyElements;
[XmlAnyAttribute]
public XmlAttribute[] anyAttributes;
public void Initialize()
{
DateUtc = DateTime.Now.ToUniversalTime().Date;
}
/// <summary>
/// Return EntryCollection excluding the private entries if the caller
/// is not in the admin role.
/// </summary>
public EntryCollection GetEntries()
{
return GetEntries(null);
}
/// <summary>
/// Return EntryCollection with the number of entries limited by <see paramref="maxResults" />
/// excluding the private entries if the caller is not in the admin role.
/// </summary>
public EntryCollection GetEntries(int maxResults)
{
return GetEntries(null, maxResults);
}
/// <summary>
/// Returns the entries that meet the include delegates criteria.
/// </summary>
/// <param name="include">The delegate indicating which items to include.</param>
public EntryCollection GetEntries(Predicate<Entry> include)
{
return GetEntries(include, Int32.MaxValue);
}
/// <summary>
/// Returns the entries that meet the include delegates criteria,
/// with the number of entries limited by <see paramref="maxResults" />.
/// </summary>
/// <param name="include">The delegate indicating which items to include.</param>
public EntryCollection GetEntries(Predicate<Entry> include, int maxResults)
{
lock(entriesLock)
{
Predicate<Entry> filter = null;
if(!System.Threading.Thread.CurrentPrincipal.IsInRole("admin"))
{
filter += EntryCollectionFilter.DefaultFilters.IsPublic();
}
if(include != null)
{
filter += include;
}
return EntryCollectionFilter.FindAll(Entries, filter, maxResults);
}
}
/// <param name="entryTitle">An URL-encoded entry title</param>
public Entry GetEntryByTitle(string entryTitle)
{
foreach (Entry entry in this.Entries)
{
string compressedTitle = entry.CompressedTitle.Replace("+", "");
if (CaseInsensitiveComparer.Default.Compare(compressedTitle,entryTitle) == 0)
{
return entry;
}
}
return null;
}
internal void Load(DataManager data)
{
if ( Loaded )
{
return;
}
lock(entriesLock)
{
if ( Loaded ) //SDH: standard thread-safe double check
{
return;
}
string fullPath = data.ResolvePath(FileName);
FileStream fileStream = FileUtils.OpenForRead(fullPath);
if ( fileStream != null )
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(DayEntry),Data.NamespaceURI);
using (StreamReader reader = new StreamReader(fileStream))
{
//XmlNamespaceUpgradeReader upg = new XmlNamespaceUpgradeReader( reader, "", Data.NamespaceURI );
DayEntry e = (DayEntry)ser.Deserialize(reader);
Entries = e.Entries;
}
}
catch(Exception e)
{
ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,e);
}
finally
{
fileStream.Close();
}
}
Entries.Sort((left,right) => right.CreatedUtc.CompareTo(left.CreatedUtc));
Loaded = true;
}
}
internal void Save(DataManager data)
{
string fullPath = data.ResolvePath(FileName);
// We use the internal list to circumvent ignoring
// items where IsPublic is set to false.
if ( Entries.Count == 0 )
{
if ( File.Exists( fullPath ) )
{
File.Delete( fullPath );
}
}
else
{
System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();
FileStream fileStream = FileUtils.OpenForWrite(fullPath);
if ( fileStream != null )
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(DayEntry),Data.NamespaceURI);
using (StreamWriter writer = new StreamWriter(fileStream))
{
ser.Serialize(writer, this);
}
}
catch(Exception e)
{
ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,e);
}
finally
{
fileStream.Close();
}
}
wi.Undo();
}
}
/// <summary>
/// Returns true if the specified DayEntry occurs before the day specified.
/// </summary>
/// <param name="dayEntry">The DayEntry to check the date of.</param>
/// <param name="dateTime">The date the DayEntry should occur before</param>
/// <returns>Returns true if the dayEntry occurs before the specified date.</returns>
public static bool OccursBefore(DayEntry dayEntry, DateTime dateTime)
{
return (dayEntry.DateUtc.Date <= dateTime);
}
public static bool OccursBetween(DayEntry dayEntry, TimeZone timeZone,
DateTime startDateTime, DateTime endDateTime)
{
//return ((timeZone.ToLocalTime(dayEntry.DateUtc) >= startDateTime)
// && (timeZone.ToLocalTime(dayEntry.DateUtc) <= endDateTime) );
return ((dayEntry.DateUtc >= startDateTime)
&& (dayEntry.DateUtc <= endDateTime) );
}
/// <summary>
/// Returns true if the specified DayEntry is within the same month as <c>month</c>;
/// </summary>
/// <param name="dayEntry"></param>
/// <param name="timeZone"></param>
/// <param name="month"></param>
/// <returns></returns>
public static bool OccursInMonth(DayEntry dayEntry, TimeZone timeZone,
DateTime month)
{
DateTime startOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0);
DateTime endOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0);
endOfMonth = endOfMonth.AddMonths(1);
endOfMonth = endOfMonth.AddSeconds(-1);
TimeSpan offset = timeZone.GetUtcOffset(endOfMonth);
endOfMonth = endOfMonth.AddHours(offset.Negate().Hours);
return ( OccursBetween(dayEntry, timeZone, startOfMonth, endOfMonth) );
}
}
}
| poppastring/dasblog | source/newtelligence.DasBlog.Runtime/DayEntry.cs | C# | mit | 9,683 |
var Example = Example || {};
Example.staticFriction = function() {
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Body = Matter.Body,
Composites = Matter.Composites,
Events = Matter.Events,
MouseConstraint = Matter.MouseConstraint,
Mouse = Matter.Mouse,
World = Matter.World,
Bodies = Matter.Bodies;
// create engine
var engine = Engine.create(),
world = engine.world;
// create renderer
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: Math.min(document.documentElement.clientWidth, 800),
height: Math.min(document.documentElement.clientHeight, 600),
showVelocity: true
}
});
Render.run(render);
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
// add bodies
var body = Bodies.rectangle(400, 500, 200, 60, { isStatic: true, chamfer: 10 }),
size = 50,
counter = -1;
var stack = Composites.stack(350, 470 - 6 * size, 1, 6, 0, 0, function(x, y) {
return Bodies.rectangle(x, y, size * 2, size, {
slop: 0.5,
friction: 1,
frictionStatic: Infinity
});
});
World.add(world, [
body,
stack,
// walls
Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),
Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),
Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),
Bodies.rectangle(0, 300, 50, 600, { isStatic: true })
]);
Events.on(engine, 'beforeUpdate', function(event) {
counter += 0.014;
if (counter < 0) {
return;
}
var px = 400 + 100 * Math.sin(counter);
// body is static so must manually update velocity for friction to work
Body.setVelocity(body, { x: px - body.position.x, y: 0 });
Body.setPosition(body, { x: px, y: body.position.y });
});
// add mouse control
var mouse = Mouse.create(render.canvas),
mouseConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: {
visible: false
}
}
});
World.add(world, mouseConstraint);
// keep the mouse in sync with rendering
render.mouse = mouse;
// fit the render viewport to the scene
Render.lookAt(render, {
min: { x: 0, y: 0 },
max: { x: 800, y: 600 }
});
// context for MatterTools.Demo
return {
engine: engine,
runner: runner,
render: render,
canvas: render.canvas,
stop: function() {
Matter.Render.stop(render);
Matter.Runner.stop(runner);
}
};
}; | lsu-emdm/nx-physicsUI | matter-js/examples/staticFriction.js | JavaScript | mit | 2,921 |
require File.dirname(__FILE__) + "/../spec_helper.rb"
| mhennemeyer/macspec | spec/mac_spec/testing_framework/spec_helper.rb | Ruby | mit | 54 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreShaderExHardwareSkinning.h"
#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS
#include "OgreShaderExDualQuaternionSkinning.h"
#include "OgreShaderExLinearSkinning.h"
#include "OgreShaderFFPRenderState.h"
#include "OgreShaderProgram.h"
#include "OgreShaderParameter.h"
#include "OgreShaderProgramSet.h"
#include "OgreEntity.h"
#include "OgreSubEntity.h"
#include "OgreMaterial.h"
#include "OgreSubMesh.h"
#include "OgreShaderGenerator.h"
#define HS_DATA_BIND_NAME "HS_SRS_DATA"
namespace Ogre {
template<> RTShader::HardwareSkinningFactory* Singleton<RTShader::HardwareSkinningFactory>::msSingleton = 0;
namespace RTShader {
HardwareSkinningFactory* HardwareSkinningFactory::getSingletonPtr(void)
{
return msSingleton;
}
HardwareSkinningFactory& HardwareSkinningFactory::getSingleton(void)
{
assert( msSingleton ); return ( *msSingleton );
}
String HardwareSkinning::Type = "SGX_HardwareSkinning";
/************************************************************************/
/* */
/************************************************************************/
HardwareSkinning::HardwareSkinning() :
mCreator(NULL),
mSkinningType(ST_LINEAR)
{
}
//-----------------------------------------------------------------------
const String& HardwareSkinning::getType() const
{
return Type;
}
//-----------------------------------------------------------------------
int HardwareSkinning::getExecutionOrder() const
{
return FFP_TRANSFORM;
}
//-----------------------------------------------------------------------
void HardwareSkinning::setHardwareSkinningParam(ushort boneCount, ushort weightCount, SkinningType skinningType, bool correctAntipodalityHandling, bool scalingShearingSupport)
{
mSkinningType = skinningType;
if(skinningType == ST_DUAL_QUATERNION)
{
if(mDualQuat.isNull())
{
mDualQuat.bind(OGRE_NEW DualQuaternionSkinning);
}
mActiveTechnique = mDualQuat;
}
else //if(skinningType == ST_LINEAR)
{
if(mLinear.isNull())
{
mLinear.bind(OGRE_NEW LinearSkinning);
}
mActiveTechnique = mLinear;
}
mActiveTechnique->setHardwareSkinningParam(boneCount, weightCount, correctAntipodalityHandling, scalingShearingSupport);
}
//-----------------------------------------------------------------------
ushort HardwareSkinning::getBoneCount()
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->getBoneCount();
}
//-----------------------------------------------------------------------
ushort HardwareSkinning::getWeightCount()
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->getWeightCount();
}
//-----------------------------------------------------------------------
SkinningType HardwareSkinning::getSkinningType()
{
assert(!mActiveTechnique.isNull());
return mSkinningType;
}
//-----------------------------------------------------------------------
bool HardwareSkinning::hasCorrectAntipodalityHandling()
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->hasCorrectAntipodalityHandling();
}
//-----------------------------------------------------------------------
bool HardwareSkinning::hasScalingShearingSupport()
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->hasScalingShearingSupport();
}
//-----------------------------------------------------------------------
void HardwareSkinning::copyFrom(const SubRenderState& rhs)
{
const HardwareSkinning& hardSkin = static_cast<const HardwareSkinning&>(rhs);
mDualQuat = hardSkin.mDualQuat;
mLinear = hardSkin.mLinear;
mActiveTechnique = hardSkin.mActiveTechnique;
mCreator = hardSkin.mCreator;
mSkinningType = hardSkin.mSkinningType;
}
//-----------------------------------------------------------------------
void operator<<(std::ostream& o, const HardwareSkinning::SkinningData& data)
{
o << data.isValid;
o << data.maxBoneCount;
o << data.maxWeightCount;
o << data.skinningType;
o << data.correctAntipodalityHandling;
o << data.scalingShearingSupport;
}
//-----------------------------------------------------------------------
bool HardwareSkinning::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass)
{
bool isValid = true;
Technique* pFirstTech = srcPass->getParent()->getParent()->getTechnique(0);
const Any& hsAny = pFirstTech->getUserObjectBindings().getUserAny(HS_DATA_BIND_NAME);
if (hsAny.isEmpty() == false)
{
HardwareSkinning::SkinningData pData =
(any_cast<HardwareSkinning::SkinningData>(hsAny));
isValid = pData.isValid;
//If the skinning data is being passed through the material, we need to create an instance of the appropriate
//skinning type and set its parameters here
setHardwareSkinningParam(pData.maxBoneCount, pData.maxWeightCount, pData.skinningType,
pData.correctAntipodalityHandling, pData.scalingShearingSupport);
}
//If there is no associated technique, default to linear skinning as a pass-through
if(mActiveTechnique.isNull())
{
setHardwareSkinningParam(0, 0, ST_LINEAR, false, false);
}
int boneCount = mActiveTechnique->getBoneCount();
int weightCount = mActiveTechnique->getWeightCount();
bool doBoneCalculations = isValid &&
(boneCount != 0) && (boneCount <= 256) &&
(weightCount != 0) && (weightCount <= 4) &&
((mCreator == NULL) || (boneCount <= mCreator->getMaxCalculableBoneCount()));
mActiveTechnique->setDoBoneCalculations(doBoneCalculations);
if ((doBoneCalculations) && (mCreator))
{
//update the receiver and caster materials
if (dstPass->getParent()->getShadowCasterMaterial().isNull())
{
dstPass->getParent()->setShadowCasterMaterial(
mCreator->getCustomShadowCasterMaterial(mSkinningType, weightCount - 1));
}
if (dstPass->getParent()->getShadowReceiverMaterial().isNull())
{
dstPass->getParent()->setShadowReceiverMaterial(
mCreator->getCustomShadowReceiverMaterial(mSkinningType, weightCount - 1));
}
}
return true;
}
//-----------------------------------------------------------------------
bool HardwareSkinning::resolveParameters(ProgramSet* programSet)
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->resolveParameters(programSet);
}
//-----------------------------------------------------------------------
bool HardwareSkinning::resolveDependencies(ProgramSet* programSet)
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->resolveDependencies(programSet);
}
//-----------------------------------------------------------------------
bool HardwareSkinning::addFunctionInvocations(ProgramSet* programSet)
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->addFunctionInvocations(programSet);
}
//-----------------------------------------------------------------------
HardwareSkinningFactory::HardwareSkinningFactory() :
mMaxCalculableBoneCount(70)
{
}
//-----------------------------------------------------------------------
const String& HardwareSkinningFactory::getType() const
{
return HardwareSkinning::Type;
}
//-----------------------------------------------------------------------
SubRenderState* HardwareSkinningFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator)
{
if (prop->name == "hardware_skinning")
{
bool hasError = false;
uint32 boneCount = 0;
uint32 weightCount = 0;
String skinningType = "";
SkinningType skinType = ST_LINEAR;
bool correctAntipodalityHandling = false;
bool scalingShearingSupport = false;
if(prop->values.size() >= 2)
{
AbstractNodeList::iterator it = prop->values.begin();
if(false == SGScriptTranslator::getUInt(*it, &boneCount))
hasError = true;
++it;
if(false == SGScriptTranslator::getUInt(*it, &weightCount))
hasError = true;
if(prop->values.size() >= 5)
{
++it;
SGScriptTranslator::getString(*it, &skinningType);
++it;
SGScriptTranslator::getBoolean(*it, &correctAntipodalityHandling);
++it;
SGScriptTranslator::getBoolean(*it, &scalingShearingSupport);
}
//If the skinningType is not specified or is specified incorrectly, default to linear skinning.
if(skinningType == "dual_quaternion")
{
skinType = ST_DUAL_QUATERNION;
}
else
{
skinType = ST_LINEAR;
}
}
if (hasError == true)
{
compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, "Expected the format: hardware_skinning <bone count> <weight count> [skinning type] [correct antipodality handling] [scaling/shearing support]");
return NULL;
}
else
{
//create and update the hardware skinning sub render state
SubRenderState* subRenderState = createOrRetrieveInstance(translator);
HardwareSkinning* hardSkinSrs = static_cast<HardwareSkinning*>(subRenderState);
hardSkinSrs->setHardwareSkinningParam(boneCount, weightCount, skinType, correctAntipodalityHandling, scalingShearingSupport);
return subRenderState;
}
}
return NULL;
}
//-----------------------------------------------------------------------
void HardwareSkinningFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState,
Pass* srcPass, Pass* dstPass)
{
ser->writeAttribute(4, "hardware_skinning");
HardwareSkinning* hardSkinSrs = static_cast<HardwareSkinning*>(subRenderState);
ser->writeValue(StringConverter::toString(hardSkinSrs->getBoneCount()));
ser->writeValue(StringConverter::toString(hardSkinSrs->getWeightCount()));
//Correct antipodality handling and scaling and shearing support are only really valid for dual quaternion skinning
if(hardSkinSrs->getSkinningType() == ST_DUAL_QUATERNION)
{
ser->writeValue("dual_quaternion");
ser->writeValue(StringConverter::toString(hardSkinSrs->hasCorrectAntipodalityHandling()));
ser->writeValue(StringConverter::toString(hardSkinSrs->hasScalingShearingSupport()));
}
}
//-----------------------------------------------------------------------
SubRenderState* HardwareSkinningFactory::createInstanceImpl()
{
HardwareSkinning* pSkin = OGRE_NEW HardwareSkinning;
pSkin->_setCreator(this);
return pSkin;
}
//-----------------------------------------------------------------------
void HardwareSkinningFactory::setCustomShadowCasterMaterials(const SkinningType skinningType, const MaterialPtr& caster1Weight, const MaterialPtr& caster2Weight,
const MaterialPtr& caster3Weight, const MaterialPtr& caster4Weight)
{
if(skinningType == ST_DUAL_QUATERNION)
{
mCustomShadowCasterMaterialsDualQuaternion[0] = caster1Weight;
mCustomShadowCasterMaterialsDualQuaternion[1] = caster2Weight;
mCustomShadowCasterMaterialsDualQuaternion[2] = caster3Weight;
mCustomShadowCasterMaterialsDualQuaternion[3] = caster4Weight;
}
else //if(skinningType == ST_LINEAR)
{
mCustomShadowCasterMaterialsLinear[0] = caster1Weight;
mCustomShadowCasterMaterialsLinear[1] = caster2Weight;
mCustomShadowCasterMaterialsLinear[2] = caster3Weight;
mCustomShadowCasterMaterialsLinear[3] = caster4Weight;
}
}
//-----------------------------------------------------------------------
void HardwareSkinningFactory::setCustomShadowReceiverMaterials(const SkinningType skinningType, const MaterialPtr& receiver1Weight, const MaterialPtr& receiver2Weight,
const MaterialPtr& receiver3Weight, const MaterialPtr& receiver4Weight)
{
if(skinningType == ST_DUAL_QUATERNION)
{
mCustomShadowReceiverMaterialsDualQuaternion[0] = receiver1Weight;
mCustomShadowReceiverMaterialsDualQuaternion[1] = receiver2Weight;
mCustomShadowReceiverMaterialsDualQuaternion[2] = receiver3Weight;
mCustomShadowReceiverMaterialsDualQuaternion[3] = receiver4Weight;
}
else //if(skinningType == ST_LINEAR)
{
mCustomShadowReceiverMaterialsLinear[0] = receiver1Weight;
mCustomShadowReceiverMaterialsLinear[1] = receiver2Weight;
mCustomShadowReceiverMaterialsLinear[2] = receiver3Weight;
mCustomShadowReceiverMaterialsLinear[3] = receiver4Weight;
}
}
//-----------------------------------------------------------------------
const MaterialPtr& HardwareSkinningFactory::getCustomShadowCasterMaterial(const SkinningType skinningType, ushort index) const
{
assert(index < HS_MAX_WEIGHT_COUNT);
if(skinningType == ST_DUAL_QUATERNION)
{
return mCustomShadowCasterMaterialsDualQuaternion[index];
}
else //if(skinningType = ST_LINEAR)
{
return mCustomShadowCasterMaterialsLinear[index];
}
}
//-----------------------------------------------------------------------
const MaterialPtr& HardwareSkinningFactory::getCustomShadowReceiverMaterial(const SkinningType skinningType, ushort index) const
{
assert(index < HS_MAX_WEIGHT_COUNT);
if(skinningType == ST_DUAL_QUATERNION)
{
return mCustomShadowReceiverMaterialsDualQuaternion[index];
}
else //if(skinningType == ST_LINEAR)
{
return mCustomShadowReceiverMaterialsLinear[index];
}
}
//-----------------------------------------------------------------------
void HardwareSkinningFactory::prepareEntityForSkinning(const Entity* pEntity, SkinningType skinningType,
bool correctAntidpodalityHandling, bool shearScale)
{
if (pEntity != NULL)
{
size_t lodLevels = pEntity->getNumManualLodLevels() + 1;
for(size_t indexLod = 0 ; indexLod < lodLevels ; ++indexLod)
{
const Entity* pCurEntity = pEntity;
if (indexLod > 0) pCurEntity = pEntity->getManualLodLevel(indexLod - 1);
unsigned int numSubEntities = pCurEntity->getNumSubEntities();
for(unsigned int indexSub = 0 ; indexSub < numSubEntities ; ++indexSub)
{
ushort boneCount = 0,weightCount = 0;
bool isValid = extractSkeletonData(pCurEntity, indexSub, boneCount, weightCount);
SubEntity* pSubEntity = pCurEntity->getSubEntity(indexSub);
const MaterialPtr& pMat = pSubEntity->getMaterial();
imprintSkeletonData(pMat, isValid, boneCount, weightCount, skinningType, correctAntidpodalityHandling, shearScale);
}
}
}
}
//-----------------------------------------------------------------------
bool HardwareSkinningFactory::extractSkeletonData(const Entity* pEntity, unsigned int subEntityIndex, ushort& boneCount, ushort& weightCount)
{
bool isValidData = false;
boneCount = 0;
weightCount = 0;
//Check if we have pose animation which the HS sub render state does not
//know how to handle
bool hasVertexAnim = pEntity->getMesh()->hasVertexAnimation();
//gather data on the skeleton
if (!hasVertexAnim && pEntity->hasSkeleton())
{
//get weights count
MeshPtr pMesh = pEntity->getMesh();
RenderOperation ro;
SubMesh* pSubMesh = pMesh->getSubMesh(subEntityIndex);
pSubMesh->_getRenderOperation(ro,0);
//get the largest bone assignment
boneCount = std::max<ushort>(pMesh->sharedBlendIndexToBoneIndexMap.size(), pSubMesh->blendIndexToBoneIndexMap.size());
//go over vertex deceleration
//check that they have blend indices and blend weights
const VertexElement* pDeclWeights = ro.vertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_WEIGHTS,0);
const VertexElement* pDeclIndexes = ro.vertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_INDICES,0);
if ((pDeclWeights != NULL) && (pDeclIndexes != NULL))
{
isValidData = true;
switch (pDeclWeights->getType())
{
case VET_FLOAT1: weightCount = 1; break;
case VET_FLOAT2: weightCount = 2; break;
case VET_FLOAT3: weightCount = 3; break;
case VET_FLOAT4: weightCount = 4; break;
default: isValidData = false;
}
}
}
return isValidData;
}
//-----------------------------------------------------------------------
bool HardwareSkinningFactory::imprintSkeletonData(const MaterialPtr& pMaterial, bool isVaild,
ushort boneCount, ushort weightCount, SkinningType skinningType, bool correctAntidpodalityHandling, bool scalingShearingSupport)
{
bool isUpdated = false;
if (pMaterial->getNumTechniques() > 0)
{
HardwareSkinning::SkinningData data;
//get the previous skinning data if available
UserObjectBindings& binding = pMaterial->getTechnique(0)->getUserObjectBindings();
const Any& hsAny = binding.getUserAny(HS_DATA_BIND_NAME);
if (hsAny.isEmpty() == false)
{
data = (any_cast<HardwareSkinning::SkinningData>(hsAny));
}
//check if we need to update the data
if (((data.isValid == true) && (isVaild == false)) ||
(data.maxBoneCount < boneCount) ||
(data.maxWeightCount < weightCount))
{
//update the data
isUpdated = true;
data.isValid &= isVaild;
data.maxBoneCount = std::max<ushort>(data.maxBoneCount, boneCount);
data.maxWeightCount = std::max<ushort>(data.maxWeightCount, weightCount);
data.skinningType = skinningType;
data.correctAntipodalityHandling = correctAntidpodalityHandling;
data.scalingShearingSupport = scalingShearingSupport;
//update the data in the material and invalidate it in the RTShader system
//do it will be regenerated
binding.setUserAny(HS_DATA_BIND_NAME, Any(data));
size_t schemeCount = ShaderGenerator::getSingleton().getRTShaderSchemeCount();
for(size_t i = 0 ; i < schemeCount ; ++i)
{
//invalidate the material so it will be recreated with the correct
//amount of bones and weights
const String& schemeName = ShaderGenerator::getSingleton().getRTShaderScheme(i);
ShaderGenerator::getSingleton().invalidateMaterial(
schemeName, pMaterial->getName(), pMaterial->getGroup());
}
}
}
return isUpdated;
}
}
}
#endif
| xsilium-frameworks/xsilium-engine | Library/Ogre/Components/RTShaderSystem/src/OgreShaderExHardwareSkinning.cpp | C++ | mit | 18,731 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//
package org.ecloudmanager.tmrk.cloudapi.model;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
/**
* <p>Java class for ResourceBurstType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ResourceBurstType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Actions" type="{}ArrayOfActionType" minOccurs="0"/>
* <element name="Status" type="{}ResourceBurstStatus" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ResourceBurstType", propOrder = {
"actions",
"status"
})
public class ResourceBurstType {
@XmlElementRef(name = "Actions", type = JAXBElement.class, required = false)
protected JAXBElement<ArrayOfActionType> actions;
@XmlElement(name = "Status")
@XmlSchemaType(name = "string")
protected ResourceBurstStatus status;
/**
* Gets the value of the actions property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link ArrayOfActionType }{@code >}
*
*/
public JAXBElement<ArrayOfActionType> getActions() {
return actions;
}
/**
* Sets the value of the actions property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link ArrayOfActionType }{@code >}
*
*/
public void setActions(JAXBElement<ArrayOfActionType> value) {
this.actions = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link ResourceBurstStatus }
*
*/
public ResourceBurstStatus getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link ResourceBurstStatus }
*
*/
public void setStatus(ResourceBurstStatus value) {
this.status = value;
}
}
| AltisourceLabs/ecloudmanager | tmrk-cloudapi/src/main/java/org/ecloudmanager/tmrk/cloudapi/model/ResourceBurstType.java | Java | mit | 2,598 |
var searchData=
[
['vertical_5fline',['vertical_line',['../class_abstract_board.html#a78c4d43cc32d9dc74d73156497db6d3f',1,'AbstractBoard']]]
];
| dawidd6/qtictactoe | docs/search/variables_9.js | JavaScript | mit | 146 |
package runner
import (
"strings"
"testing"
"gopkg.in/stretchr/testify.v1/assert"
)
// https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt
var fuzzList = `
'
"
#
-
--
'%20--
--';
'%20;
=%20'
=%20;
=%20--
\x23
\x27
\x3D%20\x3B'
\x3D%20\x27
\x27\x4F\x52 SELECT *
\x27\x6F\x72 SELECT *
'or%20select *
admin'--
<>"'%;)(&+
'%20or%20''='
'%20or%20'x'='x
"%20or%20"x"="x
')%20or%20('x'='x
0 or 1=1
' or 0=0 --
" or 0=0 --
or 0=0 --
' or 0=0 #
" or 0=0 #
or 0=0 #
' or 1=1--
" or 1=1--
' or '1'='1'--
"' or 1 --'"
or 1=1--
or%201=1
or%201=1 --
' or 1=1 or ''='
" or 1=1 or ""="
' or a=a--
" or "a"="a
') or ('a'='a
") or ("a"="a
hi" or "a"="a
hi" or 1=1 --
hi' or 1=1 --
hi' or 'a'='a
hi') or ('a'='a
hi") or ("a"="a
'hi' or 'x'='x';
@variable
,@variable
PRINT
PRINT @@variable
select
insert
as
or
procedure
limit
order by
asc
desc
delete
update
distinct
having
truncate
replace
like
handler
bfilename
' or username like '%
' or uname like '%
' or userid like '%
' or uid like '%
' or user like '%
exec xp
exec sp
'; exec master..xp_cmdshell
'; exec xp_regread
t'exec master..xp_cmdshell 'nslookup www.google.com'--
--sp_password
\x27UNION SELECT
' UNION SELECT
' UNION ALL SELECT
' or (EXISTS)
' (select top 1
'||UTL_HTTP.REQUEST
1;SELECT%20*
to_timestamp_tz
tz_offset
<>"'%;)(&+
'%20or%201=1
%27%20or%201=1
%20$(sleep%2050)
%20'sleep%2050'
char%4039%41%2b%40SELECT
'%20OR
'sqlattempt1
(sqlattempt2)
|
%7C
*|
%2A%7C
*(|(mail=*))
%2A%28%7C%28mail%3D%2A%29%29
*(|(objectclass=*))
%2A%28%7C%28objectclass%3D%2A%29%29
(
%28
)
%29
&
%26
!
%21
' or 1=1 or ''='
' or ''='
x' or 1=1 or 'x'='y
/
//
//*
*/*
`
func init() {
fuzzList += "\b"
fuzzList += "\n"
fuzzList += "\n"
fuzzList += "\r"
fuzzList += "\t"
fuzzList += "Hello\tworld"
}
func TestSQLInjectionBuilder(t *testing.T) {
for _, fuzz := range strings.Split(fuzzList, "\n") {
if fuzz == "" {
continue
}
fuzz = strings.Trim(fuzz, " \t")
var id int64
var comment string
err := testDB.
InsertInto("comments").
Columns("comment").
Values(fuzz).
SetIsInterpolated(true).
Returning("id", "comment").
QueryScalar(&id, &comment)
assert.True(t, id > 0)
assert.Equal(t, fuzz, comment)
var result int
err = testDB.SQL(`
SELECT 42
FROM comments
WHERE id = $1 AND comment = $2
`, id, comment).QueryScalar(&result)
assert.NoError(t, err)
assert.Equal(t, 42, result)
}
}
func TestSQLInjectionSQL(t *testing.T) {
for _, fuzz := range strings.Split(fuzzList, "\n") {
if fuzz == "" {
continue
}
fuzz = strings.Trim(fuzz, " \t")
var id int64
var comment string
err := testDB.
SQL(`
INSERT INTO comments (comment)
VALUES ($1)
RETURNING id, comment
`, fuzz).
SetIsInterpolated(true).
QueryScalar(&id, &comment)
assert.True(t, id > 0)
assert.Equal(t, fuzz, comment)
var result int
err = testDB.SQL(`
SELECT 42
FROM comments
WHERE id = $1 AND comment = $2
`, id, comment).QueryScalar(&result)
assert.NoError(t, err)
assert.Equal(t, 42, result)
}
}
| mgutz/dat | sqlx-runner/sqli_test.go | GO | mit | 3,048 |
import flask
from donut import auth_utils
from donut.modules.account import blueprint, helpers
@blueprint.route("/request")
def request_account():
"""Provides a form to request an account."""
return flask.render_template("request_account.html")
@blueprint.route("/request/submit", methods=["POST"])
def request_account_submit():
"""Handles an account creation request."""
uid = flask.request.form.get("uid", None)
last_name = flask.request.form.get("last_name", None)
if uid is None or last_name is None:
flask.flash("Invalid request.")
return flask.redirect(flask.url_for("account.request_account"))
success, error_msg = helpers.handle_request_account(uid, last_name)
if success:
flask.flash(
"An email has been sent with a link to create your account.")
return flask.redirect(flask.url_for("home"))
else:
flask.flash(error_msg)
return flask.redirect(flask.url_for("account.request_account"))
@blueprint.route("/create/<create_account_key>")
def create_account(create_account_key):
"""Checks the key. If valid, displays the create account page."""
user_id = auth_utils.check_create_account_key(create_account_key)
if user_id is None:
flask.current_app.logger.warn(
f'Invalid create_account_key: {create_account_key}')
flask.flash("Invalid request. Please check your link and try again.")
return flask.redirect(flask.url_for("home"))
user_data = helpers.get_user_data(user_id)
if user_data is None:
flask.flash("An unexpected error occurred. Please contact DevTeam.")
return flask.redirect(flask.url_for("home"))
return flask.render_template(
"create_account.html", user_data=user_data, key=create_account_key)
@blueprint.route("/create/<create_account_key>/submit", methods=["POST"])
def create_account_submit(create_account_key):
"""Handles a create account request."""
user_id = auth_utils.check_create_account_key(create_account_key)
if user_id is None:
# Key is invalid.
flask.current_app.logger.warn(
f'Invalid create_account_key: {create_account_key}')
flask.flash("Someone's been naughty.")
return flask.redirect(flask.url_for("home"))
username = flask.request.form.get("username", None)
password = flask.request.form.get("password", None)
password2 = flask.request.form.get("password2", None)
if username is None \
or password is None \
or password2 is None:
flask.current_app.logger.warn(
f'Invalid create account form for user ID {user_id}')
flask.flash("Invalid request.")
return flask.redirect(flask.url_for("home"))
if helpers.handle_create_account(user_id, username, password, password2):
flask.session['username'] = username
flask.current_app.logger.info(
f'Created account with username {username} for user ID {user_id}')
flask.flash("Account successfully created.")
return flask.redirect(flask.url_for("home"))
else:
# Flashes already handled.
return flask.redirect(
flask.url_for(
"account.create_account",
create_account_key=create_account_key))
| ASCIT/donut | donut/modules/account/routes.py | Python | mit | 3,294 |
package org.ominidi.api.controller;
import org.ominidi.api.exception.ConnectionException;
import org.ominidi.api.exception.NotFoundException;
import org.ominidi.api.model.Errors;
import org.ominidi.domain.model.Feed;
import org.ominidi.domain.model.Post;
import org.ominidi.facebook.service.PageFeedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/api/v1")
public class FeedController {
private PageFeedService pageFeedService;
@Autowired
public FeedController(PageFeedService pageFeedService) {
this.pageFeedService = pageFeedService;
}
@GetMapping(value = "/feed", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Feed<Post> getFeed(@RequestParam(value = "u", required = false) Optional<String> feedUrl) {
Optional<Feed<Post>> result = feedUrl.isPresent()
? pageFeedService.getFeed(feedUrl.get())
: pageFeedService.getFeed();
return result.orElseThrow(() -> new ConnectionException(Errors.CONNECTION_PROBLEM));
}
@GetMapping(value = "/post/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Post getPost(@PathVariable(value = "id") String id) {
return pageFeedService.getPostById(id).orElseThrow(() -> new NotFoundException(Errors.postNotFound(id)));
}
}
| ominidi/ominidi-web | src/main/java/org/ominidi/api/controller/FeedController.java | Java | mit | 1,506 |
#include "jsonobject.h"
#include "jsonparser.h"
namespace amgcommon {
namespace json {
JsonObject::JsonObject(string rawJson) {
this->originalJson = rawJson;
this->root = JsonNode();
}
JsonObject::JsonObject(const JsonObject &a) {
this->originalJson = a.originalJson;
this->root = a.root;
}
JsonObject *JsonObject::clone() {
return new JsonObject(*this);
}
JsonObject::~JsonObject() {
}
string JsonObject::toString() {
return this->root.toString();
}
JsonNode JsonObject::getRoot() {
return root;
}
void JsonObject::setKey(string path, Object *value) {
this->root.setKey(path, value);
}
Object *JsonObject::getKey(string path) {
return this->root.getKey(path);
}
}
}
| agancsos/cpp | amgbuildagent/src/classes/amgcommon/json/jsonobject.cpp | C++ | mit | 1,076 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Class for axis handling.
*
* PHP versions 4 and 5
*
* LICENSE: This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version. This library is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this library; if not, write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* @category Images
* @package Image_Graph
* @subpackage Axis
* @author Jesper Veggerby <pear.nosey@veggerby.dk>
* @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version CVS: $Id: Category.php,v 1.19 2006/03/02 12:15:17 nosey Exp $
* @link http://pear.php.net/package/Image_Graph
*/
/**
* Include file Image/Graph/Axis.php
*/
require_once 'Image/Graph/Axis.php';
/**
* A normal axis thats displays labels with a 'interval' of 1.
* This is basically a normal axis where the range is
* the number of labels defined, that is the range is explicitly defined
* when constructing the axis.
*
* @category Images
* @package Image_Graph
* @subpackage Axis
* @author Jesper Veggerby <pear.nosey@veggerby.dk>
* @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: @package_version@
* @link http://pear.php.net/package/Image_Graph
*/
class Image_Graph_Axis_Category extends Image_Graph_Axis
{
/**
* The labels shown on the axis
* @var array
* @access private
*/
var $_labels = false;
/**
* Image_Graph_Axis_Category [Constructor].
*
* @param int $type The type (direction) of the Axis
*/
function Image_Graph_Axis_Category($type = IMAGE_GRAPH_AXIS_X)
{
parent::Image_Graph_Axis($type);
$this->_labels = array();
$this->setlabelInterval(1);
}
/**
* Gets the minimum value the axis will show.
*
* This is always 0
*
* @return double The minumum value
* @access private
*/
function _getMinimum()
{
return 0;
}
/**
* Gets the maximum value the axis will show.
*
* This is always the number of labels passed to the constructor.
*
* @return double The maximum value
* @access private
*/
function _getMaximum()
{
return count($this->_labels) - 1;
}
/**
* Sets the minimum value the axis will show.
*
* A minimum cannot be set on a SequentialAxis, it is always 0.
*
* @param double Minimum The minumum value to use on the axis
* @access private
*/
function _setMinimum($minimum)
{
}
/**
* Sets the maximum value the axis will show
*
* A maximum cannot be set on a SequentialAxis, it is always the number
* of labels passed to the constructor.
*
* @param double Maximum The maximum value to use on the axis
* @access private
*/
function _setMaximum($maximum)
{
}
/**
* Forces the minimum value of the axis
*
* <b>A minimum cannot be set on this type of axis</b>
*
* To modify the labels which are displayed on the axis, instead use
* setLabelInterval($labels) where $labels is an array containing the
* values/labels the axis should display. <b>Note!</b> Only values in
* this array will then be displayed on the graph!
*
* @param double $minimum A minimum cannot be set on this type of axis
*/
function forceMinimum($minimum, $userEnforce = true)
{
}
/**
* Forces the maximum value of the axis
*
* <b>A maximum cannot be set on this type of axis</b>
*
* To modify the labels which are displayed on the axis, instead use
* setLabelInterval($labels) where $labels is an array containing the
* values/labels the axis should display. <b>Note!</b> Only values in
* this array will then be displayed on the graph!
*
* @param double $maximum A maximum cannot be set on this type of axis
*/
function forceMaximum($maximum, $userEnforce = true)
{
}
/**
* Sets an interval for where labels are shown on the axis.
*
* The label interval is rounded to nearest integer value.
*
* @param double $labelInterval The interval with which labels are shown
*/
function setLabelInterval($labelInterval = 'auto', $level = 1)
{
if (is_array($labelInterval)) {
parent::setLabelInterval($labelInterval);
} elseif ($labelInterval == 'auto') {
parent::setLabelInterval(1);
} else {
parent::setLabelInterval(round($labelInterval));
}
}
/**
* Preprocessor for values, ie for using logarithmic axis
*
* @param double $value The value to preprocess
* @return double The preprocessed value
* @access private
*/
function _value($value)
{
// $the_value = array_search($value, $this->_labels);
if (isset($this->_labels[$value])) {
$the_value = $this->_labels[$value];
if ($the_value !== false) {
return $the_value + ($this->_pushValues ? 0.5 : 0);
} else {
return 0;
}
}
}
/**
* Get the minor label interval with which axis label ticks are drawn.
*
* For a sequential axis this is always disabled (i.e false)
*
* @return double The minor label interval, always false
* @access private
*/
function _minorLabelInterval()
{
return false;
}
/**
* Get the size in pixels of the axis.
*
* For an x-axis this is the width of the axis including labels, and for an
* y-axis it is the corrresponding height
*
* @return int The size of the axis
* @access private
*/
function _size()
{
if (!$this->_visible) {
return 0;
}
$this->_canvas->setFont($this->_getFont());
$maxSize = 0;
foreach($this->_labels as $label => $id) {
$labelPosition = $this->_point($label);
if (is_object($this->_dataPreProcessor)) {
$labelText = $this->_dataPreProcessor->_process($label);
} else {
$labelText = $label;
}
if ((($this->_type == IMAGE_GRAPH_AXIS_X) && (!$this->_transpose)) ||
(($this->_type != IMAGE_GRAPH_AXIS_X) && ($this->_transpose)))
{
$maxSize = max($maxSize, $this->_canvas->textHeight($labelText));
} else {
$maxSize = max($maxSize, $this->_canvas->textWidth($labelText));
}
}
if ($this->_title) {
$this->_canvas->setFont($this->_getTitleFont());
if ((($this->_type == IMAGE_GRAPH_AXIS_X) && (!$this->_transpose)) ||
(($this->_type != IMAGE_GRAPH_AXIS_X) && ($this->_transpose)))
{
$maxSize += $this->_canvas->textHeight($this->_title);
} else {
$maxSize += $this->_canvas->textWidth($this->_title);
}
$maxSize += 10;
}
return $maxSize +3;
}
/**
* Apply the dataset to the axis.
*
* This calculates the order of the categories, which is very important
* for fx. line plots, so that the line does not "go backwards", consider
* these X-sets:<p>
* 1: (1, 2, 3, 4, 5, 6)<br>
* 2: (0, 1, 2, 3, 4, 5, 6, 7)<p>
* If they are not ordered, but simply appended, the categories on the axis
* would be:<p>
* X: (1, 2, 3, 4, 5, 6, 0, 7)<p>
* Which would render the a line for the second plot to show incorrectly.
* Instead this algorithm, uses and 'value- is- before' method to see that
* the 0 is before a 1 in the second set, and that it should also be before
* a 1 in the X set. Hence:<p>
* X: (0, 1, 2, 3, 4, 5, 6, 7)
*
* @param Image_Graph_Dataset $dataset The dataset
* @access private
*/
function _applyDataset(&$dataset)
{
$newLabels = array();
$allLabels = array();
$dataset->_reset();
$count = 0;
$count_new = 0;
while ($point = $dataset->_next()) {
if ($this->_type == IMAGE_GRAPH_AXIS_X) {
$data = $point['X'];
} else {
$data = $point['Y'];
}
if (!isset($this->_labels[$data])) {
$newLabels[$data] = $count_new++;
//$this->_labels[] = $data;
}
$allLabels[$data] = $count++;
}
if (count($this->_labels) == 0) {
$this->_labels = $newLabels;
} elseif ((is_array($newLabels)) && (count($newLabels) > 0)) {
// get all intersecting labels
$intersect = array_intersect(array_keys($allLabels), array_keys($this->_labels));
// traverse all new and find their relative position withing the
// intersec, fx value X0 is before X1 in the intersection, which
// means that X0 should be placed before X1 in the label array
foreach($newLabels as $newLabel => $id) {
$key = $allLabels[$newLabel];
reset($intersect);
$this_value = false;
// intersect indexes are the same as in allLabels!
$first = true;
while ((list($id, $value) = each($intersect)) &&
($this_value === false))
{
if (($first) && ($id > $key)) {
$this_value = $value;
} elseif ($id >= $key) {
$this_value = $value;
}
$first = false;
}
if ($this_value === false) {
// the new label was not found before anything in the
// intersection -> append it
$this->_labels[$newLabel] = count($this->_labels);
} else {
// the new label was found before $this_value in the
// intersection, insert the label before this position in
// the label array
// $key = $this->_labels[$this_value];
$keys = array_keys($this->_labels);
$key = array_search($this_value, $keys);
$pre = array_slice($keys, 0, $key);
$pre[] = $newLabel;
$post = array_slice($keys, $key);
$this->_labels = array_flip(array_merge($pre, $post));
}
}
unset($keys);
}
$labels = array_keys($this->_labels);
$i = 0;
foreach ($labels as $label) {
$this->_labels[$label] = $i++;
}
// $this->_labels = array_values(array_unique($this->_labels));
$this->_calcLabelInterval();
}
/**
* Return the label distance.
*
* @return int The distance between 2 adjacent labels
* @access private
*/
function _labelDistance($level = 1)
{
reset($this->_labels);
list($l1) = each($this->_labels);
list($l2) = each($this->_labels);
return abs($this->_point($l2) - $this->_point($l1));
}
/**
* Get next label point
*
* @param doubt $point The current point, if omitted or false, the first is
* returned
* @return double The next label point
* @access private
*/
function _getNextLabel($currentLabel = false, $level = 1)
{
if ($currentLabel === false) {
reset($this->_labels);
}
$result = false;
$count = ($currentLabel === false ? $this->_labelInterval() - 1 : 0);
while ($count < $this->_labelInterval()) {
$result = (list($label) = each($this->_labels));
$count++;
}
if ($result) {
return $label;
} else {
return false;
}
}
/**
* Is the axis numeric or not?
*
* @return bool True if numeric, false if not
* @access private
*/
function _isNumeric()
{
return false;
}
/**
* Output the axis
*
* @return bool Was the output 'good' (true) or 'bad' (false).
* @access private
*/
function _done()
{
$result = true;
if (Image_Graph_Element::_done() === false) {
$result = false;
}
$this->_canvas->startGroup(get_class($this));
$this->_drawAxisLines();
$this->_canvas->startGroup(get_class($this) . '_ticks');
$label = false;
while (($label = $this->_getNextLabel($label)) !== false) {
$this->_drawTick($label);
}
$this->_canvas->endGroup();
$this->_canvas->endGroup();
return $result;
}
}
?> | extremeframework/extremeframework | library/external/PEAR/Image/Graph/Axis/Category.php | PHP | mit | 13,647 |
/**
* Created by huangyao on 14-10-1.
*/
var _ = require('lodash');
var color =require('colors');
var fs =require('fs');
var config = require('../config.js');
var path = require('path');
var mongoose = require("mongoose");
var lcommon = require('lush').common;
console.log(config.db);
mongoose.connect(config.db,function (err) {
if(err){
throw new Error('db connect error!\n'+err);
}
console.log('db connect success!'.yellow);
});
// console.log('point');
// var models = {
//
// init : function (callback) {
// fs.readdir(path+'/module',function (err,files) {
// if(err){
// throw err;
// }
// // console.log(files);
// return callback(files.filter(function (item) {
// return !(item === "index.js" || item === "." || item === "..");
// }));
// });
// },
// };
//
//
// models.init(function (files) {
// // console.log(files);
// for (var item in files) {
// //reuire all modules
// // console.log(lcommon.literat(files[item]).slice(0,-3));
// console.log(files[item]);
// item = files[item].split('.')[0];
// require('./'+ item);
// var m = lcommon.literat(item);
// console.log('loading and use ',m,' model');
// exports[m] = mongoose.model(m);
//
// // _.extend(models,file.exports);
// // console.log(file);
// }
// });
//
var models = fs.readdirSync(path.resolve('.','module'));
models.forEach(function(item,index){
if(item !== '.' && item !== '..' && item !== 'index.js'){
// console.log(item.indexOf('.js'));
//ends with .js
if(item.indexOf('.js') == (item.length-3)){
item = item.split('.')[0];
require('./'+ item);
var m = lcommon.literat(item);
console.log('loading and use ',m,' model');
exports[m] = mongoose.model(m);
}
}
});
| NodeAndroid/Action_server | module/index.js | JavaScript | mit | 1,812 |
namespace SalesDatabase.Models
{
using System.Collections.Generic;
public class StoreLocation
{
public StoreLocation()
{
this.SalesInStore = new HashSet<Sale>();
}
public int Id { get; set; }
public string LocationName { get; set; }
public ICollection<Sale> SalesInStore { get; set; }
}
} | sevdalin/Software-University-SoftUni | Db Advanced - EF Core/04. EntityFramework Code-First Advanced/SalesDatabase/Models/StoreLocation.cs | C# | mit | 371 |
# -*- coding:utf-8 -*-
from re import sub
from itertools import islice
'''
如何调整字符串的文本格式
'''
# 将日志文件中的日期格式转变为美国日期格式mm/dd/yyyy
# 使用正则表达式模块中的sub函数进行替换字符串
with open("./log.log","r") as f:
for line in islice(f,0,None):
#print sub("(\d{4})-(\d{2})-(\d{2})",r"\2/\3/\1",line)
# 可以为每个匹配组起一个别名
print sub("(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})",r"\g<month>/\g<day>/\g<>",line)
| liuhll/BlogAndArticle | Notes/Python/src/exercise/string_repalce_by_resub.py | Python | mit | 537 |
version https://git-lfs.github.com/spec/v1
oid sha256:054dbc79bbfc64911008a1e140813a8705dfc5cff35cbffd8bf7bc1f74c446b6
size 5257
| yogeshsaroya/new-cdnjs | ajax/libs/flot/0.8.0/jquery.flot.fillbetween.js | JavaScript | mit | 129 |
module Supa
class Builder
COMMANDS_WITH_DEFAULT_INTERFACE = %w(attribute virtual object namespace collection append).freeze
def initialize(subject, representer:, tree:)
@subject = subject
@representer = representer
@tree = tree
end
COMMANDS_WITH_DEFAULT_INTERFACE.each do |command|
klass = Supa::Commands.const_get(command.capitalize)
define_method(command) do |name, **options, &block|
klass.new(@subject,
representer: @representer,
tree: @tree,
name: name,
options: options,
&block).represent
end
end
def attributes(*names, **options)
Supa::Commands::Attributes.new(
@subject, representer: @representer, tree: @tree, name: names, options: options
).represent
end
def to_hash
@tree.to_hash
end
def to_json
Oj.dump(to_hash, mode: :strict)
end
end
end
| dasnotme/supa | lib/supa/builder.rb | Ruby | mit | 931 |
define(["widgetjs/widgetjs", "lodash", "jquery", "prettify", "code", "bootstrap"], function(widgetjs, lodash, jQuery, prettify, code) {
var examples = {};
examples.modals = code({
group: "Modals",
label: "Modals",
links: ["http://getbootstrap.com/javascript/#modals"],
example : function(html) {
// Modal
html.div({"class": "clearfix bs-example-modal"},
html.div({ klass: "modal"},
html.div({ klass: "modal-dialog"},
html.div({ klass: "modal-content"},
html.div({ klass: "modal-header"},
html.button({ type: "button", klass: "close", "data-dismiss": "modal", "aria-hidden": "true"},
"×"
),
html.h4({ klass: "modal-title"},
"Modal title"
)
),
html.div({ klass: "modal-body"},
html.p(
"One fine body…"
)
),
html.div({ klass: "modal-footer"},
html.button({ type: "button", klass: "btn btn-default", "data-dismiss": "modal"},
"Close"
),
html.button({ type: "button", klass: "btn btn-primary"},
"Save changes"
)
)
)
)
)
);
}
});
examples.modalsDemo = code({
group: "Modals",
label: "Live Demo",
links: ["http://getbootstrap.com/javascript/#modals"],
example : function(html) {
// Modal
html.div({ id: "myModal", klass: "modal fade"},
html.div({ klass: "modal-dialog"},
html.div({ klass: "modal-content"},
html.div({ klass: "modal-header"},
html.button({ type: "button", klass: "close", "data-dismiss": "modal", "aria-hidden": "true"},
"×"
),
html.h4({ klass: "modal-title"},
"Modal title"
)
),
html.div({ klass: "modal-body"},
html.p(
"One fine body…"
)
),
html.div({ klass: "modal-footer"},
html.button({ type: "button", klass: "btn btn-default", "data-dismiss": "modal"},
"Close"
),
html.button({ type: "button", klass: "btn btn-primary"},
"Save changes"
)
)
)
)
);
html.button({ klass: "btn btn-primary btn-lg", "data-toggle": "modal", "data-target": "#myModal"}, "Show modal");
}
});
examples.toolTips = code({
group: "Tooltips",
label: "Live Demo",
links: ["http://getbootstrap.com/javascript/#tooltips"],
example : function(html) {
// TOOLTIPS
html.div({ klass: "tooltip-demo"},
html.div({ klass: "bs-example-tooltips"},
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "left", title: "", "data-original-title": "Tooltip on left"},
"Tooltip on left"
),
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "top", title: "", "data-original-title": "Tooltip on top"},
"Tooltip on top"
),
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "bottom", title: "", "data-original-title": "Tooltip on bottom"},
"Tooltip on bottom"
),
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "right", title: "", "data-original-title": "Tooltip on right"},
"Tooltip on right"
)
)
);
jQuery(".bs-example-tooltips").tooltip();
}
});
examples.popovers = code({
group: "Popovers",
label: "Popovers",
links: ["http://getbootstrap.com/javascript/#popovers"],
example : function(html) {
// Popovers
html.div({ klass: "bs-example-popovers"},
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "left", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Left"
),
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "top", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Top"
),
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "bottom", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Bottom"
),
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "right", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Right"
)
);
jQuery(".bs-example-popovers button").popover();
}
});
examples.buttonsCheckbox = code({
group: "Buttons",
label: "Checkbox",
links: ["http://getbootstrap.com/javascript/#buttons"],
example : function(html) {
html.div({ style: "padding-bottom: 24px;"},
html.div({ klass: "btn-group", "data-toggle": "buttons"},
html.label({ klass: "btn btn-primary"},
html.input({ type: "checkbox"}),
"Option 1"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "checkbox"}),
"Option 2"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "checkbox"}),
"Option 3"
)
)
);
}
});
examples.buttonsRadio= code({
group: "Buttons",
label: "Radio",
links: ["http://getbootstrap.com/javascript/#buttons"],
example : function(html) {
html.div({ style: "padding-bottom: 24px;"},
html.div({ klass: "btn-group", "data-toggle": "buttons"},
html.label({ klass: "btn btn-primary"},
html.input({ type: "radio"}),
"Option 1"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "radio"}),
"Option 2"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "radio"}),
"Option 3"
)
)
);
}
});
examples.collapse = code({
group: "Collapse",
label: "Collapse",
links: ["http://getbootstrap.com/javascript/#collapse"],
example : function(html) {
html.div({ klass: "panel-group", id: "accordion"},
html.div({ klass: "panel panel-default"},
html.div({ klass: "panel-heading"},
html.h4({ klass: "panel-title"},
html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseOne"},
"Heading #1"
)
)
),
html.div({ id: "collapseOne", klass: "panel-collapse collapse in"},
html.div({ klass: "panel-body"},
"Content"
)
)
),
html.div({ klass: "panel panel-default"},
html.div({ klass: "panel-heading"},
html.h4({ klass: "panel-title"},
html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseTwo"},
"Heading #2"
)
)
),
html.div({ id: "collapseTwo", klass: "panel-collapse collapse"},
html.div({ klass: "panel-body"},
"Content"
)
)
),
html.div({ klass: "panel panel-default"},
html.div({ klass: "panel-heading"},
html.h4({ klass: "panel-title"},
html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseThree"},
"Heading #2"
)
)
),
html.div({ id: "collapseThree", klass: "panel-collapse collapse"},
html.div({ klass: "panel-body"},
"Content"
)
)
)
);
}
});
return examples;
}); | foretagsplatsen/widget-js | sample/bootstrap/javascriptExamples.js | JavaScript | mit | 10,606 |
class AddCorrectAnswerToQuestions < ActiveRecord::Migration
def change
add_column :questions, :correct_answer, :integer, :default => nil
end
end
| lowellmower/star_overflow | db/migrate/20150711152543_add_correct_answer_to_questions.rb | Ruby | mit | 153 |
module.exports = require('./lib/dustjs-browserify'); | scottbrady/dustjs-browserify | index.js | JavaScript | mit | 52 |
namespace GE.WebUI.ViewModels
{
public sealed class VMGameMenuEmptyGame
{
public string IconPath { get; set; }
public string GoodImagePath { get; set; }
public string BadImagePath { get; set; }
}
} | simlex-titul2005/game-exe.com | GE.WebUI/ViewModels/VMGameMenuEmptyGame.cs | C# | mit | 236 |
version https://git-lfs.github.com/spec/v1
oid sha256:94e212e6fc0c837cd9fff7fca8feff0187a0a22a97c7bd4c6d8f05c5cc358519
size 3077
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.16.0/scrollview-list/scrollview-list.js | JavaScript | mit | 129 |
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_IMPL_HTTP_SYNC_CONNECTION_20100601
#define BOOST_NETWORK_PROTOCOL_HTTP_IMPL_HTTP_SYNC_CONNECTION_20100601
// Copyright 2013 Google, Inc.
// Copyright 2010 (C) Dean Michael Berris
// Copyright 2010 (C) Sinefunc, Inc.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <iterator>
#include <functional>
#include <asio/deadline_timer.hpp>
#include <asio/streambuf.hpp>
#include <boost/network/protocol/http/algorithms/linearize.hpp>
#include <boost/network/protocol/http/response.hpp>
#include <boost/network/protocol/http/traits/resolver_policy.hpp>
#include <boost/network/traits/string.hpp>
namespace boost {
namespace network {
namespace http {
namespace impl {
template <class Tag, unsigned version_major, unsigned version_minor>
struct sync_connection_base_impl;
template <class Tag, unsigned version_major, unsigned version_minor>
struct sync_connection_base;
template <class Tag, unsigned version_major, unsigned version_minor>
struct http_sync_connection
: public virtual sync_connection_base<Tag, version_major, version_minor>,
sync_connection_base_impl<Tag, version_major, version_minor>,
std::enable_shared_from_this<
http_sync_connection<Tag, version_major, version_minor> > {
typedef typename resolver_policy<Tag>::type resolver_base;
typedef typename resolver_base::resolver_type resolver_type;
typedef typename string<Tag>::type string_type;
typedef std::function<typename resolver_base::resolver_iterator_pair(
resolver_type&, string_type const&, string_type const&)>
resolver_function_type;
typedef http_sync_connection<Tag, version_major, version_minor> this_type;
typedef sync_connection_base_impl<Tag, version_major, version_minor>
connection_base;
typedef std::function<bool(string_type&)> body_generator_function_type;
http_sync_connection(resolver_type& resolver, resolver_function_type resolve,
int timeout)
: connection_base(),
timeout_(timeout),
timer_(resolver.get_io_service()),
resolver_(resolver),
resolve_(std::move(resolve)),
socket_(resolver.get_io_service()) {}
void init_socket(string_type const& hostname, string_type const& port) {
connection_base::init_socket(socket_, resolver_, hostname, port, resolve_);
}
void send_request_impl(string_type const& method,
basic_request<Tag> const& request_,
body_generator_function_type generator) {
asio::streambuf request_buffer;
linearize(
request_, method, version_major, version_minor,
std::ostreambuf_iterator<typename char_<Tag>::type>(&request_buffer));
connection_base::send_request_impl(socket_, method, request_buffer);
if (generator) {
string_type chunk;
while (generator(chunk)) {
std::copy(chunk.begin(), chunk.end(),
std::ostreambuf_iterator<typename char_<Tag>::type>(
&request_buffer));
chunk.clear();
connection_base::send_request_impl(socket_, method, request_buffer);
}
}
if (timeout_ > 0) {
timer_.expires_from_now(boost::posix_time::seconds(timeout_));
auto self = this->shared_from_this();
timer_.async_wait([=] (std::error_code const &ec) {
self->handle_timeout(ec);
});
}
}
void read_status(basic_response<Tag>& response_,
asio::streambuf& response_buffer) {
connection_base::read_status(socket_, response_, response_buffer);
}
void read_headers(basic_response<Tag>& response,
asio::streambuf& response_buffer) {
connection_base::read_headers(socket_, response, response_buffer);
}
void read_body(basic_response<Tag>& response_,
asio::streambuf& response_buffer) {
connection_base::read_body(socket_, response_, response_buffer);
typename headers_range<basic_response<Tag> >::type connection_range =
headers(response_)["Connection"];
if (version_major == 1 && version_minor == 1 &&
!boost::empty(connection_range) &&
boost::iequals(std::begin(connection_range)->second, "close")) {
close_socket();
} else if (version_major == 1 && version_minor == 0) {
close_socket();
}
}
bool is_open() { return socket_.is_open(); }
void close_socket() {
timer_.cancel();
if (!is_open()) {
return;
}
std::error_code ignored;
socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignored);
if (ignored) {
return;
}
socket_.close(ignored);
}
private:
void handle_timeout(std::error_code const& ec) {
if (!ec) {
close_socket();
}
}
int timeout_;
asio::deadline_timer timer_;
resolver_type& resolver_;
resolver_function_type resolve_;
asio::ip::tcp::socket socket_;
};
} // namespace impl
} // namespace http
} // namespace network
} // namespace boost
#endif // BOOST_NETWORK_PROTOCOL_HTTP_IMPL_HTTP_SYNC_CONNECTION_20100
| medsouz/AnvilClient | AnvilEldorado/Depends/Include/boost/network/protocol/http/client/connection/sync_normal.hpp | C++ | mit | 5,139 |
import React from 'react'
import Icon from 'react-icon-base'
const IoTshirtOutline = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m11.4 6.7l-8.1 2.4 0.8 2.5 3.1-0.3 3-0.4-0.2 3-1.1 19.9h17.2l-1.1-19.9-0.2-3 3 0.4 3.1 0.3 0.8-2.5-8.1-2.4c-0.5 0.6-1 1.1-1.6 1.5-1.2 0.8-2.7 1.2-4.5 1.2-2.7-0.1-4.6-0.9-6.1-2.7z m11.1-2.9l12.5 3.7-2.5 6.9-5-0.6 1.3 22.5h-22.5l1.2-22.5-5 0.6-2.5-6.9 12.5-3.7c1.1 2.1 2.4 3 5 3.1 2.6 0 3.9-1 5-3.1z"/></g>
</Icon>
)
export default IoTshirtOutline
| bengimbel/Solstice-React-Contacts-Project | node_modules/react-icons/io/tshirt-outline.js | JavaScript | mit | 511 |
import {NgbCalendarIslamicCivil} from './ngb-calendar-islamic-civil';
import {NgbDate} from '../ngb-date';
import {Injectable} from '@angular/core';
/**
* Umalqura calendar is one type of Hijri calendars used in islamic countries.
* This Calendar is used by Saudi Arabia for administrative purpose.
* Unlike tabular calendars, the algorithm involves astronomical calculation, but it's still deterministic.
* http://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types
*/
const GREGORIAN_FIRST_DATE = new Date(1882, 10, 12);
const GREGORIAN_LAST_DATE = new Date(2174, 10, 25);
const HIJRI_BEGIN = 1300;
const HIJRI_END = 1600;
const ONE_DAY = 1000 * 60 * 60 * 24;
const MONTH_LENGTH = [
// 1300-1304
'101010101010', '110101010100', '111011001001', '011011010100', '011011101010',
// 1305-1309
'001101101100', '101010101101', '010101010101', '011010101001', '011110010010',
// 1310-1314
'101110101001', '010111010100', '101011011010', '010101011100', '110100101101',
// 1315-1319
'011010010101', '011101001010', '101101010100', '101101101010', '010110101101',
// 1320-1324
'010010101110', '101001001111', '010100010111', '011010001011', '011010100101',
// 1325-1329
'101011010101', '001011010110', '100101011011', '010010011101', '101001001101',
// 1330-1334
'110100100110', '110110010101', '010110101100', '100110110110', '001010111010',
// 1335-1339
'101001011011', '010100101011', '101010010101', '011011001010', '101011101001',
// 1340-1344
'001011110100', '100101110110', '001010110110', '100101010110', '101011001010',
// 1345-1349
'101110100100', '101111010010', '010111011001', '001011011100', '100101101101',
// 1350-1354
'010101001101', '101010100101', '101101010010', '101110100101', '010110110100',
// 1355-1359
'100110110110', '010101010111', '001010010111', '010101001011', '011010100011',
// 1360-1364
'011101010010', '101101100101', '010101101010', '101010101011', '010100101011',
// 1365-1369
'110010010101', '110101001010', '110110100101', '010111001010', '101011010110',
// 1370-1374
'100101010111', '010010101011', '100101001011', '101010100101', '101101010010',
// 1375-1379
'101101101010', '010101110101', '001001110110', '100010110111', '010001011011',
// 1380-1384
'010101010101', '010110101001', '010110110100', '100111011010', '010011011101',
// 1385-1389
'001001101110', '100100110110', '101010101010', '110101010100', '110110110010',
// 1390-1394
'010111010101', '001011011010', '100101011011', '010010101011', '101001010101',
// 1395-1399
'101101001001', '101101100100', '101101110001', '010110110100', '101010110101',
// 1400-1404
'101001010101', '110100100101', '111010010010', '111011001001', '011011010100',
// 1405-1409
'101011101001', '100101101011', '010010101011', '101010010011', '110101001001',
// 1410-1414
'110110100100', '110110110010', '101010111001', '010010111010', '101001011011',
// 1415-1419
'010100101011', '101010010101', '101100101010', '101101010101', '010101011100',
// 1420-1424
'010010111101', '001000111101', '100100011101', '101010010101', '101101001010',
// 1425-1429
'101101011010', '010101101101', '001010110110', '100100111011', '010010011011',
// 1430-1434
'011001010101', '011010101001', '011101010100', '101101101010', '010101101100',
// 1435-1439
'101010101101', '010101010101', '101100101001', '101110010010', '101110101001',
// 1440-1444
'010111010100', '101011011010', '010101011010', '101010101011', '010110010101',
// 1445-1449
'011101001001', '011101100100', '101110101010', '010110110101', '001010110110',
// 1450-1454
'101001010110', '111001001101', '101100100101', '101101010010', '101101101010',
// 1455-1459
'010110101101', '001010101110', '100100101111', '010010010111', '011001001011',
// 1460-1464
'011010100101', '011010101100', '101011010110', '010101011101', '010010011101',
// 1465-1469
'101001001101', '110100010110', '110110010101', '010110101010', '010110110101',
// 1470-1474
'001011011010', '100101011011', '010010101101', '010110010101', '011011001010',
// 1475-1479
'011011100100', '101011101010', '010011110101', '001010110110', '100101010110',
// 1480-1484
'101010101010', '101101010100', '101111010010', '010111011001', '001011101010',
// 1485-1489
'100101101101', '010010101101', '101010010101', '101101001010', '101110100101',
// 1490-1494
'010110110010', '100110110101', '010011010110', '101010010111', '010101000111',
// 1495-1499
'011010010011', '011101001001', '101101010101', '010101101010', '101001101011',
// 1500-1504
'010100101011', '101010001011', '110101000110', '110110100011', '010111001010',
// 1505-1509
'101011010110', '010011011011', '001001101011', '100101001011', '101010100101',
// 1510-1514
'101101010010', '101101101001', '010101110101', '000101110110', '100010110111',
// 1515-1519
'001001011011', '010100101011', '010101100101', '010110110100', '100111011010',
// 1520-1524
'010011101101', '000101101101', '100010110110', '101010100110', '110101010010',
// 1525-1529
'110110101001', '010111010100', '101011011010', '100101011011', '010010101011',
// 1530-1534
'011001010011', '011100101001', '011101100010', '101110101001', '010110110010',
// 1535-1539
'101010110101', '010101010101', '101100100101', '110110010010', '111011001001',
// 1540-1544
'011011010010', '101011101001', '010101101011', '010010101011', '101001010101',
// 1545-1549
'110100101001', '110101010100', '110110101010', '100110110101', '010010111010',
// 1550-1554
'101000111011', '010010011011', '101001001101', '101010101010', '101011010101',
// 1555-1559
'001011011010', '100101011101', '010001011110', '101000101110', '110010011010',
// 1560-1564
'110101010101', '011010110010', '011010111001', '010010111010', '101001011101',
// 1565-1569
'010100101101', '101010010101', '101101010010', '101110101000', '101110110100',
// 1570-1574
'010110111001', '001011011010', '100101011010', '101101001010', '110110100100',
// 1575-1579
'111011010001', '011011101000', '101101101010', '010101101101', '010100110101',
// 1580-1584
'011010010101', '110101001010', '110110101000', '110111010100', '011011011010',
// 1585-1589
'010101011011', '001010011101', '011000101011', '101100010101', '101101001010',
// 1590-1594
'101110010101', '010110101010', '101010101110', '100100101110', '110010001111',
// 1595-1599
'010100100111', '011010010101', '011010101010', '101011010110', '010101011101',
// 1600
'001010011101'
];
function getDaysDiff(date1: Date, date2: Date): number {
const diff = Math.abs(date1.getTime() - date2.getTime());
return Math.round(diff / ONE_DAY);
}
@Injectable()
export class NgbCalendarIslamicUmalqura extends NgbCalendarIslamicCivil {
/**
* Returns the equivalent islamic(Umalqura) date value for a give input Gregorian date.
* `gdate` is s JS Date to be converted to Hijri.
*/
fromGregorian(gDate: Date): NgbDate {
let hDay = 1, hMonth = 0, hYear = 1300;
let daysDiff = getDaysDiff(gDate, GREGORIAN_FIRST_DATE);
if (gDate.getTime() - GREGORIAN_FIRST_DATE.getTime() >= 0 && gDate.getTime() - GREGORIAN_LAST_DATE.getTime() <= 0) {
let year = 1300;
for (let i = 0; i < MONTH_LENGTH.length; i++, year++) {
for (let j = 0; j < 12; j++) {
let numOfDays = +MONTH_LENGTH[i][j] + 29;
if (daysDiff <= numOfDays) {
hDay = daysDiff + 1;
if (hDay > numOfDays) {
hDay = 1;
j++;
}
if (j > 11) {
j = 0;
year++;
}
hMonth = j;
hYear = year;
return new NgbDate(hYear, hMonth + 1, hDay);
}
daysDiff = daysDiff - numOfDays;
}
}
} else {
return super.fromGregorian(gDate);
}
}
/**
* Converts the current Hijri date to Gregorian.
*/
toGregorian(hDate: NgbDate): Date {
const hYear = hDate.year;
const hMonth = hDate.month - 1;
const hDay = hDate.day;
let gDate = new Date(GREGORIAN_FIRST_DATE);
let dayDiff = hDay - 1;
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
for (let y = 0; y < hYear - HIJRI_BEGIN; y++) {
for (let m = 0; m < 12; m++) {
dayDiff += +MONTH_LENGTH[y][m] + 29;
}
}
for (let m = 0; m < hMonth; m++) {
dayDiff += +MONTH_LENGTH[hYear - HIJRI_BEGIN][m] + 29;
}
gDate.setDate(GREGORIAN_FIRST_DATE.getDate() + dayDiff);
} else {
gDate = super.toGregorian(hDate);
}
return gDate;
}
/**
* Returns the number of days in a specific Hijri hMonth.
* `hMonth` is 1 for Muharram, 2 for Safar, etc.
* `hYear` is any Hijri hYear.
*/
getDaysPerMonth(hMonth: number, hYear: number): number {
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
const pos = hYear - HIJRI_BEGIN;
return +MONTH_LENGTH[pos][hMonth - 1] + 29;
}
return super.getDaysPerMonth(hMonth, hYear);
}
}
| ktriek/ng-bootstrap | src/datepicker/hijri/ngb-calendar-islamic-umalqura.ts | TypeScript | mit | 9,063 |
declare module "react-apollo" {
declare function graphql(query: Object, options: Object): Function;
}
| NewSpring/apollos-core | .types/react-apollo.js | JavaScript | mit | 104 |
<?php
namespace Chamilo\Application\Weblcms\Tool\Implementation\ExamAssignment\Ajax\Component;
use Chamilo\Application\Weblcms\Tool\Implementation\ExamAssignment\Ajax\Manager;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* @package Chamilo\Application\Weblcms\Tool\Implementation\ExamAssignment\Ajax\Component
*
* @author Stefan Gabriëls - Hogeschool Gent
*/
class ListUsersComponent extends Manager
{
/**
* @return string
*/
function run()
{
try
{
$publication = $this->getAjaxComponent()->getContentObjectPublication();
$users = $this->getUserOvertimeService()->getUsersByPublication($publication);
return new JsonResponse([self::PARAM_RESULTS => $users]);
}
catch(\Exception $ex)
{
$this->getExceptionLogger()->logException($ex);
return new JsonResponse([self::PARAM_ERROR_MESSAGE => $ex->getMessage()], 500);
}
}
}
| forelo/cosnics | src/Chamilo/Application/Weblcms/Tool/Implementation/ExamAssignment/Ajax/Component/ListUsersComponent.php | PHP | mit | 970 |
/*
* deferred.js
*
* Copyright 2011, HeavyLifters Network Ltd. All rights reserved.
*/
;(function() {
var DeferredAPI = {
deferred: deferred,
all: all,
Deferred: Deferred,
DeferredList: DeferredList,
wrapResult: wrapResult,
wrapFailure: wrapFailure,
Failure: Failure
}
// CommonJS module support
if (typeof module !== 'undefined') {
var DeferredURLRequest = require('./DeferredURLRequest')
for (var k in DeferredURLRequest) {
DeferredAPI[k] = DeferredURLRequest[k]
}
module.exports = DeferredAPI
}
// Browser API
else if (typeof window !== 'undefined') {
window.deferred = DeferredAPI
}
// Fake out console if necessary
if (typeof console === 'undefined') {
var global = function() { return this || (1,eval)('this') }
;(function() {
var noop = function(){}
global().console = { log: noop, warn: noop, error: noop, dir: noop }
}())
}
function wrapResult(result) {
return new Deferred().resolve(result)
}
function wrapFailure(error) {
return new Deferred().reject(error)
}
function Failure(v) { this.value = v }
// Crockford style constructor
function deferred(t) { return new Deferred(t) }
function Deferred(canceller) {
this.called = false
this.running = false
this.result = null
this.pauseCount = 0
this.callbacks = []
this.verbose = false
this._canceller = canceller
// If this Deferred is cancelled and the creator of this Deferred
// didn't cancel it, then they may not know about the cancellation and
// try to resolve or reject it as well. This flag causes the
// "already called" error that resolve() or reject() normally throws
// to be suppressed once.
this._suppressAlreadyCalled = false
}
if (typeof Object.defineProperty === 'function') {
var _consumeThrownExceptions = true
Object.defineProperty(Deferred, 'consumeThrownExceptions', {
enumerable: false,
set: function(v) { _consumeThrownExceptions = v },
get: function() { return _consumeThrownExceptions }
})
} else {
Deferred.consumeThrownExceptions = true
}
Deferred.prototype.cancel = function() {
if (!this.called) {
if (typeof this._canceller === 'function') {
this._canceller(this)
} else {
this._suppressAlreadyCalled = true
}
if (!this.called) {
this.reject('cancelled')
}
} else if (this.result instanceof Deferred) {
this.result.cancel()
}
}
Deferred.prototype.then = function(callback, errback) {
this.callbacks.push({callback: callback, errback: errback})
if (this.called) _run(this)
return this
}
Deferred.prototype.fail = function(errback) {
this.callbacks.push({callback: null, errback: errback})
if (this.called) _run(this)
return this
}
Deferred.prototype.both = function(callback) {
return this.then(callback, callback)
}
Deferred.prototype.resolve = function(result) {
_startRun(this, result)
return this
}
Deferred.prototype.reject = function(err) {
if (!(err instanceof Failure)) {
err = new Failure(err)
}
_startRun(this, err)
return this
}
Deferred.prototype.pause = function() {
this.pauseCount += 1
if (this.extra) {
console.log('Deferred.pause ' + this.pauseCount + ': ' + this.extra)
}
return this
}
Deferred.prototype.unpause = function() {
this.pauseCount -= 1
if (this.extra) {
console.log('Deferred.unpause ' + this.pauseCount + ': ' + this.extra)
}
if (this.pauseCount <= 0 && this.called) {
_run(this)
}
return this
}
// For debugging
Deferred.prototype.inspect = function(extra, cb) {
this.extra = extra
var self = this
return this.then(function(r) {
console.log('Deferred.inspect resolved: ' + self.extra)
console.dir(r)
return r
}, function(e) {
console.log('Deferred.inspect rejected: ' + self.extra)
console.dir(e)
return e
})
}
/// A couple of sugary methods
Deferred.prototype.thenReturn = function(result) {
return this.then(function(_) { return result })
}
Deferred.prototype.thenCall = function(f) {
return this.then(function(result) {
f(result)
return result
})
}
Deferred.prototype.failReturn = function(result) {
return this.fail(function(_) { return result })
}
Deferred.prototype.failCall = function(f) {
return this.fail(function(result) {
f(result)
return result
})
}
function _continue(d, newResult) {
d.result = newResult
d.unpause()
return d.result
}
function _nest(outer) {
outer.result.both(function(newResult) {
return _continue(outer, newResult)
})
}
function _startRun(d, result) {
if (d.called) {
if (d._suppressAlreadyCalled) {
d._suppressAlreadyCalled = false
return
}
throw new Error("Already resolved Deferred: " + d)
}
d.called = true
d.result = result
if (d.result instanceof Deferred) {
d.pause()
_nest(d)
return
}
_run(d)
}
function _run(d) {
if (d.running) return
var link, status, fn
if (d.pauseCount > 0) return
while (d.callbacks.length > 0) {
link = d.callbacks.shift()
status = (d.result instanceof Failure) ? 'errback' : 'callback'
fn = link[status]
if (typeof fn !== 'function') continue
try {
d.running = true
d.result = fn(d.result)
d.running = false
if (d.result instanceof Deferred) {
d.pause()
_nest(d)
return
}
} catch (e) {
if (Deferred.consumeThrownExceptions) {
d.running = false
var f = new Failure(e)
f.source = f.source || status
d.result = f
if (d.verbose) {
console.warn('uncaught error in deferred ' + status + ': ' + e.message)
console.warn('Stack: ' + e.stack)
}
} else {
throw e
}
}
}
}
/// DeferredList / all
function all(ds, opts) { return new DeferredList(ds, opts) }
function DeferredList(ds, opts) {
opts = opts || {}
Deferred.call(this)
this._deferreds = ds
this._finished = 0
this._length = ds.length
this._results = []
this._fireOnFirstResult = opts.fireOnFirstResult
this._fireOnFirstError = opts.fireOnFirstError
this._consumeErrors = opts.consumeErrors
this._cancelDeferredsWhenCancelled = opts.cancelDeferredsWhenCancelled
if (this._length === 0 && !this._fireOnFirstResult) {
this.resolve(this._results)
}
for (var i = 0, n = this._length; i < n; ++i) {
ds[i].both(deferredListCallback(this, i))
}
}
if (typeof Object.create === 'function') {
DeferredList.prototype = Object.create(Deferred.prototype, {
constructor: { value: DeferredList, enumerable: false }
})
} else {
DeferredList.prototype = new Deferred()
DeferredList.prototype.constructor = DeferredList
}
DeferredList.prototype.cancelDeferredsWhenCancelled = function() {
this._cancelDeferredsWhenCancelled = true
}
var _deferredCancel = Deferred.prototype.cancel
DeferredList.prototype.cancel = function() {
_deferredCancel.call(this)
if (this._cancelDeferredsWhenCancelled) {
for (var i = 0; i < this._length; ++i) {
this._deferreds[i].cancel()
}
}
}
function deferredListCallback(d, i) {
return function(result) {
var isErr = result instanceof Failure
, myResult = (isErr && d._consumeErrors) ? null : result
// Support nesting
if (result instanceof Deferred) {
result.both(deferredListCallback(d, i))
return
}
d._results[i] = myResult
d._finished += 1
if (!d.called) {
if (d._fireOnFirstResult && !isErr) {
d.resolve(result)
} else if (d._fireOnFirstError && isErr) {
d.reject(result)
} else if (d._finished === d._length) {
d.resolve(d._results)
}
}
return myResult
}
}
}()) | heavylifters/deferred-js | lib/deferred.js | JavaScript | mit | 8,895 |
'use strict';
var request = require('request');
var querystring = require('querystring');
var FirebaseError = require('./error');
var RSVP = require('rsvp');
var _ = require('lodash');
var logger = require('./logger');
var utils = require('./utils');
var responseToError = require('./responseToError');
var refreshToken;
var commandScopes;
var scopes = require('./scopes');
var CLI_VERSION = require('../package.json').version;
var _request = function(options) {
logger.debug('>>> HTTP REQUEST',
options.method,
options.url,
options.body || options.form || ''
);
return new RSVP.Promise(function(resolve, reject) {
var req = request(options, function(err, response, body) {
if (err) {
return reject(new FirebaseError('Server Error. ' + err.message, {
original: err,
exit: 2
}));
}
logger.debug('<<< HTTP RESPONSE', response.statusCode, response.headers);
if (response.statusCode >= 400) {
logger.debug('<<< HTTP RESPONSE BODY', response.body);
if (!options.resolveOnHTTPError) {
return reject(responseToError(response, body, options));
}
}
return resolve({
status: response.statusCode,
response: response,
body: body
});
});
if (_.size(options.files) > 0) {
var form = req.form();
_.forEach(options.files, function(details, param) {
form.append(param, details.stream, {
knownLength: details.knownLength,
filename: details.filename,
contentType: details.contentType
});
});
}
});
};
var _appendQueryData = function(path, data) {
if (data && _.size(data) > 0) {
path += _.includes(path, '?') ? '&' : '?';
path += querystring.stringify(data);
}
return path;
};
var api = {
// "In this context, the client secret is obviously not treated as a secret"
// https://developers.google.com/identity/protocols/OAuth2InstalledApp
billingOrigin: utils.envOverride('FIREBASE_BILLING_URL', 'https://cloudbilling.googleapis.com'),
clientId: utils.envOverride('FIREBASE_CLIENT_ID', '563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com'),
clientSecret: utils.envOverride('FIREBASE_CLIENT_SECRET', 'j9iVZfS8kkCEFUPaAeJV0sAi'),
cloudloggingOrigin: utils.envOverride('FIREBASE_CLOUDLOGGING_URL', 'https://logging.googleapis.com'),
adminOrigin: utils.envOverride('FIREBASE_ADMIN_URL', 'https://admin.firebase.com'),
apikeysOrigin: utils.envOverride('FIREBASE_APIKEYS_URL', 'https://apikeys.googleapis.com'),
appengineOrigin: utils.envOverride('FIREBASE_APPENGINE_URL', 'https://appengine.googleapis.com'),
authOrigin: utils.envOverride('FIREBASE_AUTH_URL', 'https://accounts.google.com'),
consoleOrigin: utils.envOverride('FIREBASE_CONSOLE_URL', 'https://console.firebase.google.com'),
deployOrigin: utils.envOverride('FIREBASE_DEPLOY_URL', utils.envOverride('FIREBASE_UPLOAD_URL', 'https://deploy.firebase.com')),
functionsOrigin: utils.envOverride('FIREBASE_FUNCTIONS_URL', 'https://cloudfunctions.googleapis.com'),
googleOrigin: utils.envOverride('FIREBASE_TOKEN_URL', utils.envOverride('FIREBASE_GOOGLE_URL', 'https://www.googleapis.com')),
hostingOrigin: utils.envOverride('FIREBASE_HOSTING_URL', 'https://firebaseapp.com'),
realtimeOrigin: utils.envOverride('FIREBASE_REALTIME_URL', 'https://firebaseio.com'),
rulesOrigin: utils.envOverride('FIREBASE_RULES_URL', 'https://firebaserules.googleapis.com'),
runtimeconfigOrigin: utils.envOverride('FIREBASE_RUNTIMECONFIG_URL', 'https://runtimeconfig.googleapis.com'),
setToken: function(token) {
refreshToken = token;
},
setScopes: function(s) {
commandScopes = _.uniq(_.flatten([
scopes.EMAIL,
scopes.OPENID,
scopes.CLOUD_PROJECTS_READONLY,
scopes.FIREBASE_PLATFORM
].concat(s || [])));
logger.debug('> command requires scopes:', JSON.stringify(commandScopes));
},
getAccessToken: function() {
return require('./auth').getAccessToken(refreshToken, commandScopes);
},
addRequestHeaders: function(reqOptions) {
// Runtime fetch of Auth singleton to prevent circular module dependencies
_.set(reqOptions, ['headers', 'User-Agent'], 'FirebaseCLI/' + CLI_VERSION);
var auth = require('../lib/auth');
return auth.getAccessToken(refreshToken, commandScopes).then(function(result) {
_.set(reqOptions, 'headers.authorization', 'Bearer ' + result.access_token);
return reqOptions;
});
},
request: function(method, resource, options) {
options = _.extend({
data: {},
origin: api.adminOrigin, // default to hitting the admin backend
resolveOnHTTPError: false, // by default, status codes >= 400 leads to reject
json: true
}, options);
var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'];
if (validMethods.indexOf(method) < 0) {
method = 'GET';
}
var reqOptions = {
method: method
};
if (options.query) {
resource = _appendQueryData(resource, options.query);
}
if (method === 'GET') {
resource = _appendQueryData(resource, options.data);
} else {
if (_.size(options.data) > 0) {
reqOptions.body = options.data;
} else if (_.size(options.form) > 0) {
reqOptions.form = options.form;
}
}
reqOptions.url = options.origin + resource;
reqOptions.files = options.files;
reqOptions.resolveOnHTTPError = options.resolveOnHTTPError;
reqOptions.json = options.json;
if (options.auth === true) {
return api.addRequestHeaders(reqOptions).then(function(reqOptionsWithToken) {
return _request(reqOptionsWithToken);
});
}
return _request(reqOptions);
},
getProject: function(projectId) {
return api.request('GET', '/v1/projects/' + encodeURIComponent(projectId), {
auth: true
}).then(function(res) {
if (res.body && !res.body.error) {
return res.body;
}
return RSVP.reject(new FirebaseError('Server Error: Unexpected Response. Please try again', {
context: res,
exit: 2
}));
});
},
getProjects: function() {
return api.request('GET', '/v1/projects', {
auth: true
}).then(function(res) {
if (res.body && res.body.projects) {
return res.body.projects;
}
return RSVP.reject(new FirebaseError('Server Error: Unexpected Response. Please try again', {
context: res,
exit: 2
}));
});
}
};
module.exports = api;
| CharlesSanford/personal-site | node_modules/firebase-tools/lib/api.js | JavaScript | mit | 6,556 |
/**!
* urllib - test/fixtures/server.js
*
* Copyright(c) 2011 - 2014 fengmk2 and other contributors.
* MIT Licensed
*
* Authors:
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
*/
"use strict";
/**
* Module dependencies.
*/
var should = require('should');
var http = require('http');
var querystring = require('querystring');
var fs = require('fs');
var zlib = require('zlib');
var iconv = require('iconv-lite');
var server = http.createServer(function (req, res) {
// req.headers['user-agent'].should.match(/^node\-urllib\/\d+\.\d+\.\d+ node\//);
var chunks = [];
var size = 0;
req.on('data', function (buf) {
chunks.push(buf);
size += buf.length;
});
req.on('end', function () {
if (req.url === '/timeout') {
return setTimeout(function () {
res.end('timeout 500ms');
}, 500);
} else if (req.url === '/response_timeout') {
res.write('foo');
return setTimeout(function () {
res.end('timeout 700ms');
}, 700);
} else if (req.url === '/error') {
return res.destroy();
} else if (req.url === '/socket.destroy') {
res.write('foo haha\n');
setTimeout(function () {
res.write('foo haha 2');
setTimeout(function () {
res.destroy();
}, 300);
}, 200);
return;
} else if (req.url === '/socket.end') {
res.write('foo haha\n');
setTimeout(function () {
res.write('foo haha 2');
setTimeout(function () {
// res.end();
res.socket.end();
// res.socket.end('foosdfsdf');
}, 300);
}, 200);
return;
} else if (req.url === '/socket.end.error') {
res.write('foo haha\n');
setTimeout(function () {
res.write('foo haha 2');
setTimeout(function () {
res.socket.end('balabala');
}, 300);
}, 200);
return;
} else if (req.url === '/302') {
res.statusCode = 302;
res.setHeader('Location', '/204');
return res.end('Redirect to /204');
} else if (req.url === '/301') {
res.statusCode = 301;
res.setHeader('Location', '/204');
return res.end('I am 301 body');
} else if (req.url === '/303') {
res.statusCode = 303;
res.setHeader('Location', '/204');
return res.end('Redirect to /204');
} else if (req.url === '/307') {
res.statusCode = 307;
res.setHeader('Location', '/204');
return res.end('I am 307 body');
} else if (req.url === '/redirect_no_location') {
res.statusCode = 302;
return res.end('I am 302 body');
} else if (req.url === '/204') {
res.statusCode = 204;
return res.end();
} else if (req.url === '/loop_redirect') {
res.statusCode = 302;
res.setHeader('Location', '/loop_redirect');
return res.end('Redirect to /loop_redirect');
} else if (req.url === '/post') {
res.setHeader('X-Request-Content-Type', req.headers['content-type'] || '');
res.writeHeader(200);
return res.end(Buffer.concat(chunks));
} else if (req.url.indexOf('/get') === 0) {
res.writeHeader(200);
return res.end(req.url);
} else if (req.url === '/wrongjson') {
res.writeHeader(200);
return res.end(new Buffer('{"foo":""'));
} else if (req.url === '/wrongjson-gbk') {
res.setHeader('content-type', 'application/json; charset=gbk');
res.writeHeader(200);
return res.end(fs.readFileSync(__filename));
} else if (req.url === '/writestream') {
var s = fs.createReadStream(__filename);
return s.pipe(res);
} else if (req.url === '/auth') {
var auth = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString().split(':');
res.writeHeader(200);
return res.end(JSON.stringify({user: auth[0], password: auth[1]}));
} else if (req.url === '/stream') {
res.writeHeader(200, {
'Content-Length': String(size)
});
for (var i = 0; i < chunks.length; i++) {
res.write(chunks[i]);
}
res.end();
return;
} else if (req.url.indexOf('/json_mirror') === 0) {
res.setHeader('Content-Type', req.headers['content-type'] || 'application/json');
if (req.method === 'GET') {
res.end(JSON.stringify({
url: req.url,
data: Buffer.concat(chunks).toString(),
}));
} else {
res.end(JSON.stringify(JSON.parse(Buffer.concat(chunks))));
}
return;
} else if (req.url.indexOf('/no-gzip') === 0) {
fs.createReadStream(__filename).pipe(res);
return;
} else if (req.url.indexOf('/gzip') === 0) {
res.setHeader('Content-Encoding', 'gzip');
fs.createReadStream(__filename).pipe(zlib.createGzip()).pipe(res);
return;
} else if (req.url === '/ua') {
res.end(JSON.stringify(req.headers));
return;
} else if (req.url === '/gbk/json') {
res.setHeader('Content-Type', 'application/json;charset=gbk');
var content = iconv.encode(JSON.stringify({hello: '你好'}), 'gbk');
return res.end(content);
} else if (req.url === '/gbk/text') {
res.setHeader('Content-Type', 'text/plain;charset=gbk');
var content = iconv.encode('你好', 'gbk');
return res.end(content);
} else if (req.url === '/errorcharset') {
res.setHeader('Content-Type', 'text/plain;charset=notfound');
return res.end('你好');
}
var url = req.url.split('?');
var get = querystring.parse(url[1]);
var ret;
if (chunks.length > 0) {
ret = Buffer.concat(chunks).toString();
} else {
ret = '<html><head><meta http-equiv="Content-Type" content="text/html;charset=##{charset}##">...</html>';
}
chunks = [];
res.writeHead(get.code ? get.code : 200, {
'Content-Type': 'text/html',
});
res.end(ret.replace('##{charset}##', get.charset ? get.charset : ''));
});
});
module.exports = server;
| pmq20/urllib | test/fixtures/server.js | JavaScript | mit | 5,950 |
/*
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
Write a function:
int solution(int X, int Y, int D);
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
*/
// you can write to stdout for debugging purposes, e.g.
// printf("this is a debug message\n");
int solution(int X, int Y, int D) {
// write your code in C99
int diff=Y-X;
if(diff%D==0)
return diff/D;
else
return diff/D+1;
}
| anishacharya/Codility-Challenges | FrogJump.cpp | C++ | mit | 751 |
// Type definitions for @ag-grid-community/core v25.0.1
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
export declare function convertToSet<T>(list: T[]): Set<T>;
| ceolter/angular-grid | community-modules/core/dist/es6/utils/set.d.ts | TypeScript | mit | 214 |
package com.dubture.twig.core.model;
public interface IFunction extends ITwigCallable {
}
| gencer/Twig-Eclipse-Plugin | com.dubture.twig.core/src/com/dubture/twig/core/model/IFunction.java | Java | mit | 91 |
#!/usr/bin/env python
#
# GrovePi Example for using the Grove Slide Potentiometer (http://www.seeedstudio.com/wiki/Grove_-_Slide_Potentiometer)
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
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.
'''
import time
import grovepi
# Connect the Grove Slide Potentiometer to analog port A0
# OUT,LED,VCC,GND
slide = 0 # pin 1 (yellow wire)
# The device has an onboard LED accessible as pin 2 on port A0
# OUT,LED,VCC,GND
led = 1 # pin 2 (white wire)
grovepi.pinMode(slide,"INPUT")
grovepi.pinMode(led,"OUTPUT")
time.sleep(1)
while True:
try:
# Read sensor value from potentiometer
sensor_value = grovepi.analogRead(slide)
# Illuminate onboard LED
if sensor_value > 500:
grovepi.digitalWrite(led,1)
else:
grovepi.digitalWrite(led,0)
print("sensor_value =", sensor_value)
except IOError:
print ("Error")
| karan259/GrovePi | Software/Python/grove_slide_potentiometer.py | Python | mit | 2,307 |
package maritech.nei;
import mariculture.core.lib.Modules;
import mariculture.factory.Factory;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import codechicken.nei.api.API;
import codechicken.nei.api.IConfigureNEI;
public class MTNEIConfig implements IConfigureNEI {
@Override
public void loadConfig() {
if (Modules.isActive(Modules.factory)) {
API.hideItem(new ItemStack(Factory.customRFBlock, 1, OreDictionary.WILDCARD_VALUE));
}
}
@Override
public String getName() {
return "MariTech NEI";
}
@Override
public String getVersion() {
return "1.0";
}
}
| svgorbunov/Mariculture | src/main/java/maritech/nei/MTNEIConfig.java | Java | mit | 676 |
package tpe.exceptions.trycatchfinally;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import de.smits_net.games.framework.board.Board;
/**
* Spielfeld.
*/
public class GameBoard extends Board {
/** Sprite, das durch das Bild läuft. */
private Professor sprite;
/**
* Erzeugt ein neues Board.
*/
public GameBoard() {
// neues Spielfeld anlegen
super(10, new Dimension(400, 400), Color.BLACK);
// Sprite initialisieren
sprite = new Professor(this, new Point(300, 200));
}
/**
* Spielfeld neu zeichnen. Wird vom Framework aufgerufen.
*/
@Override
public void drawGame(Graphics g) {
sprite.draw(g, this);
}
/**
* Spielsituation updaten. Wird vom Framework aufgerufen.
*/
@Override
public boolean updateGame() {
sprite.move();
return sprite.isVisible();
}
}
| tpe-lecture/repo-27 | 06_ausnahmen/02_finally/src/tpe/exceptions/trycatchfinally/GameBoard.java | Java | mit | 955 |
<?= form_open('', array("class"=>"form-horizontal", "id"=>"frm_menu")); ?>
<div class="form-group <?= form_error('title') ? ' error' : ''; ?>">
<label for="title" class="control-label col-sm-2"><?= lang('menus_title'); ?></label>
<div class="col-sm-4">
<input type="hidden" id="menuid" name="menuid" value="<?php echo set_value('menuid', isset($data->id) ? $data->id : ''); ?>">
<input type="hidden" id="type" name="type" value="<?= isset($type) ? $type : 'add' ?>">
<input id="title" type="text" name="title" class="form-control" maxlength="100" value="<?php echo set_value('title', isset($data->title) ? $data->title : ''); ?>" />
</div>
<div class="col-sm-10 col-sm-offset-2">
<span class="help-inline"><?php echo form_error('title'); ?></span>
</div>
</div>
<div class="form-group <?= form_error('link') ? ' error' : ''; ?>">
<label for="link" class="control-label col-sm-2"><?= lang('menus_link'); ?></label>
<div class="col-sm-4">
<input id="link" type="text" name="link" class="form-control" maxlength="255" value="<?php echo set_value('link', isset($data->link) ? $data->link : ''); ?>" />
</div>
<div class="col-sm-10 col-sm-offset-2">
<span class="help-inline"><?php echo form_error('link'); ?></span>
</div>
</div>
<div class="form-group <?= form_error('icon') ? ' error' : ''; ?>">
<label for="icon" class="control-label col-sm-2"><?= lang('menus_icon'); ?></label>
<div class="col-sm-4">
<input id="icon" type="text" name="icon" class="form-control" maxlength="255" value="<?php echo set_value('icon', isset($data->icon) ? $data->icon : ''); ?>" />
<span>e.g. "fa fa-angle-right"</span>
</div>
<div class="col-sm-10 col-sm-offset-2">
<span class="help-inline"><?php echo form_error('icon'); ?></span>
</div>
</div>
<div class="form-group <?= form_error('target') ? ' error' : ''; ?>">
<label for="target" class="control-label col-sm-2"><?= lang('menus_target'); ?></label>
<div class="col-sm-3">
<select id="target" name="target" class="form-control">
<option value="sametab" <?php echo set_select('target', 'sametab', isset($data->target) && $data->target=="sametab"); ?>>Same Tab</option>
<option value="_blank" <?php echo set_select('target', '_blank', isset($data->target) && $data->target=="_blank"); ?>>New Tab</option>
</select>
</div>
<div class="col-sm-10 col-sm-offset-2">
<span class="help-inline"><?php echo form_error('target'); ?></span>
</div>
</div>
<div class="form-group <?= form_error('group_menu') ? ' error' : ''; ?>">
<label for="group_menu" class="control-label col-sm-2"><?= lang('menus_group'); ?></label>
<div class="col-sm-3">
<select id="group_menu" name="group_menu" class="form-control">
<?php foreach ($group_menus as $key => $gr) : ?>
<option value="<?= $gr->id; ?>" <?= set_select('group_menu', $gr->id, isset($data->group_menu) && $data->group_menu == $gr->id) ?>><?= $gr->group_name ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="col-sm-10 col-sm-offset-2">
<span class="help-inline"><?php echo form_error('group_menu'); ?></span>
</div>
</div>
<div class="form-group <?= form_error('parent_id') ? ' error' : ''; ?>">
<label for="parent_id" class="control-label col-sm-2"><?= lang('menus_parent'); ?></label>
<div class="col-sm-4">
<select id="parent_id" name="parent_id" class="form-control">
<option value="0">This is parent menu</option>
<?php foreach ($parents as $key => $parent) : ?>
<option value="<?= $parent->id; ?>" <?= set_select('parent_id', $parent->id, isset($data->parent_id) && $data->parent_id == $parent->id) ?>><?= $parent->title ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="col-sm-10 col-sm-offset-2">
<span class="help-inline"><?php echo form_error('parent_id'); ?></span>
</div>
</div>
<div class="form-group <?= form_error('permission_id') ? ' error' : ''; ?>">
<label for="permission_id" class="control-label col-sm-2"><?= lang('menus_permissions'); ?></label>
<div class="col-sm-4">
<select id="permission_id" name="permission_id" class="form-control">
<?php foreach ($permissions as $key => $permission) : ?>
<option value="<?= $permission->id_permission; ?>" <?= set_select('permission_id', $permission->id_permission, isset($data->permission_id) && $data->permission_id == $permission->id_permission) ?>><?= $permission->nm_permission ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="col-sm-10 col-sm-offset-2">
<span class="help-inline"><?php echo form_error('permission_id'); ?></span>
</div>
</div>
<div class="form-group ">
<label for="status" class="control-label col-sm-2"><?php echo lang('menus_status'); ?></label>
<div class="col-sm-2">
<select name="status" id="status" class="form-control">
<option value="1" <?php echo set_select('status', '1', isset($data->status) && $data->status == 1); ?>><?php echo lang('menus_active'); ?></option>
<option value="0" <?php echo set_select('status', '0', isset($data->status) && $data->status == 0); ?>><?php echo lang('menus_inactive'); ?></option>
</select>
</div>
</div>
<div class="form-group" style="margin-bottom: 5px;">
<div class="col-sm-offset-2 col-sm-6">
<input type="button" name="save" onclick="save_menu()" class="btn btn-primary btn-flat" value="<?php echo lang('menus_save'); ?>" />
<?php
echo lang('menus_or').' ' . "<input type='button' name='btn_cancel' class='btn btn-danger btn-flat' onclick='cancel()' value='".lang('menus_cancel')."' />";
?>
<div id='alert_edit' class='alert-success text-center col-md-5 pull-right' style="padding: 5px;display: none;">Menu saved</div>
</div>
</div>
<?= form_close();?>
<script type="text/javascript">
$().ready(function(){
var ns = $('ol.sortable').nestedSortable({
forcePlaceholderSize: true,
handle: 'div',
helper: 'clone',
items: 'li',
opacity: .6,
placeholder: 'placeholder',
revert: 250,
tabSize: 20,
tolerance: 'pointer',
toleranceElement: '> div',
maxLevels: 2,
isTree: true,
startCollapsed: false
});
$('.disclose').on('click', function() {
$(this).closest('li').toggleClass('mjs-nestedSortable-collapsed').toggleClass('mjs-nestedSortable-expanded');
$(this).toggleClass('ui-icon-plusthick').toggleClass('ui-icon-minusthick');
});
$("#title").focus();
});
//Edit Menu
function editmenu(idmenu){
if(idmenu!=""){
var url = 'menus/edit/'+idmenu;
$("#frm_menu_head").html("Edit Menu");
$("#form-area").load(siteurl+url);
$("#title").focus();
}
}
function save_order_menu(){
var formdata = $('ol.sortable').nestedSortable('serialize');
token_hash = $("#frm_menu_order [name='ci_csrf_token']").val();
formdata = formdata+'&ci_csrf_token='+token_hash;
$.ajax({
url : siteurl+"menus/save_order",
data : formdata,
dataType : "json",
type : "post",
success: function(msg){
if(msg['save']==1){
$("#frm_menu_order [name='ci_csrf_token']").val(msg['token']);
$("#alert_save").html("Menu order saved");
$("#alert_save").removeClass("alert-danger");
$("#alert_save").removeClass("alert-success");
$("#alert_save").addClass("alert-success");
$("#alert_save").show();
setTimeout(function(){
$("#alert_save").hide();
window.location.reload();
},2000);
}else{
$("#frm_menu_order [name='ci_csrf_token']").val(msg['token']);
$("#alert_save").html("Menu saving failed");
$("#alert_save").removeClass("alert-danger");
$("#alert_save").removeClass("alert-success");
$("#alert_save").addClass("alert-danger");
$("#alert_save").show();
setTimeout(function(){
$("#alert_save").hide();
},2000);
}
}
});
}
//Cancel Edit or Add
function cancel(){
$("#menuid").val("");
$("#type").val("add");
$("#title").val("");
$("#link").val("");
$("#icon").val("");
$("#taget").val("sametab");
$("#group_menu").val($("#group_menu option:first").val());
$("#parent_id").val(0);
$("#parent_id").prop("disabled",false);
$("#permission_id").val($("#permission_id option:first").val());
$("#taget").val(1);
$("#frm_menu_head").html("Add New Menu");
}
//Save Menu
function save_menu(){
var title = $("#title").val().trim();
var formdata = $("#frm_menu").serialize();
if(title!=""){
$.ajax({
url : siteurl+"menus/save_menus_ajax",
data : formdata,
dataType : "json",
type : "post",
success: function(msg){
if(msg['save']==1){
$("#frm_menu [name='ci_csrf_token']").val(msg['token']);
$("#alert_edit").html("Menu saved");
$("#alert_edit").removeClass("alert-danger");
$("#alert_edit").removeClass("alert-success");
$("#alert_edit").addClass("alert-success");
$("#alert_edit").show();
setTimeout(function(){
$("#alert_edit").hide();
window.location.reload();
//reset form
cancel();
},2000);
}else{
$("#frm_menu [name='ci_csrf_token']").val(msg['token']);
$("#alert_edit").html("Menu saving failed");
$("#alert_edit").removeClass("alert-danger");
$("#alert_edit").removeClass("alert-success");
$("#alert_edit").addClass("alert-danger");
$("#alert_edit").show();
setTimeout(function(){
$("#alert_edit").hide();
},2000);
}
}
});
}else{
$("#alert_edit").html("Title must be filled");
$("#alert_edit").removeClass("alert-danger");
$("#alert_edit").removeClass("alert-success");
$("#alert_edit").addClass("alert-danger");
$("#alert_edit").show();
setTimeout(function(){
$("#alert_edit").hide();
},2000);
}
}
//Delete Menu
function delete_menu(id){
var idmenu = id;
var token_hash = $("#frm_menu_order [name='ci_csrf_token']").val();
var conf = confirm("Are you sure you want to delete this menu ?");
if(idmenu!=="")
{
if(conf){
$.ajax({
url : siteurl+"menus/delete",
data : ({id: idmenu, ci_csrf_token: token_hash}),
type : "post",
dataType : "json",
success : function(msg){
if(msg['delete']==1)
{
$("#frm_menu_order [name='ci_csrf_token']").val(msg['token']);
$("#alert_save").html("Menu deleted");
$("#alert_save").removeClass("alert-danger");
$("#alert_save").removeClass("alert-success");
$("#alert_save").addClass("alert-success");
$("#alert_save").show();
setTimeout(function(){
$("#alert_save").hide();
window.location.reload();
},2000);
}else if(msg['delete']==2){
$("#frm_menu_order [name='ci_csrf_token']").val(msg['token']);
$("#alert_save").html("Delete child first");
$("#alert_save").removeClass("alert-danger");
$("#alert_save").removeClass("alert-success");
$("#alert_save").addClass("alert-danger");
$("#alert_save").show();
setTimeout(function(){
$("#alert_save").hide();
},2000);
}else{
$("#frm_menu_order [name='ci_csrf_token']").val(msg['token']);
$("#alert_save").html("Deletion failed");
$("#alert_save").removeClass("alert-danger");
$("#alert_save").removeClass("alert-success");
$("#alert_save").addClass("alert-danger");
$("#alert_save").show();
setTimeout(function(){
$("#alert_save").hide();
},2000);
}
}
});
}
}
}
</script> | suwitolt/ci3-adminlte-hmvc | application/modules/menus/views/menus_form.php | PHP | mit | 14,064 |