code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
import Footer from './Footer';
import Nav from './Nav';
import Layout from './Layout';
export default {
Nav,
Layout,
Footer
};
|
cbfx/reactstrap
|
docs/lib/UI/index.js
|
JavaScript
|
mit
| 134
|
namespace CastleWindsorFindAllImplementations
{
public interface IApplicationRunner
{
void Run();
}
}
|
Code-Inside/Samples
|
2010/CastleWindsorFindAllImplementations/CastleWindsorFindAllImplementations/IApplicationRunner.cs
|
C#
|
mit
| 121
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
#pragma once
#include <dsn/tool_api.h>
namespace dsn {
namespace tools {
class nativerun : public tool_app
{
public:
nativerun(const char* name)
: tool_app(name)
{
}
void install(service_spec& s);
virtual void run() override;
};
}
} // end namespace dsn::tools
|
linearregression/rDSN
|
include/dsn/tool/nativerun.h
|
C
|
mit
| 1,594
|
namespace Moviq.Domain.Auth
{
using Moviq.Interfaces.Models;
using System;
public class UserProfileService : IUserProfileService
{
public UserProfileService(IUserRepository userRepo)
{
this.userRepo = userRepo;
}
IUserRepository userRepo;
public IUser RegisterUser(IUser user)
{
if (userRepo.UserExists(user.UserName))
{
throw new UserExistsException();
}
var hashedPassword = PasswordHash.CreateHash(user.Password);
user.Password = hashedPassword;
user.Guid = Guid.NewGuid();
return userRepo.Set(user);
}
}
}
|
losandes/Heinz95729
|
dotnet/Moviq.Domain.Auth/UserProfileService.cs
|
C#
|
mit
| 709
|
<?php
/*
Section: twitter
Language: Czech
Translator: SierraHawk <sierrahawk@outlook.com>
*/
$translations = array(
'h1' => 'Twitter',
);
?>
|
dcdgupta/sqldatabase
|
cs/twitter.php
|
PHP
|
mit
| 145
|
require 'spec_helper'
module Dino
module Components
describe Led do
let(:board) { double(:board, digital_write: true, set_pin_mode: true) }
describe '#initialize' do
it 'should raise if it does not receive a pin' do
expect {
Led.new(board: board)
}.to raise_exception
end
it 'should raise if it does not receive a board' do
expect {
Led.new(pins: {})
}.to raise_exception
end
it 'should set the pin to out' do
board.should_receive(:set_pin_mode).with(13, :out, nil)
Led.new(pin: 13, board: board)
end
it 'should set the pin to low' do
board.should_receive(:digital_write).with(13, Board::LOW)
Led.new(pin: 13, board: board)
end
end
describe '#on' do
it 'should send a high to the board with the pin' do
@led = Led.new(pin: 13, board: board)
board.should_receive(:digital_write).with(13, Board::HIGH)
@led.on
end
end
describe '#off' do
it 'should send a high to the board with the pin' do
@led = Led.new(pin: 13, board: board)
board.should_receive(:digital_write).with(13, Board::LOW)
@led.off
end
end
describe '#blink' do
it 'should turn the led off if it is on'
it 'should not block'
end
end
end
end
|
MinasMazar/dino
|
spec/lib/components/led_spec.rb
|
Ruby
|
mit
| 1,451
|
# FileSystemConnector.GetFilenamePart Method
Returns a filename without a path
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Connectors](OfficeDevPnP.Core.Framework.Provisioning.Connectors.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public override string GetFilenamePart(String fileName)
```
### Parameters
#### fileName
  Type: System.String
  Name of the file
### Return Value
Type: string
Returns filename without path
## See also
- [FileSystemConnector](OfficeDevPnP.Core.Framework.Provisioning.Connectors.FileSystemConnector.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Connectors](OfficeDevPnP.Core.Framework.Provisioning.Connectors.md)
|
PaoloPia/PnP-Guidance
|
sitescore/OfficeDevPnP.Core.Framework.Provisioning.Connectors.FileSystemConnector.9e3b826.md
|
Markdown
|
mit
| 720
|
//
// OSPlasticButtonCell.h
// Pixen
//
// Copyright 2005-2012 Pixen Project. All rights reserved.
//
@interface OSPlasticButtonCell : NSButtonCell
@end
|
Exceltior/Pixen
|
Other Sources/OSG/OSPlasticButtonCell/OSPlasticButtonCell.h
|
C
|
mit
| 158
|
# reads a json file from the specified location
# the location may be relative (see explanantion of path() function)
# returns a map or nothing if reading fails
function(json_read file)
path("${file}")
ans(file)
if(NOT EXISTS "${file}")
return()
endif()
checksum_file("${file}")
ans(cache_key)
file_cache_return_hit("${cache_key}")
file(READ "${file}" data)
json_deserialize("${data}")
ans(data)
file_cache_update("${cache_key}" "${data}")
return_ref(data)
endfunction()
|
willyd/cmakepp
|
cmake/formats/json/json_read.cmake
|
CMake
|
mit
| 528
|
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
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 "CCUserDefault.h"
#include "platform/CCCommon.h"
#include "platform/CCFileUtils.h"
#include "../tinyxml2/tinyxml2.h"
#include "support/base64.h"
#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
// root name of xml
#define USERDEFAULT_ROOT_NAME "userDefaultRoot"
#define XML_FILE_NAME "UserDefault.xml"
using namespace std;
NS_CC_BEGIN
/**
* define the functions here because we don't want to
* export xmlNodePtr and other types in "CCUserDefault.h"
*/
static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLElement** rootNode, tinyxml2::XMLDocument **doc)
{
tinyxml2::XMLElement* curNode = NULL;
// check the key value
if (! pKey)
{
return NULL;
}
do
{
tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument();
*doc = xmlDoc;
//CCFileData data(UserDefault::getInstance()->getXMLFilePath().c_str(),"rt");
unsigned long nSize;
const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize);
//const char* pXmlBuffer = (const char*)data.getBuffer();
if(NULL == pXmlBuffer)
{
CCLOG("can not read xml file");
break;
}
xmlDoc->Parse(pXmlBuffer);
delete[] pXmlBuffer;
// get root node
*rootNode = xmlDoc->RootElement();
if (NULL == *rootNode)
{
CCLOG("read root node error");
break;
}
// find the node
curNode = (*rootNode)->FirstChildElement();
while (NULL != curNode)
{
const char* nodeName = curNode->Value();
if (!strcmp(nodeName, pKey))
{
break;
}
curNode = curNode->NextSiblingElement();
}
} while (0);
return curNode;
}
static void setValueForKey(const char* pKey, const char* pValue)
{
tinyxml2::XMLElement* rootNode;
tinyxml2::XMLDocument* doc;
tinyxml2::XMLElement* node;
// check the params
if (! pKey || ! pValue)
{
return;
}
// find the node
node = getXMLNodeForKey(pKey, &rootNode, &doc);
// if node exist, change the content
if (node)
{
if (node->FirstChild())
{
node->FirstChild()->SetValue(pValue);
}
else
{
tinyxml2::XMLText* content = doc->NewText(pValue);
node->LinkEndChild(content);
}
}
else
{
if (rootNode)
{
tinyxml2::XMLElement* tmpNode = doc->NewElement(pKey);//new tinyxml2::XMLElement(pKey);
rootNode->LinkEndChild(tmpNode);
tinyxml2::XMLText* content = doc->NewText(pValue);//new tinyxml2::XMLText(pValue);
tmpNode->LinkEndChild(content);
}
}
// save file and free doc
if (doc)
{
doc->SaveFile(UserDefault::getInstance()->getXMLFilePath().c_str());
delete doc;
}
}
/**
* implements of UserDefault
*/
UserDefault* UserDefault::_userDefault = 0;
string UserDefault::_filePath = string("");
bool UserDefault::_isFilePathInitialized = false;
/**
* If the user invoke delete UserDefault::getInstance(), should set _userDefault
* to null to avoid error when he invoke UserDefault::getInstance() later.
*/
UserDefault::~UserDefault()
{
CC_SAFE_DELETE(_userDefault);
_userDefault = NULL;
}
UserDefault::UserDefault()
{
_userDefault = NULL;
}
bool UserDefault::getBoolForKey(const char* pKey)
{
return getBoolForKey(pKey, false);
}
bool UserDefault::getBoolForKey(const char* pKey, bool defaultValue)
{
const char* value = NULL;
tinyxml2::XMLElement* rootNode;
tinyxml2::XMLDocument* doc;
tinyxml2::XMLElement* node;
node = getXMLNodeForKey(pKey, &rootNode, &doc);
// find the node
if (node && node->FirstChild())
{
value = (const char*)(node->FirstChild()->Value());
}
bool ret = defaultValue;
if (value)
{
ret = (! strcmp(value, "true"));
}
if (doc) delete doc;
return ret;
}
int UserDefault::getIntegerForKey(const char* pKey)
{
return getIntegerForKey(pKey, 0);
}
int UserDefault::getIntegerForKey(const char* pKey, int defaultValue)
{
const char* value = NULL;
tinyxml2::XMLElement* rootNode;
tinyxml2::XMLDocument* doc;
tinyxml2::XMLElement* node;
node = getXMLNodeForKey(pKey, &rootNode, &doc);
// find the node
if (node && node->FirstChild())
{
value = (const char*)(node->FirstChild()->Value());
}
int ret = defaultValue;
if (value)
{
ret = atoi(value);
}
if(doc)
{
delete doc;
}
return ret;
}
float UserDefault::getFloatForKey(const char* pKey)
{
return getFloatForKey(pKey, 0.0f);
}
float UserDefault::getFloatForKey(const char* pKey, float defaultValue)
{
float ret = (float)getDoubleForKey(pKey, (double)defaultValue);
return ret;
}
double UserDefault::getDoubleForKey(const char* pKey)
{
return getDoubleForKey(pKey, 0.0);
}
double UserDefault::getDoubleForKey(const char* pKey, double defaultValue)
{
const char* value = NULL;
tinyxml2::XMLElement* rootNode;
tinyxml2::XMLDocument* doc;
tinyxml2::XMLElement* node;
node = getXMLNodeForKey(pKey, &rootNode, &doc);
// find the node
if (node && node->FirstChild())
{
value = (const char*)(node->FirstChild()->Value());
}
double ret = defaultValue;
if (value)
{
ret = atof(value);
}
if (doc) delete doc;
return ret;
}
std::string UserDefault::getStringForKey(const char* pKey)
{
return getStringForKey(pKey, "");
}
string UserDefault::getStringForKey(const char* pKey, const std::string & defaultValue)
{
const char* value = NULL;
tinyxml2::XMLElement* rootNode;
tinyxml2::XMLDocument* doc;
tinyxml2::XMLElement* node;
node = getXMLNodeForKey(pKey, &rootNode, &doc);
// find the node
if (node && node->FirstChild())
{
value = (const char*)(node->FirstChild()->Value());
}
string ret = defaultValue;
if (value)
{
ret = string(value);
}
if (doc) delete doc;
return ret;
}
Data* UserDefault::getDataForKey(const char* pKey)
{
return getDataForKey(pKey, NULL);
}
Data* UserDefault::getDataForKey(const char* pKey, Data* defaultValue)
{
const char* encodedData = NULL;
tinyxml2::XMLElement* rootNode;
tinyxml2::XMLDocument* doc;
tinyxml2::XMLElement* node;
node = getXMLNodeForKey(pKey, &rootNode, &doc);
// find the node
if (node && node->FirstChild())
{
encodedData = (const char*)(node->FirstChild()->Value());
}
Data* ret = defaultValue;
if (encodedData)
{
unsigned char * decodedData = NULL;
int decodedDataLen = base64Decode((unsigned char*)encodedData, (unsigned int)strlen(encodedData), &decodedData);
if (decodedData) {
ret = Data::create(decodedData, decodedDataLen);
delete decodedData;
}
}
if (doc) delete doc;
return ret;
}
void UserDefault::setBoolForKey(const char* pKey, bool value)
{
// save bool value as string
if (true == value)
{
setStringForKey(pKey, "true");
}
else
{
setStringForKey(pKey, "false");
}
}
void UserDefault::setIntegerForKey(const char* pKey, int value)
{
// check key
if (! pKey)
{
return;
}
// format the value
char tmp[50];
memset(tmp, 0, 50);
sprintf(tmp, "%d", value);
setValueForKey(pKey, tmp);
}
void UserDefault::setFloatForKey(const char* pKey, float value)
{
setDoubleForKey(pKey, value);
}
void UserDefault::setDoubleForKey(const char* pKey, double value)
{
// check key
if (! pKey)
{
return;
}
// format the value
char tmp[50];
memset(tmp, 0, 50);
sprintf(tmp, "%f", value);
setValueForKey(pKey, tmp);
}
void UserDefault::setStringForKey(const char* pKey, const std::string & value)
{
// check key
if (! pKey)
{
return;
}
setValueForKey(pKey, value.c_str());
}
void UserDefault::setDataForKey(const char* pKey, const Data& value) {
// check key
if (! pKey)
{
return;
}
char *encodedData = 0;
base64Encode(value.getBytes(), value.getSize(), &encodedData);
setValueForKey(pKey, encodedData);
if (encodedData) delete encodedData;
}
UserDefault* UserDefault::getInstance()
{
initXMLFilePath();
// only create xml file one time
// the file exists after the program exit
if ((! isXMLFileExist()) && (! createXMLFile()))
{
return NULL;
}
if (! _userDefault)
{
_userDefault = new UserDefault();
}
return _userDefault;
}
void UserDefault::destroyInstance()
{
_userDefault = NULL;
}
// XXX: deprecated
UserDefault* UserDefault::sharedUserDefault()
{
return UserDefault::getInstance();
}
// XXX: deprecated
void UserDefault::purgeSharedUserDefault()
{
return UserDefault::destroyInstance();
}
bool UserDefault::isXMLFileExist()
{
FILE *fp = fopen(_filePath.c_str(), "r");
bool bRet = false;
if (fp)
{
bRet = true;
fclose(fp);
}
return bRet;
}
void UserDefault::initXMLFilePath()
{
if (! _isFilePathInitialized)
{
_filePath += FileUtils::getInstance()->getWritablePath() + XML_FILE_NAME;
_isFilePathInitialized = true;
}
}
// create new xml file
bool UserDefault::createXMLFile()
{
bool bRet = false;
tinyxml2::XMLDocument *pDoc = new tinyxml2::XMLDocument();
if (NULL==pDoc)
{
return false;
}
tinyxml2::XMLDeclaration *pDeclaration = pDoc->NewDeclaration("1.0");
if (NULL==pDeclaration)
{
return false;
}
pDoc->LinkEndChild(pDeclaration);
tinyxml2::XMLElement *pRootEle = pDoc->NewElement(USERDEFAULT_ROOT_NAME);
if (NULL==pRootEle)
{
return false;
}
pDoc->LinkEndChild(pRootEle);
bRet = tinyxml2::XML_SUCCESS == pDoc->SaveFile(_filePath.c_str());
if(pDoc)
{
delete pDoc;
}
return bRet;
}
const string& UserDefault::getXMLFilePath()
{
return _filePath;
}
void UserDefault::flush()
{
}
NS_CC_END
#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_PLATFORM != CC_PLATFORM_ANDROID)
|
qq2588258/floweers
|
libs/cocos2dx/support/user_default/CCUserDefault.cpp
|
C++
|
mit
| 11,139
|
RSpec.shared_examples 'a listable object' do |subject, attributes = []|
let(:list) { VCR.use_cassette(subject.to_s) { subject.all } }
it "should return an array of objects" do
expect(list.class).to eq Array
expect(list.first.class).to eq subject
end
attributes.each do |attribute|
it "should return a value for #{attribute}" do
expect(list.first.respond_to?(attribute)).to be true
end
end
end
|
jmonegro/bigcartel-api
|
spec/shared_examples/listable.rb
|
Ruby
|
mit
| 427
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { AnimationEvent } from '@angular/animations';
import { CdkAccordionItem } from '@angular/cdk/accordion';
import { UniqueSelectionDispatcher } from '@angular/cdk/collections';
import { TemplatePortal } from '@angular/cdk/portal';
import { AfterContentInit, ChangeDetectorRef, OnChanges, OnDestroy, SimpleChanges, ViewContainerRef } from '@angular/core';
import { Subject } from 'rxjs';
import { MatAccordion } from './accordion';
import { MatExpansionPanelContent } from './expansion-panel-content';
/** MatExpansionPanel's states. */
export declare type MatExpansionPanelState = 'expanded' | 'collapsed';
/**
* `<mat-expansion-panel>`
*
* This component can be used as a single element to show expandable content, or as one of
* multiple children of an element with the MatAccordion directive attached.
*/
export declare class MatExpansionPanel extends CdkAccordionItem implements AfterContentInit, OnChanges, OnDestroy {
private _viewContainerRef;
/** Whether the toggle indicator should be hidden. */
hideToggle: boolean;
private _hideToggle;
/** Stream that emits for changes in `@Input` properties. */
readonly _inputChanges: Subject<SimpleChanges>;
/** Optionally defined accordion the expansion panel belongs to. */
accordion: MatAccordion;
/** Content that will be rendered lazily. */
_lazyContent: MatExpansionPanelContent;
/** Portal holding the user's content. */
_portal: TemplatePortal;
/** ID for the associated header element. Used for a11y labelling. */
_headerId: string;
constructor(accordion: MatAccordion, _changeDetectorRef: ChangeDetectorRef, _uniqueSelectionDispatcher: UniqueSelectionDispatcher, _viewContainerRef: ViewContainerRef);
/** Whether the expansion indicator should be hidden. */
_getHideToggle(): boolean;
/** Determines whether the expansion panel should have spacing between it and its siblings. */
_hasSpacing(): boolean;
/** Gets the expanded state string. */
_getExpandedState(): MatExpansionPanelState;
ngAfterContentInit(): void;
ngOnChanges(changes: SimpleChanges): void;
ngOnDestroy(): void;
_bodyAnimation(event: AnimationEvent): void;
}
export declare class MatExpansionPanelActionRow {
}
|
friendsofagape/mt2414ui
|
node_modules/@angular/material/typings/expansion/expansion-panel.d.ts
|
TypeScript
|
mit
| 2,450
|
var getArticleInfo = new XMLHttpRequest();
getArticleInfo.open("GET", "articleName.html");
getArticleInfo.send();
getArticleInfo.onreadystatechange = function() {
var text = document.getElementById("textTarget");
if ((getArticleInfo.readyState === 4) && (getArticleInfo.status === 200)) {
text.innerHTML = getArticleInfo.responseText;
} else {
console.log("There was a problem with the request.");
}
};
|
kaidez/kaidez.com
|
v1.0.0/samples/ajax-tutorial-samples/sample04/scripts.js
|
JavaScript
|
mit
| 423
|
package net.dean.jraw.models;
import com.fasterxml.jackson.databind.JsonNode;
import net.dean.jraw.models.meta.JsonProperty;
public class OAuthScope extends Thing {
public OAuthScope(JsonNode dataNode) {
super(dataNode);
}
@JsonProperty
public String getDescription() {
return data("description");
}
}
|
hzsweers/JRAW
|
src/main/java/net/dean/jraw/models/OAuthScope.java
|
Java
|
mit
| 341
|
/* ========================================================================
* Bootstrap: affix.js v3.1.0
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$window = $(window)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$window.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var scrollHeight = $(document).height()
var scrollTop = this.$window.scrollTop()
var position = this.$element.offset()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
if (this.affixed == 'top') position.top += scrollTop
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false
if (this.affixed === affix) return
if (this.unpin) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger($.Event(affixType.replace('affix', 'affixed')))
if (affix == 'bottom') {
this.$element.offset({ top: scrollHeight - offsetBottom - this.$element.height() })
}
}
// AFFIX PLUGIN DEFINITION
// =======================
var old = $.fn.affix
$.fn.affix = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom) data.offset.bottom = data.offsetBottom
if (data.offsetTop) data.offset.top = data.offsetTop
$spy.affix(data)
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.1.0
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (!data.resetText) $el.data('resetText', $el[val]())
$el[val](data[state] || this.options[state])
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
var old = $.fn.button
$.fn.button = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
$btn.button('toggle')
e.preventDefault()
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.1.0
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.pause == 'hover' && this.$element
.on('mouseenter', $.proxy(this.pause, this))
.on('mouseleave', $.proxy(this.cycle, this))
}
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getActiveIndex = function () {
this.$active = this.$element.find('.item.active')
this.$items = this.$active.parent().children()
return this.$items.index(this.$active)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getActiveIndex()
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) })
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || $active[type]()
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var fallback = type == 'next' ? 'first' : 'last'
var that = this
if (!$next.length) {
if (!this.options.wrap) return
$next = this.$element.find('.item')[fallback]()
}
if ($next.hasClass('active')) return this.sliding = false
var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction })
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
this.$element.one('slid.bs.carousel', function () {
var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
$nextIndicator && $nextIndicator.addClass('active')
})
}
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one($.support.transition.end, function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0)
})
.emulateTransitionEnd($active.css('transition-duration').slice(0, -1) * 1000)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger('slid.bs.carousel')
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
var old = $.fn.carousel
$.fn.carousel = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
$(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
var $this = $(this), href
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
$target.carousel(options)
if (slideIndex = $this.attr('data-slide-to')) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
})
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
$carousel.carousel($carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.1.0
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.transitioning = null
if (this.options.parent) this.$parent = $(this.options.parent)
if (this.options.toggle) this.toggle()
}
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var actives = this.$parent && this.$parent.find('> .panel > .in')
if (actives && actives.length) {
var hasData = actives.data('bs.collapse')
if (hasData && hasData.transitioning) return
actives.collapse('hide')
hasData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')
[dimension](0)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')
[dimension]('auto')
this.transitioning = 0
this.$element.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element
[dimension](this.$element[dimension]())
[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse')
.removeClass('in')
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.trigger('hidden.bs.collapse')
.removeClass('collapsing')
.addClass('collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
var old = $.fn.collapse
$.fn.collapse = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') option = !option
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) {
var $this = $(this), href
var target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
var $target = $(target)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
var parent = $this.attr('data-parent')
var $parent = parent && $(parent)
if (!data || !data.transitioning) {
if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed')
$this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
}
$target.collapse(option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.1.0
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle=dropdown]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
$this.focus()
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27)/.test(e.keyCode)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) {
if (e.which == 27) $parent.find(toggle).focus()
return $this.click()
}
var desc = ' li:not(.divider):visible a'
var $items = $parent.find('[role=menu]' + desc + ', [role=listbox]' + desc)
if (!$items.length) return
var index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index-- // up
if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).focus()
}
function clearMenus(e) {
$(backdrop).remove()
$(toggle).each(function () {
var $parent = getParent($(this))
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
var old = $.fn.dropdown
$.fn.dropdown = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle + ', [role=menu], [role=listbox]', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.1.0
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: previous
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active
.one($.support.transition.end, next)
.emulateTransitionEnd(150) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
var old = $.fn.tab
$.fn.tab = function ( option ) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
$(this).tab('show')
})
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.1.0
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'transition' : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false, $el = this
$(this).one($.support.transition.end, function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
})
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.1.0
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var href
var process = $.proxy(this.process, this)
this.$element = $(element).is('body') ? $(window) : $(element)
this.$body = $('body')
this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.offsets = $([])
this.targets = $([])
this.activeTarget = null
this.refresh()
this.process()
}
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
this.offsets = $([])
this.targets = $([])
var self = this
var $targets = this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
var maxScroll = scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0]) && this.activate(i)
}
if (activeTarget && scrollTop <= offsets[0]) {
return activeTarget != (i = targets[0]) && this.activate(i)
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate( targets[i] )
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
var old = $.fn.scrollspy
$.fn.scrollspy = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.1.0
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$element = $(element)
this.$backdrop =
this.isShown = null
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this[!this.isShown ? 'show' : 'hide'](_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.escape()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(document.body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one($.support.transition.end, function () {
that.$element.focus().trigger(e)
})
.emulateTransitionEnd(300) :
that.$element.focus().trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one($.support.transition.end, $.proxy(this.hideModal, this))
.emulateTransitionEnd(300) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.focus()
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.removeBackdrop()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(document.body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one($.support.transition.end, callback)
.emulateTransitionEnd(150) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one($.support.transition.end, callback)
.emulateTransitionEnd(150) :
callback()
} else if (callback) {
callback()
}
}
// MODAL PLUGIN DEFINITION
// =======================
var old = $.fn.modal
$.fn.modal = function (option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target
.modal(option, this)
.one('hide', function () {
$this.is(':visible') && $this.focus()
})
})
$(document)
.on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') })
.on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') })
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.1.0
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
var that = this;
var $tip = this.tip()
this.setContent()
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var $parent = this.$element.parent()
var orgPlacement = placement
var docScroll = document.documentElement.scrollTop || document.body.scrollTop
var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth()
var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
this.hoverState = null
var complete = function() {
that.$element.trigger('shown.bs.' + that.type)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one($.support.transition.end, complete)
.emulateTransitionEnd(150) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var replace
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
replace = true
offset.top = offset.top + height - actualHeight
}
if (/bottom|top/.test(placement)) {
var delta = 0
if (offset.left < 0) {
delta = offset.left * -2
offset.left = 0
$tip.offset(offset)
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
}
this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
} else {
this.replaceArrow(actualHeight - height, actualHeight, 'top')
}
if (replace) $tip.offset(offset)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, position) {
this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function () {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element.trigger('hidden.bs.' + that.type)
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one($.support.transition.end, complete)
.emulateTransitionEnd(150) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function () {
var el = this.$element[0]
return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
width: el.offsetWidth,
height: el.offsetHeight
}, this.$element.offset())
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.tip = function () {
return this.$tip = this.$tip || $(this.options.template)
}
Tooltip.prototype.arrow = function () {
return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')
}
Tooltip.prototype.validate = function () {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function () {
clearTimeout(this.timeout)
this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
}
// TOOLTIP PLUGIN DEFINITION
// =========================
var old = $.fn.tooltip
$.fn.tooltip = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.1.0
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content')[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return this.$arrow = this.$arrow || this.tip().find('.arrow')
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
var old = $.fn.popover
$.fn.popover = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
|
sandeepsailor/Personal-website-single-page
|
app/js/bootstrap.js
|
JavaScript
|
mit
| 52,875
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.logic.v2016_06_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The batch configuration properties definition.
*/
public class BatchConfigurationProperties extends ArtifactProperties {
/**
* The name of the batch group.
*/
@JsonProperty(value = "batchGroupName", required = true)
private String batchGroupName;
/**
* The batch release criteria.
*/
@JsonProperty(value = "releaseCriteria", required = true)
private BatchReleaseCriteria releaseCriteria;
/**
* Get the name of the batch group.
*
* @return the batchGroupName value
*/
public String batchGroupName() {
return this.batchGroupName;
}
/**
* Set the name of the batch group.
*
* @param batchGroupName the batchGroupName value to set
* @return the BatchConfigurationProperties object itself.
*/
public BatchConfigurationProperties withBatchGroupName(String batchGroupName) {
this.batchGroupName = batchGroupName;
return this;
}
/**
* Get the batch release criteria.
*
* @return the releaseCriteria value
*/
public BatchReleaseCriteria releaseCriteria() {
return this.releaseCriteria;
}
/**
* Set the batch release criteria.
*
* @param releaseCriteria the releaseCriteria value to set
* @return the BatchConfigurationProperties object itself.
*/
public BatchConfigurationProperties withReleaseCriteria(BatchReleaseCriteria releaseCriteria) {
this.releaseCriteria = releaseCriteria;
return this;
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/logic/mgmt-v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/BatchConfigurationProperties.java
|
Java
|
mit
| 1,881
|
.infiniteCarousel {
position: relative;
}
div.infiniteCarousel.w600, div.infiniteCarousel.w600 div.wrapper {
height:102px;
}
div.infiniteCarousel div.wrapper {
overflow: hidden;
position: absolute;
top: 0;
}
.infiniteCarousel.w300 .wrapper {
width: 220px; /* .infiniteCarousel width - (.wrapper margin-left + .wrapper margin-right) */
left: 26px; /* (width of containter - width of wrapper )/2 */
}
.infiniteCarousel.w600 .wrapper {
/*border:1px solid red;*/
width: 560px; /* .infiniteCarousel width - (.wrapper margin-left + .wrapper margin-right) */
left: 12px; /* (width of containter - width of wrapper )/2 */
}
.infiniteCarousel .wrapper ul {
/*width: 840px; single item * n */
list-style-image:none;
list-style-position:outside;
list-style-type:none;
margin:0;
padding:0;
position: absolute;
top: 0;
}
.infiniteCarousel ul li {
display:inline-block;
padding: 0px 3px;
}
.infiniteCarousel ul li a img {
display:block;
}
.infiniteCarousel .arrow {
display: block;
height: 11px;
width: 11px;
background: url(/sites/all/themes/shoptalk/images/infinitecarousel/arrows.gif) no-repeat 0 0;
text-indent: -9999px;
position: absolute;
top: 45px;
cursor: pointer;
outline: 0;
}
.infiniteCarousel .forward {
background-position: 0 0;
right: -3px;
}
.infiniteCarousel .back {
background-position: 0 -11px;
left: -6px;
}
/* specializations: */
/* article Items */
div.articleItem-cnt-bdy { margin:30px 0px; }
div.articleItem-cnt-bdy .infiniteCarousel div.articleItemImage { /*border-right:1px dotted #CBCBCB;*/ padding: 0 16px 0 0 !important; margin:0 15px 0 0 !important; }
div.articleItem-cnt-bdy .infiniteCarousel { height:120px; }
div.articleItem-cnt-bdy .infiniteCarousel ul { margin:0px !important; padding:0px !important; }
div.articleItem-cnt-bdy .infiniteCarousel li { margin:0px !important; padding:0px !important; width:117px; }
div.articleItem-cnt-bdy .infiniteCarousel .wrapper { left:20px !important; height:120px !important; width:575px !important; margin:0px 11px !important; }
|
quattromani/placewise
|
temple/src/assets/mimages/Banana Republic at Legacy Place in Dedham, MA 781-326-4117 - MA_files/carousel.css
|
CSS
|
mit
| 2,069
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Bindables;
using osu.Game.Rulesets;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API.Requests.Responses;
using osuTK;
using osu.Framework.Allocation;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Rankings.Tables;
using System.Linq;
using System.Threading;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.BeatmapListing.Panels;
namespace osu.Game.Overlays.Rankings
{
public class SpotlightsLayout : CompositeDrawable
{
public readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>();
private readonly Bindable<APISpotlight> selectedSpotlight = new Bindable<APISpotlight>();
private readonly Bindable<RankingsSortCriteria> sort = new Bindable<RankingsSortCriteria>();
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private RulesetStore rulesets { get; set; }
private CancellationTokenSource cancellationToken;
private GetSpotlightRankingsRequest getRankingsRequest;
private GetSpotlightsRequest spotlightsRequest;
private SpotlightSelector selector;
private Container content;
private LoadingLayer loading;
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChild = new ReverseChildIDFillFlowContainer<Drawable>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
selector = new SpotlightSelector
{
Current = selectedSpotlight,
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
content = new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Margin = new MarginPadding { Vertical = 10 }
},
loading = new LoadingLayer(true)
}
}
}
};
sort.BindTo(selector.Sort);
}
protected override void LoadComplete()
{
base.LoadComplete();
selectedSpotlight.BindValueChanged(_ => onSpotlightChanged());
sort.BindValueChanged(_ => onSpotlightChanged());
Ruleset.BindValueChanged(onRulesetChanged);
getSpotlights();
}
private void getSpotlights()
{
spotlightsRequest = new GetSpotlightsRequest();
spotlightsRequest.Success += response => Schedule(() => selector.Spotlights = response.Spotlights);
api.Queue(spotlightsRequest);
}
private void onRulesetChanged(ValueChangedEvent<RulesetInfo> ruleset)
{
if (!selector.Spotlights.Any())
return;
selectedSpotlight.TriggerChange();
}
private void onSpotlightChanged()
{
loading.Show();
cancellationToken?.Cancel();
getRankingsRequest?.Cancel();
getRankingsRequest = new GetSpotlightRankingsRequest(Ruleset.Value, selectedSpotlight.Value.Id, sort.Value);
getRankingsRequest.Success += onSuccess;
api.Queue(getRankingsRequest);
}
private void onSuccess(GetSpotlightRankingsResponse response)
{
LoadComponentAsync(createContent(response), loaded =>
{
selector.ShowInfo(response);
content.Clear();
content.Add(loaded);
loading.Hide();
}, (cancellationToken = new CancellationTokenSource()).Token);
}
private Drawable createContent(GetSpotlightRankingsResponse response) => new FillFlowContainer
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 20),
Children = new Drawable[]
{
new ScoresTable(1, response.Users),
new FillFlowContainer
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Spacing = new Vector2(10),
Children = response.BeatmapSets.Select(b => new GridBeatmapPanel(b.ToBeatmapSet(rulesets))
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
}).ToList()
}
}
};
protected override void Dispose(bool isDisposing)
{
spotlightsRequest?.Cancel();
getRankingsRequest?.Cancel();
cancellationToken?.Cancel();
base.Dispose(isDisposing);
}
}
}
|
UselessToucan/osu
|
osu.Game/Overlays/Rankings/SpotlightsLayout.cs
|
C#
|
mit
| 5,509
|
CAAT.Module({
defines : "CAAT.Module.Preloader.XHR",
extendsWith : {
/**
*
* @param callback function({string},{object}) a callback function. string will be "ok" or "error"
* @param url {string} a url
* @param asynch {bool} load synchronous or asynchronously
* @param method {string} GET or POST
*/
load : function( callback, url, asynch, method ) {
if (typeof asynch==="undefined") {
asynch= true;
}
if (typeof method==="undefined") {
method= "GET";;
}
var req = false;
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.open(method, url, false);
req.onreadystatechange = function(e) {
if( req.status != 200 )
return callback("error");
var text= e.currentTarget ? e.currentTarget.responseText : e.target.responseText;
callback("ok", text);
} ;
req.send();
}
}
}
});
|
hyperandroid/CAAT
|
src/Modules/Image/Preloader/XHR.js
|
JavaScript
|
mit
| 1,689
|
/**
In short, mpool is distributed under so called "BSD license",
Copyright (c) 2009-2010 Tatsuhiko Kubo <cubicdaiya@gmail.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:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the authors 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.
*/
/* written by C99 style */
#include "mpool.h"
/**
* private function
*/
static inline bool mpool_extend(mpool_pool_t *p, size_t siz, mpool_t *pool);
static inline size_t mpool_align(size_t siz);
static inline size_t mpool_decide_create_siz(size_t siz);
/**
* create memory pool
*/
mpool_t *mpool_create (size_t siz) {
mpool_t *pool;
siz = mpool_decide_create_siz(siz);
pool = malloc(sizeof(*pool));
if (pool == NULL) {
return NULL;
}
pool->mpool = malloc(sizeof(*pool->mpool));
if (pool->mpool == NULL) {
return NULL;
}
pool->mpool->pool = malloc(siz);
if (pool->mpool->pool == NULL) {
return NULL;
}
pool->mpool->next = NULL;
pool->begin = pool->mpool->pool;
pool->head = pool->mpool;
pool->usiz = 0;
pool->msiz = siz;
return pool;
}
/**
* allocate memory from memory pool
*/
void *mpool_alloc(size_t siz, mpool_t *pool) {
mpool_pool_t **p = &pool->mpool;
mpool_pool_t *pp = *p;
size_t usiz = mpool_align(pool->usiz + siz);
size_t msiz = pool->msiz;
void *d = pool->begin;
if (usiz > msiz) {
if (!mpool_extend(pp, usiz * 2 + 1, pool)) {
return NULL;
}
pool->usiz = 0;
pool->msiz = usiz * 2;
d = pool->begin;
pool->begin += mpool_align(siz);
*p = pp->next;
} else {
pool->usiz = usiz;
pool->begin += mpool_align(siz);
}
return d;
}
/**
* release all memory pool
*/
void mpool_destroy (mpool_t *pool) {
for (mpool_pool_t *cur = pool->head, *next; cur; cur = next){
next = cur->next;
MPOOL_FREE(cur->pool);
MPOOL_FREE(cur);
}
MPOOL_FREE(pool);
}
/* following is private function */
/**
* extend memory pool
*/
static inline bool mpool_extend(mpool_pool_t *p, size_t siz, mpool_t *pool) {
siz = mpool_decide_create_siz(siz);
mpool_pool_t *pp;
pp = malloc(sizeof(*pp));
if (pp == NULL) {
return false;
}
pp->pool = malloc(siz);
if (pp->pool == NULL) {
return false;
}
memset(pp->pool, 0, siz);
pp->next = NULL;
p->next = pp;
pool->begin = pp->pool;
return true;
}
/**
* align byte boundary
*/
static inline size_t mpool_align(size_t siz) {
return (siz + (MPOOL_ALIGN_SIZE - 1)) & ~(MPOOL_ALIGN_SIZE - 1);
}
/**
* decide mpool size
*/
static inline size_t mpool_decide_create_siz(size_t siz) {
return siz <= 0 ? MPOOL_POOL_SIZ : mpool_align(siz);
}
|
westfly/leopard
|
util/memory/mpool.c
|
C
|
mit
| 4,192
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
/**
* This package contains the implementation classes for SubscriptionClient.
* All resource groups and resources exist within subscriptions. These operation enable you get information about your subscriptions and tenants. A tenant is a dedicated instance of Azure Active Directory (Azure AD) for your organization.
*/
package com.microsoft.azure.management.resources.v2016_06_01.implementation;
|
selvasingh/azure-sdk-for-java
|
sdk/resources/mgmt-v2016_06_01/src/main/java/com/microsoft/azure/management/resources/v2016_06_01/implementation/package-info.java
|
Java
|
mit
| 624
|
/* eslint max-classes-per-file: off */
import { __assign } from 'tslib'
import { Component, Ref } from './vdom'
import { ViewContextType, ViewContext } from './ViewContext'
import { compareObjs, EqualityFuncs, getUnequalProps } from './util/object'
import { Dictionary } from './options'
export abstract class PureComponent<Props=Dictionary, State=Dictionary> extends Component<Props, State> {
static addPropsEquality = addPropsEquality
static addStateEquality = addStateEquality
static contextType: any = ViewContextType
context: ViewContext
propEquality: EqualityFuncs<Props>
stateEquality: EqualityFuncs<State>
debug: boolean
shouldComponentUpdate(nextProps: Props, nextState: State) {
if (this.debug) {
// eslint-disable-next-line no-console
console.log(getUnequalProps(nextProps, this.props), getUnequalProps(nextState, this.state))
}
return !compareObjs(this.props, nextProps, this.propEquality) ||
!compareObjs(this.state, nextState, this.stateEquality)
}
}
PureComponent.prototype.propEquality = {}
PureComponent.prototype.stateEquality = {}
export abstract class BaseComponent<Props=Dictionary, State=Dictionary> extends PureComponent<Props, State> {
static contextType: any = ViewContextType
context: ViewContext
}
function addPropsEquality(this: { prototype: { propEquality: any } }, propEquality) {
let hash = Object.create(this.prototype.propEquality)
__assign(hash, propEquality)
this.prototype.propEquality = hash
}
function addStateEquality(this: { prototype: { stateEquality: any } }, stateEquality) {
let hash = Object.create(this.prototype.stateEquality)
__assign(hash, stateEquality)
this.prototype.stateEquality = hash
}
// use other one
export function setRef<RefType>(ref: Ref<RefType> | void, current: RefType) {
if (typeof ref === 'function') {
ref(current)
} else if (ref) {
// see https://github.com/facebook/react/issues/13029
(ref as any).current = current
}
}
|
fullcalendar/fullcalendar
|
packages/common/src/vdom-util.tsx
|
TypeScript
|
mit
| 1,984
|
<div>
Hudson 1.20 e anteriores usavam para criar diretórios redundantes dentro do workspace.
Por exemplo, se o nome do módulo CVS fosse "foo/bar", ele primeiro criava "foo/bar" e
depois colocava tudo abaixo desta estrutura. Com este opção desmarcada, não haverá mais
diretórios intermediários desnecessários.
<p>
Isto afeta outros especificadores de caminho, tal como arquivadores de artefatos --- você agora especifica
"build/foo.jar" ao invés de "foo/build/foo.jar".
</div>
|
ricardobaumann/jenkins_release_plugin
|
work/plugins/cvs/WEB-INF/classes/hudson/scm/CVSSCM/help-legacy_pt_BR.html
|
HTML
|
mit
| 490
|
var postgres = require('../config.js').postgres;
module.exports = function(ws, data) {
if (data.action === 'list') {
var patches = [];
postgres.query('SELECT time, patch, user_email, id, parent FROM changes WHERE file_id=$1 AND time>$2 ORDER BY time ASC', [ws.docId, new Date(data.after || 0)]).on('row', function(row) {
patches.push(row);
}).on('end', function() {
ws.sendJSON({
type: 'diff_list',
reqId: data.reqId,
patches: patches
});
});
}
};
|
shilpi230/WebSync
|
lib/routes/diffs.js
|
JavaScript
|
mit
| 511
|
import numpy as np
from keras.datasets import mnist
from keras.layers import Activation
from keras.layers import Dense
from keras.models import Sequential
from keras.utils import np_utils
np.random.seed(1337)
nb_classes = 10
batch_size = 128
nb_epoch = 5
weighted_class = 9
standard_weight = 1
high_weight = 5
max_train_samples = 5000
max_test_samples = 1000
def get_data():
# the data, shuffled and split between tran and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(60000, 784)[:max_train_samples]
X_test = X_test.reshape(10000, 784)[:max_test_samples]
X_train = X_train.astype('float32') / 255
X_test = X_test.astype('float32') / 255
# convert class vectors to binary class matrices
y_train = y_train[:max_train_samples]
y_test = y_test[:max_test_samples]
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
test_ids = np.where(y_test == np.array(weighted_class))[0]
return (X_train, Y_train), (X_test, Y_test), test_ids
def validate_regularizer(weight_reg=None, activity_reg=None):
model = Sequential()
model.add(Dense(50, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dense(10, W_regularizer=weight_reg,
activity_regularizer=activity_reg))
model.add(Activation('softmax'))
return model
|
farizrahman4u/keras-contrib
|
keras_contrib/tests/regularizers.py
|
Python
|
mit
| 1,414
|
'use strict';
describe('$routeProvider', function() {
var $routeProvider;
beforeEach(module('ngRoute'));
beforeEach(module(function(_$routeProvider_) {
$routeProvider = _$routeProvider_;
$routeProvider.when('/foo', {template: 'Hello, world!'});
}));
it('should support enabling/disabling automatic instantiation upon initial load',
inject(function() {
expect($routeProvider.eagerInstantiationEnabled(true)).toBe($routeProvider);
expect($routeProvider.eagerInstantiationEnabled()).toBe(true);
expect($routeProvider.eagerInstantiationEnabled(false)).toBe($routeProvider);
expect($routeProvider.eagerInstantiationEnabled()).toBe(false);
expect($routeProvider.eagerInstantiationEnabled(true)).toBe($routeProvider);
expect($routeProvider.eagerInstantiationEnabled()).toBe(true);
})
);
it('should automatically instantiate `$route` upon initial load', function() {
inject(function($location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
});
inject(function($route) {
expect($route.current).toBeDefined();
});
});
it('should not automatically instantiate `$route` if disabled', function() {
module(function($routeProvider) {
$routeProvider.eagerInstantiationEnabled(false);
});
inject(function($location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
});
inject(function($route) {
expect($route.current).toBeUndefined();
});
});
});
describe('$route', function() {
var $httpBackend,
element;
beforeEach(module('ngRoute'));
beforeEach(module(function() {
return function(_$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', 'Chapter.html').respond('chapter');
$httpBackend.when('GET', 'test.html').respond('test');
$httpBackend.when('GET', 'foo.html').respond('foo');
$httpBackend.when('GET', 'baz.html').respond('baz');
$httpBackend.when('GET', 'bar.html').respond('bar');
$httpBackend.when('GET', 'http://example.com/trusted-template.html').respond('cross domain trusted template');
$httpBackend.when('GET', '404.html').respond('not found');
};
}));
afterEach(function() {
dealoc(element);
});
it('should allow cancellation via $locationChangeStart via $routeChangeStart', function() {
module(function($routeProvider) {
$routeProvider.when('/Edit', {
id: 'edit', template: 'Some edit functionality'
});
$routeProvider.when('/Home', {
id: 'home'
});
});
module(provideLog);
inject(function($route, $location, $rootScope, $compile, log) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (next.id === 'home' && current.scope.unsavedChanges) {
event.preventDefault();
}
});
element = $compile('<div><div ng-view></div></div>')($rootScope);
$rootScope.$apply(function() {
$location.path('/Edit');
});
$rootScope.$on('$routeChangeSuccess', log.fn('routeChangeSuccess'));
$rootScope.$on('$locationChangeSuccess', log.fn('locationChangeSuccess'));
// aborted route change
$rootScope.$apply(function() {
$route.current.scope.unsavedChanges = true;
});
$rootScope.$apply(function() {
$location.path('/Home');
});
expect($route.current.id).toBe('edit');
expect($location.path()).toBe('/Edit');
expect(log).toEqual([]);
// successful route change
$rootScope.$apply(function() {
$route.current.scope.unsavedChanges = false;
});
$rootScope.$apply(function() {
$location.path('/Home');
});
expect($route.current.id).toBe('home');
expect($location.path()).toBe('/Home');
expect(log).toEqual(['locationChangeSuccess', 'routeChangeSuccess']);
});
});
it('should allow redirects while handling $routeChangeStart', function() {
module(function($routeProvider) {
$routeProvider.when('/some', {
id: 'some', template: 'Some functionality'
});
$routeProvider.when('/redirect', {
id: 'redirect'
});
});
module(provideLog);
inject(function($route, $location, $rootScope, $compile, log) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (next.id === 'some') {
$location.path('/redirect');
}
});
$compile('<div><div ng-view></div></div>')($rootScope);
$rootScope.$on('$routeChangeStart', log.fn('routeChangeStart'));
$rootScope.$on('$routeChangeError', log.fn('routeChangeError'));
$rootScope.$on('$routeChangeSuccess', log.fn('routeChangeSuccess'));
$rootScope.$apply(function() {
$location.path('/some');
});
expect($route.current.id).toBe('redirect');
expect($location.path()).toBe('/redirect');
expect(log).toEqual(['routeChangeStart', 'routeChangeStart', 'routeChangeSuccess']);
});
});
it('should route and fire change event', function() {
var log = '',
lastRoute,
nextRoute;
module(function($routeProvider) {
$routeProvider.when('/Book/:book/Chapter/:chapter',
{controller: angular.noop, templateUrl: 'Chapter.html'});
$routeProvider.when('/Blank', {});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
log += 'before();';
expect(current).toBe($route.current);
lastRoute = current;
nextRoute = next;
});
$rootScope.$on('$routeChangeSuccess', function(event, current, last) {
log += 'after();';
expect(current).toBe($route.current);
expect(lastRoute).toBe(last);
expect(nextRoute).toBe(current);
});
$location.path('/Book/Moby/Chapter/Intro').search('p=123');
$rootScope.$digest();
$httpBackend.flush();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', p:'123'});
log = '';
$location.path('/Blank').search('ignore');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({ignore:true});
log = '';
$location.path('/NONE');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current).toEqual(undefined);
});
});
it('should route and fire change event when catch-all params are used', function() {
var log = '',
lastRoute,
nextRoute;
module(function($routeProvider) {
$routeProvider.when('/Book1/:book/Chapter/:chapter/:highlight*/edit',
{controller: angular.noop, templateUrl: 'Chapter.html'});
$routeProvider.when('/Book2/:book/:highlight*/Chapter/:chapter',
{controller: angular.noop, templateUrl: 'Chapter.html'});
$routeProvider.when('/Blank', {});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
log += 'before();';
expect(current).toBe($route.current);
lastRoute = current;
nextRoute = next;
});
$rootScope.$on('$routeChangeSuccess', function(event, current, last) {
log += 'after();';
expect(current).toBe($route.current);
expect(lastRoute).toBe(last);
expect(nextRoute).toBe(current);
});
$location.path('/Book1/Moby/Chapter/Intro/one/edit').search('p=123');
$rootScope.$digest();
$httpBackend.flush();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'});
log = '';
$location.path('/Blank').search('ignore');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({ignore:true});
log = '';
$location.path('/Book1/Moby/Chapter/Intro/one/two/edit').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'});
log = '';
$location.path('/Book2/Moby/one/two/Chapter/Intro').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'});
log = '';
$location.path('/NONE');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current).toEqual(undefined);
});
});
it('should route and fire change event correctly whenever the case insensitive flag is utilized', function() {
var log = '',
lastRoute,
nextRoute;
module(function($routeProvider) {
$routeProvider.when('/Book1/:book/Chapter/:chapter/:highlight*/edit',
{controller: angular.noop, templateUrl: 'Chapter.html', caseInsensitiveMatch: true});
$routeProvider.when('/Book2/:book/:highlight*/Chapter/:chapter',
{controller: angular.noop, templateUrl: 'Chapter.html'});
$routeProvider.when('/Blank', {});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
log += 'before();';
expect(current).toBe($route.current);
lastRoute = current;
nextRoute = next;
});
$rootScope.$on('$routeChangeSuccess', function(event, current, last) {
log += 'after();';
expect(current).toBe($route.current);
expect(lastRoute).toBe(last);
expect(nextRoute).toBe(current);
});
$location.path('/Book1/Moby/Chapter/Intro/one/edit').search('p=123');
$rootScope.$digest();
$httpBackend.flush();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'});
log = '';
$location.path('/BOOK1/Moby/CHAPTER/Intro/one/EDIT').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'});
log = '';
$location.path('/Blank').search('ignore');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({ignore:true});
log = '';
$location.path('/BLANK');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current).toEqual(undefined);
log = '';
$location.path('/Book2/Moby/one/two/Chapter/Intro').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'});
log = '';
$location.path('/BOOK2/Moby/one/two/CHAPTER/Intro').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current).toEqual(undefined);
});
});
it('should allow configuring caseInsensitiveMatch on the route provider level', function() {
module(function($routeProvider) {
$routeProvider.caseInsensitiveMatch = true;
$routeProvider.when('/Blank', {template: 'blank'});
$routeProvider.otherwise({template: 'other'});
});
inject(function($route, $location, $rootScope) {
$location.path('/bLaNk');
$rootScope.$digest();
expect($route.current.template).toBe('blank');
});
});
it('should allow overriding provider\'s caseInsensitiveMatch setting on the route level', function() {
module(function($routeProvider) {
$routeProvider.caseInsensitiveMatch = true;
$routeProvider.when('/Blank', {template: 'blank', caseInsensitiveMatch: false});
$routeProvider.otherwise({template: 'other'});
});
inject(function($route, $location, $rootScope) {
$location.path('/bLaNk');
$rootScope.$digest();
expect($route.current.template).toBe('other');
});
});
it('should not change route when location is canceled', function() {
module(function($routeProvider) {
$routeProvider.when('/somePath', {template: 'some path'});
});
inject(function($route, $location, $rootScope, $log) {
$rootScope.$on('$locationChangeStart', function(event) {
$log.info('$locationChangeStart');
event.preventDefault();
});
$rootScope.$on('$routeChangeSuccess', function(event) {
throw new Error('Should not get here');
});
$location.path('/somePath');
$rootScope.$digest();
expect($log.info.logs.shift()).toEqual(['$locationChangeStart']);
});
});
describe('should match a route that contains special chars in the path', function() {
beforeEach(module(function($routeProvider) {
$routeProvider.when('/$test.23/foo*(bar)/:baz', {templateUrl: 'test.html'});
}));
it('matches the full path', inject(function($route, $location, $rootScope) {
$location.path('/test');
$rootScope.$digest();
expect($route.current).toBeUndefined();
}));
it('matches literal .', inject(function($route, $location, $rootScope) {
$location.path('/$testX23/foo*(bar)/222');
$rootScope.$digest();
expect($route.current).toBeUndefined();
}));
it('matches literal *', inject(function($route, $location, $rootScope) {
$location.path('/$test.23/foooo(bar)/222');
$rootScope.$digest();
expect($route.current).toBeUndefined();
}));
it('treats backslashes normally', inject(function($route, $location, $rootScope) {
$location.path('/$test.23/foo*\\(bar)/222');
$rootScope.$digest();
expect($route.current).toBeUndefined();
}));
it('matches a URL with special chars', inject(function($route, $location, $rootScope) {
$location.path('/$test.23/foo*(bar)/~!@#$%^&*()_+=-`');
$rootScope.$digest();
expect($route.current).toBeDefined();
}));
it('should use route params inherited from prototype chain', function() {
function BaseRoute() {}
BaseRoute.prototype.templateUrl = 'foo.html';
module(function($routeProvider) {
$routeProvider.when('/foo', new BaseRoute());
});
inject(function($route, $location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
expect($route.current.templateUrl).toBe('foo.html');
});
});
});
describe('should match a route that contains optional params in the path', function() {
beforeEach(module(function($routeProvider) {
$routeProvider.when('/test/:opt?/:baz/edit', {templateUrl: 'test.html'});
}));
it('matches a URL with optional params', inject(function($route, $location, $rootScope) {
$location.path('/test/optValue/bazValue/edit');
$rootScope.$digest();
expect($route.current).toBeDefined();
}));
it('matches a URL without optional param', inject(function($route, $location, $rootScope) {
$location.path('/test//bazValue/edit');
$rootScope.$digest();
expect($route.current).toBeDefined();
}));
it('not match a URL with a required param', inject(function($route, $location, $rootScope) {
$location.path('///edit');
$rootScope.$digest();
expect($route.current).not.toBeDefined();
}));
});
it('should change route even when only search param changes', function() {
module(function($routeProvider) {
$routeProvider.when('/test', {templateUrl: 'test.html'});
});
inject(function($route, $location, $rootScope) {
var callback = jasmine.createSpy('onRouteChange');
$rootScope.$on('$routeChangeStart', callback);
$location.path('/test');
$rootScope.$digest();
callback.calls.reset();
$location.search({any: true});
$rootScope.$digest();
expect(callback).toHaveBeenCalled();
});
});
it('should allow routes to be defined with just templates without controllers', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
});
inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange');
$rootScope.$on('$routeChangeStart', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.path('/foo');
$rootScope.$digest();
expect($route.current.templateUrl).toEqual('foo.html');
expect($route.current.controller).toBeUndefined();
expect(onChangeSpy).toHaveBeenCalled();
});
});
it('should chain whens and otherwise', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'}).
otherwise({templateUrl: 'bar.html'}).
when('/baz', {templateUrl: 'baz.html'});
});
inject(function($route, $location, $rootScope) {
$rootScope.$digest();
expect($route.current.templateUrl).toBe('bar.html');
$location.url('/baz');
$rootScope.$digest();
expect($route.current.templateUrl).toBe('baz.html');
});
});
it('should skip routes with incomplete params', function() {
module(function($routeProvider) {
$routeProvider
.otherwise({template: 'other'})
.when('/pages/:page/:comment*', {template: 'comment'})
.when('/pages/:page', {template: 'page'})
.when('/pages', {template: 'index'})
.when('/foo/', {template: 'foo'})
.when('/foo/:bar', {template: 'bar'})
.when('/foo/:bar*/:baz', {template: 'baz'});
});
inject(function($route, $location, $rootScope) {
$location.url('/pages/');
$rootScope.$digest();
expect($route.current.template).toBe('index');
$location.url('/pages/page/');
$rootScope.$digest();
expect($route.current.template).toBe('page');
$location.url('/pages/page/1/');
$rootScope.$digest();
expect($route.current.template).toBe('comment');
$location.url('/foo/');
$rootScope.$digest();
expect($route.current.template).toBe('foo');
$location.url('/foo/bar/');
$rootScope.$digest();
expect($route.current.template).toBe('bar');
$location.url('/foo/bar/baz/');
$rootScope.$digest();
expect($route.current.template).toBe('baz');
$location.url('/something/');
$rootScope.$digest();
expect($route.current.template).toBe('other');
});
});
describe('otherwise', function() {
it('should handle unknown routes with "otherwise" route definition', function() {
function NotFoundCtrl() {}
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.otherwise({templateUrl: '404.html', controller: NotFoundCtrl});
});
inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange');
$rootScope.$on('$routeChangeStart', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.path('/unknownRoute');
$rootScope.$digest();
expect($route.current.templateUrl).toBe('404.html');
expect($route.current.controller).toBe(NotFoundCtrl);
expect(onChangeSpy).toHaveBeenCalled();
onChangeSpy.calls.reset();
$location.path('/foo');
$rootScope.$digest();
expect($route.current.templateUrl).toEqual('foo.html');
expect($route.current.controller).toBeUndefined();
expect(onChangeSpy).toHaveBeenCalled();
});
});
it('should update $route.current and $route.next when default route is matched', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.otherwise({templateUrl: '404.html'});
});
inject(function($route, $location, $rootScope) {
var currentRoute, nextRoute,
onChangeSpy = jasmine.createSpy('onChange').and.callFake(function(e, next) {
currentRoute = $route.current;
nextRoute = next;
});
// init
$rootScope.$on('$routeChangeStart', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
// match otherwise route
$location.path('/unknownRoute');
$rootScope.$digest();
expect(currentRoute).toBeUndefined();
expect(nextRoute.templateUrl).toBe('404.html');
expect($route.current.templateUrl).toBe('404.html');
expect(onChangeSpy).toHaveBeenCalled();
onChangeSpy.calls.reset();
// match regular route
$location.path('/foo');
$rootScope.$digest();
expect(currentRoute.templateUrl).toBe('404.html');
expect(nextRoute.templateUrl).toBe('foo.html');
expect($route.current.templateUrl).toEqual('foo.html');
expect(onChangeSpy).toHaveBeenCalled();
onChangeSpy.calls.reset();
// match otherwise route again
$location.path('/anotherUnknownRoute');
$rootScope.$digest();
expect(currentRoute.templateUrl).toBe('foo.html');
expect(nextRoute.templateUrl).toBe('404.html');
expect($route.current.templateUrl).toEqual('404.html');
expect(onChangeSpy).toHaveBeenCalled();
});
});
it('should interpret a string as a redirect route', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.when('/baz', {templateUrl: 'baz.html'});
$routeProvider.otherwise('/foo');
});
inject(function($route, $location, $rootScope) {
$location.path('/unknownRoute');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
});
});
});
describe('events', function() {
it('should not fire $routeChangeStart/Success during bootstrap (if no route)', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/one', {}); // no otherwise defined
});
inject(function($rootScope, $route, $location) {
$rootScope.$on('$routeChangeStart', routeChangeSpy);
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$rootScope.$digest();
expect(routeChangeSpy).not.toHaveBeenCalled();
$location.path('/no-route-here');
$rootScope.$digest();
expect(routeChangeSpy).not.toHaveBeenCalled();
$location.path('/one');
$rootScope.$digest();
expect(routeChangeSpy).toHaveBeenCalled();
});
});
it('should fire $routeChangeStart and resolve promises', function() {
var deferA,
deferB;
module(function($provide, $routeProvider) {
$provide.factory('b', function($q) {
deferB = $q.defer();
return deferB.promise;
});
$routeProvider.when('/path', { templateUrl: 'foo.html', resolve: {
a: ['$q', function($q) {
deferA = $q.defer();
return deferA.promise;
}],
b: 'b'
} });
});
inject(function($location, $route, $rootScope, $httpBackend) {
var log = '';
$httpBackend.expectGET('foo.html').respond('FOO');
$location.path('/path');
$rootScope.$digest();
expect(log).toEqual('');
$httpBackend.flush();
expect(log).toEqual('');
deferA.resolve();
$rootScope.$digest();
expect(log).toEqual('');
deferB.resolve();
$rootScope.$digest();
expect($route.current.locals.$template).toEqual('FOO');
});
});
it('should fire $routeChangeError event on resolution error', function() {
var deferA;
module(function($provide, $routeProvider) {
$routeProvider.when('/path', { template: 'foo', resolve: {
a: function($q) {
deferA = $q.defer();
return deferA.promise;
}
} });
});
inject(function($location, $route, $rootScope) {
var log = '';
$rootScope.$on('$routeChangeStart', function() { log += 'before();'; });
$rootScope.$on('$routeChangeError', function(e, n, l, reason) { log += 'failed(' + reason + ');'; });
$location.path('/path');
$rootScope.$digest();
expect(log).toEqual('before();');
deferA.reject('MyError');
$rootScope.$digest();
expect(log).toEqual('before();failed(MyError);');
});
});
it('should fetch templates', function() {
module(function($routeProvider) {
$routeProvider.
when('/r1', { templateUrl: 'r1.html' }).
when('/r2', { templateUrl: 'r2.html' });
});
inject(function($route, $httpBackend, $location, $rootScope) {
var log = '';
$rootScope.$on('$routeChangeStart', function(e, next) { log += '$before(' + next.templateUrl + ');'; });
$rootScope.$on('$routeChangeSuccess', function(e, next) { log += '$after(' + next.templateUrl + ');'; });
$httpBackend.expectGET('r1.html').respond('R1');
$httpBackend.expectGET('r2.html').respond('R2');
$location.path('/r1');
$rootScope.$digest();
expect(log).toBe('$before(r1.html);');
$location.path('/r2');
$rootScope.$digest();
expect(log).toBe('$before(r1.html);$before(r2.html);');
$httpBackend.flush();
expect(log).toBe('$before(r1.html);$before(r2.html);$after(r2.html);');
expect(log).not.toContain('$after(r1.html);');
});
});
it('should NOT load cross domain templates by default', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', { templateUrl: 'http://example.com/foo.html' });
});
inject(function($route, $location, $rootScope) {
var onError = jasmine.createSpy('onError');
var onSuccess = jasmine.createSpy('onSuccess');
$rootScope.$on('$routeChangeError', onError);
$rootScope.$on('$routeChangeSuccess', onSuccess);
$location.path('/foo');
$rootScope.$digest();
expect(onSuccess).not.toHaveBeenCalled();
expect(onError).toHaveBeenCalled();
expect(onError.calls.mostRecent().args[3]).toEqualMinErr('$sce', 'insecurl',
'Blocked loading resource from url not allowed by $sceDelegate policy. ' +
'URL: http://example.com/foo.html');
});
});
it('should load cross domain templates that are trusted', function() {
module(function($routeProvider, $sceDelegateProvider) {
$routeProvider.when('/foo', { templateUrl: 'http://example.com/foo.html' });
$sceDelegateProvider.resourceUrlWhitelist([/^http:\/\/example\.com\/foo\.html$/]);
});
inject(function($route, $location, $rootScope) {
$httpBackend.whenGET('http://example.com/foo.html').respond('FOO BODY');
$location.path('/foo');
$rootScope.$digest();
$httpBackend.flush();
expect($route.current.locals.$template).toEqual('FOO BODY');
});
});
it('should not update $routeParams until $routeChangeSuccess', function() {
module(function($routeProvider) {
$routeProvider.
when('/r1/:id', { templateUrl: 'r1.html' }).
when('/r2/:id', { templateUrl: 'r2.html' });
});
inject(function($route, $httpBackend, $location, $rootScope, $routeParams) {
var log = '';
$rootScope.$on('$routeChangeStart', function(e, next) { log += '$before' + angular.toJson($routeParams) + ';'; });
$rootScope.$on('$routeChangeSuccess', function(e, next) { log += '$after' + angular.toJson($routeParams) + ';'; });
$httpBackend.whenGET('r1.html').respond('R1');
$httpBackend.whenGET('r2.html').respond('R2');
$location.path('/r1/1');
$rootScope.$digest();
expect(log).toBe('$before{};');
$httpBackend.flush();
expect(log).toBe('$before{};$after{"id":"1"};');
log = '';
$location.path('/r2/2');
$rootScope.$digest();
expect(log).toBe('$before{"id":"1"};');
$httpBackend.flush();
expect(log).toBe('$before{"id":"1"};$after{"id":"2"};');
});
});
it('should drop in progress route change when new route change occurs', function() {
module(function($routeProvider) {
$routeProvider.
when('/r1', { templateUrl: 'r1.html' }).
when('/r2', { templateUrl: 'r2.html' });
});
inject(function($route, $httpBackend, $location, $rootScope) {
var log = '';
$rootScope.$on('$routeChangeStart', function(e, next) { log += '$before(' + next.templateUrl + ');'; });
$rootScope.$on('$routeChangeSuccess', function(e, next) { log += '$after(' + next.templateUrl + ');'; });
$httpBackend.expectGET('r1.html').respond('R1');
$httpBackend.expectGET('r2.html').respond('R2');
$location.path('/r1');
$rootScope.$digest();
expect(log).toBe('$before(r1.html);');
$location.path('/r2');
$rootScope.$digest();
expect(log).toBe('$before(r1.html);$before(r2.html);');
$httpBackend.flush();
expect(log).toBe('$before(r1.html);$before(r2.html);$after(r2.html);');
expect(log).not.toContain('$after(r1.html);');
});
});
it('should throw an error when a template is not found', function() {
module(function($routeProvider, $exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
$routeProvider.
when('/r1', { templateUrl: 'r1.html' }).
when('/r2', { templateUrl: 'r2.html' }).
when('/r3', { templateUrl: 'r3.html' });
});
inject(function($route, $httpBackend, $location, $rootScope, $exceptionHandler) {
$httpBackend.expectGET('r1.html').respond(404, 'R1');
$location.path('/r1');
$rootScope.$digest();
$httpBackend.flush();
expect($exceptionHandler.errors.pop()).
toEqualMinErr('$templateRequest', 'tpload', 'Failed to load template: r1.html');
$httpBackend.expectGET('r2.html').respond('');
$location.path('/r2');
$rootScope.$digest();
$httpBackend.flush();
expect($exceptionHandler.errors.length).toBe(0);
$httpBackend.expectGET('r3.html').respond('abc');
$location.path('/r3');
$rootScope.$digest();
$httpBackend.flush();
expect($exceptionHandler.errors.length).toBe(0);
});
});
it('should catch local factory errors', function() {
var myError = new Error('MyError');
module(function($routeProvider) {
$routeProvider.when('/locals', {
resolve: {
a: function($q) {
throw myError;
}
}
});
});
inject(function($location, $route, $rootScope) {
spyOn($rootScope, '$broadcast').and.callThrough();
$location.path('/locals');
$rootScope.$digest();
expect($rootScope.$broadcast).toHaveBeenCalledWith(
'$routeChangeError', jasmine.any(Object), undefined, myError);
});
});
});
it('should match route with and without trailing slash', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.when('/bar/', {templateUrl: 'bar.html'});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
$location.path('/foo/');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
$location.path('/bar');
$rootScope.$digest();
expect($location.path()).toBe('/bar/');
expect($route.current.templateUrl).toBe('bar.html');
$location.path('/bar/');
$rootScope.$digest();
expect($location.path()).toBe('/bar/');
expect($route.current.templateUrl).toBe('bar.html');
});
});
it('should not get affected by modifying the route definition object after route registration',
function() {
module(function($routeProvider) {
var rdo = {};
rdo.templateUrl = 'foo.html';
$routeProvider.when('/foo', rdo);
rdo.templateUrl = 'bar.html';
$routeProvider.when('/bar', rdo);
});
inject(function($location, $rootScope, $route) {
$location.path('/bar');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect($route.current.templateUrl).toBe('bar.html');
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
});
}
);
it('should use the property values of the passed in route definition object directly',
function() {
var $routeProvider;
module(function(_$routeProvider_) {
$routeProvider = _$routeProvider_;
});
inject(function($location, $rootScope, $route, $sce) {
var sceWrappedUrl = $sce.trustAsResourceUrl('foo.html');
$routeProvider.when('/foo', {templateUrl: sceWrappedUrl});
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe(sceWrappedUrl);
});
}
);
it('should support custom `$sce` implementations', function() {
function MySafeResourceUrl(val) {
var self = this;
this._val = val;
this.getVal = function() {
return (this !== self) ? null : this._val;
};
}
var $routeProvider;
module(function($provide, _$routeProvider_) {
$routeProvider = _$routeProvider_;
$provide.decorator('$sce', function($delegate) {
function getVal(v) { return v.getVal ? v.getVal() : v; }
$delegate.trustAsResourceUrl = function(url) { return new MySafeResourceUrl(url); };
$delegate.getTrustedResourceUrl = function(v) { return getVal(v); };
$delegate.valueOf = function(v) { return getVal(v); };
return $delegate;
});
});
inject(function($location, $rootScope, $route, $sce) {
$routeProvider.when('/foo', {templateUrl: $sce.trustAsResourceUrl('foo.html')});
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($sce.valueOf($route.current.templateUrl)).toBe('foo.html');
});
});
describe('redirection', function() {
describe('via `redirectTo`', function() {
it('should support redirection via redirectTo property by updating $location', function() {
module(function($routeProvider) {
$routeProvider.when('/', {redirectTo: '/foo'});
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.when('/bar', {templateUrl: 'bar.html'});
$routeProvider.when('/baz', {redirectTo: '/bar'});
$routeProvider.otherwise({templateUrl: '404.html'});
});
inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange');
$rootScope.$on('$routeChangeStart', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.path('/');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
expect(onChangeSpy).toHaveBeenCalledTimes(2);
onChangeSpy.calls.reset();
$location.path('/baz');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect($route.current.templateUrl).toBe('bar.html');
expect(onChangeSpy).toHaveBeenCalledTimes(2);
});
});
it('should interpolate route vars in the redirected path from original path', function() {
module(function($routeProvider) {
$routeProvider.when('/foo/:id/foo/:subid/:extraId', {redirectTo: '/bar/:id/:subid/23'});
$routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'});
$routeProvider.when('/baz/:id/:path*', {redirectTo: '/path/:path/:id'});
$routeProvider.when('/path/:path*/:id', {templateUrl: 'foo.html'});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id1/foo/subid3/gah');
$rootScope.$digest();
expect($location.path()).toEqual('/bar/id1/subid3/23');
expect($location.search()).toEqual({extraId: 'gah'});
expect($route.current.templateUrl).toEqual('bar.html');
$location.path('/baz/1/foovalue/barvalue');
$rootScope.$digest();
expect($location.path()).toEqual('/path/foovalue/barvalue/1');
expect($route.current.templateUrl).toEqual('foo.html');
});
});
it('should interpolate route vars in the redirected path from original search', function() {
module(function($routeProvider) {
$routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'});
$routeProvider.when('/foo/:id/:extra', {redirectTo: '/bar/:id/:subid/99'});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id3/eId').search('subid=sid1&appended=true');
$rootScope.$digest();
expect($location.path()).toEqual('/bar/id3/sid1/99');
expect($location.search()).toEqual({appended: 'true', extra: 'eId'});
expect($route.current.templateUrl).toEqual('bar.html');
});
});
it('should properly process route params which are both eager and optional', function() {
module(function($routeProvider) {
$routeProvider.when('/foo/:param1*?/:param2', {templateUrl: 'foo.html'});
});
inject(function($location, $rootScope, $route) {
$location.path('/foo/bar1/bar2/bar3/baz');
$rootScope.$digest();
expect($location.path()).toEqual('/foo/bar1/bar2/bar3/baz');
expect($route.current.params.param1).toEqual('bar1/bar2/bar3');
expect($route.current.params.param2).toEqual('baz');
expect($route.current.templateUrl).toEqual('foo.html');
$location.path('/foo/baz');
$rootScope.$digest();
expect($location.path()).toEqual('/foo/baz');
expect($route.current.params.param1).toEqual(undefined);
expect($route.current.params.param2).toEqual('baz');
expect($route.current.templateUrl).toEqual('foo.html');
});
});
it('should properly interpolate optional and eager route vars ' +
'when redirecting from path with trailing slash', function() {
module(function($routeProvider) {
$routeProvider.when('/foo/:id?/:subid?', {templateUrl: 'foo.html'});
$routeProvider.when('/bar/:id*/:subid', {templateUrl: 'bar.html'});
});
inject(function($location, $rootScope, $route) {
$location.path('/foo/id1/subid2/');
$rootScope.$digest();
expect($location.path()).toEqual('/foo/id1/subid2');
expect($route.current.templateUrl).toEqual('foo.html');
$location.path('/bar/id1/extra/subid2/');
$rootScope.$digest();
expect($location.path()).toEqual('/bar/id1/extra/subid2');
expect($route.current.templateUrl).toEqual('bar.html');
});
});
it('should allow custom redirectTo function to be used', function() {
function customRedirectFn(routePathParams, path, search) {
expect(routePathParams).toEqual({id: 'id3'});
expect(path).toEqual('/foo/id3');
expect(search).toEqual({subid: 'sid1', appended: 'true'});
return '/custom';
}
module(function($routeProvider) {
$routeProvider.when('/foo/:id', {redirectTo: customRedirectFn});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id3').search('subid=sid1&appended=true');
$rootScope.$digest();
expect($location.path()).toEqual('/custom');
});
});
it('should broadcast `$routeChangeError` when redirectTo throws', function() {
var error = new Error('Test');
module(function($routeProvider) {
$routeProvider.when('/foo', {redirectTo: function() { throw error; }});
});
inject(function($exceptionHandler, $location, $rootScope, $route) {
spyOn($rootScope, '$broadcast').and.callThrough();
$location.path('/foo');
$rootScope.$digest();
var lastCallArgs = $rootScope.$broadcast.calls.mostRecent().args;
expect(lastCallArgs[0]).toBe('$routeChangeError');
expect(lastCallArgs[3]).toBe(error);
});
});
it('should replace the url when redirecting', function() {
module(function($routeProvider) {
$routeProvider.when('/bar/:id', {templateUrl: 'bar.html'});
$routeProvider.when('/foo/:id/:extra', {redirectTo: '/bar/:id'});
});
inject(function($browser, $route, $location, $rootScope) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$location.path('/foo/id3/eId');
$rootScope.$digest();
expect($location.path()).toEqual('/bar/id3');
expect($browserUrl.calls.mostRecent().args)
.toEqual(['http://server/#!/bar/id3?extra=eId', true, null]);
});
});
it('should not process route bits', function() {
var firstController = jasmine.createSpy('first controller spy');
var firstTemplate = jasmine.createSpy('first template spy').and.returnValue('redirected view');
var firstResolve = jasmine.createSpy('first resolve spy');
var secondController = jasmine.createSpy('second controller spy');
var secondTemplate = jasmine.createSpy('second template spy').and.returnValue('redirected view');
var secondResolve = jasmine.createSpy('second resolve spy');
module(function($routeProvider) {
$routeProvider.when('/redirect', {
template: firstTemplate,
redirectTo: '/redirected',
resolve: { value: firstResolve },
controller: firstController
});
$routeProvider.when('/redirected', {
template: secondTemplate,
resolve: { value: secondResolve },
controller: secondController
});
});
inject(function($route, $location, $rootScope, $compile) {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/redirect');
$rootScope.$digest();
expect(firstController).not.toHaveBeenCalled();
expect(firstTemplate).not.toHaveBeenCalled();
expect(firstResolve).not.toHaveBeenCalled();
expect(secondController).toHaveBeenCalled();
expect(secondTemplate).toHaveBeenCalled();
expect(secondResolve).toHaveBeenCalled();
dealoc(element);
});
});
it('should not redirect transition if `redirectTo` returns `undefined`', function() {
var controller = jasmine.createSpy('first controller spy');
var templateFn = jasmine.createSpy('first template spy').and.returnValue('redirected view');
module(function($routeProvider) {
$routeProvider.when('/redirect/to/undefined', {
template: templateFn,
redirectTo: function() {},
controller: controller
});
});
inject(function($route, $location, $rootScope, $compile) {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/redirect/to/undefined');
$rootScope.$digest();
expect(controller).toHaveBeenCalled();
expect(templateFn).toHaveBeenCalled();
expect($location.path()).toEqual('/redirect/to/undefined');
dealoc(element);
});
});
});
describe('via `resolveRedirectTo`', function() {
var $compile;
var $location;
var $rootScope;
var $route;
beforeEach(module(function() {
return function(_$compile_, _$location_, _$rootScope_, _$route_) {
$compile = _$compile_;
$location = _$location_;
$rootScope = _$rootScope_;
$route = _$route_;
};
}));
it('should be ignored if `redirectTo` is also present', function() {
var newUrl;
var getNewUrl = function() { return newUrl; };
var resolveRedirectToSpy = jasmine.createSpy('resolveRedirectTo').and.returnValue('/bar');
var redirectToSpy = jasmine.createSpy('redirectTo').and.callFake(getNewUrl);
var templateSpy = jasmine.createSpy('template').and.returnValue('Foo');
module(function($routeProvider) {
$routeProvider.
when('/foo', {
resolveRedirectTo: resolveRedirectToSpy,
redirectTo: redirectToSpy,
template: templateSpy
}).
when('/bar', {template: 'Bar'}).
when('/baz', {template: 'Baz'});
});
inject(function() {
newUrl = '/baz';
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/baz');
expect($route.current.template).toBe('Baz');
expect(resolveRedirectToSpy).not.toHaveBeenCalled();
expect(redirectToSpy).toHaveBeenCalled();
expect(templateSpy).not.toHaveBeenCalled();
redirectToSpy.calls.reset();
newUrl = undefined;
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.template).toBe(templateSpy);
expect(resolveRedirectToSpy).not.toHaveBeenCalled();
expect(redirectToSpy).toHaveBeenCalled();
expect(templateSpy).toHaveBeenCalled();
});
});
it('should redirect to the returned url', function() {
module(function($routeProvider) {
$routeProvider.
when('/foo', {resolveRedirectTo: function() { return '/bar?baz=qux'; }}).
when('/bar', {template: 'Bar'});
});
inject(function() {
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect($location.search()).toEqual({baz: 'qux'});
expect($route.current.template).toBe('Bar');
});
});
it('should support returning a promise', function() {
module(function($routeProvider) {
$routeProvider.
when('/foo', {resolveRedirectTo: function($q) { return $q.resolve('/bar'); }}).
when('/bar', {template: 'Bar'});
});
inject(function() {
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect($route.current.template).toBe('Bar');
});
});
it('should support dependency injection', function() {
module(function($provide, $routeProvider) {
$provide.value('nextRoute', '/bar');
$routeProvider.
when('/foo', {
resolveRedirectTo: function(nextRoute) {
return nextRoute;
}
});
});
inject(function() {
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
});
});
it('should have access to the current routeParams via `$route.current.params`', function() {
module(function($routeProvider) {
$routeProvider.
when('/foo/:bar/baz/:qux', {
resolveRedirectTo: function($route) {
expect($route.current.params).toEqual(jasmine.objectContaining({
bar: '1',
qux: '2'
}));
return '/passed';
}
});
});
inject(function() {
$location.path('/foo/1/baz/2').search({bar: 'qux'});
$rootScope.$digest();
expect($location.path()).toBe('/passed');
});
});
it('should not process route bits until the promise is resolved', function() {
var spies = createSpies();
var called = false;
var deferred;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function($q) {
called = true;
deferred = $q.defer();
return deferred.promise;
});
});
inject(function() {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
deferred.resolve('/bar');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).toHaveBeenCalled();
expect(spies.barTemplateSpy).toHaveBeenCalled();
expect(spies.barControllerSpy).toHaveBeenCalled();
dealoc(element);
});
});
it('should not redirect if `undefined` is returned', function() {
var spies = createSpies();
var called = false;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function() {
called = true;
return undefined;
});
});
inject(function() {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).toHaveBeenCalled();
expect(spies.fooTemplateSpy).toHaveBeenCalled();
expect(spies.fooControllerSpy).toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
dealoc(element);
});
});
it('should not redirect if the returned promise resolves to `undefined`', function() {
var spies = createSpies();
var called = false;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function($q) {
called = true;
return $q.resolve(undefined);
});
});
inject(function() {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).toHaveBeenCalled();
expect(spies.fooTemplateSpy).toHaveBeenCalled();
expect(spies.fooControllerSpy).toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
dealoc(element);
});
});
it('should not redirect if the returned promise gets rejected', function() {
var spies = createSpies();
var called = false;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function($q) {
called = true;
return $q.reject('');
});
});
inject(function() {
spyOn($rootScope, '$broadcast').and.callThrough();
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
var lastCallArgs = $rootScope.$broadcast.calls.mostRecent().args;
expect(lastCallArgs[0]).toBe('$routeChangeError');
dealoc(element);
});
});
it('should ignore previous redirection if newer transition happened', function() {
var spies = createSpies();
var called = false;
var deferred;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function($q) {
called = true;
deferred = $q.defer();
return deferred.promise;
});
});
inject(function() {
spyOn($location, 'url').and.callThrough();
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
expect(spies.bazResolveSpy).not.toHaveBeenCalled();
expect(spies.bazTemplateSpy).not.toHaveBeenCalled();
expect(spies.bazControllerSpy).not.toHaveBeenCalled();
$location.path('/baz');
$rootScope.$digest();
expect($location.path()).toBe('/baz');
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
expect(spies.bazResolveSpy).toHaveBeenCalledOnce();
expect(spies.bazTemplateSpy).toHaveBeenCalledOnce();
expect(spies.bazControllerSpy).toHaveBeenCalledOnce();
deferred.resolve();
$rootScope.$digest();
expect($location.path()).toBe('/baz');
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
expect(spies.bazResolveSpy).toHaveBeenCalledOnce();
expect(spies.bazTemplateSpy).toHaveBeenCalledOnce();
expect(spies.bazControllerSpy).toHaveBeenCalledOnce();
dealoc(element);
});
});
// Helpers
function createSpies() {
return {
fooResolveSpy: jasmine.createSpy('fooResolve'),
fooTemplateSpy: jasmine.createSpy('fooTemplate').and.returnValue('Foo'),
fooControllerSpy: jasmine.createSpy('fooController'),
barResolveSpy: jasmine.createSpy('barResolve'),
barTemplateSpy: jasmine.createSpy('barTemplate').and.returnValue('Bar'),
barControllerSpy: jasmine.createSpy('barController'),
bazResolveSpy: jasmine.createSpy('bazResolve'),
bazTemplateSpy: jasmine.createSpy('bazTemplate').and.returnValue('Baz'),
bazControllerSpy: jasmine.createSpy('bazController')
};
}
function setupRoutes(routeProvider, spies, resolveRedirectToFn) {
routeProvider.
when('/foo', {
resolveRedirectTo: resolveRedirectToFn,
resolve: {_: spies.fooResolveSpy},
template: spies.fooTemplateSpy,
controller: spies.fooControllerSpy
}).
when('/bar', {
resolve: {_: spies.barResolveSpy},
template: spies.barTemplateSpy,
controller: spies.barControllerSpy
}).
when('/baz', {
resolve: {_: spies.bazResolveSpy},
template: spies.bazTemplateSpy,
controller: spies.bazControllerSpy
});
}
});
});
describe('reloadOnSearch', function() {
it('should reload a route when reloadOnSearch is enabled and .search() changes', function() {
var reloaded = jasmine.createSpy('route reload');
module(function($routeProvider) {
$routeProvider.when('/foo', {controller: angular.noop});
});
inject(function($route, $location, $rootScope, $routeParams) {
$rootScope.$on('$routeChangeStart', reloaded);
$location.path('/foo');
$rootScope.$digest();
expect(reloaded).toHaveBeenCalled();
expect($routeParams).toEqual({});
reloaded.calls.reset();
// trigger reload
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(reloaded).toHaveBeenCalled();
expect($routeParams).toEqual({foo:'bar'});
});
});
it('should not reload a route when reloadOnSearch is disabled and only .search() changes', function() {
var routeChange = jasmine.createSpy('route change'),
routeUpdate = jasmine.createSpy('route update');
module(function($routeProvider) {
$routeProvider.when('/foo', {controller: angular.noop, reloadOnSearch: false});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', routeChange);
$rootScope.$on('$routeChangeSuccess', routeChange);
$rootScope.$on('$routeUpdate', routeUpdate);
expect(routeChange).not.toHaveBeenCalled();
$location.path('/foo');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalled();
expect(routeChange).toHaveBeenCalledTimes(2);
expect(routeUpdate).not.toHaveBeenCalled();
routeChange.calls.reset();
// don't trigger reload
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(routeChange).not.toHaveBeenCalled();
expect(routeUpdate).toHaveBeenCalled();
});
});
it('should reload reloadOnSearch route when url differs only in route path param', function() {
var routeChange = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/foo/:fooId', {controller: angular.noop, reloadOnSearch: false});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', routeChange);
$rootScope.$on('$routeChangeSuccess', routeChange);
expect(routeChange).not.toHaveBeenCalled();
$location.path('/foo/aaa');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalled();
expect(routeChange).toHaveBeenCalledTimes(2);
routeChange.calls.reset();
$location.path('/foo/bbb');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalled();
expect(routeChange).toHaveBeenCalledTimes(2);
routeChange.calls.reset();
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(routeChange).not.toHaveBeenCalled();
});
});
it('should update params when reloadOnSearch is disabled and .search() changes', function() {
var routeParamsWatcher = jasmine.createSpy('routeParamsWatcher');
module(function($routeProvider) {
$routeProvider.when('/foo', {controller: angular.noop});
$routeProvider.when('/bar/:barId', {controller: angular.noop, reloadOnSearch: false});
});
inject(function($route, $location, $rootScope, $routeParams) {
$rootScope.$watch(function() {
return $routeParams;
}, function(value) {
routeParamsWatcher(value);
}, true);
expect(routeParamsWatcher).not.toHaveBeenCalled();
$location.path('/foo');
$rootScope.$digest();
expect(routeParamsWatcher).toHaveBeenCalledWith({});
routeParamsWatcher.calls.reset();
// trigger reload
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(routeParamsWatcher).toHaveBeenCalledWith({foo: 'bar'});
routeParamsWatcher.calls.reset();
$location.path('/bar/123').search({});
$rootScope.$digest();
expect(routeParamsWatcher).toHaveBeenCalledWith({barId: '123'});
routeParamsWatcher.calls.reset();
// don't trigger reload
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(routeParamsWatcher).toHaveBeenCalledWith({barId: '123', foo: 'bar'});
});
});
it('should allow using a function as a template', function() {
var customTemplateWatcher = jasmine.createSpy('customTemplateWatcher');
function customTemplateFn(routePathParams) {
customTemplateWatcher(routePathParams);
expect(routePathParams).toEqual({id: 'id3'});
return '<h1>' + routePathParams.id + '</h1>';
}
module(function($routeProvider) {
$routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'});
$routeProvider.when('/foo/:id', {template: customTemplateFn});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id3');
$rootScope.$digest();
expect(customTemplateWatcher).toHaveBeenCalledWith({id: 'id3'});
});
});
it('should allow using a function as a templateUrl', function() {
var customTemplateUrlWatcher = jasmine.createSpy('customTemplateUrlWatcher');
function customTemplateUrlFn(routePathParams) {
customTemplateUrlWatcher(routePathParams);
expect(routePathParams).toEqual({id: 'id3'});
return 'foo.html';
}
module(function($routeProvider) {
$routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'});
$routeProvider.when('/foo/:id', {templateUrl: customTemplateUrlFn});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id3');
$rootScope.$digest();
expect(customTemplateUrlWatcher).toHaveBeenCalledWith({id: 'id3'});
expect($route.current.loadedTemplateUrl).toEqual('foo.html');
});
});
describe('reload', function() {
var $location;
var $log;
var $rootScope;
var $route;
var routeChangeStartSpy;
var routeChangeSuccessSpy;
beforeEach(module(function($routeProvider) {
$routeProvider.when('/bar/:barId', {
template: '',
controller: controller,
reloadOnSearch: false
});
function controller($log) {
$log.debug('initialized');
}
}));
beforeEach(inject(function($compile, _$location_, _$log_, _$rootScope_, _$route_) {
$location = _$location_;
$log = _$log_;
$rootScope = _$rootScope_;
$route = _$route_;
routeChangeStartSpy = jasmine.createSpy('routeChangeStart');
routeChangeSuccessSpy = jasmine.createSpy('routeChangeSuccess');
$rootScope.$on('$routeChangeStart', routeChangeStartSpy);
$rootScope.$on('$routeChangeSuccess', routeChangeSuccessSpy);
element = $compile('<div><div ng-view></div></div>')($rootScope);
}));
it('should reload the current route', function() {
$location.path('/bar/123');
$rootScope.$digest();
expect($location.path()).toBe('/bar/123');
expect(routeChangeStartSpy).toHaveBeenCalledOnce();
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
routeChangeStartSpy.calls.reset();
routeChangeSuccessSpy.calls.reset();
$log.reset();
$route.reload();
$rootScope.$digest();
expect($location.path()).toBe('/bar/123');
expect(routeChangeStartSpy).toHaveBeenCalledOnce();
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
$log.reset();
});
it('should support preventing a route reload', function() {
$location.path('/bar/123');
$rootScope.$digest();
expect($location.path()).toBe('/bar/123');
expect(routeChangeStartSpy).toHaveBeenCalledOnce();
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
routeChangeStartSpy.calls.reset();
routeChangeSuccessSpy.calls.reset();
$log.reset();
routeChangeStartSpy.and.callFake(function(evt) { evt.preventDefault(); });
$route.reload();
$rootScope.$digest();
expect($location.path()).toBe('/bar/123');
expect(routeChangeStartSpy).toHaveBeenCalledOnce();
expect(routeChangeSuccessSpy).not.toHaveBeenCalled();
expect($log.debug.logs).toEqual([]);
});
it('should reload even if reloadOnSearch is false', inject(function($routeParams) {
$location.path('/bar/123');
$rootScope.$digest();
expect($routeParams).toEqual({barId: '123'});
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
routeChangeSuccessSpy.calls.reset();
$log.reset();
$location.search('a=b');
$rootScope.$digest();
expect($routeParams).toEqual({barId: '123', a: 'b'});
expect(routeChangeSuccessSpy).not.toHaveBeenCalled();
expect($log.debug.logs).toEqual([]);
$route.reload();
$rootScope.$digest();
expect($routeParams).toEqual({barId: '123', a: 'b'});
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
$log.reset();
}));
});
});
describe('update', function() {
it('should support single-parameter route updating', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1');
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '2'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '2'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/2');
});
});
it('should support total multi-parameter route updating', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId/:fooId/:spamId/:eggId', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1/2/3/4');
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '5', fooId: '6', spamId: '7', eggId: '8'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '7', eggId: '8'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/5/6/7/8');
});
});
it('should support partial multi-parameter route updating', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId/:fooId/:spamId/:eggId', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1/2/3/4');
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '5', fooId: '6'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '3', eggId: '4'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/5/6/3/4');
});
});
it('should update query params when new properties are not in path', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId/:fooId/:spamId/', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1/2/3');
$location.search({initial: 'true'});
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '5', fooId: '6', eggId: '4'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '3', eggId: '4', initial: 'true'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/5/6/3/');
expect($location.search()).toEqual({eggId: '4', initial: 'true'});
});
});
it('should not update query params when an optional property was previously not in path', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId/:fooId/:spamId/:eggId?', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1/2/3');
$location.search({initial: 'true'});
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '5', fooId: '6', eggId: '4'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '3', eggId: '4', initial: 'true'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/5/6/3/4');
expect($location.search()).toEqual({initial: 'true'});
});
});
it('should complain if called without an existing route', inject(function($route) {
expect(function() { $route.updateParams(); }).toThrowMinErr('ngRoute', 'norout');
}));
});
describe('testability', function() {
it('should wait for $resolve promises before calling callbacks', function() {
var deferred;
module(function($provide, $routeProvider) {
$routeProvider.when('/path', {
template: '',
resolve: {
a: function($q) {
deferred = $q.defer();
return deferred.promise;
}
}
});
});
inject(function($location, $route, $rootScope, $httpBackend, $$testability) {
$location.path('/path');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferred.resolve();
$rootScope.$digest();
expect(callback).toHaveBeenCalled();
});
});
it('should call callback after $resolve promises are rejected', function() {
var deferred;
module(function($provide, $routeProvider) {
$routeProvider.when('/path', {
template: '',
resolve: {
a: function($q) {
deferred = $q.defer();
return deferred.promise;
}
}
});
});
inject(function($location, $route, $rootScope, $httpBackend, $$testability) {
$location.path('/path');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferred.reject();
$rootScope.$digest();
expect(callback).toHaveBeenCalled();
});
});
it('should wait for resolveRedirectTo promises before calling callbacks', function() {
var deferred;
module(function($provide, $routeProvider) {
$routeProvider.when('/path', {
resolveRedirectTo: function($q) {
deferred = $q.defer();
return deferred.promise;
}
});
});
inject(function($location, $route, $rootScope, $httpBackend, $$testability) {
$location.path('/path');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferred.resolve();
$rootScope.$digest();
expect(callback).toHaveBeenCalled();
});
});
it('should call callback after resolveRedirectTo promises are rejected', function() {
var deferred;
module(function($provide, $routeProvider) {
$routeProvider.when('/path', {
resolveRedirectTo: function($q) {
deferred = $q.defer();
return deferred.promise;
}
});
});
inject(function($location, $route, $rootScope, $httpBackend, $$testability) {
$location.path('/path');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferred.reject();
$rootScope.$digest();
expect(callback).toHaveBeenCalled();
});
});
it('should wait for all route promises before calling callbacks', function() {
var deferreds = {};
module(function($provide, $routeProvider) {
// While normally `$browser.defer()` modifies the `outstandingRequestCount`, the mocked
// version (provided by `ngMock`) does not. This doesn't matter in most tests, but in this
// case we need the `outstandingRequestCount` logic to ensure that we don't call the
// `$$testability.whenStable()` callbacks part way through a `$rootScope.$evalAsync` block.
// See ngRoute's commitRoute()'s finally() block for details.
$provide.decorator('$browser', function($delegate) {
var oldDefer = $delegate.defer;
var newDefer = function(fn, delay) {
var requestCountAwareFn = function() { $delegate.$$completeOutstandingRequest(fn); };
$delegate.$$incOutstandingRequestCount();
return oldDefer.call($delegate, requestCountAwareFn, delay);
};
$delegate.defer = angular.extend(newDefer, oldDefer);
return $delegate;
});
addRouteWithAsyncRedirect('/foo', '/bar');
addRouteWithAsyncRedirect('/bar', '/baz');
addRouteWithAsyncRedirect('/baz', '/qux');
$routeProvider.when('/qux', {
template: '',
resolve: {
a: function($q) {
var deferred = deferreds['/qux'] = $q.defer();
return deferred.promise;
}
}
});
// Helpers
function addRouteWithAsyncRedirect(fromPath, toPath) {
$routeProvider.when(fromPath, {
resolveRedirectTo: function($q) {
var deferred = deferreds[fromPath] = $q.defer();
return deferred.promise.then(function() { return toPath; });
}
});
}
});
inject(function($browser, $location, $rootScope, $route, $$testability) {
$location.path('/foo');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferreds['/foo'].resolve();
$browser.defer.flush();
expect(callback).not.toHaveBeenCalled();
deferreds['/bar'].resolve();
$browser.defer.flush();
expect(callback).not.toHaveBeenCalled();
deferreds['/baz'].resolve();
$browser.defer.flush();
expect(callback).not.toHaveBeenCalled();
deferreds['/qux'].resolve();
$browser.defer.flush();
expect(callback).toHaveBeenCalled();
});
});
});
});
|
lgalfaso/angular.js
|
test/ngRoute/routeSpec.js
|
JavaScript
|
mit
| 78,403
|
<?php
/*
* This file is part of Gush package.
*
* (c) Luis Cordova <cordoval@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Gush\Tests\Command\Branch;
use Gush\Command\Branch\BranchForkCommand;
use Gush\Tests\Command\CommandTestCase;
use Symfony\Component\Console\Helper\HelperSet;
class BranchForkCommandTest extends CommandTestCase
{
public function testForkRepositoryToUserOrg()
{
$command = new BranchForkCommand();
$tester = $this->getCommandTester(
$command,
null,
null,
function (HelperSet $helperSet) {
$helperSet->set($this->getGitConfigHelper()->reveal());
}
);
$tester->execute();
$display = $tester->getDisplay();
$this->assertCommandOutputMatches(
[
'Forked repository gushphp/gush into cordoval/gush',
'Added remote "cordoval" with "git@github.com:cordoval/gush.git".',
],
$display
);
}
public function testForkRepositoryTosSpecificOrg()
{
$command = new BranchForkCommand();
$tester = $this->getCommandTester(
$command,
null,
null,
function (HelperSet $helperSet) {
$helperSet->set($this->getGitConfigHelper('someone')->reveal());
}
);
$tester->execute(['target_organization' => 'someone']);
$display = $tester->getDisplay();
$this->assertCommandOutputMatches(
[
'Forked repository gushphp/gush into someone/gush',
'Added remote "someone" with "git@github.com:cordoval/gush.git".',
],
$display
);
}
protected function getGitConfigHelper($remoteName = 'cordoval')
{
$gitHelper = parent::getGitConfigHelper();
$gitHelper->setRemote($remoteName, 'git@github.com:cordoval/gush.git')->shouldBeCalled();
return $gitHelper;
}
}
|
sstok/gush
|
tests/Command/Branch/BranchForkCommandTest.php
|
PHP
|
mit
| 2,105
|
import zlib
from test_support import TestFailed
import sys
import imp
try:
t = imp.find_module('test_zlib')
file = t[0]
except ImportError:
file = open(__file__)
buf = file.read() * 8
file.close()
# test the checksums (hex so the test doesn't break on 64-bit machines)
print hex(zlib.crc32('penguin')), hex(zlib.crc32('penguin', 1))
print hex(zlib.adler32('penguin')), hex(zlib.adler32('penguin', 1))
# make sure we generate some expected errors
try:
zlib.compress('ERROR', zlib.MAX_WBITS + 1)
except zlib.error, msg:
print "expecting", msg
try:
zlib.compressobj(1, 8, 0)
except ValueError, msg:
print "expecting", msg
try:
zlib.decompressobj(0)
except ValueError, msg:
print "expecting", msg
x = zlib.compress(buf)
y = zlib.decompress(x)
if buf != y:
print "normal compression/decompression failed"
else:
print "normal compression/decompression succeeded"
buf = buf * 16
co = zlib.compressobj(8, 8, -15)
x1 = co.compress(buf)
x2 = co.flush()
x = x1 + x2
dc = zlib.decompressobj(-15)
y1 = dc.decompress(x)
y2 = dc.flush()
y = y1 + y2
if buf != y:
print "compress/decompression obj failed"
else:
print "compress/decompression obj succeeded"
co = zlib.compressobj(2, 8, -12, 9, 1)
bufs = []
for i in range(0, len(buf), 256):
bufs.append(co.compress(buf[i:i+256]))
bufs.append(co.flush())
combuf = ''.join(bufs)
decomp1 = zlib.decompress(combuf, -12, -5)
if decomp1 != buf:
print "decompress with init options failed"
else:
print "decompress with init options succeeded"
deco = zlib.decompressobj(-12)
bufs = []
for i in range(0, len(combuf), 128):
bufs.append(deco.decompress(combuf[i:i+128]))
bufs.append(deco.flush())
decomp2 = ''.join(bufs)
if decomp2 != buf:
print "decompressobj with init options failed"
else:
print "decompressobj with init options succeeded"
print "should be '':", `deco.unconsumed_tail`
# Check a decompression object with max_length specified
deco = zlib.decompressobj(-12)
cb = combuf
bufs = []
while cb:
max_length = 1 + len(cb)/10
chunk = deco.decompress(cb, max_length)
if len(chunk) > max_length:
print 'chunk too big (%d>%d)' % (len(chunk),max_length)
bufs.append(chunk)
cb = deco.unconsumed_tail
bufs.append(deco.flush())
decomp2 = ''.join(buf)
if decomp2 != buf:
print "max_length decompressobj failed"
else:
print "max_length decompressobj succeeded"
# Misc tests of max_length
deco = zlib.decompressobj(-12)
try:
deco.decompress("", -1)
except ValueError:
pass
else:
print "failed to raise value error on bad max_length"
print "unconsumed_tail should be '':", `deco.unconsumed_tail`
# Test flush() with the various options, using all the different levels
# in order to provide more variations.
sync_opt = ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH']
sync_opt = [getattr(zlib, opt) for opt in sync_opt if hasattr(zlib, opt)]
for sync in sync_opt:
for level in range(10):
obj = zlib.compressobj( level )
d = obj.compress( buf[:3000] )
d = d + obj.flush( sync )
d = d + obj.compress( buf[3000:] )
d = d + obj.flush()
if zlib.decompress(d) != buf:
print "Decompress failed: flush mode=%i, level=%i" % (sync,level)
del obj
# Test for the odd flushing bugs noted in 2.0, and hopefully fixed in 2.1
import random
random.seed(1)
print 'Testing on 17K of random data'
if hasattr(zlib, 'Z_SYNC_FLUSH'):
# Create compressor and decompressor objects
c=zlib.compressobj(9)
d=zlib.decompressobj()
# Try 17K of data
# generate random data stream
a=""
for i in range(17*1024):
a=a+chr(random.randint(0,255))
# compress, sync-flush, and decompress
t = d.decompress( c.compress(a)+c.flush(zlib.Z_SYNC_FLUSH) )
# if decompressed data is different from the input data, choke.
if len(t) != len(a):
print len(a),len(t),len(d.unused_data)
raise TestFailed, "output of 17K doesn't match"
def ignore():
"""An empty function with a big string.
Make the compression algorithm work a little harder.
"""
"""
LAERTES
O, fear me not.
I stay too long: but here my father comes.
Enter POLONIUS
A double blessing is a double grace,
Occasion smiles upon a second leave.
LORD POLONIUS
Yet here, Laertes! aboard, aboard, for shame!
The wind sits in the shoulder of your sail,
And you are stay'd for. There; my blessing with thee!
And these few precepts in thy memory
See thou character. Give thy thoughts no tongue,
Nor any unproportioned thought his act.
Be thou familiar, but by no means vulgar.
Those friends thou hast, and their adoption tried,
Grapple them to thy soul with hoops of steel;
But do not dull thy palm with entertainment
Of each new-hatch'd, unfledged comrade. Beware
Of entrance to a quarrel, but being in,
Bear't that the opposed may beware of thee.
Give every man thy ear, but few thy voice;
Take each man's censure, but reserve thy judgment.
Costly thy habit as thy purse can buy,
But not express'd in fancy; rich, not gaudy;
For the apparel oft proclaims the man,
And they in France of the best rank and station
Are of a most select and generous chief in that.
Neither a borrower nor a lender be;
For loan oft loses both itself and friend,
And borrowing dulls the edge of husbandry.
This above all: to thine ownself be true,
And it must follow, as the night the day,
Thou canst not then be false to any man.
Farewell: my blessing season this in thee!
LAERTES
Most humbly do I take my leave, my lord.
LORD POLONIUS
The time invites you; go; your servants tend.
LAERTES
Farewell, Ophelia; and remember well
What I have said to you.
OPHELIA
'Tis in my memory lock'd,
And you yourself shall keep the key of it.
LAERTES
Farewell.
"""
|
MalloyPower/parsing-python
|
front-end/testsuite-python-lib/Python-2.2/Lib/test/test_zlib.py
|
Python
|
mit
| 6,045
|
# Require Radix Parameter (radix)
When using the `parseInt()` function it is common to omit the second argument, the radix, and let the function try to determine from the first argument what type of number it is. By default, `parseInt()` will autodetect decimal and hexadecimal (via `0x` prefix). Prior to ECMAScript 5, `parseInt()` also autodetected octal literals, which caused problems because many developers assumed a leading `0` would be ignored.
This confusion led to the suggestion that you always use the radix parameter to `parseInt()` to eliminate unintended consequences. So instead of doing this:
```js
var num = parseInt("071"); // 57
```
Do this:
```js
var num = parseInt("071", 10); // 71
```
ECMAScript 5 changed the behavior of `parseInt()` so that it no longer autodetects octal literals and instead treats them as decimal literals. However, the differences between hexadecimal and decimal interpretation of the first parameter causes many developers to continue using the radix parameter to ensure the string is interpreted in the intended way.
On the other hand, if the code is targeting only ES5-compliant environments passing the radix `10` may be redundant. In such a case you might want to disallow using such a radix.
## Rule Details
This rule is aimed at preventing the unintended conversion of a string to a number of a different base than intended or at preventing the redundant `10` radix if targeting modern environments only.
## Options
There are two options for this rule:
* `"always"` enforces providing a radix (default)
* `"as-needed"` disallows providing the `10` radix
### always
Examples of **incorrect** code for the default `"always"` option:
```js
/*eslint radix: "error"*/
var num = parseInt("071");
var num = parseInt(someValue);
var num = parseInt("071", "abc");
var num = parseInt("071", 37);
var num = parseInt();
```
Examples of **correct** code for the default `"always"` option:
```js
/*eslint radix: "error"*/
var num = parseInt("071", 10);
var num = parseInt("071", 8);
var num = parseFloat(someValue);
```
### as-needed
Examples of **incorrect** code for the `"as-needed"` option:
```js
/*eslint radix: ["error", "as-needed"]*/
var num = parseInt("071", 10);
var num = parseInt("071", "abc");
var num = parseInt();
```
Examples of **correct** code for the `"as-needed"` option:
```js
/*eslint radix: ["error", "as-needed"]*/
var num = parseInt("071");
var num = parseInt("071", 8);
var num = parseFloat(someValue);
```
## When Not To Use It
If you don't want to enforce either presence or omission of the `10` radix value you can turn this rule off.
## Further Reading
* [parseInt and radix](https://davidwalsh.name/parseint-radix)
|
pvamshi/eslint
|
docs/rules/radix.md
|
Markdown
|
mit
| 2,732
|
<div>
Specificare facoltativamente <a href='https://ant.apache.org/manual/Types/fileset.html'>il pattern 'excludes'</a>,
ad esempio "pippo/pluto/**/*". Un file corrispondente a questa maschera non
sarà archiviato anche nel caso in cui corrisponda alla maschera specificata
nella sezione "File di cui rilevare le impronte digitali".
</div>
|
v1v/jenkins
|
core/src/main/resources/hudson/tasks/Fingerprinter/help-excludes_it.html
|
HTML
|
mit
| 348
|
using System;
using System.Collections.ObjectModel;
namespace Torshify
{
public interface IPlaylist : ISessionObject
{
#region Events
event EventHandler<DescriptionEventArgs> DescriptionChanged;
event EventHandler<ImageEventArgs> ImageChanged;
event EventHandler MetadataUpdated;
event EventHandler Renamed;
event EventHandler StateChanged;
event EventHandler<TrackCreatedChangedEventArgs> TrackCreatedChanged;
event EventHandler<TracksAddedEventArgs> TracksAdded;
event EventHandler<TrackSeenEventArgs> TrackSeenChanged;
event EventHandler<TracksMovedEventArgs> TracksMoved;
event EventHandler<TracksRemovedEventArgs> TracksRemoved;
event EventHandler<PlaylistUpdateEventArgs> UpdateInProgress;
event EventHandler SubscribersChanged;
#endregion Events
#region Properties
/// <summary>
/// Gets a value indicating whether this playlist is loaded.
/// </summary>
/// <value>
/// <c>true</c> if this playlist is loaded; otherwise, <c>false</c>.
/// </value>
bool IsLoaded
{
get;
}
/// <summary>
/// Gets the description.
/// </summary>
string Description
{
get;
}
/// <summary>
/// Gets the image id.
/// </summary>
string ImageId
{
get;
}
/// <summary>
/// Gets or sets a value indicating whether this playlist is collaborative.
/// </summary>
/// <value>
/// <c>true</c> if this playlist is collaborative; otherwise, <c>false</c>.
/// </value>
bool IsCollaborative
{
get; set;
}
/// <summary>
/// Gets or sets the name of this playilst
/// </summary>
/// <value>
/// The name.
/// </value>
string Name
{
get; set;
}
/// <summary>
/// Gets a value indicating whether this playlist has any pending changes.
/// </summary>
/// <value>
/// <c>true</c> if it has any pending changes; otherwise, <c>false</c>.
/// </value>
bool PendingChanges
{
get;
}
/// <summary>
/// Gets the tracks for this playlist
/// </summary>
IPlaylistTrackList Tracks
{
get;
}
/// <summary>
/// Get offline status
/// </summary>
/// <remarks>
/// When in Downloading mode, the GetOfflineDownloadCompleted() can be used to query progress of the download
/// </remarks>
PlaylistOfflineStatus OfflineStatus
{
get;
}
/// <summary>
/// Returns a collection of canonical usernames of who are subscribing to this playlist
/// </summary>
ReadOnlyCollection<string> Subscribers
{
get;
}
/// <summary>
/// Returns the owner of the playlist
/// </summary>
IUser Owner
{
get;
}
/// <summary>
/// Return whether a playlist is loaded in RAM (as opposed to only stored on disk)
/// </summary>
bool IsInRam
{
get;
set;
}
#endregion Properties
#region Methods
/// <summary>
/// Set autolinking state for the playlist
///
/// If a playlist is autolinked, unplayable tracks will be made playable
/// by linking them to other Spotify tracks, where possible.
/// </summary>
/// <param name="autoLink">if set to <c>true</c> auto linking is enabled.</param>
void AutoLinkTracks(bool autoLink);
/// <summary>
/// Mark a playlist to be synchronized for offline playback
/// </summary>
/// <param name="offline"></param>
void SetOfflineMode(bool offline);
/// <summary>
/// Get download progress for an offline playlist
/// </summary>
/// <returns>Value from 0 - 100 that indicates amount of playlist that is downloaded</returns>
int GetOfflineDownloadCompleted();
/// <summary>
/// Ask library to update the subscription count for a playlist
/// </summary>
void UpdateSubscribers();
#endregion Methods
}
}
|
torshy/torshify
|
src/Torshify/IPlaylist.cs
|
C#
|
mit
| 4,519
|
class Groups::GroupMembersController < Groups::ApplicationController
skip_before_filter :authenticate_user!, only: [:index]
before_filter :group
# Authorize
before_filter :authorize_read_group!
before_filter :authorize_admin_group!, except: [:index, :leave]
layout :determine_layout
def index
@project = @group.projects.find(params[:project_id]) if params[:project_id]
@members = @group.group_members
@members = @members.non_invite unless can?(current_user, :admin_group, @group)
if params[:search].present?
users = @group.users.search(params[:search]).to_a
@members = @members.where(user_id: users)
end
@members = @members.order('access_level DESC').page(params[:page]).per(50)
@group_member = GroupMember.new
end
def create
@group.add_users(params[:user_ids].split(','), params[:access_level], current_user)
redirect_to group_group_members_path(@group), notice: 'Users were successfully added.'
end
def update
@member = @group.group_members.find(params[:id])
@member.update_attributes(member_params)
end
def destroy
@group_member = @group.group_members.find(params[:id])
if can?(current_user, :destroy_group_member, @group_member) # May fail if last owner.
@group_member.destroy
respond_to do |format|
format.html { redirect_to group_group_members_path(@group), notice: 'User was successfully removed from group.' }
format.js { render nothing: true }
end
else
return render_403
end
end
def resend_invite
redirect_path = group_group_members_path(@group)
@group_member = @group.group_members.find(params[:id])
if @group_member.invite?
@group_member.resend_invite
redirect_to redirect_path, notice: 'The invitation was successfully resent.'
else
redirect_to redirect_path, alert: 'The invitation has already been accepted.'
end
end
def leave
@group_member = @group.group_members.where(user_id: current_user.id).first
if can?(current_user, :destroy_group_member, @group_member)
@group_member.destroy
redirect_to(dashboard_groups_path, notice: "You left #{group.name} group.")
else
return render_403
end
end
protected
def group
@group ||= Group.find_by(path: params[:group_id])
end
def member_params
params.require(:group_member).permit(:access_level, :user_id)
end
end
|
PoojaWEP/Final_gitlancer
|
app/controllers/groups/group_members_controller.rb
|
Ruby
|
mit
| 2,433
|
import { usingEvalSync, usingEval } from '../lib/utils'
export async function getServerSideProps() {
return {
props: await usingEval(),
}
}
export default function Page(props) {
return (
<div>
{props.value} and {usingEvalSync().value}
</div>
)
}
|
zeit/next.js
|
test/integration/middleware/with-eval/pages/index.js
|
JavaScript
|
mit
| 274
|
require 'grape/exceptions/base'
module Grape
module Exceptions
class Validation < Grape::Exceptions::Base
attr_accessor :params
attr_accessor :message_key
def initialize(args = {})
fail 'Params are missing:' unless args.key? :params
@params = args[:params]
args[:message] = translate_message(args[:message]) if args.key? :message
super
end
# remove all the unnecessary stuff from Grape::Exceptions::Base like status
# and headers when converting a validation error to json or string
def as_json(*_args)
to_s
end
def to_s
message
end
end
end
end
|
niedhui/grape
|
lib/grape/exceptions/validation.rb
|
Ruby
|
mit
| 669
|
from django import template
from django.shortcuts import render_to_response, redirect, get_object_or_404
# from product.models import Slide
register = template.Library()
# @register.inclusion_tag('slides/slides.html')
# def get_main_slides():
# slides = Slide.objects.filter(published_main=1).order_by('ordering')
# return {'slides': slides}
# @register.inclusion_tag('comments/comments.html')
# def comments(paket, item_model, item_id):
# from comments.models import Comments
# nodes = Comments.objects.filter(paket=paket, item_model=item_model,item_id=item_id, published=1)
# return {'nodes':nodes, 'paket':paket, 'item_model':item_model, 'item_id':item_id}
# @register.filter(name='suit_conf')
# def suit_conf(name):
# value = get_config(name)
# return mark_safe(value) if isinstance(value, str) else value
# @register.tag
# def suit_date(parser, token):
# return NowNode(get_config('HEADER_DATE_FORMAT'))
# @register.tag
# def suit_time(parser, token):
# return NowNode(get_config('HEADER_TIME_FORMAT'))
# @register.filter
# def field_contents_foreign_linked(admin_field):
# """Return the .contents attribute of the admin_field, and if it
# is a foreign key, wrap it in a link to the admin page for that
# object.
# Use by replacing '{{ field.contents }}' in an admin template (e.g.
# fieldset.html) with '{{ field|field_contents_foreign_linked }}'.
# """
# fieldname = admin_field.field['field']
# displayed = admin_field.contents()
# obj = admin_field.form.instance
# if not hasattr(admin_field.model_admin,
# 'linked_readonly_fields') or fieldname not in admin_field \
# .model_admin \
# .linked_readonly_fields:
# return displayed
# try:
# fieldtype, attr, value = lookup_field(fieldname, obj,
# admin_field.model_admin)
# except ObjectDoesNotExist:
# fieldtype = None
# if isinstance(fieldtype, ForeignKey):
# try:
# url = admin_url(value)
# except NoReverseMatch:
# url = None
# if url:
# displayed = "<a href='%s'>%s</a>" % (url, displayed)
# return mark_safe(displayed)
# @register.filter
# def admin_url(obj):
# info = (obj._meta.app_label, obj._meta.module_name)
# return reverse("admin:%s_%s_change" % info, args=[obj.pk])
# @register.simple_tag
# def suit_bc(*args):
# return utils.value_by_version(args)
# @register.assignment_tag
# def suit_bc_value(*args):
# return utils.value_by_version(args)
|
skylifewww/pangolin-fog
|
product/templatetags/category_tags.py
|
Python
|
mit
| 2,627
|
東京 SHIRASAGI ハンズオン用 Vagrant
===
東京 SHIRASAGI ハンズオン用 Vagrantを公開します。
## 使用方法
適当なディレクトリを作成し、次のような内容を持つ Vagrantfile を作成してください。
64 ビット OS をお使いの方:
$ mkdir tokyo-handson
$ cd tokyo-handson
$ cat Vagrantfile
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ss-vagrant"
config.vm.box_url = "https://github.com/shirasagi/ss-vagrant/releases/download/v0.7.0-SNAPSHOT-20150406-1849/ss-vagrant-virtualbox.box"
config.vm.network :forwarded_port, guest: 3000, host: 3000
config.vm.provider :virtualbox do |vb|
# see: http://blog.shibayu36.org/entry/2013/08/12/090545
# IPv6 と DNS でのネットワーク遅延対策で追記
vb.customize ["modifyvm", :id, "--natdnsproxy1", "off"]
vb.customize ["modifyvm", :id, "--natdnshostresolver1", "off"]
end
end
32 ビット OS をお使いの方:
$ mkdir tokyo-handson
$ cd tokyo-handson
$ cat Vagrantfile
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ss-vagrant"
config.vm.box_url = "https://github.com/shirasagi/ss-vagrant/releases/download/v0.7.0-SNAPSHOT-20150406-1849/ss-vagrant-virtualbox-i386.box"
config.vm.network :forwarded_port, guest: 3000, host: 3000
config.vm.provider :virtualbox do |vb|
# see: http://blog.shibayu36.org/entry/2013/08/12/090545
# IPv6 と DNS でのネットワーク遅延対策で追記
vb.customize ["modifyvm", :id, "--natdnsproxy1", "off"]
vb.customize ["modifyvm", :id, "--natdnshostresolver1", "off"]
end
end
次のコマンドで起動できます。
```
$ vagrant up
```
5 分から 10 分ぐらいかかるので、コーヒーでも飲みながら待ってください。
起動したら ssh クライアントでログインしてください。
* host: localhost
* port: 2222
* user: vagrant
* password: vagrant
東京 SHIRASAGI ハンズオン用 Vagrant には、SHIRASAGI が `/vagrant/home` にインストールされています。
```
$ tree -L 2 /vagrant/home
/home/vagrant
`-- shirasagi
|-- app
|-- bin
|-- config
|-- config.ru
|-- db
|-- doc
|-- Gemfile
|-- Gemfile.lock
|-- Guardfile
|-- lib
|-- MIT-LICENSE
|-- private
|-- public
|-- Rakefile
|-- README.md
|-- spec
`-- vendor
```
SHIRASAGI を起動してみましょう。
```
$ cd $HOME/shirasagi
$ bundle exec rake unicorn:start
bundle exec unicorn_rails -c /home/vagrant/shirasagi/config/unicorn.rb -E production -D
```
ブラウザで "http://localhost:3000/" にアクセスしてみましょう。 次のような画面が表示された成功です。

## Vagrant について
Vagrant Box を使用するには、別途 VirtualBox と Vagrant のインストールが必要です。
それぞれ以下の場所からダウンロードし、インストールしてください。
* VirtualBox: [VirtualBox Download](https://www.virtualbox.org/wiki/Downloads)
* Vagrant: [Vagrant Download](http://www.vagrantup.com/downloads.html)
## Vagrant Box の中身
* CentOS 6.6 (2015-04-06 時点での最新)
* MongoDB 2.6.9
* Ruby 2.2.1p85
* SHIRASAGI のソース一式 (2015-04-06 時点での最新)
32 ビット版の制限:
* MongoDB の最大サイズがジャーナルを含めて 2 GB に制限されています。
|
sunny4381/ss-handson
|
doc/hands-on-0422/hands-on-vagrant.md
|
Markdown
|
mit
| 3,616
|
<?php
/*
* This file is part of the Symfony CS utility.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Symfony\CS\Tests\Fixer\PSR2;
use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*/
class MultipleUseFixerTest extends AbstractFixerTestBase
{
public function testFix()
{
$expected = <<<'EOF'
use Some, Not, PHP, Like, Use, Statement;
<?php
use Foo;
use FooA;
use FooB;
use FooC;
use FooD as D;
use FooE;
use FooF;
use FooG as G;
use FooH;
use FooI;
use FooJ;
use FooZ;
namespace Boo {
use Bar;
use BarA;
use BarB;
use BarC;
use BarD as D;
use BarE;
use BarF;
use BarG as G;
use BarH;
use BarI;
use BarJ;
use BarZ;
}
EOF;
$input = <<<'EOF'
use Some, Not, PHP, Like, Use, Statement;
<?php
use Foo;
use FooA, FooB;
use FooC, FooD as D, FooE;
use FooF,
FooG as G,
FooH, FooI,
FooJ;
use FooZ;
namespace Boo {
use Bar;
use BarA, BarB;
use BarC, BarD as D, BarE;
use BarF,
BarG as G,
BarH, BarI,
BarJ;
use BarZ;
}
EOF;
$this->makeTest($expected, $input);
}
}
|
MicHaeLann/new_best365
|
vendor/fabpot/php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/MultipleUseFixerTest.php
|
PHP
|
mit
| 1,311
|
#-*- encoding:utf-8 -*-
'''
Created on Nov 30, 2014
@author: letian
'''
import networkx as nx
from Segmentation import Segmentation
import numpy as np
class TextRank4Keyword(object):
def __init__(self, stop_words_file = None, delimiters = '?!;?!。;…\n'):
'''
`stop_words_file`:默认值为None,此时内部停止词表为空;可以设置为文件路径(字符串),将从停止词文件中提取停止词。
`delimiters`:默认值是`'?!;?!。;…\n'`,用来将文本拆分为句子。
self.words_no_filter:对sentences中每个句子分词而得到的两级列表。
self.words_no_stop_words:去掉words_no_filter中的停止词而得到的两级列表。
self.words_all_filters:保留words_no_stop_words中指定词性的单词而得到的两级列表。
'''
self.text = ''
self.keywords = []
self.seg = Segmentation(stop_words_file=stop_words_file, delimiters=delimiters)
self.words_no_filter = None # 2维列表
self.words_no_stop_words = None
self.words_all_filters = None
self.word_index = {}
self.index_word = {}
self.graph = None
def train(self, text, window = 2, lower = False, speech_tag_filter=True,
vertex_source = 'all_filters',
edge_source = 'no_stop_words'):
'''
`text`:文本内容,字符串。
`window`:窗口大小,int,用来构造单词之间的边。默认值为2。
`lower`:是否将文本转换为小写。默认为False。
`speech_tag_filter`:若值为True,将调用内部的词性列表来过滤生成words_all_filters。
若值为False,words_all_filters与words_no_stop_words相同。
`vertex_source`:选择使用words_no_filter, words_no_stop_words, words_all_filters中的哪一个来构造pagerank对应的图中的节点。
默认值为`'all_filters'`,可选值为`'no_filter', 'no_stop_words', 'all_filters'`。关键词也来自`vertex_source`。
`edge_source`:选择使用words_no_filter, words_no_stop_words, words_all_filters中的哪一个来构造pagerank对应的图中的节点之间的边。
默认值为`'no_stop_words'`,可选值为`'no_filter', 'no_stop_words', 'all_filters'`。边的构造要结合`window`参数。
'''
self.text = text
self.word_index = {}
self.index_word = {}
self.keywords = []
self.graph = None
(_, self.words_no_filter, self.words_no_stop_words, self.words_all_filters) = self.seg.segment(text=text,
lower=lower,
speech_tag_filter=speech_tag_filter)
if vertex_source == 'no_filter':
vertex_source = self.words_no_filter
elif vertex_source == 'no_stop_words':
vertex_source = self.words_no_stop_words
else:
vertex_source = self.words_all_filters
if edge_source == 'no_filter':
edge_source = self.words_no_filter
elif vertex_source == 'all_filters':
edge_source = self.words_all_filters
else:
edge_source = self.words_no_stop_words
index = 0
for words in vertex_source:
for word in words:
if not self.word_index.has_key(word):
self.word_index[word] = index
self.index_word[index] = word
index += 1
words_number = index # 单词数量
self.graph = np.zeros((words_number, words_number))
for word_list in edge_source:
for w1, w2 in self.combine(word_list, window):
if not self.word_index.has_key(w1):
continue
if not self.word_index.has_key(w2):
continue
index1 = self.word_index[w1]
index2 = self.word_index[w2]
self.graph[index1][index2] = 1.0
self.graph[index2][index1] = 1.0
# for x in xrange(words_number):
# row_sum = np.sum(self.graph[x, :])
# if row_sum > 0:
# self.graph[x, :] = self.graph[x, :] / row_sum
nx_graph = nx.from_numpy_matrix(self.graph)
scores = nx.pagerank(nx_graph) # this is a dict
sorted_scores = sorted(scores.items(), key = lambda item: item[1], reverse=True)
for index, _ in sorted_scores:
self.keywords.append(self.index_word[index])
def combine(self, word_list, window = 2):
'''
构造在window下的单词组合,用来构造单词之间的边。使用了生成器。
word_list: 由单词组成的列表。
windows:窗口大小。
'''
window = int(window)
if window < 2: window = 2
for x in xrange(1, window):
if x >= len(word_list):
break
word_list2 = word_list[x:]
res = zip(word_list, word_list2)
for r in res:
yield r
def get_keywords(self, num = 6, word_min_len = 1):
'''
获取最重要的num个长度大于等于word_min_len的关键词。
返回关键词列表。
'''
result = []
count = 0
for word in self.keywords:
if count >= num:
break
if len(word) >= word_min_len:
result.append(word)
count += 1
return result
def get_keyphrases(self, keywords_num = 12, min_occur_num = 2):
'''
获取关键短语。
获取 keywords_num 个关键词构造在可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。
返回关键短语的列表。
'''
keywords_set = set(self.get_keywords(num=keywords_num, word_min_len = 1))
keyphrases = set()
one = []
for sentence_list in self.words_no_filter:
for word in sentence_list:
# print '/'.join(one)
# print word
if word in keywords_set:
one.append(word)
else:
if len(one)>1:
keyphrases.add(''.join(one))
one = []
continue
one = []
return [phrase for phrase in keyphrases
if self.text.count(phrase) >= min_occur_num]
if __name__ == '__main__':
import codecs
text = codecs.open('../text/02.txt', 'r', 'utf-8').read()
# text = "坏人"
tr4w = TextRank4Keyword(stop_words_file='../stopword.data')
tr4w.train(text=text, speech_tag_filter=True, lower=True, window=2)
for word in tr4w.get_keywords(10, word_min_len=2):
print word
print '---'
for phrase in tr4w.get_keyphrases(keywords_num=20, min_occur_num= 2):
print phrase
|
MSC19950601/TextRank4ZH
|
textrank4zh/TextRank4Keyword.py
|
Python
|
mit
| 7,411
|
<?php
namespace Oro\Bundle\EntityBundle\Tests\Functional\Controller;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;
class DictionaryControllerTest extends WebTestCase
{
protected function setUp()
{
$this->initClient([], $this->generateBasicAuthHeader());
}
public function testSearch()
{
$expectedJson = '{"results":[{"id":"UM","value":"UM","text":"United States Minor Outlying Islands"},
{"id":"US","value":"US","text":"United States"}]}';
$this->client->request(
'POST',
$this->getUrl('oro_dictionary_search', ['dictionary' => 'Oro_Bundle_AddressBundle_Entity_Country']),
['q' => 'United States']
);
$result = $this->client->getResponse();
$this->assertJsonResponseStatusCodeEquals($result, 200);
$this->assertJsonStringEqualsJsonString($expectedJson, $result->getContent());
}
public function testLoadValue()
{
$expectedJson = '{"results":[{"id":"UM","value":"UM","text":"United States Minor Outlying Islands"},
{"id":"US","value":"US","text":"United States"}]}';
$this->client->request(
'POST',
$this->getUrl('oro_dictionary_value', ['dictionary'=>'Oro_Bundle_AddressBundle_Entity_Country']),
[
'keys'=>['US','UM']
]
);
$result = $this->client->getResponse();
$this->assertJsonResponseStatusCodeEquals($result, 200);
$this->assertJsonStringEqualsJsonString($expectedJson, $result->getContent());
}
}
|
Djamy/platform
|
src/Oro/Bundle/EntityBundle/Tests/Functional/Controller/DictionaryControllerTest.php
|
PHP
|
mit
| 1,575
|
#pragma once
#include <string>
#include "tnet_http.h"
namespace tnet
{
class WsClient : public nocopyable
, public std::enable_shared_from_this<WsClient>
{
public:
WsClient(IOLoop* loop);
~WsClient();
//now only support ip:port
void connect(const std::string& url, const WsCallback_t& callback);
void connect(const std::string& url, const Headers_t& headers, const WsCallback_t& callback);
private:
void connect(HttpRequest& request, const WsCallback_t& callback);
void onResponse(const HttpConnectorPtr_t&, const HttpResponse&, ResponseEvent, const WsCallback_t&);
void onConnect(const HttpConnectorPtr_t& conn, bool connected, const std::string& requestData, const WsCallback_t& callback);
private:
IOLoop* m_loop;
};
}
|
xujun10110/libtnet
|
src/http/wsclient.h
|
C
|
mit
| 853
|
<?php
namespace App\Events\VisitTransfer;
use App\Models\VisitTransfer\Application;
use Illuminate\Queue\SerializesModels;
class ApplicationCompleted extends ApplicationStatusChanged
{
use SerializesModels;
public $application = null;
public function __construct(Application $application)
{
$this->application = $application;
}
}
|
atoff/core
|
app/Events/VisitTransfer/ApplicationCompleted.php
|
PHP
|
mit
| 363
|
var assert = require('assert');
var common = require('../../common');
var cluster = common.createPoolCluster({canRetry: false});
var server = common.createFakeServer();
var connCount = 0;
var poolConfig = common.getTestConfig({port: common.fakeServerPort});
cluster.add('MASTER', poolConfig);
server.listen(common.fakeServerPort, function(err) {
assert.ifError(err);
cluster.getConnection('MASTER', function (err) {
assert.ok(err);
assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR');
assert.equal(err.fatal, true);
assert.equal(connCount, 1);
cluster.end(function (err) {
assert.ifError(err);
server.destroy();
});
});
});
server.on('connection', function (conn) {
connCount += 1;
conn.deny();
});
|
mysqljs/mysql
|
test/unit/pool-cluster/test-connection-no-retry.js
|
JavaScript
|
mit
| 751
|
package main
import (
"fmt"
"time"
"github.com/hybridgroup/gobot"
"github.com/hybridgroup/gobot/platforms/beaglebone"
"github.com/hybridgroup/gobot/platforms/i2c"
)
func main() {
gbot := gobot.NewGobot()
beagleboneAdaptor := beaglebone.NewBeagleboneAdaptor("beaglebone")
blinkm := i2c.NewBlinkMDriver(beagleboneAdaptor, "blinkm")
work := func() {
gobot.Every(3*time.Second, func() {
r := byte(gobot.Rand(255))
g := byte(gobot.Rand(255))
b := byte(gobot.Rand(255))
blinkm.Rgb(r, g, b)
color, _ := blinkm.Color()
fmt.Println("color", color)
})
}
robot := gobot.NewRobot("blinkmBot",
[]gobot.Connection{beagleboneAdaptor},
[]gobot.Device{blinkm},
work,
)
gbot.AddRobot(robot)
gbot.Start()
}
|
Jay-AHR/qpid_em
|
vendor/github.com/hybridgroup/gobot/examples/beaglebone_blinkm.go
|
GO
|
mit
| 737
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Debian -- Details of package sysvinit-utils in wheezy</title>
<link rev="made" href="mailto:webmaster@debian.org">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="Author" content="Debian Webmaster, webmaster@debian.org">
<meta name="Description" content="System-V-like utilities">
<meta name="Keywords" content="Debian, wheezy, us, main, admin, 2.88dsf-41+deb7u1">
<link href="/debpkg.css" rel="stylesheet" type="text/css" media="all">
<script src="/packages.js" type="text/javascript"></script>
</head>
<body>
<div id="header">
<div id="upperheader">
<div id="logo">
<!-- very Debian specific use of the logo stuff -->
<a href="http://www.debian.org/"><img src="/Pics/openlogo-50.png" alt="Debian" with="50" height="61"></a>
</div> <!-- end logo -->
<p class="hidecss"><a href="#inner">skip the navigation</a></p>
<p class="section"><a href="/">Packages</a></p>
</div> <!-- end upperheader -->
<!-- navbar -->
<div id="navbar">
<ul>
<li><a href="http://www.debian.org/intro/about">About Debian</a></li>
<li><a href="http://www.debian.org/distrib/">Getting Debian</a></li>
<li><a href="http://www.debian.org/support">Support</a></li>
<li><a href="http://www.debian.org/devel/">Developers' Corner</a></li>
</ul>
</div> <!-- end navbar -->
<div id="pnavbar">
/ <a href="/" title="Debian Packages Homepage">Packages</a>
/ <a href="/wheezy/" title="Overview over this suite">wheezy (stable)</a>
/ <a href="/wheezy/admin/" title="All packages in this section">admin</a>
/ sysvinit-utils
</div> <!-- end navbar -->
</div> <!-- end header -->
<div id="content">
<form method="GET" action="/search">
<div id="hpacketsearch">
<input type="submit" value="Search">
<select size="1" name="searchon">
<option value="names" selected="selected">
package names</option>
<option value="all" >descriptions</option>
<option value="sourcenames" >source package names</option>
<option value="contents" >package contents</option>
</select>
<input type="text" size="30" name="keywords" value="" id="kw">
<span style="font-size: 60%"><a href="/">all options</a></span>
</div> <!-- end hpacketsearch -->
</form>
<!-- show.tmpl -->
<div id="pothers"> [ <a href="/squeeze/sysvinit-utils">squeeze</a> ]
[ <strong>wheezy</strong> ]
[ <a href="/jessie/sysvinit-utils">jessie</a> ]
[ <a href="/sid/sysvinit-utils">sid</a> ]</div>
<div id="psource">
[ Source: <a title="Source package building this package" href="/source/wheezy/sysvinit">sysvinit</a> ]
</div>
<!-- messages.tmpl -->
<h1>Package: sysvinit-utils (2.88dsf-41+deb7u1)
[<a href="http://www.debian.org/doc/debian-policy/ch-binary.html#s3.8"><strong class="pmarker" title="package manager will refuse to remove this package by default">essential</strong></a>] </h1>
<div id="pmoreinfo">
<h2>Links for sysvinit-utils</h2>
<div class="screenshot">
<a id="screenshot" href="//screenshots.debian.net/package/sysvinit-utils"><img src="//screenshots.debian.net/thumbnail-with-version//sysvinit-utils/2.88dsf-41+deb7u1" alt="Screenshot" border="0"/></a>
</div>
<h3>Debian Resources:</h3>
<ul>
<li><a href="http://bugs.debian.org/sysvinit-utils">Bug Reports</a></li>
<li><a href="http://packages.qa.debian.org/sysvinit">Developer Information (PTS)</a></li>
<li><a href="http://ftp-master.metadata.debian.org/changelogs//main/s/sysvinit/sysvinit_2.88dsf-41+deb7u1_changelog">Debian Changelog</a></li>
<li><a href="http://ftp-master.metadata.debian.org/changelogs//main/s/sysvinit/sysvinit_2.88dsf-41+deb7u1_copyright">Copyright File</a></li>
<li><a href="http://patch-tracker.debian.org/package/sysvinit/2.88dsf-41+deb7u1">Debian Patch Tracker</a></li>
</ul>
<h3>Download Source Package <a href="/source/wheezy/sysvinit">sysvinit</a>:</h3>
<ul>
<li><a href="http://ftp.de.debian.org/debian/pool/main/s/sysvinit/sysvinit_2.88dsf-41+deb7u1.dsc">[sysvinit_2.88dsf-41+deb7u1.dsc]</a></li>
<li><a href="http://ftp.de.debian.org/debian/pool/main/s/sysvinit/sysvinit_2.88dsf.orig.tar.gz">[sysvinit_2.88dsf.orig.tar.gz]</a></li>
<li><a href="http://ftp.de.debian.org/debian/pool/main/s/sysvinit/sysvinit_2.88dsf-41+deb7u1.debian.tar.gz">[sysvinit_2.88dsf-41+deb7u1.debian.tar.gz]</a></li>
</ul>
<h3>Maintainers:</h3><ul> <li><a href="mailto:pkg-sysvinit-devel@lists.alioth.debian.org">Debian sysvinit maintainers</a>
(<a href="http://qa.debian.org/developer.php?login=pkg-sysvinit-devel%40lists.alioth.debian.org" title="An overview over the maintainer's packages and uploads">QA Page</a>, <a href="http://lists.alioth.debian.org/pipermail/pkg-sysvinit-devel/" title="Archive of the Maintainer Mailinglist">Mail Archive</a>)
</li> <li><a href="mailto:pere@debian.org">Petter Reinholdtsen</a>
(<a href="http://qa.debian.org/developer.php?login=pere%40debian.org" title="An overview over the maintainer's packages and uploads">QA Page</a>)
</li> <li><a href="mailto:hmh@debian.org">Henrique de Moraes Holschuh</a>
(<a href="http://qa.debian.org/developer.php?login=hmh%40debian.org" title="An overview over the maintainer's packages and uploads">QA Page</a>)
</li> <li><a href="mailto:kel@otaku42.de">Kel Modderman</a>
(<a href="http://qa.debian.org/developer.php?login=kel%40otaku42.de" title="An overview over the maintainer's packages and uploads">QA Page</a>)
</li> <li><a href="mailto:rleigh@debian.org">Roger Leigh</a>
(<a href="http://qa.debian.org/developer.php?login=rleigh%40debian.org" title="An overview over the maintainer's packages and uploads">QA Page</a>)
</li></ul>
<h3>External Resources:</h3>
<ul>
<li><a href="http://savannah.nongnu.org/projects/sysvinit">Homepage</a> [savannah.nongnu.org]</li>
</ul>
<h3>Similar packages:</h3>
<ul>
<li><a href="/sysvinit">sysvinit</a></li>
<li><a href="/util-linux">util-linux</a></li>
<li><a href="/sysvinit-core">sysvinit-core</a></li>
<li><a href="/sysv-rc">sysv-rc</a></li>
<li><a href="/psmisc">psmisc</a></li>
<li><a href="/net-tools">net-tools</a></li>
<li><a href="/bsdutils">bsdutils</a></li>
<li><a href="/coreutils">coreutils</a></li>
<li><a href="/rcconf">rcconf</a></li>
<li><a href="/puppet">puppet</a></li>
</ul>
</div> <!-- end pmoreinfo -->
<div id="ptablist">
</div>
<div id="pdesctab">
<div id="pdesc" >
<h2>System-V-like utilities</h2>
<p>
This package contains the important System-V-like utilities.
<p>
Specifically, this package includes:
killall5, last, lastb, mesg, pidof, service, sulogin
</div> <!-- end pdesc -->
<div id="ptags"><p>
<a href="http://debtags.alioth.debian.org/edit.html?pkg=sysvinit-utils">Tags</a>:
System Administration:
<a href="/about/debtags#admin::login">Login</a>,
Implemented in:
<a href="/about/debtags#implemented-in::c">C</a>,
User Interface:
<a href="/about/debtags#interface::commandline">Command Line</a>,
Role:
role::program,
scope::utility,
Works with:
<a href="/about/debtags#works-with::software:running">Running Programs</a>
</p>
</div> <!-- end ptags -->
</div> <!-- pdesctab -->
<div id="pdeps">
<h2>Other Packages Related to sysvinit-utils</h2>
<table id="pdeplegend" class="visual" summary="legend"><tr>
<td><ul class="uldep"><li>depends</li></ul></td>
<td><ul class="ulrec"><li>recommends</li></ul></td>
<td><ul class="ulsug"><li>suggests</li></ul></td>
<td><ul class="ulenh"><li>enhances</li></ul></td>
</tr></table>
<ul class="uldep">
<li>
<dl>
<dt><span class="nonvisual">dep:</span>
<a href="/wheezy/libc0.1">libc0.1</a>
(>= 2.8)
[kfreebsd-amd64, kfreebsd-i386]</dt> <dd lang="en">Embedded GNU C Library: Shared libraries <br>also a virtual package provided by
<span id="js_libc0.1" class="p_js_elem"></span> <span id="html_libc0.1"><a href="/wheezy/libc0.1-udeb">libc0.1-udeb</a></span>
</dd>
</dl>
<li>
<dl>
<dt><span class="nonvisual">dep:</span>
<a href="/wheezy/libc6">libc6</a>
(>= 2.10)
[not armhf, ia64, kfreebsd-amd64, kfreebsd-i386, s390x]</dt> <dd lang="en">Embedded GNU C Library: Shared libraries <br>also a virtual package provided by
<span id="js_libc6" class="p_js_elem"></span> <span id="html_libc6"><a href="/wheezy/libc6-udeb">libc6-udeb</a></span>
</dd>
</dl>
<dl>
<dt><span class="nonvisual">dep:</span>
<a href="/wheezy/libc6">libc6</a>
(>= 2.13)
[s390x]</dt>
</dl>
<dl>
<dt><span class="nonvisual">dep:</span>
<a href="/wheezy/libc6">libc6</a>
(>= 2.13-28)
[armhf]</dt>
</dl>
<li>
<dl>
<dt><span class="nonvisual">dep:</span>
<a href="/wheezy/libc6.1">libc6.1</a>
(>= 2.13-25~)
[ia64]</dt> <dd lang="en">Embedded GNU C Library: Shared libraries <br>also a virtual package provided by
<span id="js_libc6.1" class="p_js_elem"></span> <span id="html_libc6.1"><a href="/wheezy/libc6.1-udeb">libc6.1-udeb</a></span>
</dd>
</dl>
<li>
<dl>
<dt><span class="nonvisual">dep:</span>
<a href="/wheezy/libselinux1">libselinux1</a>
(>= 1.32)
[not kfreebsd-amd64, kfreebsd-i386]</dt> <dd lang="en">SELinux runtime shared libraries
</dd>
</dl>
</ul>
<ul class="ulsug">
<li>
<dl>
<dt><span class="nonvisual">sug:</span>
<a href="/wheezy/bootlogd">bootlogd</a>
</dt> <dd lang="en">daemon to log boot messages
</dd>
</dl>
<li>
<dl>
<dt><span class="nonvisual">sug:</span>
<a href="/wheezy/sash">sash</a>
</dt> <dd lang="en">Stand-alone shell
</dd>
</dl>
</ul>
</div> <!-- end pdeps -->
<div id="pdownload">
<h2>Download sysvinit-utils</h2>
<table summary="The download table links to the download of the package and a file overview. In addition it gives information about the package size and the installed size.">
<caption class="hidecss">Download for all available architectures</caption>
<tr><th>Architecture</th>
<th>Package Size</th>
<th>Installed Size</th>
<th>Files</th>
</tr>
<tr>
<th><a href="/wheezy/amd64/sysvinit-utils/download">amd64</a></th>
<td class="size">97.8 kB</td><td class="size">272.0 kB</td>
<td>
[<a href="/wheezy/amd64/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/armel/sysvinit-utils/download">armel</a></th>
<td class="size">97.9 kB</td><td class="size">215.0 kB</td>
<td>
[<a href="/wheezy/armel/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/armhf/sysvinit-utils/download">armhf</a></th>
<td class="size">92.7 kB</td><td class="size">203.0 kB</td>
<td>
[<a href="/wheezy/armhf/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/i386/sysvinit-utils/download">i386</a></th>
<td class="size">95.7 kB</td><td class="size">218.0 kB</td>
<td>
[<a href="/wheezy/i386/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/ia64/sysvinit-utils/download">ia64</a></th>
<td class="size">115.1 kB</td><td class="size">293.0 kB</td>
<td>
[<a href="/wheezy/ia64/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/kfreebsd-amd64/sysvinit-utils/download">kfreebsd-amd64</a></th>
<td class="size">95.1 kB</td><td class="size">169.0 kB</td>
<td>
[<a href="/wheezy/kfreebsd-amd64/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/kfreebsd-i386/sysvinit-utils/download">kfreebsd-i386</a></th>
<td class="size">92.6 kB</td><td class="size">156.0 kB</td>
<td>
[<a href="/wheezy/kfreebsd-i386/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/mips/sysvinit-utils/download">mips</a></th>
<td class="size">96.3 kB</td><td class="size">223.0 kB</td>
<td>
[<a href="/wheezy/mips/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/mipsel/sysvinit-utils/download">mipsel</a></th>
<td class="size">94.6 kB</td><td class="size">223.0 kB</td>
<td>
[<a href="/wheezy/mipsel/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/powerpc/sysvinit-utils/download">powerpc</a></th>
<td class="size">95.6 kB</td><td class="size">219.0 kB</td>
<td>
[<a href="/wheezy/powerpc/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/s390/sysvinit-utils/download">s390</a></th>
<td class="size">97.4 kB</td><td class="size">226.0 kB</td>
<td>
[<a href="/wheezy/s390/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/s390x/sysvinit-utils/download">s390x</a></th>
<td class="size">101.8 kB</td><td class="size">243.0 kB</td>
<td>
[<a href="/wheezy/s390x/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
<tr>
<th><a href="/wheezy/sparc/sysvinit-utils/download">sparc</a></th>
<td class="size">96.7 kB</td><td class="size">236.0 kB</td>
<td>
[<a href="/wheezy/sparc/sysvinit-utils/filelist">list of files</a>]
</td>
</tr>
</table>
</div> <!-- end pdownload -->
</div> <!-- end inner -->
<div id="footer">
<hr class="hidecss">
<!--UdmComment-->
<div id="pageLang">
<div id="langSelector">
<p>This page is also available in the following languages (How to set <a href="http://www.debian.org/intro/cn">the default document language</a>):</p>
<div id="langContainer">
<a href="/bg/wheezy/sysvinit-utils" title="Bulgarian" hreflang="bg" lang="bg" rel="alternate">Български (Bəlgarski)</a>
<a href="/cs/wheezy/sysvinit-utils" title="Czech" hreflang="cs" lang="cs" rel="alternate">česky</a>
<a href="/da/wheezy/sysvinit-utils" title="Danish" hreflang="da" lang="da" rel="alternate">dansk</a>
<a href="/de/wheezy/sysvinit-utils" title="German" hreflang="de" lang="de" rel="alternate">Deutsch</a>
<a href="/es/wheezy/sysvinit-utils" title="Spanish" hreflang="es" lang="es" rel="alternate">español</a>
<a href="/fi/wheezy/sysvinit-utils" title="Finnish" hreflang="fi" lang="fi" rel="alternate">suomi</a>
<a href="/fr/wheezy/sysvinit-utils" title="French" hreflang="fr" lang="fr" rel="alternate">français</a>
<a href="/ko/wheezy/sysvinit-utils" title="Korean" hreflang="ko" lang="ko" rel="alternate">한국어 (Hangul)</a>
<a href="/hu/wheezy/sysvinit-utils" title="Hungarian" hreflang="hu" lang="hu" rel="alternate">magyar</a>
<a href="/it/wheezy/sysvinit-utils" title="Italian" hreflang="it" lang="it" rel="alternate">Italiano</a>
<a href="/ja/wheezy/sysvinit-utils" title="Japanese" hreflang="ja" lang="ja" rel="alternate">日本語 (Nihongo)</a>
<a href="/nl/wheezy/sysvinit-utils" title="Dutch" hreflang="nl" lang="nl" rel="alternate">Nederlands</a>
<a href="/pl/wheezy/sysvinit-utils" title="Polish" hreflang="pl" lang="pl" rel="alternate">polski</a>
<a href="/pt/wheezy/sysvinit-utils" title="Portuguese" hreflang="pt" lang="pt" rel="alternate">Português (pt)</a>
<a href="/pt-br/wheezy/sysvinit-utils" title="Portuguese (Brasilia)" hreflang="pt-br" lang="pt-br" rel="alternate">Português (br)</a>
<a href="/ru/wheezy/sysvinit-utils" title="Russian" hreflang="ru" lang="ru" rel="alternate">Русский (Russkij)</a>
<a href="/sk/wheezy/sysvinit-utils" title="Slovak" hreflang="sk" lang="sk" rel="alternate">slovensky</a>
<a href="/sv/wheezy/sysvinit-utils" title="Swedish" hreflang="sv" lang="sv" rel="alternate">svenska</a>
<a href="/tr/wheezy/sysvinit-utils" title="Turkish" hreflang="tr" lang="tr" rel="alternate">Türkçe</a>
<a href="/uk/wheezy/sysvinit-utils" title="Ukrainian" hreflang="uk" lang="uk" rel="alternate">українська (ukrajins'ka)</a>
<a href="/zh-cn/wheezy/sysvinit-utils" title="Chinese (China)" hreflang="zh-cn" lang="zh-cn" rel="alternate">中文 (Zhongwen,简)</a>
<a href="/zh-tw/wheezy/sysvinit-utils" title="Chinese (Taiwan)" hreflang="zh-tw" lang="zh-tw" rel="alternate">中文 (Zhongwen,繁)</a>
</div>
</div>
</div>
<!--/UdmComment-->
<hr class="hidecss">
<div id="fineprint" class="bordertop">
<div id="impressum">
<p>To report a problem with the web site, e-mail <a href="mailto:debian-www@lists.debian.org">debian-www@lists.debian.org</a>. For other contact information, see the Debian <a href="http://www.debian.org/contact">contact page</a>.</p>
<p>
Content Copyright © 1997 - 2015 <a href="http://www.spi-inc.org/">SPI Inc.</a>; See <a href="http://www.debian.org/license">license terms</a>. Debian is a <a href="http://www.debian.org/trademark">trademark</a> of SPI Inc.
<a href="/about/">Learn more about this site</a>.</p>
</div> <!-- end impressum -->
<div id="sponsorfooter"><p>
This service is sponsored by <a href="http://cs.helsinki.fi/index.en.html">University of Helsinki - Department of Computer Science</a>.</p></div>
</div> <!-- end fineprint -->
</div> <!-- end footer -->
</body>
</html>
|
linuxfoundation/cii-census
|
original_cache/debian_role/sysvinit-utils.html
|
HTML
|
mit
| 18,088
|
// @flow
export { default as CircularProgress } from './CircularProgress';
export { default as LinearProgress } from './LinearProgress';
|
AndriusBil/material-ui
|
src/Progress/index.js
|
JavaScript
|
mit
| 137
|
#!/usr/bin/env php
<?php
/**
* Allows to get the content of a php-fpm environment configuration file
*/
class PhpFpmEnvironment {
/**
* The temporary directory, used in TMP, TEMP and TMPDIR environment variables
* @var string
*/
const TMP = '/tmp';
/**
* The path where to find executables, where sbin should be excluded if you don't run PHP as root.
* @var string
*/
const PATH = '/usr/local/bin:/usr/bin:/bin';
/**
* The environment variables to discard
* @var Array
*/
const VARIABLES_TO_DISCARD = [
'_', // The caller executable script, not pertinent
'HOME', // Set correctly by php-fpm
'TERM', // Not pertinent in server context
'MYSQL_ENV_MYSQL_ROOT_PASSWORD', // from --link …:mysql
];
/**
* Gets an environment array from the current process environment,
* with PATH and temp variablesfiltered.
*
* @return Array
*/
public static function getEnvironmentVariables () {
$variables = [];
foreach ($_ENV as $key => $value) {
if (!static::mustIgnoreVariable($key)) {
$variables[$key] = $value;
}
}
static::addHardcodedEnvironmentVariables($variables);
return $variables;
}
/**
* Adds hardcoded and always wanted environment variables
* (path, temporary directory) to the specified array.
*
* @paran array $variables the array to add the variables to
*/
public static function addHardcodedEnvironmentVariables (&$variables) {
static::addTempEnvironmentVariables ($variables);
static::addPathEnvironmentVariables ($variables);
}
/**
* Adds temporary directory environment variables to the specified array.
*
* @paran array $variables the array to add the variables to
*/
public static function addTempEnvironmentVariables (&$variables) {
$variables['TMP'] = static::TMP;
$variables['TEMP'] = static::TMP;
$variables['TMPDIR'] = static::TMP;
}
/**
* Adds temporary directory environment variables to the specified array.
*
* @paran array $variables the array to add the variables to
*/
public static function addPathEnvironmentVariables (&$variables) {
$variables['PATH'] = static::PATH;
}
/**
* Determines if the variable name must be ignored
*
* @return bool true if the variable must be ignored; otherwise, false.
*/
public static function mustIgnoreVariable ($variableName) {
return in_array($variableName, static::VARIABLES_TO_DISCARD);
}
/**
* Prints the environment
*/
public static function printConfig () {
$variables = static::getEnvironmentVariables();
foreach ($variables as $key => $value) {
echo 'env["', $key, '"] = "', $value, '"', PHP_EOL;
}
}
}
PhpFpmEnvironment::printConfig();
|
nasqueron/docker-nginx-php-fpm
|
novolume/files/usr/local/lib/php-fpm-env/PhpFpmEnvironment.php
|
PHP
|
mit
| 3,005
|
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Tax Rate Titles Renderer
*
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Adminhtml_Block_Tax_Rate_Title extends Mage_Core_Block_Template
{
protected $_titles;
protected function _construct()
{
$this->setTemplate('tax/rate/title.phtml');
}
public function getTitles()
{
if (is_null($this->_titles)) {
$this->_titles = array();
$titles = Mage::getSingleton('tax/calculation_rate')->getTitles();
foreach ($titles as $title) {
$this->_titles[$title->getStoreId()] = $title->getValue();
}
foreach ($this->getStores() as $store) {
if (!isset($this->_titles[$store->getId()])) {
$this->_titles[$store->getId()] = '';
}
}
}
return $this->_titles;
}
public function getStores()
{
$stores = $this->getData('stores');
if (is_null($stores)) {
$stores = Mage::getModel('core/store')
->getResourceCollection()
->setLoadDefault(false)
->load();
$this->setData('stores', $stores);
}
return $stores;
}
}
|
fabiensebban/magento
|
app/code/core/Mage/Adminhtml/Block/Tax/Rate/Title.php
|
PHP
|
mit
| 2,204
|
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// Represents an error that occurs when a call to the CreateAttachment web method fails.
/// </summary>
[Serializable]
public sealed class CreateAttachmentException : BatchServiceResponseException<CreateAttachmentResponse>
{
/// <summary>
/// Initializes a new instance of CreateAttachmentException.
/// </summary>
/// <param name="serviceResponses">The list of responses to be associated with this exception.</param>
/// <param name="message">The message that describes the error.</param>
internal CreateAttachmentException(
ServiceResponseCollection<CreateAttachmentResponse> serviceResponses,
string message)
: base(serviceResponses, message)
{
}
/// <summary>
/// Initializes a new instance of CreateAttachmentException.
/// </summary>
/// <param name="serviceResponses">The list of responses to be associated with this exception.</param>
/// <param name="message">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
internal CreateAttachmentException(
ServiceResponseCollection<CreateAttachmentResponse> serviceResponses,
string message,
Exception innerException)
: base(serviceResponses, message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:Microsoft.Exchange.WebServices.Data.CreateAttachmentException"/> class with serialized data.
/// </summary>
/// <param name="info">The object that holds the serialized object data.</param>
/// <param name="context">The contextual information about the source or destination.</param>
private CreateAttachmentException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
|
gscales/ews-managed-api
|
Exceptions/CreateAttachmentException.cs
|
C#
|
mit
| 3,329
|
JSMpeg.Decoder.Base = (function(){ "use strict";
var BaseDecoder = function(options) {
this.destination = null;
this.canPlay = false;
this.collectTimestamps = !options.streaming;
this.timestamps = [];
this.timestampIndex = 0;
this.startTime = 0;
this.decodedTime = 0;
Object.defineProperty(this, 'currentTime', {get: this.getCurrentTime});
};
BaseDecoder.prototype.connect = function(destination) {
this.destination = destination;
};
BaseDecoder.prototype.write = function(pts, buffers) {
if (this.collectTimestamps) {
if (this.timestamps.length === 0) {
this.startTime = pts;
this.decodedTime = pts;
}
this.timestamps.push({index: this.bits.byteLength << 3, time: pts});
}
this.bits.write(buffers);
this.canPlay = true;
};
BaseDecoder.prototype.seek = function(time) {
if (!this.collectTimestamps) {
return;
}
this.timestampIndex = 0;
for (var i = 0; i < this.timestamps.length; i++) {
if (this.timestamps[i].time > time) {
break;
}
this.timestampIndex = i;
}
var ts = this.timestamps[this.timestampIndex];
if (ts) {
this.bits.index = ts.index;
this.decodedTime = ts.time;
}
else {
this.bits.index = 0;
this.decodedTime = this.startTime;
}
};
BaseDecoder.prototype.decode = function() {
this.advanceDecodedTime(0);
};
BaseDecoder.prototype.advanceDecodedTime = function(seconds) {
if (this.collectTimestamps) {
var newTimestampIndex = -1;
for (var i = this.timestampIndex; i < this.timestamps.length; i++) {
if (this.timestamps[i].index > this.bits.index) {
break;
}
newTimestampIndex = i;
}
// Did we find a new PTS, different from the last? If so, we don't have
// to advance the decoded time manually and can instead sync it exactly
// to the PTS.
if (
newTimestampIndex !== -1 &&
newTimestampIndex !== this.timestampIndex
) {
this.timestampIndex = newTimestampIndex;
this.decodedTime = this.timestamps[this.timestampIndex].time;
return;
}
}
this.decodedTime += seconds;
};
BaseDecoder.prototype.getCurrentTime = function() {
return this.decodedTime;
};
return BaseDecoder;
})();
|
faljse/jsmpeg
|
src/decoder.js
|
JavaScript
|
mit
| 2,109
|
class CreateProjectImportData < ActiveRecord::Migration[4.2]
def change
create_table :project_import_data do |t|
t.references :project
t.text :data
end
end
end
|
iiet/iiet-git
|
db/migrate/20150417121913_create_project_import_data.rb
|
Ruby
|
mit
| 184
|
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
using System.Globalization;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public abstract partial class JsonWriter : IDisposable
{
internal enum State
{
Start = 0,
Property = 1,
ObjectStart = 2,
Object = 3,
ArrayStart = 4,
Array = 5,
ConstructorStart = 6,
Constructor = 7,
Closed = 8,
Error = 9
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] StateArray;
internal static readonly State[][] StateArrayTempate = new[]
{
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }
};
internal static State[][] BuildStateArray()
{
List<State[]> allStates = StateArrayTempate.ToList();
State[] errorStates = StateArrayTempate[0];
State[] valueStates = StateArrayTempate[7];
foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken)))
{
if (allStates.Count <= (int)valueToken)
{
switch (valueToken)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
allStates.Add(valueStates);
break;
default:
allStates.Add(errorStates);
break;
}
}
}
return allStates.ToArray();
}
static JsonWriter()
{
StateArray = BuildStateArray();
}
private List<JsonPosition> _stack;
private JsonPosition _currentPosition;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the destination should be closed when this writer is closed.
/// </summary>
/// <value>
/// <c>true</c> to close the destination when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the JSON should be auto-completed when this writer is closed.
/// </summary>
/// <value>
/// <c>true</c> to auto-complete the JSON when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>.
/// </value>
public bool AutoCompleteOnClose { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get
{
int depth = (_stack != null) ? _stack.Count : 0;
if (Peek() != JsonContainerType.None)
{
depth++;
}
return depth;
}
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null);
}
}
}
internal string ContainerPath
{
get
{
if (_currentPosition.Type == JsonContainerType.None || _stack == null)
{
return string.Empty;
}
return JsonPosition.BuildPath(_stack, null);
}
}
/// <summary>
/// Gets the path of the writer.
/// </summary>
public string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
{
return string.Empty;
}
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack, current);
}
}
private DateFormatHandling _dateFormatHandling;
private DateTimeZoneHandling _dateTimeZoneHandling;
private StringEscapeHandling _stringEscapeHandling;
private FloatFormatHandling _floatFormatHandling;
private string _dateFormatString;
private CultureInfo _culture;
/// <summary>
/// Gets or sets a value indicating how JSON text output should be formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set
{
if (value < Formatting.None || value > Formatting.Indented)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_formatting = value;
}
}
/// <summary>
/// Gets or sets how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get { return _dateFormatHandling; }
set
{
if (value < DateFormatHandling.IsoDateFormat || value > DateFormatHandling.MicrosoftDateFormat)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateFormatHandling = value;
}
}
/// <summary>
/// Gets or sets how <see cref="DateTime"/> time zones are handled when writing JSON text.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set
{
if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateTimeZoneHandling = value;
}
}
/// <summary>
/// Gets or sets how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get { return _stringEscapeHandling; }
set
{
if (value < StringEscapeHandling.Default || value > StringEscapeHandling.EscapeHtml)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_stringEscapeHandling = value;
OnStringEscapeHandlingChanged();
}
}
internal virtual void OnStringEscapeHandlingChanged()
{
// hacky but there is a calculated value that relies on StringEscapeHandling
}
/// <summary>
/// Gets or sets how special floating point numbers, e.g. <see cref="Double.NaN"/>,
/// <see cref="Double.PositiveInfinity"/> and <see cref="Double.NegativeInfinity"/>,
/// are written to JSON text.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get { return _floatFormatHandling; }
set
{
if (value < FloatFormatHandling.String || value > FloatFormatHandling.DefaultValue)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_floatFormatHandling = value;
}
}
/// <summary>
/// Gets or sets how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString; }
set { _dateFormatString = value; }
}
/// <summary>
/// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriter"/> class.
/// </summary>
protected JsonWriter()
{
_currentState = State.Start;
_formatting = Formatting.None;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
CloseOutput = true;
AutoCompleteOnClose = true;
}
internal void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
{
_currentPosition.Position++;
}
}
private void Push(JsonContainerType value)
{
if (_currentPosition.Type != JsonContainerType.None)
{
if (_stack == null)
{
_stack = new List<JsonPosition>();
}
_stack.Add(_currentPosition);
}
_currentPosition = new JsonPosition(value);
}
private JsonContainerType Pop()
{
JsonPosition oldPosition = _currentPosition;
if (_stack != null && _stack.Count > 0)
{
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
_currentPosition = new JsonPosition();
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Flushes whatever is in the buffer to the destination and also flushes the destination.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this writer.
/// If <see cref="CloseOutput"/> is set to <c>true</c>, the destination is also closed.
/// If <see cref="AutoCompleteOnClose"/> is set to <c>true</c>, the JSON is auto-completed.
/// </summary>
public virtual void Close()
{
if (AutoCompleteOnClose)
{
AutoCompleteAll();
}
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
public virtual void WriteStartObject()
{
InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);
}
/// <summary>
/// Writes the end of a JSON object.
/// </summary>
public virtual void WriteEndObject()
{
InternalWriteEnd(JsonContainerType.Object);
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
public virtual void WriteStartArray()
{
InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
InternalWriteEnd(JsonContainerType.Array);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
InternalWriteEnd(JsonContainerType.Constructor);
}
/// <summary>
/// Writes the property name of a name/value pair of a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
InternalWritePropertyName(name);
}
/// <summary>
/// Writes the property name of a name/value pair of a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param>
public virtual void WritePropertyName(string name, bool escape)
{
WritePropertyName(name);
}
/// <summary>
/// Writes the end of the current JSON object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token and its children.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
WriteToken(reader, true);
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
/// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param>
public void WriteToken(JsonReader reader, bool writeChildren)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
WriteToken(reader, writeChildren, true, true);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token and its value.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
/// <param name="value">
/// The value to write.
/// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>.
/// <c>null</c> can be passed to the method for tokens that don't have a value, e.g. <see cref="JsonToken.StartObject"/>.
/// </param>
public void WriteToken(JsonToken token, object value)
{
switch (token)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteStartConstructor(value.ToString());
break;
case JsonToken.PropertyName:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WritePropertyName(value.ToString());
break;
case JsonToken.Comment:
WriteComment(value?.ToString());
break;
case JsonToken.Integer:
ValidationUtils.ArgumentNotNull(value, nameof(value));
#if HAVE_BIG_INTEGER
if (value is BigInteger)
{
WriteValue((BigInteger)value);
}
else
#endif
{
WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value is decimal)
{
WriteValue((decimal)value);
}
else if (value is double)
{
WriteValue((double)value);
}
else if (value is float)
{
WriteValue((float)value);
}
else
{
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.String:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteValue(value.ToString());
break;
case JsonToken.Boolean:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
ValidationUtils.ArgumentNotNull(value, nameof(value));
#if HAVE_DATE_TIME_OFFSET
if (value is DateTimeOffset)
{
WriteValue((DateTimeOffset)value);
}
else
#endif
{
WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Raw:
WriteRawValue(value?.ToString());
break;
case JsonToken.Bytes:
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value is Guid)
{
WriteValue((Guid)value);
}
else
{
WriteValue((byte[])value);
}
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type.");
}
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
public void WriteToken(JsonToken token)
{
WriteToken(token, null);
}
internal virtual void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments)
{
int initialDepth = CalculateWriteTokenInitialDepth(reader);
do
{
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
{
WriteConstructorDate(reader);
}
else
{
if (writeComments || reader.TokenType != JsonToken.Comment)
{
WriteToken(reader.TokenType, reader.Value);
}
}
} while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
if (initialDepth < CalculateWriteTokenFinalDepth(reader))
{
throw JsonWriterException.Create(this, "Unexpected end when reading token.", null);
}
}
private int CalculateWriteTokenInitialDepth(JsonReader reader)
{
JsonToken type = reader.TokenType;
if (type == JsonToken.None)
{
return -1;
}
return JsonTokenUtils.IsStartToken(type) ? reader.Depth : reader.Depth + 1;
}
private int CalculateWriteTokenFinalDepth(JsonReader reader)
{
JsonToken type = reader.TokenType;
if (type == JsonToken.None)
{
return -1;
}
return JsonTokenUtils.IsEndToken(type) ? reader.Depth - 1 : reader.Depth;
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
{
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
}
if (reader.TokenType != JsonToken.Integer)
{
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null);
}
long ticks = (long)reader.Value;
DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
{
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
}
if (reader.TokenType != JsonToken.EndConstructor)
{
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null);
}
WriteValue(date);
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
WriteEndObject();
break;
case JsonContainerType.Array:
WriteEndArray();
break;
case JsonContainerType.Constructor:
WriteEndConstructor();
break;
default:
throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null);
}
}
private void AutoCompleteAll()
{
while (Top > 0)
{
WriteEnd();
}
}
private JsonToken GetCloseTokenForType(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
return JsonToken.EndObject;
case JsonContainerType.Array:
return JsonToken.EndArray;
case JsonContainerType.Constructor:
return JsonToken.EndConstructor;
default:
throw JsonWriterException.Create(this, "No close token for type: " + type, null);
}
}
private void AutoCompleteClose(JsonContainerType type)
{
int levelsToComplete = CalculateLevelsToComplete(type);
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState == State.Property)
{
WriteNull();
}
if (_formatting == Formatting.Indented)
{
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
{
WriteIndent();
}
}
WriteEnd(token);
UpdateCurrentState();
}
}
private int CalculateLevelsToComplete(JsonContainerType type)
{
int levelsToComplete = 0;
if (_currentPosition.Type == type)
{
levelsToComplete = 1;
}
else
{
int top = Top - 2;
for (int i = top; i >= 0; i--)
{
int currentLevel = top - i;
if (_stack[currentLevel].Type == type)
{
levelsToComplete = i + 2;
break;
}
}
}
if (levelsToComplete == 0)
{
throw JsonWriterException.Create(this, "No token to close.", null);
}
return levelsToComplete;
}
private void UpdateCurrentState()
{
JsonContainerType currentLevelType = Peek();
switch (currentLevelType)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Array;
break;
case JsonContainerType.None:
_currentState = State.Start;
break;
default:
throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null);
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
// gets new state based on the current state and what is being written
State newState = StateArray[(int)tokenBeingWritten][(int)_currentState];
if (newState == State.Error)
{
throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null);
}
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
if (_formatting == Formatting.Indented)
{
if (_currentState == State.Property)
{
WriteIndentSpace();
}
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart)
|| (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start))
{
WriteIndent();
}
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
InternalWriteValue(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
InternalWriteValue(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
InternalWriteRaw();
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
UpdateScopeWithFinishedValue();
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
InternalWriteValue(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
InternalWriteValue(JsonToken.Date);
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
InternalWriteValue(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.Bytes);
}
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.String);
}
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
}
else
{
#if HAVE_BIG_INTEGER
// this is here because adding a WriteValue(BigInteger) to JsonWriter will
// mean the user has to add a reference to System.Numerics.dll
if (value is BigInteger)
{
throw CreateUnsupportedTypeException(this, value);
}
#endif
WriteValue(this, ConvertUtils.GetTypeCode(value.GetType()), value);
}
}
#endregion
/// <summary>
/// Writes a comment <c>/*...*/</c> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
InternalWriteComment();
}
/// <summary>
/// Writes the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
InternalWriteWhitespace(ws);
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
{
Close();
}
}
internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value)
{
switch (typeCode)
{
case PrimitiveTypeCode.Char:
writer.WriteValue((char)value);
break;
case PrimitiveTypeCode.CharNullable:
writer.WriteValue((value == null) ? (char?)null : (char)value);
break;
case PrimitiveTypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case PrimitiveTypeCode.BooleanNullable:
writer.WriteValue((value == null) ? (bool?)null : (bool)value);
break;
case PrimitiveTypeCode.SByte:
writer.WriteValue((sbyte)value);
break;
case PrimitiveTypeCode.SByteNullable:
writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value);
break;
case PrimitiveTypeCode.Int16:
writer.WriteValue((short)value);
break;
case PrimitiveTypeCode.Int16Nullable:
writer.WriteValue((value == null) ? (short?)null : (short)value);
break;
case PrimitiveTypeCode.UInt16:
writer.WriteValue((ushort)value);
break;
case PrimitiveTypeCode.UInt16Nullable:
writer.WriteValue((value == null) ? (ushort?)null : (ushort)value);
break;
case PrimitiveTypeCode.Int32:
writer.WriteValue((int)value);
break;
case PrimitiveTypeCode.Int32Nullable:
writer.WriteValue((value == null) ? (int?)null : (int)value);
break;
case PrimitiveTypeCode.Byte:
writer.WriteValue((byte)value);
break;
case PrimitiveTypeCode.ByteNullable:
writer.WriteValue((value == null) ? (byte?)null : (byte)value);
break;
case PrimitiveTypeCode.UInt32:
writer.WriteValue((uint)value);
break;
case PrimitiveTypeCode.UInt32Nullable:
writer.WriteValue((value == null) ? (uint?)null : (uint)value);
break;
case PrimitiveTypeCode.Int64:
writer.WriteValue((long)value);
break;
case PrimitiveTypeCode.Int64Nullable:
writer.WriteValue((value == null) ? (long?)null : (long)value);
break;
case PrimitiveTypeCode.UInt64:
writer.WriteValue((ulong)value);
break;
case PrimitiveTypeCode.UInt64Nullable:
writer.WriteValue((value == null) ? (ulong?)null : (ulong)value);
break;
case PrimitiveTypeCode.Single:
writer.WriteValue((float)value);
break;
case PrimitiveTypeCode.SingleNullable:
writer.WriteValue((value == null) ? (float?)null : (float)value);
break;
case PrimitiveTypeCode.Double:
writer.WriteValue((double)value);
break;
case PrimitiveTypeCode.DoubleNullable:
writer.WriteValue((value == null) ? (double?)null : (double)value);
break;
case PrimitiveTypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case PrimitiveTypeCode.DateTimeNullable:
writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value);
break;
#if HAVE_DATE_TIME_OFFSET
case PrimitiveTypeCode.DateTimeOffset:
writer.WriteValue((DateTimeOffset)value);
break;
case PrimitiveTypeCode.DateTimeOffsetNullable:
writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value);
break;
#endif
case PrimitiveTypeCode.Decimal:
writer.WriteValue((decimal)value);
break;
case PrimitiveTypeCode.DecimalNullable:
writer.WriteValue((value == null) ? (decimal?)null : (decimal)value);
break;
case PrimitiveTypeCode.Guid:
writer.WriteValue((Guid)value);
break;
case PrimitiveTypeCode.GuidNullable:
writer.WriteValue((value == null) ? (Guid?)null : (Guid)value);
break;
case PrimitiveTypeCode.TimeSpan:
writer.WriteValue((TimeSpan)value);
break;
case PrimitiveTypeCode.TimeSpanNullable:
writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value);
break;
#if HAVE_BIG_INTEGER
case PrimitiveTypeCode.BigInteger:
// this will call to WriteValue(object)
writer.WriteValue((BigInteger)value);
break;
case PrimitiveTypeCode.BigIntegerNullable:
// this will call to WriteValue(object)
writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value);
break;
#endif
case PrimitiveTypeCode.Uri:
writer.WriteValue((Uri)value);
break;
case PrimitiveTypeCode.String:
writer.WriteValue((string)value);
break;
case PrimitiveTypeCode.Bytes:
writer.WriteValue((byte[])value);
break;
#if HAVE_DB_NULL_TYPE_CODE
case PrimitiveTypeCode.DBNull:
writer.WriteNull();
break;
#endif
default:
#if HAVE_ICONVERTIBLE
IConvertible convertible = value as IConvertible;
if (convertible != null)
{
// the value is a non-standard IConvertible
// convert to the underlying value and retry
TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertible);
// if convertible has an underlying typecode of Object then attempt to convert it to a string
PrimitiveTypeCode resolvedTypeCode = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? PrimitiveTypeCode.String : typeInformation.TypeCode;
Type resolvedType = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? typeof(string) : typeInformation.Type;
object convertedValue = convertible.ToType(resolvedType, CultureInfo.InvariantCulture);
WriteValue(writer, resolvedTypeCode, convertedValue);
break;
}
#endif
throw CreateUnsupportedTypeException(writer, value);
}
}
private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value)
{
return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
/// <summary>
/// Sets the state of the <see cref="JsonWriter"/>.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> being written.</param>
/// <param name="value">The value being written.</param>
protected void SetWriteState(JsonToken token, object value)
{
switch (token)
{
case JsonToken.StartObject:
InternalWriteStart(token, JsonContainerType.Object);
break;
case JsonToken.StartArray:
InternalWriteStart(token, JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
InternalWriteStart(token, JsonContainerType.Constructor);
break;
case JsonToken.PropertyName:
if (!(value is string))
{
throw new ArgumentException("A name is required when setting property name state.", nameof(value));
}
InternalWritePropertyName((string)value);
break;
case JsonToken.Comment:
InternalWriteComment();
break;
case JsonToken.Raw:
InternalWriteRaw();
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
case JsonToken.Null:
case JsonToken.Undefined:
InternalWriteValue(token);
break;
case JsonToken.EndObject:
InternalWriteEnd(JsonContainerType.Object);
break;
case JsonToken.EndArray:
InternalWriteEnd(JsonContainerType.Array);
break;
case JsonToken.EndConstructor:
InternalWriteEnd(JsonContainerType.Constructor);
break;
default:
throw new ArgumentOutOfRangeException(nameof(token));
}
}
internal void InternalWriteEnd(JsonContainerType container)
{
AutoCompleteClose(container);
}
internal void InternalWritePropertyName(string name)
{
_currentPosition.PropertyName = name;
AutoComplete(JsonToken.PropertyName);
}
internal void InternalWriteRaw()
{
}
internal void InternalWriteStart(JsonToken token, JsonContainerType container)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
Push(container);
}
internal void InternalWriteValue(JsonToken token)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
}
internal void InternalWriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
{
throw JsonWriterException.Create(this, "Only white space characters should be used.", null);
}
}
}
internal void InternalWriteComment()
{
AutoComplete(JsonToken.Comment);
}
}
}
|
benaadams/Newtonsoft.Json
|
Src/Newtonsoft.Json/JsonWriter.cs
|
C#
|
mit
| 62,501
|
export function noProject(project: string) {
return `Unable to find project '${project}' in the workspace`;
}
export function unsupportedStyles(styleFilePath: string) {
return `Project style file found has unsupported extension: '${styleFilePath}'\nAdding 'bootstrap.min.css' to 'angular.json'`;
}
|
benouat/ng-bootstrap
|
schematics/ng-add/messages.ts
|
TypeScript
|
mit
| 303
|
# Ref. https://raw.githubusercontent.com/cake-build/resources/480522f00dc9671225c0d32713d858dc5ac1d56e/build.ps1
##########################################################################
# This is the Cake bootstrapper script for PowerShell.
# This file was downloaded from https://github.com/cake-build/resources
# Feel free to change this file to fit your needs.
##########################################################################
<#
.SYNOPSIS
This is a Powershell script to bootstrap a Cake build.
.DESCRIPTION
This Powershell script will download NuGet if missing, restore NuGet tools (including Cake)
and execute your Cake build script with the parameters you provide.
.PARAMETER Script
The build script to execute.
.PARAMETER Target
The build script target to run.
.PARAMETER Configuration
The build configuration to use.
.PARAMETER Verbosity
Specifies the amount of information to be displayed.
.PARAMETER ShowDescription
Shows description about tasks.
.PARAMETER DryRun
Performs a dry run.
.PARAMETER SkipToolPackageRestore
Skips restoring of packages.
.PARAMETER ScriptArgs
Remaining arguments are added here.
.LINK
https://cakebuild.net
#>
[CmdletBinding()]
Param(
[string]$Script = "build.cake",
[string]$Target,
[string]$Configuration,
[ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")]
[string]$Verbosity,
[switch]$ShowDescription,
[Alias("WhatIf", "Noop")]
[switch]$DryRun,
[switch]$SkipToolPackageRestore,
[Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)]
[string[]]$ScriptArgs
)
# Attempt to set highest encryption available for SecurityProtocol.
# PowerShell will not set this by default (until maybe .NET 4.6.x). This
# will typically produce a message for PowerShell v2 (just an info
# message though)
try {
# Set TLS 1.2 (3072), then TLS 1.1 (768), then TLS 1.0 (192), finally SSL 3.0 (48)
# Use integers because the enumeration values for TLS 1.2 and TLS 1.1 won't
# exist in .NET 4.0, even though they are addressable if .NET 4.5+ is
# installed (.NET 4.5 is an in-place upgrade).
[System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192 -bor 48
} catch {
Write-Output 'Unable to set PowerShell to use TLS 1.2 and TLS 1.1 due to old .NET Framework installed. If you see underlying connection closed or trust errors, you may need to upgrade to .NET Framework 4.5+ and PowerShell v3'
}
[Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
function MD5HashFile([string] $filePath)
{
if ([string]::IsNullOrEmpty($filePath) -or !(Test-Path $filePath -PathType Leaf))
{
return $null
}
[System.IO.Stream] $file = $null;
[System.Security.Cryptography.MD5] $md5 = $null;
try
{
$md5 = [System.Security.Cryptography.MD5]::Create()
$file = [System.IO.File]::OpenRead($filePath)
return [System.BitConverter]::ToString($md5.ComputeHash($file))
}
finally
{
if ($file -ne $null)
{
$file.Dispose()
}
}
}
function GetProxyEnabledWebClient
{
$wc = New-Object System.Net.WebClient
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$wc.Proxy = $proxy
return $wc
}
Write-Host "Preparing to run build script..."
if(!$PSScriptRoot){
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
}
$TOOLS_DIR = Join-Path $PSScriptRoot "tools"
$ADDINS_DIR = Join-Path $TOOLS_DIR "Addins"
$MODULES_DIR = Join-Path $TOOLS_DIR "Modules"
$NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe"
$CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe"
$NUGET_URL = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config"
$PACKAGES_CONFIG_MD5 = Join-Path $TOOLS_DIR "packages.config.md5sum"
$ADDINS_PACKAGES_CONFIG = Join-Path $ADDINS_DIR "packages.config"
$MODULES_PACKAGES_CONFIG = Join-Path $MODULES_DIR "packages.config"
# Make sure tools folder exists
if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) {
Write-Verbose -Message "Creating tools directory..."
New-Item -Path $TOOLS_DIR -Type directory | out-null
}
# Make sure that packages.config exist.
if (!(Test-Path $PACKAGES_CONFIG)) {
Write-Verbose -Message "Downloading packages.config..."
try {
$wc = GetProxyEnabledWebClient
$wc.DownloadFile("https://cakebuild.net/download/bootstrapper/packages", $PACKAGES_CONFIG)
} catch {
Throw "Could not download packages.config."
}
}
# Try find NuGet.exe in path if not exists
if (!(Test-Path $NUGET_EXE)) {
Write-Verbose -Message "Trying to find nuget.exe in PATH..."
$existingPaths = $Env:Path -Split ';' | Where-Object { (![string]::IsNullOrEmpty($_)) -and (Test-Path $_ -PathType Container) }
$NUGET_EXE_IN_PATH = Get-ChildItem -Path $existingPaths -Filter "nuget.exe" | Select -First 1
if ($NUGET_EXE_IN_PATH -ne $null -and (Test-Path $NUGET_EXE_IN_PATH.FullName)) {
Write-Verbose -Message "Found in PATH at $($NUGET_EXE_IN_PATH.FullName)."
$NUGET_EXE = $NUGET_EXE_IN_PATH.FullName
}
}
# Try download NuGet.exe if not exists
if (!(Test-Path $NUGET_EXE)) {
Write-Verbose -Message "Downloading NuGet.exe..."
try {
$wc = GetProxyEnabledWebClient
$wc.DownloadFile($NUGET_URL, $NUGET_EXE)
} catch {
Throw "Could not download NuGet.exe."
}
}
# Save nuget.exe path to environment to be available to child processed
$ENV:NUGET_EXE = $NUGET_EXE
# Restore tools from NuGet?
if(-Not $SkipToolPackageRestore.IsPresent) {
Push-Location
Set-Location $TOOLS_DIR
# Check for changes in packages.config and remove installed tools if true.
[string] $md5Hash = MD5HashFile($PACKAGES_CONFIG)
if((!(Test-Path $PACKAGES_CONFIG_MD5)) -Or
($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) {
Write-Verbose -Message "Missing or changed package.config hash..."
Get-ChildItem -Exclude packages.config,nuget.exe,Cake.Bakery |
Remove-Item -Recurse
}
Write-Verbose -Message "Restoring tools from NuGet..."
$NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`""
if ($LASTEXITCODE -ne 0) {
Throw "An error occurred while restoring NuGet tools."
}
else
{
$md5Hash | Out-File $PACKAGES_CONFIG_MD5 -Encoding "ASCII"
}
Write-Verbose -Message ($NuGetOutput | out-string)
Pop-Location
}
# Restore addins from NuGet
if (Test-Path $ADDINS_PACKAGES_CONFIG) {
Push-Location
Set-Location $ADDINS_DIR
Write-Verbose -Message "Restoring addins from NuGet..."
$NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$ADDINS_DIR`""
if ($LASTEXITCODE -ne 0) {
Throw "An error occurred while restoring NuGet addins."
}
Write-Verbose -Message ($NuGetOutput | out-string)
Pop-Location
}
# Restore modules from NuGet
if (Test-Path $MODULES_PACKAGES_CONFIG) {
Push-Location
Set-Location $MODULES_DIR
Write-Verbose -Message "Restoring modules from NuGet..."
$NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$MODULES_DIR`""
if ($LASTEXITCODE -ne 0) {
Throw "An error occurred while restoring NuGet modules."
}
Write-Verbose -Message ($NuGetOutput | out-string)
Pop-Location
}
# Make sure that Cake has been installed.
if (!(Test-Path $CAKE_EXE)) {
Throw "Could not find Cake.exe at $CAKE_EXE"
}
# Build Cake arguments
$cakeArguments = @("$Script");
if ($Target) { $cakeArguments += "-target=$Target" }
if ($Configuration) { $cakeArguments += "-configuration=$Configuration" }
if ($Verbosity) { $cakeArguments += "-verbosity=$Verbosity" }
if ($ShowDescription) { $cakeArguments += "-showdescription" }
if ($DryRun) { $cakeArguments += "-dryrun" }
$cakeArguments += $ScriptArgs
# Start Cake
Write-Host "Running build script..."
&$CAKE_EXE $cakeArguments
exit $LASTEXITCODE
|
khalidabuhakmeh/filter
|
build.ps1
|
PowerShell
|
mit
| 8,132
|
{% extends 'base/base.html' %}
{% load i18n %}
{% load static %}
{% block extra_js %}
<script src="{% static 'js/new_password_validator.js' %}" charset="utf-8"></script>
{% endblock %}
{% block content %}
{% if validlink %}
<div class="password-reset jumbotron">
<div class="container">
<p>{% trans "Please enter your new password twice so we can verify you typed it in correctly." %}</p>
</div>
<form method="post">
{% csrf_token %}
<div class="form-group">
{{ form.new_password1.errors }}
<label for="id_new_password1">{% trans 'New password:' %}</label>
<div class="pass-wrapper">
{{ form.new_password1 }}
</div>
</div>
<div class="form-group">
{{ form.new_password2.errors }}
<label for="id_new_password2">{% trans 'Confirm password:' %}</label>
<div class="pass-wrapper">
{{ form.new_password2 }}
</div>
</div>
<input id="send_new" class="btn btn-primary btn-xs" type="submit" value="{% trans 'Change my password' %}" />
</form>
</div>
{% else %}
<div class="password-reset jumbotron">
<div class="container">
<p>
{% trans "The password reset link was invalid, possibly because it has already been used. Please request a new password reset." %}
</p>
</div>
</div>
{% endif %}
{% endblock %}
|
iPablo/starter-python-sevilla
|
python_sevilla/users/templates/registration/password_reset_confirm.html
|
HTML
|
mit
| 1,837
|
---
title: Additional Thought
date: 06/04/2018
---
> <p></p>
> “There was a time when every angel and person that God made loved God with a loyal heart. There was perfect happiness and peace everywhere because of this loyalty and love for God. The angels in heaven loved to do everything God wanted. They loved to show God’s glory in their lives and to praise Him. Their love for God was the most important thing in their lives. Their love for each other was deep and unselfish. Nothing evil poisoned their peace. Then a change took place. Lucifer put to bad use the freedom that God gave to everyone He made. Sin started in Lucifer. God honored Lucifer above all the other angels. Only Jesus was honored more in heaven than Lucifer.”—Ellen G. White, Patriarchs [Bible fathers] and Prophets [special messengers from God], page 35, adapted.
Notice Ellen White’s words: “ . . . loved God with a loyal heart.” This wording is very powerful and full of meaning. It teaches us that love leads us to be loyal to God and to live a life of faith. A person who is married will show that same love and loyalty to the one he or she loves. The angels in heaven loved God and each other that way. That is how we should love God and each other.
**Discussion questions**
`1. What proof does the Bible give us that Satan is real? What proof does the Bible give us about Satan’s part in the big war between good and evil? How can we help people understand that Satan is a real person and not just a word-picture for evil in the human heart?`
`2. God blessed Seventh-day Adventists with much knowledge about the Bible. But why is knowing the truth not enough to save us? What more do we need?`
`3. How have you experienced Jesus’ love and power over sin in your life? How can these experiences help you in the times of trouble ahead?`
`4. In class, talk more about the powerful words that Ellen G. White wrote: “. . . loved God with a loyal heart.” How does this idea help us understand better the close connection between the law and the Good News? How does this idea show us the truth that to love we first must be free to choose to love? What are ways we can show God’s love to other people?`
|
PrJared/sabbath-school-lessons
|
src/en/2018-02-er/01/07.md
|
Markdown
|
mit
| 2,220
|
Makes a shallow clone of an object, setting or overriding the specified
property with the given value. Note that this copies and flattens prototype
properties onto the new object as well. All non-primitive properties are
copied by reference.
@func
@memberOf R
@since v0.8.0
@category Object
@sig String -> a -> {k: v} -> {k: v}
@param {String} prop The property name to set
@param {*} val The new value
@param {Object} obj The object to clone
@return {Object} A new object equivalent to the original except for the changed property.
@see R.dissoc
@example
R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}
|
donnut/typescript-ramda
|
templates/assoc.md
|
Markdown
|
mit
| 618
|
#include <gloperate/rendering/StencilRenderTarget.h>
#include <glbinding/gl/enum.h>
#include <gloperate/rendering/AttachmentType.h>
namespace gloperate
{
AttachmentType StencilRenderTarget::underlyingAttachmentType() const
{
return AttachmentType::Stencil;
}
gl::GLenum StencilRenderTarget::attachmentGLType() const
{
return gl::GL_STENCIL;
}
gl::GLint StencilRenderTarget::clearBufferDrawBuffer(size_t /*index*/) const
{
return 0;
}
gl::GLenum StencilRenderTarget::drawBufferAttachment(size_t /*index*/) const
{
return gl::GL_NONE;
}
} // namespace gloperate
|
cginternals/gloperate
|
source/gloperate/source/rendering/StencilRenderTarget.cpp
|
C++
|
mit
| 588
|
body,input,select,textarea{color:#fff}input[type="submit"],input[type="reset"],input[type="button"],button,.button{position:relative}input[type="submit"]:after,input[type="reset"]:after,input[type="button"]:after,button:after,.button:after{display:none}.features{border:solid 1px}input[type="text"],input[type="password"],input[type="email"],input[type="tel"],select,textarea{background:transparent;border:solid 1px}.split.style1>:first-child{padding-right:2em;width:70%}
|
nicolaschaillot/electron-events
|
src/client/assets/css/ie8.css
|
CSS
|
mit
| 472
|
<div ng-show="product.images.length">
<div class="img-wrap">
<img ng-src="{{product.images[gallery.current]}}" />
</div>
<ul class="img-thumbnails clearfix">
<li class="small-image pull-left thumbnail" ng-repeat="image in product.images">
<img ng-src="{{image}}" />
</li>
</ul>
</div>
|
misterdavemeister/meanio
|
tests/tut/angular_tut/product-gallery.html
|
HTML
|
mit
| 310
|
#!/bin/sh -e
export DEBIAN_FRONTEND=noninteractive
sudo apt-get --quiet 2 update
sudo apt-get --quiet 2 upgrade
sudo apt-get --quiet 2 dist-upgrade
|
FunTimeCoding/debian-tools
|
script/vagrant/update-system.sh
|
Shell
|
mit
| 149
|
'use strict';
/**
* @ngdoc function
* @name inflightHubApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the inflightHubApp
*/
angular.module('inflightHubApp')
.controller('MainCtrl', function () {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
Sirintra1/FlightHub
|
app/scripts/controllers/main.js
|
JavaScript
|
mit
| 325
|
version https://git-lfs.github.com/spec/v1
oid sha256:c4fdd080b70bb03e8f649ff90f86d76a3604a3589ce2f201730c4441edb66ec1
size 8234
|
yogeshsaroya/new-cdnjs
|
ajax/libs/yui/3.14.1/node-pluginhost/node-pluginhost-coverage.js
|
JavaScript
|
mit
| 129
|
//
// agc_crcf_example.c
//
// Automatic gain control example demonstrating its transient
// response.
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <getopt.h>
#include "liquid.h"
#define OUTPUT_FILENAME "agc_crcf_squelch_example.m"
// print usage/help message
void usage()
{
printf("agc_crcf_squelch_example [options]\n");
printf(" -h : print usage\n");
printf(" -b <bandwidth> : AGC bandwidth, b >= 0, default: 0.25\n");
}
int main(int argc, char*argv[])
{
// options
float bt = 0.25f; // agc loop bandwidth
int dopt;
while((dopt = getopt(argc,argv,"hn:N:s:b:")) != EOF){
switch (dopt) {
case 'h': usage(); return 0;
case 'b': bt = atof(optarg); break;
default:
exit(1);
}
}
// validate input
if (bt < 0.0f) {
fprintf(stderr,"error: %s, bandwidth must be positive\n", argv[0]);
exit(1);
}
unsigned int i;
// create agc object, set loop bandwidth, and initialize parameters
agc_crcf q = agc_crcf_create();
agc_crcf_set_bandwidth(q, bt);
agc_crcf_set_signal_level(q,1e-3f); // initial guess at starting signal level
// initialize squelch functionality
agc_crcf_squelch_enable(q); // enable squelch
agc_crcf_squelch_set_threshold(q, -50); // threshold for detection [dB]
agc_crcf_squelch_set_timeout (q, 100); // timeout for hysteresis
// initialize arrays
unsigned int num_samples = 2000; // total number of samples to run
float complex x [num_samples]; // input
float complex y [num_samples]; // output
float rssi[num_samples]; // received signal strength
int mode[num_samples]; // squelch mode
// print info
printf("automatic gain control // loop bandwidth: %4.2e\n",bt);
// generate signal, applying tapering window appropriately
for (i=0; i<num_samples; i++) {
float gamma = 0.0f;
if (i < 500) gamma = 1e-3f;
else if (i < 550) gamma = 1e-3f + (1e-2f - 1e-3f)*(0.5f - 0.5f*cosf(M_PI*(float)(i- 500)/50.0f));
else if (i < 1450) gamma = 1e-2f;
else if (i < 1500) gamma = 1e-3f + (1e-2f - 1e-3f)*(0.5f + 0.5f*cosf(M_PI*(float)(i-1450)/50.0f));
else gamma = 1e-3f;
// apply window to signal
x[i] = gamma * cexpf(_Complex_I*2*M_PI*0.0193f*i);
}
// run agc
for (i=0; i<num_samples; i++) {
// apply gain
agc_crcf_execute(q, x[i], &y[i]);
// retrieve signal level [dB]
rssi[i] = agc_crcf_get_rssi(q);
// get squelch mode
mode[i] = agc_crcf_squelch_get_status(q);
// print status every so often
if ( (i % 100)==0 || i==num_samples-1 || mode[i] == LIQUID_AGC_SQUELCH_RISE || mode[i] == LIQUID_AGC_SQUELCH_FALL) {
char mode_str[20] = "";
switch (mode[i]) {
case LIQUID_AGC_SQUELCH_ENABLED: sprintf(mode_str,"squelch enabled"); break;
case LIQUID_AGC_SQUELCH_RISE: sprintf(mode_str,"signal detected"); break;
case LIQUID_AGC_SQUELCH_SIGNALHI: sprintf(mode_str,"signal high"); break;
case LIQUID_AGC_SQUELCH_FALL: sprintf(mode_str,"signal falling"); break;
case LIQUID_AGC_SQUELCH_SIGNALLO: sprintf(mode_str,"signal low"); break;
case LIQUID_AGC_SQUELCH_TIMEOUT: sprintf(mode_str,"signal timed out"); break;
case LIQUID_AGC_SQUELCH_DISABLED: sprintf(mode_str,"squelch disabled"); break;
default: sprintf(mode_str,"(unknown)"); break;
}
printf("%4u : %18s (%1u), rssi = %8.2f dB\n", i, mode_str, mode[i], rssi[i]);
}
}
// destroy AGC object
agc_crcf_destroy(q);
//
// export results
//
FILE* fid = fopen(OUTPUT_FILENAME,"w");
if (!fid) {
fprintf(stderr,"error: %s, could not open '%s' for writing\n", argv[0], OUTPUT_FILENAME);
exit(1);
}
fprintf(fid,"%% %s: auto-generated file\n\n",OUTPUT_FILENAME);
fprintf(fid,"clear all;\nclose all;\n\n");
fprintf(fid,"n = %u;\n", num_samples);
for (i=0; i<num_samples; i++) {
fprintf(fid,"x(%4u) = %12.4e + j*%12.4e;\n", i+1, crealf(x[i]), cimagf(x[i]));
fprintf(fid,"y(%4u) = %12.4e + j*%12.4e;\n", i+1, crealf(y[i]), cimagf(y[i]));
fprintf(fid,"rssi(%4u) = %12.4e;\n", i+1, rssi[i]);
fprintf(fid,"mode(%4u) = %d;\n", i+1, mode[i]);
}
// plot results
fprintf(fid,"\n");
fprintf(fid,"figure('position',[100 100 1200 900]);\n");
fprintf(fid,"t = 0:(n-1);\n");
fprintf(fid,"subplot(4,1,1);\n");
fprintf(fid," plot(t, real(x), '-', 'LineWidth',1.2, 'Color',[0 0.2 0.5],...\n");
fprintf(fid," t, imag(x), '-', 'LineWidth',1.2, 'Color',[0 0.5 0.2]);\n");
fprintf(fid," grid on;\n");
fprintf(fid," xlabel('sample index');\n");
fprintf(fid," ylabel('input');\n");
fprintf(fid," axis([0 %u -0.011 0.011]);\n", num_samples);
fprintf(fid,"subplot(4,1,2);\n");
fprintf(fid," plot(t, real(y), '-', 'LineWidth',1.2, 'Color',[0 0.2 0.5],...\n");
fprintf(fid," t, imag(y), '-', 'LineWidth',1.2, 'Color',[0 0.5 0.2]);\n");
fprintf(fid," grid on;\n");
fprintf(fid," xlabel('sample index');\n");
fprintf(fid," ylabel('output');\n");
fprintf(fid,"subplot(4,1,3);\n");
fprintf(fid," plot(t,rssi,'-','LineWidth',1.2,'Color',[0.5 0 0]);\n");
fprintf(fid," grid on;\n");
fprintf(fid," xlabel('sample index');\n");
fprintf(fid," ylabel('rssi [dB]');\n");
fprintf(fid,"subplot(4,1,4);\n");
fprintf(fid," plot(t,mode,'-s','LineWidth',1.2,'MarkerSize',4,'Color',[0.5 0 0]);\n");
fprintf(fid," grid on;\n");
fprintf(fid," xlabel('sample index');\n");
fprintf(fid," ylabel('squelch mode');\n");
fprintf(fid," axis([0 %u 0 8]);\n", num_samples);
fclose(fid);
printf("results written to %s\n", OUTPUT_FILENAME);
printf("done.\n");
return 0;
}
|
jgaeddert/liquid-dsp
|
examples/agc_crcf_squelch_example.c
|
C
|
mit
| 6,133
|
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2017-2018 Baldur Karlsson
*
* 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.
******************************************************************************/
#pragma once
#include "api/app/renderdoc_app.h"
#include "api/replay/renderdoc_replay.h"
#include "common/common.h"
#include "gl_common.h"
|
etnlGD/renderdoc
|
renderdoc/driver/gl/precompiled.h
|
C
|
mit
| 1,449
|
<template name="notificationButton">
<a class="notification-button item">
<i class="comment icon"></i> Notifications
{{#if unreadCount}}
<div class="ui red label">{{unreadCount}}</div>
{{/if}}
</a>
</template>
|
katopz/nullchat
|
client/views/modals/notifications/notification-button.html
|
HTML
|
mit
| 253
|
#include "NetList.h"
#include "imgui/imgui.h"
NetList::NetList(TcharStringCallback cbNetSelected) {
cbNetSelected_ = cbNetSelected;
}
NetList::~NetList() {}
void NetList::Draw(const char *title, bool *p_open, Board *board) {
// TODO: export / fix dimensions & behaviour
int width = 400;
int height = 640;
ImGui::SetNextWindowSize(ImVec2(width, height));
ImGui::Begin("Net List");
ImGui::Columns(1, "part_infos");
ImGui::Separator();
ImGui::Text("Name");
ImGui::NextColumn();
ImGui::Separator();
if (board) {
auto nets = board->Nets();
static int selected = -1;
string net_name = "";
ImGuiListClipper clipper;
clipper.Begin(nets.size());
while (clipper.Step()) {
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
net_name = nets.at(i)->name;
if (ImGui::Selectable(
net_name.c_str(), selected == i, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowDoubleClick)) {
selected = i;
if (ImGui::IsMouseDoubleClicked(0)) {
cbNetSelected_(net_name.c_str());
}
}
ImGui::NextColumn();
}
}
clipper.End();
}
ImGui::Columns(1);
ImGui::Separator();
ImGui::End();
}
|
chloridite/OpenBoardView
|
src/openboardview/NetList.cpp
|
C++
|
mit
| 1,175
|
---
title: <a-torus>
type: primitives
layout: docs
parent_section: primitives
order: 17
---
The torus primitive creates a donut or circular tube shape. It is an entity that prescribes the [geometry](../components/geometry.md) with its geometric primitive set to `torus`.
## Example
```html
<a-torus color="blue" position="0 0 0" segments-radial="50" segments-tubular="200" radius="5"
radius-tubular="0.1"></a-torus>
```
## Attributes
Note that the torus primitive inherits common [mesh attributes](./mesh-attributes.md).
| Attribute | Component Mapping | Default Value |
|-------------------|--------------------------|---------------|
| arc | geometry.arc | 360 |
| radius | geometry.radius | 1 |
| radius-tubular | geometry.radiusTubular | 0.2 |
| segments-radial | geometry.segmentsRadial | 36 |
| segments-tubular | geometry.segmentsTubular | 8 |
|
jzitelli/aframe
|
docs/primitives/a-torus.md
|
Markdown
|
mit
| 991
|
/*
FreeRTOS V7.0.1 - Copyright (C) 2011 Real Time Engineers Ltd.
FreeRTOS supports many tools and architectures. V7.0.0 is sponsored by:
Atollic AB - Atollic provides professional embedded systems development
tools for C/C++ development, code analysis and test automation.
See http://www.atollic.com
***************************************************************************
* *
* FreeRTOS tutorial books are available in pdf and paperback. *
* Complete, revised, and edited pdf reference manuals are also *
* available. *
* *
* Purchasing FreeRTOS documentation will not only help you, by *
* ensuring you get running as quickly as possible and with an *
* in-depth knowledge of how to use FreeRTOS, it will also help *
* the FreeRTOS project to continue with its mission of providing *
* professional grade, cross platform, de facto standard solutions *
* for microcontrollers - completely free of charge! *
* *
* >>> See http://www.FreeRTOS.org/Documentation for details. <<< *
* *
* Thank you for using FreeRTOS, and thank you for your support! *
* *
***************************************************************************
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
>>>NOTE<<< The modification to the GPL is included to allow you to
distribute a combined work that includes FreeRTOS without being obliged to
provide the source code for proprietary components outside of the FreeRTOS
kernel. FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not it
can be viewed here: http://www.freertos.org/a00114.html and also obtained
by writing to Richard Barry, contact details for whom are available on the
FreeRTOS WEB site.
1 tab == 4 spaces!
http://www.FreeRTOS.org - Documentation, latest information, license and
contact details.
http://www.SafeRTOS.com - A version that is certified for use in safety
critical systems.
http://www.OpenRTOS.com - Commercial support, development, porting,
licensing and training services.
*/
/*-----------------------------------------------------------
* Portable layer API. Each function must be defined for each port.
*----------------------------------------------------------*/
#ifndef PORTABLE_H
#define PORTABLE_H
/* Include the macro file relevant to the port being used. */
#ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT
#include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h"
typedef void ( __interrupt __far *pxISR )();
#endif
#ifdef OPEN_WATCOM_FLASH_LITE_186_PORT
#include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h"
typedef void ( __interrupt __far *pxISR )();
#endif
#ifdef GCC_MEGA_AVR
#include "../portable/GCC/ATMega323/portmacro.h"
#endif
#ifdef IAR_MEGA_AVR
#include "../portable/IAR/ATMega323/portmacro.h"
#endif
#ifdef MPLAB_PIC24_PORT
#include "..\..\Source\portable\MPLAB\PIC24_dsPIC\portmacro.h"
#endif
#ifdef MPLAB_DSPIC_PORT
#include "..\..\Source\portable\MPLAB\PIC24_dsPIC\portmacro.h"
#endif
#ifdef MPLAB_PIC18F_PORT
#include "..\..\Source\portable\MPLAB\PIC18F\portmacro.h"
#endif
#ifdef MPLAB_PIC32MX_PORT
#include "..\..\Source\portable\MPLAB\PIC32MX\portmacro.h"
#endif
#ifdef _FEDPICC
#include "libFreeRTOS/Include/portmacro.h"
#endif
#ifdef SDCC_CYGNAL
#include "../../Source/portable/SDCC/Cygnal/portmacro.h"
#endif
#ifdef GCC_ARM7
#include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h"
#endif
#ifdef GCC_ARM7_ECLIPSE
#include "portmacro.h"
#endif
#ifdef ROWLEY_LPC23xx
#include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h"
#endif
#ifdef IAR_MSP430
#include "..\..\Source\portable\IAR\MSP430\portmacro.h"
#endif
#ifdef GCC_MSP430
#include "../../Source/portable/GCC/MSP430F449/portmacro.h"
#endif
#ifdef ROWLEY_MSP430
#include "../../Source/portable/Rowley/MSP430F449/portmacro.h"
#endif
#ifdef ARM7_LPC21xx_KEIL_RVDS
#include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h"
#endif
#ifdef SAM7_GCC
#include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h"
#endif
#ifdef SAM7_IAR
#include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h"
#endif
#ifdef SAM9XE_IAR
#include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h"
#endif
#ifdef LPC2000_IAR
#include "..\..\Source\portable\IAR\LPC2000\portmacro.h"
#endif
#ifdef STR71X_IAR
#include "..\..\Source\portable\IAR\STR71x\portmacro.h"
#endif
#ifdef STR75X_IAR
#include "..\..\Source\portable\IAR\STR75x\portmacro.h"
#endif
#ifdef STR75X_GCC
#include "..\..\Source\portable\GCC\STR75x\portmacro.h"
#endif
#ifdef STR91X_IAR
#include "..\..\Source\portable\IAR\STR91x\portmacro.h"
#endif
#ifdef GCC_H8S
#include "../../Source/portable/GCC/H8S2329/portmacro.h"
#endif
#ifdef GCC_AT91FR40008
#include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h"
#endif
#ifdef RVDS_ARMCM3_LM3S102
#include "../../Source/portable/RVDS/ARM_CM3/portmacro.h"
#endif
#ifdef GCC_ARMCM3_LM3S102
#include "../../Source/portable/GCC/ARM_CM3/portmacro.h"
#endif
#ifdef GCC_ARMCM3
#include "../../Source/portable/GCC/ARM_CM3/portmacro.h"
#endif
#ifdef IAR_ARM_CM3
#include "../../Source/portable/IAR/ARM_CM3/portmacro.h"
#endif
#ifdef IAR_ARMCM3_LM
#include "../../Source/portable/IAR/ARM_CM3/portmacro.h"
#endif
#ifdef HCS12_CODE_WARRIOR
#include "../../Source/portable/CodeWarrior/HCS12/portmacro.h"
#endif
#ifdef MICROBLAZE_GCC
#include "../../Source/portable/GCC/MicroBlaze/portmacro.h"
#endif
#ifdef TERN_EE
#include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h"
#endif
#ifdef GCC_HCS12
#include "../../Source/portable/GCC/HCS12/portmacro.h"
#endif
#ifdef GCC_MCF5235
#include "../../Source/portable/GCC/MCF5235/portmacro.h"
#endif
#ifdef COLDFIRE_V2_GCC
#include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h"
#endif
#ifdef COLDFIRE_V2_CODEWARRIOR
#include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h"
#endif
#ifdef GCC_PPC405
#include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h"
#endif
#ifdef GCC_PPC440
#include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h"
#endif
#ifdef _16FX_SOFTUNE
#include "..\..\Source\portable\Softune\MB96340\portmacro.h"
#endif
#ifdef GCC_OMAP3_BeagleBoard
#include "../../Source/portable/GCC/OMAP3_BeagleBoard/portmacro.h"
#endif
#ifdef BCC_INDUSTRIAL_PC_PORT
/* A short file name has to be used in place of the normal
FreeRTOSConfig.h when using the Borland compiler. */
#include "frconfig.h"
#include "..\portable\BCC\16BitDOS\PC\prtmacro.h"
typedef void ( __interrupt __far *pxISR )();
#endif
#ifdef BCC_FLASH_LITE_186_PORT
/* A short file name has to be used in place of the normal
FreeRTOSConfig.h when using the Borland compiler. */
#include "frconfig.h"
#include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h"
typedef void ( __interrupt __far *pxISR )();
#endif
#ifdef __GNUC__
#ifdef __AVR32_AVR32A__
#include "portmacro.h"
#endif
#endif
#ifdef __ICCAVR32__
#ifdef __CORE__
#if __CORE__ == __AVR32A__
#include "portmacro.h"
#endif
#endif
#endif
#ifdef __91467D
#include "portmacro.h"
#endif
#ifdef __96340
#include "portmacro.h"
#endif
#ifdef __IAR_V850ES_Fx3__
#include "../../Source/portable/IAR/V850ES/portmacro.h"
#endif
#ifdef __IAR_V850ES_Jx3__
#include "../../Source/portable/IAR/V850ES/portmacro.h"
#endif
#ifdef __IAR_V850ES_Jx3_L__
#include "../../Source/portable/IAR/V850ES/portmacro.h"
#endif
#ifdef __IAR_V850ES_Jx2__
#include "../../Source/portable/IAR/V850ES/portmacro.h"
#endif
#ifdef __IAR_V850ES_Hx2__
#include "../../Source/portable/IAR/V850ES/portmacro.h"
#endif
#ifdef __IAR_78K0R_Kx3__
#include "../../Source/portable/IAR/78K0R/portmacro.h"
#endif
#ifdef __IAR_78K0R_Kx3L__
#include "../../Source/portable/IAR/78K0R/portmacro.h"
#endif
/* Catch all to ensure portmacro.h is included in the build. Newer demos
have the path as part of the project options, rather than as relative from
the project location. If portENTER_CRITICAL() has not been defined then
portmacro.h has not yet been included - as every portmacro.h provides a
portENTER_CRITICAL() definition. Check the demo application for your demo
to find the path to the correct portmacro.h file. */
#ifndef portENTER_CRITICAL
#include "portmacro.h"
#endif
#if portBYTE_ALIGNMENT == 8
#define portBYTE_ALIGNMENT_MASK ( 0x0007 )
#endif
#if portBYTE_ALIGNMENT == 4
#define portBYTE_ALIGNMENT_MASK ( 0x0003 )
#endif
#if portBYTE_ALIGNMENT == 2
#define portBYTE_ALIGNMENT_MASK ( 0x0001 )
#endif
#if portBYTE_ALIGNMENT == 1
#define portBYTE_ALIGNMENT_MASK ( 0x0000 )
#endif
#ifndef portBYTE_ALIGNMENT_MASK
#error "Invalid portBYTE_ALIGNMENT definition"
#endif
#ifndef portNUM_CONFIGURABLE_REGIONS
#define portNUM_CONFIGURABLE_REGIONS 1
#endif
#ifdef __cplusplus
extern "C" {
#endif
#include "mpu_wrappers.h"
/*
* Setup the stack of a new task so it is ready to be placed under the
* scheduler control. The registers have to be placed on the stack in
* the order that the port expects to find them.
*
*/
#if( portUSING_MPU_WRAPPERS == 1 )
portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters, portBASE_TYPE xRunPrivileged ) PRIVILEGED_FUNCTION;
#else
portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters );
#endif
/*
* Map to the memory management routines required for the port.
*/
void *pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION;
void vPortFree( void *pv ) PRIVILEGED_FUNCTION;
void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION;
size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION;
/*
* Setup the hardware ready for the scheduler to take control. This generally
* sets up a tick interrupt and sets timers for the correct tick frequency.
*/
portBASE_TYPE xPortStartScheduler( void ) PRIVILEGED_FUNCTION;
/*
* Undo any hardware/ISR setup that was performed by xPortStartScheduler() so
* the hardware is left in its original condition after the scheduler stops
* executing.
*/
void vPortEndScheduler( void ) PRIVILEGED_FUNCTION;
/*
* The structures and methods of manipulating the MPU are contained within the
* port layer.
*
* Fills the xMPUSettings structure with the memory region information
* contained in xRegions.
*/
#if( portUSING_MPU_WRAPPERS == 1 )
struct xMEMORY_REGION;
void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, portSTACK_TYPE *pxBottomOfStack, unsigned short usStackDepth ) PRIVILEGED_FUNCTION;
#endif
#ifdef __cplusplus
}
#endif
#endif /* PORTABLE_H */
|
NikhilKalige/uefi_freertos_beagleboard
|
freertos_test/Source/include/portable.h
|
C
|
mit
| 12,141
|
require 'spec_helper'
describe Array do
before do
@array = Forgery::Extend([0,1,2,3,4,5,6,7,8,9])
end
it "should get a random item out of the array" do
10.times { expect(@array).to include(@array.random) }
end
it "should return nil if the array is empty" do
expect(Forgery::Extend([]).random).to be_nil
end
it "should return a random subset of the array" do
@array.random_subset(5).each do |i|
expect(@array).to include(i)
end
end
it "should return a random subset of the array that is 3 long" do
expect(@array.random_subset(3).size).to eq(3)
end
end
|
sevenwire/forgery
|
spec/extensions/array_spec.rb
|
Ruby
|
mit
| 606
|
package authorizer
import (
"context"
"github.com/influxdata/influxdb/v2"
"github.com/influxdata/influxdb/v2/kit/platform"
)
var _ influxdb.SecretService = (*SecretService)(nil)
// SecretService wraps a influxdb.SecretService and authorizes actions
// against it appropriately.
type SecretService struct {
s influxdb.SecretService
}
// NewSecretService constructs an instance of an authorizing secret service.
func NewSecretService(s influxdb.SecretService) *SecretService {
return &SecretService{
s: s,
}
}
// LoadSecret checks to see if the authorizer on context has read access to the secret key provided.
func (s *SecretService) LoadSecret(ctx context.Context, orgID platform.ID, key string) (string, error) {
if _, _, err := AuthorizeOrgReadResource(ctx, influxdb.SecretsResourceType, orgID); err != nil {
return "", err
}
secret, err := s.s.LoadSecret(ctx, orgID, key)
if err != nil {
return "", err
}
return secret, nil
}
// GetSecretKeys checks to see if the authorizer on context has read access to all the secrets belonging to orgID.
func (s *SecretService) GetSecretKeys(ctx context.Context, orgID platform.ID) ([]string, error) {
if _, _, err := AuthorizeOrgReadResource(ctx, influxdb.SecretsResourceType, orgID); err != nil {
return []string{}, err
}
secrets, err := s.s.GetSecretKeys(ctx, orgID)
if err != nil {
return []string{}, err
}
return secrets, nil
}
// PutSecret checks to see if the authorizer on context has write access to the secret key provided.
func (s *SecretService) PutSecret(ctx context.Context, orgID platform.ID, key string, val string) error {
if _, _, err := AuthorizeCreate(ctx, influxdb.SecretsResourceType, orgID); err != nil {
return err
}
err := s.s.PutSecret(ctx, orgID, key, val)
if err != nil {
return err
}
return nil
}
// PutSecrets checks to see if the authorizer on context has read and write access to the secret keys provided.
func (s *SecretService) PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error {
// PutSecrets operates on intersection between m and keys beloging to orgID.
// We need to have read access to those secrets since it deletes the secrets (within the intersection) that have not be overridden.
if _, _, err := AuthorizeOrgReadResource(ctx, influxdb.SecretsResourceType, orgID); err != nil {
return err
}
if _, _, err := AuthorizeOrgWriteResource(ctx, influxdb.SecretsResourceType, orgID); err != nil {
return err
}
err := s.s.PutSecrets(ctx, orgID, m)
if err != nil {
return err
}
return nil
}
// PatchSecrets checks to see if the authorizer on context has write access to the secret keys provided.
func (s *SecretService) PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error {
if _, _, err := AuthorizeOrgWriteResource(ctx, influxdb.SecretsResourceType, orgID); err != nil {
return err
}
err := s.s.PatchSecrets(ctx, orgID, m)
if err != nil {
return err
}
return nil
}
// DeleteSecret checks to see if the authorizer on context has write access to the secret keys provided.
func (s *SecretService) DeleteSecret(ctx context.Context, orgID platform.ID, keys ...string) error {
if _, _, err := AuthorizeOrgWriteResource(ctx, influxdb.SecretsResourceType, orgID); err != nil {
return err
}
err := s.s.DeleteSecret(ctx, orgID, keys...)
if err != nil {
return err
}
return nil
}
|
influxdb/influxdb
|
authorizer/secret.go
|
GO
|
mit
| 3,383
|
# oVirt Node
This is the main entry page for using oVirt Node.
More informations about developing oVirt Node can be found here (TBD).
# Overview
The oVirt Node sub-project is geared towards building a small, robust operating system
image. It uses minimal resources while providing the ability to control virtual machines
running upon it.
After installing oVirt Node the host can directly be added to oVirt Engine and be used as a
host to run your Virtual Machines.
For installation Node now relies on [Anaconda](https://github.com/rhinstaller/) - the installer
used for installing Fedora, CentOS and Red Hat Enterprise Linux. Formerly Node used a
specialiced TUI installer to perform the installation.
For administration Node is now leveraging [Cockpit](http://cockpit-project.org/) formerly
the administration was performed by a specialiced administration TUI.
# Quickstart
1. Download the oVirt Node installation iso from one of our release streams([see below](#releases))
2. Install oVirt Node on your bare-metal host
3. Navigate to Cockpit on https://yourhost.example.com:9090/ to configure your host (i.e. configure networking)
4. Navigate to Engine and add the host **OR** run `hosted-engine-setup`
> If you encounter problems, please file them in [bugzilla](https://bugzilla.redhat.com/enter_bug.cgi?product=ovirt-node&component=General).
# Frequently asked questions
Please see [this page](faq) for some common questions.
# Releases and Streams
oVirt Node is released continously.
Usually you install Node once, using one of our installer images (see below). Afterwards you
use `yum update` (or updates through Engine from 4.0 on) to keep your hosts updated.
> Note: `yum update` will not update individual packages like on normal Fedora or CentOS systems,
> it will rather update the whole image.
> Note: You can verify the integrity of any downloaded installation iso by checking the embedded checksum:
> `checkisomd5 $ISONAME`
## Legacy vs. Vintage
With oVirt 4.0 Node got a complete overhaul and reimplementation - which are using Anaconda
and Cockpit as described above.
Up to oVirt 3.x Node was using a custom installer, a custom administration TUI, and a custom
build process. All of these - including other design decisions - caused a couple of issues,
which we addressed with the re-designed oVirt Node 4.0.
## oVirt Node 3
* **oVirt Node 3 Next** (Tech-Preview, downwards compatible within oVirt 3, **recommended**)
* This is the oVirt Node Next image, with the newly designed oVirt Node, but using the stable oVirt 3 packages.
* [Installation ISO](http://jenkins.ovirt.org/job/ovirt-node-ng_ovirt-3.6_build-artifacts-fc22-x86_64/lastSuccessfulBuild/artifact/exported-artifacts/latest-installation-iso.html)
* Jenkins job: <http://jenkins.ovirt.org/job/ovirt-node-ng_ovirt-3.6_build-artifacts-fc22-x86_64/>
* **oVirt Node 3 Vintage** (downwards compatible within oVirt 3, legacy)
* Installation and update ISO: <http://jenkins.ovirt.org/job/ovirt-node_ovirt-3.6_create-iso-el7_merged/>
## oVirt Node 4
This is the oVirt Node 4 image including the latest oVirt 4 packages.
* [Installation ISO](http://jenkins.ovirt.org/job/ovirt-node-ng_ovirt-4.0_build-artifacts-fc22-x86_64/lastSuccessfulBuild/artifact/exported-artifacts/latest-installation-iso.html)
* Jenkins job: <http://jenkins.ovirt.org/job/ovirt-node-ng_ovirt-4.0_build-artifacts-fc22-x86_64/>
## oVirt Node Master
This is the oVirt Node image build based on oVirt packages from the master branches.
* [Installation ISO](http://jenkins.ovirt.org/job/ovirt-node-ng_master_build-artifacts-fc22-x86_64/lastSuccessfulBuild/artifact/exported-artifacts/latest-installation-iso.html)
* Jenkins job: <http://jenkins.ovirt.org/job/ovirt-node-ng_master_build-artifacts-fc22-x86_64/>
|
jtokar/ovirt-site
|
source/node/index.md
|
Markdown
|
mit
| 3,789
|
<?php
namespace MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Cegedim\Bundle\OwaCasBundle\Security\User\OwaUser;
class OptionController extends Controller
{
public function indexAction()
{
$name = '';
$webinar_params = '';
if($this->get('security.context')->getToken()->getUser() instanceof OwaUser){
$name = $this->get('security.context')->getToken()->getUser()->getUsername();
$firstname = $this->get('security.context')->getToken()->getUser()->getFirstname();
$webinar_params = '?name='. $name .'&firstname='. $firstname;
}
return $this->render('MainBundle:Option:option.html.twig', array('name' => $name, 'webinar_params' => $webinar_params));
}
}
|
stephanekesy/test
|
src/MainBundle/Controller/OptionController.php
|
PHP
|
mit
| 757
|
namespace ProGaudi.Tarantool.Client.Model
{
public class Metrics
{
private readonly ILogicalConnection _logicalConnection;
public Metrics(ILogicalConnection logicalConnection)
{
_logicalConnection = logicalConnection;
}
public uint PingsFailedByTimeoutCount => _logicalConnection.PingsFailedByTimeoutCount;
}
}
|
progaudi/progaudi.tarantool
|
src/progaudi.tarantool/Model/Metrics.cs
|
C#
|
mit
| 380
|
---
layout: post
title: "Lissted"
slug: lissted
source: http://lissted.com
---
<img src="/screenshots/lissted.png">
|
GetBlimp/built-with-ember
|
_posts/2015-11-02-lissted.md
|
Markdown
|
mit
| 117
|
// Adafruit Motor shield library
// copyright Adafruit Industries LLC, 2009
// this code is public domain, enjoy!
// v1r1_2018-07-14 : ������ ����, �Լ� �߰�
#if (ARDUINO >= 100)
#include "Arduino.h"
#else
#if defined(__AVR__)
#include <avr/io.h>
#endif
#include "WProgram.h"
#endif
//#include "AFMotor.h"
#include "AFMotor_v1r1.h"
static uint8_t latch_state;
#if (MICROSTEPS == 8)
uint8_t microstepcurve[] = {0, 50, 98, 142, 180, 212, 236, 250, 255};
#elif (MICROSTEPS == 16)
uint8_t microstepcurve[] = {0, 25, 50, 74, 98, 120, 141, 162, 180, 197, 212, 225, 236, 244, 250, 253, 255};
#endif
AFMotorController::AFMotorController(void) {
TimerInitalized = false;
}
void AFMotorController::enable(void) {
// setup the latch
/*
LATCH_DDR |= _BV(LATCH);
ENABLE_DDR |= _BV(ENABLE);
CLK_DDR |= _BV(CLK);
SER_DDR |= _BV(SER);
*/
pinMode(MOTORLATCH, OUTPUT);
pinMode(MOTORENABLE, OUTPUT);
pinMode(MOTORDATA, OUTPUT);
pinMode(MOTORCLK, OUTPUT);
latch_state = 0;
latch_tx(); // "reset"
//ENABLE_PORT &= ~_BV(ENABLE); // enable the chip outputs!
digitalWrite(MOTORENABLE, LOW);
}
void AFMotorController::latch_tx(void) {
uint8_t i;
//LATCH_PORT &= ~_BV(LATCH);
digitalWrite(MOTORLATCH, LOW);
//SER_PORT &= ~_BV(SER);
digitalWrite(MOTORDATA, LOW);
for (i=0; i<8; i++) {
//CLK_PORT &= ~_BV(CLK);
digitalWrite(MOTORCLK, LOW);
if (latch_state & _BV(7-i)) {
//SER_PORT |= _BV(SER);
digitalWrite(MOTORDATA, HIGH);
} else {
//SER_PORT &= ~_BV(SER);
digitalWrite(MOTORDATA, LOW);
}
//CLK_PORT |= _BV(CLK);
digitalWrite(MOTORCLK, HIGH);
}
//LATCH_PORT |= _BV(LATCH);
digitalWrite(MOTORLATCH, HIGH);
}
static AFMotorController MC;
/******************************************
MOTORS
******************************************/
inline void initPWM1(uint8_t freq) {
#if defined(__AVR_ATmega8__) || \
defined(__AVR_ATmega48__) || \
defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega328P__)
// use PWM from timer2A on PB3 (Arduino pin #11)
TCCR2A |= _BV(COM2A1) | _BV(WGM20) | _BV(WGM21); // fast PWM, turn on oc2a
TCCR2B = freq & 0x7;
OCR2A = 0;
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// on arduino mega, pin 11 is now PB5 (OC1A)
TCCR1A |= _BV(COM1A1) | _BV(WGM10); // fast PWM, turn on oc1a
TCCR1B = (freq & 0x7) | _BV(WGM12);
OCR1A = 0;
#elif defined(__PIC32MX__)
#if defined(PIC32_USE_PIN9_FOR_M1_PWM)
// Make sure that pin 11 is an input, since we have tied together 9 and 11
pinMode(9, OUTPUT);
pinMode(11, INPUT);
if (!MC.TimerInitalized)
{ // Set up Timer2 for 80MHz counting fro 0 to 256
T2CON = 0x8000 | ((freq & 0x07) << 4); // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=<freq>, T32=0, TCS=0; // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=0, T32=0, TCS=0
TMR2 = 0x0000;
PR2 = 0x0100;
MC.TimerInitalized = true;
}
// Setup OC4 (pin 9) in PWM mode, with Timer2 as timebase
OC4CON = 0x8006; // OC32 = 0, OCTSEL=0, OCM=6
OC4RS = 0x0000;
OC4R = 0x0000;
#elif defined(PIC32_USE_PIN10_FOR_M1_PWM)
// Make sure that pin 11 is an input, since we have tied together 9 and 11
pinMode(10, OUTPUT);
pinMode(11, INPUT);
if (!MC.TimerInitalized)
{ // Set up Timer2 for 80MHz counting fro 0 to 256
T2CON = 0x8000 | ((freq & 0x07) << 4); // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=<freq>, T32=0, TCS=0; // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=0, T32=0, TCS=0
TMR2 = 0x0000;
PR2 = 0x0100;
MC.TimerInitalized = true;
}
// Setup OC5 (pin 10) in PWM mode, with Timer2 as timebase
OC5CON = 0x8006; // OC32 = 0, OCTSEL=0, OCM=6
OC5RS = 0x0000;
OC5R = 0x0000;
#else
// If we are not using PWM for pin 11, then just do digital
digitalWrite(11, LOW);
#endif
#else
#error "This chip is not supported!"
#endif
#if !defined(PIC32_USE_PIN9_FOR_M1_PWM) && !defined(PIC32_USE_PIN10_FOR_M1_PWM)
pinMode(11, OUTPUT);
#endif
}
inline void setPWM1(uint8_t s) {
#if defined(__AVR_ATmega8__) || \
defined(__AVR_ATmega48__) || \
defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega328P__)
// use PWM from timer2A on PB3 (Arduino pin #11)
OCR2A = s;
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// on arduino mega, pin 11 is now PB5 (OC1A)
OCR1A = s;
#elif defined(__PIC32MX__)
#if defined(PIC32_USE_PIN9_FOR_M1_PWM)
// Set the OC4 (pin 9) PMW duty cycle from 0 to 255
OC4RS = s;
#elif defined(PIC32_USE_PIN10_FOR_M1_PWM)
// Set the OC5 (pin 10) PMW duty cycle from 0 to 255
OC5RS = s;
#else
// If we are not doing PWM output for M1, then just use on/off
if (s > 127)
{
digitalWrite(11, HIGH);
}
else
{
digitalWrite(11, LOW);
}
#endif
#else
#error "This chip is not supported!"
#endif
}
inline void initPWM2(uint8_t freq) {
#if defined(__AVR_ATmega8__) || \
defined(__AVR_ATmega48__) || \
defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega328P__)
// use PWM from timer2B (pin 3)
TCCR2A |= _BV(COM2B1) | _BV(WGM20) | _BV(WGM21); // fast PWM, turn on oc2b
TCCR2B = freq & 0x7;
OCR2B = 0;
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// on arduino mega, pin 3 is now PE5 (OC3C)
TCCR3A |= _BV(COM1C1) | _BV(WGM10); // fast PWM, turn on oc3c
TCCR3B = (freq & 0x7) | _BV(WGM12);
OCR3C = 0;
#elif defined(__PIC32MX__)
if (!MC.TimerInitalized)
{ // Set up Timer2 for 80MHz counting fro 0 to 256
T2CON = 0x8000 | ((freq & 0x07) << 4); // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=<freq>, T32=0, TCS=0; // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=0, T32=0, TCS=0
TMR2 = 0x0000;
PR2 = 0x0100;
MC.TimerInitalized = true;
}
// Setup OC1 (pin3) in PWM mode, with Timer2 as timebase
OC1CON = 0x8006; // OC32 = 0, OCTSEL=0, OCM=6
OC1RS = 0x0000;
OC1R = 0x0000;
#else
#error "This chip is not supported!"
#endif
pinMode(3, OUTPUT);
}
inline void setPWM2(uint8_t s) {
#if defined(__AVR_ATmega8__) || \
defined(__AVR_ATmega48__) || \
defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega328P__)
// use PWM from timer2A on PB3 (Arduino pin #11)
OCR2B = s;
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// on arduino mega, pin 11 is now PB5 (OC1A)
OCR3C = s;
#elif defined(__PIC32MX__)
// Set the OC1 (pin3) PMW duty cycle from 0 to 255
OC1RS = s;
#else
#error "This chip is not supported!"
#endif
}
inline void initPWM3(uint8_t freq) {
#if defined(__AVR_ATmega8__) || \
defined(__AVR_ATmega48__) || \
defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega328P__)
// use PWM from timer0A / PD6 (pin 6)
TCCR0A |= _BV(COM0A1) | _BV(WGM00) | _BV(WGM01); // fast PWM, turn on OC0A
//TCCR0B = freq & 0x7;
OCR0A = 0;
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// on arduino mega, pin 6 is now PH3 (OC4A)
TCCR4A |= _BV(COM1A1) | _BV(WGM10); // fast PWM, turn on oc4a
TCCR4B = (freq & 0x7) | _BV(WGM12);
//TCCR4B = 1 | _BV(WGM12);
OCR4A = 0;
#elif defined(__PIC32MX__)
if (!MC.TimerInitalized)
{ // Set up Timer2 for 80MHz counting fro 0 to 256
T2CON = 0x8000 | ((freq & 0x07) << 4); // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=<freq>, T32=0, TCS=0; // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=0, T32=0, TCS=0
TMR2 = 0x0000;
PR2 = 0x0100;
MC.TimerInitalized = true;
}
// Setup OC3 (pin 6) in PWM mode, with Timer2 as timebase
OC3CON = 0x8006; // OC32 = 0, OCTSEL=0, OCM=6
OC3RS = 0x0000;
OC3R = 0x0000;
#else
#error "This chip is not supported!"
#endif
pinMode(6, OUTPUT);
}
inline void setPWM3(uint8_t s) {
#if defined(__AVR_ATmega8__) || \
defined(__AVR_ATmega48__) || \
defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega328P__)
// use PWM from timer0A on PB3 (Arduino pin #6)
OCR0A = s;
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// on arduino mega, pin 6 is now PH3 (OC4A)
OCR4A = s;
#elif defined(__PIC32MX__)
// Set the OC3 (pin 6) PMW duty cycle from 0 to 255
OC3RS = s;
#else
#error "This chip is not supported!"
#endif
}
inline void initPWM4(uint8_t freq) {
#if defined(__AVR_ATmega8__) || \
defined(__AVR_ATmega48__) || \
defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega328P__)
// use PWM from timer0B / PD5 (pin 5)
TCCR0A |= _BV(COM0B1) | _BV(WGM00) | _BV(WGM01); // fast PWM, turn on oc0a
//TCCR0B = freq & 0x7;
OCR0B = 0;
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// on arduino mega, pin 5 is now PE3 (OC3A)
TCCR3A |= _BV(COM1A1) | _BV(WGM10); // fast PWM, turn on oc3a
TCCR3B = (freq & 0x7) | _BV(WGM12);
//TCCR4B = 1 | _BV(WGM12);
OCR3A = 0;
#elif defined(__PIC32MX__)
if (!MC.TimerInitalized)
{ // Set up Timer2 for 80MHz counting fro 0 to 256
T2CON = 0x8000 | ((freq & 0x07) << 4); // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=<freq>, T32=0, TCS=0; // ON=1, FRZ=0, SIDL=0, TGATE=0, TCKPS=0, T32=0, TCS=0
TMR2 = 0x0000;
PR2 = 0x0100;
MC.TimerInitalized = true;
}
// Setup OC2 (pin 5) in PWM mode, with Timer2 as timebase
OC2CON = 0x8006; // OC32 = 0, OCTSEL=0, OCM=6
OC2RS = 0x0000;
OC2R = 0x0000;
#else
#error "This chip is not supported!"
#endif
pinMode(5, OUTPUT);
}
inline void setPWM4(uint8_t s) {
#if defined(__AVR_ATmega8__) || \
defined(__AVR_ATmega48__) || \
defined(__AVR_ATmega88__) || \
defined(__AVR_ATmega168__) || \
defined(__AVR_ATmega328P__)
// use PWM from timer0A on PB3 (Arduino pin #6)
OCR0B = s;
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// on arduino mega, pin 6 is now PH3 (OC4A)
OCR3A = s;
#elif defined(__PIC32MX__)
// Set the OC2 (pin 5) PMW duty cycle from 0 to 255
OC2RS = s;
#else
#error "This chip is not supported!"
#endif
}
AF_DCMotor::AF_DCMotor(uint8_t num, uint8_t freq) {
motornum = num;
pwmfreq = freq;
/*
MC.enable();
switch (num) {
case 1:
latch_state &= ~_BV(MOTOR1_A) & ~_BV(MOTOR1_B); // set both motor pins to 0
MC.latch_tx();
initPWM1(freq);
break;
case 2:
latch_state &= ~_BV(MOTOR2_A) & ~_BV(MOTOR2_B); // set both motor pins to 0
MC.latch_tx();
initPWM2(freq);
break;
case 3:
latch_state &= ~_BV(MOTOR3_A) & ~_BV(MOTOR3_B); // set both motor pins to 0
MC.latch_tx();
initPWM3(freq);
break;
case 4:
latch_state &= ~_BV(MOTOR4_A) & ~_BV(MOTOR4_B); // set both motor pins to 0
MC.latch_tx();
initPWM4(freq);
break;
}
*/
}
void AF_DCMotor::ready() {
MC.enable();
switch (motornum) {
case 1:
latch_state &= ~_BV(MOTOR1_A) & ~_BV(MOTOR1_B); // set both motor pins to 0
MC.latch_tx();
initPWM1(pwmfreq);
break;
case 2:
latch_state &= ~_BV(MOTOR2_A) & ~_BV(MOTOR2_B); // set both motor pins to 0
MC.latch_tx();
initPWM2(pwmfreq);
break;
case 3:
latch_state &= ~_BV(MOTOR3_A) & ~_BV(MOTOR3_B); // set both motor pins to 0
MC.latch_tx();
initPWM3(pwmfreq);
break;
case 4:
latch_state &= ~_BV(MOTOR4_A) & ~_BV(MOTOR4_B); // set both motor pins to 0
MC.latch_tx();
initPWM4(pwmfreq);
break;
}
}
void AF_DCMotor::run(uint8_t cmd) {
uint8_t a, b;
switch (motornum) {
case 1:
a = MOTOR1_A; b = MOTOR1_B; break;
case 2:
a = MOTOR2_A; b = MOTOR2_B; break;
case 3:
a = MOTOR3_A; b = MOTOR3_B; break;
case 4:
a = MOTOR4_A; b = MOTOR4_B; break;
default:
return;
}
switch (cmd) {
case FORWARD:
latch_state |= _BV(a);
latch_state &= ~_BV(b);
MC.latch_tx();
break;
case BACKWARD:
latch_state &= ~_BV(a);
latch_state |= _BV(b);
MC.latch_tx();
break;
case RELEASE:
latch_state &= ~_BV(a); // A and B both low
latch_state &= ~_BV(b);
MC.latch_tx();
break;
}
}
void AF_DCMotor::setSpeed(uint8_t speed) {
switch (motornum) {
case 1:
setPWM1(speed); break;
case 2:
setPWM2(speed); break;
case 3:
setPWM3(speed); break;
case 4:
setPWM4(speed); break;
}
}
/******************************************
STEPPERS
******************************************/
AF_Stepper::AF_Stepper(uint16_t steps, uint8_t num) {
// MC.enable();
revsteps = steps;
steppernum = num;
currentstep = 0;
/*
if (steppernum == 1) {
latch_state &= ~_BV(MOTOR1_A) & ~_BV(MOTOR1_B) &
~_BV(MOTOR2_A) & ~_BV(MOTOR2_B); // all motor pins to 0
MC.latch_tx();
// enable both H bridges
pinMode(11, OUTPUT);
pinMode(3, OUTPUT);
digitalWrite(11, HIGH);
digitalWrite(3, HIGH);
// use PWM for microstepping support
initPWM1(STEPPER1_PWM_RATE);
initPWM2(STEPPER1_PWM_RATE);
setPWM1(255);
setPWM2(255);
} else if (steppernum == 2) {
latch_state &= ~_BV(MOTOR3_A) & ~_BV(MOTOR3_B) &
~_BV(MOTOR4_A) & ~_BV(MOTOR4_B); // all motor pins to 0
MC.latch_tx();
// enable both H bridges
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
// use PWM for microstepping support
// use PWM for microstepping support
initPWM3(STEPPER2_PWM_RATE);
initPWM4(STEPPER2_PWM_RATE);
setPWM3(255);
setPWM4(255);
}
*/
}
void AF_Stepper::ready() {
MC.enable();
if (steppernum == 1) {
latch_state &= ~_BV(MOTOR1_A) & ~_BV(MOTOR1_B) &
~_BV(MOTOR2_A) & ~_BV(MOTOR2_B); // all motor pins to 0
MC.latch_tx();
// enable both H bridges
pinMode(11, OUTPUT);
pinMode(3, OUTPUT);
digitalWrite(11, HIGH);
digitalWrite(3, HIGH);
// use PWM for microstepping support
initPWM1(STEPPER1_PWM_RATE);
initPWM2(STEPPER1_PWM_RATE);
setPWM1(255);
setPWM2(255);
} else if (steppernum == 2) {
latch_state &= ~_BV(MOTOR3_A) & ~_BV(MOTOR3_B) &
~_BV(MOTOR4_A) & ~_BV(MOTOR4_B); // all motor pins to 0
MC.latch_tx();
// enable both H bridges
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
// use PWM for microstepping support
// use PWM for microstepping support
initPWM3(STEPPER2_PWM_RATE);
initPWM4(STEPPER2_PWM_RATE);
setPWM3(255);
setPWM4(255);
}
}
void AF_Stepper::setSpeed(uint16_t rpm) {
usperstep = 60000000 / ((uint32_t)revsteps * (uint32_t)rpm);
steppingcounter = 0;
}
void AF_Stepper::release(void) {
if (steppernum == 1) {
latch_state &= ~_BV(MOTOR1_A) & ~_BV(MOTOR1_B) &
~_BV(MOTOR2_A) & ~_BV(MOTOR2_B); // all motor pins to 0
MC.latch_tx();
} else if (steppernum == 2) {
latch_state &= ~_BV(MOTOR3_A) & ~_BV(MOTOR3_B) &
~_BV(MOTOR4_A) & ~_BV(MOTOR4_B); // all motor pins to 0
MC.latch_tx();
}
}
void AF_Stepper::step(uint16_t steps, uint8_t dir, uint8_t style) {
uint32_t uspers = usperstep;
uint8_t ret = 0;
if (style == INTERLEAVE) {
uspers /= 2;
}
else if (style == MICROSTEP) {
uspers /= MICROSTEPS;
steps *= MICROSTEPS;
#ifdef MOTORDEBUG
Serial.print("steps = "); Serial.println(steps, DEC);
#endif
}
while (steps--) {
ret = onestep(dir, style);
delay(uspers/1000); // in ms
steppingcounter += (uspers % 1000);
if (steppingcounter >= 1000) {
delay(1);
steppingcounter -= 1000;
}
}
if (style == MICROSTEP) {
while ((ret != 0) && (ret != MICROSTEPS)) {
ret = onestep(dir, style);
delay(uspers/1000); // in ms
steppingcounter += (uspers % 1000);
if (steppingcounter >= 1000) {
delay(1);
steppingcounter -= 1000;
}
}
}
}
uint8_t AF_Stepper::onestep(uint8_t dir, uint8_t style) {
uint8_t a, b, c, d;
uint8_t ocrb, ocra;
ocra = ocrb = 255;
if (steppernum == 1) {
a = _BV(MOTOR1_A);
b = _BV(MOTOR2_A);
c = _BV(MOTOR1_B);
d = _BV(MOTOR2_B);
} else if (steppernum == 2) {
a = _BV(MOTOR3_A);
b = _BV(MOTOR4_A);
c = _BV(MOTOR3_B);
d = _BV(MOTOR4_B);
} else {
return 0;
}
// next determine what sort of stepping procedure we're up to
if (style == SINGLE) {
if ((currentstep/(MICROSTEPS/2)) % 2) { // we're at an odd step, weird
if (dir == FORWARD) {
currentstep += MICROSTEPS/2;
}
else {
currentstep -= MICROSTEPS/2;
}
} else { // go to the next even step
if (dir == FORWARD) {
currentstep += MICROSTEPS;
}
else {
currentstep -= MICROSTEPS;
}
}
} else if (style == DOUBLE) {
if (! (currentstep/(MICROSTEPS/2) % 2)) { // we're at an even step, weird
if (dir == FORWARD) {
currentstep += MICROSTEPS/2;
} else {
currentstep -= MICROSTEPS/2;
}
} else { // go to the next odd step
if (dir == FORWARD) {
currentstep += MICROSTEPS;
} else {
currentstep -= MICROSTEPS;
}
}
} else if (style == INTERLEAVE) {
if (dir == FORWARD) {
currentstep += MICROSTEPS/2;
} else {
currentstep -= MICROSTEPS/2;
}
}
if (style == MICROSTEP) {
if (dir == FORWARD) {
currentstep++;
} else {
// BACKWARDS
currentstep--;
}
currentstep += MICROSTEPS*4;
currentstep %= MICROSTEPS*4;
ocra = ocrb = 0;
if ( (currentstep >= 0) && (currentstep < MICROSTEPS)) {
ocra = microstepcurve[MICROSTEPS - currentstep];
ocrb = microstepcurve[currentstep];
} else if ( (currentstep >= MICROSTEPS) && (currentstep < MICROSTEPS*2)) {
ocra = microstepcurve[currentstep - MICROSTEPS];
ocrb = microstepcurve[MICROSTEPS*2 - currentstep];
} else if ( (currentstep >= MICROSTEPS*2) && (currentstep < MICROSTEPS*3)) {
ocra = microstepcurve[MICROSTEPS*3 - currentstep];
ocrb = microstepcurve[currentstep - MICROSTEPS*2];
} else if ( (currentstep >= MICROSTEPS*3) && (currentstep < MICROSTEPS*4)) {
ocra = microstepcurve[currentstep - MICROSTEPS*3];
ocrb = microstepcurve[MICROSTEPS*4 - currentstep];
}
}
currentstep += MICROSTEPS*4;
currentstep %= MICROSTEPS*4;
#ifdef MOTORDEBUG
Serial.print("current step: "); Serial.println(currentstep, DEC);
Serial.print(" pwmA = "); Serial.print(ocra, DEC);
Serial.print(" pwmB = "); Serial.println(ocrb, DEC);
#endif
if (steppernum == 1) {
setPWM1(ocra);
setPWM2(ocrb);
} else if (steppernum == 2) {
setPWM3(ocra);
setPWM4(ocrb);
}
// release all
latch_state &= ~a & ~b & ~c & ~d; // all motor pins to 0
//Serial.println(step, DEC);
if (style == MICROSTEP) {
if ((currentstep >= 0) && (currentstep < MICROSTEPS))
latch_state |= a | b;
if ((currentstep >= MICROSTEPS) && (currentstep < MICROSTEPS*2))
latch_state |= b | c;
if ((currentstep >= MICROSTEPS*2) && (currentstep < MICROSTEPS*3))
latch_state |= c | d;
if ((currentstep >= MICROSTEPS*3) && (currentstep < MICROSTEPS*4))
latch_state |= d | a;
} else {
switch (currentstep/(MICROSTEPS/2)) {
case 0:
latch_state |= a; // energize coil 1 only
break;
case 1:
latch_state |= a | b; // energize coil 1+2
break;
case 2:
latch_state |= b; // energize coil 2 only
break;
case 3:
latch_state |= b | c; // energize coil 2+3
break;
case 4:
latch_state |= c; // energize coil 3 only
break;
case 5:
latch_state |= c | d; // energize coil 3+4
break;
case 6:
latch_state |= d; // energize coil 4 only
break;
case 7:
latch_state |= d | a; // energize coil 1+4
break;
}
}
MC.latch_tx();
return currentstep;
}
|
kjsii123/entry-hw
|
app/firmwares/examples/freearduino/AFMotor_v1r1.cpp
|
C++
|
mit
| 20,250
|
using GraphQL.Validation.Rules;
using Xunit;
namespace GraphQL.Tests.Validation
{
public class UniqueFragmentNamesTests : ValidationTestBase<UniqueFragmentNames, ValidationSchema>
{
[Fact]
public void no_fragments()
{
ShouldPassRule(@"
{
field
}
");
}
[Fact]
public void one_fragment()
{
ShouldPassRule(@"
{
...fragA
}
fragment fragA on Type {
field
}
");
}
[Fact]
public void many_fragments()
{
ShouldPassRule(@"
{
...fragA
...fragB
...fragC
}
fragment fragA on Type {
fieldA
}
fragment fragB on Type {
fieldB
}
fragment fragC on Type {
fieldC
}
");
}
[Fact]
public void inline_fragments_are_always_unique()
{
ShouldPassRule(@"
{
...on Type {
fieldA
}
...on Type {
fieldB
}
}
");
}
[Fact]
public void fragment_and_operation_named_the_same()
{
ShouldPassRule(@"
query Foo {
...Foo
}
fragment Foo on Type {
field
}
");
}
[Fact]
public void fragments_named_the_same()
{
ShouldFailRule(_ =>
{
_.Query = @"
{
...fragA
}
fragment fragA on Type {
fieldA
}
fragment fragA on Type {
fieldB
}
";
// Note: this is failing on "fragment"; graphql-js fails on the fragment name.
duplicateFrag(_, "fragA", 5, 11, 8, 11);
});
}
[Fact]
public void fragments_named_the_same_without_being_referenced()
{
ShouldFailRule(_ =>
{
_.Query = @"
fragment fragA on Type {
fieldA
}
fragment fragA on Type {
fieldB
}
";
// Note: this is failing on "fragment"; graphql-js fails on the fragment name.
duplicateFrag(_, "fragA", 2, 11, 5, 11);
});
}
private void duplicateFrag(
ValidationTestConfig _,
string fragName,
int line1,
int column1,
int line2,
int column2)
{
_.Error(err =>
{
err.Message = Rule.DuplicateFragmentNameMessage(fragName);
err.Loc(line1, column1);
err.Loc(line2, column2);
});
}
}
}
|
dNetGuru/graphql-dotnet
|
src/GraphQL.Tests/Validation/UniqueFragmentNamesTests.cs
|
C#
|
mit
| 2,547
|
require "./template_item.rb"
puts "==========================================="
puts "Test Item"
puts "==========================================="
#{
# property : [{type=>name},{type=>name},...]
# class:xxx
# superclass:xxx
#}
hash = {"class" => "TestListItem",
"superclass" => "VZItem",
"property" => [{"name"=>"name","class"=>"NSString"},{"name"=>"desc","class"=>"NSArray"}]}
puts "Hash Value : #{hash}"
puts "\n"
h = T_Item::renderH(hash)
puts h
puts "-------------------------------------------"
m = T_Item::renderM(hash)
puts m
|
vizlabxt/VZScaffold
|
scaffold/template/vizzle/test_item.rb
|
Ruby
|
mit
| 557
|
# jsdom
jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG [DOM](https://dom.spec.whatwg.org/) and [HTML](https://html.spec.whatwg.org/multipage/) Standards, for use with Node.js. In general, the goal of the project is to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications.
The latest versions of jsdom require Node.js v6 or newer. (Versions of jsdom below v10 still work with Node.js v4, but are unsupported.)
As of v10, jsdom has a new API (documented below). The old API is still supported for now; [see its documentation](./lib/old-api.md) for details.
## Basic usage
```js
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
```
To use jsdom, you will primarily use the `JSDOM` constructor, which is a named export of the jsdom main module. Pass the constructor a string. You will get back a `JSDOM` object, which has a number of useful properties, notably `window`:
```js
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"
```
(Note that jsdom will parse the HTML you pass it just like a browser does, including implied `<html>`, `<head>`, and `<body>` tags.)
The resulting object is an instance of the `JSDOM` class, which contains a number of useful properties and methods besides `window`. In general it can be used to act on the jsdom from the "outside," doing things that are not possible with the normal DOM APIs. For simple cases, where you don't need any of this functionality, we recommend a coding pattern like
```js
const { window } = new JSDOM(`...`);
// or even
const { document } = (new JSDOM(`...`)).window;
```
Full documentation on everything you can do with the `JSDOM` class is below, in the section "`JSDOM` Object API".
## Customizing jsdom
The `JSDOM` constructor accepts a second parameter which can be used to customize your jsdom in the following ways.
### Simple options
```js
const dom = new JSDOM(``, {
url: "https://example.org/",
referrer: "https://example.com/",
contentType: "text/html",
userAgent: "Mellblomenator/9000",
includeNodeLocations: true
});
```
- `url` sets the value returned by `window.location`, `document.URL`, and `document.documentURI`, and affects things like resolution of relative URLs within the document and the same-origin restrictions and referrer used while fetching subresources. It defaults to `"about:blank"`.
- `referrer` just affects the value read from `document.referrer`. It defaults to no referrer (which reflects as the empty string).
- `contentType` affects the value read from `document.contentType`, and how the document is parsed: as HTML or as XML. Values that are not `"text/html"` or an [XML mime type](https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type) will throw. It defaults to `"text/html"`.
- `userAgent` affects the value read from `navigator.userAgent`, as well as the `User-Agent` header sent while fetching subresources. It defaults to <code>\`Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}\`</code>.
- `includeNodeLocations` preserves the location info produced by the HTML parser, allowing you to retrieve it with the `nodeLocation()` method (described below). It defaults to `false` to give the best performance, and cannot be used with an XML content type since our XML parser does not support location info.
Note that both `url` and `referrer` are canonicalized before they're used, so e.g. if you pass in `"https:example.com"`, jsdom will interpret that as if you had given `"https://example.com/"`. If you pass an unparseable URL, the call will throw. (URLs are parsed and serialized according to the [URL Standard](http://url.spec.whatwg.org/).)
### Executing scripts
jsdom's most powerful ability is that it can execute scripts inside the jsdom. These scripts can modify the content of the page and access all the web platform APIs jsdom implements.
However, this is also highly dangerous when dealing with untrusted content. The jsdom sandbox is not foolproof, and code running inside the DOM's `<script>`s can, if it tries hard enough, get access to the Node.js environment, and thus to your machine. As such, the ability to execute scripts embedded in the HTML is disabled by default:
```js
const dom = new JSDOM(`<body>
<script>document.body.appendChild(document.createElement("hr"));</script>
</body>`);
// The script will not be executed, by default:
dom.window.document.body.children.length === 1;
```
To enable executing scripts inside the page, you can use the `runScripts: "dangerously"` option:
```js
const dom = new JSDOM(`<body>
<script>document.body.appendChild(document.createElement("hr"));</script>
</body>`, { runScripts: "dangerously" });
// The script will be executed and modify the DOM:
dom.window.document.body.children.length === 2;
```
Again we emphasize to only use this when feeding jsdom code you know is safe. If you use it on arbitrary user-supplied code, or code from the Internet, you are effectively running untrusted Node.js code, and your machine could be compromised.
Note that event handler attributes, like `<div onclick="">`, will also not function unless `runScripts` is set to `"dangerously"`. (However, event handler _properties_, like `div.onclick = ...`, will function regardless of `runScripts`.)
If you are simply trying to execute script "from the outside", instead of letting `<script>` elements (and inline event handlers) run "from the inside", you can use the `runScripts: "outside-only"` option, which enables `window.eval`:
```js
const window = (new JSDOM(``, { runScripts: "outside-only" })).window;
window.eval(`document.body.innerHTML = "<p>Hello, world!</p>";`);
window.document.body.children.length === 1;
```
This is turned off by default for performance reasons, but is safe to enable.
Note that we strongly advise against trying to "execute scripts" by mashing together the jsdom and Node global environments (e.g. by doing `global.window = dom.window`), and then executing scripts or test code inside the Node global environment. Instead, you should treat jsdom like you would a browser, and run all scripts and tests that need access to a DOM inside the jsdom environment, using `window.eval` or `runScripts: "dangerously"`. This might require, for example, creating a browserify bundle to execute as a `<script>` element—just like you would in a browser.
Finally, for advanced use cases you can use the `dom.runVMScript(script)` method, documented below.
### Loading subresources
By default, jsdom will not load any subresources such as scripts, stylesheets, images, or iframes. If you'd like jsdom to load such resources, you can pass the `resources: "usable"` option, which will load all usable resources. Those are:
* Frames and iframes, via `<frame>` and `<iframe>`
* Stylesheets, via `<link rel="stylesheet">`
* Scripts, via `<script>`, but only if `runScripts: "dangerously"` is also set
* Images, via `<img>`, but only if the `canvas` (or `canvas-prebuilt`) npm package is also installed (see "Canvas Support" below)
In the future we plan to offer more customization of resource loading via this option, but for now the default and the `"usable"` option are the two modes offered.
### Virtual consoles
Like web browsers, jsdom has the concept of a "console". This records both information directly sent from the page, via scripts executing inside the document, as well as information from the jsdom implementation itself. We call the user-controllable console a "virtual console", to distinguish it from the Node.js `console` API and from the inside-the-page `window.console` API.
By default, the `JSDOM` constructor will return an instance with a virtual console that forwards all its output to the Node.js console. To create your own virtual console and pass it to jsdom, you can override this default by doing
```js
const virtualConsole = new jsdom.VirtualConsole();
const dom = new JSDOM(``, { virtualConsole });
```
Code like this will create a virtual console with no behavior. You can give it behavior by adding event listeners for all the possible console methods:
```js
virtualConsole.on("error", () => { ... });
virtualConsole.on("warn", () => { ... });
virtualConsole.on("info", () => { ... });
virtualConsole.on("dir", () => { ... });
// ... etc. See https://console.spec.whatwg.org/#logging
```
(Note that it is probably best to set up these event listeners *before* calling `new JSDOM()`, since errors or console-invoking script might occur during parsing.)
If you simply want to redirect the virtual console output to another console, like the default Node.js one, you can do
```js
virtualConsole.sendTo(console);
```
There is also a special event, `"jsdomError"`, which will fire with error objects to report errors from jsdom itself. This is similar to how error messages often show up in web browser consoles, even if they are not initiated by `console.error`. So far, the following errors are output this way:
- Errors loading or parsing subresources (scripts, stylesheets, frames, and iframes)
- Script execution errors that are not handled by a window `onerror` event handler that returns `true` or calls `event.preventDefault()`
- Not-implemented errors resulting from calls to methods, like `window.alert`, which jsdom does not implement, but installs anyway for web compatibility
If you're using `sendTo(c)` to send errors to `c`, by default it will call `console.error` with information from `"jsdomError"` events. If you'd prefer to maintain a strict one-to-one mapping of events to method calls, and perhaps handle `"jsdomError"`s yourself, then you can do
```js
virtualConsole.sendTo(c, { omitJSDOMErrors: true });
```
### Cookie jars
Like web browsers, jsdom has the concept of a cookie jar, storing HTTP cookies. Cookies that have a URL on the same domain as the document, and are not marked HTTP-only, are accessible via the `document.cookie` API. Additionally, all cookies in the cookie jar will impact the fetching of subresources.
By default, the `JSDOM` constructor will return an instance with an empty cookie jar. To create your own cookie jar and pass it to jsdom, you can override this default by doing
```js
const cookieJar = new jsdom.CookieJar(store, options);
const dom = new JSDOM(``, { cookieJar });
```
This is mostly useful if you want to share the same cookie jar among multiple jsdoms, or prime the cookie jar with certain values ahead of time.
Cookie jars are provided by the [tough-cookie](https://www.npmjs.com/package/tough-cookie) package. The `jsdom.CookieJar` constructor is a subclass of the tough-cookie cookie jar which by default sets the `looseMode: true` option, since that [matches better how browsers behave](https://github.com/whatwg/html/issues/804). If you want to use tough-cookie's utilities and classes yourself, you can use the `jsdom.toughCookie` module export to get access to the tough-cookie module instance packaged with jsdom.
### Intervening before parsing
jsdom allows you to intervene in the creation of a jsdom very early: after the `Window` and `Document` objects are created, but before any HTML is parsed to populate the document with nodes:
```js
const dom = new JSDOM(`<p>Hello</p>`, {
beforeParse(window) {
window.document.childNodes.length === 0;
window.someCoolAPI = () => { /* ... */ };
}
});
```
This is especially useful if you are wanting to modify the environment in some way, for example adding shims for web platform APIs jsdom does not support.
## `JSDOM` object API
Once you have constructed a `JSDOM` object, it will have the following useful capabilities:
### Properties
The property `window` retrieves the `Window` object that was created for you.
The properties `virtualConsole` and `cookieJar` reflect the options you pass in, or the defaults created for you if nothing was passed in for those options.
### Serializing the document with `serialize()`
The `serialize()` method will return the [HTML serialization](https://html.spec.whatwg.org/#html-fragment-serialisation-algorithm) of the document, including the doctype:
```js
const dom = new JSDOM(`<!DOCTYPE html>hello`);
dom.serialize() === "<!DOCTYPE html><html><head></head><body>hello</body></html>";
// Contrast with:
dom.window.document.documentElement.outerHTML === "<html><head></head><body>hello</body></html>";
```
### Getting the source location of a node with `nodeLocation(node)`
The `nodeLocation()` method will find where a DOM node is within the source document, returning the [parse5 location info](https://www.npmjs.com/package/parse5#options-locationinfo) for the node:
```js
const dom = new JSDOM(
`<p>Hello
<img src="foo.jpg">
</p>`,
{ includeNodeLocations: true }
);
const document = dom.window.document;
const bodyEl = document.body; // implicitly created
const pEl = document.querySelector("p");
const textNode = pEl.firstChild;
const imgEl = document.querySelector("img");
console.log(dom.nodeLocation(bodyEl)); // null; it's not in the source
console.log(dom.nodeLocation(pEl)); // { startOffset: 0, endOffset: 39, startTag: ..., endTag: ... }
console.log(dom.nodeLocation(textNode)); // { startOffset: 3, endOffset: 13 }
console.log(dom.nodeLocation(imgEl)); // { startOffset: 13, endOffset: 32 }
```
Note that this feature only works if you have set the `includeNodeLocations` option; node locations are off by default for performance reasons.
### Running vm-created scripts with `runVMScript(script)`
The built-in `vm` module of Node.js allows you to create `Script` instances, which can be compiled ahead of time and then run multiple times on a given "VM context". Behind the scenes, a jsdom `Window` is indeed a VM context. To get access to this ability, use the `runVMScript()` method:
```js
const { Script } = require("vm");
const dom = new JSDOM(``, { runScripts: "outside-only" });
const s = new Script(`
if (!this.ran) {
this.ran = 0;
}
++this.ran;
`);
dom.runVMScript(s);
dom.runVMScript(s);
dom.runVMScript(s);
dom.window.ran === 3;
```
This is somewhat-advanced functionality, and we advise sticking to normal DOM APIs (such as `window.eval()` or `document.createElement("script")`) unless you have very specific needs.
### Reconfiguring the jsdom with `reconfigure(settings)`
The `top` property on `window` is marked `[Unforgeable]` in the spec, meaning it is a non-configurable own property and thus cannot be overridden or shadowed by normal code running inside the jsdom, even using `Object.defineProperty`.
Similarly, at present jsdom does not handle navigation (such as setting `window.location.href === "https://example.com/"`); doing so will cause the virtual console to emit a `"jsdomError"` explaining that this feature is not implemented, and nothing will change: there will be no new `Window` or `Document` object, and the existing `window`'s `location` object will still have all the same property values.
However, if you're acting from outside the window, e.g. in some test framework that creates jsdoms, you can override one or both of these using the special `reconfigure()` method:
```js
const dom = new JSDOM();
dom.window.top === dom.window;
dom.window.location.href === "about:blank";
dom.reconfigure({ windowTop: myFakeTopForTesting, url: "https://example.com/" });
dom.window.top === myFakeTopForTesting;
dom.window.location.href === "https://example.com/";
```
Note that changing the jsdom's URL will impact all APIs that return the current document URL, such as `window.location`, `document.URL`, and `document.documentURI`, as well as resolution of relative URLs within the document, and the same-origin checks and referrer used while fetching subresources. It will not, however, perform a navigation to the contents of that URL; the contents of the DOM will remain unchanged, and no new instances of `Window`, `Document`, etc. will be created.
## Convenience APIs
### `fromURL()`
In addition to the `JSDOM` constructor itself, jsdom provides a promise-returning factory method for constructing a jsdom from a URL:
```js
JSDOM.fromURL("https://example.com/", options).then(dom => {
console.log(dom.serialize());
});
```
The returned promise will fulfill with a `JSDOM` instance if the URL is valid and the request is successful. Any redirects will be followed to their ultimate destination.
The options provided to `fromURL()` are similar to those provided to the `JSDOM` constructor, with the following additional restrictions and consequences:
- The `url` and `contentType` options cannot be provided.
- The `referrer` option is used as the HTTP `Referer` request header of the initial request.
- The `userAgent` option is used as the HTTP `User-Agent` request header of any requests.
- The resulting jsdom's URL, content type, and referrer are determined from the response.
- Any cookies set via HTTP `Set-Cookie` response headers are stored in the jsdom's cookie jar. Similarly, any cookies already in a supplied cookie jar are sent as HTTP `Cookie` request headers.
The initial request is not infinitely customizable to the same extent as is possible in a package like [request](https://www.npmjs.com/package/request); `fromURL()` is meant to be a convenience API for the majority of cases. If you need greater control over the initial request, you should perform it yourself, and then use the `JSDOM` constructor manually.
### `fromFile()`
Similar to `fromURL()`, jsom also provides a `fromFile()` factory method for constructing a jsdom from a filename:
```js
JSDOM.fromFile("stuff.html", options).then(dom => {
console.log(dom.serialize());
});
```
The returned promise will fulfill with a `JSDOM` instance if the given file can be opened. As usual in Node.js APIs, the filename is given relative to the current working directory.
The options provided to `fromFile()` are similar to those provided to the `JSDOM` constructor, with the following additional defaults:
- The `url` option will default to a file URL corresponding to the given filename, instead of to `"about:blank"`.
- The `contentType` option will default to `"application/xhtml+xml"` if the given filename ends in `.xhtml` or `.xml`; otherwise it will continue to default to `"text/html"`.
### `fragment()`
For the very simplest of cases, you might not need a whole `JSDOM` instance with all its associated power. You might not even need a `Window` or `Document`! Instead, you just need to parse some HTML, and get a DOM object you can manipulate. For that, we have `fragment()`, which creates a `DocumentFragment` from a given string:
```js
const frag = JSDOM.fragment(`<p>Hello</p><p><strong>Hi!</strong>`);
frag.childNodes.length === 2;
frag.querySelector("strong").textContent = "Why hello there!";
// etc.
```
Here `frag` is a [`DocumentFragment`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) instance, whose contents are created by parsing the provided string. The parsing is done using a `<template>` element, so you can include any element there (including ones with weird parsing rules like `<td>`).
All invocations of the `framgment()` factory result in `DocumentFragment`s that share the same owner `Document` and `Window`. This allows many calls to `fragment()` with no extra overhead. But it also means that calls to `fragment()` cannot be customized with any options.
Note that serialization is not as easy with `DocumentFragment`s as it is with full `JSDOM` objects. If you need to serialize your DOM, you should probably use the `JSDOM` constructor more directly. But for the special case of a fragment containing a single element, it's pretty easy to do through normal means:
```js
const frag = JSDOM.fragment(`<p>Hello</p>`);
console.log(frag.firstChild.outerHTML); // logs "<p>Hello</p>"
```
## Other noteworthy features
### Canvas support
jsdom includes support for using the [`canvas`](https://www.npmjs.com/package/canvas) or [`canvas-prebuilt`](https://npmjs.org/package/canvas-prebuilt) package to extend any `<canvas>` elements with the canvas API. To make this work, you need to include `canvas` as a dependency in your project, as a peer of `jsdom`. If jsdom can find the `canvas` package, it will use it, but if it's not present, then `<canvas>` elements will behave like `<div>`s.
### Encoding sniffing
In addition to supplying a string, the `JSDOM` constructor can also be supplied binary data, in the form of a Node.js [`Buffer`](https://nodejs.org/docs/latest/api/buffer.html) or a standard JavaScript binary data type like `ArrayBuffer`, `Uint8Array`, `DataView`, etc. When this is done, jsdom will [sniff the encoding](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm) from the supplied bytes, scanning for `<meta charset>` tags just like a browser does.
This encoding sniffing also applies to `JSDOM.fromFile()` and `JSDOM.fromURL()`. In the latter case, just as in a browser, any `Content-Type` headers sent with the response will take priority.
### Closing down a jsdom
Timers in the jsdom (set by `window.setTimeout()` or `window.setInterval()`) will, by definition, execute code in the future in the context of the window. Since there is no way to execute code in the future without keeping the process alive, outstanding jsdom timers will keep your Node.js process alive. Similarly, since there is no way to execute code in the context of an object without keeping that object alive, outstanding jsdom timers will prevent garbage collection of the window on which they are scheduled.
If you want to be sure to shut down a jsdom window, use `window.close()`, which will terminate all running timers (and also remove any event listeners on the window and document).
### Running jsdom inside a web browser
jsdom has some support for being run inside a web browser, using [browserify](https://browserify.org/). That is, inside a web browser, you can use a browserified jsdom to create an entirely self-contained set of plain JavaScript objects which look and act much like the browser's existing DOM objects, while being entirely independent of them. "Virtual DOM", indeed!
jsdom's primary target is still Node.js, and so we use language features that are only present in recent Node.js versions (namely, Node.js v6+). Thus, older browsers will likely not work. (Even transpilation will not help much: we plan to use `Proxy`s extensively throughout the course of jsdom v10.x.)
Notably, jsdom works well inside a web worker. The original contributor, [@lawnsea](https://github.com/lawnsea/), who made this possible, has [published a paper](https://pdfs.semanticscholar.org/47f0/6bb6607a975500a30e9e52d7c9fbc0034e27.pdf) about his project which uses this capability.
Not everything works perfectly when running jsdom inside a web browser. Sometimes that is because of fundamental limitations (such as not having filesystem access), but sometimes it is simply because we haven't spent enough time making the appropriate small tweaks. Bug reports are certainly welcome.
## Caveats
### Asynchronous script loading
People often have trouble with asynchronous script loading when using jsdom. Many pages loads scripts asynchronously, but there is no way to tell when they're done doing so, and thus when it's a good time to run your code and inspect the resulting DOM structure. This is a fundamental limitation; we cannot predict what scripts on the web page will do, and so cannot tell you when they are done loading more scripts.
This can be worked around in a few ways. The best way, if you control the page in question, is to use whatever mechanisms are given by the script loader to detect when loading is done. For example, if you're using a module loader like RequireJS, the code could look like:
```js
// On the Node.js side:
const window = (new JSDOM(...)).window;
window.onModulesLoaded = () => {
console.log("ready to roll!");
};
```
```html
<!-- Inside the HTML you supply to jsdom -->
<script>
requirejs(["entry-module"], () => {
window.onModulesLoaded();
});
</script>
```
If you do not control the page, you could try workarounds such as polling for the presence of a specific element.
For more details, see the discussion in [#640](https://github.com/tmpvar/jsdom/issues/640), especially [@matthewkastor](https://github.com/matthewkastor)'s [insightful comment](https://github.com/tmpvar/jsdom/issues/640#issuecomment-22216965).
### Shared constructors and prototypes
At the present time, for most web platform APIs, jsdom shares the same class definition between multiple seemingly-independent jsdoms. That means that, for example, the following situation can occur:
```js
const dom1 = new JSDOM();
const dom2 = new JSDOM();
dom1.window.Element.prototype.expando = "blah";
console.log(dom2.window.document.createElement("frameset").expando); // logs "blah"
```
This is done mainly for performance and memory reasons: creating separate copies of all the many classes on the web platform, each time we create a jsdom, would be rather expensive.
Nevertheless, we remain interested in one day providing an option to create an "independent" jsdom, at the cost of some performance.
### Missing features in the new API
Compared to the old jsdom API from v9.x and before, the new API is noticably missing fine-grained control of resource loads. Previous versions of jsdom allowed you to set options that were used when making requests (both for the initial request, in the old equivalent of `JSDOM.fromURL()`, and for subresource requests). They also allowed you to control which subresources were requested and applied to the main document, so that you could e.g. download stylesheets but not scripts. Finally, they provided a customizable resource loader that let you intercept any outgoing request and fulfill it with a completely synthetic response.
None of these features are yet in the new jsdom API, although we are hoping to add them back soon! This requires a decent amount of behind-the-scenes work to implement in a reasonable way, unfortunately.
In the meantime, please feel free to use the old jsdom API to get access to this functionality. It is supported and maintained, although it will not be getting new features. The documentation is found in [lib/old-api.md](./lib/old-api.md).
### Unimplemented parts of the web platform
Although we enjoy adding new features to jsdom and keeping it up to date with the latest web specs, it has many missing APIs. Please feel free to file an issue for anything missing, but we're a small and busy team, so a pull request might work even better.
Beyond just features that we haven't gotten to yet, there are two major features that are currently outside the scope of jsdom. These are:
- **Navigation**: the ability to change the global object, and all other objects, when clicking a link or assigning `location.href` or similar.
- **Layout**: the ability to calculate where elements will be visually laid out as a result of CSS, which impacts methods like `getBoundingClientRects()` or properties like `offsetTop`.
Currently jsdom has dummy behaviors for some aspects of these features, such as sending a "not implemented" `"jsdomError"` to the virtual console for navigation, or returning zeros for many layout-related properties. Often you can work around these limitations in your code, e.g. by creating new `JSDOM` instances for each page you "navigate" to during a crawl, or using `Object.defineProperty()` to change what various layout-related getters and methods return.
Note that other tools in the same space, such as PhantomJS, do support these features. On the wiki, we have a more complete writeup about [jsdom vs. PhantomJS](https://github.com/tmpvar/jsdom/wiki/jsdom-vs.-PhantomJS).
## Getting help
If you need help with jsdom, please feel free to use any of the following venues:
- The [mailing list](http://groups.google.com/group/jsdom) (best for "how do I" questions)
- The [issue tracker](https://github.com/tmpvar/jsdom/issues) (best for bug reports)
- The IRC channel: [#jsdom on freenode](irc://irc.freenode.net/jsdom)
|
danshapiro-optimizely/full_stack_redux
|
voting-client/node_modules/jsdom/README.md
|
Markdown
|
mit
| 28,230
|
// Type definitions for ag-grid v3.3.3
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ceolter/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
export interface SetFilterParameters {
/** Same as cell renderer for grid (you can use the same one in both locations). Setting it separatly here allows for the value to be rendered differently in the filter. */
cellRenderer?: Function;
/** The height of the cell. */
cellHeight?: number;
/** The values to display in the filter. */
values?: any;
/** What to do when new rows are loaded. The default is to reset the filter, as the set of values to select from can have changed. If you want to keep the selection, then set this value to 'keep'. */
newRowsAction?: string;
/** If true, the filter will not remove items that are no longer availabe due to other filters. */
suppressRemoveEntries?: boolean;
/** Comparator for sorting. If not provided, the colDef comparator is used. If colDef also not provided, the default (agGrid provided) comparator is used.*/
comparator?: (a: any, b: any) => number;
}
|
JohnGeorgiadis/x-formation-test-sample
|
node_modules/ag-grid/dist/lib/filter/setFilterParameters.d.ts
|
TypeScript
|
mit
| 1,152
|
import numpy
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
def _pair(x):
if hasattr(x, '__getitem__'):
return x
return x, x
class Shift(function_node.FunctionNode):
def __init__(self, ksize=3, dilate=1):
super(Shift, self).__init__()
self.kh, self.kw = _pair(ksize)
if self.kh % 2 != 1:
raise ValueError('kh must be odd')
if self.kw % 2 != 1:
raise ValueError('kw must be odd')
self.dy, self.dx = _pair(dilate)
def check_type_forward(self, in_types):
n_in = in_types.size()
type_check.expect(n_in == 1)
x_type = in_types[0]
type_check.expect(
x_type.dtype.kind == 'f',
x_type.ndim == 4,
x_type.shape[1] >= self.kh * self.kw,
)
def forward_cpu(self, inputs):
x = inputs[0]
b, c, h, w = x.shape
py = self.kh // 2 * abs(self.dy)
px = self.kw // 2 * abs(self.dx)
x = numpy.pad(x, ((0, 0), (0, 0), (py, py), (px, px)),
'constant')
n_groups = self.kh * self.kw
group_size = c // n_groups
ret = []
for i, group_idx in enumerate(range(n_groups)):
# Make sure that center group is last
if group_idx == (n_groups - 1) // 2:
group_idx = n_groups - 1
elif group_idx == (n_groups - 1):
group_idx = (n_groups - 1) // 2
ky = (group_idx // self.kw) - py // abs(self.dy)
kx = (group_idx % self.kw) - px // abs(self.dx)
hs = py + -ky * self.dy
ws = px + -kx * self.dx
he = hs + h
we = ws + w
cs = i * group_size
ce = (i + 1) * group_size if i < n_groups - 1 else None
ret.append(x[:, cs:ce, hs:he, ws:we])
return numpy.concatenate(ret, axis=1),
def forward_gpu(self, inputs):
x = inputs[0]
b, c, h, w = x.shape
y = cuda.cupy.empty_like(x)
cuda.elementwise(
'raw T x, int32 c, int32 h, int32 w,'
'int32 kh, int32 kw,'
'int32 dy, int32 dx',
'T y',
'''
int b0 = i / (c * h * w);
int rest = i % (c * h * w);
int c0 = rest / (h * w);
rest %= h * w;
int out_row = rest / w;
int out_col = rest % w;
int n_groups = kh * kw;
int group_size = c / n_groups;
int group_idx = c0 / group_size;
// Make sure that center group is last
if (group_idx == (n_groups - 1) / 2) {
group_idx = n_groups - 1;
} else if (group_idx == n_groups - 1) {
group_idx = (n_groups - 1) / 2;
}
int ky = (group_idx / kw) - kh / 2;
int kx = (group_idx % kw) - kw / 2;
if (group_idx >= n_groups) {
ky = 0;
kx = 0;
}
int in_row = -ky * dy + out_row;
int in_col = -kx * dx + out_col;
if (in_row >= 0 && in_row < h && in_col >= 0 && in_col < w) {
y = x[b0 * c * h * w + c0 * h * w + in_row * w + in_col];
} else {
y = 0;
}
''',
'shift_gpu')(x, c, h, w, self.kh, self.kw, self.dy, self.dx, y)
return y,
def backward(self, indexes, grad_outputs):
return shift(grad_outputs[0], ksize=(self.kh, self.kw),
dilate=(-self.dy, -self.dx)),
def shift(x, ksize=3, dilate=1):
"""Shift function.
See: `Shift: A Zero FLOP, Zero Parameter Alternative to Spatial \
Convolutions <https://arxiv.org/abs/1711.08141>`_
Args:
x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`):
Input variable of shape :math:`(n, c, h, w)`.
ksize (int or pair of ints): Size of filters (a.k.a. kernels).
``ksize=k`` and ``ksize=(k, k)`` are equivalent.
dilate (int or pair of ints): Dilation factor of filter applications.
``dilate=d`` and ``dilate=(d, d)`` are equivalent.
Returns:
~chainer.Variable:
Output variable of same shape as ``x``.
"""
fnode = Shift(ksize, dilate)
y, = fnode.apply((x,))
return y
|
anaruse/chainer
|
chainer/functions/connection/shift.py
|
Python
|
mit
| 4,492
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2013 Orcacoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef _BITCOINRPC_H_
#define _BITCOINRPC_H_ 1
#include <string>
#include <list>
#include <map>
class CBlockIndex;
class CReserveKey;
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#include "util.h"
// HTTP status codes
enum HTTPStatusCode
{
HTTP_OK = 200,
HTTP_BAD_REQUEST = 400,
HTTP_UNAUTHORIZED = 401,
HTTP_FORBIDDEN = 403,
HTTP_NOT_FOUND = 404,
HTTP_INTERNAL_SERVER_ERROR = 500,
};
// Bitcoin RPC error codes
enum RPCErrorCode
{
// Standard JSON-RPC 2.0 errors
RPC_INVALID_REQUEST = -32600,
RPC_METHOD_NOT_FOUND = -32601,
RPC_INVALID_PARAMS = -32602,
RPC_INTERNAL_ERROR = -32603,
RPC_PARSE_ERROR = -32700,
// General application defined errors
RPC_MISC_ERROR = -1, // std::exception thrown in command handling
RPC_FORBIDDEN_BY_SAFE_MODE = -2, // Server is in safe mode, and command is not allowed in safe mode
RPC_TYPE_ERROR = -3, // Unexpected type was passed as parameter
RPC_INVALID_ADDRESS_OR_KEY = -5, // Invalid address or key
RPC_OUT_OF_MEMORY = -7, // Ran out of memory during operation
RPC_INVALID_PARAMETER = -8, // Invalid, missing or duplicate parameter
RPC_DATABASE_ERROR = -20, // Database error
RPC_DESERIALIZATION_ERROR = -22, // Error parsing or validating structure in raw format
// P2P client errors
RPC_CLIENT_NOT_CONNECTED = -9, // Bitcoin is not connected
RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, // Still downloading initial blocks
// Wallet errors
RPC_WALLET_ERROR = -4, // Unspecified problem with wallet (key not found etc.)
RPC_WALLET_INSUFFICIENT_FUNDS = -6, // Not enough funds in wallet or account
RPC_WALLET_INVALID_ACCOUNT_NAME = -11, // Invalid account name
RPC_WALLET_KEYPOOL_RAN_OUT = -12, // Keypool ran out, call keypoolrefill first
RPC_WALLET_UNLOCK_NEEDED = -13, // Enter the wallet passphrase with walletpassphrase first
RPC_WALLET_PASSPHRASE_INCORRECT = -14, // The wallet passphrase entered was incorrect
RPC_WALLET_WRONG_ENC_STATE = -15, // Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.)
RPC_WALLET_ENCRYPTION_FAILED = -16, // Failed to encrypt the wallet
RPC_WALLET_ALREADY_UNLOCKED = -17, // Wallet is already unlocked
};
json_spirit::Object JSONRPCError(int code, const std::string& message);
void StartRPCThreads();
void StopRPCThreads();
int CommandLineRPC(int argc, char *argv[]);
/** Convert parameter values for RPC call from strings to command-specific JSON objects. */
json_spirit::Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams);
/*
Type-check arguments; throws JSONRPCError if wrong type given. Does not check that
the right number of arguments are passed, just that any passed are the correct type.
Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type));
*/
void RPCTypeCheck(const json_spirit::Array& params,
const std::list<json_spirit::Value_type>& typesExpected, bool fAllowNull=false);
/*
Check for expected keys/value types in an Object.
Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type));
*/
void RPCTypeCheck(const json_spirit::Object& o,
const std::map<std::string, json_spirit::Value_type>& typesExpected, bool fAllowNull=false);
typedef json_spirit::Value(*rpcfn_type)(const json_spirit::Array& params, bool fHelp);
class CRPCCommand
{
public:
std::string name;
rpcfn_type actor;
bool okSafeMode;
bool threadSafe;
};
/**
* Bitcoin RPC command dispatcher.
*/
class CRPCTable
{
private:
std::map<std::string, const CRPCCommand*> mapCommands;
public:
CRPCTable();
const CRPCCommand* operator[](std::string name) const;
std::string help(std::string name) const;
/**
* Execute a method.
* @param method Method to execute
* @param params Array of arguments (JSON objects)
* @returns Result of the call.
* @throws an exception (json_spirit::Value) when an error happens.
*/
json_spirit::Value execute(const std::string &method, const json_spirit::Array ¶ms) const;
};
extern const CRPCTable tableRPC;
extern CReserveKey* pMiningKey;
extern int64 nWalletUnlockTime;
extern int64 AmountFromValue(const json_spirit::Value& value);
extern json_spirit::Value ValueFromAmount(int64 amount);
extern double GetDifficulty(const CBlockIndex* blockindex = NULL);
extern std::string HexBits(unsigned int nBits);
extern std::string HelpRequiringPassphrase();
extern void EnsureWalletIsUnlocked();
extern json_spirit::Value getconnectioncount(const json_spirit::Array& params, bool fHelp); // in rpcnet.cpp
extern json_spirit::Value getpeerinfo(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value addnode(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getaddednodeinfo(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getcheckpoint(const json_spirit::Array& params, bool fHelp); // in checkpointsync.cpp
extern json_spirit::Value sendcheckpoint(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value enforcecheckpoint(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value makekeypair(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value sendalert(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value dumpprivkey(const json_spirit::Array& params, bool fHelp); // in rpcdump.cpp
extern json_spirit::Value importprivkey(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getnetworkhashps(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getmininginfo(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getworkex(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getwork(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getblocktemplate(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value submitblock(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getnewaddress(const json_spirit::Array& params, bool fHelp); // in rpcwallet.cpp
extern json_spirit::Value getaccountaddress(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value setaccount(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getaccount(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getaddressesbyaccount(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value sendtoaddress(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value signmessage(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value verifymessage(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getreceivedbyaddress(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getreceivedbyaccount(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getbalance(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value movecmd(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value sendfrom(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value sendmany(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value addmultisigaddress(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value createmultisig(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value listreceivedbyaddress(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value listreceivedbyaccount(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value listtransactions(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value listaddressgroupings(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value listaccounts(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value listsinceblock(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value gettransaction(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value backupwallet(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value keypoolrefill(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value walletpassphrase(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value walletpassphrasechange(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value walletlock(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value encryptwallet(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value validateaddress(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getinfo(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getrawtransaction(const json_spirit::Array& params, bool fHelp); // in rcprawtransaction.cpp
extern json_spirit::Value listunspent(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value lockunspent(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value listlockunspent(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value createrawtransaction(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value decoderawtransaction(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value signrawtransaction(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value sendrawtransaction(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value makekeypair(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getblockcount(const json_spirit::Array& params, bool fHelp); // in rpcblockchain.cpp
extern json_spirit::Value getdifficulty(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value settxfee(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value setmininput(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getrawmempool(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getblockhash(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getblock(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value gettxoutsetinfo(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value gettxout(const json_spirit::Array& params, bool fHelp);
#endif
|
orkacoin/orkacoin
|
src/bitcoinrpc.h
|
C
|
mit
| 11,085
|
using System.Collections.Generic;
using System.Web.Http;
using HaloOnline.Server.Core.Http.Interface.Services;
using HaloOnline.Server.Core.Http.Model;
using HaloOnline.Server.Core.Http.Model.Heartbeat;
using HaloOnline.Server.Model.Heartbeat;
namespace HaloOnline.Server.Core.Http.Controllers
{
public class HeartbeatController : ApiController, IHeartbeatService
{
[HttpPost]
public GetServicesStatusResult GetServicesStatus(GetServicesStatusRequest request)
{
return new GetServicesStatusResult
{
Result = new ServiceResult<List<HeartbeatStatusContract>>
{
ReturnCode = 0,
Data = new List<HeartbeatStatusContract>
{
new HeartbeatStatusContract
{
Name = "UserService",
Quality = 0,
Status = 0
},
new HeartbeatStatusContract
{
Name = "MessagingService",
Quality = 0,
Status = 0
},
new HeartbeatStatusContract
{
Name = "SessionControlService",
Quality = 0,
Status = 0
},
new HeartbeatStatusContract
{
Name = "PresenceService",
Quality = 0,
Status = 0
},
new HeartbeatStatusContract
{
Name = "GameStatisticsService",
Quality = 0,
Status = 0
}
}
}
};
}
}
}
|
Atvaark/Emurado
|
HaloOnline.Server.Core.Http/Controllers/HeartbeatController.cs
|
C#
|
mit
| 2,046
|
The MIT License (MIT)
Copyright (c) 2017 Jack Lam <jacklam718@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.
|
jacklam718/react-native-carousel-component
|
LICENSE.md
|
Markdown
|
mit
| 1,098
|
require 'spec_helper'
module Capybara::Poltergeist
describe Driver do
context 'with no options' do
subject { Driver.new(nil) }
it 'does not log' do
expect(subject.logger).to be_nil
end
it 'has no inspector' do
expect(subject.inspector).to be_nil
end
end
context 'with a :logger option' do
subject { Driver.new(nil, :logger => :my_custom_logger) }
it 'logs to the logger given' do
expect(subject.logger).to eq(:my_custom_logger)
end
end
context 'with a :phantomjs_logger option' do
subject { Driver.new(nil, :phantomjs_logger => :my_custom_logger) }
it 'logs to the phantomjs_logger given' do
expect(subject.phantomjs_logger).to eq(:my_custom_logger)
end
end
context 'with a :debug => true option' do
subject { Driver.new(nil, :debug => true) }
it 'logs to STDERR' do
expect(subject.logger).to eq(STDERR)
end
end
context 'with an :inspector option' do
subject { Driver.new(nil, :inspector => 'foo') }
it 'has an inspector' do
expect(subject.inspector).to_not be_nil
expect(subject.inspector).to be_a(Inspector)
expect(subject.inspector.browser).to eq('foo')
end
end
context 'with a :timeout option' do
subject { Driver.new(nil, :timeout => 3) }
it 'starts the server with the provided timeout' do
server = double
Server.should_receive(:new).with(anything, 3).and_return(server)
expect(subject.server).to eq(server)
end
end
context 'with a :window_size option' do
subject { Driver.new(nil, :window_size => [800, 600]) }
it "creates a client with the desired width and height settings" do
server = double
Server.should_receive(:new).and_return(server)
Client.should_receive(:start).with(server, hash_including(:window_size => [800, 600]))
subject.client
end
end
end
end
|
farmersweb/poltergeist
|
spec/unit/driver_spec.rb
|
Ruby
|
mit
| 2,001
|
---
title: 'Отворање На Првиот Печат'
date: 27/01/2019
---
`Прочитајте ги следните текстови: Откровение 6,1-8; 3. Мојсеева 26,21-26; Матеј 24,1-14. Забележете ги заедничките клучни зборови во овие текстови. Што дознавате за значењето на првите четири печати врз основа на тие поклопувања?`
Настаните од седумте печати мора да се сфатат во рамките на заветните клетви од Стариот завет во кој се споменуваат изразите меч, глад, помор и диви ѕверови (3. Мојсеева 26,21-26). Езекиел ги нарекува Божји „четири тешки казни“ (Езекиел 14,21). Тоа биле дисциплински судови во кои Бог го опоменувал својот народ кога му биле неверни на заветот, настојувајќи да ги разбуди за да ја увидат својата духовна состојба. На сличен начин, четирите коњаници претставуваат средство кое Бог го користи за да го одржи буден својот народ додека го чека Исусовото враќање.
Исто така, постојат големи сличности меѓу првите четири печати и текстот од Матеј 24,4-14, во кој Исус објаснил што ќе се случува во светот. Четирите коњаници Бог ги користи за да го задржи својот народ на вистинскиот пат, потсетувајќи ги дека овој свет, каков што е сега, не е нивниот дом.
Иако симболичен, текстот од Откровение 6,1.2 исто така зборува за победата. Нё потсетува на текстот од Откровение 19,11-16, во кој Христос е прикажан како јава на бел коњ и ги води своите војски од ангели да го ослободат Неговиот народ при Второто доаѓање. Како симбол за чистота, белата боја постојано се поврзува со Христа и Неговите следбеници. Јавачот во раката држи стрела и добива венец (Откровение 6,2), што потсетува на сликата на Бога во Стариот завет, кој јава коњ со стрела во рацете додека ги победува непријателите на својот народ (Авакум 3,8-13; Псалм 45,4.5). Грчкиот збор за венец (Откровение 6,2) што го носи јавачот е *stephanos*, и значи венец на победата (Oткровение 2,10; Oткровение 3,11). Овој јавач е освојувач кој победува и оди напред за да победи.
Сцената од првиот печат го опишува ширењето на Евангелието, кое моќно започнало на денот Педесетница, со што Исус го започнал ширењето на своето Царство. Имало, а и сё уште има, уште многу области кои треба да се освојат и многу луѓе кои треба да станат Исусови следбеници, додека конечната победа не биде остварена кога Христос ќе дојде во слава.
Во пророчка смисла, глетката на првиот печат одговара на пораката упатена до црквата во Ефес; го опишува апостолскиот период во првиот век, кога Евангелието брзо се ширело низ светот (Колошаните 1,23).
`Зошто никогаш не смееме да заборавиме дека сме, во Христа, на победничката страна без оглед на моменталните околности?`
|
PrJared/sabbath-school-lessons
|
src/mk/2019-01/05/02.md
|
Markdown
|
mit
| 4,566
|
/*************************************************************\
* Triple.cpp *
* This file was created by Jeremy Greenburg *
* As part of The God Core game for the University of *
* Tennessee at Martin's University Scholars Organization *
* *
* This file contains the definition of the TwoD class *
* For more information, see Triple.h *
\*************************************************************/
#include "Triple.h"
Triple makeTrip(double _a, double _b, double _c)
{
Triple ret;
ret.a = _a;
ret.b = _b;
ret.c = _c;
return ret;
}
|
Airtamis/The-God-Core
|
The God Core/The God Core/Triple.cpp
|
C++
|
mit
| 709
|
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/marshal_data'
mv = [Marshal::MAJOR_VERSION].pack 'C'
nv = [Marshal::MINOR_VERSION].pack 'C'
class UserDefinedBad
def _dump(depth); 10; end
end
# TODO: these need to be reviewed and cleaned up
describe "Marshal.dump" do
it "raises an ArgumentError when the recursion limit is exceeded" do
lambda { Marshal.dump([], 1) }.should_not raise_error(ArgumentError)
lambda { Marshal.dump([[]], 2) }.should_not raise_error(ArgumentError)
lambda { Marshal.dump([[[]]], 3) }.should_not raise_error(ArgumentError)
h = {'one' => {'two' => {'three' => 0}}}
lambda { Marshal.dump(h, 3) }.should raise_error(ArgumentError)
lambda { Marshal.dump([h], 4) }.should raise_error(ArgumentError)
lambda { Marshal.dump({}, 1) }.should_not raise_error(ArgumentError)
lambda { Marshal.dump(h, 4) }.should_not raise_error(ArgumentError)
lambda { Marshal.dump([], 0) }.should raise_error(ArgumentError)
lambda { Marshal.dump([[[]]], 1) }.should raise_error(ArgumentError)
end
it "ignores the recursion limit if the limit is negative" do
Marshal.dump([], -1).should == "\004\b[\000"
Marshal.dump([[]], -1).should == "\004\b[\006[\000"
Marshal.dump([[[]]], -1).should == "\004\b[\006[\006[\000"
end
it "writes the serialized data to the IO-Object" do
(obj = mock('test')).should_receive(:write).at_least(1)
Marshal.dump("test", obj)
end
it "returns the IO-Object" do
(obj = mock('test')).should_receive(:write).at_least(1)
Marshal.dump("test", obj).should == obj
end
it "raises an Error when the IO-Object does not respond to #write" do
obj = mock('test')
lambda { Marshal.dump("test", obj) }.should raise_error(TypeError)
end
it "raises an ArgumentError when given more than three arguments" do
lambda { Marshal.dump(nil, nil, nil, nil) }.should raise_error(ArgumentError)
end
it "raises an Error when trying to dump an anonymous class/module" do
klass = Class.new
mod = Module.new
lambda { Marshal.dump(klass) }.should raise_error(TypeError)
lambda { Marshal.dump(mod) }.should raise_error(TypeError)
end
it "raises a TypeError if _dump returns a non-string" do
lambda { Marshal.dump(UserDefinedBad.new) }.should raise_error(TypeError)
end
it "dumps an Object" do
Marshal.dump(Object.new).should == "#{mv+nv}o:\x0BObject\x00"
end
it "dumps an extended_object" do
Marshal.dump(Object.new.extend(Meths)).should == "#{mv+nv}e:\x0AMethso:\x0BObject\x00"
end
ruby_version_is ""..."1.9" do
it "dumps an object having ivar" do
s = 'hi'
obj = Object.new
obj.instance_variable_set(:@str, [:so, :so, s, s])
Marshal.dump(obj).should == "#{mv+nv}o:\x0BObject\x06:\x09@str[\x09:\x07so;\x07\"\x07hi@\x07"
end
end
ruby_version_is "1.9" do
it "dumps an object having ivar" do
s = 'hi'
obj = Object.new
obj.instance_variable_set(:@str, [:so, :so, s, s])
Marshal.dump(obj).should ==
"#{mv+nv}o:\vObject\x06:\t@str[\t:\aso;\aI\"\ahi\x06:\x06EF@\a"
end
end
ruby_version_is ""..."1.9" do
it "dumps an extended_user_regexp having ivar" do
r = UserRegexp.new('').extend(Meths)
r.instance_variable_set(:@noise, 'much')
Marshal.dump(r).should == "#{mv+nv}Ie:\x0AMethsC:\x0FUserRegexp/\x00\x00\x06:\x0B@noise\"\x09much"
end
end
ruby_version_is "1.9" do
it "dumps an extended_user_regexp having ivar" do
r = UserRegexp.new('').extend(Meths)
r.instance_variable_set(:@noise, 'much')
Marshal.dump(r).should ==
"#{mv+nv}Ie:\nMethsC:\x0FUserRegexp/\x00\x00\a:\x06EF:\v@noiseI\"\tmuch\x06;\aF"
end
end
it "raises a TypeError with hash having default proc" do
lambda { Marshal.dump(Hash.new {}) }.should raise_error(TypeError)
end
it "raises a TypeError if marshalling a Method instance" do
lambda { Marshal.dump(Marshal.method(:dump)) }.should raise_error(TypeError)
end
it "raises a TypeError if marshalling a Proc" do
lambda { Marshal.dump(proc {}) }.should raise_error(TypeError)
end
it "raises a TypeError if dumping a IO/File instance" do
lambda { Marshal.dump(STDIN) }.should raise_error(TypeError)
lambda { File.open(__FILE__) { |f| Marshal.dump(f) } }.should raise_error(TypeError)
end
it "raises a TypeError if dumping a MatchData instance" do
lambda { "foo" =~ /(.)/; Marshal.dump($~) }.should raise_error(TypeError)
end
ruby_version_is ""..."1.9" do
it "dumps an extended_user_hash_default" do
h = UserHash.new(:Meths).extend(Meths)
h['three'] = 3
Marshal.dump(h).should == "#{mv+nv}e:\x0AMethsC:\x0DUserHash}\x06\"\x0Athreei\x08;\x00"
end
end
ruby_version_is "1.9" do
it "dumps an extended_user_hash_default" do
h = UserHash.new(:Meths).extend(Meths)
h['three'] = 3
Marshal.dump(h).should ==
"\x04\be:\nMethsC:\rUserHash}\x06I\"\nthree\x06:\x06EFi\b;\x00"
end
end
ruby_version_is ""..."1.9" do
it "dumps an extended_user_hash with a parameter to initialize" do
h = UserHashInitParams.new(:abc).extend(Meths)
h['three'] = 3
Marshal.dump(h).should == "\004\bIe:\nMethsC:\027UserHashInitParams{\006\"\nthreei\b\006:\a@a:\babc"
end
end
ruby_version_is "1.9" do
it "dumps an extended_user_hash with a parameter to initialize" do
h = UserHashInitParams.new(:abc).extend(Meths)
h['three'] = 3
Marshal.dump(h).should ==
"\x04\bIe:\nMethsC:\x17UserHashInitParams{\x06I\"\nthree\x06:\x06EFi\b\x06:\a@a:\babc"
end
end
ruby_version_is ""..."1.9" do
it "dumps an array containing objects having _dump method" do
o1 = UserDefined.new
o2 = UserDefinedWithIvar.new
a = [o1, o2, o1, o2]
Marshal.dump(a).should ==
"#{mv+nv}[\tu:\020UserDefined\022\004\b[\a\"\nstuff@\006u:\030UserDefinedWithIvar5\004\b[\bI\"\nstuff\006:\t@foo:\030UserDefinedWithIvar\"\tmore@\a@\006@\a"
end
end
ruby_version_is "1.9" do
it "dumps an array containing objects having _dump method" do
o1 = UserDefined.new
o2 = UserDefinedWithIvar.new
a = [o1, o2, o1, o2]
Marshal.dump(a).should ==
"#{mv+nv}[\tu:\x10UserDefined\x18\x04\b[\aI\"\nstuff\x06:\x06EF@\x06u:\x18UserDefinedWithIvar>\x04\b[\bI\"\nstuff\a:\x06EF:\t@foo:\x18UserDefinedWithIvarI\"\tmore\x06;\x00F@\a@\x06@\a"
end
end
ruby_version_is ""..."1.9" do
it "dumps an array containing objects having marshal_dump method" do
o1 = UserMarshal.new
o2 = UserMarshalWithIvar.new
a = [o1, o2, o1, o2]
Marshal.dump(a).should ==
"#{mv+nv}[\tU:\020UserMarshal\"\nstuffU:\030UserMarshalWithIvar[\006\"\fmy data@\006@\b"
end
end
ruby_version_is "1.9" do
it "dumps an array containing objects having marshal_dump method" do
o1 = UserMarshal.new
o2 = UserMarshalWithIvar.new
a = [o1, o2, o1, o2]
Marshal.dump(a).should ==
"#{mv+nv}[\tU:\x10UserMarshalI\"\nstuff\x06:\x06EFU:\x18UserMarshalWithIvar[\x06I\"\fmy data\x06;\x06F@\x06@\b"
end
end
ruby_version_is ""..."1.9" do
it "dumps an array containing the same objects" do
s = 'oh'; b = 'hi'; r = //; d = [b, :no, s, :go]; c = String
a = [:so, 'hello', 100, :so, :so, d, :so, :so, :no, :go, c, nil,
:go, :no, s, b, r, :so, 'huh', true, b, b, 99, r, b, s, :so, c, :no, d]
Marshal.dump(a).should ==
"#{mv+nv}[\x23:\x07so\"\x0Ahelloi\x69;\x00;\x00[\x09\"\x07hi:\x07no\"\x07oh:\x07go;\x00;\x00;\x06;\x07c\x0BString0;\x07;\x06@\x09@\x08/\x00\x00;\x00\"\x08huhT@\x08@\x08i\x68@\x0B@\x08@\x09;\x00@\x0A;\x06@\x07"
end
end
ruby_version_is "1.9" do
it "dumps an array containing the same objects" do
s = 'oh'; b = 'hi'; r = //; d = [b, :no, s, :go]; c = String
a = [:so, 'hello', 100, :so, :so, d, :so, :so, :no, :go, c, nil,
:go, :no, s, b, r, :so, 'huh', true, b, b, 99, r, b, s, :so, c, :no, d]
Marshal.dump(a).should ==
"#{mv+nv}[#:\asoI\"\nhello\x06:\x06EFii;\x00;\x00[\tI\"\ahi\x06;\x06F:\anoI\"\aoh\x06;\x06F:\ago;\x00;\x00;\a;\bc\vString0;\b;\a@\t@\bI/\x00\x00\x06;\x06F;\x00I\"\bhuh\x06;\x06FT@\b@\bih@\v@\b@\t;\x00@\n;\a@\a"
end
end
ruby_version_is ""..."1.9" do
it "dumps an extended_array having ivar" do
s = 'well'
s.instance_variable_set(:@foo, 10)
a = ['5', s, 'hi'].extend(Meths, MethsMore)
a.instance_variable_set(:@mix, s)
Marshal.dump(a).should ==
"#{mv+nv}Ie:\x0AMethse:\x0EMethsMore[\x08\"\x065I\"\x09well\x06:\x09@fooi\x0F\"\x07hi\x06:\x09@mix@\x07"
end
end
ruby_version_is "1.9" do
it "dumps an extended_array having ivar" do
s = 'well'
s.instance_variable_set(:@foo, 10)
a = ['5', s, 'hi'].extend(Meths, MethsMore)
a.instance_variable_set(:@mix, s)
Marshal.dump(a).should ==
"#{mv+nv}Ie:\nMethse:\x0EMethsMore[\bI\"\x065\x06:\x06EFI\"\twell\a;\aF:\t@fooi\x0FI\"\ahi\x06;\aF\x06:\t@mix@\a"
end
end
it "dumps a struct having ivar" do
st = Struct.new("Thick").new
st.instance_variable_set(:@foo, 5)
Marshal.dump(st).should == "#{mv+nv}IS:\x12Struct::Thick\x00\x06:\x09@fooi\x0A"
end
it "dumps a struct having fields" do
Marshal.dump(Struct.new("Ure1", :a, :b).new).should == "#{mv+nv}S:\x11Struct::Ure1\x07:\x06a0:\x06b0"
end
ruby_version_is ""..."1.9" do
it "dumps an extended_struct having fields with same objects" do
s = 'hi'
st = Struct.new("Ure2", :a, :b).new.extend(Meths)
st.a = [:a, s]; st.b = [:Meths, s]
Marshal.dump(st).should ==
"#{mv+nv}e:\x0AMethsS:\x11Struct::Ure2\x07:\x06a[\x07;\x07\"\x07hi:\x06b[\x07;\x00@\x07"
end
end
ruby_version_is "1.9" do
it "dumps an extended_struct having fields with same objects" do
s = 'hi'
st = Struct.new("Ure2", :a, :b).new.extend(Meths)
st.a = [:a, s]; st.b = [:Meths, s]
Marshal.dump(st).should ==
"#{mv+nv}e:\nMethsS:\x11Struct::Ure2\a:\x06a[\a;\aI\"\ahi\x06:\x06EF:\x06b[\a;\x00@\a"
end
end
end
describe "Marshal.dump" do
ruby_version_is ""..."1.9" do
MarshalSpec::DATA.each do |description, (object, marshal, attributes)|
it "dumps a #{description}" do
unless attributes then
Marshal.dump(object).should == marshal
else
# these objects have non-deterministic field order in the
# marshal stream, so they need a round trip and independent
# verification.
object = Marshal.load(Marshal.dump(object))
attributes.each do |attr, val|
object.send(attr).should == val
end
end
end
end
end
ruby_version_is "1.9" do
MarshalSpec::DATA_19.each do |description, (object, marshal, attributes)|
it "dumps a #{description}" do
unless attributes then
Marshal.dump(object).should == marshal
else
# these objects have non-deterministic field order in the
# marshal stream, so they need a round trip and independent
# verification.
object = Marshal.load(Marshal.dump(object))
attributes.each do |attr, val|
object.send(attr).should == val
end
end
end
end
end
end
|
mattetti/rubyspec
|
core/marshal/dump_spec.rb
|
Ruby
|
mit
| 11,387
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// HyperVReplicaAzure specific planned failover input.
/// </summary>
[Newtonsoft.Json.JsonObject("HyperVReplicaAzure")]
public partial class HyperVReplicaAzurePlannedFailoverProviderInput : PlannedFailoverProviderSpecificFailoverInput
{
/// <summary>
/// Initializes a new instance of the
/// HyperVReplicaAzurePlannedFailoverProviderInput class.
/// </summary>
public HyperVReplicaAzurePlannedFailoverProviderInput()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// HyperVReplicaAzurePlannedFailoverProviderInput class.
/// </summary>
/// <param name="primaryKekCertificatePfx">Primary kek certificate
/// pfx.</param>
/// <param name="secondaryKekCertificatePfx">Secondary kek certificate
/// pfx.</param>
/// <param name="recoveryPointId">The recovery point id to be passed to
/// failover to a particular recovery point. In case of latest recovery
/// point, null should be passed.</param>
public HyperVReplicaAzurePlannedFailoverProviderInput(string primaryKekCertificatePfx = default(string), string secondaryKekCertificatePfx = default(string), string recoveryPointId = default(string))
{
PrimaryKekCertificatePfx = primaryKekCertificatePfx;
SecondaryKekCertificatePfx = secondaryKekCertificatePfx;
RecoveryPointId = recoveryPointId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets primary kek certificate pfx.
/// </summary>
[JsonProperty(PropertyName = "primaryKekCertificatePfx")]
public string PrimaryKekCertificatePfx { get; set; }
/// <summary>
/// Gets or sets secondary kek certificate pfx.
/// </summary>
[JsonProperty(PropertyName = "secondaryKekCertificatePfx")]
public string SecondaryKekCertificatePfx { get; set; }
/// <summary>
/// Gets or sets the recovery point id to be passed to failover to a
/// particular recovery point. In case of latest recovery point, null
/// should be passed.
/// </summary>
[JsonProperty(PropertyName = "recoveryPointId")]
public string RecoveryPointId { get; set; }
}
}
|
jackmagic313/azure-sdk-for-net
|
sdk/recoveryservices-siterecovery/Microsoft.Azure.Management.RecoveryServices.SiteRecovery/src/Generated/Models/HyperVReplicaAzurePlannedFailoverProviderInput.cs
|
C#
|
mit
| 3,012
|
<?php
return [
'issue-1776-A' => [
'ua' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3) AppleWebKit/534.31 (KHTML, like Gecko) Chrome/17.0.558.0 Safari/534.31 UCBrowser/2.2.2.259',
'properties' => [
'Comment' => 'UC Browser 2.2 for Android',
'Browser' => 'UC Browser',
'Browser_Type' => 'Browser',
'Browser_Bits' => '32',
'Browser_Maker' => 'UCWeb Inc.',
'Browser_Modus' => 'Desktop Mode',
'Version' => '2.2',
'Platform' => 'Android',
'Platform_Version' => 'unknown',
'Platform_Description' => 'Android OS',
'Platform_Bits' => '32',
'Platform_Maker' => 'Google Inc',
'Alpha' => false,
'Beta' => false,
'Frames' => true,
'IFrames' => true,
'Tables' => true,
'Cookies' => true,
'JavaScript' => true,
'VBScript' => false,
'JavaApplets' => true,
'isSyndicationReader' => false,
'isFake' => false,
'isAnonymized' => false,
'isModified' => false,
'CssVersion' => '3',
'Device_Name' => 'general Mobile Phone',
'Device_Maker' => 'unknown',
'Device_Type' => 'Mobile Phone',
'Device_Pointing_Method' => 'touchscreen',
'Device_Code_Name' => 'general Mobile Phone',
'Device_Brand_Name' => 'unknown',
'RenderingEngine_Name' => 'WebKit',
'RenderingEngine_Version' => 'unknown',
'RenderingEngine_Maker' => 'Apple Inc',
],
'lite' => false,
'standard' => true,
'full' => true,
],
];
|
mimmi20/browscap
|
tests/issues/issue-1776.php
|
PHP
|
mit
| 1,749
|
package openblocks.client.renderer.item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.client.IItemRenderer;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import openblocks.client.renderer.block.BlockTankRenderer;
import openblocks.client.renderer.tileentity.TileEntityTankRenderer;
import openblocks.client.renderer.tileentity.tank.ITankRenderFluidData;
import openblocks.common.tileentity.TileEntityTank;
import openmods.utils.Diagonal;
import org.lwjgl.opengl.GL11;
public class ItemRendererTank implements IItemRenderer {
private FluidTank tank = new FluidTank(TileEntityTank.getTankCapacity());
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type) {
return true;
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
return true;
}
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
GL11.glPushMatrix();
if (type == ItemRenderType.ENTITY) GL11.glTranslated(-0.5, -0.5, -0.5);
else if (type == ItemRenderType.INVENTORY) GL11.glTranslated(0, -0.1, 0);
BlockTankRenderer.EMPTY_FRAME.render();
NBTTagCompound tag = item.getTagCompound();
if (tag != null && tag.hasKey("tank")) {
final FluidStack stack = readFluid(tag);
if (stack != null) {
final float height = (float)tank.getFluidAmount() / tank.getCapacity();
TileEntityTankRenderer.renderFluid(new ITankRenderFluidData() {
@Override
public boolean shouldRenderFluidWall(ForgeDirection side) {
return true;
}
@Override
public boolean hasFluid() {
return true;
}
@Override
public FluidStack getFluid() {
return stack;
}
@Override
public float getCornerFluidLevel(Diagonal diagonal, float time) {
return height;
}
@Override
public float getCenterFluidLevel(float time) {
return height;
}
}, 0);
}
}
GL11.glPopMatrix();
}
private FluidStack readFluid(NBTTagCompound tag) {
synchronized (tank) {
tank.setFluid(null);
tank.readFromNBT(tag.getCompoundTag("tank"));
return tank.getFluid();
}
}
}
|
PrinceOfAmber/OpenBlocks
|
src/main/java/openblocks/client/renderer/item/ItemRendererTank.java
|
Java
|
mit
| 2,308
|
' 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
Imports System.Reflection
Public Module Extensions_826
''' <summary>
''' A T extension method that gets property value.
''' </summary>
''' <typeparam name="T">Generic type parameter.</typeparam>
''' <param name="this">The @this to act on.</param>
''' <param name="propertyName">Name of the property.</param>
''' <returns>The property value.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function GetPropertyValue(Of T)(this As T, propertyName As String) As Object
Dim type As Type = this.[GetType]()
Dim [property] As PropertyInfo = type.GetProperty(propertyName, BindingFlags.[Public] Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.[Static])
Return [property].GetValue(this, Nothing)
End Function
End Module
|
zzzprojects/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Reflection/System.Object/Object.GetPropertyValue.vb
|
Visual Basic
|
mit
| 1,151
|
package org.beansugar.oauth.services.signature;
import org.beansugar.oauth.exceptions.OAuthException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class HMACSha1SignatureServiceTest {
private HMACSha1SignatureService service;
@Before
public void setup() {
service = new HMACSha1SignatureService();
}
@Test
public void shouldReturnSignatureMethodString() {
String expected = "HMAC-SHA1";
assertEquals(expected, service.getSignatureMethod());
}
@Test
public void shouldReturnSignature() {
String apiSecret = "api secret";
String tokenSecret = "token secret";
String baseString = "base string";
String signature = "uGymw2KHOTWI699YEaoi5xyLT50=";
assertEquals(signature, service.getSignature(baseString, apiSecret, tokenSecret));
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfBaseStringIsNull() {
service.getSignature(null, "apiSecret", "tokenSecret");
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfBaseStringIsEmpty() {
service.getSignature(" ", "apiSecret", "tokenSecret");
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfApiSecretIsNull() {
service.getSignature("base string", null, "tokenSecret");
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfApiSecretIsEmpty() {
service.getSignature("base string", " ", "tokenSecret");
}
}
|
archmagece/bs-oauth-java
|
src/test/java/org/beansugar/oauth/services/signature/HMACSha1SignatureServiceTest.java
|
Java
|
mit
| 1,454
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
/**
* @class
* Initializes a new instance of the AvailabilitySetUpdateParameters class.
* @constructor
* @member {object} tags A set of tags. A description about the set of tags.
*
*/
export interface AvailabilitySetUpdateParameters {
tags: { [propertyName: string]: string };
}
|
yugangw-msft/autorest
|
src/generator/AutoRest.NodeJS.Tests/Expected/AcceptanceTests/ParameterFlattening/models/index.d.ts
|
TypeScript
|
mit
| 607
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="index, follow, all" />
<title>Thelia\Core\Security\User\UserInterface | Thelia 2 API</title>
<link rel="stylesheet" type="text/css" href="../../../../css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../../../../css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="../../../../css/sami.css">
<script src="../../../../js/jquery-1.11.1.min.js"></script>
<script src="../../../../js/bootstrap.min.js"></script>
<script src="../../../../js/typeahead.min.js"></script>
<script src="../../../../sami.js"></script>
<meta name="MobileOptimized" content="width">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
</head>
<body id="class" data-name="class:Thelia_Core_Security_User_UserInterface" data-root-path="../../../../">
<div id="content">
<div id="left-column">
<div id="control-panel">
<form id="search-form" action="../../../../search.html" method="GET">
<span class="glyphicon glyphicon-search"></span>
<input name="search"
class="typeahead form-control"
type="search"
placeholder="Search">
</form>
</div>
<div id="api-tree"></div>
</div>
<div id="right-column">
<nav id="site-nav" class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../../index.html">Thelia 2 API</a>
</div>
<div class="collapse navbar-collapse" id="navbar-elements">
<ul class="nav navbar-nav">
<li><a href="../../../../classes.html">Classes</a></li>
<li><a href="../../../../namespaces.html">Namespaces</a></li>
<li><a href="../../../../interfaces.html">Interfaces</a></li>
<li><a href="../../../../traits.html">Traits</a></li>
<li><a href="../../../../doc-index.html">Index</a></li>
<li><a href="../../../../search.html">Search</a></li>
</ul>
</div>
</div>
</nav>
<div class="namespace-breadcrumbs">
<ol class="breadcrumb">
<li><span class="label label-default">interface</span></li>
<li><a href="../../../../Thelia.html">Thelia</a></li>
<li><a href="../../../../Thelia/Core.html">Core</a></li>
<li><a href="../../../../Thelia/Core/Security.html">Security</a></li>
<li><a href="../../../../Thelia/Core/Security/User.html">User</a></li>
<li>UserInterface</li>
</ol>
</div>
<div id="page-content">
<div class="page-header">
<h1>UserInterface</h1>
</div>
<p> interface
<strong>UserInterface</strong>
</p>
<div class="description">
<p>This interface should be implemented by user classes</p> </div>
<h2>Methods</h2>
<div class="container-fluid underlined">
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_getUsername">getUsername</a>()
<p>Return the user unique name</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_getPassword">getPassword</a>()
<p>Return the user encoded password</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_checkPassword">checkPassword</a>($password)
<p>Check a string against a the user password</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Thelia\Core\Security\User\Role">Role</abbr>[]
</div>
<div class="col-md-8 type">
<a href="#method_getRoles">getRoles</a>()
<p>Returns the roles granted to the user.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_eraseCredentials">eraseCredentials</a>()
<p>Removes sensitive data from the user.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_getToken">getToken</a>()
<p>return the user token (used by remember me authnetication system)</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_setToken">setToken</a>($token)
<p>Set a token in the user data (used by remember me authnetication system)</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_getSerial">getSerial</a>()
<p>return the user serial (used by remember me authnetication system)</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_setSerial">setSerial</a>($serial)
<p>Set a serial number int the user data (used by remember me authnetication system)</p> </div>
<div class="col-md-2"></div>
</div>
</div>
<h2>Details</h2>
<div id="method-details">
<div class="method-item">
<h3 id="method_getUsername">
<div class="location">at line 26</div>
<code>
<strong>getUsername</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Return the user unique name</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getPassword">
<div class="location">at line 31</div>
<code>
<strong>getPassword</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Return the user encoded password</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_checkPassword">
<div class="location">at line 36</div>
<code>
<strong>checkPassword</strong>($password)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Check a string against a the user password</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$password</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getRoles">
<div class="location">at line 50</div>
<code>
<abbr title="Thelia\Core\Security\User\Role">Role</abbr>[]
<strong>getRoles</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Returns the roles granted to the user.</p> <p><code>
public function getRoles()
{
return array('USER');
}
</code></p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Core\Security\User\Role">Role</abbr>[]</td>
<td>The user roles</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_eraseCredentials">
<div class="location">at line 60</div>
<code>
void
<strong>eraseCredentials</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Removes sensitive data from the user.</p> <p>This is important if, at any given point, sensitive information like
the plain-text password is stored on this object.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getToken">
<div class="location">at line 65</div>
<code>
<strong>getToken</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>return the user token (used by remember me authnetication system)</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setToken">
<div class="location">at line 70</div>
<code>
<strong>setToken</strong>($token)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set a token in the user data (used by remember me authnetication system)</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$token</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getSerial">
<div class="location">at line 75</div>
<code>
<strong>getSerial</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>return the user serial (used by remember me authnetication system)</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setSerial">
<div class="location">at line 80</div>
<code>
<strong>setSerial</strong>($serial)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set a serial number int the user data (used by remember me authnetication system)</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$serial</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://sami.sensiolabs.org/">Sami, the API Documentation Generator</a>.
</div>
</div>
</div>
</body>
</html>
|
sitecrafting/thelia.github.io
|
api/2.0/Thelia/Core/Security/User/UserInterface.html
|
HTML
|
mit
| 15,020
|
maintainer "Opscode, Inc."
maintainer_email "cookbooks@opscode.com"
license "Apache 2.0"
description "Installs sudo and configures /etc/sudoers"
version "1.1.0"
recipe "sudo", "Installs sudo and configures /etc/sudoers"
%w{redhat centos fedora ubuntu debian freebsd}.each do |os|
supports os
end
attribute "authorization",
:display_name => "Authorization",
:description => "Hash of Authorization attributes",
:type => "hash"
attribute "authorization/sudoers",
:display_name => "Authorization Sudoers",
:description => "Hash of Authorization/Sudoers attributes",
:type => "hash"
attribute "authorization/sudoers/users",
:display_name => "Sudo Users",
:description => "Users who are allowed sudo ALL",
:type => "array",
:default => ""
attribute "authorization/sudoers/groups",
:display_name => "Sudo Groups",
:description => "Groups who are allowed sudo ALL",
:type => "array",
:default => ""
attribute "authorization/sudoers/passwordless",
:display_name => "Passwordless Sudo",
:description => "",
:type => "string",
:default => "false"
|
mehulsbhatt/smartvpn-billing
|
cookbooks/chef-sudo/metadata.rb
|
Ruby
|
mit
| 1,115
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
#region Namespaces
using System;
using System.ComponentModel.Composition;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
#endregion
/// <summary>
/// Class of extension rule for Minimal.Conformance.1001
/// </summary>
[Export(typeof(ExtensionRule))]
public class MinimalConformance1001 : ConformanceMinimalExtensionRule
{
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Minimal.Conformance.1001";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "1. MUST publish a service document at the service root (section 11.1.1)";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string V4SpecificationSection
{
get
{
return "13.1.1";
}
}
/// <summary>
/// Verifies the extension rule.
/// </summary>
/// <param name="context">The Interop service context</param>
/// <param name="info">out parameter to return violation information when rule does not pass</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
var response = WebHelper.Get(context.Destination, string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
ExtensionRuleResultDetail detail = new ExtensionRuleResultDetail(this.Name, context.Destination.AbsoluteUri, "GET", StringHelper.MergeHeaders(string.Empty, context.RequestHeaders), response);
if (response != null && response.StatusCode != null)
{
var payloadFormat = response.ResponsePayload.GetFormatFromPayload();
var payloadType = response.ResponsePayload.GetTypeFromPayload(payloadFormat);
if (payloadType == RuleEngine.PayloadType.ServiceDoc)
{
passed = true;
}
else
{
passed = false;
detail.ErrorMessage = "The response is not service document.";
}
}
else
{
passed = false;
detail.ErrorMessage = String.Format("No response returned from above URI.");
}
info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail);
return passed;
}
}
}
|
congysu/ValidationTool
|
src/CodeRules/Conformance/MinimalConformance1001.cs
|
C#
|
mit
| 3,354
|
'use strict';
/**
* Mounts a folder in a connect server
*/
module.exports = function mountFolder(connect, dir) {
return connect.static(require('path').resolve(dir));
};
|
carlosrubio/TimeWatcher
|
tasks/grunt-helpers/mount-folder.js
|
JavaScript
|
mit
| 176
|
$(function () {
var form = $('#search');
var input = form.find('input');
var list = form.find('.results');
var items = list.find('a');
var selected = null;
// Don't submit on return.
form.on('submit', function () {
return false;
});
// Open search
input.on('focus', function () {
form.addClass('open');
});
// Close search.
$(window).click(function () {
form.removeClass('open');
});
form.click(function (e) {
e.stopPropagation();
});
// Handle simple searching
input.on('keydown', function (e) {
/**
* Capture the down arrow.
*/
if (e.which == 40) {
if (selected) {
/**
* If we have a selection then
* push to the next visible option.
*/
if (selected.nextAll('a:visible').length) {
items.removeClass('active');
selected = selected.nextAll('a:visible').first();
selected.addClass('active');
}
} else {
/**
* Otherwise select the first
* visible option in the list.
*/
selected = items.filter('a:visible').first();
selected.addClass('active');
}
}
/**
* Capture the up arrow.
*/
if (e.which == 38) {
if (selected) {
/**
* If we have a selection then push
* to the previous visible option.
*/
if (selected.prevAll('a:visible').length) {
items.removeClass('active');
selected = selected.prevAll('a:visible').first();
selected.addClass('active');
}
} else {
/**
* Otherwise select the last
* visible option in the list.
*/
selected = items.filter('a:visible').last();
selected.addClass('active');
}
}
/**
* Capture the enter key.
*/
if (e.which == 13) {
if (selected) {
/**
* If the key press was the return
* key and we have a selection
* then follow the link.
*/
if (selected.hasClass('has-click-event') || selected.hasClass('ajax')) {
selected.trigger('click');
} else {
/**
* If nothing is selected
* there's nothing to do.
*/
if (!selected.length) {
return false;
}
/**
* If control or the meta key is
* being held open a new window.
*/
if (e.ctrlKey || e.metaKey) {
window.open(selected.attr('href'), "_blank");
} else {
window.location = selected.attr('href');
}
input.val('');
input.blur();
form.removeClass('open');
modal.find('.modal-content').append('<div class="modal-loading"><div class="active large loader"></div></div>');
}
}
}
/**
* Capture up and down arrows.
*/
if (e.which == 38 || e.which == 40) {
// store current positions in variables
var start = input[0].selectionStart,
end = input[0].selectionEnd;
// restore from variables...
input[0].setSelectionRange(start, end);
e.preventDefault();
}
/**
* Capture the escape key.
*/
if (e.which == 27) {
form.removeClass('open');
items
.show()
.removeClass('active');
input.val('').blur();
}
});
input.on('keyup', function (e) {
/**
* If the keyup was a an arrow
* up or down then skip this step.
*/
if (e.which == 38 || e.which == 40) {
return;
}
var value = $(this).val();
/**
* Filter the list by the items to
* show only those containing value.
*/
items.each(function () {
if ($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) {
$(this).show();
} else {
$(this).hide();
}
});
/**
* If we don't have a selected item
* then choose the first visible option.
*/
if (!selected || !selected.is(':visible')) {
selected = items.filter(':visible').first();
selected.addClass('active');
}
});
});
|
pyrocms/accelerant-theme
|
resources/js/theme/search.js
|
JavaScript
|
mit
| 5,118
|
/*
* ASIListener.java
*
* Created on February 27, 2003, 11:44 AM
*/
package cern.laser.source.alarmsysteminterface.listener;
import java.sql.Timestamp;
import java.util.Collection;
/**
* ASIMessage listener interface.
* @author fracalde
*/
public interface ASIListener {
/**
* Callback method. Called on ASIMessage reception.
* @param source the alarm source pushing the fault states.
* @param sourceHostname the alarm source host name.
* @param sourceTimestamp the alarm source timestamp (ISO fromat)
* @param backup true iff the message is a backup.
* @param states the actual fault states collection.
*/
public void onMessage(String source, String sourceHostname, String sourceTimestamp, boolean backup, Collection states);
}
|
csrg-utfsm/acscb
|
LGPL/CommonSoftware/ACSLaser/laser-source/src/cern/laser/source/alarmsysteminterface/listener/ASIListener.java
|
Java
|
mit
| 783
|
package com.lukaspili.mortardemo.flow;
import android.view.View;
import android.view.ViewTreeObserver;
final class FlowUtils {
public interface OnMeasuredCallback {
void onMeasured(View view, int width, int height);
}
public static void waitForMeasure(final View view, final OnMeasuredCallback callback) {
int width = view.getWidth();
int height = view.getHeight();
if (width > 0 && height > 0) {
callback.onMeasured(view, width, height);
return;
}
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
final ViewTreeObserver observer = view.getViewTreeObserver();
if (observer.isAlive()) {
observer.removeOnPreDrawListener(this);
}
callback.onMeasured(view, view.getWidth(), view.getHeight());
return true;
}
});
}
private FlowUtils() {
}
}
|
creativepsyco/Mortar-Flow-Dagger2-demo
|
app/src/main/java/com/lukaspili/mortardemo/flow/FlowUtils.java
|
Java
|
mit
| 1,066
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.