repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
DennisWandschura/vxEngine | source/vxEngine/ConditionPlayerMoving.cpp | 627 | #include "ConditionPlayerMoving.h"
#include "Entity.h"
ConditionPlayerMoving::ConditionPlayerMoving(EntityHuman* human)
:m_human(human)
{
}
ConditionPlayerMoving::~ConditionPlayerMoving()
{
}
u8 ConditionPlayerMoving::test() const
{
auto cmp = m_human->m_state & (1 << (u32)EntityHuman::State::Walking);
return (cmp != 0);
}
ConditionPlayerNotMoving::ConditionPlayerNotMoving(EntityHuman* human)
:m_human(human)
{
}
ConditionPlayerNotMoving::~ConditionPlayerNotMoving()
{
}
u8 ConditionPlayerNotMoving::test() const
{
auto cmp = m_human->m_state & (1 << (u32)EntityHuman::State::Walking);
return (cmp == 0);
} | mit |
r3d83ard/assemblyline_daily_sample | api/vti_api.py | 11458 | import os
import requests
class VTI_API:
a_vti_api_key = ''
a_api_scan_file = 'https://www.virustotal.com/vtapi/v2/file/scan'
a_api_scan_large_file = 'https://www.virustotal.com/vtapi/v2/file/scan/upload_url'
a_api_md5_report = 'https://www.virustotal.com/vtapi/v2/file/report'
a_api_md5_behaviour = 'https://www.virustotal.com/vtapi/v2/file/behaviour'
a_api_md5_pcap = 'https://www.virustotal.com/vtapi/v2/file/network-traffic'
a_api_search = 'https://www.virustotal.com/vtapi/v2/file/search'
a_api_clusters = 'https://www.virustotal.com/vtapi/v2/file/clusters'
a_api_md5_download = 'https://www.virustotal.com/vtapi/v2/file/download'
a_api_fp_report = 'https://www.virustotal.com/vtapi/v2/file/false-positives'
def __init__(self):
try:
logger_util.setup_logger('master_logger', 'master.log', logging.INFO)
logger_util.setup_logger('api_logger', 'api.log', logging.INFO)
self.master_logger = logging.getLogger('master_logger')
self.api_logger = logging.getLogger('api_logger')
self.api_logger.debug('Getting environment variable $%s', 'MALSHR_API_KEY')
self.a_vti_api_key = os.environ['VTI_API_KEY']
self.api_logger.debug('Successfully found api key')
except:
self.master_logger.error('Environment variable $%s does not exist', 'MALSHR_API_KEY')
self.api_logger.error('Environment variable $%s does not exist', 'MALSHR_API_KEY')
raise
def m_api_scan_file(self, file_location):
"""
Description:
------------
POST /vtapi/v2/file/scan. Upload a file for scanning with VirusTotal. File must be smaller than 32MB
Parameters:
-----------
string : file_handle
path to file to be uploaded
Returns:
--------
json object
response contains scan_id to access report and other info
"""
try:
params = {'apikey':self.a_malshare_api_key}
files = {'file': (file_location, open(file_location, 'rb'))}
response = requests.post(self.a_api_scan_file, files=files, params=params)
return response.json()
except requests.exceptions.RequestException as e:
print "ERROR: VTI API call failed: m_api_scan_file. Got an error code:", e
def m_api_scan_large_file(self, file_location):
"""
Description:
------------
GET /vtapi/v2/file/scan/upload_url. Get a special URL to upload files bigger than 32MB in size
and upload file.
Parameters:
-----------
string : file_location
path to file to be uploaded
Returns:
--------
json object
response contains scan_id to access report and other info
"""
try:
params = {'apikey':self.a_malshare_api_key}
# obtaining the upload URL
response = requests.get(self.a_api_scan_large_file, params=params)
json_response = response.json()
upload_url = json_response['upload_url']
# submitting the file to the upload URL
files = {'file': (file_location.decode('utf-8'), open(file_location, 'rb'))}
response = requests.post(upload_url, files=files)
return response.json()
except requests.exceptions.RequestException as e:
print "ERROR: VTI API call failed: m_api_scan_file. Got an error code:", e
def m_api_md5_report(self, md5):
"""
Description:
------------
GET /vtapi/v2/file/report Get the scan results for a file
Parameters:
-----------
string : md5
hash value of file
Returns:
--------
json object
report detailing file
"""
try:
params = {'apikey':self.a_malshare_api_key,'resource':md5}
headers = {
"Accept-Encoding": "gzip, deflate",
"User-Agent" : "gzip, graywolf"
}
response = requests.get(self.a_api_md5_report, params=params, headers=headers)
return response.json()
except requests.exceptions.RequestException as e:
print "ERROR: VTI API call failed: m_api_scan_file. Got an error code:", e
def m_api_md5_behaviour(self, md5):
"""
Description:
------------
GET /vtapi/v2/file/behaviour. Get a report about the behaviour of the file when executed in a sandboxed environment.
Parameters:
-----------
string : md5
hash value of file
Returns:
--------
json object
report detailing file
"""
try:
params = {'apikey':self.a_malshare_api_key,'hash': md5}
headers = {
"Accept-Encoding": "gzip, deflate",
"User-Agent" : "gzip, graywolf"
}
response = requests.get(self.a_api_md5_behaviour, params=params, headers=headers)
return response.json()
except requests.exceptions.RequestException as e:
print "ERROR: VTI API call failed: m_api_scan_file. Got an error code:", e
#TODO: Broken, I/O issue
def m_api_md5_pcap(self, md5, file_location):
"""
Description:
------------
GET /vtapi/v2/file/network-traffic Get a dump of the network traffic generated by the file when executed.
Parameters:
-----------
string : md5
hash value of file
string : file_location
where to save the file
Returns:
--------
none
"""
try:
params = {'apikey':self.a_malshare_api_key,'hash':md5}
headers = {
"Accept-Encoding": "gzip, deflate",
"User-Agent" : "gzip, graywolf"
}
first_bytes = None
with open(file_location, 'wb') as handle:
response = requests.get(self.a_api_md5_pcap, params=params, headers=headers, stream=True)
if not response.ok:
print "something is wrong %s" % (response)
return
for block in response.iter_content(4096):
handle.write(block)
if not first_bytes:
first_bytes = str(block)[:4]
valid_pcap_magics = [ '\xd4\xc3\xb2\xa1', '\xa1\xb2\xc3\xd4', '\x4d\x3c\xb2\xa1', '\xa1\xb2\x3c\x4d' ]
if first_bytes in valid_pcap_magics:
print "PCAP downloaded"
elif first_bytes.startswith('{"'):
print "NOT found"
else:
print "unknown file"
except requests.exceptions.RequestException as e:
print "ERROR: VTI API call failed: m_api_scan_file. Got an error code:", e
def m_api_search(self, query_str):
"""
Description:
------------
POST /vtapi/v2/file/search Search for samples that match certain binary/metadata/detection criteria.
Parameters:
-----------
string : query_str
hash value of file
example: 'type:peexe size:90kb+ positives:5+ behaviour:"taskkill"'
Returns:
--------
json object
report detailing file
"""
try:
headers = {
"Accept-Encoding": "gzip, deflate",
"User-Agent" : "gzip, graywolf"
}
params = {'apikey': self.a_malshare_api_key, 'query': query_str}
response = requests.post(self.a_api_search, data=params, headers=headers)
return response.json()
except requests.exceptions.RequestException as e:
print "ERROR: VTI API call failed: m_api_scan_file. Got an error code:", e
def m_api_clusters(self, date):
"""
Description:
------------
GET /vtapi/v2/file/clusters List file similarity clusters for a given time frame.
Parameters:
-----------
string : date
time frame for clusters
Returns:
--------
json object
report detailing cluster information
"""
try:
params = {'apikey': self.a_malshare_api_key, 'date': date}
response = requests.get(self.a_api_clusters, params=params)
return response.json()
except requests.exceptions.RequestException as e:
print "ERROR: VTI API call failed: m_api_scan_file. Got an error code:", e
def m_api_md5_download(self, md5, file_location="./"):
"""
Description:
------------
GET /vtapi/v2/file/download Download a file by its hash.
Parameters:
-----------
string : md5
hash value of file
Returns:
--------
none
"""
try:
headers = {
"Accept-Encoding": "gzip, deflate",
"User-Agent" : "gzip, graywolf"
}
params = {'apikey': self.a_malshare_api_key, 'hash': md5}
response = requests.get(self.a_api_md5_download, params=params)
new_file_byte_array = bytearray(response.content)
new_file = open(file_location+md5, "w")
new_file.write(new_file_byte_array)
return True
except requests.exceptions.RequestException as e:
print "ERROR: VTI API call failed: m_api_scan_file. Got an error code:", e
return False
#TODO: Need to be granted access
def m_api_fp_report(self):
"""
Description:
------------
GET /vtapi/v2/file/false-positives Consume file false positives from your notifications pipe
Parameters:
-----------
none
Returns:
--------
none
"""
try:
headers = {'User-Agent': 'gzip', 'Accept-Encoding': 'gzip'}
params = {'apikey': self.a_malshare_api_key, 'limit': 500}
response = requests.get(self.a_api_fp_report, params=params, headers=headers)
return response.json()
except requests.exceptions.RequestException as e:
print "ERROR: VTI API call failed: m_api_scan_file. Got an error code:", e
def main():
vti = VTI_API()
# Small test file : WARNING: Malicious File
md5 = '231a8de70336d7dbfff05de94d0c33a2'
assert vti.m_api_md5_download(md5)
print "PASS: m_api_md5_download"
assert vti.m_api_scan_file("./"+md5)
print "PASS: m_api_scan_file"
os.remove("./"+md5)
# Large test file : WARNING: Malicious File
md5 = '4f5902bf3aef48a4b20b65fff434c98e'
vti.m_api_md5_download(md5)
assert vti.m_api_scan_large_file("./"+md5)
print "PASS: m_api_scan_large_file"
os.remove("./"+md5)
assert vti.m_api_md5_report(md5)
print "PASS: m_api_md5_report"
assert vti.m_api_md5_behaviour(md5)
print "PASS: m_api_md5_behaviour"
#assert vti.m_api_md5_pcap(md5, "./"+md5)
#print "PASS: m_api_md5_pcap"
#os.remove("./"+md5)
assert vti.m_api_search('type:peexe size:90kb+ positives:5+ behaviour:"taskkill"')
print "PASS: m_api_search"
#assert vti.m_api_fp_report()
#print "PASS: m_api_fp_report"
if __name__ == "__main__":
main()
| mit |
metacpp/LeetCpp | src/array/longest_substr_without_repeating_chars_unittest.cc | 581 | #include <string>
using std::string;
#include <gtest/gtest.h>
#include "longest_substr_without_repeating_chars.h"
namespace {
TEST(LongestSubstrWithoutRepeatingCharsTest, Case1) {
string s = "abcabcbb";
int expected_length = 3;
LongestSubstrWithoutRepeatingChars solution;
EXPECT_EQ(expected_length, solution.longestLength(s));
}
TEST(LongestSubstrWithoutRepeatingCharsTest, Case2) {
string s = "bbbbb";
int expected_length = 1;
LongestSubstrWithoutRepeatingChars solution;
EXPECT_EQ(expected_length, solution.longestLength(s));
}
}
| mit |
ingetat2014/www | src/Fdr/UserBundle/Controller/RegistrationController.php | 522 | <?php
namespace Fdr\UserBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class RegistrationController extends BaseController {
public function registerAction(Request $request) {
$request = $this->get('request');
$response = parent::registerAction($request);
return $response;
}
}
| mit |
barrabinfc/react-iching | docs/assets/wb-assets/workbox-v3.4.1/workbox-cacheable-response.dev.js | 8632 | this.workbox = this.workbox || {};
this.workbox.cacheableResponse = (function (exports,WorkboxError_mjs,assert_mjs,getFriendlyURL_mjs,logger_mjs) {
'use strict';
try {
self.workbox.v['workbox:cacheable-response:3.4.1'] = 1;
} catch (e) {} // eslint-disable-line
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* This class allows you to set up rules determining what
* status codes and/or headers need to be present in order for a
* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* to be considered cacheable.
*
* @memberof workbox.cacheableResponse
*/
class CacheableResponse {
/**
* To construct a new CacheableResponse instance you must provide at least
* one of the `config` properties.
*
* If both `statuses` and `headers` are specified, then both conditions must
* be met for the `Response` to be considered cacheable.
*
* @param {Object} config
* @param {Array<number>} [config.statuses] One or more status codes that a
* `Response` can have and be considered cacheable.
* @param {Object<string,string>} [config.headers] A mapping of header names
* and expected values that a `Response` can have and be considered cacheable.
* If multiple headers are provided, only one needs to be present.
*/
constructor(config = {}) {
{
if (!(config.statuses || config.headers)) {
throw new WorkboxError_mjs.WorkboxError('statuses-or-headers-required', {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'constructor'
});
}
if (config.statuses) {
assert_mjs.assert.isArray(config.statuses, {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'constructor',
paramName: 'config.statuses'
});
}
if (config.headers) {
assert_mjs.assert.isType(config.headers, 'object', {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'constructor',
paramName: 'config.headers'
});
}
}
this._statuses = config.statuses;
this._headers = config.headers;
}
/**
* Checks a response to see whether it's cacheable or not, based on this
* object's configuration.
*
* @param {Response} response The response whose cacheability is being
* checked.
* @return {boolean} `true` if the `Response` is cacheable, and `false`
* otherwise.
*/
isResponseCacheable(response) {
{
assert_mjs.assert.isInstance(response, Response, {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'isResponseCacheable',
paramName: 'response'
});
}
let cacheable = true;
if (this._statuses) {
cacheable = this._statuses.includes(response.status);
}
if (this._headers && cacheable) {
cacheable = Object.keys(this._headers).some(headerName => {
return response.headers.get(headerName) === this._headers[headerName];
});
}
{
if (!cacheable) {
logger_mjs.logger.groupCollapsed(`The request for ` + `'${getFriendlyURL_mjs.getFriendlyURL(response.url)}' returned a response that does ` + `not meet the criteria for being cached.`);
logger_mjs.logger.groupCollapsed(`View cacheability criteria here.`);
logger_mjs.logger.unprefixed.log(`Cacheable statuses: ` + JSON.stringify(this._statuses));
logger_mjs.logger.unprefixed.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2));
logger_mjs.logger.groupEnd();
const logFriendlyHeaders = {};
response.headers.forEach((value, key) => {
logFriendlyHeaders[key] = value;
});
logger_mjs.logger.groupCollapsed(`View response status and headers here.`);
logger_mjs.logger.unprefixed.log(`Response status: ` + response.status);
logger_mjs.logger.unprefixed.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2));
logger_mjs.logger.groupEnd();
logger_mjs.logger.groupCollapsed(`View full response details here.`);
logger_mjs.logger.unprefixed.log(response.headers);
logger_mjs.logger.unprefixed.log(response);
logger_mjs.logger.groupEnd();
logger_mjs.logger.groupEnd();
}
}
return cacheable;
}
}
/*
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* A class implementing the `cacheWillUpdate` lifecycle callback. This makes it
* easier to add in cacheability checks to requests made via Workbox's built-in
* strategies.
*
* @memberof workbox.cacheableResponse
*/
class Plugin {
/**
* To construct a new cacheable response Plugin instance you must provide at
* least one of the `config` properties.
*
* If both `statuses` and `headers` are specified, then both conditions must
* be met for the `Response` to be considered cacheable.
*
* @param {Object} config
* @param {Array<number>} [config.statuses] One or more status codes that a
* `Response` can have and be considered cacheable.
* @param {Object<string,string>} [config.headers] A mapping of header names
* and expected values that a `Response` can have and be considered cacheable.
* If multiple headers are provided, only one needs to be present.
*/
constructor(config) {
this._cacheableResponse = new CacheableResponse(config);
}
/**
* @param {Object} options
* @param {Response} options.response
* @return {boolean}
* @private
*/
cacheWillUpdate({ response }) {
if (this._cacheableResponse.isResponseCacheable(response)) {
return response;
}
return null;
}
}
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
exports.CacheableResponse = CacheableResponse;
exports.Plugin = Plugin;
return exports;
}({},workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private));
//# sourceMappingURL=workbox-cacheable-response.dev.js.map
| mit |
jonDotsoy/MicroCSS | lib/scanTheCssSelectors.js | 1766 | var decomposeCSS = require('./decomposeCSS')
/**
* Retorna un conjunto con los selectores de la hoja de estilo indicado.
* @param {string} CSS Hoja de estilo CSS
* @return {object}
*/
var scanTheCssSelectors = function scanTheCssSelectors (strCSS) {
var cssComponent = new decomposeCSS(strCSS)
this.cssComponent = cssComponent// .objectCSSElement
}
var getTitles = function(objectCSS) {
if (objectCSS.type) {
if (objectCSS.type == 'decomposeCSS' && objectCSS.objectCSSElement) {
var arrWithTitles = []
for (var key in objectCSS.objectCSSElement) {
var CSSElement = objectCSS.objectCSSElement[key]
var tmpToPush = null
if (tmpToPush = getTitles(CSSElement)) {
arrWithTitles.push(tmpToPush)
}
}
return arrWithTitles
}
if (objectCSS.type == 'selector') {
return objectCSS.title
}
if (objectCSS.type == 'media') {
var arrTitlesFromMedia = []
for (var key in objectCSS.selectors) {
var selector = objectCSS.selectors[key]
arrTitlesFromMedia.push(getTitles(selector))
}
return [objectCSS.title,arrTitlesFromMedia]
}
}
}
scanTheCssSelectors.prototype.getHeaders = function() {
return getTitles(this.cssComponent)
}
var getSelectosFromObject = function(){
}
scanTheCssSelectors.prototype.getOnlyHeadersSelectors = function() {
var headers = this.getHeaders(this.cssComponent)
var selectors = []
for (var key in headers) {
var head = headers[key]
if (typeof head == 'string') {
selectors.push(head)
}
if (typeof head == 'object') {
for(var key in head[1]) {
selectors.push(head[1][key])
}
}
}
return selectors
}
scanTheCssSelectors.prototype.getUnifiedSelectors = function (argument) {
// body...
}
module.exports = function () {
scanTheCssSelectors
} | mit |
berkeley-gif/vtm | build/src/common/filters/ThumbnailUrl.js | 222 | angular.module('filters.thumbnail', []).filter('thumbnailUrl', [function () {
return function (url) {
var thumbnailUrl = url.replace(/imgs\/(.*?)(\/)/, 'imgs/128x192/');
return thumbnailUrl;
};
}]);
; | mit |
github/codeql | csharp/ql/src/Security Features/CWE-020/ExternalAPISinkExample.cs | 281 | using System;
using System.Text;
using System.Web;
public class UntrustedData : IHttpHandler
{
public void ProcessRequest(HttpContext ctx)
{
var name = ctx.Request.QueryString["name"];
ctx.Response.Write(name);
}
public bool IsReusable => true;
}
| mit |
apoydence/pubsub | benchmarks_test.go | 5558 | package pubsub_test
import (
"fmt"
"math/rand"
"sync"
"testing"
"github.com/apoydence/pubsub"
)
func BenchmarkPublishing(b *testing.B) {
b.StopTimer()
p := pubsub.New()
for i := 0; i < 100; i++ {
_, f := newSpySubscrption()
p.Subscribe(f, pubsub.WithPath(randPath()))
}
b.StartTimer()
for i := 0; i < b.N; i++ {
p.Publish("data", pubsub.LinearTreeTraverser(randPath()))
}
}
func BenchmarkPublishingStructs(b *testing.B) {
b.StopTimer()
p := pubsub.New()
for i := 0; i < 100; i++ {
_, f := newSpySubscrption()
p.Subscribe(f, pubsub.WithPath(randPath()))
}
data := randStructs()
st := StructTraverser{}
b.StartTimer()
for i := 0; i < b.N; i++ {
p.Publish(data[i%len(data)], st.traverse)
}
}
func BenchmarkSubscriptions(b *testing.B) {
b.StopTimer()
p := pubsub.New()
b.StartTimer()
b.RunParallel(func(b *testing.PB) {
i := rand.Int()
for b.Next() {
_, f := newSpySubscrption()
unsub := p.Subscribe(f, pubsub.WithPath(randPath()))
unsub()
i++
}
})
}
func BenchmarkPublishingParallel(b *testing.B) {
b.StopTimer()
p := pubsub.New()
for i := 0; i < 100; i++ {
_, f := newSpySubscrption()
p.Subscribe(f, pubsub.WithPath(randPath()))
}
b.StartTimer()
b.RunParallel(func(b *testing.PB) {
i := rand.Int()
for b.Next() {
p.Publish("data", pubsub.LinearTreeTraverser(randPath()))
i++
}
})
}
func BenchmarkPublishingParallelStructs(b *testing.B) {
b.StopTimer()
p := pubsub.New()
for i := 0; i < 100; i++ {
_, f := newSpySubscrption()
p.Subscribe(f, pubsub.WithPath(randPath()))
}
data := randStructs()
st := StructTraverser{}
b.StartTimer()
b.RunParallel(func(b *testing.PB) {
i := rand.Int()
for b.Next() {
p.Publish(data[i%len(data)], st.traverse)
i++
}
})
}
func BenchmarkPublishingWhileSubscribing(b *testing.B) {
b.StopTimer()
p := pubsub.New()
var wg sync.WaitGroup
for x := 0; x < 5; x++ {
wg.Add(1)
go func() {
wg.Done()
for i := 0; ; i++ {
_, f := newSpySubscrption()
unsub := p.Subscribe(f, pubsub.WithPath(randPath()))
if i%2 == 0 {
unsub()
}
}
}()
}
wg.Wait()
b.StartTimer()
b.RunParallel(func(b *testing.PB) {
i := rand.Int()
for b.Next() {
p.Publish("data", pubsub.LinearTreeTraverser(randPath()))
i++
}
})
}
func BenchmarkPublishingWhileSubscribingStructs(b *testing.B) {
b.StopTimer()
p := pubsub.New()
data := randStructs()
var wg sync.WaitGroup
for x := 0; x < 5; x++ {
wg.Add(1)
go func() {
wg.Done()
for i := 0; ; i++ {
_, f := newSpySubscrption()
unsub := p.Subscribe(f, pubsub.WithPath(randPath()))
if i%2 == 0 {
unsub()
}
}
}()
}
wg.Wait()
st := StructTraverser{}
b.StartTimer()
b.RunParallel(func(b *testing.PB) {
i := rand.Int()
for b.Next() {
p.Publish(data[i%len(data)], st.traverse)
i++
}
})
}
func randPath() []uint64 {
var r []uint64
for i := 0; i < 10; i++ {
r = append(r, uint64(rand.Int63n(10)))
}
return r
}
func randData() [][]interface{} {
var r [][]interface{}
for i := 0; i < 100000; i++ {
r = append(r, nil)
for j := 0; j < 10; j++ {
r[i] = append(r[i], fmt.Sprintf("%d", rand.Intn(10)))
}
}
return r
}
type someType struct {
a uint64
b uint64
w *w
x *x
}
type w struct {
i uint64
j uint64
}
type x struct {
i uint64
j uint64
}
func randNum(i int64) uint64 {
return uint64(rand.Int63n(i))
}
func randStructs() []*someType {
var r []*someType
for i := 0; i < 100000; i++ {
r = append(r, &someType{
a: randNum(10),
b: randNum(10),
x: &x{
i: randNum(10),
j: randNum(10),
},
})
}
return r
}
type StructTraverser struct{}
func (s StructTraverser) traverse(data interface{}) pubsub.Paths {
// a
return pubsub.PathsWithTraverser([]uint64{0, data.(*someType).a}, pubsub.TreeTraverser(s.b))
}
func (s StructTraverser) b(data interface{}) pubsub.Paths {
return pubsub.PathAndTraversers(
[]pubsub.PathAndTraverser{
{
Path: 0,
Traverser: pubsub.TreeTraverser(s.w),
},
{
Path: data.(*someType).b,
Traverser: pubsub.TreeTraverser(s.w),
},
{
Path: 0,
Traverser: pubsub.TreeTraverser(s.x),
},
{
Path: data.(*someType).b,
Traverser: pubsub.TreeTraverser(s.x),
},
},
)
}
var (
W = uint64(1)
X = uint64(2)
)
func (s StructTraverser) w(data interface{}) pubsub.Paths {
if data.(*someType).w == nil {
return pubsub.PathsWithTraverser([]uint64{0}, pubsub.TreeTraverser(s.done))
}
return pubsub.PathsWithTraverser([]uint64{W}, pubsub.TreeTraverser(s.wi))
}
func (s StructTraverser) wi(data interface{}) pubsub.Paths {
return pubsub.PathsWithTraverser([]uint64{0, data.(*someType).w.i}, pubsub.TreeTraverser(s.wj))
}
func (s StructTraverser) wj(data interface{}) pubsub.Paths {
return pubsub.PathsWithTraverser([]uint64{0, data.(*someType).w.j}, pubsub.TreeTraverser(s.done))
}
func (s StructTraverser) x(data interface{}) pubsub.Paths {
if data.(*someType).x == nil {
return pubsub.PathsWithTraverser([]uint64{0}, pubsub.TreeTraverser(s.done))
}
return pubsub.PathsWithTraverser([]uint64{X}, pubsub.TreeTraverser(s.xi))
}
func (s StructTraverser) xi(data interface{}) pubsub.Paths {
return pubsub.PathsWithTraverser([]uint64{0, data.(*someType).x.i}, pubsub.TreeTraverser(s.xj))
}
func (s StructTraverser) xj(data interface{}) pubsub.Paths {
return pubsub.PathsWithTraverser([]uint64{0, data.(*someType).x.j}, pubsub.TreeTraverser(s.done))
}
func (s StructTraverser) done(data interface{}) pubsub.Paths {
return pubsub.FlatPaths(nil)
}
| mit |
hadalin/firefox-hidefedora | lib/main.js | 1817 | var self = require("sdk/self"),
data = self.data,
pageMod = require("sdk/page-mod"),
ss = require("sdk/simple-storage"),
simplePrefs = require("sdk/simple-prefs");
if (!ss.storage.bannedProfiles) {
ss.storage.bannedProfiles = [];
}
if (!ss.storage.lastJSONUpdate) {
var date = new Date();
date.setFullYear(date.getFullYear() - 1);
ss.storage.lastJSONUpdate = date;
}
var bannedProfiles = ss.storage.bannedProfiles,
lastJSONUpdate = ss.storage.lastJSONUpdate;
function startListening(worker) {
function onPrefsChange(pref) {
var payload = {};
payload[pref] = simplePrefs.prefs[pref];
worker.port.emit('prefsChange', payload);
}
simplePrefs.on("showReportButton", onPrefsChange);
worker.port.emit("prefsChange", {
showReportButton: simplePrefs.prefs.showReportButton
});
simplePrefs.on("bannedWords", onPrefsChange);
worker.port.emit("prefsChange", {
bannedWords: simplePrefs.prefs.bannedWords
});
worker.port.on('bannedProfilesChange', function(payload) {
bannedProfiles = payload.bannedProfiles;
ss.storage.bannedProfiles = bannedProfiles;
});
worker.port.emit("bannedProfiles", {
bannedProfiles: bannedProfiles
});
worker.port.on('lastJSONUpdateChange', function(payload) {
lastJSONUpdate = payload.lastJSONUpdate;
ss.storage.bannedProfiles = lastJSONUpdate;
});
worker.port.emit("lastJSONUpdate", {
lastJSONUpdate: lastJSONUpdate
});
}
pageMod.PageMod({
include: ["*.youtube.com", "*.jhvisser.com"],
contentScriptWhen: 'end',
contentScriptFile: [
data.url("jquery-1.11.1.min.js"),
data.url("underscore-min.js"),
data.url("moment.min.js"),
data.url("content.js")
],
contentStyleFile: data.url("content.css"),
contentScriptOptions: {
"bannedProfiles": bannedProfiles,
"lastJSONUpdate": lastJSONUpdate
},
onAttach: startListening
});
| mit |
galbiati/video-representations | infer.py | 2929 | import os
import numpy as np
import tensorflow as tf
import tqdm
from training import *
from render import *
from download import get_filepaths, video_to_array
from models.AELSTM import *
from models.model import *
L = tf.layers
def infer(video_files, model_file, seqlen=64, batchsize=8):
"""
Takes a list of avi files and a runs the model in model_file on them
Args:
------
:video_files is a list of filepaths to avi files
:model_file is the name of a saved tensorflow session
:output_dir is where the outputs and logs will be stored
:batchsize is batchsize
Outputs:
-------
None
"""
if len(video_files) > 8:
# for now, don't handle more than 8 videos at once
print('Please use 8 or fewer videos at a time')
return None
# load videos to arrays
video_arrays = [video_to_array(vf, n_frames=seqlen+1) for vf in video_files]
video_arrays = np.concatenate(video_arrays)
# initialize downsampler and model
with tf.device('/cpu:0'):
video_placeholder = tf.placeholder(name='video', dtype=tf.float32, shape=(None, 240, 320, 3))
downsampled = tf.tf.image.resize_images(video_placeholder, [60, 80])
downsampled = tf.reshape(downsampled, (batchsize, seqlen+1, 60, 80, 3))
model = Model(encoder, lstm_cell, tied_decoder, batchsize, seqlen)
input_videos = tf.slice(downsampled, begin=[0, 0, 0, 0, 0], size=[batchsize, seqlen, -1, -1, -1])
output_videos = tf.slice(downsampled, begin=[0, 1, 0, 0, 0], size=[batchsize, seqlen, -1, -1, -1])
encoded, transitioned, decoded = model.build(input_videos)
loss = tf.reduce_mean(tf.pow(decoded - output_videos, 2))
saver = tf.train.Saver()
with tf.Session() as sesh:
saver.restore(sesh, model_file)
loss_value, encodings, transitions, predictions, recovered = sesh.run(
[loss, encoded, transitioned, decoded, downsampled],
{video_placeholder: video_arrays}
)
return loss_value, encodings, transitions, predictions, recovered
def main():
data_dir = os.path.expanduser('~/Insight/video-representations/')
outputs_dir = os.path.join(data_dir, 'outputs')
os.makedirs(outputs_dir, exist_ok=True)
model_file = 'ptypelstm-tied-relu'
video_files, _ = get_filepaths(data_dir)
np.random.shuffle(video_files)
video_files = video_files[:8]
loss, encodings, transitions, predictions, recovered = infer(video_files, model_file)
outputs_filename = '{}_output.mp4'
recover_filename = '{}_recov.mp4'
for i in range(8):
render_movie(predictions[i], os.path.join(outputs_dir, outputs_filename.format(i)))
render_movie(recovered[i], os.path.join(outputs_dir, recover_filename.format(i)))
np.savez_compressed(os.path.join(outputs_dir, 'infered.npz'), loss, encodings, transitions)
return None
if __name__ == '__main__':
main()
| mit |
Dziemborowicz/Hourglass | Hourglass/Parsing/TimeToken.cs | 6668 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="TimeToken.cs" company="Chris Dziemborowicz">
// Copyright (c) Chris Dziemborowicz. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Hourglass.Parsing
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
/// <summary>
/// Represents the time part of an instant in time.
/// </summary>
[XmlInclude(typeof(EmptyTimeToken))]
[XmlInclude(typeof(NormalTimeToken))]
[XmlInclude(typeof(SpecialTimeToken))]
public abstract class TimeToken
{
/// <summary>
/// Gets a list of all supported <see cref="Parser"/>s.
/// </summary>
public static Parser[] Parsers
{
get
{
return new Parser[]
{
EmptyTimeToken.Parser.Instance,
NormalTimeToken.Parser.Instance,
SpecialTimeToken.Parser.Instance
};
}
}
/// <summary>
/// Gets a value indicating whether the token is valid.
/// </summary>
public abstract bool IsValid { get; }
/// <summary>
/// Returns the next date and time after <paramref name="minDate"/> that is represented by this token.
/// </summary>
/// <remarks>
/// This method may return a date and time that is before <paramref name="minDate"/> if there is no date and
/// time after <paramref name="minDate"/> that is represented by this token.
/// </remarks>
/// <param name="minDate">The minimum date and time to return.</param>
/// <param name="datePart">The date part of the date and time to return.</param>
/// <returns>The next date and time after <paramref name="minDate"/> that is represented by this token.
/// </returns>
/// <exception cref="InvalidOperationException">If this token is not valid.</exception>
public abstract DateTime ToDateTime(DateTime minDate, DateTime datePart);
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public sealed override string ToString()
{
return this.ToString(CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <param name="provider">An <see cref="IFormatProvider"/> to use.</param>
/// <returns>A string that represents the current object.</returns>
public abstract string ToString(IFormatProvider provider);
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if <see cref="IsValid"/> is <c>false</c>.
/// </summary>
protected void ThrowIfNotValid()
{
if (!this.IsValid)
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Parses <see cref="TimeToken"/> strings.
/// </summary>
public abstract class Parser
{
/// <summary>
/// Returns a value indicating whether this parser can be used in conjunction with a specified <see
/// cref="DateToken.Parser"/>.
/// </summary>
/// <param name="dateTokenParser">A <see cref="DateToken.Parser"/>.</param>
/// <returns>A value indicating whether this parser can be used in conjunction with the specified <see
/// cref="DateToken.Parser"/>.</returns>
public virtual bool IsCompatibleWith(DateToken.Parser dateTokenParser)
{
return true;
}
/// <summary>
/// Returns a set of regular expressions supported by this parser.
/// </summary>
/// <param name="provider">An <see cref="IFormatProvider"/>.</param>
/// <returns>A set of regular expressions supported by this parser.</returns>
public abstract IEnumerable<string> GetPatterns(IFormatProvider provider);
/// <summary>
/// Parses a <see cref="Match"/> into a <see cref="TimeToken"/>.
/// </summary>
/// <param name="match">A <see cref="Match"/> representation of a <see cref="TimeToken"/>.</param>
/// <param name="provider">An <see cref="IFormatProvider"/>.</param>
/// <returns>The <see cref="TimeToken"/> parsed from the <see cref="Match"/>.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="match"/> or <paramref name="provider"/> is
/// <c>null</c>.</exception>
/// <exception cref="FormatException">If the <paramref name="match"/> is not a supported representation of
/// a <see cref="TimeToken"/>.</exception>
public TimeToken Parse(Match match, IFormatProvider provider)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
if (!match.Success)
{
throw new FormatException();
}
TimeToken timeToken = this.ParseInternal(match, provider);
if (!timeToken.IsValid)
{
throw new FormatException();
}
return timeToken;
}
/// <summary>
/// Parses a <see cref="Match"/> into a <see cref="TimeToken"/>.
/// </summary>
/// <param name="match">A <see cref="Match"/> representation of a <see cref="TimeToken"/>.</param>
/// <param name="provider">An <see cref="IFormatProvider"/>.</param>
/// <returns>The <see cref="TimeToken"/> parsed from the <see cref="Match"/>.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="match"/> or <paramref name="provider"/> is
/// <c>null</c>.</exception>
/// <exception cref="FormatException">If the <paramref name="match"/> is not a supported representation of
/// a <see cref="TimeToken"/>.</exception>
protected abstract TimeToken ParseInternal(Match match, IFormatProvider provider);
}
}
}
| mit |
jackschmidt/rclone | yandex/yandex.go | 16080 | // Package yandex provides an interface to the Yandex Disk storage.
//
// dibu28 <dibu28@gmail.com> github.com/dibu28
package yandex
import (
"encoding/json"
"fmt"
"io"
"log"
"path"
"path/filepath"
"strings"
"time"
"github.com/ncw/rclone/fs"
"github.com/ncw/rclone/oauthutil"
yandex "github.com/ncw/rclone/yandex/api"
"github.com/pkg/errors"
"golang.org/x/oauth2"
)
//oAuth
const (
rcloneClientID = "ac39b43b9eba4cae8ffb788c06d816a8"
rcloneEncryptedClientSecret = "EfyyNZ3YUEwXM5yAhi72G9YwKn2mkFrYwJNS7cY0TJAhFlX9K-uJFbGlpO-RYjrJ"
)
// Globals
var (
// Description of how to auth for this app
oauthConfig = &oauth2.Config{
Endpoint: oauth2.Endpoint{
AuthURL: "https://oauth.yandex.com/authorize", //same as https://oauth.yandex.ru/authorize
TokenURL: "https://oauth.yandex.com/token", //same as https://oauth.yandex.ru/token
},
ClientID: rcloneClientID,
ClientSecret: fs.MustReveal(rcloneEncryptedClientSecret),
RedirectURL: oauthutil.RedirectURL,
}
)
// Register with Fs
func init() {
fs.Register(&fs.RegInfo{
Name: "yandex",
Description: "Yandex Disk",
NewFs: NewFs,
Config: func(name string) {
err := oauthutil.Config("yandex", name, oauthConfig)
if err != nil {
log.Fatalf("Failed to configure token: %v", err)
}
},
Options: []fs.Option{{
Name: fs.ConfigClientID,
Help: "Yandex Client Id - leave blank normally.",
}, {
Name: fs.ConfigClientSecret,
Help: "Yandex Client Secret - leave blank normally.",
}},
})
}
// Fs represents a remote yandex
type Fs struct {
name string
yd *yandex.Client // client for rest api
root string //root path
diskRoot string //root path with "disk:/" container name
mkdircache map[string]int
}
// Object describes a swift object
type Object struct {
fs *Fs // what this object is part of
remote string // The remote path
md5sum string // The MD5Sum of the object
bytes uint64 // Bytes in the object
modTime time.Time // Modified time of the object
mimeType string // Content type according to the server
}
// ------------------------------------------------------------
// Name of the remote (as passed into NewFs)
func (f *Fs) Name() string {
return f.name
}
// Root of the remote (as passed into NewFs)
func (f *Fs) Root() string {
return f.root
}
// String converts this Fs to a string
func (f *Fs) String() string {
return fmt.Sprintf("Yandex %s", f.root)
}
// read access token from ConfigFile string
func getAccessToken(name string) (*oauth2.Token, error) {
// Read the token from the config file
tokenConfig := fs.ConfigFile.MustValue(name, "token")
//Get access token from config string
decoder := json.NewDecoder(strings.NewReader(tokenConfig))
var result *oauth2.Token
err := decoder.Decode(&result)
if err != nil {
return nil, err
}
return result, nil
}
// NewFs constructs an Fs from the path, container:path
func NewFs(name, root string) (fs.Fs, error) {
//read access token from config
token, err := getAccessToken(name)
if err != nil {
return nil, err
}
//create new client
yandexDisk := yandex.NewClient(token.AccessToken, fs.Config.Client())
f := &Fs{
yd: yandexDisk,
}
f.setRoot(root)
// Check to see if the object exists and is a file
//request object meta info
var opt2 yandex.ResourceInfoRequestOptions
if ResourceInfoResponse, err := yandexDisk.NewResourceInfoRequest(root, opt2).Exec(); err != nil {
//return err
} else {
if ResourceInfoResponse.ResourceType == "file" {
f.setRoot(path.Dir(root))
// return an error with an fs which points to the parent
return f, fs.ErrorIsFile
}
}
return f, nil
}
// Sets root in f
func (f *Fs) setRoot(root string) {
//Set root path
f.root = strings.Trim(root, "/")
//Set disk root path.
//Adding "disk:" to root path as all paths on disk start with it
var diskRoot = ""
if f.root == "" {
diskRoot = "disk:/"
} else {
diskRoot = "disk:/" + f.root + "/"
}
f.diskRoot = diskRoot
}
// listFn is called from list and listContainerRoot to handle an object.
type listFn func(remote string, item *yandex.ResourceInfoResponse, isDirectory bool) error
// listDir lists this directory only returning objects and directories
func (f *Fs) listDir(fn listFn) (err error) {
//request object meta info
var opt yandex.ResourceInfoRequestOptions
ResourceInfoResponse, err := f.yd.NewResourceInfoRequest(f.diskRoot, opt).Exec()
if err != nil {
return err
}
if ResourceInfoResponse.ResourceType == "dir" {
//list all subdirs
for _, element := range ResourceInfoResponse.Embedded.Items {
remote := element.Name
switch element.ResourceType {
case "dir":
err = fn(remote, &element, true)
if err != nil {
return err
}
case "file":
err = fn(remote, &element, false)
if err != nil {
return err
}
default:
fs.Debug(f, "Unknown resource type %q", element.ResourceType)
}
}
}
return nil
}
// list the objects into the function supplied
//
// This does a flat listing of all the files in the drive
func (f *Fs) list(dir string, fn listFn) error {
//request files list. list is divided into pages. We send request for each page
//items per page is limited by limit
//TODO may be add config parameter for the items per page limit
var limit uint32 = 1000 // max number of object per request
var itemsCount uint32 //number of items per page in response
var offset uint32 //for the next page of request
// yandex disk api request options
var opt yandex.FlatFileListRequestOptions
opt.Limit = &limit
opt.Offset = &offset
prefix := f.diskRoot
if dir != "" {
prefix += dir + "/"
}
//query each page of list until itemCount is less then limit
for {
//send request
info, err := f.yd.NewFlatFileListRequest(opt).Exec()
if err != nil {
return err
}
itemsCount = uint32(len(info.Items))
//list files
for _, item := range info.Items {
// filter file list and get only files we need
if strings.HasPrefix(item.Path, prefix) {
//trim root folder from filename
var name = strings.TrimPrefix(item.Path, f.diskRoot)
err = fn(name, &item, false)
if err != nil {
return err
}
}
}
//offset for the next page of items
offset += itemsCount
//check if we reached end of list
if itemsCount < limit {
break
}
}
return nil
}
// List walks the path returning a channel of Objects
func (f *Fs) List(out fs.ListOpts, dir string) {
defer out.Finished()
listItem := func(remote string, object *yandex.ResourceInfoResponse, isDirectory bool) error {
if isDirectory {
t, err := time.Parse(time.RFC3339Nano, object.Modified)
if err != nil {
return err
}
dir := &fs.Dir{
Name: remote,
When: t,
Bytes: int64(object.Size),
Count: -1,
}
if out.AddDir(dir) {
return fs.ErrorListAborted
}
} else {
o, err := f.newObjectWithInfo(remote, object)
if err != nil {
return err
}
if out.Add(o) {
return fs.ErrorListAborted
}
}
return nil
}
var err error
switch out.Level() {
case 1:
if dir == "" {
err = f.listDir(listItem)
} else {
err = f.list(dir, listItem)
}
case fs.MaxLevel:
err = f.list(dir, listItem)
default:
out.SetError(fs.ErrorLevelNotSupported)
}
if err != nil {
// FIXME
// if err == swift.ContainerNotFound {
// err = fs.ErrorDirNotFound
// }
out.SetError(err)
}
}
// NewObject finds the Object at remote. If it can't be found it
// returns the error fs.ErrorObjectNotFound.
func (f *Fs) NewObject(remote string) (fs.Object, error) {
return f.newObjectWithInfo(remote, nil)
}
// Return an Object from a path
//
// If it can't be found it returns the error fs.ErrorObjectNotFound.
func (f *Fs) newObjectWithInfo(remote string, info *yandex.ResourceInfoResponse) (fs.Object, error) {
o := &Object{
fs: f,
remote: remote,
}
if info != nil {
o.setMetaData(info)
} else {
err := o.readMetaData()
if err != nil {
return nil, err
}
}
return o, nil
}
// setMetaData sets the fs data from a storage.Object
func (o *Object) setMetaData(info *yandex.ResourceInfoResponse) {
o.bytes = info.Size
o.md5sum = info.Md5
o.mimeType = info.MimeType
var modTimeString string
modTimeObj, ok := info.CustomProperties["rclone_modified"]
if ok {
// read modTime from rclone_modified custom_property of object
modTimeString, ok = modTimeObj.(string)
}
if !ok {
// read modTime from Modified property of object as a fallback
modTimeString = info.Modified
}
t, err := time.Parse(time.RFC3339Nano, modTimeString)
if err != nil {
fs.Log("Failed to parse modtime from %q: %v", modTimeString, err)
} else {
o.modTime = t
}
}
// readMetaData gets the info if it hasn't already been fetched
func (o *Object) readMetaData() (err error) {
// exit if already fetched
if !o.modTime.IsZero() {
return nil
}
//request meta info
var opt2 yandex.ResourceInfoRequestOptions
ResourceInfoResponse, err := o.fs.yd.NewResourceInfoRequest(o.remotePath(), opt2).Exec()
if err != nil {
if dcErr, ok := err.(yandex.DiskClientError); ok {
if dcErr.Code == "DiskNotFoundError" {
return fs.ErrorObjectNotFound
}
}
return err
}
o.setMetaData(ResourceInfoResponse)
return nil
}
// Put the object
//
// Copy the reader in to the new object which is returned
//
// The new object may have been created if an error is returned
func (f *Fs) Put(in io.Reader, src fs.ObjectInfo) (fs.Object, error) {
remote := src.Remote()
size := src.Size()
modTime := src.ModTime()
o := &Object{
fs: f,
remote: remote,
bytes: uint64(size),
modTime: modTime,
}
//TODO maybe read metadata after upload to check if file uploaded successfully
return o, o.Update(in, src)
}
// Mkdir creates the container if it doesn't exist
func (f *Fs) Mkdir() error {
return mkDirFullPath(f.yd, f.diskRoot)
}
// Rmdir deletes the container
//
// Returns an error if it isn't empty
func (f *Fs) Rmdir() error {
return f.purgeCheck(true)
}
// purgeCheck remotes the root directory, if check is set then it
// refuses to do so if it has anything in
func (f *Fs) purgeCheck(check bool) error {
if check {
//to comply with rclone logic we check if the directory is empty before delete.
//send request to get list of objects in this directory.
var opt yandex.ResourceInfoRequestOptions
ResourceInfoResponse, err := f.yd.NewResourceInfoRequest(f.diskRoot, opt).Exec()
if err != nil {
return errors.Wrap(err, "rmdir failed")
}
if len(ResourceInfoResponse.Embedded.Items) != 0 {
return errors.New("rmdir failed: directory not empty")
}
}
//delete directory
return f.yd.Delete(f.diskRoot, true)
}
// Precision return the precision of this Fs
func (f *Fs) Precision() time.Duration {
return time.Nanosecond
}
// Purge deletes all the files and the container
//
// Optional interface: Only implement this if you have a way of
// deleting all the files quicker than just running Remove() on the
// result of List()
func (f *Fs) Purge() error {
return f.purgeCheck(false)
}
// Hashes returns the supported hash sets.
func (f *Fs) Hashes() fs.HashSet {
return fs.HashSet(fs.HashMD5)
}
// ------------------------------------------------------------
// Fs returns the parent Fs
func (o *Object) Fs() fs.Info {
return o.fs
}
// Return a string version
func (o *Object) String() string {
if o == nil {
return "<nil>"
}
return o.remote
}
// Remote returns the remote path
func (o *Object) Remote() string {
return o.remote
}
// Hash returns the Md5sum of an object returning a lowercase hex string
func (o *Object) Hash(t fs.HashType) (string, error) {
if t != fs.HashMD5 {
return "", fs.ErrHashUnsupported
}
return o.md5sum, nil
}
// Size returns the size of an object in bytes
func (o *Object) Size() int64 {
var size = int64(o.bytes) //need to cast from uint64 in yandex disk to int64 in rclone. can cause overflow
return size
}
// ModTime returns the modification time of the object
//
// It attempts to read the objects mtime and if that isn't present the
// LastModified returned in the http headers
func (o *Object) ModTime() time.Time {
err := o.readMetaData()
if err != nil {
fs.Log(o, "Failed to read metadata: %v", err)
return time.Now()
}
return o.modTime
}
// Open an object for read
func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) {
return o.fs.yd.Download(o.remotePath(), fs.OpenOptionHeaders(options))
}
// Remove an object
func (o *Object) Remove() error {
return o.fs.yd.Delete(o.remotePath(), true)
}
// SetModTime sets the modification time of the local fs object
//
// Commits the datastore
func (o *Object) SetModTime(modTime time.Time) error {
remote := o.remotePath()
// set custom_property 'rclone_modified' of object to modTime
err := o.fs.yd.SetCustomProperty(remote, "rclone_modified", modTime.Format(time.RFC3339Nano))
if err != nil {
return err
}
o.modTime = modTime
return nil
}
// Storable returns whether this object is storable
func (o *Object) Storable() bool {
return true
}
// Returns the remote path for the object
func (o *Object) remotePath() string {
return o.fs.diskRoot + o.remote
}
// Update the already existing object
//
// Copy the reader into the object updating modTime and size
//
// The new object may have been created if an error is returned
func (o *Object) Update(in io.Reader, src fs.ObjectInfo) error {
size := src.Size()
modTime := src.ModTime()
remote := o.remotePath()
//create full path to file before upload.
err1 := mkDirFullPath(o.fs.yd, remote)
if err1 != nil {
return err1
}
//upload file
overwrite := true //overwrite existing file
mimeType := fs.MimeType(src)
err := o.fs.yd.Upload(in, remote, overwrite, mimeType)
if err == nil {
//if file uploaded sucessfully then return metadata
o.bytes = uint64(size)
o.modTime = modTime
o.md5sum = "" // according to unit tests after put the md5 is empty.
//and set modTime of uploaded file
err = o.SetModTime(modTime)
}
return err
}
// utility funcs-------------------------------------------------------------------
// mkDirExecute execute mkdir
func mkDirExecute(client *yandex.Client, path string) (int, string, error) {
statusCode, jsonErrorString, err := client.Mkdir(path)
if statusCode == 409 { // dir already exist
return statusCode, jsonErrorString, err
}
if statusCode == 201 { // dir was created
return statusCode, jsonErrorString, err
}
if err != nil {
// error creating directory
return statusCode, jsonErrorString, errors.Wrap(err, "failed to create folder")
}
return 0, "", nil
}
//mkDirFullPath Creates Each Directory in the path if needed. Send request once for every directory in the path.
func mkDirFullPath(client *yandex.Client, path string) error {
//trim filename from path
dirString := strings.TrimSuffix(path, filepath.Base(path))
//trim "disk:/" from path
dirString = strings.TrimPrefix(dirString, "disk:/")
//1 Try to create directory first
if _, jsonErrorString, err := mkDirExecute(client, dirString); err != nil {
er2, _ := client.ParseAPIError(jsonErrorString)
if er2 != "DiskPathPointsToExistentDirectoryError" {
//2 if it fails then create all directories in the path from root.
dirs := strings.Split(dirString, "/") //path separator /
var mkdirpath = "/" //path separator /
for _, element := range dirs {
if element != "" {
mkdirpath += element + "/" //path separator /
_, _, err2 := mkDirExecute(client, mkdirpath)
if err2 != nil {
//we continue even if some directories exist.
}
}
}
}
}
return nil
}
// MimeType of an Object if known, "" otherwise
func (o *Object) MimeType() string {
err := o.readMetaData()
if err != nil {
fs.Log(o, "Failed to read metadata: %v", err)
return ""
}
return o.mimeType
}
// Check the interfaces are satisfied
var (
_ fs.Fs = (*Fs)(nil)
_ fs.Purger = (*Fs)(nil)
//_ fs.Copier = (*Fs)(nil)
_ fs.Object = (*Object)(nil)
_ fs.MimeTyper = &Object{}
)
| mit |
bonevbb/restraurant-uni-dev | app/Http/Controllers/Admin/AllergensController.php | 1669 | <?php
namespace App\Http\Controllers\Admin;
use App\Allergens;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AllergensController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$options = Allergens::paginate(15);
return view('admin.options',['options' => $options]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
| mit |
litongbupt/iframework | src/test/java/com/bupt/app/security/dao/UserMapperTest.java | 1570 | package com.bupt.app.security.dao;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.bupt.core.system.dao.UserMapper;
import com.bupt.core.system.model.User;
import com.bupt.core.system.model.UserExample;
import com.bupt.core.system.model.UserExample.Criteria;
public class UserMapperTest
{
ApplicationContext aContext = new FileSystemXmlApplicationContext("src/main/resources/com/bupt/config/applicationContext.xml");
UserMapper userMapper = aContext.getBean(UserMapper.class);
public void testUserMapper()
{
User user = new User();
user.setLoginName("litong");
user.setPassword("yang1290");
user.setDepartmentId(3);
user.setUesrName("李彤");
userMapper.insertSelective(user);
UserExample ue = new UserExample();
Criteria criteri = ue.createCriteria();
criteri.andLoginNameEqualTo("张三");
List<User> resultUserExcample = userMapper.selectByExample(ue);
System.out.println(resultUserExcample.get(0));
}
@Test
public void testListResult(){
List<User> result = userMapper.listResults(0, 10, "login_name", "asc", null);
System.out.println(result);
}
@Test
public void testSelectByExample(){
UserExample ue = new UserExample();
ue.setOrderByClause("login_name asc");
ue.setStart(0);
ue.setLimit(10);
List<User> userList = userMapper.selectByExample(ue);
for (User user : userList) {
System.out.println(user);
}
}
}
| mit |
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/fragment/CoreCharacterEditStressFragment.java | 4964 | package link.standen.michael.fatesheets.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.ConsequenceArrayAdapter;
import link.standen.michael.fatesheets.adapter.StressArrayAdapter;
import link.standen.michael.fatesheets.view.AdapterLinearLayout;
import link.standen.michael.fatesheets.model.Consequence;
import link.standen.michael.fatesheets.model.CoreCharacter;
import link.standen.michael.fatesheets.model.Stress;
/**
* A fragment for managing a characters stress.
*/
public class CoreCharacterEditStressFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.core_character_edit_stress, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Physical
Fragment childFragment = new PhysicalStressFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.physical_stress_container, childFragment).commit();
// Mental
childFragment = new MentalStressFragment();
transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.mental_stress_container, childFragment).commit();
// Consequence
childFragment = new ConsequenceFragment();
transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.consequence_container, childFragment).commit();
}
/**
* Class for managing physical stress.
*/
public static class PhysicalStressFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
CoreCharacter character = getCoreCharacter();
View rootView = inflater.inflate(R.layout.core_character_edit_stress_physical, container, false);
// Physical Stress
final StressArrayAdapter physicalStressListAdapter = new StressArrayAdapter(getContext(),
R.layout.character_edit_stress_list_item, character.getPhysicalStress());
((AdapterLinearLayout) rootView.findViewById(R.id.physical_stress_list)).setAdapter(physicalStressListAdapter);
rootView.findViewById(R.id.add_physical_stress).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
int nextValue = getCoreCharacter().getPhysicalStress().size() + 1;
getCoreCharacter().getPhysicalStress().add(new Stress(nextValue));
physicalStressListAdapter.notifyDataSetChanged();
}
});
return rootView;
}
}
/**
* Class for managing mental stress.
*/
public static class MentalStressFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
CoreCharacter character = getCoreCharacter();
View rootView = inflater.inflate(R.layout.core_character_edit_stress_mental, container, false);
final StressArrayAdapter mentalStressListAdapter = new StressArrayAdapter(getContext(),
R.layout.character_edit_stress_list_item, character.getMentalStress());
((AdapterLinearLayout) rootView.findViewById(R.id.mental_stress_list)).setAdapter(mentalStressListAdapter);
rootView.findViewById(R.id.add_mental_stress).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int nextValue = getCoreCharacter().getMentalStress().size() + 1;
getCoreCharacter().getMentalStress().add(new Stress(nextValue));
mentalStressListAdapter.notifyDataSetChanged();
}
});
return rootView;
}
}
/**
* Class for managing consequences.
*/
public static class ConsequenceFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_stress_consequence, container, false);
// Consequences
final ConsequenceArrayAdapter consequenceListAdapter = new ConsequenceArrayAdapter(getContext(),
R.layout.character_edit_consequence_list_item, getCharacter().getConsequences());
((AdapterLinearLayout) rootView.findViewById(R.id.consequence_list)).setAdapter(consequenceListAdapter);
rootView.findViewById(R.id.add_consequence).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
int nextValue = getCoreCharacter().getConsequences().size() * 2 + 2;
getCoreCharacter().getConsequences().add(new Consequence(nextValue));
consequenceListAdapter.notifyDataSetChanged();
}
});
return rootView;
}
}
} | mit |
Ardakaniz/NzPacman | extlibs/Nazara/include/Nazara/Audio/Algorithm.hpp | 493 | // Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Audio module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_ALGORITHM_AUDIO_HPP
#define NAZARA_ALGORITHM_AUDIO_HPP
#include <Nazara/Prerequesites.hpp>
namespace Nz
{
template<typename T> void MixToMono(T* input, T* output, UInt32 channelCount, UInt64 frameCount);
}
#include <Nazara/Audio/Algorithm.inl>
#endif // NAZARA_ALGORITHM_AUDIO_HPP
| mit |
CoralineAda/mongoid_session_store | lib/mongoid/session_store/session.rb | 1278 | module Mongoid
module SessionStore
class Session
include Mongoid::Document
include Mongoid::Timestamps
field :session_id
field :raw_data
field :expires_at, :type => DateTime
DEFAULT_SESSION_EXPIRY = 60
store_in :collection => :sessions, :database => 'mongoid_session_store'
before_update :set_expires_at
def self.find_by_session_id(session_id)
where(:session_id => session_id).last
end
def self.session_expiry
ENV['SESSION_TIMEOUT'].to_i.minutes || DEFAULT_SESSION_EXPIRY.minutes
end
def data
self.raw_data.present? && Marshal.load(Base64.decode64(self.raw_data)).merge(:expires_at => self.expires_at) || {}
end
def data=(raw={})
self.raw_data = Base64.encode64(Marshal.dump(raw))
end
def set_expires_at
if current?
self.expires_at = Time.now + Session.session_expiry
else
self.expires_at = nil
end
end
def current?
return true unless self.expires_at.present?
self.expires_at.in_time_zone > Time.now.in_time_zone
end
def expired?
! current?
end
def loaded?
self.raw_data.present?
end
end
end
end
| mit |
TomHarte/CLK | Machines/Apple/ADB/Keyboard.hpp | 2854 | //
// Keyboard.hpp
// Clock Signal
//
// Created by Thomas Harte on 13/02/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#ifndef Keyboard_hpp
#define Keyboard_hpp
#include "ReactiveDevice.hpp"
#include "../../../Inputs/Keyboard.hpp"
#include "../../KeyboardMachine.hpp"
#include <array>
#include <cstdint>
#include <mutex>
#include <vector>
namespace Apple {
namespace ADB {
/*!
Defines the keycodes that could be passed directly via set_key_pressed; these
are based on the Apple Extended Keyboard.
*/
enum class Key: uint16_t {
/*
These are transcribed from Page 19-11 of
the Macintosh Family Hardware Reference.
*/
BackTick = 0x32,
k1 = 0x12, k2 = 0x13, k3 = 0x14, k4 = 0x15, k5 = 0x17,
k6 = 0x16, k7 = 0x1a, k8 = 0x1c, k9 = 0x19, k0 = 0x1d,
Help = 0x72,
Home = 0x73,
PageUp = 0x74,
Delete = 0x75,
End = 0x77,
PageDown = 0x79,
Escape = 0x35,
Hyphen = 0x1b,
Equals = 0x18,
Backspace = 0x33,
Tab = 0x30,
Power = 0x7f,
F1 = 0x7a, F2 = 0x78, F3 = 0x63, F4 = 0x76,
F5 = 0x60, F6 = 0x61, F7 = 0x62, F8 = 0x64,
F9 = 0x65, F10 = 0x6d, F11 = 0x67, F12 = 0x6f,
F13 = 0x69, F14 = 0x6b, F15 = 0x71,
Q = 0x0c, W = 0x0d, E = 0x0e, R = 0x0f, T = 0x11, Y = 0x10, U = 0x20, I = 0x22, O = 0x1f, P = 0x23,
A = 0x00, S = 0x01, D = 0x02, F = 0x03, G = 0x05, H = 0x04, J = 0x26, K = 0x28, L = 0x25,
Z = 0x06, X = 0x07, C = 0x08, V = 0x09, B = 0x0b, N = 0x2d, M = 0x2e,
OpenSquareBracket = 0x21,
CloseSquareBracket = 0x1e,
Semicolon = 0x29,
Quote = 0x27,
Comma = 0x2b,
FullStop = 0x2f,
ForwardSlash = 0x2c,
CapsLock = 0x39,
LeftShift = 0x38, RightShift = 0x7b,
LeftControl = 0x36, RightControl = 0x7d,
LeftOption = 0x3a, RightOption = 0x7c,
Command = 0x37,
Space = 0x31,
Backslash = 0x2a,
Return = 0x24,
Left = 0x3b,
Right = 0x3c,
Up = 0x3e,
Down = 0x3d,
KeypadClear = 0x47,
KeypadEquals = 0x51,
KeypadSlash = 0x4b,
KeypadAsterisk = 0x43,
KeypadMinus = 0x4e,
KeypadPlus = 0x45,
KeypadEnter = 0x4c,
KeypadDecimalPoint = 0x41,
Keypad9 = 0x5c, Keypad8 = 0x5b, Keypad7 = 0x59,
Keypad6 = 0x58, Keypad5 = 0x57, Keypad4 = 0x56,
Keypad3 = 0x55, Keypad2 = 0x54, Keypad1 = 0x53,
Keypad0 = 0x52,
};
class Keyboard: public ReactiveDevice {
public:
Keyboard(Bus &);
bool set_key_pressed(Key key, bool is_pressed);
void clear_all_keys();
private:
void perform_command(const Command &command) override;
void did_receive_data(const Command &, const std::vector<uint8_t> &) override;
std::mutex keys_mutex_;
std::array<bool, 128> pressed_keys_;
std::vector<uint8_t> pending_events_;
uint16_t modifiers_ = 0xffff;
};
/*!
Provides a mapping from idiomatic PC keys to ADB keys.
*/
class KeyboardMapper: public MachineTypes::MappedKeyboardMachine::KeyboardMapper {
uint16_t mapped_key_for_key(Inputs::Keyboard::Key key) const final;
};
}
}
#endif /* Keyboard_hpp */
| mit |
adatapost/java-web | DbApp/src/in/anita/test/TestMain.java | 496 | package in.anita.test;
import in.anita.Db;
public class TestMain {
public static void main(String[] args) {
String sql = "insert into emp values (?,?,?)";
Db x = null;
try {
x =new Db(sql);
x.getPs().setInt(1, 103);
x.getPs().setString(2,"Rakesh");
x.getPs().setDate(3,Db.toSqlDate("1-12-2002"));
x.execute();
System.out.println("OK");
} catch (Exception e) {
System.out.println(e);
} finally{
if(x!=null)
x.dispose();
}
}
}
| mit |
Azure/azure-sdk-for-python | sdk/cosmos/azure-cosmos/test/test_partition_key.py | 10646 | # The MIT License (MIT)
# Copyright (c) 2014 Microsoft Corporation
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import unittest
import pytest
import requests
import datetime
import json
import uuid
from urllib.parse import quote as urllib_quote
import azure.cosmos.auth as auth
import azure.cosmos.partition_key as partition_key
import azure.cosmos.cosmos_client as cosmos_client
import test_config
pytestmark = pytest.mark.cosmosEmulator
@pytest.mark.usefixtures("teardown")
class PartitionKeyTests(unittest.TestCase):
"""Tests to verify if non partitoned collections are properly accessed on migration with version 2018-12-31.
"""
host = test_config._test_config.host
masterKey = test_config._test_config.masterKey
connectionPolicy = test_config._test_config.connectionPolicy
@classmethod
def tearDownClass(cls):
cls.created_db.delete_container(container=cls.created_collection_id)
@classmethod
def setUpClass(cls):
cls.client = cosmos_client.CosmosClient(cls.host, cls.masterKey, "Session", connection_policy=cls.connectionPolicy)
cls.created_db = test_config._test_config.create_database_if_not_exist(cls.client)
cls.created_collection = test_config._test_config.create_multi_partition_collection_with_custom_pk_if_not_exist(cls.client)
# Create a non partitioned collection using the rest API and older version
requests_client = requests.Session()
base_url_split = cls.host.split(":");
resource_url = base_url_split[0] + ":" + base_url_split[1] + ":" + base_url_split[2].split("/")[0] + "//dbs/" + cls.created_db.id + "/colls/"
verb = "post"
resource_id_or_fullname = "dbs/" + cls.created_db.id
resource_type = "colls"
data = '{"id":"mycoll"}'
headers = {}
headers["x-ms-version"] = "2018-09-17"
headers["x-ms-date"] = (datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT'))
headers['authorization'] = cls.get_authorization(cls.created_db.client_connection, verb, resource_id_or_fullname, resource_type, headers)
response = requests_client.request(verb,
resource_url,
data=data,
headers=headers,
timeout=60,
stream=False,
verify=False)
data = response.content
data = data.decode('utf-8')
data = json.loads(data)
cls.created_collection_id = data['id']
# Create a document in the non partitioned collection using the rest API and older version
resource_url = base_url_split[0] + ":" + base_url_split[1] + ":" + base_url_split[2].split("/")[0]\
+ "//dbs/" + cls.created_db.id + "/colls/" + cls.created_collection_id + "/docs/"
resource_id_or_fullname = "dbs/" + cls.created_db.id + "/colls/" + cls.created_collection_id
resource_type = "docs"
data = '{"id":"doc1"}'
headers['authorization'] = cls.get_authorization(cls.created_db.client_connection, verb,
resource_id_or_fullname, resource_type, headers)
response = requests_client.request(verb,
resource_url,
data=data,
headers=headers,
timeout=60,
stream=False,
verify=False)
data = response.content
data = data.decode('utf-8')
data = json.loads(data)
cls.created_document = data
@classmethod
def get_authorization(cls, client, verb, resource_id_or_fullname, resource_type, headers):
authorization = auth.GetAuthorizationHeader(
cosmos_client_connection=client,
verb=verb,
path='',
resource_id_or_fullname=resource_id_or_fullname,
is_name_based=True,
resource_type=resource_type,
headers=headers)
# urllib.quote throws when the input parameter is None
if authorization:
# -_.!~*'() are valid characters in url, and shouldn't be quoted.
authorization = urllib_quote(authorization, '-_.!~*\'()')
return authorization
def test_non_partitioned_collection_operations(self):
created_container = self.created_db.get_container_client(self.created_collection_id)
# Pass partitionKey.Empty as partition key to access documents from a single partition collection with v 2018-12-31 SDK
read_item = created_container.read_item(self.created_document['id'], partition_key=partition_key.NonePartitionKeyValue)
self.assertEqual(read_item['id'], self.created_document['id'])
document_definition = {'id': str(uuid.uuid4())}
created_item = created_container.create_item(body=document_definition)
self.assertEqual(created_item['id'], document_definition['id'])
read_item = created_container.read_item(created_item['id'], partition_key=partition_key.NonePartitionKeyValue)
self.assertEqual(read_item['id'], created_item['id'])
document_definition_for_replace = {'id': str(uuid.uuid4())}
replaced_item = created_container.replace_item(created_item['id'], body=document_definition_for_replace)
self.assertEqual(replaced_item['id'], document_definition_for_replace['id'])
upserted_item = created_container.upsert_item(body=document_definition)
self.assertEqual(upserted_item['id'], document_definition['id'])
# one document was created during setup, one with create (which was replaced) and one with upsert
items = list(created_container.query_items("SELECT * from c", partition_key=partition_key.NonePartitionKeyValue))
self.assertEqual(len(items), 3)
document_created_by_sproc_id = 'testDoc'
sproc = {
'id': 'storedProcedure' + str(uuid.uuid4()),
'body': (
'function () {' +
' var client = getContext().getCollection();' +
' var doc = client.createDocument(client.getSelfLink(), { id: \'' + document_created_by_sproc_id + '\'}, {}, function(err, docCreated, options) { ' +
' if(err) throw new Error(\'Error while creating document: \' + err.message);' +
' else {' +
' getContext().getResponse().setBody(1);' +
' }' +
' });}')
}
created_sproc = created_container.scripts.create_stored_procedure(body=sproc)
# Partiton Key value same as what is specified in the stored procedure body
result = created_container.scripts.execute_stored_procedure(sproc=created_sproc['id'], partition_key=partition_key.NonePartitionKeyValue)
self.assertEqual(result, 1)
# 3 previous items + 1 created from the sproc
items = list(created_container.read_all_items())
self.assertEqual(len(items), 4)
created_container.delete_item(upserted_item['id'], partition_key=partition_key.NonePartitionKeyValue)
created_container.delete_item(replaced_item['id'], partition_key=partition_key.NonePartitionKeyValue)
created_container.delete_item(document_created_by_sproc_id, partition_key=partition_key.NonePartitionKeyValue)
created_container.delete_item(self.created_document['id'], partition_key=partition_key.NonePartitionKeyValue)
items = list(created_container.read_all_items())
self.assertEqual(len(items), 0)
def test_multi_partition_collection_read_document_with_no_pk(self):
document_definition = {'id': str(uuid.uuid4())}
self.created_collection.create_item(body=document_definition)
read_item = self.created_collection.read_item(item=document_definition['id'], partition_key=partition_key.NonePartitionKeyValue)
self.assertEqual(read_item['id'], document_definition['id'])
self.created_collection.delete_item(item=document_definition['id'], partition_key=partition_key.NonePartitionKeyValue)
def test_hash_v2_partition_key_definition(self):
created_container = self.created_db.create_container(
id='container_with_pkd_v2' + str(uuid.uuid4()),
partition_key=partition_key.PartitionKey(path="/id", kind="Hash")
)
created_container_properties = created_container.read()
self.assertEqual(created_container_properties['partitionKey']['version'], 2)
self.created_db.delete_container(created_container)
created_container = self.created_db.create_container(
id='container_with_pkd_v2' + str(uuid.uuid4()),
partition_key=partition_key.PartitionKey(path="/id", kind="Hash", version=2)
)
created_container_properties = created_container.read()
self.assertEqual(created_container_properties['partitionKey']['version'], 2)
self.created_db.delete_container(created_container)
def test_hash_v1_partition_key_definition(self):
created_container = self.created_db.create_container(
id='container_with_pkd_v2' + str(uuid.uuid4()),
partition_key=partition_key.PartitionKey(path="/id", kind="Hash", version=1)
)
created_container_properties = created_container.read()
self.assertEqual(created_container_properties['partitionKey']['version'], 1)
self.created_db.delete_container(created_container)
| mit |
MrSim17/LaserCutterTools | GearBuilder/PointGeneratorRack.cs | 6557 | using System;
using System.Collections.Generic;
using System.Linq;
using LaserCutterTools.Common;
namespace LaserCutterTools.GearBuilder
{
// TODO: add interface for rack generation
internal sealed class PointGeneratorRack : IPointGeneratorRack
{
// TODO: Account for tool width
/// <summary>
///
/// </summary>
/// <param name="NumTeeth">Number of teeth on the rack. Determines the length of the rack.</param>
/// <param name="PressureAngle"></param>
/// <param name="circularPitch">Circumference of the pitch circle divided by the number of teeth.</param>
/// <param name="Backlash">Minimal distance between meshing gears.</param>
/// <param name="Clearance">Minimal distance between the apex of a tooth and the trough of the other gear.</param>
/// <param name="Addendum"></param>
/// <param name="SupportBarWidth">Thickness of the material attached to the rack teeth.</param>
/// <param name="SlotDepth">Depth of the slot.</param>
/// <param name="MaterialThickness">Thickness of the material used to make this part.</param>
/// <param name="ToolSpacing">Width of the tool used to cut this part.</param>
/// <returns></returns>
public List<PointDouble> CreateRackWithSlots(IMaterial Material, IMachineSettings MachineSettings, int NumTeeth, double PressureAngle, double circularPitch, double Backlash, double Clearance, double Addendum, double SupportBarWidth, double SlotDepth)
{
var tmpRack = CreateRack(NumTeeth, PressureAngle, circularPitch, Backlash, Clearance, Addendum, SupportBarWidth);
// add the slots
var dimension = HelperMethods.GetPolygonDimension(tmpRack);
// add slot one .5 inches from the bottom
var slotOne = HelperMethods.TranslatePolygon(0, dimension.Y - 0.5, CreateSlot(SlotDepth, (double)MachineSettings.ToolSpacing, (double) Material.MaterialThickness));
tmpRack.InsertRange(tmpRack.Count - 1, slotOne);
// add slot two .5 inches from the top
var slotTwo = HelperMethods.TranslatePolygon(0, 0.5, CreateSlot(SlotDepth, (double)MachineSettings.ToolSpacing, (double)Material.MaterialThickness));
tmpRack.InsertRange(tmpRack.Count - 1, slotTwo);
return tmpRack;
}
/// <summary>
///
/// </summary>
/// <param name="NumTeeth">Number of teeth on the rack. Determines the length of the rack.</param>
/// <param name="PressureAngle"></param>
/// <param name="circularPitch">Circumference of the pitch circle divided by the number of teeth.</param>
/// <param name="Backlash">Minimal distance between meshing gears.</param>
/// <param name="Clearance">Minimal distance between the apex of a tooth and the trough of the other gear.</param>
/// <param name="Addendum"></param>
/// <param name="SupportBarWidth">Thickness of the material attached to the rack teeth.</param>
/// <returns></returns>
public List<PointDouble> CreateRack(int NumTeeth, double PressureAngle, double circularPitch, double Backlash, double Clearance, double Addendum, double SupportBarWidth)
{
List<PointDouble> rack = new List<PointDouble>();
var protoTooth = createRackTooth(PressureAngle, circularPitch, Clearance, Backlash, Addendum);
// we draw one tooth in the middle and then five on either side
for (var i = 0; i < NumTeeth; i++)
{
// TODO: Get rid of this drawing on both sides of the midpoint
var tooth = HelperMethods.TranslatePolygon(0, (0.5 + -NumTeeth / 2 + i) * circularPitch, protoTooth);
rack.AddRange(tooth);
}
// creating the bar backing the teeth
var rightX = -(Addendum + Clearance);
var width = 4 * Addendum;
var halfHeight = NumTeeth * circularPitch / 2;
// Create the supporting bar to hold the teeth
var firstPoint = rack.First();
var lastPoint = rack.Last();
rack.Add(new PointDouble(lastPoint.X - SupportBarWidth, lastPoint.Y));
rack.Add(new PointDouble(firstPoint.X - SupportBarWidth, firstPoint.Y));
// move part to quadrant 1
// TODO: This may be unnecessary if the above loop is fixed. A bit of amasking of strange calculations above.
return HelperMethods.MovePolygonToQuadrantOne(rack);
}
private static List<PointDouble> CreateSlot(double SlotDepth, double ToolSpacing, double MaterialThickness)
{
// NOTE: Adjusting for tool spacing on the slot but nowhere else
var slot = new List<PointDouble>
{
new PointDouble(0, MaterialThickness - ToolSpacing),
new PointDouble(SlotDepth -ToolSpacing, MaterialThickness - ToolSpacing),
new PointDouble(SlotDepth - ToolSpacing, 0),
new PointDouble(0, 0)
};
return slot;
}
private static List<PointDouble> createRackTooth(double PressureAngle, double CircularPitch, double Clearance, double Backlash, double Addendum)
{
var toothWidth = CircularPitch / 2;
var toothDepth = Addendum + Clearance;
var sinPressureAngle = Math.Sin(PressureAngle * Math.PI / 180);
var cosPressureAngle = Math.Cos(PressureAngle * Math.PI / 180);
// if a positive backlash is defined then we widen the trapezoid accordingly.
// Each side of the tooth needs to widened by a fourth of the backlash (vertical to cutter faces).
var dx = Backlash / 4 / cosPressureAngle;
var leftDepth = Addendum + Clearance;
var upperLeftCorner = new PointDouble(-leftDepth, toothWidth / 2 - dx + (Addendum + Clearance) * sinPressureAngle);
var upperRightCorner = new PointDouble(Addendum, toothWidth / 2 - dx - Addendum * sinPressureAngle);
var lowerRightCorner = new PointDouble(upperRightCorner.X, -upperRightCorner.Y);
var lowerLeftCorner = new PointDouble(upperLeftCorner.X, -upperLeftCorner.Y);
//return new List<PointDouble>() { upperLeftCorner, upperRightCorner, lowerRightCorner, lowerLeftCorner };
return new List<PointDouble>() { lowerLeftCorner, lowerRightCorner, upperRightCorner, upperLeftCorner };
}
}
} | mit |
ganjitoka/podcoin | src/rpcdump.cpp | 2957 | // Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include <boost/lexical_cast.hpp>
#define printf OutputDebugStringF
using namespace json_spirit;
using namespace std;
class CTxDump
{
public:
CBlockIndex *pindex;
int64 nValue;
bool fSpent;
CWalletTx* ptx;
int nOut;
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
{
pindex = NULL;
nValue = 0;
fSpent = false;
this->ptx = ptx;
this->nOut = nOut;
}
};
Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importprivkey <podcoinprivkey> [label] [rescan=true]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (params.size() > 2)
fRescan = params[2].get_bool();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
CKeyID vchAddress = key.GetPubKey().GetID();
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
if (!pwalletMain->AddKey(key))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
if (fRescan) {
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
}
return Value::null;
}
Value dumpprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <podcoinaddress>\n"
"Reveals the private key corresponding to <podcoinaddress>.");
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PODCOIN address");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CSecret vchSecret;
bool fCompressed;
if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret, fCompressed).ToString();
}
| mit |
storlihoel/tomteportalen | craft/app/services/SectionsService.php | 31166 | <?php
namespace Craft;
/**
* Class SectionsService
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @copyright Copyright (c) 2014, Pixel & Tonic, Inc.
* @license http://buildwithcraft.com/license Craft License Agreement
* @see http://buildwithcraft.com
* @package craft.app.services
* @since 1.0
*/
class SectionsService extends BaseApplicationComponent
{
// Properties
// =========================================================================
/**
* @var
*/
public $typeLimits;
/**
* @var
*/
private $_allSectionIds;
/**
* @var
*/
private $_editableSectionIds;
/**
* @var
*/
private $_sectionsById;
/**
* @var bool
*/
private $_fetchedAllSections = false;
/**
* @var
*/
private $_entryTypesById;
// Public Methods
// =========================================================================
// Sections
// -------------------------------------------------------------------------
/**
* Returns all of the section IDs.
*
* @return array All the sections’ IDs.
*/
public function getAllSectionIds()
{
if (!isset($this->_allSectionIds))
{
$this->_allSectionIds = array();
foreach ($this->getAllSections() as $section)
{
$this->_allSectionIds[] = $section->id;
}
}
return $this->_allSectionIds;
}
/**
* Returns all of the section IDs that are editable by the current user.
*
* @return array All the editable sections’ IDs.
*/
public function getEditableSectionIds()
{
if (!isset($this->_editableSectionIds))
{
$this->_editableSectionIds = array();
foreach ($this->getAllSectionIds() as $sectionId)
{
if (craft()->userSession->checkPermission('editEntries:'.$sectionId))
{
$this->_editableSectionIds[] = $sectionId;
}
}
}
return $this->_editableSectionIds;
}
/**
* Returns all sections.
*
* @param string|null $indexBy
*
* @return SectionModel[] All the sections.
*/
public function getAllSections($indexBy = null)
{
if (!$this->_fetchedAllSections)
{
$results = $this->_createSectionQuery()
->queryAll();
$this->_sectionsById = array();
$typeCounts = array(
SectionType::Single => 0,
SectionType::Channel => 0,
SectionType::Structure => 0
);
foreach ($results as $result)
{
$type = $result['type'];
if (craft()->getEdition() >= Craft::Client || $typeCounts[$type] < $this->typeLimits[$type])
{
$section = new SectionModel($result);
$this->_sectionsById[$section->id] = $section;
$typeCounts[$type]++;
}
}
$this->_fetchedAllSections = true;
}
if ($indexBy == 'id')
{
$sections = $this->_sectionsById;
}
else if (!$indexBy)
{
$sections = array_values($this->_sectionsById);
}
else
{
$sections = array();
foreach ($this->_sectionsById as $section)
{
$sections[$section->$indexBy] = $section;
}
}
return $sections;
}
/**
* Returns all editable sections.
*
* @param string|null $indexBy
*
* @return SectionModel[] All the editable sections.
*/
public function getEditableSections($indexBy = null)
{
$editableSectionIds = $this->getEditableSectionIds();
$editableSections = array();
foreach ($this->getAllSections() as $section)
{
if (in_array($section->id, $editableSectionIds))
{
if ($indexBy)
{
$editableSections[$section->$indexBy] = $section;
}
else
{
$editableSections[] = $section;
}
}
}
return $editableSections;
}
/**
* Returns all sections of a given type.
*
* @param string $type
*
* @return SectionModel[] All the sections of the given type.
*/
public function getSectionsByType($type)
{
$sections = array();
foreach ($this->getAllSections() as $section)
{
if ($section->type == $type)
{
$sections[] = $section;
}
}
return $sections;
}
/**
* Gets the total number of sections.
*
* @return int
*/
public function getTotalSections()
{
return count($this->getAllSectionIds());
}
/**
* Gets the total number of sections that are editable by the current user.
*
* @return int
*/
public function getTotalEditableSections()
{
return count($this->getEditableSectionIds());
}
/**
* Returns a section by its ID.
*
* @param int $sectionId
*
* @return SectionModel|null
*/
public function getSectionById($sectionId)
{
// If we've already fetched all sections we can save ourselves a trip to the DB for section IDs that don't exist
if (!$this->_fetchedAllSections &&
(!isset($this->_sectionsById) || !array_key_exists($sectionId, $this->_sectionsById))
)
{
$result = $this->_createSectionQuery()
->where('sections.id = :sectionId', array(':sectionId' => $sectionId))
->queryRow();
if ($result)
{
$section = new SectionModel($result);
}
else
{
$section = null;
}
$this->_sectionsById[$sectionId] = $section;
}
if (isset($this->_sectionsById[$sectionId]))
{
return $this->_sectionsById[$sectionId];
}
}
/**
* Gets a section by its handle.
*
* @param string $sectionHandle
*
* @return SectionModel|null
*/
public function getSectionByHandle($sectionHandle)
{
$result = $this->_createSectionQuery()
->where('sections.handle = :sectionHandle', array(':sectionHandle' => $sectionHandle))
->queryRow();
if ($result)
{
$section = new SectionModel($result);
$this->_sectionsById[$section->id] = $section;
return $section;
}
}
/**
* Returns a section’s locales.
*
* @param int $sectionId
* @param string|null $indexBy
*
* @return SectionLocaleModel[] The section’s locales.
*/
public function getSectionLocales($sectionId, $indexBy = null)
{
$records = craft()->db->createCommand()
->select('*')
->from('sections_i18n sections_i18n')
->join('locales locales', 'locales.locale = sections_i18n.locale')
->where('sections_i18n.sectionId = :sectionId', array(':sectionId' => $sectionId))
->order('locales.sortOrder')
->queryAll();
return SectionLocaleModel::populateModels($records, $indexBy);
}
/**
* Saves a section.
*
* @param SectionModel $section
*
* @throws \Exception
* @return bool
*/
public function saveSection(SectionModel $section)
{
if ($section->id)
{
$sectionRecord = SectionRecord::model()->with('structure')->findById($section->id);
if (!$sectionRecord)
{
throw new Exception(Craft::t('No section exists with the ID “{id}”.', array('id' => $section->id)));
}
$oldSection = SectionModel::populateModel($sectionRecord);
$isNewSection = false;
}
else
{
$sectionRecord = new SectionRecord();
$isNewSection = true;
}
// Shared attributes
$sectionRecord->name = $section->name;
$sectionRecord->handle = $section->handle;
$sectionRecord->type = $section->type;
$sectionRecord->enableVersioning = $section->enableVersioning;
if (($isNewSection || $section->type != $oldSection->type) && !$this->canHaveMore($section->type))
{
$section->addError('type', Craft::t('You can’t add any more {type} sections.', array('type' => Craft::t(ucfirst($section->type)))));
}
// Type-specific attributes
if ($section->type == SectionType::Single)
{
$sectionRecord->hasUrls = $section->hasUrls = true;
}
else
{
$sectionRecord->hasUrls = $section->hasUrls;
}
if ($section->hasUrls)
{
$sectionRecord->template = $section->template;
}
else
{
$sectionRecord->template = $section->template = null;
}
$sectionRecord->validate();
$section->addErrors($sectionRecord->getErrors());
// Make sure that all of the URL formats are set properly
$sectionLocales = $section->getLocales();
if (!$sectionLocales)
{
$section->addError('localeErrors', Craft::t('At least one locale must be selected for the section.'));
}
foreach ($sectionLocales as $localeId => $sectionLocale)
{
if ($section->type == SectionType::Single)
{
$errorKey = 'urlFormat-'.$localeId;
if (empty($sectionLocale->urlFormat))
{
$section->addError($errorKey, Craft::t('URI cannot be blank.'));
}
else if ($section)
{
// Make sure no other elements are using this URI already
$query = craft()->db->createCommand()
->from('elements_i18n elements_i18n')
->where(
array('and', 'elements_i18n.locale = :locale', 'elements_i18n.uri = :uri'),
array(':locale' => $localeId, ':uri' => $sectionLocale->urlFormat)
);
if ($section->id)
{
$query->join('entries entries', 'entries.id = elements_i18n.elementId')
->andWhere('entries.sectionId != :sectionId', array(':sectionId' => $section->id));
}
$count = $query->count('elements_i18n.id');
if ($count)
{
$section->addError($errorKey, Craft::t('This URI is already in use.'));
}
}
$sectionLocale->nestedUrlFormat = null;
}
else if ($section->hasUrls)
{
$urlFormatAttributes = array('urlFormat');
$sectionLocale->urlFormatIsRequired = true;
if ($section->type == SectionType::Structure && $section->maxLevels != 1)
{
$urlFormatAttributes[] = 'nestedUrlFormat';
$sectionLocale->nestedUrlFormatIsRequired = true;
}
else
{
$sectionLocale->nestedUrlFormat = null;
}
foreach ($urlFormatAttributes as $attribute)
{
if (!$sectionLocale->validate(array($attribute)))
{
$section->addError($attribute.'-'.$localeId, $sectionLocale->getError($attribute));
}
}
}
else
{
$sectionLocale->urlFormat = null;
$sectionLocale->nestedUrlFormat = null;
}
}
if (!$section->hasErrors())
{
$transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
try
{
// Fire an 'onBeforeSaveSection' event
$event = new Event($this, array(
'section' => $section,
'isNewSection' => $isNewSection,
));
$this->onBeforeSaveSection($event);
// Is the event giving us the go-ahead?
if ($event->performAction)
{
// Do we need to create a structure?
if ($section->type == SectionType::Structure)
{
if (!$isNewSection && $oldSection->type == SectionType::Structure)
{
$structure = craft()->structures->getStructureById($oldSection->structureId);
$isNewStructure = false;
}
if (empty($structure))
{
$structure = new StructureModel();
$isNewStructure = true;
}
$structure->maxLevels = $section->maxLevels;
craft()->structures->saveStructure($structure);
$sectionRecord->structureId = $structure->id;
$section->structureId = $structure->id;
}
else
{
if (!$isNewSection && $oldSection->structureId)
{
// Delete the old one
craft()->structures->deleteStructureById($oldSection->structureId);
$sectionRecord->structureId = null;
}
}
$sectionRecord->save(false);
// Now that we have a section ID, save it on the model
if ($isNewSection)
{
$section->id = $sectionRecord->id;
}
// Might as well update our cache of the section while we have it. (It's possible that the URL format
//includes {section.handle} or something...)
$this->_sectionsById[$section->id] = $section;
// Update the sections_i18n table
$newLocaleData = array();
if (!$isNewSection)
{
// Get the old section locales
$oldSectionLocaleRecords = SectionLocaleRecord::model()->findAllByAttributes(array(
'sectionId' => $section->id
));
$oldSectionLocales = SectionLocaleModel::populateModels($oldSectionLocaleRecords, 'locale');
}
foreach ($sectionLocales as $localeId => $locale)
{
// Was this already selected?
if (!$isNewSection && isset($oldSectionLocales[$localeId]))
{
$oldLocale = $oldSectionLocales[$localeId];
// Has anything changed?
if ($locale->enabledByDefault != $oldLocale->enabledByDefault || $locale->urlFormat != $oldLocale->urlFormat || $locale->nestedUrlFormat != $oldLocale->nestedUrlFormat)
{
craft()->db->createCommand()->update('sections_i18n', array(
'enabledByDefault' => (int)$locale->enabledByDefault,
'urlFormat' => $locale->urlFormat,
'nestedUrlFormat' => $locale->nestedUrlFormat
), array(
'id' => $oldLocale->id
));
}
}
else
{
$newLocaleData[] = array($section->id, $localeId, (int)$locale->enabledByDefault, $locale->urlFormat, $locale->nestedUrlFormat);
}
}
// Insert the new locales
craft()->db->createCommand()->insertAll('sections_i18n',
array('sectionId', 'locale', 'enabledByDefault', 'urlFormat', 'nestedUrlFormat'),
$newLocaleData
);
if (!$isNewSection)
{
// Drop any locales that are no longer being used, as well as the associated entry/element locale
// rows
$droppedLocaleIds = array_diff(array_keys($oldSectionLocales), array_keys($sectionLocales));
if ($droppedLocaleIds)
{
craft()->db->createCommand()->delete('sections_i18n',
array('and', 'sectionId = :sectionId', array('in', 'locale', $droppedLocaleIds)),
array(':sectionId' => $section->id)
);
}
}
// Make sure there's at least one entry type for this section
$entryTypeId = null;
if (!$isNewSection)
{
// Let's grab all of the entry type IDs to save ourselves a query down the road if this is a Single
$entryTypeIds = craft()->db->createCommand()
->select('id')
->from('entrytypes')
->where('sectionId = :sectionId', array(':sectionId' => $section->id))
->queryColumn();
if ($entryTypeIds)
{
$entryTypeId = array_shift($entryTypeIds);
}
}
if (!$entryTypeId)
{
$entryType = new EntryTypeModel();
$entryType->sectionId = $section->id;
$entryType->name = $section->name;
$entryType->handle = $section->handle;
if ($section->type == SectionType::Single)
{
$entryType->hasTitleField = false;
$entryType->titleLabel = null;
$entryType->titleFormat = '{section.name|raw}';
}
else
{
$entryType->hasTitleField = true;
$entryType->titleLabel = Craft::t('Title');
$entryType->titleFormat = null;
}
$this->saveEntryType($entryType);
$entryTypeId = $entryType->id;
}
// Now, regardless of whether the section type changed or not, let the section type make sure
// everything is cool
switch ($section->type)
{
case SectionType::Single:
{
// Make sure that there is one and only one Entry Type and Entry for this section.
$singleEntryId = null;
if (!$isNewSection)
{
// Make sure there's only one entry in this section
$entryIds = craft()->db->createCommand()
->select('id')
->from('entries')
->where('sectionId = :sectionId', array(':sectionId' => $section->id))
->queryColumn();
if ($entryIds)
{
$singleEntryId = array_shift($entryIds);
// If there are any more, get rid of them
if ($entryIds)
{
craft()->elements->deleteElementById($entryIds);
}
// Make sure it's enabled and all that.
craft()->db->createCommand()->update('elements', array(
'enabled' => 1,
'archived' => 0,
), array(
'id' => $singleEntryId
));
craft()->db->createCommand()->update('entries', array(
'typeId' => $entryTypeId,
'authorId' => null,
'postDate' => DateTimeHelper::currentTimeForDb(),
'expiryDate' => null,
), array(
'id' => $singleEntryId
));
}
// Make sure there's only one entry type for this section
if ($entryTypeIds)
{
$this->deleteEntryTypeById($entryTypeIds);
}
}
if (!$singleEntryId)
{
// Create it, baby
$singleEntry = new EntryModel();
$singleEntry->sectionId = $section->id;
$singleEntry->typeId = $entryTypeId;
$singleEntry->getContent()->title = $section->name;
craft()->entries->saveEntry($singleEntry);
}
break;
}
case SectionType::Structure:
{
if (!$isNewSection && $isNewStructure)
{
// Add all of the entries to the structure
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->locale = array_shift(array_keys($oldSectionLocales));
$criteria->sectionId = $section->id;
$criteria->status = null;
$criteria->localeEnabled = null;
$criteria->order = 'elements.id';
$criteria->limit = 25;
do
{
$batchEntries = $criteria->find();
foreach ($batchEntries as $entry)
{
craft()->structures->appendToRoot($section->structureId, $entry, 'insert');
}
$criteria->offset += 25;
} while ($batchEntries);
}
break;
}
}
// Finally, deal with the existing entries...
if (!$isNewSection)
{
$criteria = craft()->elements->getCriteria(ElementType::Entry);
// Get the most-primary locale that this section was already enabled in
$locales = array_values(array_intersect(craft()->i18n->getSiteLocaleIds(), array_keys($oldSectionLocales)));
if ($locales)
{
$criteria->locale = $locales[0];
$criteria->sectionId = $section->id;
$criteria->status = null;
$criteria->localeEnabled = null;
$criteria->limit = null;
craft()->tasks->createTask('ResaveElements', Craft::t('Resaving {section} entries', array('section' => $section->name)), array(
'elementType' => ElementType::Entry,
'criteria' => $criteria->getAttributes()
));
}
}
$success = true;
}
else
{
$success = false;
}
// Commit the transaction regardless of whether we saved the section, in case something changed
// in onBeforeSaveSection
if ($transaction !== null)
{
$transaction->commit();
}
} catch (\Exception $e)
{
if ($transaction !== null)
{
$transaction->rollback();
}
throw $e;
}
}
else
{
$success = false;
}
if ($success)
{
// Fire an 'onSaveSection' event
$this->onSaveSection(new Event($this, array(
'section' => $section,
'isNewSection' => $isNewSection,
)));
}
return $success;
}
/**
* Deletes a section by its ID.
*
* @param int $sectionId
*
* @throws \Exception
* @return bool
*/
public function deleteSectionById($sectionId)
{
if (!$sectionId)
{
return false;
}
// Fire an 'onBeforeDeleteSection' event
$event = new Event($this, array(
'sectionId' => $sectionId
));
$this->onBeforeDeleteSection($event);
if ($event->performAction)
{
$transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
try
{
// Grab the entry ids so we can clean the elements table.
$entryIds = craft()->db->createCommand()
->select('id')
->from('entries')
->where(array('sectionId' => $sectionId))
->queryColumn();
craft()->elements->deleteElementById($entryIds);
// Delete the structure, if there is one
$structureId = craft()->db->createCommand()
->select('structureId')
->from('sections')
->where(array('id' => $sectionId))
->queryScalar();
if ($structureId)
{
craft()->structures->deleteStructureById($structureId);
}
// Delete the section.
$affectedRows = craft()->db->createCommand()->delete('sections', array('id' => $sectionId));
if ($transaction !== null)
{
$transaction->commit();
}
// Fire an 'onDeleteSection' event
$this->onDeleteSection(new Event($this, array(
'sectionId' => $sectionId
)));
return (bool)$affectedRows;
}
catch (\Exception $e)
{
if ($transaction !== null)
{
$transaction->rollback();
}
throw $e;
}
}
}
/**
* Returns whether a section’s entries have URLs, and if the section’s template path is valid.
*
* @param SectionModel $section
*
* @return bool
*/
public function isSectionTemplateValid(SectionModel $section)
{
if ($section->hasUrls)
{
// Set Craft to the site template path
$oldTemplatesPath = craft()->path->getTemplatesPath();
craft()->path->setTemplatesPath(craft()->path->getSiteTemplatesPath());
// Does the template exist?
$templateExists = craft()->templates->doesTemplateExist($section->template);
// Restore the original template path
craft()->path->setTemplatesPath($oldTemplatesPath);
if ($templateExists)
{
return true;
}
}
return false;
}
// Entry Types
// -------------------------------------------------------------------------
/**
* Returns a section’s entry types.
*
* @param int $sectionId
* @param string|null $indexBy
*
* @return array
*/
public function getEntryTypesBySectionId($sectionId, $indexBy = null)
{
$records = EntryTypeRecord::model()->ordered()->findAllByAttributes(array(
'sectionId' => $sectionId
));
return EntryTypeModel::populateModels($records, $indexBy);
}
/**
* Returns an entry type by its ID.
*
* @param int $entryTypeId
*
* @return EntryTypeModel|null
*/
public function getEntryTypeById($entryTypeId)
{
if (!isset($this->_entryTypesById) || !array_key_exists($entryTypeId, $this->_entryTypesById))
{
$entryTypeRecord = EntryTypeRecord::model()->findById($entryTypeId);
if ($entryTypeRecord)
{
$this->_entryTypesById[$entryTypeId] = EntryTypeModel::populateModel($entryTypeRecord);
}
else
{
$this->_entryTypesById[$entryTypeId] = null;
}
}
return $this->_entryTypesById[$entryTypeId];
}
/**
* Returns entry types that have a given handle.
*
* @param int $entryTypeHandle
*
* @return array
*/
public function getEntryTypesByHandle($entryTypeHandle)
{
$entryTypeRecords = EntryTypeRecord::model()->findAllByAttributes(array(
'handle' => $entryTypeHandle
));
return EntryTypeModel::populateModels($entryTypeRecords);
}
/**
* Saves an entry type.
*
* @param EntryTypeModel $entryType
*
* @throws Exception
* @throws \CDbException
* @throws \Exception
* @return bool
*/
public function saveEntryType(EntryTypeModel $entryType)
{
if ($entryType->id)
{
$entryTypeRecord = EntryTypeRecord::model()->findById($entryType->id);
if (!$entryTypeRecord)
{
throw new Exception(Craft::t('No entry type exists with the ID “{id}”.', array('id' => $entryType->id)));
}
$isNewEntryType = false;
$oldEntryType = EntryTypeModel::populateModel($entryTypeRecord);
}
else
{
$entryTypeRecord = new EntryTypeRecord();
$isNewEntryType = true;
}
$entryTypeRecord->sectionId = $entryType->sectionId;
$entryTypeRecord->name = $entryType->name;
$entryTypeRecord->handle = $entryType->handle;
$entryTypeRecord->hasTitleField = $entryType->hasTitleField;
$entryTypeRecord->titleLabel = ($entryType->hasTitleField ? $entryType->titleLabel : null);
$entryTypeRecord->titleFormat = (!$entryType->hasTitleField ? $entryType->titleFormat : null);
$entryTypeRecord->validate();
$entryType->addErrors($entryTypeRecord->getErrors());
if (!$entryType->hasErrors())
{
$transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
try
{
// Fire an 'onBeforeSaveEntryType' event
$event = new Event($this, array(
'entryType' => $entryType,
'isNewEntryType' => $isNewEntryType
));
$this->onBeforeSaveEntryType($event);
// Is the event giving us the go-ahead?
if ($event->performAction)
{
if (!$isNewEntryType && $oldEntryType->fieldLayoutId)
{
// Drop the old field layout
craft()->fields->deleteLayoutById($oldEntryType->fieldLayoutId);
}
// Save the new one
$fieldLayout = $entryType->getFieldLayout();
craft()->fields->saveLayout($fieldLayout);
// Update the entry type record/model with the new layout ID
$entryType->fieldLayoutId = $fieldLayout->id;
$entryTypeRecord->fieldLayoutId = $fieldLayout->id;
$entryTypeRecord->save(false);
// Now that we have an entry type ID, save it on the model
if (!$entryType->id)
{
$entryType->id = $entryTypeRecord->id;
}
// Might as well update our cache of the entry type while we have it.
$this->_entryTypesById[$entryType->id] = $entryType;
$success = true;
}
else
{
$success = false;
}
// Commit the transaction regardless of whether we saved the user, in case something changed
// in onBeforeSaveEntryType
if ($transaction !== null)
{
$transaction->commit();
}
} catch (\Exception $e)
{
if ($transaction !== null)
{
$transaction->rollback();
}
throw $e;
}
}
else
{
$success = false;
}
if ($success)
{
// Fire an 'onSaveEntryType' event
$this->onSaveEntryType(new Event($this, array(
'entryType' => $entryType,
'isNewEntryType' => $isNewEntryType
)));
}
return $success;
}
/**
* Reorders entry types.
*
* @param array $entryTypeIds
*
* @throws \Exception
* @return bool
*/
public function reorderEntryTypes($entryTypeIds)
{
$transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
try
{
foreach ($entryTypeIds as $entryTypeOrder => $entryTypeId)
{
$entryTypeRecord = EntryTypeRecord::model()->findById($entryTypeId);
$entryTypeRecord->sortOrder = $entryTypeOrder+1;
$entryTypeRecord->save();
}
if ($transaction !== null)
{
$transaction->commit();
}
}
catch (\Exception $e)
{
if ($transaction !== null)
{
$transaction->rollback();
}
throw $e;
}
return true;
}
/**
* Deletes an entry type(s) by its ID.
*
* @param int|array $entryTypeId
*
* @throws \Exception
* @return bool
*/
public function deleteEntryTypeById($entryTypeId)
{
if (!$entryTypeId)
{
return false;
}
$transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
try
{
// Delete the field layout
$query = craft()->db->createCommand()
->select('fieldLayoutId')
->from('entrytypes');
if (is_array($entryTypeId))
{
$query->where(array('in', 'id', $entryTypeId));
}
else
{
$query->where(array('id' => $entryTypeId));
}
$fieldLayoutIds = $query->queryColumn();
if ($fieldLayoutIds)
{
craft()->fields->deleteLayoutById($fieldLayoutIds);
}
// Grab the entry IDs so we can clean the elements table.
$query = craft()->db->createCommand()
->select('id')
->from('entries');
if (is_array($entryTypeId))
{
$query->where(array('in', 'typeId', $entryTypeId));
}
else
{
$query->where(array('typeId' => $entryTypeId));
}
$entryIds = $query->queryColumn();
craft()->elements->deleteElementById($entryIds);
// Delete the entry type.
if (is_array($entryTypeId))
{
$affectedRows = craft()->db->createCommand()->delete('entrytypes', array('in', 'id', $entryTypeId));
}
else
{
$affectedRows = craft()->db->createCommand()->delete('entrytypes', array('id' => $entryTypeId));
}
if ($transaction !== null)
{
$transaction->commit();
}
return (bool) $affectedRows;
}
catch (\Exception $e)
{
if ($transaction !== null)
{
$transaction->rollback();
}
throw $e;
}
}
// Helpers
// -------------------------------------------------------------------------
/**
* Returns whether a homepage section exists.
*
* @return bool
*/
public function doesHomepageExist()
{
$conditions = array('and', 'sections.type = :type', 'sections_i18n.urlFormat = :homeUri');
$params = array(':type' => SectionType::Single, ':homeUri' => '__home__');
$count = craft()->db->createCommand()
->from('sections sections')
->join('sections_i18n sections_i18n', 'sections_i18n.sectionId = sections.id')
->where($conditions, $params)
->count('sections.id');
return (bool) $count;
}
/**
* Returns whether another section can be added of a given type.
*
* @param string $type
*
* @return bool
*/
public function canHaveMore($type)
{
if (craft()->getEdition() >= Craft::Client)
{
return true;
}
else
{
if (isset($this->typeLimits[$type]))
{
$count = craft()->db->createCommand()
->from('sections')
->where('type = :type', array(':type' => $type))
->count('id');
return $count < $this->typeLimits[$type];
}
else
{
return false;
}
}
}
// Events
// -------------------------------------------------------------------------
/**
* Fires an 'onBeforeSaveEntryType' event.
*
* @param Event $event
*
* @return null
*/
public function onBeforeSaveEntryType(Event $event)
{
$this->raiseEvent('onBeforeSaveEntryType', $event);
}
/**
* Fires an 'onSaveEntryType' event.
*
* @param Event $event
*
* @return null
*/
public function onSaveEntryType(Event $event)
{
$this->raiseEvent('onSaveEntryType', $event);
}
/**
* Fires an 'onBeforeSaveSection' event.
*
* @param Event $event
*
* @return null
*/
public function onBeforeSaveSection(Event $event)
{
$this->raiseEvent('onBeforeSaveSection', $event);
}
/**
* Fires an 'onSaveSection' event.
*
* @param Event $event
*
* @return null
*/
public function onSaveSection(Event $event)
{
$this->raiseEvent('onSaveSection', $event);
}
/**
* Fires an 'onBeforeDeleteSection' event.
*
* @param Event $event
*
* @return null
*/
public function onBeforeDeleteSection(Event $event)
{
$this->raiseEvent('onBeforeDeleteSection', $event);
}
/**
* Fires an 'onDeleteSection' event.
*
* @param Event $event
*
* @return null
*/
public function onDeleteSection(Event $event)
{
$this->raiseEvent('onDeleteSection', $event);
}
// Private Methods
// =========================================================================
/**
* Returns a DbCommand object prepped for retrieving sections.
*
* @return DbCommand
*/
private function _createSectionQuery()
{
return craft()->db->createCommand()
->select('sections.id, sections.structureId, sections.name, sections.handle, sections.type, sections.hasUrls, sections.template, sections.enableVersioning, structures.maxLevels')
->leftJoin('structures structures', 'structures.id = sections.structureId')
->from('sections sections')
->order('name');
}
}
| mit |
piouPiouM/livre-sass-compass-avance | ch06/ch06-002/config.rb | 146 | css_dir = "css"
sass_dir = "sass"
images_dir = "img"
javascripts_dir = "js"
relative_assets = true
output_style = :expanded
line_comments = false
| mit |
bbyars/mountebank | mbTest/api/tcp/tcpStubTest.js | 8586 | 'use strict';
const assert = require('assert'),
api = require('../../api').create(),
port = api.port + 1,
isWindows = require('os').platform().indexOf('win') === 0,
timeout = isWindows ? 10000 : parseInt(process.env.MB_SLOW_TEST_TIMEOUT || 2000),
tcp = require('./tcpClient'),
airplaneMode = process.env.MB_AIRPLANE_MODE === 'true';
describe('tcp imposter', function () {
this.timeout(timeout);
afterEach(async function () {
await api.del('/imposters');
});
describe('POST /imposters with stubs', function () {
it('should return stubbed response', async function () {
const stub = {
predicates: [{ equals: { data: 'client' } }],
responses: [{ is: { data: 'server' } }]
},
request = { protocol: 'tcp', port, stubs: [stub], mode: 'text' };
await api.createImposter(request);
const response = await tcp.send('client', port);
assert.strictEqual(response.toString(), 'server');
});
it('should allow binary stub responses', async function () {
const buffer = Buffer.from([0, 1, 2, 3]),
stub = { responses: [{ is: { data: buffer.toString('base64') } }] },
request = { protocol: 'tcp', port, stubs: [stub], mode: 'binary' };
await api.createImposter(request);
const response = await tcp.send('0', port);
assert.ok(Buffer.isBuffer(response));
assert.deepEqual(response.toJSON().data, [0, 1, 2, 3]);
});
it('should allow a sequence of stubs as a circular buffer', async function () {
const stub = {
predicates: [{ equals: { data: 'request' } }],
responses: [{ is: { data: 'first' } }, { is: { data: 'second' } }]
},
request = { protocol: 'tcp', port, stubs: [stub] };
await api.createImposter(request);
const first = await tcp.send('request', port);
assert.strictEqual(first.toString(), 'first');
const second = await tcp.send('request', port);
assert.strictEqual(second.toString(), 'second');
const third = await tcp.send('request', port);
assert.strictEqual(third.toString(), 'first');
const fourth = await tcp.send('request', port);
assert.strictEqual(fourth.toString(), 'second');
});
it('should only return stubbed response if matches complex predicate', async function () {
const stub = {
responses: [{ is: { data: 'MATCH' } }],
predicates: [
{ equals: { data: 'test' } },
{ startsWith: { data: 'te' } }
]
},
request = { protocol: 'tcp', port, stubs: [stub] };
await api.createImposter(request);
const first = await tcp.send('not test', port, 100);
assert.strictEqual(first.toString(), '');
const second = await tcp.send('test', port, 250);
assert.strictEqual(second.toString(), 'MATCH');
});
it('should return 400 if uses matches predicate with binary mode', async function () {
const stub = {
responses: [{ is: { data: 'dGVzdA==' } }],
predicates: [{ matches: { data: 'dGVzdA==' } }]
},
request = { protocol: 'tcp', port, mode: 'binary', stubs: [stub] };
const response = await api.post('/imposters', request);
assert.strictEqual(response.statusCode, 400, JSON.stringify(response.body, null, 4));
assert.strictEqual(response.body.errors[0].message, 'the matches predicate is not allowed in binary mode');
});
it('should allow proxy stubs', async function () {
const proxyPort = port + 1,
proxyStub = { responses: [{ is: { data: 'PROXIED' } }] },
proxyRequest = { protocol: 'tcp', port: proxyPort, stubs: [proxyStub], name: 'PROXY' },
stub = { responses: [{ proxy: { to: `tcp://localhost:${proxyPort}` } }] },
request = { protocol: 'tcp', port, stubs: [stub], name: 'MAIN' };
await api.createImposter(proxyRequest);
await api.createImposter(request);
const response = await tcp.send('request', port);
assert.strictEqual(response.toString(), 'PROXIED');
});
it('should support old proxy syntax for backwards compatibility', async function () {
const proxyPort = port + 1,
proxyStub = { responses: [{ is: { data: 'PROXIED' } }] },
proxyRequest = { protocol: 'tcp', port: proxyPort, stubs: [proxyStub], name: 'PROXY' },
stub = { responses: [{ proxy: { to: { host: 'localhost', port: proxyPort } } }] },
request = { protocol: 'tcp', port, stubs: [stub], name: 'MAIN' };
await api.createImposter(proxyRequest);
await api.createImposter(request);
const response = await tcp.send('request', port);
assert.strictEqual(response.toString(), 'PROXIED');
});
it('should allow keepalive proxies', async function () {
const proxyPort = port + 1,
proxyStub = { responses: [{ is: { data: 'PROXIED' } }] },
proxyRequest = { protocol: 'tcp', port: proxyPort, stubs: [proxyStub], name: 'PROXY' },
stub = { responses: [{ proxy: { to: `tcp://localhost:${proxyPort}`, keepalive: true } }] },
request = { protocol: 'tcp', port, stubs: [stub], name: 'MAIN' };
await api.createImposter(proxyRequest);
await api.createImposter(request);
const first = await tcp.send('request', port);
assert.strictEqual(first.toString(), 'PROXIED');
const second = await tcp.send('request', port);
assert.strictEqual(second.toString(), 'PROXIED');
});
if (!airplaneMode) {
it('should allow proxy stubs to invalid hosts', async function () {
const stub = { responses: [{ proxy: { to: 'tcp://remotehost:8000' } }] },
request = { protocol: 'tcp', port, stubs: [stub] };
await api.createImposter(request);
const response = await tcp.send('request', port),
error = JSON.parse(response).errors[0];
assert.strictEqual(error.code, 'invalid proxy');
assert.strictEqual(error.message, 'Cannot resolve "tcp://remotehost:8000"');
});
}
it('should split each packet into a separate request by default', async function () {
// max 64k packet size, likely to hit max on the loopback interface
const largeRequest = `${new Array(65537).join('1')}2`,
stub = { responses: [{ is: { data: 'success' } }] },
request = {
protocol: 'tcp',
port,
stubs: [stub],
mode: 'text',
recordRequests: true
};
await api.createImposter(request);
await tcp.send(largeRequest, port);
const response = await api.get(`/imposters/${port}`),
requests = response.body.requests,
dataLength = requests.reduce((sum, recordedRequest) => sum + recordedRequest.data.length, 0);
assert.ok(requests.length > 1);
assert.strictEqual(65537, dataLength);
});
it('should support changing default response for stub', async function () {
const stub = {
responses: [{ is: { data: 'Given response' } }],
predicates: [{ equals: { data: 'MATCH ME' } }]
},
request = {
protocol: 'tcp',
mode: 'text',
port,
defaultResponse: { data: 'Default response' },
stubs: [stub]
};
await api.createImposter(request);
const first = await tcp.send('MATCH ME', port);
assert.strictEqual(first.toString(), 'Given response');
const second = await tcp.send('NO MATCH', port);
assert.strictEqual(second.toString(), 'Default response');
});
});
});
| mit |
phpManufaktur/kfConfirmationLog | Control/Backend/Report.php | 6778 | <?php
/**
* ConfirmationLog
*
* @author Team phpManufaktur <team@phpmanufaktur.de>
* @link https://kit2.phpmanufaktur.de/ConfirmationLog
* @copyright 2013 Ralf Hertsch <ralf.hertsch@phpmanufaktur.de>
* @license MIT License (MIT) http://www.opensource.org/licenses/MIT
*/
namespace phpManufaktur\ConfirmationLog\Control\Backend;
use phpManufaktur\ConfirmationLog\Data\Filter\Installations;
use phpManufaktur\ConfirmationLog\Data\Config;
use phpManufaktur\ConfirmationLog\Control\Filter\MissingConfirmation;
use phpManufaktur\ConfirmationLog\Data\Filter\Persons;
use phpManufaktur\ConfirmationLog\Data\Documents;
class Report extends Backend
{
public function controllerReport($app)
{
$this->initialize($app);
$ConfigurationData = new Config($app);
$config = $ConfigurationData->getConfiguration();
$active_filter = (isset($_POST['filter'])) ? $_POST['filter'] : -1;
$select_filter = array();
$select_filter[] = array(
'title' => $app['translator']->trans('- no selection -'),
'selected' => (int) ($active_filter == -1),
'value' => -1
);
// can be 'title' or 'name'
$use_group_by = null;
// the array with the missing confirmations
$missing = array();
// the group name (installation group or CMS user group)
$use_group = null;
// counter for the filter
$filter_counter = 0;
// filter type - needed by the template
$filter_type = null;
if ($config['filter']['installations']['active']) {
// the filter for the INSTALLATION_NAME is active
$Installations = new Installations($app);
if (false === ($installation_names = $Installations->getAllNamedInstallations())) {
// nothing to do - no installation_names!
$this->setMessage('There exists no installation names in the records which can be used for the reports!');
}
else {
// get all installation names to the configuration
$has_changed = false;
foreach ($installation_names as $installation_name) {
if (!in_array($installation_name, $config['filter']['installations']['groups']['installation_names'])) {
$config['filter']['installations']['groups']['installation_names'][] = $installation_name;
$has_changed = true;
}
}
if ($has_changed) {
$ConfigurationData->setConfiguration($config);
$ConfigurationData->saveConfiguration();
}
}
foreach ($config['filter']['installations']['groups'] as $group_name => $group) {
// loop through the installation groups defined in config.confirmation.json
foreach (array('title', 'name') as $group_by) {
// create the filter ID
$filter_id = sprintf('%d_%s', $filter_counter, $group_by);
if (false !== ($selected = ($filter_id == $active_filter))) {
// execute the filter for this ID
$MissingConfirmation = new MissingConfirmation($app);
$missing = $MissingConfirmation->missingGroups($group, $group_by);
$use_group_by = $group_by;
$use_group = $group;
$filter_type = 'installations';
}
$select_filter[] = array(
'title' => $app['translator']->trans('Group: %group_name%, group by: %group_by%',
array('%group_name%' => $app['translator']->trans($group_name),
'%group_by%' => $app['translator']->trans($group_by))),
'selected' => $selected,
'value' => $filter_id
);
}
$filter_counter++;
}
}
if ($config['filter']['persons']['active']) {
// filter for the PERSONS is active
$Persons = new Persons($app);
$groups = $Persons->getGroups();
foreach ($groups as $group) {
if (in_array($group['name'], $config['filter']['persons']['cms']['ignore_groups'])) {
// ignore this group
continue;
}
foreach (array('title', 'name') as $group_by) {
$filter_id = sprintf('%d_%s', $filter_counter, $group_by);
if (false !== ($selected = ($filter_id == $active_filter))) {
// execute the filter for this ID
$MissingConfirmation = new MissingConfirmation($app);
$missing = $MissingConfirmation->missingPersons($group['id'], $group_by,
$config['filter']['persons']['cms']['identifier']);
$use_group_by = $group_by;
$use_group = $group['name'];
$filter_type = 'persons';
}
$select_filter[] = array(
'title' => $app['translator']->trans('Persons: %group_name%, group by: %group_by%',
array('%group_name%' => $app['translator']->trans($group['name']),
'%group_by%' => $app['translator']->trans(($group_by == 'title') ? 'title' : 'person_name'))),
'selected' => $selected,
'value' => $filter_id
);
}
$filter_counter++;
}
}
if (($active_filter != -1) && empty($missing)) {
if (is_null($use_group)) {
$this->setMessage('No results for filter ID %filter_id%.', array('%filter_id%' => $active_filter));
}
else {
$this->setMessage('No results for the group %group%!', array('%group%' => $use_group));
}
}
return $this->app['twig']->render($this->app['utils']->getTemplateFile(
'@phpManufaktur/ConfirmationLog/Template', 'backend/report.twig'),
array(
'locale' => $app['translator']->getLocale(),
'usage' => self::$usage,
'message' => $this->getMessage(),
'toolbar' => $this->getToolbar('report'),
'select_filter' => $select_filter,
'group_by' => $use_group_by,
'missing' => $missing,
'filter' => $filter_type
));
}
}
| mit |
nverdhan/satticentre | scripts/pages/AddBookToLibrary.js | 6044 | import React, { Component, PropTypes } from 'react';
import { addons } from 'react/addons'
const ReactCSSTransitionGroup = addons.CSSTransitionGroup
import mui from 'material-ui';
// const ThemeManager = new mui.Styles.ThemeManager();
const ThemeManager = require('material-ui/lib/styles/theme-manager');
const { FloatingActionButton } = mui;
import Loading from '../components/Loading';
import * as BookActions from '../actions/BookActions';
import AddBookStore from '../stores/AddBookStore'
import injectTapEventPlugin from 'react-tap-event-plugin';
import connectToStores from '../utils/connectToStores';
import selectn from 'selectn';
import ExecutionEnvironment from 'react/lib/ExecutionEnvironment';
function getState(){
var book = AddBookStore.get();
var bookStatus = AddBookStore.getStatus();
var showLoading = AddBookStore.getLoadingStatus();
return {
book,
bookStatus,
showLoading
}
}
//Google Books API
//https://www.googleapis.com/books/v1/volumes?q=isbn13:9781405088831&key=AIzaSyB-RcG0iuq22z44pnqx3QDCQD38ErUFuRM
//Image
//https://books.google.com/books?id=A8bAPdi_TOAC&printsec=frontcover&img=2&zoom=2&edge=curl&source=gbs_api
/*
* Higher order Component
*/
class AnimatingElement extends Component{
constructor(props){
super(props);
this.state = {
style : {
left : '-110px',
bottom : '-100px',
}
}
}
componentWillReceiveProps(nextProps){
if(nextProps.animation == 'enter'){
this.enter()
}else{
this.leave()
}
}
leave(){
console.log(88)
this.state = {
style : {
left : '-110px',
bottom : '-100px',
}
}
this.setState(this.state)
}
enter(){
console.log(99)
this.state = {
style : {
left : '0px',
bottom : '100px',
}
}
}
componentWillUnmount(){
console.log(this.props.animation);
this.leave()
}
render(){
// console.log(this.props)
return (
<div className="animation" style={this.state.style}>
{this.props.children}
</div>
)
}
}
@connectToStores([AddBookStore], getState)
export default class AddBookToLibrary extends Component{
static propTypes = {
params : PropTypes.shape({
id : PropTypes.string.isRequired
}).isRequired,
book : PropTypes.object,
}
static contextTypes = {
router: PropTypes.object.isRequired
}
static childContextTypes = {
muiTheme: PropTypes.object,
}
constructor(props){
super(props);
this.state = {
showMenuItems : false,
animateMenu : 'enter'
}
}
/*
*Properties/Object which need to be transfered down to Component Hierarchy
*/
getChildContext(){
var theme = ThemeManager.getCurrentTheme();
theme.component.textField.focusColor = "#8CBB30";
return {
muiTheme: theme,
}
}
componentWillRecieveProps(nextProps){
console.log(nextProps)
}
componentWillMount(){
var url = '/getbookinfo';
var data = {
id : this.props.params.id,
format : 'xml',
}
BookActions.getBookFromGR(url, data);
}
updateBookStatus(action){
var url = '/updatestatus'
var data = {
id : this.props.params.id,
action : action
}
BookActions.updateBookStatusAPI(url, data);
}
Styles = {
Center : {
position : 'relative',
left : 0,
right : 0,
top : '50px',
margin : '0 auto',
maxWidth : '800px',
},
Slider : {
color : '#8CBB30'
},
container : {
padding : '12px',
color : '#8CBB30',
},
exampleFlatButtonIcon : {
float : 'left',
color: '#ccc',
top: '4px',
left: '8px',
}
}
handleClickUp(key){
console.log(key);
}
showMenuItems(){
if(this.state.showMenuItems){
this.state.animateMenu = 'enter';
this.state.showMenuItems = false;
}else{
this.state.animateMenu = 'leave';
this.state.showMenuItems = true;
}
this.setState(this.state);
}
addBook(e){
var url = '/addbook'
var data = {
isbn13 : this.props.book.isbn13,
status : e,
title : this.props.book.title,
author : this.props.book.authors.author.name,
image : this.props.book.authors.author.image_url
}
BookActions.addBookAPI(url, data);
}
render(){
const { book, showLoading, bookStatus } = this.props;
var divBox = <div ref="lastElement" style={{height:'20px'}}></div>
if(showLoading){
var divBox = <div><Loading/></div>
}
if(book){
var bookElement = '<div></div>';
}
switch(bookStatus){ //NA, OWN, WISH, LEND, RENT
case 'NA':
break;
case 'OWN':
break;
case 'WISH':
break;
case 'LEND':
break;
case 'RENT':
break;
}
var getBookInfoComponent = function (book) {
var authors = [];
var author = <span className="author-name">{book.authors.author.name}</span>
return (
<div>
<div style={{float:'left'}}>
<img src={book['image_url']} />
</div>
<div style={{float:'left'}}>
<h2>
{book.title}
</h2>
<h3>
{author}
</h3>
<h4>{book['average-rating']}</h4>
</div>
<div style={{clear:'both'}}></div>
</div>
)
}
if(book.hasOwnProperty('title')){
var bookInfoComponent = getBookInfoComponent(book);
}else{
var bookInfoComponent = <div></div>
}
var addOptions = {
'OWN' : 'add to library',
'WL' : 'add to wishlist'
}
var addOptionsComponent = [];
for(var key in addOptions){
addOptionsComponent.push(<div onClick={this.addBook.bind(this, key)}>{addOptions[key]}</div>);
}
var showMenuItemsComponent = function(){
return (
<div className="menu-items">
<div className="menu-items-ul">
{addOptionsComponent}
</div>;
</div>
)
}
return (
<div style={this.Styles.Center}>
<div style={{paddingTop:'50px'}}>
{bookInfoComponent}
<AnimatingElement animation={this.state.animateMenu}>
{this.state.showMenuItems ? showMenuItemsComponent.call(this) : ''}
</AnimatingElement>
<div className="icon-btn">
<FloatingActionButton onClick={this.showMenuItems.bind(this)} iconClassName="fa fa-plus"/>
</div>
</div>
{divBox}
</div>
)
}
} | mit |
rahku/corefx | src/System.Net.ServicePoint/tests/ServicePointManagerTest.cs | 15462 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Xunit;
namespace System.Net.Tests
{
public class ServicePointManagerTest
{
[Fact]
public static void RequireEncryption_ExpectedDefault()
{
Assert.Equal(EncryptionPolicy.RequireEncryption, ServicePointManager.EncryptionPolicy);
}
[Fact]
public static void CheckCertificateRevocationList_Roundtrips()
{
Assert.False(ServicePointManager.CheckCertificateRevocationList);
ServicePointManager.CheckCertificateRevocationList = true;
Assert.True(ServicePointManager.CheckCertificateRevocationList);
ServicePointManager.CheckCertificateRevocationList = false;
Assert.False(ServicePointManager.CheckCertificateRevocationList);
}
[Fact]
public static void DefaultConnectionLimit_Roundtrips()
{
Assert.Equal(2, ServicePointManager.DefaultConnectionLimit);
ServicePointManager.DefaultConnectionLimit = 20;
Assert.Equal(20, ServicePointManager.DefaultConnectionLimit);
ServicePointManager.DefaultConnectionLimit = 2;
Assert.Equal(2, ServicePointManager.DefaultConnectionLimit);
}
[Fact]
public static void DnsRefreshTimeout_Roundtrips()
{
Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout);
ServicePointManager.DnsRefreshTimeout = 42;
Assert.Equal(42, ServicePointManager.DnsRefreshTimeout);
ServicePointManager.DnsRefreshTimeout = 120000;
Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout);
}
[Fact]
public static void EnableDnsRoundRobin_Roundtrips()
{
Assert.False(ServicePointManager.EnableDnsRoundRobin);
ServicePointManager.EnableDnsRoundRobin = true;
Assert.True(ServicePointManager.EnableDnsRoundRobin);
ServicePointManager.EnableDnsRoundRobin = false;
Assert.False(ServicePointManager.EnableDnsRoundRobin);
}
[Fact]
public static void Expect100Continue_Roundtrips()
{
Assert.True(ServicePointManager.Expect100Continue);
ServicePointManager.Expect100Continue = false;
Assert.False(ServicePointManager.Expect100Continue);
ServicePointManager.Expect100Continue = true;
Assert.True(ServicePointManager.Expect100Continue);
}
[Fact]
public static void MaxServicePointIdleTime_Roundtrips()
{
Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime);
ServicePointManager.MaxServicePointIdleTime = 42;
Assert.Equal(42, ServicePointManager.MaxServicePointIdleTime);
ServicePointManager.MaxServicePointIdleTime = 100000;
Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime);
}
[Fact]
public static void MaxServicePoints_Roundtrips()
{
Assert.Equal(0, ServicePointManager.MaxServicePoints);
ServicePointManager.MaxServicePoints = 42;
Assert.Equal(42, ServicePointManager.MaxServicePoints);
ServicePointManager.MaxServicePoints = 0;
Assert.Equal(0, ServicePointManager.MaxServicePoints);
}
[Fact]
public static void ReusePort_Roundtrips()
{
Assert.False(ServicePointManager.ReusePort);
ServicePointManager.ReusePort = true;
Assert.True(ServicePointManager.ReusePort);
ServicePointManager.ReusePort = false;
Assert.False(ServicePointManager.ReusePort);
}
[Fact]
public static void SecurityProtocol_Roundtrips()
{
var orig = (SecurityProtocolType)0; // SystemDefault.
Assert.Equal(orig, ServicePointManager.SecurityProtocol);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
Assert.Equal(SecurityProtocolType.Tls11, ServicePointManager.SecurityProtocol);
ServicePointManager.SecurityProtocol = orig;
Assert.Equal(orig, ServicePointManager.SecurityProtocol);
}
[Fact]
public static void ServerCertificateValidationCallback_Roundtrips()
{
Assert.Null(ServicePointManager.ServerCertificateValidationCallback);
RemoteCertificateValidationCallback callback = delegate { return true; };
ServicePointManager.ServerCertificateValidationCallback = callback;
Assert.Same(callback, ServicePointManager.ServerCertificateValidationCallback);
ServicePointManager.ServerCertificateValidationCallback = null;
Assert.Null(ServicePointManager.ServerCertificateValidationCallback);
}
[Fact]
public static void UseNagleAlgorithm_Roundtrips()
{
Assert.True(ServicePointManager.UseNagleAlgorithm);
ServicePointManager.UseNagleAlgorithm = false;
Assert.False(ServicePointManager.UseNagleAlgorithm);
ServicePointManager.UseNagleAlgorithm = true;
Assert.True(ServicePointManager.UseNagleAlgorithm);
}
[Fact]
public static void InvalidArguments_Throw()
{
const int ssl2Client = 0x00000008;
const int ssl2Server = 0x00000004;
SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server);
#pragma warning disable 0618 // Ssl2, Ssl3 are deprecated.
Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3);
Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | ssl2);
#pragma warning restore
Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = ssl2);
AssertExtensions.Throws<ArgumentNullException>("uriString", () => ServicePointManager.FindServicePoint((string)null, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.MaxServicePoints = -1);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.DefaultConnectionLimit = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.MaxServicePointIdleTime = -2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveTime", () => ServicePointManager.SetTcpKeepAlive(true, -1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveInterval", () => ServicePointManager.SetTcpKeepAlive(true, 1, -1));
AssertExtensions.Throws<ArgumentNullException>("address", () => ServicePointManager.FindServicePoint(null));
AssertExtensions.Throws<ArgumentNullException>("uriString", () => ServicePointManager.FindServicePoint((string)null, null));
AssertExtensions.Throws<ArgumentNullException>("address", () => ServicePointManager.FindServicePoint((Uri)null, null));
Assert.Throws<NotSupportedException>(() => ServicePointManager.FindServicePoint("http://anything", new FixedWebProxy("https://anything")));
ServicePoint sp = ServicePointManager.FindServicePoint("http://" + Guid.NewGuid().ToString("N"), null);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLeaseTimeout = -2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLimit = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.MaxIdleTime = -2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ReceiveBufferSize = -2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveTime", () => sp.SetTcpKeepAlive(true, -1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveInterval", () => sp.SetTcpKeepAlive(true, 1, -1));
}
[Fact]
public static void FindServicePoint_ReturnsCachedServicePoint()
{
const string Localhost = "http://localhost";
string address1 = "http://" + Guid.NewGuid().ToString("N");
string address2 = "http://" + Guid.NewGuid().ToString("N");
Assert.NotNull(ServicePointManager.FindServicePoint(new Uri(address1)));
Assert.Same(
ServicePointManager.FindServicePoint(address1, null),
ServicePointManager.FindServicePoint(address1, null));
Assert.Same(
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)),
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)));
Assert.Same(
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)),
ServicePointManager.FindServicePoint(address2, new FixedWebProxy(address1)));
Assert.Same(
ServicePointManager.FindServicePoint(Localhost, new FixedWebProxy(address1)),
ServicePointManager.FindServicePoint(Localhost, new FixedWebProxy(address2)));
Assert.NotSame(
ServicePointManager.FindServicePoint(address1, null),
ServicePointManager.FindServicePoint(address2, null));
Assert.NotSame(
ServicePointManager.FindServicePoint(address1, null),
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)));
Assert.NotSame(
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)),
ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address2)));
}
[Fact]
public static void FindServicePoint_Collectible()
{
string address = "http://" + Guid.NewGuid().ToString("N");
bool initial = GetExpect100Continue(address);
SetExpect100Continue(address, !initial);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.Equal(initial, GetExpect100Continue(address));
}
[Fact]
public static void FindServicePoint_ReturnedServicePointMatchesExpectedValues()
{
string address = "http://" + Guid.NewGuid().ToString("N");
DateTime start = DateTime.Now;
ServicePoint sp = ServicePointManager.FindServicePoint(address, null);
Assert.InRange(sp.IdleSince, start, DateTime.MaxValue);
Assert.Equal(new Uri(address), sp.Address);
Assert.Null(sp.BindIPEndPointDelegate);
Assert.Null(sp.Certificate);
Assert.Null(sp.ClientCertificate);
Assert.Equal(-1, sp.ConnectionLeaseTimeout);
Assert.Equal("http", sp.ConnectionName);
Assert.Equal(0, sp.CurrentConnections);
Assert.Equal(true, sp.Expect100Continue);
Assert.Equal(100000, sp.MaxIdleTime);
Assert.Equal(new Version(1, 1), sp.ProtocolVersion);
Assert.Equal(-1, sp.ReceiveBufferSize);
Assert.True(sp.SupportsPipelining, "SupportsPipelining");
Assert.True(sp.UseNagleAlgorithm, "UseNagleAlgorithm");
}
[Fact]
public static void FindServicePoint_PropertiesRoundtrip()
{
string address = "http://" + Guid.NewGuid().ToString("N");
BindIPEndPoint expectedBindIPEndPointDelegate = delegate { return null; };
int expectedConnectionLeaseTimeout = 42;
int expectedConnectionLimit = 84;
bool expected100Continue = false;
int expectedMaxIdleTime = 200000;
int expectedReceiveBufferSize = 123;
bool expectedUseNagleAlgorithm = false;
ServicePoint sp1 = ServicePointManager.FindServicePoint(address, null);
sp1.BindIPEndPointDelegate = expectedBindIPEndPointDelegate;
sp1.ConnectionLeaseTimeout = expectedConnectionLeaseTimeout;
sp1.ConnectionLimit = expectedConnectionLimit;
sp1.Expect100Continue = expected100Continue;
sp1.MaxIdleTime = expectedMaxIdleTime;
sp1.ReceiveBufferSize = expectedReceiveBufferSize;
sp1.UseNagleAlgorithm = expectedUseNagleAlgorithm;
ServicePoint sp2 = ServicePointManager.FindServicePoint(address, null);
Assert.Same(expectedBindIPEndPointDelegate, sp2.BindIPEndPointDelegate);
Assert.Equal(expectedConnectionLeaseTimeout, sp2.ConnectionLeaseTimeout);
Assert.Equal(expectedConnectionLimit, sp2.ConnectionLimit);
Assert.Equal(expected100Continue, sp2.Expect100Continue);
Assert.Equal(expectedMaxIdleTime, sp2.MaxIdleTime);
Assert.Equal(expectedReceiveBufferSize, sp2.ReceiveBufferSize);
Assert.Equal(expectedUseNagleAlgorithm, sp2.UseNagleAlgorithm);
}
[Fact]
public static void FindServicePoint_NewServicePointsInheritCurrentValues()
{
string address1 = "http://" + Guid.NewGuid().ToString("N");
string address2 = "http://" + Guid.NewGuid().ToString("N");
bool orig100Continue = ServicePointManager.Expect100Continue;
bool origNagle = ServicePointManager.UseNagleAlgorithm;
ServicePointManager.Expect100Continue = false;
ServicePointManager.UseNagleAlgorithm = false;
ServicePoint sp1 = ServicePointManager.FindServicePoint(address1, null);
Assert.False(sp1.Expect100Continue);
Assert.False(sp1.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = true;
ServicePointManager.UseNagleAlgorithm = true;
ServicePoint sp2 = ServicePointManager.FindServicePoint(address2, null);
Assert.True(sp2.Expect100Continue);
Assert.True(sp2.UseNagleAlgorithm);
Assert.False(sp1.Expect100Continue);
Assert.False(sp1.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = orig100Continue;
ServicePointManager.UseNagleAlgorithm = origNagle;
}
// Separated out to avoid the JIT in debug builds interfering with object lifetimes
private static bool GetExpect100Continue(string address) =>
ServicePointManager.FindServicePoint(address, null).Expect100Continue;
private static void SetExpect100Continue(string address, bool value) =>
ServicePointManager.FindServicePoint(address, null).Expect100Continue = value;
private sealed class FixedWebProxy : IWebProxy
{
private readonly Uri _proxyAddress;
public FixedWebProxy(string proxyAddress) { _proxyAddress = new Uri(proxyAddress); }
public Uri GetProxy(Uri destination) => _proxyAddress;
public bool IsBypassed(Uri host) => false;
public ICredentials Credentials { get; set; }
}
}
}
| mit |
jasnow/human_error | spec/lib/human_error/errors/request_errors/unpermitted_parameters_error_spec.rb | 2309 | require 'rspectacular'
require 'human_error'
require 'action_controller'
class HumanError
module Errors
describe UnpermittedParametersError do
it 'has a status' do
error = UnpermittedParametersError.new
expect(error.http_status).to eql 400
end
it 'has a code' do
error = UnpermittedParametersError.new
expect(error.code).to eql 'errors.unpermitted_parameters_error'
end
it 'has a title' do
error = UnpermittedParametersError.new
expect(error.title).to eql 'Unpermitted Parameters'
end
it 'includes the resource name and action in the detail' do
error = UnpermittedParametersError.new resource_name: 'trenchcoat',
action: 'create',
parameters: 'color'
expect(error.detail).to eql 'Attempting to create a trenchcoat with the ' \
'following parameters is not allowed: color'
end
it 'includes the resource name and action in the detail' do
error = UnpermittedParametersError.new resource_name: 'trenchcoat',
action: 'create',
parameters: %w{color size}
expect(error.detail).to eql 'Attempting to create a trenchcoat with the ' \
'following parameters is not allowed: color, size'
end
it 'includes the resource name and action in the source' do
error = UnpermittedParametersError.new parameters: 'trenchcoat'
expect(error.source).to eql('unpermitted_parameters' => ['trenchcoat'])
end
it 'can convert an "ActionController::UnpermittedParameters"' do
parameters_error = ActionController::UnpermittedParameters.new(%w{trenchcoat})
error = UnpermittedParametersError.convert(parameters_error)
expect(error.parameters).to eql %w{trenchcoat}
end
it 'can convert an "ActionController::ParameterMissing" while overriding attributes' do
parameters_error = ActionController::UnpermittedParameters.new(%w{trenchcoat})
error = UnpermittedParametersError.convert(parameters_error,
parameters: 'matrix')
expect(error.parameters).to eql %w{matrix}
end
end
end
end
| mit |
customerlobby/less_accounting | lib/less_accounting/api.rb | 513 | require File.expand_path('../request', __FILE__)
require File.expand_path('../response', __FILE__)
require File.expand_path('../connection', __FILE__)
module LessAccounting
class API
attr_accessor *Configuration::VALID_OPTIONS_KEYS
def initialize(options = {})
options = LessAccounting.options.merge(options)
Configuration::VALID_OPTIONS_KEYS.each do |key|
send("#{key}=", options[key])
end
end
include Request
include Response
include Connection
end
end
| mit |
ilios/common | tests/unit/models/mesh-concept-test.js | 314 | import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Model | MeshConcept', function (hooks) {
setupTest(hooks);
test('it exists', function (assert) {
const model = this.owner.lookup('service:store').createRecord('mesh-concept');
assert.ok(!!model);
});
});
| mit |
Secretmapper/react-transmission | src/components/menus/SortByContextMenu/index.js | 1941 | import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import { inject } from 'mobx-react';
import autobind from 'autobind-decorator';
import ContextMenu from 'components/menus/ContextMenu';
import styles from './styles/index.css';
@inject('prefs_store', 'view_store', 'torrents_store')
@CSSModules(styles)
class SortByContextMenu extends Component {
@autobind onToggleSortByContextMenu() {
this.props.view_store.toggleSortByContextMenu();
}
@autobind onToggleContextMenu() {
// TODO: Move it to ContextMenu component
this.props.view_store.toggleContextMenus();
}
@autobind onSetSortCriteria(sortCriteria) {
this.props.prefs_store.setSortCriteria(sortCriteria)
}
render() {
const { sortCriteria, sortDirection } = this.props.prefs_store;
const criteriaList = {
queue_order: 'Queue Order',
activity: 'Activity',
age: 'Age',
name: 'Name',
percent_completed: 'Progress',
ratio: 'Ratio',
size: 'Size',
state: 'State',
};
return (
<ContextMenu
show={this.props.show}
container={this.props.container}
target={this.props.target}
onHide={this.props.onHide}
>
<ul
styleName='torrentMenu'
onClick={this.onToggleContextMenu}
onMouseEnter={this.onToggleSortByContextMenu}
onMouseLeave={this.onToggleSortByContextMenu}
>
{Object.keys(criteriaList).map((key) => (
<li key={key} styleName={sortCriteria === key ? 'torrentMenuSelected' : 'torrentMenuItem'} onClick={this.onSetSortCriteria.bind(this, key)}>{criteriaList[key]}</li>
))}
<li styleName='torrentMenuSeparator' />
<li styleName={sortDirection === 'ascending' ? 'torrentMenuItem' : 'torrentMenuSelected'}>Reverse Sort Order</li>
</ul>
</ContextMenu>
);
}
}
export default SortByContextMenu;
| mit |
CslaGenFork/CslaGenFork | trunk/Samples/DeepLoad/ParentLoad.Business/ERCLevel/B05_SubContinent_Child.Designer.cs | 9669 | using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B05_SubContinent_Child (editable child object).<br/>
/// This is a generated base class of <see cref="B05_SubContinent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="B04_SubContinent"/> collection.
/// </remarks>
[Serializable]
public partial class B05_SubContinent_Child : BusinessBase<B05_SubContinent_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int subContinent_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name");
/// <summary>
/// Gets or sets the Sub Continent Child Name.
/// </summary>
/// <value>The Sub Continent Child Name.</value>
public string SubContinent_Child_Name
{
get { return GetProperty(SubContinent_Child_NameProperty); }
set { SetProperty(SubContinent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B05_SubContinent_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B05_SubContinent_Child"/> object.</returns>
internal static B05_SubContinent_Child NewB05_SubContinent_Child()
{
return DataPortal.CreateChild<B05_SubContinent_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="B05_SubContinent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B05_SubContinent_Child"/> object.</returns>
internal static B05_SubContinent_Child GetB05_SubContinent_Child(SafeDataReader dr)
{
B05_SubContinent_Child obj = new B05_SubContinent_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B05_SubContinent_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B05_SubContinent_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B05_SubContinent_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B05_SubContinent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name"));
// parent properties
subContinent_ID1 = dr.GetInt32("SubContinent_ID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="B05_SubContinent_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddB05_SubContinent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B05_SubContinent_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(B04_SubContinent parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateB05_SubContinent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="B05_SubContinent_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(B04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteB05_SubContinent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| mit |
malnuxstarck/SiteDuSavoir | class/ManagerPost.class.php | 5159 |
<?php
/* se charge des operations sur la base de donnees pour la class Post */
class ManagerPost
{
const ERR_AUTH_EDIT = "Vous ne pouveez pas modifier ce Post ";
const ERR_AUTH_DELETE = "Vous ne pouvez pas supprimer ce message ";
protected $_db;
public $_iErros = 0 ;
protected $_errors = array();
public function __construct(PDO $bdd)
{
$this->setDb($bdd);
}
public function setDb($bdd)
{
$this->_db = $bdd ;
}
public function infosPost($idPost)
{
$query = $this->_db->prepare('SELECT topic.id AS id ,post.createur AS createur, post.topic AS topic, titre, topic.forum AS forum, post.texte AS texte ,locked, posttime,name, auth_view, auth_post, auth_topic, auth_annonce, auth_modo
FROM post
LEFT JOIN topic
ON topic.id = post.topic
LEFT JOIN forums
ON forums.id = topic.forum
WHERE post.id = :post');
$query->bindValue(':post',$idPost,PDO::PARAM_INT);
$query->execute();
$donnees = $query->fetch();
if(!empty($donnees))
return $donnees;
else
return array();
}
public function verifierChamps(Post $post)
{
if(empty($post->texte()))
{
$this->_iErros++;
$this->_errors['texte'] = '<p>Le message du post est vides</p>';
}
}
public function errors()
{
return $this->_errors;
}
public function nouveauPost(Post $post)
{
$query = $this->_db->prepare('INSERT INTO post(createur, texte, posttime, topic, forum)
VALUES (:id, :mess, NOW(), :topic, :forum)');
$query->bindValue(':id', $post->createur(), PDO::PARAM_INT);
$query->bindValue(':mess', $post->texte(), PDO::PARAM_STR);
$query->bindValue(':topic', (int)$post->topic(), PDO::PARAM_INT);
$query->bindValue(':forum', $post->forum(), PDO::PARAM_INT);
$query->execute();
$idPost = $this->_db->lastInsertId();
return $idPost;
}
public function positionDuPostEditer(Post $post)
{
$query = $this->_db->prepare('SELECT COUNT(*) AS nbr FROM post WHERE topic = :topic AND posttime < :temps');
$query->bindValue(':topic',$post->topic(),PDO::PARAM_INT);
$query->bindValue(':temps',$post->posttime(),PDO::PARAM_STR);
$query->execute();
$total=$query->fetchColumn();
return $total;
}
public function miseAjoursPost(Post $post)
{
$query = $this->_db->prepare('UPDATE post SET texte = :message WHERE id = :post');
$query->bindValue(':message',$post->texte(),PDO::PARAM_STR);
$query->bindValue(':post',$post->id(),PDO::PARAM_INT);
$query->execute();
}
public function deletePost($idPost)
{
$query = $this->_db->prepare('DELETE FROM post WHERE id = :post');
$query->bindValue(':post',$idPost,PDO::PARAM_INT);
$query->execute();
$query->CloseCursor();
}
public function dernierPost($idTopicOuForum , $genre)
{
$query = $this->_db->prepare('SELECT *
FROM post WHERE '.$genre.' = :valeur
ORDER BY id DESC LIMIT 0,1');
$query->bindValue(':valeur',$idTopicOuForum,PDO::PARAM_INT);
$query->execute();
$data=$query->fetch();
if(!empty($data))
return $data;
else
return array();
}
public function nombreDePostParMembreDuTopic($idTopic)
{
$query = $this->_db->prepare('SELECT createur, COUNT(*) AS nombre_mess FROM post
WHERE topic = :topic GROUP BY createur');
$query->execute(array('topic' => $idTopic));
$datas = $query->fetchAll();
return $datas;
}
public function deletePostsDuTopic($idTopic)
{
$query=$this->_db->prepare('DELETE FROM post WHERE topic =:topic');
$query->bindValue(':topic',$idTopic,PDO::PARAM_INT);
$query->execute();
$query->CloseCursor();
}
public function deplacerPostsVersForum(Topic $topic)
{
$query = $this->_db->prepare('UPDATE post SET forum = :dest
WHERE topic = :topic');
$query->bindValue(':dest',$topic->forum(),PDO::PARAM_INT);
$query->bindValue(':topic',$topic->id(),PDO::PARAM_INT);
$query->execute();
$query->CloseCursor();
}
public function nombrePostPourCeTopic($idTopic)
{
$query=$this->_db->prepare('SELECT COUNT(*) AS nombre_post FROM post WHERE topic = :topic');
$query->bindValue(':topic',$idTopic,PDO::PARAM_INT);
$query->execute();
$data = $query->fetchColumn();
return $data;
}
public function tousLesPostsDuTopic($idTopic , $debut , $nombre)
{
$query = $this->_db->prepare('SELECT post.id As id, post.createur AS createur ,rang, texte , posttime,membres.id AS idMembre, pseudo, inscrit, avatar,localisation, membres.posts AS posts, signature
FROM post
LEFT JOIN membres ON membres.id = post.createur
WHERE topic =:topic
ORDER BY id
LIMIT :premier, :nombre');
$query->bindValue(':topic',$idTopic,PDO::PARAM_INT);
$query->bindValue(':premier',(int)$debut,PDO::PARAM_INT);
$query->bindValue(':nombre',(int)$nombre,PDO::PARAM_INT);
$query->execute();
$datas = $query->fetchAll();
return $datas;
}
} | mit |
robdmoore/NQUnit | SampleWebApp/Scripts/my-javascript.js | 718 | /// <reference path="jquery-1.4.4-vsdoc.js" />
var MyNamespace = (function ($) {
var that = {};
var counter = 0;
var multiply = function (y) {
if (!isNaN(y)) {
counter *= y;
}
};
var add = function (y) {
if (!isNaN(y)) {
counter += y * 1;
}
};
var increment = function () {
add(1);
};
var display = function () {
$("#display").text(counter);
};
var getCount = function () {
return counter;
};
var reset = function () {
counter = 0;
};
// Public methods
that.add = add;
that.multiply = multiply;
that.display = display;
that.increment = increment;
that.getCount = getCount;
that.reset = reset;
return that;
})(jQuery); | mit |
madison-kerndt/avant-garde-synesthesia | lib/components/Note.js | 221 | import React from 'react';
export default ({ noteName }) => {
const note = noteName.slice(0,-1);
return(
<div className='direction'>
<div
className={note} > ø {note}
</div>
</div>
)
}
| mit |
GoodiesHQ/Daddy | daddy/__init__.py | 38 | from . import utils
from . import bot
| mit |
MyConnectedSite/TCC-.NET-Library | TCC2.API.CloudTracker/Types/SetCloudTrackerEPCEventsResult.cs | 605 | using System;
using Newtonsoft.Json;
namespace TCC2.API.CloudTracker
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class SetCloudTrackerEPCEventsResult : ApiCallResult
{
[JsonProperty(PropertyName = "events")]
public SetCloudTrackerEPCEventsResultEntry[] ResultEntries { get; protected set; }
protected override void ValidateInstance(IRequestDataProvider provider)
{
base.ValidateInstance(provider);
ValidateHasValue(ResultEntries, "events");
}
}
} | mit |
rshell/oracle-enhanced | lib/active_record/connection_adapters/oracle_enhanced/procedures.rb | 6413 | # frozen_string_literal: true
require "active_support"
module ActiveRecord #:nodoc:
# Custom create, update, delete methods functionality.
#
# Example:
#
# class Employee < ActiveRecord::Base
# include ActiveRecord::OracleEnhancedProcedures
#
# set_create_method do
# plsql.employees_pkg.create_employee(
# :p_first_name => first_name,
# :p_last_name => last_name,
# :p_employee_id => nil
# )[:p_employee_id]
# end
#
# set_update_method do
# plsql.employees_pkg.update_employee(
# :p_employee_id => id,
# :p_first_name => first_name,
# :p_last_name => last_name
# )
# end
#
# set_delete_method do
# plsql.employees_pkg.delete_employee(
# :p_employee_id => id
# )
# end
# end
#
module OracleEnhancedProcedures #:nodoc:
module ClassMethods
# Specify custom create method which should be used instead of Rails generated INSERT statement.
# Provided block should return ID of new record.
# Example:
# set_create_method do
# plsql.employees_pkg.create_employee(
# :p_first_name => first_name,
# :p_last_name => last_name,
# :p_employee_id => nil
# )[:p_employee_id]
# end
def set_create_method(&block)
self.custom_create_method = block
end
# Specify custom update method which should be used instead of Rails generated UPDATE statement.
# Example:
# set_update_method do
# plsql.employees_pkg.update_employee(
# :p_employee_id => id,
# :p_first_name => first_name,
# :p_last_name => last_name
# )
# end
def set_update_method(&block)
self.custom_update_method = block
end
# Specify custom delete method which should be used instead of Rails generated DELETE statement.
# Example:
# set_delete_method do
# plsql.employees_pkg.delete_employee(
# :p_employee_id => id
# )
# end
def set_delete_method(&block)
self.custom_delete_method = block
end
end
def self.included(base)
base.class_eval do
extend ClassMethods
class_attribute :custom_create_method
class_attribute :custom_update_method
class_attribute :custom_delete_method
end
end
def destroy #:nodoc:
# check if class has custom delete method
if self.class.custom_delete_method
# wrap destroy in transaction
with_transaction_returning_status do
# run before/after callbacks defined in model
run_callbacks(:destroy) { destroy_using_custom_method }
end
else
super
end
end
private
# Creates a record with custom create method
# and returns its id.
def _create_record
# check if class has custom create method
if self.class.custom_create_method
# run before/after callbacks defined in model
run_callbacks(:create) do
# timestamp
if self.record_timestamps
current_time = current_time_from_proper_timezone
all_timestamp_attributes_in_model.each do |column|
if respond_to?(column) && respond_to?("#{column}=") && self.send(column).nil?
write_attribute(column.to_s, current_time)
end
end
end
# run
create_using_custom_method
end
else
super
end
end
def create_using_custom_method
log_custom_method("custom create method", "#{self.class.name} Create") do
self.id = instance_eval(&self.class.custom_create_method)
end
@new_record = false
# Starting from ActiveRecord 3.0.3 @persisted is used instead of @new_record
@persisted = true
id
end
# Updates the associated record with custom update method
# Returns the number of affected rows.
def _update_record(attribute_names = @attributes.keys)
# check if class has custom update method
if self.class.custom_update_method
# run before/after callbacks defined in model
run_callbacks(:update) do
# timestamp
if should_record_timestamps?
current_time = current_time_from_proper_timezone
timestamp_attributes_for_update_in_model.each do |column|
column = column.to_s
next if will_save_change_to_attribute?(column)
write_attribute(column, current_time)
end
end
# update just dirty attributes
if partial_writes?
# Serialized attributes should always be written in case they've been
# changed in place.
update_using_custom_method(changed | (attributes.keys & self.class.columns.select { |column| column.is_a?(Type::Serialized) }))
else
update_using_custom_method(attributes.keys)
end
end
else
super
end
end
def update_using_custom_method(attribute_names)
return 0 if attribute_names.empty?
log_custom_method("custom update method with #{self.class.primary_key}=#{self.id}", "#{self.class.name} Update") do
instance_eval(&self.class.custom_update_method)
end
1
end
# Deletes the record in the database with custom delete method
# and freezes this instance to reflect that no changes should
# be made (since they can't be persisted).
def destroy_using_custom_method
unless new_record? || @destroyed
log_custom_method("custom delete method with #{self.class.primary_key}=#{self.id}", "#{self.class.name} Destroy") do
instance_eval(&self.class.custom_delete_method)
end
end
@destroyed = true
freeze
end
def log_custom_method(*args)
self.class.connection.send(:log, *args) { yield }
end
alias_method :update_record, :_update_record if private_method_defined?(:_update_record)
alias_method :create_record, :_create_record if private_method_defined?(:_create_record)
end
end
| mit |
cdnjs/cdnjs | ajax/libs/primereact/5.0.2/components/tree/UITreeNode.js | 35749 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UITreeNode = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _ClassNames = require("../utils/ClassNames");
var _DomHandler = _interopRequireDefault(require("../utils/DomHandler"));
var _Ripple = require("../ripple/Ripple");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var UITreeNode = /*#__PURE__*/function (_Component) {
_inherits(UITreeNode, _Component);
var _super = _createSuper(UITreeNode);
function UITreeNode(props) {
var _this;
_classCallCheck(this, UITreeNode);
_this = _super.call(this, props);
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onRightClick = _this.onRightClick.bind(_assertThisInitialized(_this));
_this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this));
_this.onTogglerClick = _this.onTogglerClick.bind(_assertThisInitialized(_this));
_this.onNodeKeyDown = _this.onNodeKeyDown.bind(_assertThisInitialized(_this));
_this.propagateUp = _this.propagateUp.bind(_assertThisInitialized(_this));
_this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this));
_this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this));
_this.onDragEnter = _this.onDragEnter.bind(_assertThisInitialized(_this));
_this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this));
_this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this));
_this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this));
_this.onDropPointDragOver = _this.onDropPointDragOver.bind(_assertThisInitialized(_this));
_this.onDropPointDragEnter = _this.onDropPointDragEnter.bind(_assertThisInitialized(_this));
_this.onDropPointDragLeave = _this.onDropPointDragLeave.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(UITreeNode, [{
key: "isLeaf",
value: function isLeaf() {
return this.props.isNodeLeaf(this.props.node);
}
}, {
key: "expand",
value: function expand(event) {
var expandedKeys = this.props.expandedKeys ? _objectSpread({}, this.props.expandedKeys) : {};
expandedKeys[this.props.node.key] = true;
this.props.onToggle({
originalEvent: event,
value: expandedKeys
});
this.invokeToggleEvents(event, true);
}
}, {
key: "collapse",
value: function collapse(event) {
var expandedKeys = _objectSpread({}, this.props.expandedKeys);
delete expandedKeys[this.props.node.key];
this.props.onToggle({
originalEvent: event,
value: expandedKeys
});
this.invokeToggleEvents(event, false);
}
}, {
key: "onTogglerClick",
value: function onTogglerClick(event) {
if (this.props.disabled) {
return;
}
if (this.isExpanded()) this.collapse(event);else this.expand(event);
}
}, {
key: "invokeToggleEvents",
value: function invokeToggleEvents(event, expanded) {
if (expanded) {
if (this.props.onExpand) {
this.props.onExpand({
originalEvent: event,
node: this.props.node
});
}
} else {
if (this.props.onCollapse) {
this.props.onCollapse({
originalEvent: event,
node: this.props.node
});
}
}
}
}, {
key: "isExpanded",
value: function isExpanded() {
return this.props.expandedKeys ? this.props.expandedKeys[this.props.node.key] !== undefined : false;
}
}, {
key: "onNodeKeyDown",
value: function onNodeKeyDown(event) {
if (this.props.disabled) {
return;
}
var nodeElement = event.target.parentElement;
if (!_DomHandler.default.hasClass(nodeElement, 'p-treenode')) {
return;
}
switch (event.which) {
//down arrow
case 40:
var listElement = nodeElement.children[1];
if (listElement) {
this.focusNode(listElement.children[0]);
} else {
var nextNodeElement = nodeElement.nextElementSibling;
if (nextNodeElement) {
this.focusNode(nextNodeElement);
} else {
var nextSiblingAncestor = this.findNextSiblingOfAncestor(nodeElement);
if (nextSiblingAncestor) {
this.focusNode(nextSiblingAncestor);
}
}
}
event.preventDefault();
break;
//up arrow
case 38:
if (nodeElement.previousElementSibling) {
this.focusNode(this.findLastVisibleDescendant(nodeElement.previousElementSibling));
} else {
var parentNodeElement = this.getParentNodeElement(nodeElement);
if (parentNodeElement) {
this.focusNode(parentNodeElement);
}
}
event.preventDefault();
break;
//right arrow
case 39:
if (!this.isExpanded()) {
this.expand(event);
}
event.preventDefault();
break;
//left arrow
case 37:
if (this.isExpanded()) {
this.collapse(event);
}
event.preventDefault();
break;
//enter
case 13:
this.onClick(event);
event.preventDefault();
break;
default:
//no op
break;
}
}
}, {
key: "findNextSiblingOfAncestor",
value: function findNextSiblingOfAncestor(nodeElement) {
var parentNodeElement = this.getParentNodeElement(nodeElement);
if (parentNodeElement) {
if (parentNodeElement.nextElementSibling) return parentNodeElement.nextElementSibling;else return this.findNextSiblingOfAncestor(parentNodeElement);
} else {
return null;
}
}
}, {
key: "findLastVisibleDescendant",
value: function findLastVisibleDescendant(nodeElement) {
var childrenListElement = nodeElement.children[1];
if (childrenListElement) {
var lastChildElement = childrenListElement.children[childrenListElement.children.length - 1];
return this.findLastVisibleDescendant(lastChildElement);
} else {
return nodeElement;
}
}
}, {
key: "getParentNodeElement",
value: function getParentNodeElement(nodeElement) {
var parentNodeElement = nodeElement.parentElement.parentElement;
return _DomHandler.default.hasClass(parentNodeElement, 'p-treenode') ? parentNodeElement : null;
}
}, {
key: "focusNode",
value: function focusNode(element) {
element.children[0].focus();
}
}, {
key: "onClick",
value: function onClick(event) {
if (event.target.className && event.target.className.constructor === String && event.target.className.indexOf('p-tree-toggler') === 0 || this.props.disabled) {
return;
}
if (this.props.selectionMode && this.props.node.selectable !== false) {
var selectionKeys;
if (this.isCheckboxSelectionMode()) {
var checked = this.isChecked();
selectionKeys = this.props.selectionKeys ? _objectSpread({}, this.props.selectionKeys) : {};
if (checked) {
if (this.props.propagateSelectionDown) this.propagateDown(this.props.node, false, selectionKeys);else delete selectionKeys[this.props.node.key];
if (this.props.propagateSelectionUp && this.props.onPropagateUp) {
this.props.onPropagateUp({
originalEvent: event,
check: false,
selectionKeys: selectionKeys
});
}
if (this.props.onUnselect) {
this.props.onUnselect({
originalEvent: event,
node: this.props.node
});
}
} else {
if (this.props.propagateSelectionDown) this.propagateDown(this.props.node, true, selectionKeys);else selectionKeys[this.props.node.key] = {
checked: true
};
if (this.props.propagateSelectionUp && this.props.onPropagateUp) {
this.props.onPropagateUp({
originalEvent: event,
check: true,
selectionKeys: selectionKeys
});
}
if (this.props.onSelect) {
this.props.onSelect({
originalEvent: event,
node: this.props.node
});
}
}
} else {
var selected = this.isSelected();
var metaSelection = this.nodeTouched ? false : this.props.metaKeySelection;
if (metaSelection) {
var metaKey = event.metaKey || event.ctrlKey;
if (selected && metaKey) {
if (this.isSingleSelectionMode()) {
selectionKeys = null;
} else {
selectionKeys = _objectSpread({}, this.props.selectionKeys);
delete selectionKeys[this.props.node.key];
}
if (this.props.onUnselect) {
this.props.onUnselect({
originalEvent: event,
node: this.props.node
});
}
} else {
if (this.isSingleSelectionMode()) {
selectionKeys = this.props.node.key;
} else if (this.isMultipleSelectionMode()) {
selectionKeys = !metaKey ? {} : this.props.selectionKeys ? _objectSpread({}, this.props.selectionKeys) : {};
selectionKeys[this.props.node.key] = true;
}
if (this.props.onSelect) {
this.props.onSelect({
originalEvent: event,
node: this.props.node
});
}
}
} else {
if (this.isSingleSelectionMode()) {
if (selected) {
selectionKeys = null;
if (this.props.onUnselect) {
this.props.onUnselect({
originalEvent: event,
node: this.props.node
});
}
} else {
selectionKeys = this.props.node.key;
if (this.props.onSelect) {
this.props.onSelect({
originalEvent: event,
node: this.props.node
});
}
}
} else {
if (selected) {
selectionKeys = _objectSpread({}, this.props.selectionKeys);
delete selectionKeys[this.props.node.key];
if (this.props.onUnselect) {
this.props.onUnselect({
originalEvent: event,
node: this.props.node
});
}
} else {
selectionKeys = this.props.selectionKeys ? _objectSpread({}, this.props.selectionKeys) : {};
selectionKeys[this.props.node.key] = true;
if (this.props.onSelect) {
this.props.onSelect({
originalEvent: event,
node: this.props.node
});
}
}
}
}
}
if (this.props.onSelectionChange) {
this.props.onSelectionChange({
originalEvent: event,
value: selectionKeys
});
}
}
this.nodeTouched = false;
}
}, {
key: "onRightClick",
value: function onRightClick(event) {
if (this.props.disabled) {
return;
}
_DomHandler.default.clearSelection();
if (this.props.onContextMenuSelectionChange) {
this.props.onContextMenuSelectionChange({
originalEvent: event,
value: this.props.node.key
});
}
if (this.props.onContextMenu) {
this.props.onContextMenu({
originalEvent: event,
node: this.props.node
});
}
}
}, {
key: "propagateUp",
value: function propagateUp(event) {
var check = event.check;
var selectionKeys = event.selectionKeys;
var checkedChildCount = 0;
var childPartialSelected = false;
var _iterator = _createForOfIteratorHelper(this.props.node.children),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
if (selectionKeys[child.key] && selectionKeys[child.key].checked) checkedChildCount++;else if (selectionKeys[child.key] && selectionKeys[child.key].partialChecked) childPartialSelected = true;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (check && checkedChildCount === this.props.node.children.length) {
selectionKeys[this.props.node.key] = {
checked: true,
partialChecked: false
};
} else {
if (!check) {
delete selectionKeys[this.props.node.key];
}
if (childPartialSelected || checkedChildCount > 0 && checkedChildCount !== this.props.node.children.length) selectionKeys[this.props.node.key] = {
checked: false,
partialChecked: true
};else selectionKeys[this.props.node.key] = {
checked: false,
partialChecked: false
};
}
if (this.props.propagateSelectionUp && this.props.onPropagateUp) {
this.props.onPropagateUp(event);
}
}
}, {
key: "propagateDown",
value: function propagateDown(node, check, selectionKeys) {
if (check) selectionKeys[node.key] = {
checked: true,
partialChecked: false
};else delete selectionKeys[node.key];
if (node.children && node.children.length) {
for (var i = 0; i < node.children.length; i++) {
this.propagateDown(node.children[i], check, selectionKeys);
}
}
}
}, {
key: "isSelected",
value: function isSelected() {
if (this.props.selectionMode && this.props.selectionKeys) return this.isSingleSelectionMode() ? this.props.selectionKeys === this.props.node.key : this.props.selectionKeys[this.props.node.key] !== undefined;else return false;
}
}, {
key: "isChecked",
value: function isChecked() {
return this.props.selectionKeys ? this.props.selectionKeys[this.props.node.key] && this.props.selectionKeys[this.props.node.key].checked : false;
}
}, {
key: "isPartialChecked",
value: function isPartialChecked() {
return this.props.selectionKeys ? this.props.selectionKeys[this.props.node.key] && this.props.selectionKeys[this.props.node.key].partialChecked : false;
}
}, {
key: "isSingleSelectionMode",
value: function isSingleSelectionMode() {
return this.props.selectionMode && this.props.selectionMode === 'single';
}
}, {
key: "isMultipleSelectionMode",
value: function isMultipleSelectionMode() {
return this.props.selectionMode && this.props.selectionMode === 'multiple';
}
}, {
key: "isCheckboxSelectionMode",
value: function isCheckboxSelectionMode() {
return this.props.selectionMode && this.props.selectionMode === 'checkbox';
}
}, {
key: "onTouchEnd",
value: function onTouchEnd() {
this.nodeTouched = true;
}
}, {
key: "onDropPoint",
value: function onDropPoint(event, position) {
event.preventDefault();
if (this.props.node.droppable !== false) {
_DomHandler.default.removeClass(event.target, 'p-treenode-droppoint-active');
if (this.props.onDropPoint) {
this.props.onDropPoint({
originalEvent: event,
path: this.props.path,
index: this.props.index,
position: position
});
}
}
}
}, {
key: "onDropPointDragOver",
value: function onDropPointDragOver(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) {
event.dataTransfer.dropEffect = 'move';
event.preventDefault();
}
}
}, {
key: "onDropPointDragEnter",
value: function onDropPointDragEnter(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) {
_DomHandler.default.addClass(event.target, 'p-treenode-droppoint-active');
}
}
}, {
key: "onDropPointDragLeave",
value: function onDropPointDragLeave(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) {
_DomHandler.default.removeClass(event.target, 'p-treenode-droppoint-active');
}
}
}, {
key: "onDrop",
value: function onDrop(event) {
if (this.props.dragdropScope && this.props.node.droppable !== false) {
_DomHandler.default.removeClass(this.contentElement, 'p-treenode-dragover');
event.preventDefault();
event.stopPropagation();
if (this.props.onDrop) {
this.props.onDrop({
originalEvent: event,
path: this.props.path
});
}
}
}
}, {
key: "onDragOver",
value: function onDragOver(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) {
event.dataTransfer.dropEffect = 'move';
event.preventDefault();
event.stopPropagation();
}
}
}, {
key: "onDragEnter",
value: function onDragEnter(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) {
_DomHandler.default.addClass(this.contentElement, 'p-treenode-dragover');
}
}
}, {
key: "onDragLeave",
value: function onDragLeave(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) {
var rect = event.currentTarget.getBoundingClientRect();
if (event.nativeEvent.x > rect.left + rect.width || event.nativeEvent.x < rect.left || event.nativeEvent.y >= Math.floor(rect.top + rect.height) || event.nativeEvent.y < rect.top) {
_DomHandler.default.removeClass(this.contentElement, 'p-treenode-dragover');
}
}
}
}, {
key: "onDragStart",
value: function onDragStart(event) {
event.dataTransfer.setData("text", this.props.dragdropScope);
event.dataTransfer.setData(this.props.dragdropScope, this.props.dragdropScope);
if (this.props.onDragStart) {
this.props.onDragStart({
originalEvent: event,
path: this.props.path,
index: this.props.index
});
}
}
}, {
key: "onDragEnd",
value: function onDragEnd(event) {
if (this.props.onDragEnd) {
this.props.onDragEnd({
originalEvent: event
});
}
}
}, {
key: "renderLabel",
value: function renderLabel() {
var label = this.props.nodeTemplate ? this.props.nodeTemplate(this.props.node) : this.props.node.label;
return /*#__PURE__*/_react.default.createElement("span", {
className: "p-treenode-label"
}, label);
}
}, {
key: "renderCheckbox",
value: function renderCheckbox() {
if (this.isCheckboxSelectionMode() && this.props.node.selectable !== false) {
var checked = this.isChecked();
var partialChecked = this.isPartialChecked();
var className = (0, _ClassNames.classNames)('p-checkbox-box', {
'p-highlight': checked,
'p-indeterminate': partialChecked,
'p-disabled': this.props.disabled
});
var icon = (0, _ClassNames.classNames)('p-checkbox-icon p-c', {
'pi pi-check': checked,
'pi pi-minus': partialChecked
});
return /*#__PURE__*/_react.default.createElement("div", {
className: "p-checkbox p-component"
}, /*#__PURE__*/_react.default.createElement("div", {
className: className,
role: "checkbox",
"aria-checked": checked
}, /*#__PURE__*/_react.default.createElement("span", {
className: icon
})));
}
return null;
}
}, {
key: "renderIcon",
value: function renderIcon(expanded) {
var icon = this.props.node.icon || (expanded ? this.props.node.expandedIcon : this.props.node.collapsedIcon);
if (icon) {
var className = (0, _ClassNames.classNames)('p-treenode-icon', icon);
return /*#__PURE__*/_react.default.createElement("span", {
className: className
});
}
return null;
}
}, {
key: "renderToggler",
value: function renderToggler(expanded) {
var iconClassName = (0, _ClassNames.classNames)('p-tree-toggler-icon pi pi-fw', {
'pi-chevron-right': !expanded,
'pi-chevron-down': expanded
});
return /*#__PURE__*/_react.default.createElement("button", {
type: "button",
className: "p-tree-toggler p-link",
tabIndex: "-1",
onClick: this.onTogglerClick
}, /*#__PURE__*/_react.default.createElement("span", {
className: iconClassName
}), /*#__PURE__*/_react.default.createElement(_Ripple.Ripple, null));
}
}, {
key: "renderDropPoint",
value: function renderDropPoint(position) {
var _this2 = this;
if (this.props.dragdropScope) {
return /*#__PURE__*/_react.default.createElement("li", {
className: "p-treenode-droppoint",
onDrop: function onDrop(event) {
return _this2.onDropPoint(event, position);
},
onDragOver: this.onDropPointDragOver,
onDragEnter: this.onDropPointDragEnter,
onDragLeave: this.onDropPointDragLeave
});
}
return null;
}
}, {
key: "renderContent",
value: function renderContent() {
var _this3 = this;
var selected = this.isSelected();
var checked = this.isChecked();
var className = (0, _ClassNames.classNames)('p-treenode-content', this.props.node.className, {
'p-treenode-selectable': this.props.selectionMode && this.props.node.selectable !== false,
'p-highlight': this.isCheckboxSelectionMode() ? checked : selected,
'p-highlight-contextmenu': this.props.contextMenuSelectionKey && this.props.contextMenuSelectionKey === this.props.node.key,
'p-disabled': this.props.disabled
});
var expanded = this.isExpanded();
var toggler = this.renderToggler(expanded);
var checkbox = this.renderCheckbox();
var icon = this.renderIcon(expanded);
var label = this.renderLabel();
var tabIndex = this.props.disabled ? undefined : '0';
return /*#__PURE__*/_react.default.createElement("div", {
ref: function ref(el) {
return _this3.contentElement = el;
},
className: className,
style: this.props.node.style,
onClick: this.onClick,
onContextMenu: this.onRightClick,
onTouchEnd: this.onTouchEnd,
draggable: this.props.dragdropScope && this.props.node.draggable !== false && !this.props.disabled,
onDrop: this.onDrop,
onDragOver: this.onDragOver,
onDragEnter: this.onDragEnter,
onDragLeave: this.onDragLeave,
onDragStart: this.onDragStart,
onDragEnd: this.onDragEnd,
tabIndex: tabIndex,
onKeyDown: this.onNodeKeyDown,
role: "treeitem",
"aria-posinset": this.props.index + 1,
"aria-expanded": this.isExpanded(),
"aria-selected": checked || selected
}, toggler, checkbox, icon, label);
}
}, {
key: "renderChildren",
value: function renderChildren() {
var _this4 = this;
if (this.props.node.children && this.props.node.children.length && this.isExpanded()) {
return /*#__PURE__*/_react.default.createElement("ul", {
className: "p-treenode-children",
role: "group"
}, this.props.node.children.map(function (childNode, index) {
return /*#__PURE__*/_react.default.createElement(UITreeNode, {
key: childNode.key || childNode.label,
node: childNode,
parent: _this4.props.node,
index: index,
last: index === _this4.props.node.children.length - 1,
path: _this4.props.path + '-' + index,
disabled: _this4.props.disabled,
selectionMode: _this4.props.selectionMode,
selectionKeys: _this4.props.selectionKeys,
onSelectionChange: _this4.props.onSelectionChange,
metaKeySelection: _this4.props.metaKeySelection,
propagateSelectionDown: _this4.props.propagateSelectionDown,
propagateSelectionUp: _this4.props.propagateSelectionUp,
contextMenuSelectionKey: _this4.props.contextMenuSelectionKey,
onContextMenuSelectionChange: _this4.props.onContextMenuSelectionChange,
onContextMenu: _this4.props.onContextMenu,
onExpand: _this4.props.onExpand,
onCollapse: _this4.props.onCollapse,
onSelect: _this4.props.onSelect,
onUnselect: _this4.props.onUnselect,
expandedKeys: _this4.props.expandedKeys,
onToggle: _this4.props.onToggle,
onPropagateUp: _this4.propagateUp,
nodeTemplate: _this4.props.nodeTemplate,
isNodeLeaf: _this4.props.isNodeLeaf,
dragdropScope: _this4.props.dragdropScope,
onDragStart: _this4.props.onDragStart,
onDragEnd: _this4.props.onDragEnd,
onDrop: _this4.props.onDrop,
onDropPoint: _this4.props.onDropPoint
});
}));
}
return null;
}
}, {
key: "renderNode",
value: function renderNode() {
var className = (0, _ClassNames.classNames)('p-treenode', {
'p-treenode-leaf': this.isLeaf()
}, this.props.node.className);
var content = this.renderContent();
var children = this.renderChildren();
return /*#__PURE__*/_react.default.createElement("li", {
className: className,
style: this.props.node.style
}, content, children);
}
}, {
key: "render",
value: function render() {
var node = this.renderNode();
if (this.props.dragdropScope && !this.props.disabled) {
var beforeDropPoint = this.renderDropPoint(-1);
var afterDropPoint = this.props.last ? this.renderDropPoint(1) : null;
return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, beforeDropPoint, node, afterDropPoint);
} else {
return node;
}
}
}]);
return UITreeNode;
}(_react.Component);
exports.UITreeNode = UITreeNode;
_defineProperty(UITreeNode, "defaultProps", {
node: null,
index: null,
last: null,
parent: null,
path: null,
disabled: false,
selectionMode: null,
selectionKeys: null,
contextMenuSelectionKey: null,
metaKeySelection: true,
expandedKeys: null,
propagateSelectionUp: true,
propagateSelectionDown: true,
dragdropScope: null,
ariaLabel: null,
ariaLabelledBy: null,
nodeTemplate: null,
isNodeLeaf: null,
onSelect: null,
onUnselect: null,
onExpand: null,
onCollapse: null,
onToggle: null,
onSelectionChange: null,
onContextMenuSelectionChange: null,
onPropagateUp: null,
onDragStart: null,
onDragEnd: null,
onDrop: null,
onDropPoint: null,
onContextMenu: null
});
_defineProperty(UITreeNode, "propTypes", {
node: _propTypes.default.object,
index: _propTypes.default.number,
last: _propTypes.default.bool,
parent: _propTypes.default.object,
path: _propTypes.default.string,
disabled: _propTypes.default.bool,
selectionMode: _propTypes.default.string,
selectionKeys: _propTypes.default.any,
contextMenuSelectionKey: _propTypes.default.any,
metaKeySelection: _propTypes.default.bool,
expandedKeys: _propTypes.default.object,
propagateSelectionUp: _propTypes.default.bool,
propagateSelectionDown: _propTypes.default.bool,
dragdropScope: _propTypes.default.string,
ariaLabel: _propTypes.default.string,
ariaLabelledBy: _propTypes.default.string,
nodeTemplate: _propTypes.default.func,
isNodeLeaf: _propTypes.default.func,
onSelect: _propTypes.default.func,
onUnselect: _propTypes.default.func,
onExpand: _propTypes.default.func,
onCollapse: _propTypes.default.func,
onToggle: _propTypes.default.func,
onSelectionChange: _propTypes.default.func,
onContextMenuSelectionChange: _propTypes.default.func,
onPropagateUp: _propTypes.default.func,
onDragStart: _propTypes.default.func,
onDragEnd: _propTypes.default.func,
onDrop: _propTypes.default.func,
onDropPoint: _propTypes.default.func,
onContextMenu: _propTypes.default.func
}); | mit |
supranove/clockwork | codebase/include/scene/scene.hh | 3714 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Jeremy Othieno.
*
* 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 <QAbstractItemModel>
#include <QModelIndex>
#include <QSet>
#include "scene.object.hh"
namespace clockwork {
namespace scene {
/**
* @see scene.viewer.hh.
*/
class Viewer;
/**
* The scene graph.
*/
class Scene : public QAbstractItemModel
{
public:
/**
* Return the scene's unique instance.
*/
static Scene& getInstance();
/**
* Return the scene graph.
*/
Object& getGraph();
/**
* Return the set of active viewers.
*/
const QSet<Viewer*>& getActiveViewers();
/**
* Activate a viewer. When a viewer is activated, it receives
* requests to render the scene from its viewpoint.
* @param viewer the viewer to activate.
*/
void activateViewer(Viewer& viewer);
/**
* Deactivate a viewer.
* @param viewer the viewer to deregister.
*/
void deactivateViewer(Viewer& viewer);
/**
* Return true if the scene has at least one active viewer, false otherwise.
*/
bool hasActiveViewers() const;
/**
* Save the scene to a JSON file.
* @param filename the name of the JSON file.
*/
void save(const QString& filename) const;
/**
* @see QAbstractItemModel::index.
*/
QModelIndex index(const int, const int, const QModelIndex& = QModelIndex()) const override final;
/**
* @see QAbstractItemModel::parent.
*/
QModelIndex parent(const QModelIndex&) const override final;
/**
* @see QAbstractItemModel::rowCount.
*/
int rowCount(const QModelIndex& = QModelIndex()) const override final;
/**
* @see QAbstractItemModel::columnCount.
*/
inline int columnCount(const QModelIndex& = QModelIndex()) const override final { return 1; }
/**
* @see QAbstractItemModel::data.
*/
QVariant data(const QModelIndex&, const int) const override final;
/**
* @see QAbstractItemModel::headerData.
*/
QVariant headerData(const int, const Qt::Orientation = Qt::Horizontal, const int = Qt::DisplayRole) const override final;
private:
/**
* The Scene is a singleton.
*/
Scene();
Scene(const Scene&) = delete;
Scene& operator=(const Scene&) = delete;
/**
* The scene graph.
*/
Object* const _graph;
/**
* The set of active viewers.
*/
QSet<Viewer*> _activeViewers;
/**
* When true, this signals that each active viewer's viewport needs to be updated.
*/
bool _doViewportUpdate;
/**
* Update the viewports of each activated viewer.
*/
void updateViewports();
};
} // namespace scene
} // namespace clockwork
| mit |
lenscas/webshop | application/models/general/Gusers_model.php | 3582 | <?php
Class Gusers_model extends CI_Model {
public function Register($data, $sort){
foreach ($data as $key => $value) {
if ($value == "") {
$error = "Niet alle velden zijn ingevuld!";
break;
}
}
if (!isset($error) && $data['Password'] != $data['PasswordCheck'] ) {
$error = "Wachtwoorden komen niet overeen.";
}
$birthdata=$this->getDate($data['Birthdate']);
if($birthdata['correct']){
$data['Birthdate']=$birthdata['date'];
} else {
$error="Er is geen geldige geboortedatum ingevuld";
}
if (isset($error)) {
return $error;
}
unset($data['PasswordCheck']);
if ($sort == 'users') {
$data['Id']=$this->GenId();
}
//encrypt password for registration
$this->load->library('encryption');
$data['Password']=$this->encryption->encrypt($data['Password']);
//insert in database
$this->db->insert($sort, $data);
}
public function GenId(){
$this->load->helper('string');
$this->db->select('count(*) as counter');
$this->db->from('users');
$query = $this->db->get();
$result = $query->row_array();
return sha1($result['counter']."/".random_string("alpha", 4)."/".time());
}
public function getAllUserData($userId){
$this->db->select("*");
$this->db->from("users");
$this->db->where("Id",$userId);
$this->db->limit("1");
$query=$this->db->get();
return $query->row_array();
}
public function editUser($data,$userId){
$updatePassword=false;
//check if the password needs to be set
if($data['Password'] && $data['PasswordCheck']){
if($data['Password']==$data["PasswordCheck"]){
$updatePassword=true;
}
}
if(! $updatePassword){
unset($data['Password']);
}
unset($data["PasswordCheck"]);
//check if the date is valid
$birthdata=$this->getDate($data["Birthdate"]);
if($birthdata['correct']){
$data['Birthdate']=$birthdata['date'];
}else {
unset($data['Birthdate']);
}
//unset all emtpy values
foreach($data as $key => $value){
if($value==""){
unset($data[$key]);
}
}
//encrypt password for edit profile
if (isset($data['Password'])) {
$this->load->library('encryption');
$data['Password']=$this->encryption->encrypt($data['Password']);
}
//update the database
$this->db->where("Id",$userId);
$this->db->update("users",$data);
}
public function getDate($dateString){
$data=explode ( "/", $dateString );
//0=the month,1=the day,2 = the year
$correct=false;
if(count($data)==3){
$correct=checkdate ( $data[0] , $data[1] , $data[2] );
}
if($correct){
return array("correct"=>true,"date"=>$data[2].'-'.$data[0].'-'.$data[1]);
}
}
public function logout($sort){
//$this->load->view('front/users/logout_form');
$this->session->sess_destroy($sort);
$this->output->set_header('refresh:3;url=login');
//$this->load->view('front/defaults/front-footer.php');
}
public function login($table,$login_data){
$error=true;
$this->db->select("*");
$this->db->from($table);
$this->db->where("Username",$login_data["Username"]);
$this->db->limit("1");
$query=$this->db->get();
$result=$query->row_array();
$this->load->library('encryption');
if (isset($result['Password'])) {
$decryptedPassword=$this->encryption->decrypt($result['Password']);
if($decryptedPassword==$login_data['Password']){
if($table="admin"){
$this->session->set_userdata("adminId",$result['Id']);
} else {
$this->session->set_userdata("userId",$result['Id']);
}
$error=false;
}
}
if($error){
return "De gebruikersnaam of het wachtwoord is onjuist.";
}
}
}
?>
| mit |
gintechsystems/GINcose-Android | app/src/main/java/com/gintechsystems/gincose/messages/TransmitterMessage.java | 238 | package com.gintechsystems.gincose.messages;
import java.nio.ByteBuffer;
/**
* Created by joeginley on 3/16/16.
*/
public abstract class TransmitterMessage {
public byte[] byteSequence = null;
public ByteBuffer data = null;
}
| mit |
adrienhobbs/redux-glow | src/components/case-study/single/templates/hbo/the-night-of.js | 3352 | import React, { PropTypes } from 'react';
import BaseTemplate from '../base-study-template';
import AboutSection from '../../../content-modules/about.js';
import LoopingVideo from '../../../../video/looping-video.js';
import styles from './night-of.css';
export class NightOf extends BaseTemplate {
static propTypes = {
data: PropTypes.object.isRequired
};
constructor (props) {
super(props);
}
render () {
const ResultsSection = this.getResultsTemplate();
return (
<div ref='studyContent' className='study-content'>
<div className='content-container'>
<AboutSection data={this.props.data} />
<ResultsSection data={this.props.data} />
<div className='social-strategy'>
<div className='copy'>
<div className='copy-inner' lang='en'>
<p style={this.getCopyStyle()}>In order to get people to the pilot and get them hooked, we utilized sampling tactics such as critic praise quote cards and captivating countdowns which resulted in 1.5 million people streaming the first episode on HBO NOW and HBO GO before the premiere.</p>
</div>
</div>
<div className='copy'>
<div className='copy-inner' lang='en'>
<p style={this.getCopyStyle()}>Each week, we highlighted the breathtaking cinematography through gritty, visually compelling GIFs, character-based cinemagraphs, and video quote cards. To spark conversation, we emphasized quotes that played to the philosophical edge of the series as well as in real life facts about the judicial system. All content was showcased on The Night Of’s Facebook Page and HBO’s Twitter account.</p>
</div>
</div>
<div className='img-single'>
<div className={styles.fullWidth}>
<LoopingVideo videoSrc='https://s3.amazonaws.com/weareglow-assets/case-studies/hbo/the-night-of/night-of-one.mp4' />
</div>
<div className={styles.row}>
<LoopingVideo videoSrc='https://s3.amazonaws.com/weareglow-assets/case-studies/hbo/the-night-of/night-of-two.mp4' />
<LoopingVideo videoSrc='https://s3.amazonaws.com/weareglow-assets/case-studies/hbo/the-night-of/night-of-three.mp4' />
</div>
<div className={styles.row}>
<div className='inner_section'><img src='https://s3.amazonaws.com/weareglow-assets/case-studies/hbo/the-night-of/night-of-four.jpg' alt=''/></div>
<div className='inner_section'><img src='https://s3.amazonaws.com/weareglow-assets/case-studies/hbo/the-night-of/night-of-five.jpg' alt=''/></div>
</div>
<div className={styles.row}>
<LoopingVideo videoSrc='https://s3.amazonaws.com/weareglow-assets/case-studies/hbo/the-night-of/night-of-six.mp4' />
<LoopingVideo videoSrc='https://s3.amazonaws.com/weareglow-assets/case-studies/hbo/the-night-of/night-of-seven.mp4' />
</div>
<div className={styles.fullWidth}>
<LoopingVideo videoSrc='https://s3.amazonaws.com/weareglow-assets/case-studies/hbo/the-night-of/night-of-8.mp4' />
</div>
</div>
</div>
</div>
</div>
);
}
}
export default NightOf;
| mit |
alivesay/catbox-crypto | test/test.js | 4469 | var assert = require('assert');
var Catbox = require('catbox');
var CatboxCrypto = require('..');
var options = {
algorithm: 'aes-256-cbc',
keySize: 32,
ivSize: 16
};
describe('CatboxCrypto', function() {
it('errors if not created with new', function () {
assert.throws(CatboxCrypto, function (err) {
return (err.message === 'Client must be instantiated with new');
});
});
it('creates a new connection', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
client.start(function (err) {
assert.equal(client.isReady(), true);
done(err);
});
});
describe('#set()', function () {
it('should set the cache value without error', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
var key = { segment: 'test', id: 'test' };
client.start(function () {
client.set(key, 0xbeef, 5000, function (err) {
if (err) { done(err); }
assert.notEqual(client.connection.connection.cache[key.segment][key.id], undefined);
done();
});
});
});
it('should error on null key', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
client.start(function () {
client.set(null, 0xbeef, 5000, function (err) {
assert.equal(err.message, 'Invalid key');
done();
});
});
});
it('should error on invalid key', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
client.start(function () {
client.set({}, 0xbeef, 5000, function (err) {
assert.equal(err.message, 'Invalid key');
done();
});
});
});
it('should error on circular reference', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
var key = { segment: 'test', id: 'test' };
var value = { x: 1 };
value.y = value;
client.start(function () {
client.set(key, value, 5000, function (err) {
assert.equal(err.message, 'Converting circular structure to JSON');
done();
});
});
});
});
describe('#get()', function () {
it('should get cached value after setting', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
var key = { segment: 'test', id: 'test' };
client.start(function () {
client.set(key, 0xbeef, 5000, function (err) {
if (err) { done(err); }
client.get(key, function (err, cached) {
if (err) { done(err); }
assert.equal(cached.item, 0xbeef);
done();
});
});
});
});
it('should return null when item not found', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
var key = { segment: 'test', id: 'test' };
client.start(function () {
client.get(key, function (err, cached) {
assert.equal(err, null);
assert.equal(cached, null);
done();
});
});
});
});
it('should return null when item is expired', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
var key = { segment: 'test', id: 'test' };
client.start(function () {
client.set(key, 0xbeef, 1, function (err) {
if (err) { done(err); }
setTimeout(function () {
client.get(key, function (err, cached) {
assert.equal(err, null);
assert.equal(err, cached);
done();
});
}, 2);
});
});
});
describe('#drop()', function () {
it('should drop cached item without error', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
var key = { segment: 'test', id: 'test' };
client.start(function () {
client.set(key, 0xbeef, 5000, function (err) {
if (err) { done(err); }
client.drop(key, done);
});
});
});
it('should error when dropping invalid key', function (done) {
var client = new Catbox.Client(CatboxCrypto, options);
var key = { segment: 'test', id: 'test' };
client.start(function () {
client.set(key, 0xbeef, 5000, function (err) {
if (err) { done(err); }
client.drop(null, function (err) {
assert(err.message === 'Invalid key');
done();
});
});
});
});
});
}); | mit |
thatguyjordan/TCF-Community-Mod | MBase.cs | 4060 | using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using TAPI;
using Terraria;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace tcfcomm
{
public sealed class MBase : ModBase
{
internal static MBase BaseInstance;
public override void OnLoad()
{
BaseInstance = this;
DateTime now = DateTime.Now;
int day = now.Day;
int month = now.Month;
bool red = now.Day == 12 && now.Month == 11;
bool jordan = now.Day == 3 && now.Month == 7;
bool neal = now.Day == 27 && now.Month == 7;
bool test = now.Day == 1 && now.Month == 11;
/* bool cireus = now.Day == 0 && now.Month == 0;
Main.chain3Texture = MBase.BaseInstance.textures["Images/SOMETHING Chain"]; //loads chain texture?
*/ Main.NPCLoaded[4] = true; //loads npc so texture is loaded first time around, not after first encounter with said enemy
Main.npcTexture[4] = MBase.BaseInstance.textures["Images/Scarecrow/EoC"]; //changes eoc texture to EoC
if (NPC.downedBoss3 = true) //checks to see whether skeletron has been defeated
{
Main.NPCLoaded[35] = true; //loads skeletron head
Main.npcTexture[35] = MBase.BaseInstance.textures["Images/Scarecrow/SkeleDowned"]; //replaces skele head with skeledowned
Main.NPCLoaded[36] = true; //same
Main.npcTexture[36] = MBase.BaseInstance.textures["Images/Scarecrow/SkeleHandDowned"]; //replaces skele hand with skelehanddowned
Main.boneArmTexture = MBase.BaseInstance.textures["Images/Scarecrow/SkeleBoneDowned"]; //replaces skele hand with skelehanddowned
}
if (red || jordan || neal || test) //checks if it is any of the specified dates
{
// fuck my codes shit
Main.NPCLoaded[113] = true; //loads npc so texture is loaded first time around, not after first encounter with said enemy
Main.NPCLoaded[114] = true;
Main.NPCLoaded[115] = true;
Main.NPCLoaded[116] = true;
Main.NPCLoaded[117] = true;
Main.NPCLoaded[118] = true;
Main.NPCLoaded[119] = true;
Main.npcTexture[114] = MBase.BaseInstance.textures["Images/Scarecrow/WallEyes"];//changes wall of flesh eyes texture to WallEyes
Main.npcTexture[113] = MBase.BaseInstance.textures["Images/Scarecrow/WallMouth"]; //changes wall of flesh mouth texture to WallMouth
Main.npcTexture[115] = MBase.BaseInstance.textures["Images/Scarecrow/Cupcake"]; //changes the hungry texture to Cupcake
Main.npcTexture[116] = MBase.BaseInstance.textures["Images/Scarecrow/CupcakeF"]; //changes the hungry texture to CupcakeF
Main.npcTexture[117] = MBase.BaseInstance.textures["Images/Scarecrow/GummyWormHead"]; //changes the hungry texture to GummyWormHead
Main.npcTexture[118] = MBase.BaseInstance.textures["Images/Scarecrow/GummyWormBody"]; //changes the hungry texture to GummyWormBody
Main.npcTexture[119] = MBase.BaseInstance.textures["Images/Scarecrow/GummyWormTail"]; //changes the hungry texture to GummyWormTail
Main.chain12Texture = MBase.BaseInstance.textures["Images/Scarecrow/HungryChain"]; //loads hungry chain texture
Main.wofTexture = MBase.BaseInstance.textures["Images/Scarecrow/WallOfCake"]; //changes wall of flesh eyes texture to WallEyes
}
}
public override void OnUnload() {
Main.NPCLoaded[4] = false; //unloads texture, I assume in case of mod removal, or changes in mod?
Main.NPCLoaded[114] = false; //unloads texture, I assume in case of mod removal, or changes in mod?
// Main.chain3Texture = MBase.BaseInstance.textures["Images/Chain3"]; //resets back to default chain texture
}
}
} | mit |
nico01f/z-pec | ZimbraServer/src/java/com/zimbra/cs/filter/FilterListener.java | 5734 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2011 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.filter;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.mailbox.Folder;
import com.zimbra.cs.mailbox.MailItem;
import com.zimbra.cs.mailbox.MailboxListener;
import com.zimbra.cs.mailbox.MailboxOperation;
import com.zimbra.cs.mailbox.Tag;
import com.zimbra.cs.session.PendingModifications;
import com.zimbra.cs.session.PendingModifications.Change;
import com.zimbra.cs.session.PendingModifications.ModificationKey;
public class FilterListener extends MailboxListener {
public static final ImmutableSet<MailboxOperation> EVENTS = ImmutableSet.of(
MailboxOperation.MoveItem, MailboxOperation.DeleteItem,
MailboxOperation.RenameItem, MailboxOperation.RenameItemPath,
MailboxOperation.RenameTag
);
public static final ImmutableSet<MailItem.Type> ITEMTYPES = ImmutableSet.of(
MailItem.Type.FOLDER, MailItem.Type.MOUNTPOINT, MailItem.Type.TAG
);
@Override
public void notify(ChangeNotification notification) {
if (notification.mods.modified != null && EVENTS.contains(notification.op)) {
for (PendingModifications.Change change : notification.mods.modified.values()) {
if (change.what instanceof Folder) {
if ((change.why & Change.PARENT) == 0 && (change.why & Change.NAME) == 0) {
continue;
}
Folder folder = (Folder) change.what;
Folder oldFolder = (Folder) change.preModifyObj;
if (oldFolder == null) {
ZimbraLog.filter.warn("Cannot determine the old folder name for %s.", folder.getName());
continue;
}
updateFilterRules(notification.mailboxAccount, folder, oldFolder.getPath());
} else if (change.what instanceof Tag) {
if ((change.why & Change.NAME) == 0) {
continue;
}
Tag tag = (Tag) change.what;
Tag oldTag = (Tag) change.preModifyObj;
if (oldTag == null) {
ZimbraLog.filter.warn("Cannot determine the old tag name for %s.", tag.getName());
continue;
}
updateFilterRules(notification.mailboxAccount, tag, oldTag.getName());
}
}
}
if (notification.mods.deleted != null) {
for (Map.Entry<ModificationKey, Change> entry : notification.mods.deleted.entrySet()) {
MailItem.Type type = (MailItem.Type) entry.getValue().what;
if (type == MailItem.Type.FOLDER || type == MailItem.Type.MOUNTPOINT) {
Folder oldFolder = (Folder) entry.getValue().preModifyObj;
if (oldFolder == null) {
ZimbraLog.filter.warn("Cannot determine the old folder name for %s.", entry.getKey());
continue;
}
updateFilterRules(notification.mailboxAccount, (Folder) null, oldFolder.getPath());
} else if (type == MailItem.Type.TAG) {
Tag oldTag = (Tag) entry.getValue().preModifyObj;
updateFilterRules(notification.mailboxAccount, oldTag);
}
}
}
}
@Override
public Set<MailItem.Type> registerForItemTypes() {
return ITEMTYPES;
}
private void updateFilterRules(Account account, Folder folder, String oldPath) {
try {
if (folder == null || folder.inTrash() || folder.isHidden()) {
ZimbraLog.filter.info("Disabling filter rules that reference %s.", oldPath);
RuleManager.folderDeleted(account, oldPath);
} else if (!folder.getPath().equals(oldPath)) {
ZimbraLog.filter.info("Updating filter rules that reference %s.", oldPath);
RuleManager.folderRenamed(account, oldPath, folder.getPath());
}
} catch (ServiceException e) {
ZimbraLog.filter.warn("Unable to update filter rules with new folder path.", e);
}
}
private void updateFilterRules(Account account, Tag tag, String oldName) {
try {
ZimbraLog.filter.info("Updating filter rules that reference %s.", oldName);
RuleManager.tagRenamed(account, oldName, tag.getName());
} catch (ServiceException e) {
ZimbraLog.filter.warn("Unable to update filter rules with new folder path.", e);
}
}
private void updateFilterRules(Account account, Tag tag) {
try {
ZimbraLog.filter.info("Disabling filter rules that reference %s.", tag.getName());
RuleManager.tagDeleted(account, tag.getName());
} catch (ServiceException e) {
ZimbraLog.filter.warn("Unable to update filter rules with new folder path.", e);
}
}
}
| mit |
nnaabbcc/exercise | windows/pw6e.official/CSharp/Chapter05/SliderSketch/SliderSketch/App.xaml.cs | 3617 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
namespace SliderSketch
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| mit |
Ezeer/VegaStrike_win32FR | vegastrike/boost/1_35/boost/date_time/int_adapter.hpp | 13775 | #ifndef _DATE_TIME_INT_ADAPTER_HPP__
#define _DATE_TIME_INT_ADAPTER_HPP__
/* Copyright (c) 2002,2003 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
* Author: Jeff Garland, Bart Garst
* $Date: 2008-02-27 21:00:24 +0100 (mer., 27 févr. 2008) $
*/
#include "boost/config.hpp"
#include "boost/limits.hpp" //work around compilers without limits
#include "boost/date_time/special_defs.hpp"
#include "boost/date_time/locale_config.hpp"
#include <iostream>
namespace boost {
namespace date_time {
//! Adapter to create integer types with +-infinity, and not a value
/*! This class is used internally in counted date/time representations.
* It adds the floating point like features of infinities and
* not a number. It also provides mathmatical operations with
* consideration to special values following these rules:
*@code
* +infinity - infinity == Not A Number (NAN)
* infinity * non-zero == infinity
* infinity * zero == NAN
* +infinity * -integer == -infinity
* infinity / infinity == NAN
* infinity * infinity == infinity
*@endcode
*/
template<typename int_type_>
class int_adapter {
public:
typedef int_type_ int_type;
int_adapter(int_type v) :
value_(v)
{}
static bool has_infinity()
{
return true;
}
static const int_adapter pos_infinity()
{
return (::std::numeric_limits<int_type>::max)();
}
static const int_adapter neg_infinity()
{
return (::std::numeric_limits<int_type>::min)();
}
static const int_adapter not_a_number()
{
return (::std::numeric_limits<int_type>::max)()-1;
}
static int_adapter max BOOST_PREVENT_MACRO_SUBSTITUTION ()
{
return (::std::numeric_limits<int_type>::max)()-2;
}
static int_adapter min BOOST_PREVENT_MACRO_SUBSTITUTION ()
{
return (::std::numeric_limits<int_type>::min)()+1;
}
static int_adapter from_special(special_values sv)
{
switch (sv) {
case not_a_date_time: return not_a_number();
case neg_infin: return neg_infinity();
case pos_infin: return pos_infinity();
case max_date_time: return (max)();
case min_date_time: return (min)();
default: return not_a_number();
}
}
static bool is_inf(int_type v)
{
return (v == neg_infinity().as_number() ||
v == pos_infinity().as_number());
}
static bool is_neg_inf(int_type v)
{
return (v == neg_infinity().as_number());
}
static bool is_pos_inf(int_type v)
{
return (v == pos_infinity().as_number());
}
static bool is_not_a_number(int_type v)
{
return (v == not_a_number().as_number());
}
//! Returns either special value type or is_not_special
static special_values to_special(int_type v)
{
if (is_not_a_number(v)) return not_a_date_time;
if (is_neg_inf(v)) return neg_infin;
if (is_pos_inf(v)) return pos_infin;
return not_special;
}
//-3 leaves room for representations of infinity and not a date
static int_type maxcount()
{
return (::std::numeric_limits<int_type>::max)()-3;
}
bool is_infinity() const
{
return (value_ == neg_infinity().as_number() ||
value_ == pos_infinity().as_number());
}
bool is_pos_infinity()const
{
return(value_ == pos_infinity().as_number());
}
bool is_neg_infinity()const
{
return(value_ == neg_infinity().as_number());
}
bool is_nan() const
{
return (value_ == not_a_number().as_number());
}
bool is_special() const
{
return(is_infinity() || is_nan());
}
bool operator==(const int_adapter& rhs) const
{
return (compare(rhs) == 0);
}
bool operator==(const int& rhs) const
{
// quiets compiler warnings
bool is_signed = std::numeric_limits<int_type>::is_signed;
if(!is_signed)
{
if(is_neg_inf(value_) && rhs == 0)
{
return false;
}
}
return (compare(rhs) == 0);
}
bool operator!=(const int_adapter& rhs) const
{
return (compare(rhs) != 0);
}
bool operator!=(const int& rhs) const
{
// quiets compiler warnings
bool is_signed = std::numeric_limits<int_type>::is_signed;
if(!is_signed)
{
if(is_neg_inf(value_) && rhs == 0)
{
return true;
}
}
return (compare(rhs) != 0);
}
bool operator<(const int_adapter& rhs) const
{
return (compare(rhs) == -1);
}
bool operator<(const int& rhs) const
{
// quiets compiler warnings
bool is_signed = std::numeric_limits<int_type>::is_signed;
if(!is_signed)
{
if(is_neg_inf(value_) && rhs == 0)
{
return true;
}
}
return (compare(rhs) == -1);
}
bool operator>(const int_adapter& rhs) const
{
return (compare(rhs) == 1);
}
int_type as_number() const
{
return value_;
}
//! Returns either special value type or is_not_special
special_values as_special() const
{
return int_adapter::to_special(value_);
}
//creates nasty ambiguities
// operator int_type() const
// {
// return value_;
// }
/*! Operator allows for adding dissimilar int_adapter types.
* The return type will match that of the the calling object's type */
template<class rhs_type>
inline
int_adapter operator+(const int_adapter<rhs_type>& rhs) const
{
if(is_special() || rhs.is_special())
{
if (is_nan() || rhs.is_nan())
{
return int_adapter::not_a_number();
}
if((is_pos_inf(value_) && rhs.is_neg_inf(rhs.as_number())) ||
(is_neg_inf(value_) && rhs.is_pos_inf(rhs.as_number())) )
{
return int_adapter::not_a_number();
}
if (is_infinity())
{
return *this;
}
if (rhs.is_pos_inf(rhs.as_number()))
{
return int_adapter::pos_infinity();
}
if (rhs.is_neg_inf(rhs.as_number()))
{
return int_adapter::neg_infinity();
}
}
return int_adapter<int_type>(value_ + rhs.as_number());
}
int_adapter operator+(const int_type rhs) const
{
if(is_special())
{
if (is_nan())
{
return int_adapter<int_type>(not_a_number());
}
if (is_infinity())
{
return *this;
}
}
return int_adapter<int_type>(value_ + rhs);
}
/*! Operator allows for subtracting dissimilar int_adapter types.
* The return type will match that of the the calling object's type */
template<class rhs_type>
inline
int_adapter operator-(const int_adapter<rhs_type>& rhs)const
{
if(is_special() || rhs.is_special())
{
if (is_nan() || rhs.is_nan())
{
return int_adapter::not_a_number();
}
if((is_pos_inf(value_) && rhs.is_pos_inf(rhs.as_number())) ||
(is_neg_inf(value_) && rhs.is_neg_inf(rhs.as_number())) )
{
return int_adapter::not_a_number();
}
if (is_infinity())
{
return *this;
}
if (rhs.is_pos_inf(rhs.as_number()))
{
return int_adapter::neg_infinity();
}
if (rhs.is_neg_inf(rhs.as_number()))
{
return int_adapter::pos_infinity();
}
}
return int_adapter<int_type>(value_ - rhs.as_number());
}
int_adapter operator-(const int_type rhs) const
{
if(is_special())
{
if (is_nan())
{
return int_adapter<int_type>(not_a_number());
}
if (is_infinity())
{
return *this;
}
}
return int_adapter<int_type>(value_ - rhs);
}
// should templatize this to be consistant with op +-
int_adapter operator*(const int_adapter& rhs)const
{
if(this->is_special() || rhs.is_special())
{
return mult_div_specials(rhs);
}
return int_adapter<int_type>(value_ * rhs.value_);
}
/*! Provided for cases when automatic conversion from
* 'int' to 'int_adapter' causes incorrect results. */
int_adapter operator*(const int rhs) const
{
if(is_special())
{
return mult_div_specials(rhs);
}
return int_adapter<int_type>(value_ * rhs);
}
// should templatize this to be consistant with op +-
int_adapter operator/(const int_adapter& rhs)const
{
if(this->is_special() || rhs.is_special())
{
if(is_infinity() && rhs.is_infinity())
{
return int_adapter<int_type>(not_a_number());
}
if(rhs != 0)
{
return mult_div_specials(rhs);
}
else { // let divide by zero blow itself up
return int_adapter<int_type>(value_ / rhs.value_);
}
}
return int_adapter<int_type>(value_ / rhs.value_);
}
/*! Provided for cases when automatic conversion from
* 'int' to 'int_adapter' causes incorrect results. */
int_adapter operator/(const int rhs) const
{
if(is_special() && rhs != 0)
{
return mult_div_specials(rhs);
}
return int_adapter<int_type>(value_ / rhs);
}
// should templatize this to be consistant with op +-
int_adapter operator%(const int_adapter& rhs)const
{
if(this->is_special() || rhs.is_special())
{
if(is_infinity() && rhs.is_infinity())
{
return int_adapter<int_type>(not_a_number());
}
if(rhs != 0)
{
return mult_div_specials(rhs);
}
else { // let divide by zero blow itself up
return int_adapter<int_type>(value_ % rhs.value_);
}
}
return int_adapter<int_type>(value_ % rhs.value_);
}
/*! Provided for cases when automatic conversion from
* 'int' to 'int_adapter' causes incorrect results. */
int_adapter operator%(const int rhs) const
{
if(is_special() && rhs != 0)
{
return mult_div_specials(rhs);
}
return int_adapter<int_type>(value_ % rhs);
}
private:
int_type value_;
//! returns -1, 0, 1, or 2 if 'this' is <, ==, >, or 'nan comparison' rhs
int compare(const int_adapter& rhs)const
{
if(this->is_special() || rhs.is_special())
{
if(this->is_nan() || rhs.is_nan()) {
if(this->is_nan() && rhs.is_nan()) {
return 0; // equal
}
else {
return 2; // nan
}
}
if((is_neg_inf(value_) && !is_neg_inf(rhs.value_)) ||
(is_pos_inf(rhs.value_) && !is_pos_inf(value_)) )
{
return -1; // less than
}
if((is_pos_inf(value_) && !is_pos_inf(rhs.value_)) ||
(is_neg_inf(rhs.value_) && !is_neg_inf(value_)) ) {
return 1; // greater than
}
}
if(value_ < rhs.value_) return -1;
if(value_ > rhs.value_) return 1;
// implied-> if(value_ == rhs.value_)
return 0;
}
/* When multiplying and dividing with at least 1 special value
* very simmilar rules apply. In those cases where the rules
* are different, they are handled in the respective operator
* function. */
//! Assumes at least 'this' or 'rhs' is a special value
int_adapter mult_div_specials(const int_adapter& rhs)const
{
int min_value;
// quiets compiler warnings
bool is_signed = std::numeric_limits<int_type>::is_signed;
if(is_signed) {
min_value = 0;
}
else {
min_value = 1;// there is no zero with unsigned
}
if(this->is_nan() || rhs.is_nan()) {
return int_adapter<int_type>(not_a_number());
}
if((*this > 0 && rhs > 0) || (*this < min_value && rhs < min_value)) {
return int_adapter<int_type>(pos_infinity());
}
if((*this > 0 && rhs < min_value) || (*this < min_value && rhs > 0)) {
return int_adapter<int_type>(neg_infinity());
}
//implied -> if(this->value_ == 0 || rhs.value_ == 0)
return int_adapter<int_type>(not_a_number());
}
/* Overloaded function necessary because of special
* situation where int_adapter is instantiated with
* 'unsigned' and func is called with negative int.
* It would produce incorrect results since 'unsigned'
* wraps around when initialized with a negative value */
//! Assumes 'this' is a special value
int_adapter mult_div_specials(const int& rhs) const
{
int min_value;
// quiets compiler warnings
bool is_signed = std::numeric_limits<int_type>::is_signed;
if(is_signed) {
min_value = 0;
}
else {
min_value = 1;// there is no zero with unsigned
}
if(this->is_nan()) {
return int_adapter<int_type>(not_a_number());
}
if((*this > 0 && rhs > 0) || (*this < min_value && rhs < 0)) {
return int_adapter<int_type>(pos_infinity());
}
if((*this > 0 && rhs < 0) || (*this < min_value && rhs > 0)) {
return int_adapter<int_type>(neg_infinity());
}
//implied -> if(this->value_ == 0 || rhs.value_ == 0)
return int_adapter<int_type>(not_a_number());
}
};
#ifndef BOOST_DATE_TIME_NO_LOCALE
/*! Expected output is either a numeric representation
* or a special values representation.<BR>
* Ex. "12", "+infinity", "not-a-number", etc. */
//template<class charT = char, class traits = std::traits<charT>, typename int_type>
template<class charT, class traits, typename int_type>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const int_adapter<int_type>& ia)
{
if(ia.is_special()) {
// switch copied from date_names_put.hpp
switch(ia.as_special())
{
case not_a_date_time:
os << "not-a-number";
break;
case pos_infin:
os << "+infinity";
break;
case neg_infin:
os << "-infinity";
break;
default:
os << "";
}
}
else {
os << ia.as_number();
}
return os;
}
#endif
} } //namespace date_time
#endif
| mit |
PaulTrampert/DocSite | DocSite.Test/SiteModel/DocEventTests.cs | 1046 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DocSite.SiteModel;
using DocSite.Xml;
using Xunit;
using Xunit.Sdk;
namespace DocSite.Test.SiteModel
{
public class DocEventTests
{
[Theory]
[InlineData("M:Test.Method")]
[InlineData("P:Test.Property")]
public void ThrowWhenPassedANonEventMemberDetails(string memberId)
{
Assert.Throws<ArgumentException>(() => new DocEvent(new MemberDetails {Id = memberId}));
}
[Fact]
public void ThrowsWhenPassedNullConstructorArgument()
{
Assert.Throws<ArgumentNullException>(() => new DocEvent(null));
}
[Theory]
[InlineData("E:Test.OnSomething")]
[InlineData("E:Test.OnSomethingElse(System.String[])")]
public void DoesNotThrowForEventMemberDetails(string memberId)
{
var result = new DocEvent(new MemberDetails {Id = memberId});
Assert.NotNull(result);
}
}
}
| mit |
cimocimocimo/staydrysystems.com | web/app/plugins/woocommerce-table-rate-shipping/woocommerce-table-rate-shipping.php | 7469 | <?php
/*
Plugin Name: WooCommerce Table Rate Shipping
Plugin URI: https://woocommerce.com/products/table-rate-shipping/
Description: Table rate shipping lets you define rates depending on location vs shipping class, price, weight, or item count.
Version: 3.0.2
Author: Automattic
Author URI: https://woocommerce.com/
Requires at least: 4.0
Tested up to: 4.6
Copyright: 2016 Automattic.
License: GNU General Public License v3.0
License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Required functions
*/
if ( ! function_exists( 'woothemes_queue_update' ) ) {
require_once( 'woo-includes/woo-functions.php' );
}
/**
* Plugin updates
*/
woothemes_queue_update( plugin_basename( __FILE__ ), '3034ed8aff427b0f635fe4c86bbf008a', '18718' );
/**
* Check if WooCommerce is active
*/
if ( is_woocommerce_active() ) {
/**
* Main Class
*/
class WC_Table_Rate_Shipping {
/**
* Constructor
*/
public function __construct() {
define( 'TABLE_RATE_SHIPPING_VERSION', '3.0.2' );
define( 'TABLE_RATE_SHIPPING_DEBUG', defined( 'WP_DEBUG' ) && 'true' == WP_DEBUG && ( ! defined( 'WP_DEBUG_DISPLAY' ) || 'true' == WP_DEBUG_DISPLAY ) );
add_action( 'plugins_loaded', array( $this, 'init' ) );
register_activation_hook( __FILE__, array( $this, 'install' ) );
}
/**
* Register method for usage
* @param array $shipping_methods
* @return array
*/
public function woocommerce_shipping_methods( $shipping_methods ) {
$shipping_methods['table_rate'] = 'WC_Shipping_Table_Rate';
return $shipping_methods;
}
/**
* Init TRS
*/
public function init() {
include_once( 'includes/functions-ajax.php' );
include_once( 'includes/functions-admin.php' );
/**
* Install check (for updates)
*/
if ( get_option( 'table_rate_shipping_version' ) < TABLE_RATE_SHIPPING_VERSION ) {
$this->install();
}
// 2.6.0+ supports zones and instances
if ( version_compare( WC_VERSION, '2.6.0', '>=' ) ) {
add_filter( 'woocommerce_shipping_methods', array( $this, 'woocommerce_shipping_methods' ) );
} else {
if ( ! defined( 'SHIPPING_ZONES_TEXTDOMAIN' ) ) {
define( 'SHIPPING_ZONES_TEXTDOMAIN', 'woocommerce-table-rate-shipping' );
}
if ( ! class_exists( 'WC_Shipping_zone' ) ) {
include_once( 'includes/legacy/shipping-zones/class-wc-shipping-zones.php' );
}
add_action( 'woocommerce_load_shipping_methods', array( $this, 'load_shipping_methods' ) );
add_action( 'admin_notices', array( $this, 'welcome_notice' ) );
}
// Hooks
add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
add_filter( 'plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 2 );
add_action( 'woocommerce_shipping_init', array( $this, 'shipping_init' ) );
}
/**
* Localisation
*/
public function load_plugin_textdomain() {
load_plugin_textdomain( 'woocommerce-table-rate-shipping', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
/**
* Row meta
* @param array $links
* @param string $file
* @return array
*/
public function plugin_row_meta( $links, $file ) {
if ( $file === plugin_basename( __FILE__ ) ) {
$row_meta = array(
'docs' => '<a href="' . esc_url( apply_filters( 'woocommerce_table_rate_shipping_docs_url', 'http://docs.woothemes.com/document/table-rate-shipping/' ) ) . '" title="' . esc_attr( __( 'View Documentation', 'woocommerce-table-rate-shipping' ) ) . '">' . __( 'Docs', 'woocommerce-table-rate-shipping' ) . '</a>',
'support' => '<a href="' . esc_url( apply_filters( 'woocommerce_table_rate_support_url', 'http://support.woothemes.com/' ) ) . '" title="' . esc_attr( __( 'Visit Premium Customer Support Forum', 'woocommerce-table-rate-shipping' ) ) . '">' . __( 'Premium Support', 'woocommerce-table-rate-shipping' ) . '</a>',
);
return array_merge( $links, $row_meta );
}
return (array) $links;
}
/**
* Admin welcome notice
*/
public function welcome_notice() {
if ( get_option( 'hide_table_rate_welcome_notice' ) ) {
return;
}
wp_enqueue_style( 'woocommerce-activation', WC()->plugin_url() . '/assets/css/activation.css' );
?>
<div id="message" class="updated woocommerce-message wc-connect">
<div class="squeezer">
<h4><?php _e( '<strong>Table Rates is installed</strong> – Add some shipping zones to get started :)', 'woocommerce-table-rate-shipping' ); ?></h4>
<p class="submit"><a href="<?php echo admin_url('admin.php?page=shipping_zones'); ?>" class="button-primary"><?php _e( 'Setup Zones', 'woocommerce-table-rate-shipping' ); ?></a> <a class="skip button-primary" href="http://docs.woothemes.com/document/table-rate-shipping/"><?php _e('Documentation', 'woocommerce-table-rate-shipping'); ?></a></p>
</div>
</div>
<?php
update_option( 'hide_table_rate_welcome_notice', 1 );
}
/**
* Admin styles + scripts
*/
public function admin_enqueue_scripts() {
$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
wp_enqueue_style( 'woocommerce_shipping_table_rate_styles', plugins_url( '/assets/css/admin.css', __FILE__ ) );
wp_register_script( 'woocommerce_shipping_table_rate_rows', plugins_url( '/assets/js/table-rate-rows' . $suffix . '.js', __FILE__ ), array( 'jquery', 'wp-util' ) );
wp_localize_script( 'woocommerce_shipping_table_rate_rows', 'woocommerce_shipping_table_rate_rows', array(
'i18n' => array(
'order' => __( 'Order', 'woocommerce-table-rate-shipping' ),
'item' => __( 'Item', 'woocommerce-table-rate-shipping' ),
'line_item' => __( 'Line Item', 'woocommerce-table-rate-shipping' ),
'class' => __( 'Class', 'woocommerce-table-rate-shipping' ),
'delete_rates' => __( 'Delete the selected rates?', 'woocommerce-table-rate-shipping' ),
'dupe_rates' => __( 'Duplicate the selected rates?', 'woocommerce-table-rate-shipping' ),
),
'delete_rates_nonce' => wp_create_nonce( "delete-rate" ),
) );
}
/**
* Load shipping class
*/
public function shipping_init() {
include_once( 'includes/class-wc-shipping-table-rate.php' );
}
/**
* Load shipping methods
*/
public function load_shipping_methods( $package ) {
// Register the main class
woocommerce_register_shipping_method( 'WC_Shipping_Table_Rate' );
if ( ! $package ) return;
// Get zone for package
$zone = woocommerce_get_shipping_zone( $package );
if ( TABLE_RATE_SHIPPING_DEBUG ) {
$notice_text = 'Customer matched shipping zone <strong>' . $zone->zone_name . '</strong> (#' . $zone->zone_id . ')';
if ( ! wc_has_notice( $notice_text, 'notice' ) ) {
wc_add_notice( $notice_text, 'notice' );
}
}
if ( $zone->exists() ) {
// Register zone methods
$zone->register_shipping_methods();
}
}
/**
* Installer
*/
public function install() {
include_once( 'installer.php' );
update_option( 'table_rate_shipping_version', TABLE_RATE_SHIPPING_VERSION );
}
}
new WC_Table_Rate_Shipping();
}
/**
* Callback function for loading an instance of this method
*
* @param mixed $instance
* @param mixed $title
* @return WC_Shipping_Table_Rate
*/
function woocommerce_get_shipping_method_table_rate( $instance = false ) {
return new WC_Shipping_Table_Rate( $instance );
}
| mit |
ranea/ArxPy | arxpy/primitives/multi2.py | 9765 | """MULTI2 cipher.
Source: Cryptanalysis of the ISDB Scrambling Algorithm (MULTI2)
"""
from arxpy.bitvector.core import Constant
from arxpy.bitvector.operation import RotateLeft
from arxpy.primitives.primitives import KeySchedule, Encryption, Cipher
# for BvOR and XDOr
from arxpy.bitvector.operation import BvComp, Operation
from arxpy.bitvector.extraop import PopCount
from arxpy.differential.difference import XorDiff
from arxpy.differential.derivative import Derivative
REFERENCE_VERSION = False # if True, ctes are added in the encryption
class BvOr(Operation):
"""The OR function."""
arity = [2, 0]
is_symmetric = True
@classmethod
def output_width(cls, x, y):
return x.width
@classmethod
def eval(cls, x, y):
if all(isinstance(x_i, Constant) for x_i in [x, y]):
return x | y
@classmethod
def xor_derivative(cls, input_diff):
return XDOr(input_diff)
class XDOr(Derivative):
"""Represent the derivative of the function If w.r.t XOR differences."""
diff_type = XorDiff
op = BvOr
def is_possible(self, output_diff):
dx, dy = [d.val for d in self.input_diff]
dz = output_diff.val
n = dx.width
# (dx, dy) = (0, 0) -> dz =(1)
bad_case = (~dx) & (~dy) & dz
return BvComp(bad_case, Constant(0, n))
def has_probability_one(self, output_diff):
dx, dy = [d.val for d in self.input_diff]
dz = output_diff.val
n = dx.width
# (dx, dy) = (0, 0) -> dz =(0)
pr1_case = (~dx) & (~dy) & (~dz)
return BvComp(pr1_case, ~Constant(0, n))
def weight(self, output_diff):
dx, dy = [d.val for d in self.input_diff]
return PopCount(dx | dy)
def max_weight(self):
dx, dy = [d.val for d in self.input_diff]
return dx.width
def error(self):
return 0
def exact_weight(self, output_diff):
return int(self.weight(output_diff))
def num_frac_bits(self):
return 0
def pi1(L):
return L
def pi2(R, k_i):
if REFERENCE_VERSION:
x = RotateLeft(R + k_i, 1) + (R + k_i) + (-Constant(1, 32))
else:
assert isinstance(k_i, list)
x = RotateLeft(R + k_i[0], 1) + (R + k_i[1])
return RotateLeft(x, 4) ^ x
def pi3(L, k_i, k_j):
if REFERENCE_VERSION:
y = RotateLeft(L + k_i, 2) + (L + k_i) + Constant(1, 32)
else:
assert isinstance(k_i, list)
y = RotateLeft(L + k_i[0], 2) + (L + k_i[1])
x = RotateLeft(RotateLeft(y, 8) ^ (y + k_j), 1) - (RotateLeft(y, 8) ^ (y + k_j))
return RotateLeft(x, 16) ^ (BvOr(x, L))
def pi4(R, k_i):
if REFERENCE_VERSION:
x = RotateLeft(R + k_i, 2) + (R + k_i) + Constant(1, 32)
else:
assert isinstance(k_i, list)
x = RotateLeft(R + k_i[0], 2) + (R + k_i[1])
return x
class Multi2KeySchedule(KeySchedule):
"""Key schedule function."""
rounds = 32
input_widths = [32, 32] + [32 for _ in range(8)]
output_widths = [32 for _ in range(8)]
@classmethod
def get_num_keys(cls):
num_system_keys = 0
num_round_keys = 0
for i in range(min(8, cls.rounds)):
if i == 0:
# s[1] |
num_system_keys += 1
elif i == 1:
# s[2], s[3] | k[1]
num_system_keys += 2
num_round_keys += 1
elif i == 2:
# s[4] | k[2], k[3]
num_system_keys += 1
num_round_keys += 2
elif i == 3:
# | k[4]
num_round_keys += 1
elif i == 4:
# s[5] |
num_system_keys += 1
elif i == 5:
# s[6], s[7] | k[5]
num_system_keys += 2
num_round_keys += 1
elif i == 6:
# s[8] | k[6], k[7]
num_system_keys += 1
num_round_keys += 2
elif i == 7:
# | k[8]
num_round_keys += 1
num_expanded_round_keys = num_round_keys
if not REFERENCE_VERSION:
for i in range(min(8, cls.rounds)):
if i == 0:
pass
elif i == 1:
num_expanded_round_keys += 1
elif i == 2:
num_expanded_round_keys += 1
elif i == 3:
num_expanded_round_keys += 1
elif i == 4:
pass
elif i == 5:
num_expanded_round_keys += 1
elif i == 6:
num_expanded_round_keys += 1
elif i == 7:
num_expanded_round_keys += 1
return num_system_keys, num_round_keys, num_expanded_round_keys
@classmethod
def set_rounds(cls, new_rounds):
cls.rounds = new_rounds
num_system_keys, _, num_expanded_round_keys = cls.get_num_keys()
cls.input_widths = [32, 32] + [32 for _ in range(num_system_keys)]
cls.output_widths = [32 for _ in range(num_expanded_round_keys)]
@classmethod
def eval(cls, d1, d2, *system_key):
s = [None] + list(system_key)
num_system_keys, num_round_keys, num_expanded_round_keys = cls.get_num_keys()
global REFERENCE_VERSION
old_ref_v = REFERENCE_VERSION
REFERENCE_VERSION = True
k = [None]
for i in range(num_round_keys):
if i == 0:
k.append(d1 ^ pi2(d1 ^ d2, s[1]))
elif i == 1:
k.append(d1 ^ d2 ^ pi3(k[1], s[2], s[3]))
elif i == 2:
k.append(k[1] ^ pi4(k[2], s[4]))
elif i == 3:
k.append(k[2] ^ k[3])
elif i == 4:
k.append(k[3] ^ pi2(k[4], s[5]))
elif i == 5:
k.append(k[4] ^ pi3(k[5], s[6], s[7]))
elif i == 6:
k.append(k[5] ^ pi4(k[6], s[8]))
elif i == 7:
k.append(k[6] ^ k[7])
assert len(k) == num_round_keys + 1
REFERENCE_VERSION = old_ref_v
if not REFERENCE_VERSION:
if len(k) > 8:
# pi4(R, k[8]) | pi4 : k_i + Constant(1, 32)
k.append(k[8] + Constant(1, 32))
if len(k) > 6:
# pi3(L, k[6], *) | pi3 : k_i + Constant(1, 32)
k.append(k[6] + Constant(1, 32))
if len(k) > 5:
# pi2(R, k[5]) | pi2 : k_i + (-Constant(1, 32))
k.append(k[5] + (-Constant(1, 32)))
if len(k) > 4:
# pi4(R, k[4]) | pi4 : k_i + Constant(1, 32)
k.append(k[4] + Constant(1, 32))
if len(k) > 2:
# pi3(L, k[2], *) | pi3 : k_i + Constant(1, 32)
k.append(k[2] + Constant(1, 32))
if len(k) > 1:
# pi2(R, k[1]) | pi2 : k_i + (-Constant(1, 32))
k.append(k[1] + (-Constant(1, 32)))
assert len(k) == num_expanded_round_keys + 1
return k[1: 1+num_expanded_round_keys]
class Multi2Encryption(Encryption):
"""Encryption function."""
rounds = 32
input_widths = [32, 32]
output_widths = [32, 32]
round_keys = None
@classmethod
def set_rounds(cls, new_rounds):
cls.rounds = new_rounds
@classmethod
def eval(cls, L, R):
k = [None] + list(cls.round_keys)
for i in range(cls.rounds):
if REFERENCE_VERSION:
if i % 8 == 0:
R ^= pi1(L)
elif i % 8 == 1:
L ^= pi2(R, k[1])
elif i % 8 == 2:
R ^= pi3(L, k[2], k[3])
elif i % 8 == 3:
L ^= pi4(R, k[4])
elif i % 8 == 4:
R ^= pi1(L)
elif i % 8 == 5:
L ^= pi2(R, k[5])
elif i % 8 == 6:
R ^= pi3(L, k[6], k[7])
elif i % 8 == 7:
L ^= pi4(R, k[8])
else:
if i % 8 == 0:
R ^= pi1(L)
elif i % 8 == 1:
L ^= pi2(R, [k[1], k[-1]])
elif i % 8 == 2:
R ^= pi3(L, [k[2], k[-2]], k[3])
elif i % 8 == 3:
L ^= pi4(R, [k[4], k[-3]])
elif i % 8 == 4:
R ^= pi1(L)
elif i % 8 == 5:
L ^= pi2(R, [k[5], k[-4]])
elif i % 8 == 6:
R ^= pi3(L, [k[6], k[-5]], k[7])
elif i % 8 == 7:
L ^= pi4(R, [k[8], k[-6]])
return L, R
class Multi2Cipher(Cipher):
key_schedule = Multi2KeySchedule
encryption = Multi2Encryption
rounds = 32
@classmethod
def set_rounds(cls, new_rounds):
cls.rounds = new_rounds
cls.encryption.set_rounds(new_rounds)
cls.key_schedule.set_rounds(new_rounds)
@classmethod
def test(cls):
old_rounds = cls.rounds
global REFERENCE_VERSION
for ref_v in [True, False]:
REFERENCE_VERSION = ref_v
cls.set_rounds(32)
plaintext = [0, 0]
key = [0 for _ in range(len(cls.key_schedule.input_widths))]
ciphertext = (0x1d9dfa1e, 0x4d64bc67)
assert cls(plaintext, key) == ciphertext
plaintext = [0x01, 0x23]
key = [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23]
ciphertext = (0xd241e7c8, 0x74166979)
assert cls(plaintext, key) == ciphertext
cls.set_rounds(old_rounds)
| mit |
brave/brightray | browser/browser_context.cc | 6830 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/browser_context.h"
#include "browser/brightray_paths.h"
#include "browser/browser_client.h"
#include "browser/inspectable_web_contents_impl.h"
#include "browser/network_delegate.h"
#include "browser/permission_manager.h"
#include "browser/special_storage_policy.h"
#include "common/application_info.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_service_factory.h"
#include "base/strings/string_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/storage_partition.h"
#include "net/base/escape.h"
#include "components/component_updater/component_updater_paths.h"
using content::BrowserThread;
namespace brightray {
namespace {
// Convert string to lower case and escape it.
std::string MakePartitionName(const std::string& input) {
return net::EscapePath(base::ToLowerASCII(input));
}
} // namespace
class BrowserContext::ResourceContext : public content::ResourceContext {
public:
ResourceContext() : getter_(nullptr) {}
void set_url_request_context_getter(URLRequestContextGetter* getter) {
getter_ = getter;
}
private:
net::HostResolver* GetHostResolver() override {
return getter_->host_resolver();
}
net::URLRequestContext* GetRequestContext() override {
return getter_->GetURLRequestContext();
}
URLRequestContextGetter* getter_;
};
// static
BrowserContext::BrowserContextMap BrowserContext::browser_context_map_;
// static
scoped_refptr<BrowserContext> BrowserContext::Get(
const std::string& partition, bool in_memory) {
PartitionKey key(partition, in_memory);
if (browser_context_map_[key].get())
return make_scoped_refptr(browser_context_map_[key].get());
return nullptr;
}
BrowserContext::BrowserContext(const std::string& partition, bool in_memory)
: in_memory_(in_memory),
resource_context_(new ResourceContext),
storage_policy_(new SpecialStoragePolicy),
weak_factory_(this) {
if (!PathService::Get(DIR_USER_DATA, &path_)) {
PathService::Get(DIR_APP_DATA, &path_);
path_ = path_.Append(base::FilePath::FromUTF8Unsafe(GetApplicationName()));
PathService::Override(DIR_USER_DATA, path_);
}
if (!PathService::Get(component_updater::DIR_COMPONENT_USER, &path_)) {
base::FilePath component_path =
path_.Append(FILE_PATH_LITERAL("Extensions"));
PathService::Override(component_updater::DIR_COMPONENT_USER, component_path);
}
if (!in_memory_ && !partition.empty())
path_ = path_.Append(FILE_PATH_LITERAL("Partitions"))
.Append(base::FilePath::FromUTF8Unsafe(MakePartitionName(partition)));
content::BrowserContext::Initialize(this, path_);
browser_context_map_[PartitionKey(partition, in_memory)] = GetWeakPtr();
}
BrowserContext::~BrowserContext() {
BrowserThread::DeleteSoon(BrowserThread::IO,
FROM_HERE,
resource_context_.release());
}
void BrowserContext::InitPrefs() {
auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences"));
PrefServiceFactory prefs_factory;
prefs_factory.SetUserPrefsFile(prefs_path,
JsonPrefStore::GetTaskRunnerForFile(
prefs_path, BrowserThread::GetBlockingPool()).get());
auto registry = make_scoped_refptr(new PrefRegistrySimple);
RegisterInternalPrefs(registry.get());
RegisterPrefs(registry.get());
prefs_ = prefs_factory.Create(registry.get());
}
void BrowserContext::RegisterInternalPrefs(PrefRegistrySimple* registry) {
InspectableWebContentsImpl::RegisterPrefs(registry);
}
URLRequestContextGetter* BrowserContext::GetRequestContext() {
return static_cast<URLRequestContextGetter*>(
GetDefaultStoragePartition(this)->GetURLRequestContext());
}
net::URLRequestContextGetter* BrowserContext::CreateRequestContext(
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector protocol_interceptors) {
DCHECK(!url_request_getter_.get());
url_request_getter_ = new URLRequestContextGetter(
this,
network_controller_handle(),
static_cast<NetLog*>(BrowserClient::Get()->GetNetLog()),
GetPath(),
in_memory_,
BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO),
BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE),
protocol_handlers,
std::move(protocol_interceptors));
resource_context_->set_url_request_context_getter(url_request_getter_.get());
return url_request_getter_.get();
}
net::NetworkDelegate* BrowserContext::CreateNetworkDelegate() {
return new NetworkDelegate;
}
base::FilePath BrowserContext::GetPath() const {
return path_;
}
std::unique_ptr<content::ZoomLevelDelegate> BrowserContext::CreateZoomLevelDelegate(
const base::FilePath& partition_path) {
return std::unique_ptr<content::ZoomLevelDelegate>();
}
bool BrowserContext::IsOffTheRecord() const {
return in_memory_;
}
content::ResourceContext* BrowserContext::GetResourceContext() {
return resource_context_.get();
}
content::DownloadManagerDelegate* BrowserContext::GetDownloadManagerDelegate() {
return nullptr;
}
content::BrowserPluginGuestManager* BrowserContext::GetGuestManager() {
return nullptr;
}
storage::SpecialStoragePolicy* BrowserContext::GetSpecialStoragePolicy() {
return storage_policy_.get();
}
content::PushMessagingService* BrowserContext::GetPushMessagingService() {
return nullptr;
}
content::SSLHostStateDelegate* BrowserContext::GetSSLHostStateDelegate() {
return nullptr;
}
content::PermissionManager* BrowserContext::GetPermissionManager() {
if (!permission_manager_.get())
permission_manager_.reset(new PermissionManager);
return permission_manager_.get();
}
content::BackgroundSyncController* BrowserContext::GetBackgroundSyncController() {
return nullptr;
}
net::URLRequestContextGetter*
BrowserContext::CreateRequestContextForStoragePartition(
const base::FilePath& partition_path,
bool in_memory,
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector request_interceptors) {
return nullptr;
}
net::URLRequestContextGetter*
BrowserContext::CreateMediaRequestContext() {
return url_request_getter_.get();
}
net::URLRequestContextGetter*
BrowserContext::CreateMediaRequestContextForStoragePartition(
const base::FilePath& partition_path,
bool in_memory) {
return nullptr;
}
} // namespace brightray
| mit |
tholum/PiBunny | system.d/library/BunnyTap/js/ajax.googleapis.com__ajax__libs__dojo__1.8.10__dojo__dojo.js | 116944 | /*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
/*
This is an optimized version of Dojo, built for deployment and not for
development. To get sources and documentation, please visit:
http://dojotoolkit.org
*/
//>>built
(function(b,i){var g,n=function(){},l=function(a){for(var c in a)return 0;return 1},k={}.toString,o=function(a){return"[object Function]"==k.call(a)},j=function(a){return"[object String]"==k.call(a)},e=function(a){return"[object Array]"==k.call(a)},a=function(a,c){if(a)for(var d=0;d<a.length;)c(a[d++])},f=function(a,c){for(var d in c)a[d]=c[d];return a},d=function(a,c){return f(Error(a),{src:"dojoLoader",info:c})},c=1,m=function(){return"_"+c++},h=function(a,c,d){return Ga(a,c,d,0,h)},p=this,s=p.document,
r=s&&s.createElement("DiV"),q=h.has=function(a){return o(u[a])?u[a]=u[a](p,s,r):u[a]},u=q.cache=i.hasCache;q.add=function(a,c,d,b){(void 0===u[a]||b)&&(u[a]=c);return d&&q(a)};for(var B in b.has)q.add(B,b.has[B],0,1);var t=0,v=[],x=0,E=n,I=n,J;h.isXdUrl=n;h.initSyncLoader=function(a,c,d){x||(x=a,E=c,I=d);return{sync:"sync",requested:1,arrived:2,nonmodule:3,executing:4,executed:5,syncExecStack:v,modules:w,execQ:N,getModule:S,injectModule:la,setArrived:Y,signal:z,finishExec:ca,execModule:da,dojoRequirePlugin:x,
getLegacyMode:function(){return t},guardCheckComplete:ea}};var H=location.protocol,M=location.host;h.isXdUrl=function(a){if(/^\./.test(a))return!1;return/^\/\//.test(a)?!0:(a=a.match(/^([^\/\:]+\:)\/+([^\/]+)/))&&(a[1]!=H||M&&a[2]!=M)};q.add("dojo-force-activex-xhr",!s.addEventListener&&"file:"==window.location.protocol);q.add("native-xhr","undefined"!=typeof XMLHttpRequest);if(q("native-xhr")&&!q("dojo-force-activex-xhr"))J=function(){return new XMLHttpRequest};else{var Z=["Msxml2.XMLHTTP","Microsoft.XMLHTTP",
"Msxml2.XMLHTTP.4.0"],y;for(g=0;3>g;)try{if(y=Z[g++],new ActiveXObject(y))break}catch(D){}J=function(){return new ActiveXObject(y)}}h.getXhr=J;q.add("dojo-gettext-api",1);h.getText=function(a,c,b){var f=J();f.open("GET",ma(a),!1);f.send(null);if(200==f.status||!location.host&&!f.status)b&&b(f.responseText,c);else throw d("xhrFailed",f.status);return f.responseText};var K=new Function("return eval(arguments[0]);");h.eval=function(a,c){return K(a+"\r\n//# sourceURL="+c)};var A={},z=h.signal=function(c,
d){var b=A[c];a(b&&b.slice(0),function(a){a.apply(null,e(d)?d:[d])})},L=h.on=function(a,c){var d=A[a]||(A[a]=[]);d.push(c);return{remove:function(){for(var a=0;a<d.length;a++)if(d[a]===c){d.splice(a,1);break}}}},$=[],T={},U=[],G={},F=h.map={},P=[],w={},C="",R={},Q={},aa={},V=function(a){var c,d,b,f;for(c in Q)d=Q[c],(b=c.match(/^url\:(.+)/))?R["url:"+Ha(b[1],a)]=d:"*now"==c?f=d:"*noref"!=c&&(b=fa(c,a,!0),R[b.mid]=R["url:"+b.url]=d);f&&f(wa(a));Q={}},Ia=function(a){return a.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,
function(a){return"\\"+a})},xa=function(a,c){c.splice(0,c.length);for(var d in a)c.push([d,a[d],RegExp("^"+Ia(d)+"(/|$)"),d.length]);c.sort(function(a,c){return c[3]-a[3]});return c},Ja=function(a){var c=a.name;c||(c=a,a={name:c});a=f({main:"main"},a);a.location=a.location?a.location:c;if(a.packageMap)F[c]=a.packageMap;if(!a.main.indexOf("./"))a.main=a.main.substring(2);G[c]=a},Ka=[],ga=function(c,d,b){for(var e in c){if("waitSeconds"==e)h.waitms=1E3*(c[e]||0);"cacheBust"==e&&(C=c[e]?j(c[e])?c[e]:
(new Date).getTime()+"":"");if("baseUrl"==e||"combo"==e)h[e]=c[e];if("async"==e){var m=c[e];h.legacyMode=t=j(m)&&/sync|legacyAsync/.test(m)?m:!m?"sync":!1;h.async=!t}c[e]!==u&&(h.rawConfig[e]=c[e],"has"!=e&&q.add("config-"+e,c[e],0,d))}if(!h.baseUrl)h.baseUrl="./";/\/$/.test(h.baseUrl)||(h.baseUrl+="/");for(e in c.has)q.add(e,c.has[e],0,d);a(c.packages,Ja);for(var k in c.packagePaths)a(c.packagePaths[k],function(a){var c=k+"/"+a;j(a)&&(a={name:a});a.location=c;Ja(a)});xa(f(F,c.map),P);a(P,function(a){a[1]=
xa(a[1],[]);if("*"==a[0])P.star=a});xa(f(T,c.paths),U);a(c.aliases,function(a){j(a[0])&&(a[0]=RegExp("^"+Ia(a[0])+"$"));$.push(a)});if(d)Ka.push({config:c.config});else for(e in c.config)d=S(e,b),d.config=f(d.config||{},c.config[e]);if(c.cache)V(),Q=c.cache,c.cache["*noref"]&&V();z("config",[c,h.rawConfig])};q("dojo-cdn");var La=s.getElementsByTagName("script");g=0;for(var na,X,oa,ha;g<La.length;)if(na=La[g++],(oa=na.getAttribute("src"))&&(ha=oa.match(/(((.*)\/)|^)dojo\.js(\W|$)/i))){X=ha[3]||"";
i.baseUrl=i.baseUrl||X;(oa=na.getAttribute("data-dojo-config")||na.getAttribute("djConfig"))&&(aa=h.eval("({ "+oa+" })","data-dojo-config"));break}h.rawConfig={};ga(i,1);if(q("dojo-cdn"))(G.dojo.location=X)&&(X+="/"),G.dijit.location=X+"../dijit/",G.dojox.location=X+"../dojox/";ga(b,1);ga(aa,1);var ia=function(c){ea(function(){a(c.deps,la)})},Ga=function(a,c,b,k,p){var q;if(j(a)){if((q=S(a,k,!0))&&q.executed)return q.result;throw d("undefinedModule",a);}e(a)||(ga(a,0,k),a=c,c=b);if(e(a))if(a.length){for(var b=
"require*"+m(),s,o=[],g=0;g<a.length;)s=a[g++],o.push(S(s,k));q=f(pa("",b,0,""),{injected:2,deps:o,def:c||n,require:k?k.require:h,gc:1});w[q.mid]=q;ia(q);var l=ja&&"sync"!=t;ea(function(){da(q,l)});q.executed||N.push(q);ba()}else c&&c();return p},wa=function(a){if(!a)return h;var c=a.require;if(!c)c=function(d,b,f){return Ga(d,b,f,a,c)},a.require=f(c,h),c.module=a,c.toUrl=function(c){return Ha(c,a)},c.toAbsMid=function(c){return ya(c,a)},c.syncLoadNls=function(c){var c=fa(c,a),d=w[c.mid];if(!d||!d.executed)if(W=
R[c.mid]||R["url:"+c.url])qa(W),d=w[c.mid];return d&&d.executed&&d.result};return c},N=[],ra=[],O={},Xa=function(a){a.injected=1;O[a.mid]=1;a.url&&(O[a.url]=a.pack||1);Ma()},Y=function(a){a.injected=2;delete O[a.mid];a.url&&delete O[a.url];l(O)&&(sa(),"xd"==t&&(t="sync"))},Ya=h.idle=function(){return!ra.length&&l(O)&&!N.length&&!ja},za=function(a,c){if(c)for(var d=0;d<c.length;d++)if(c[d][2].test(a))return c[d];return 0},Na=function(a){for(var c=[],d,b,a=a.replace(/\\/g,"/").split("/");a.length;)d=
a.shift(),".."==d&&c.length&&".."!=b?(c.pop(),b=c[c.length-1]):"."!=d&&c.push(b=d);return c.join("/")},pa=function(a,c,d,b){var f=h.isXdUrl(b);return{pid:a,mid:c,pack:d,url:b,executed:0,def:0,isXd:f,isAmd:!!(f||G[a]&&G[a].isAmd)}},Oa=function(c,b,f,e,m,h,k,p){var j,s,g,l;l=/^\./.test(c);if(/(^\/)|(\:)|(\.js$)/.test(c)||l&&!b)return pa(0,c,0,c);c=Na(l?b.mid+"/../"+c:c);if(/^\./.test(c))throw d("irrationalPath",c);b&&(g=za(b.mid,h));(g=(g=g||h.star)&&za(c,g[1]))&&(c=g[1]+c.substring(g[3]));b=(ha=c.match(/^([^\/]+)(\/(.+))?$/))?
ha[1]:"";(j=f[b])?c=b+"/"+(s=ha[3]||j.main):b="";var i=0;a($,function(a){var d=c.match(a[0]);d&&0<d.length&&(i=o(a[1])?c.replace(a[0],a[1]):a[1])});if(i)return Oa(i,0,f,e,m,h,k,p);if(f=e[c])return p?pa(f.pid,f.mid,f.pack,f.url):e[c];e=(g=za(c,k))?g[1]+c.substring(g[3]):b?j.location+"/"+s:q("config-tlmSiblingOfDojo")?"../"+c:c;/(^\/)|(\:)/.test(e)||(e=m+e);return pa(b,c,j,Na(e+".js"))},fa=function(a,c,d){return Oa(a,c,G,w,h.baseUrl,d?[]:P,d?[]:U)},Pa=function(a,c,d){return a.normalize?a.normalize(c,
function(a){return ya(a,d)}):ya(c,d)},Qa=0,S=function(a,c,d){var b,f;(b=a.match(/^(.+?)\!(.*)$/))?(f=S(b[1],c,d),"sync"==t&&!f.executed&&(la(f),2===f.injected&&!f.executed&&ea(function(){da(f)}),f.executed?ta(f):N.unshift(f)),5===f.executed&&!f.load&&ta(f),f.load?(b=Pa(f,b[2],c),a=f.mid+"!"+(f.dynamic?++Qa+"!":"")+b):(b=b[2],a=f.mid+"!"+ ++Qa+"!waitingForPlugin"),a={plugin:f,mid:a,req:wa(c),prid:b}):a=fa(a,c);return w[a.mid]||!d&&(w[a.mid]=a)},ya=h.toAbsMid=function(a,c){return fa(a,c).mid},Ha=h.toUrl=
function(a,c){var d=fa(a+"/x",c),b=d.url;return ma(0===d.pid?a:b.substring(0,b.length-5))},Ra={injected:2,executed:5,def:3,result:3},Aa=function(a){return w[a]=f({mid:a},Ra)},Za=Aa("require"),$a=Aa("exports"),ab=Aa("module"),ua={},Ba=0,ta=function(a){var c=a.result;a.dynamic=c.dynamic;a.normalize=c.normalize;a.load=c.load;return a},bb=function(c){var d={};a(c.loadQ,function(a){var b=Pa(c,a.prid,a.req.module),e=c.dynamic?a.mid.replace(/waitingForPlugin$/,b):c.mid+"!"+b,b=f(f({},a),{mid:e,prid:b,injected:0});
w[e]||Sa(w[e]=b);d[a.mid]=w[e];Y(a);delete w[a.mid]});c.loadQ=0;var b=function(a){for(var c=a.deps||[],b=0;b<c.length;b++)(a=d[c[b].mid])&&(c[b]=a)},e;for(e in w)b(w[e]);a(N,b)},ca=function(c){h.trace("loader-finish-exec",[c.mid]);c.executed=5;c.defOrder=Ba++;a(c.provides,function(a){a()});c.loadQ&&(ta(c),bb(c));for(g=0;g<N.length;)N[g]===c?N.splice(g,1):g++;/^require\*/.test(c.mid)&&delete w[c.mid]},cb=[],da=function(a,c){if(4===a.executed)return h.trace("loader-circular-dependency",[cb.concat(a.mid).join("->")]),
!a.def||c?ua:a.cjs&&a.cjs.exports;if(!a.executed){if(!a.def)return ua;var b=a.mid,f=a.deps||[],e,m=[],k=0;for(a.executed=4;k<f.length;){e=f[k++];e=e===Za?wa(a):e===$a?a.cjs.exports:e===ab?a.cjs:da(e,c);if(e===ua)return a.executed=0,h.trace("loader-exec-module",["abort",b]),ua;m.push(e)}h.trace("loader-run-factory",[a.mid]);var b=a.def,p;v.unshift(a);if(q("config-dojo-loader-catches"))try{p=o(b)?b.apply(null,m):b}catch(j){z("error",a.result=d("factoryThrew",[a,j]))}else p=o(b)?b.apply(null,m):b;a.result=
void 0===p&&a.cjs?a.cjs.exports:p;v.shift(a);ca(a)}return a.result},ja=0,ea=function(a){try{ja++,a()}finally{ja--}Ya()&&z("idle",[])},ba=function(){ja||ea(function(){E();for(var a,c,d=0;d<N.length;)a=Ba,c=N[d],da(c),a!=Ba?(E(),d=0):d++})};void 0===q("dojo-loader-eval-hint-url")&&q.add("dojo-loader-eval-hint-url",1);var ma=function(a){a+="";return a+(C?(/\?/.test(a)?"&":"?")+C:"")},Sa=function(a){var c=a.plugin;5===c.executed&&!c.load&&ta(c);var d=function(c){a.result=c;Y(a);ca(a);ba()};c.load?c.load(a.prid,
a.req,d):c.loadQ?c.loadQ.push(a):(c.loadQ=[a],N.unshift(c),la(c))},W=0,ka=0,Ca=0,qa=function(a,c){q("config-stripStrict")&&(a=a.replace(/"use strict"/g,""));Ca=1;if(q("config-dojo-loader-catches"))try{a===W?W.call(null):h.eval(a,q("dojo-loader-eval-hint-url")?c.url:c.mid)}catch(b){z("error",d("evalModuleThrew",c))}else a===W?W.call(null):h.eval(a,q("dojo-loader-eval-hint-url")?c.url:c.mid);Ca=0},la=function(c){var b=c.mid,e=c.url;if(!c.executed&&!c.injected&&!(O[b]||c.url&&(c.pack&&O[c.url]===c.pack||
1==O[c.url])))if(Xa(c),c.plugin)Sa(c);else{var m=function(){Ta(c);2!==c.injected&&(Y(c),f(c,Ra),h.trace("loader-define-nonmodule",[c.url]));t?!v.length&&ba():ba()};if(W=R[b]||R["url:"+c.url])h.trace("loader-inject",["cache",c.mid,e]),qa(W,c),m();else{if(t)if(c.isXd)"sync"==t&&(t="xd");else if(!(c.isAmd&&"sync"!=t)){var k=function(d){if("sync"==t){v.unshift(c);qa(d,c);v.shift();Ta(c);c.cjs||(Y(c),ca(c));if(c.finish){var d=b+"*finish",f=c.finish;delete c.finish;Da(d,["dojo",("dojo/require!"+f.join(",")).replace(/\./g,
"/")],function(c){a(f,function(a){c.require(a)})});N.unshift(S(d))}m()}else(d=I(c,d))?(qa(d,c),m()):(ka=c,h.injectUrl(ma(e),m,c),ka=0)};h.trace("loader-inject",["xhr",c.mid,e,"sync"!=t]);if(q("config-dojo-loader-catches"))try{h.getText(e,"sync"!=t,k)}catch(p){z("error",d("xhrInjectFailed",[c,p]))}else h.getText(e,"sync"!=t,k);return}h.trace("loader-inject",["script",c.mid,e]);ka=c;h.injectUrl(ma(e),m,c);ka=0}}},Ea=function(a,c,b){h.trace("loader-define-module",[a.mid,c]);var e=a.mid;if(2===a.injected)return z("error",
d("multipleDefine",a)),a;f(a,{deps:c,def:b,cjs:{id:a.mid,uri:a.url,exports:a.result={},setExports:function(c){a.cjs.exports=c},config:function(){return a.config}}});for(var m=0;m<c.length;m++)c[m]=S(c[m],a);t&&!O[e]&&(ia(a),N.push(a),ba());Y(a);if(!o(b)&&!c.length)a.result=b,ca(a);return a},Ta=function(c,d){for(var b=[],f,e;ra.length;)e=ra.shift(),d&&(e[0]=d.shift()),f=e[0]&&S(e[0])||c,b.push([f,e[1],e[2]]);V(c);a(b,function(a){ia(Ea.apply(null,a))})},va=0,sa=n,Ma=n;sa=function(){va&&clearTimeout(va);
va=0};Ma=function(){sa();h.waitms&&(va=window.setTimeout(function(){sa();z("error",d("timeout",O))},h.waitms))};q.add("ie-event-behavior",!!s.attachEvent&&("undefined"===typeof opera||"[object Opera]"!=opera.toString()));var Fa=function(a,c,d,b){if(q("ie-event-behavior"))return a.attachEvent(d,b),function(){a.detachEvent(d,b)};a.addEventListener(c,b,!1);return function(){a.removeEventListener(c,b,!1)}},db=Fa(window,"load","onload",function(){h.pageLoaded=1;"complete"!=s.readyState&&(s.readyState=
"complete");db()}),Ua=s.getElementsByTagName("script")[0],eb=Ua.parentNode;h.injectUrl=function(a,c,b){var b=b.node=s.createElement("script"),f=Fa(b,"load","onreadystatechange",function(a){var a=a||window.event,d=a.target||a.srcElement;if("load"===a.type||/complete|loaded/.test(d.readyState))f(),e(),c&&c()}),e=Fa(b,"error","onerror",function(c){f();e();z("error",d("scriptError",[a,c]))});b.type="text/javascript";b.charset="utf-8";b.src=a;eb.insertBefore(b,Ua);return b};h.log=function(){try{for(var a=
0;a<arguments.length;a++);}catch(c){}};h.trace=n;var Da=function(a,c,b){var f=arguments.length,e=["require","exports","module"],m=[0,a,c];1==f?m=[0,o(a)?e:[],a]:2==f&&j(a)?m=[a,o(c)?e:[],c]:3==f&&(m=[a,c,b]);h.trace("loader-define",m.slice(0,2));if((f=m[0]&&S(m[0]))&&!O[f.mid])ia(Ea(f,m[1],m[2]));else if(!q("ie-event-behavior")||Ca)ra.push(m);else{f=f||ka;if(!f)for(a in O)if((e=w[a])&&e.node&&"interactive"===e.node.readyState){f=e;break}f?(V(f),ia(Ea(f,m[1],m[2]))):z("error",d("ieDefineFailed",m[0]));
ba()}};Da.amd={vendor:"dojotoolkit.org"};f(f(h,i.loaderPatch),b.loaderPatch);L("error",function(a){try{if(console.error(a),a instanceof Error)for(var c in a);}catch(d){}});f(h,{uid:m,cache:R,packs:G});if(p.define)z("error",d("defineAlreadyDefined",0));else{p.define=Da;p.require=h;a(Ka,function(a){ga(a)});var Va=aa.deps||b.deps||i.deps,Wa=aa.callback||b.callback||i.callback;h.boot=Va||Wa?[Va||[],Wa]:0}})(this.dojoConfig||this.djConfig||this.require||{},{async:"legacyAsync",hasCache:{"config-selectorEngine":"acme",
"config-tlmSiblingOfDojo":1,"dojo-built":1,"dojo-cdn":1,"dojo-loader":1,dom:1,"host-browser":1},packages:[{location:"../dijit",name:"dijit"},{location:"../dojox",name:"dojox"},{location:".",name:"dojo"}]});
require({cache:{"dojo/_base/fx":function(){define("dojo/_base/fx","./kernel,./config,./lang,../Evented,./Color,./connect,./sniff,../dom,../dom-style".split(","),function(b,i,g,n,l,k,o,j,e){var a=g.mixin,f={},d=f._Line=function(a,c){this.start=a;this.end=c};d.prototype.getValue=function(a){return(this.end-this.start)*a+this.start};var c=f.Animation=function(c){a(this,c);if(g.isArray(this.curve))this.curve=new d(this.curve[0],this.curve[1])};c.prototype=new n;g.extend(c,{duration:350,repeat:0,rate:20,
_percent:0,_startRepeatCount:0,_getStep:function(){var a=this._percent,c=this.easing;return c?c(a):a},_fire:function(a,c){var d=c||[];if(this[a])if(i.debugAtAllCosts)this[a].apply(this,d);else try{this[a].apply(this,d)}catch(b){console.error("exception in animation handler for:",a),console.error(b)}return this},play:function(a,c){this._delayTimer&&this._clearTimer();if(c)this._stopTimer(),this._active=this._paused=!1,this._percent=0;else if(this._active&&!this._paused)return this;this._fire("beforeBegin",
[this.node]);var d=a||this.delay,b=g.hitch(this,"_play",c);if(0<d)return this._delayTimer=setTimeout(b,d),this;b();return this},_play:function(){this._delayTimer&&this._clearTimer();this._startTime=(new Date).valueOf();this._paused&&(this._startTime-=this.duration*this._percent);this._active=!0;this._paused=!1;var a=this.curve.getValue(this._getStep());if(!this._percent){if(!this._startRepeatCount)this._startRepeatCount=this.repeat;this._fire("onBegin",[a])}this._fire("onPlay",[a]);this._cycle();
return this},pause:function(){this._delayTimer&&this._clearTimer();this._stopTimer();if(!this._active)return this;this._paused=!0;this._fire("onPause",[this.curve.getValue(this._getStep())]);return this},gotoPercent:function(a,c){this._stopTimer();this._active=this._paused=!0;this._percent=a;c&&this.play();return this},stop:function(a){this._delayTimer&&this._clearTimer();if(!this._timer)return this;this._stopTimer();if(a)this._percent=1;this._fire("onStop",[this.curve.getValue(this._getStep())]);
this._active=this._paused=!1;return this},status:function(){return this._active?this._paused?"paused":"playing":"stopped"},_cycle:function(){if(this._active){var a=(new Date).valueOf(),a=0===this.duration?1:(a-this._startTime)/this.duration;1<=a&&(a=1);this._percent=a;this.easing&&(a=this.easing(a));this._fire("onAnimate",[this.curve.getValue(a)]);if(1>this._percent)this._startTimer();else{this._active=!1;if(0<this.repeat)this.repeat--,this.play(null,!0);else if(-1==this.repeat)this.play(null,!0);
else if(this._startRepeatCount)this.repeat=this._startRepeatCount,this._startRepeatCount=0;this._percent=0;this._fire("onEnd",[this.node]);!this.repeat&&this._stopTimer()}}return this},_clearTimer:function(){clearTimeout(this._delayTimer);delete this._delayTimer}});var m=0,h=null,p={run:function(){}};g.extend(c,{_startTimer:function(){if(!this._timer)this._timer=k.connect(p,"run",this,"_cycle"),m++;h||(h=setInterval(g.hitch(p,"run"),this.rate))},_stopTimer:function(){if(this._timer)k.disconnect(this._timer),
this._timer=null,m--;0>=m&&(clearInterval(h),h=null,m=0)}});var s=o("ie")?function(a){var c=a.style;if(!c.width.length&&"auto"==e.get(a,"width"))c.width="auto"}:function(){};f._fade=function(c){c.node=j.byId(c.node);var d=a({properties:{}},c),c=d.properties.opacity={};c.start=!("start"in d)?function(){return+e.get(d.node,"opacity")||0}:d.start;c.end=d.end;c=f.animateProperty(d);k.connect(c,"beforeBegin",g.partial(s,d.node));return c};f.fadeIn=function(c){return f._fade(a({end:1},c))};f.fadeOut=function(c){return f._fade(a({end:0},
c))};f._defaultEasing=function(a){return 0.5+Math.sin((a+1.5)*Math.PI)/2};var r=function(a){this._properties=a;for(var c in a){var d=a[c];if(d.start instanceof l)d.tempColor=new l}};r.prototype.getValue=function(a){var c={},d;for(d in this._properties){var b=this._properties[d],f=b.start;f instanceof l?c[d]=l.blendColors(f,b.end,a,b.tempColor).toCss():g.isArray(f)||(c[d]=(b.end-f)*a+f+("opacity"!=d?b.units||"px":0))}return c};f.animateProperty=function(d){var f=d.node=j.byId(d.node);if(!d.easing)d.easing=
b._defaultEasing;d=new c(d);k.connect(d,"beforeBegin",d,function(){var c={},d;for(d in this.properties){if("width"==d||"height"==d)this.node.display="block";var b=this.properties[d];g.isFunction(b)&&(b=b(f));b=c[d]=a({},g.isObject(b)?b:{end:b});if(g.isFunction(b.start))b.start=b.start(f);if(g.isFunction(b.end))b.end=b.end(f);var m=0<=d.toLowerCase().indexOf("color"),h=function(a,c){var d={height:a.offsetHeight,width:a.offsetWidth}[c];if(void 0!==d)return d;d=e.get(a,c);return"opacity"==c?+d:m?d:parseFloat(d)};
if("end"in b){if(!("start"in b))b.start=h(f,d)}else b.end=h(f,d);m?(b.start=new l(b.start),b.end=new l(b.end)):b.start="opacity"==d?+b.start:parseFloat(b.start)}this.curve=new r(c)});k.connect(d,"onAnimate",g.hitch(e,"set",d.node));return d};f.anim=function(a,d,b,e,m,h){return f.animateProperty({node:a,duration:b||c.prototype.duration,properties:d,easing:e,onEnd:m}).play(h||0)};a(b,f);b._Animation=c;return f})},"dojo/dom-form":function(){define(["./_base/lang","./dom","./io-query","./json"],function(b,
i,g,n){var l={fieldToObject:function(b){var g=null;if(b=i.byId(b)){var j=b.name,e=(b.type||"").toLowerCase();if(j&&e&&!b.disabled)if("radio"==e||"checkbox"==e){if(b.checked)g=b.value}else if(b.multiple){g=[];for(b=[b.firstChild];b.length;)for(j=b.pop();j;j=j.nextSibling)if(1==j.nodeType&&"option"==j.tagName.toLowerCase())j.selected&&g.push(j.value);else{j.nextSibling&&b.push(j.nextSibling);j.firstChild&&b.push(j.firstChild);break}}else g=b.value}return g},toObject:function(k){for(var g={},k=i.byId(k).elements,
j=0,e=k.length;j<e;++j){var a=k[j],f=a.name,d=(a.type||"").toLowerCase();if(f&&d&&0>"file|submit|image|reset|button".indexOf(d)&&!a.disabled){var c=g,m=f,a=l.fieldToObject(a);if(null!==a){var h=c[m];"string"==typeof h?c[m]=[h,a]:b.isArray(h)?h.push(a):c[m]=a}if("image"==d)g[f+".x"]=g[f+".y"]=g[f].x=g[f].y=0}}return g},toQuery:function(b){return g.objectToQuery(l.toObject(b))},toJson:function(b,g){return n.stringify(l.toObject(b),null,g?4:0)}};return l})},"dojo/i18n":function(){define("./_base/kernel,require,./has,./_base/array,./_base/config,./_base/lang,./_base/xhr,./json,module".split(","),
function(b,i,g,n,l,k,o,j,e){g.add("dojo-preload-i18n-Api",1);var a=b.i18n={},f=/(^.*(^|\/)nls)(\/|$)([^\/]*)\/?([^\/]*)/,d=function(a,c,b,d){for(var f=[b+d],c=c.split("-"),e="",m=0;m<c.length;m++)e+=(e?"-":"")+c[m],(!a||a[e])&&f.push(b+e+"/"+d);return f},c={},m=function(a,c,d){d=d?d.toLowerCase():b.locale;a=a.replace(/\./g,"/");c=c.replace(/\./g,"/");return/root/i.test(d)?a+"/nls/"+c:a+"/nls/"+d+"/"+c};b.getL10nName=function(a,c,d){return e.id+"!"+m(a,c,d)};var h=function(a,b,f,e,m,h){a([b],function(p){var j=
k.clone(p.root||p.ROOT),g=d(!p._v1x&&p,m,f,e);a(g,function(){for(var a=1;a<g.length;a++)j=k.mixin(k.clone(j),arguments[a]);c[b+"/"+m]=j;h()})})},p=function(a){var c=l.extraLocale||[],c=k.isArray(c)?c:[c];c.push(a);return c},s=function(a,d,e){if(g("dojo-preload-i18n-Api")){var m=a.split("*"),s="preload"==m[1];s&&(c[a]||(c[a]=1,t(m[2],j.parse(m[3]),1,d)),e(1));if(!(m=s))u&&B.push([a,d,e]),m=u;if(m)return}var a=f.exec(a),l=a[1]+"/",o=a[5]||a[4],i=l+o,m=(a=a[5]&&a[4])||b.locale,q=i+"/"+m,a=a?[m]:p(m),
r=a.length,x=function(){--r||e(k.delegate(c[q]))};n.forEach(a,function(a){var b=i+"/"+a;g("dojo-preload-i18n-Api")&&v(b);c[b]?x():h(d,i,l,o,a,x)})};if(g("dojo-unit-tests"))var r=a.unitTests=[];g("dojo-preload-i18n-Api");var q=a.normalizeLocale=function(a){a=a?a.toLowerCase():b.locale;return"root"==a?"ROOT":a},u=0,B=[],t=a._preloadLocalizations=function(a,d,f,e){function m(a,c){e.isXdUrl(i.toUrl(a+".js"))||f?e([a],c):I([a],c,e)}function h(a,c){for(var d=a.split("-");d.length;){if(c(d.join("-")))return;
d.pop()}c("ROOT")}function p(){for(--u;!u&&B.length;)s.apply(null,B.shift())}function j(b){b=q(b);h(b,function(f){if(0<=n.indexOf(d,f)){var j=a.replace(/\./g,"/")+"_"+f;u++;m(j,function(a){for(var d in a){var m=a[d],j=d.match(/(.+)\/([^\/]+)$/),g;if(j){g=j[2];j=j[1]+"/";m._localized=m._localized||{};var s;if("ROOT"===f){var l=s=m._localized;delete m._localized;l.root=m;c[i.toAbsMid(d)]=l}else s=m._localized,c[i.toAbsMid(j+g+"/"+f)]=m;f!==b&&function(a,d,f,m){var j=[],g=[];h(b,function(c){m[c]&&(j.push(i.toAbsMid(a+
c+"/"+d)),g.push(i.toAbsMid(a+d+"/"+c)))});j.length?(u++,e(j,function(){for(var e=0;e<j.length;e++)f=k.mixin(k.clone(f),arguments[e]),c[g[e]]=f;c[i.toAbsMid(a+d+"/"+b)]=k.clone(f);p()})):c[i.toAbsMid(a+d+"/"+b)]=f}(j,g,m,s)}}p()});return!0}return!1})}e=e||i;j();n.forEach(b.config.extraLocale,j)},v=function(){},x={},E=new Function("__bundle","__checkForLegacyModules","__mid","__amdValue","var define = function(mid, factory){define.called = 1; __amdValue.result = factory || mid;},\t require = function(){define.called = 1;};try{define.called = 0;eval(__bundle);if(define.called==1)return __amdValue;if((__checkForLegacyModules = __checkForLegacyModules(__mid)))return __checkForLegacyModules;}catch(e){}try{return eval('('+__bundle+')');}catch(e){return e;}"),
I=function(a,d,b){var f=[];n.forEach(a,function(a){function d(b){b=E(b,v,a,x);b===x?f.push(c[e]=x.result):(b instanceof Error&&(console.error("failed to evaluate i18n bundle; url="+e,b),b={}),f.push(c[e]=/nls\/[^\/]+\/[^\/]+$/.test(e)?b:{root:b,_v1x:1}))}var e=b.toUrl(a+".js");if(c[e])f.push(c[e]);else{var m=b.syncLoadNls(a);if(m)f.push(m);else if(o)o.get({url:e,sync:!0,load:d,error:function(){f.push(c[e]={})}});else try{b.getText(e,!0,d)}catch(h){f.push(c[e]={})}}});d&&d.apply(null,f)},v=function(a){for(var d,
f=a.split("/"),e=b.global[f[0]],m=1;e&&m<f.length-1;e=e[f[m++]]);e&&((d=e[f[m]])||(d=e[f[m].replace(/-/g,"_")]),d&&(c[a]=d));return d};a.getLocalization=function(a,c,d){var b,a=m(a,c,d);s(a,!i.isXdUrl(i.toUrl(a+".js"))?function(a,c){I(a,c,i)}:i,function(a){b=a});return b};g("dojo-unit-tests")&&r.push(function(a){a.register("tests.i18n.unit",function(a){var c;c=E("{prop:1}",v,"nonsense",x);a.is({prop:1},c);a.is(void 0,c[1]);c=E("({prop:1})",v,"nonsense",x);a.is({prop:1},c);a.is(void 0,c[1]);c=E("{'prop-x':1}",
v,"nonsense",x);a.is({"prop-x":1},c);a.is(void 0,c[1]);c=E("({'prop-x':1})",v,"nonsense",x);a.is({"prop-x":1},c);a.is(void 0,c[1]);c=E("define({'prop-x':1})",v,"nonsense",x);a.is(x,c);a.is({"prop-x":1},x.result);c=E("define('some/module', {'prop-x':1})",v,"nonsense",x);a.is(x,c);a.is({"prop-x":1},x.result);c=E("this is total nonsense and should throw an error",v,"nonsense",x);a.is(c instanceof Error,!0)})});return k.mixin(a,{dynamic:!0,normalize:function(a,c){return/^\./.test(a)?c(a):a},load:s,cache:c})})},
"dojo/promise/tracer":function(){define("dojo/promise/tracer",["../_base/lang","./Promise","../Evented"],function(b,i,g){function n(b){setTimeout(function(){k.apply(l,b)},0)}var l=new g,k=l.emit;l.emit=null;i.prototype.trace=function(){var k=b._toArray(arguments);this.then(function(b){n(["resolved",b].concat(k))},function(b){n(["rejected",b].concat(k))},function(b){n(["progress",b].concat(k))});return this};i.prototype.traceRejected=function(){var k=b._toArray(arguments);this.otherwise(function(b){n(["rejected",
b].concat(k))});return this};return l})},"dojo/errors/RequestError":function(){define("dojo/errors/RequestError",["./create"],function(b){return b("RequestError",function(b,g){this.response=g})})},"dojo/_base/html":function(){define("./kernel,../dom,../dom-style,../dom-attr,../dom-prop,../dom-class,../dom-construct,../dom-geometry".split(","),function(b,i,g,n,l,k,o,j){b.byId=i.byId;b.isDescendant=i.isDescendant;b.setSelectable=i.setSelectable;b.getAttr=n.get;b.setAttr=n.set;b.hasAttr=n.has;b.removeAttr=
n.remove;b.getNodeProp=n.getNodeProp;b.attr=function(b,a,f){return 2==arguments.length?n["string"==typeof a?"get":"set"](b,a):n.set(b,a,f)};b.hasClass=k.contains;b.addClass=k.add;b.removeClass=k.remove;b.toggleClass=k.toggle;b.replaceClass=k.replace;b._toDom=b.toDom=o.toDom;b.place=o.place;b.create=o.create;b.empty=function(b){o.empty(b)};b._destroyElement=b.destroy=function(b){o.destroy(b)};b._getPadExtents=b.getPadExtents=j.getPadExtents;b._getBorderExtents=b.getBorderExtents=j.getBorderExtents;
b._getPadBorderExtents=b.getPadBorderExtents=j.getPadBorderExtents;b._getMarginExtents=b.getMarginExtents=j.getMarginExtents;b._getMarginSize=b.getMarginSize=j.getMarginSize;b._getMarginBox=b.getMarginBox=j.getMarginBox;b.setMarginBox=j.setMarginBox;b._getContentBox=b.getContentBox=j.getContentBox;b.setContentSize=j.setContentSize;b._isBodyLtr=b.isBodyLtr=j.isBodyLtr;b._docScroll=b.docScroll=j.docScroll;b._getIeDocumentElementOffset=b.getIeDocumentElementOffset=j.getIeDocumentElementOffset;b._fixIeBiDiScrollLeft=
b.fixIeBiDiScrollLeft=j.fixIeBiDiScrollLeft;b.position=j.position;b.marginBox=function(b,a){return a?j.setMarginBox(b,a):j.getMarginBox(b)};b.contentBox=function(b,a){return a?j.setContentSize(b,a):j.getContentBox(b)};b.coords=function(e,a){b.deprecated("dojo.coords()","Use dojo.position() or dojo.marginBox().");var e=i.byId(e),f=g.getComputedStyle(e),f=j.getMarginBox(e,f),d=j.position(e,a);f.x=d.x;f.y=d.y;return f};b.getProp=l.get;b.setProp=l.set;b.prop=function(b,a,f){return 2==arguments.length?
l["string"==typeof a?"get":"set"](b,a):l.set(b,a,f)};b.getStyle=g.get;b.setStyle=g.set;b.getComputedStyle=g.getComputedStyle;b.__toPixelValue=b.toPixelValue=g.toPixelValue;b.style=function(b,a,f){switch(arguments.length){case 1:return g.get(b);case 2:return g["string"==typeof a?"get":"set"](b,a)}return g.set(b,a,f)};return b})},"dojo/_base/kernel":function(){define(["../has","./config","require","module"],function(b,i,g,n){var l,k;l=function(){return this}();var o={},j={},e={config:i,global:l,dijit:o,
dojox:j},o={dojo:["dojo",e],dijit:["dijit",o],dojox:["dojox",j]},n=g.map&&g.map[n.id.match(/[^\/]+/)[0]];for(k in n)o[k]?o[k][0]=n[k]:o[k]=[n[k],{}];for(k in o)n=o[k],n[1]._scopeName=n[0],i.noGlobals||(l[n[0]]=n[1]);e.scopeMap=o;e.baseUrl=e.config.baseUrl=g.baseUrl;e.isAsync=g.async;e.locale=i.locale;l="$Rev: 7199349 $".match(/[0-9a-f]{7,}/);e.version={major:1,minor:8,patch:10,flag:"",revision:l?l[0]:NaN,toString:function(){var a=e.version;return a.major+"."+a.minor+"."+a.patch+a.flag+" ("+a.revision+
")"}};Function("d","d.eval = function(){return d.global.eval ? d.global.eval(arguments[0]) : eval(arguments[0]);}")(e);e.exit=function(){};"undefined"!=typeof console||(console={});var n="assert,count,debug,dir,dirxml,error,group,groupEnd,info,profile,profileEnd,time,timeEnd,trace,warn,log".split(","),a;for(l=0;a=n[l++];)console[a]||function(){var b=a+"";console[b]="log"in console?function(){var a=Array.prototype.slice.call(arguments);a.unshift(b+":");console.log(a.join(" "))}:function(){};console[b]._fake=
!0}();b.add("dojo-debug-messages",!!i.isDebug);e.deprecated=e.experimental=function(){};if(b("dojo-debug-messages"))e.deprecated=function(a,b,c){a="DEPRECATED: "+a;b&&(a+=" "+b);c&&(a+=" -- will be removed in version: "+c);console.warn(a)},e.experimental=function(a,b){var c="EXPERIMENTAL: "+a+" -- APIs subject to change without notice.";b&&(c+=" "+b);console.warn(c)};if(i.modulePaths){e.deprecated("dojo.modulePaths","use paths configuration");b={};for(k in i.modulePaths)b[k.replace(/\./g,"/")]=i.modulePaths[k];
g({paths:b})}e.moduleUrl=function(a,b){e.deprecated("dojo.moduleUrl()","use require.toUrl","2.0");var c=null;a&&(c=g.toUrl(a.replace(/\./g,"/")+(b?"/"+b:"")+"/*.*").replace(/\/\*\.\*/,"")+(b?"":"/"));return c};e._hasResource={};return e})},"dojo/io-query":function(){define(["./_base/lang"],function(b){var i={};return{objectToQuery:function(g){var n=encodeURIComponent,l=[],k;for(k in g){var o=g[k];if(o!=i[k]){var j=n(k)+"=";if(b.isArray(o))for(var e=0,a=o.length;e<a;++e)l.push(j+n(o[e]));else l.push(j+
n(o))}}return l.join("&")},queryToObject:function(g){for(var i=decodeURIComponent,g=g.split("&"),l={},k,o,j=0,e=g.length;j<e;++j)if(o=g[j],o.length){var a=o.indexOf("=");0>a?(k=i(o),o=""):(k=i(o.slice(0,a)),o=i(o.slice(a+1)));"string"==typeof l[k]&&(l[k]=[l[k]]);b.isArray(l[k])?l[k].push(o):l[k]=o}return l}}})},"dojo/_base/Deferred":function(){define("./kernel,../Deferred,../promise/Promise,../errors/CancelError,../has,./lang,../when".split(","),function(b,i,g,n,l,k,o){var j=function(){},e=Object.freeze||
function(){},a=b.Deferred=function(b){function d(a){if(h)throw Error("This deferred has already been resolved");m=a;h=!0;c()}function c(){for(var a;!a&&o;){var c=o;o=o.next;if(a=c.progress==j)h=!1;var b=p?c.error:c.resolved;l("config-useDeferredInstrumentation")&&p&&i.instrumentRejected&&i.instrumentRejected(m,!!b);if(b)try{var d=b(m);d&&"function"===typeof d.then?d.then(k.hitch(c.deferred,"resolve"),k.hitch(c.deferred,"reject"),k.hitch(c.deferred,"progress")):(b=a&&void 0===d,a&&!b&&(p=d instanceof
Error),c.deferred[b&&p?"reject":"resolve"](b?m:d))}catch(f){c.deferred.reject(f)}else p?c.deferred.reject(m):c.deferred.resolve(m)}}var m,h,p,s,o,q=this.promise=new g;this.resolve=this.callback=function(a){this.fired=0;this.results=[a,null];d(a)};this.reject=this.errback=function(a){p=!0;this.fired=1;l("config-useDeferredInstrumentation")&&i.instrumentRejected&&i.instrumentRejected(a,!!o);d(a);this.results=[null,a]};this.progress=function(a){for(var c=o;c;){var b=c.progress;b&&b(a);c=c.next}};this.addCallbacks=
function(a,c){this.then(a,c,j);return this};q.then=this.then=function(b,d,f){var e=f==j?this:new a(q.cancel),b={resolved:b,error:d,progress:f,deferred:e};o?s=s.next=b:o=s=b;h&&c();return e.promise};var u=this;q.cancel=this.cancel=function(){if(!h){var a=b&&b(u);if(!h)a instanceof Error||(a=new n(a)),a.log=!1,u.reject(a)}};e(q)};k.extend(a,{addCallback:function(a){return this.addCallbacks(k.hitch.apply(b,arguments))},addErrback:function(a){return this.addCallbacks(null,k.hitch.apply(b,arguments))},
addBoth:function(a){var d=k.hitch.apply(b,arguments);return this.addCallbacks(d,d)},fired:-1});a.when=b.when=o;return a})},"dojo/NodeList-dom":function(){define("./_base/kernel,./query,./_base/array,./_base/lang,./dom-class,./dom-construct,./dom-geometry,./dom-attr,./dom-style".split(","),function(b,i,g,n,l,k,o,j,e){function a(a){return function(c,b,d){return 2==arguments.length?a["string"==typeof b?"get":"set"](c,b):a.set(c,b,d)}}var f=function(a){return 1==a.length&&"string"==typeof a[0]},d=function(a){var c=
a.parentNode;c&&c.removeChild(a)},c=i.NodeList,m=c._adaptWithCondition,h=c._adaptAsForEach,p=c._adaptAsMap;n.extend(c,{_normalize:function(a,c){var d=!0===a.parse;if("string"==typeof a.template)var f=a.templateFunc||b.string&&b.string.substitute,a=f?f(a.template,a):a;f=typeof a;"string"==f||"number"==f?(a=k.toDom(a,c&&c.ownerDocument),a=11==a.nodeType?n._toArray(a.childNodes):[a]):n.isArrayLike(a)?n.isArray(a)||(a=n._toArray(a)):a=[a];if(d)a._runParse=!0;return a},_cloneNode:function(a){return a.cloneNode(!0)},
_place:function(a,c,d,f){if(!(1!=c.nodeType&&"only"==d))for(var e,m=a.length,h=m-1;0<=h;h--){var p=f?this._cloneNode(a[h]):a[h];if(a._runParse&&b.parser&&b.parser.parse){e||(e=c.ownerDocument.createElement("div"));e.appendChild(p);b.parser.parse(e);for(p=e.firstChild;e.firstChild;)e.removeChild(e.firstChild)}h==m-1?k.place(p,c,d):c.parentNode.insertBefore(p,c);c=p}},position:p(o.position),attr:m(a(j),f),style:m(a(e),f),addClass:h(l.add),removeClass:h(l.remove),toggleClass:h(l.toggle),replaceClass:h(l.replace),
empty:h(k.empty),removeAttr:h(j.remove),marginBox:p(o.getMarginBox),place:function(a,c){var b=i(a)[0];return this.forEach(function(a){k.place(a,b,c)})},orphan:function(a){return(a?i._filterResult(this,a):this).forEach(d)},adopt:function(a,c){return i(a).place(this[0],c)._stash(this)},query:function(a){if(!a)return this;var b=new c;this.map(function(c){i(a,c).forEach(function(a){void 0!==a&&b.push(a)})});return b._stash(this)},filter:function(a){var c=arguments,b=this,d=0;if("string"==typeof a){b=
i._filterResult(this,c[0]);if(1==c.length)return b._stash(this);d=1}return this._wrap(g.filter(b,c[d],c[d+1]),this)},addContent:function(a,c){for(var a=this._normalize(a,this[0]),b=0,d;d=this[b];b++)this._place(a,d,c,0<b);return this}});return c})},"dojo/query":function(){define("./_base/kernel,./has,./dom,./on,./_base/array,./_base/lang,./selector/_loader,./selector/_loader!default".split(","),function(b,i,g,n,l,k,o,j){function e(a,c){var b=function(b,d){if("string"==typeof d&&(d=g.byId(d),!d))return new c([]);
var f="string"==typeof b?a(b,d):b?b.orphan?b:[b]:[];return f.orphan?f:new c(f)};b.matches=a.match||function(a,c,d){return 0<b.filter([a],c,d).length};b.filter=a.filter||function(a,c,d){return b(c,d).filter(function(c){return-1<l.indexOf(a,c)})};if("function"!=typeof a)var d=a.search,a=function(a,c){return d(c||document,a)};return b}i.add("array-extensible",function(){return 1==k.delegate([],{length:1}).length&&!i("bug-for-in-skips-shadowed")});var a=Array.prototype,f=a.slice,d=a.concat,c=l.forEach,
m=function(a,c,d){c=[0].concat(f.call(c,0));d=d||b.global;return function(b){c[0]=b;return a.apply(d,c)}},h=function(a){var c=this instanceof p&&i("array-extensible");"number"==typeof a&&(a=Array(a));var b=a&&"length"in a?a:arguments;if(c||!b.sort){for(var d=c?this:[],f=d.length=b.length,e=0;e<f;e++)d[e]=b[e];if(c)return d;b=d}k._mixin(b,s);b._NodeListCtor=function(a){return p(a)};return b},p=h,s=p.prototype=i("array-extensible")?[]:{};p._wrap=s._wrap=function(a,c,b){a=new (b||this._NodeListCtor||
p)(a);return c?a._stash(c):a};p._adaptAsMap=function(a,c){return function(){return this.map(m(a,arguments,c))}};p._adaptAsForEach=function(a,c){return function(){this.forEach(m(a,arguments,c));return this}};p._adaptAsFilter=function(a,c){return function(){return this.filter(m(a,arguments,c))}};p._adaptWithCondition=function(a,c,d){return function(){var f=arguments,e=m(a,f,d);if(c.call(d||b.global,f))return this.map(e);this.forEach(e);return this}};c(["slice","splice"],function(c){var b=a[c];s[c]=
function(){return this._wrap(b.apply(this,arguments),"slice"==c?this:null)}});c(["indexOf","lastIndexOf","every","some"],function(a){var c=l[a];s[a]=function(){return c.apply(b,[this].concat(f.call(arguments,0)))}});k.extend(h,{constructor:p,_NodeListCtor:p,toString:function(){return this.join(",")},_stash:function(a){this._parent=a;return this},on:function(a,c){var b=this.map(function(b){return n(b,a,c)});b.remove=function(){for(var a=0;a<b.length;a++)b[a].remove()};return b},end:function(){return this._parent?
this._parent:new this._NodeListCtor(0)},concat:function(a){var c=f.call(this,0),b=l.map(arguments,function(a){return f.call(a,0)});return this._wrap(d.apply(c,b),this)},map:function(a,c){return this._wrap(l.map(this,a,c),this)},forEach:function(a,b){c(this,a,b);return this},filter:function(a){var c=arguments,b=this,d=0;if("string"==typeof a){b=r._filterResult(this,c[0]);if(1==c.length)return b._stash(this);d=1}return this._wrap(l.filter(b,c[d],c[d+1]),this)},instantiate:function(a,c){var b=k.isFunction(a)?
a:k.getObject(a),c=c||{};return this.forEach(function(a){new b(c,a)})},at:function(){var a=new this._NodeListCtor(0);c(arguments,function(c){0>c&&(c=this.length+c);this[c]&&a.push(this[c])},this);return a._stash(this)}});var r=e(j,h);b.query=e(j,function(a){return h(a)});r.load=function(a,c,b){o.load(a,c,function(a){b(e(a,h))})};b._filterQueryResult=r._filterResult=function(a,c,b){return new h(r.filter(a,c,b))};b.NodeList=r.NodeList=h;return r})},"dojo/has":function(){define(["require","module"],
function(b){var i=b.has||function(){};i.add("dom-addeventlistener",!!document.addEventListener);i.add("touch","ontouchstart"in document||0<window.navigator.msMaxTouchPoints);i.add("device-width",screen.availWidth||innerWidth);b=document.createElement("form");i.add("dom-attributes-explicit",0==b.attributes.length);i.add("dom-attributes-specified-flag",0<b.attributes.length&&40>b.attributes.length);i.clearElement=function(b){b.innerHTML="";return b};i.normalize=function(b,n){var l=b.match(/[\?:]|[^:\?]*/g),
k=0,o=function(b){var e=l[k++];if(":"==e)return 0;if("?"==l[k++]){if(!b&&i(e))return o();o(!0);return o(b)}return e||0};return(b=o())&&n(b)};i.load=function(b,i,l){b?i([b],l):l()};return i})},"dojo/_base/loader":function(){define("./kernel,../has,require,module,./json,./lang,./array".split(","),function(b,i,g,n,l,k,o){var j=function(a){return a.replace(/\./g,"/")},e=/\/\/>>built/,a=[],f=[],d=function(b,d,e){a.push(e);o.forEach(b.split(","),function(a){a=M(a,d.module);f.push(a);Z(a)});c()},c=function(){var c,
b;for(b in J){c=J[b];if(void 0===c.noReqPluginCheck)c.noReqPluginCheck=/loadInit\!/.test(b)||/require\!/.test(b)?1:0;if(!c.executed&&!c.noReqPluginCheck&&c.injected==B)return}L(function(){var c=a;a=[];o.forEach(c,function(a){a(1)})})},m=function(a,c,d){var f=/\(|\)/g,e=1;for(f.lastIndex=c;(c=f.exec(a))&&!(e=")"==c[0]?e-1:e+1,0==e););if(0!=e)throw"unmatched paren around character "+f.lastIndex+" in: "+a;return[b.trim(a.substring(d,f.lastIndex))+";\n",f.lastIndex]},h=/(\/\*([\s\S]*?)\*\/|\/\/(.*)$)/mg,
p=/(^|\s)dojo\.(loadInit|require|provide|requireLocalization|requireIf|requireAfterIf|platformRequire)\s*\(/mg,s=/(^|\s)(require|define)\s*\(/m,r=function(a,c){var b,d,f,e=[],k=[];b=[];for(c=c||a.replace(h,function(a){p.lastIndex=s.lastIndex=0;return p.test(a)||s.test(a)?"":a});b=p.exec(c);)d=p.lastIndex,f=d-b[0].length,d=m(c,d,f),"loadInit"==b[2]?e.push(d[0]):k.push(d[0]),p.lastIndex=d[1];b=e.concat(k);return b.length||!s.test(c)?[a.replace(/(^|\s)dojo\.loadInit\s*\(/g,"\n0 && dojo.loadInit("),b.join(""),
b]:0},q=g.initSyncLoader(d,c,function(a,c){var d,f,m=[],h=[];if(e.test(c)||!(d=r(c)))return 0;f=a.mid+"-*loadInit";for(var p in M("dojo",a).result.scopeMap)m.push(p),h.push('"'+p+'"');return"// xdomain rewrite of "+a.mid+"\ndefine('"+f+"',{\n\tnames:"+b.toJson(m)+",\n\tdef:function("+m.join(",")+"){"+d[1]+"}});\n\ndefine("+b.toJson(m.concat(["dojo/loadInit!"+f]))+", function("+m.join(",")+"){\n"+d[0]+"});"}),u=q.sync,B=q.requested,t=q.arrived,v=q.nonmodule,x=q.executing,E=q.executed,I=q.syncExecStack,
J=q.modules,H=q.execQ,M=q.getModule,Z=q.injectModule,y=q.setArrived,D=q.signal,K=q.finishExec,A=q.execModule,z=q.getLegacyMode,L=q.guardCheckComplete,d=q.dojoRequirePlugin;b.provide=function(a){var c=I[0],b=k.mixin(M(j(a),g.module),{executed:x,result:k.getObject(a,!0)});y(b);if(c)(c.provides||(c.provides=[])).push(function(){b.result=k.getObject(a);delete b.provides;b.executed!==E&&K(b)});return b.result};i.add("config-publishRequireResult",1,0,0);b.require=function(a,c){var b=function(a,c){var b=
M(j(a),g.module);if(I.length&&I[0].finish)I[0].finish.push(a);else{if(b.executed)return b.result;c&&(b.result=v);var d=z();Z(b);d=z();b.executed!==E&&b.injected===t&&q.guardCheckComplete(function(){A(b)});if(b.executed)return b.result;d==u?b.cjs?H.unshift(b):I.length&&(I[0].finish=[a]):H.push(b)}}(a,c);i("config-publishRequireResult")&&!k.exists(a)&&void 0!==b&&k.setObject(a,b);return b};b.loadInit=function(a){a()};b.registerModulePath=function(a,c){var b={};b[a.replace(/\./g,"/")]=c;g({paths:b})};
b.platformRequire=function(a){for(var a=(a.common||[]).concat(a[b._name]||a["default"]||[]),c;a.length;)k.isArray(c=a.shift())?b.require.apply(b,c):b.require(c)};b.requireIf=b.requireAfterIf=function(a,c,d){a&&b.require(c,d)};b.requireLocalization=function(a,c,b){g(["../i18n"],function(d){d.getLocalization(a,c,b)})};return{extractLegacyApiApplications:r,require:d,loadInit:function(a,c,f){c([a],function(a){c(a.names,function(){for(var e="",m=[],h=0;h<arguments.length;h++)e+="var "+a.names[h]+"= arguments["+
h+"]; ",m.push(arguments[h]);eval(e);var p=c.module,k=[],g,e={provide:function(a){a=j(a);a=M(a,p);a!==p&&y(a)},require:function(a,c){a=j(a);c&&(M(a,p).result=v);k.push(a)},requireLocalization:function(a,c,d){g||(g=["dojo/i18n"]);d=(d||b.locale).toLowerCase();a=j(a)+"/nls/"+(/root/i.test(d)?"":d+"/")+j(c);M(a,p).isXd&&g.push("dojo/i18n!"+a)},loadInit:function(a){a()}},h={},l;try{for(l in e)h[l]=b[l],b[l]=e[l];a.def.apply(null,m)}catch(o){D("error",[{src:n.id,id:"failedDojoLoadInit"},o])}finally{for(l in e)b[l]=
h[l]}g&&(k=k.concat(g));k.length?d(k.join(","),c,f):f()})})}}})},"dojo/json":function(){define(["./has"],function(b){var i="undefined"!=typeof JSON;b.add("json-parse",i);b.add("json-stringify",i&&'{"a":1}'==JSON.stringify({a:0},function(b,g){return g||1}));if(b("json-stringify"))return JSON;var g=function(b){return('"'+b.replace(/(["\\])/g,"\\$1")+'"').replace(/[\f]/g,"\\f").replace(/[\b]/g,"\\b").replace(/[\n]/g,"\\n").replace(/[\t]/g,"\\t").replace(/[\r]/g,"\\r")};return{parse:b("json-parse")?JSON.parse:
function(b,g){if(g&&!/^([\s\[\{]*(?:"(?:\\.|[^"])+"|-?\d[\d\.]*(?:[Ee][+-]?\d+)?|null|true|false|)[\s\]\}]*(?:,|:|$))+$/.test(b))throw new SyntaxError("Invalid characters in JSON");return eval("("+b+")")},stringify:function(b,l,k){function o(b,a,f){l&&(b=l(f,b));var d;d=typeof b;if("number"==d)return isFinite(b)?b+"":"null";if("boolean"==d)return b+"";if(null===b)return"null";if("string"==typeof b)return g(b);if("function"==d||"undefined"==d)return j;if("function"==typeof b.toJSON)return o(b.toJSON(f),
a,f);if(b instanceof Date)return'"{FullYear}-{Month+}-{Date}T{Hours}:{Minutes}:{Seconds}Z"'.replace(/\{(\w+)(\+)?\}/g,function(a,c,d){a=b["getUTC"+c]()+(d?1:0);return 10>a?"0"+a:a});if(b.valueOf()!==b)return o(b.valueOf(),a,f);var c=k?a+k:"",m=k?" ":"",h=k?"\n":"";if(b instanceof Array){for(var m=b.length,p=[],f=0;f<m;f++)d=o(b[f],c,f),"string"!=typeof d&&(d="null"),p.push(h+c+d);return"["+p.join(",")+h+a+"]"}p=[];for(f in b){var i;if(b.hasOwnProperty(f)){if("number"==typeof f)i='"'+f+'"';else if("string"==
typeof f)i=g(f);else continue;d=o(b[f],c,f);"string"==typeof d&&p.push(h+c+i+":"+m+d)}}return"{"+p.join(",")+h+a+"}"}var j;"string"==typeof l&&(k=l,l=null);return o(b,"","")}}})},"dojo/_base/declare":function(){define("dojo/_base/declare",["./kernel","../has","./lang"],function(b,i,g){function n(a,c){throw Error("declare"+(c?" "+c:"")+": "+a);}function l(a,c,b){var d,f,e,m,h,p,k,j=this._inherited=this._inherited||{};"string"==typeof a&&(d=a,a=c,c=b);b=0;m=a.callee;(d=d||m.nom)||n("can't deduce a name to call inherited()",
this.declaredClass);h=this.constructor._meta;e=h.bases;k=j.p;if(d!=x){if(j.c!==m&&(k=0,p=e[0],h=p._meta,h.hidden[d]!==m)){(f=h.chains)&&"string"==typeof f[d]&&n("calling chained method with inherited: "+d,this.declaredClass);do if(h=p._meta,f=p.prototype,h&&(f[d]===m&&f.hasOwnProperty(d)||h.hidden[d]===m))break;while(p=e[++k]);k=p?k:-1}if(p=e[++k])if(f=p.prototype,p._meta&&f.hasOwnProperty(d))b=f[d];else{m=u[d];do if(f=p.prototype,(b=f[d])&&(p._meta?f.hasOwnProperty(d):b!==m))break;while(p=e[++k])}b=
p&&b||u[d]}else{if(j.c!==m&&(k=0,(h=e[0]._meta)&&h.ctor!==m)){f=h.chains;for((!f||"manual"!==f.constructor)&&n("calling chained constructor with inherited",this.declaredClass);(p=e[++k])&&!((h=p._meta)&&h.ctor===m););k=p?k:-1}for(;(p=e[++k])&&!(b=(h=p._meta)?h.ctor:p););b=p&&b}j.c=b;j.p=k;if(b)return!0===c?b:b.apply(this,c||a)}function k(a,c){return"string"==typeof a?this.__inherited(a,c,!0):this.__inherited(a,!0)}function o(a,c,b){var d=this.getInherited(a,c);if(d)return d.apply(this,b||c||a)}function j(a){for(var c=
this.constructor._meta.bases,b=0,d=c.length;b<d;++b)if(c[b]===a)return!0;return this instanceof a}function e(a,c){for(var b in c)b!=x&&c.hasOwnProperty(b)&&(a[b]=c[b]);if(i("bug-for-in-skips-shadowed"))for(var d=g._extraNames,f=d.length;f;)b=d[--f],b!=x&&c.hasOwnProperty(b)&&(a[b]=c[b])}function a(a){r.safeMixin(this.prototype,a);return this}function f(a){return r([this].concat(a))}function d(a,c){return function(){var w;var b=arguments,d=b,f=b[0],e,m;m=a.length;var h;if(!(this instanceof b.callee))return s(b);
if(c&&(f&&f.preamble||this.preamble)){h=Array(a.length);h[0]=b;for(e=0;;){if(f=b[0])(f=f.preamble)&&(b=f.apply(this,b)||b);f=a[e].prototype;(f=f.hasOwnProperty("preamble")&&f.preamble)&&(b=f.apply(this,b)||b);if(++e==m)break;h[e]=b}}for(e=m-1;0<=e;--e)f=a[e],(w=(m=f._meta)?m.ctor:f,f=w)&&f.apply(this,h?h[e]:b);(f=this.postscript)&&f.apply(this,d)}}function c(a,c){return function(){var b=arguments,d=b,f=b[0];if(!(this instanceof b.callee))return s(b);if(c){if(f)(f=f.preamble)&&(d=f.apply(this,d)||
d);(f=this.preamble)&&f.apply(this,d)}a&&a.apply(this,b);(f=this.postscript)&&f.apply(this,b)}}function m(a){return function(){var w;var c=arguments,b=0,d,f;if(!(this instanceof c.callee))return s(c);for(;d=a[b];++b)if(w=(f=d._meta)?f.ctor:d,d=w){d.apply(this,c);break}(d=this.postscript)&&d.apply(this,c)}}function h(a,c,b){return function(){var d,f,e=0,m=1;b&&(e=c.length-1,m=-1);for(;d=c[e];e+=m)f=d._meta,(d=(f?f.hidden:d.prototype)[a])&&d.apply(this,arguments)}}function p(a){t.prototype=a.prototype;
a=new t;t.prototype=null;return a}function s(a){var c=a.callee,b=p(c);c.apply(b,a);return b}function r(b,o,i){"string"!=typeof b&&(i=o,o=b,b="");var i=i||{},s,t,y,D,K,A,z,L=1,$=o;if("[object Array]"==B.call(o)){L=b;y=[];D=[{cls:0,refs:[]}];A={};for(var T=1,U=o.length,G=0,F,P,w,C;G<U;++G){(F=o[G])?"[object Function]"!=B.call(F)&&n("mixin #"+G+" is not a callable constructor.",L):n("mixin #"+G+" is unknown. Did you use dojo.require to pull it in?",L);P=F._meta?F._meta.bases:[F];w=0;for(F=P.length-1;0<=
F;--F){C=P[F].prototype;if(!C.hasOwnProperty("declaredClass"))C.declaredClass="uniqName_"+v++;C=C.declaredClass;A.hasOwnProperty(C)||(A[C]={count:0,refs:[],cls:P[F]},++T);C=A[C];w&&w!==C&&(C.refs.push(w),++w.count);w=C}++w.count;D[0].refs.push(w)}for(;D.length;){w=D.pop();y.push(w.cls);for(--T;t=w.refs,1==t.length;){w=t[0];if(!w||--w.count){w=0;break}y.push(w.cls);--T}if(w)for(G=0,U=t.length;G<U;++G)w=t[G],--w.count||D.push(w)}T&&n("can't build consistent linearization",L);F=o[0];y[0]=F?F._meta&&
F===y[y.length-F._meta.bases.length]?F._meta.bases.length:1:0;A=y;y=A[0];L=A.length-y;o=A[L]}else A=[0],o?"[object Function]"==B.call(o)?(y=o._meta,A=A.concat(y?y.bases:o)):n("base class is not a callable constructor.",b):null!==o&&n("unknown base class. Did you use dojo.require to pull it in?",b);if(o)for(t=L-1;;--t){s=p(o);if(!t)break;y=A[t];(y._meta?e:q)(s,y.prototype);D=new Function;D.superclass=o;D.prototype=s;o=s.constructor=D}else s={};r.safeMixin(s,i);y=i.constructor;if(y!==u.constructor)y.nom=
x,s.constructor=y;for(t=L-1;t;--t)(y=A[t]._meta)&&y.chains&&(z=q(z||{},y.chains));s["-chains-"]&&(z=q(z||{},s["-chains-"]));y=!z||!z.hasOwnProperty(x);A[0]=D=z&&"manual"===z.constructor?m(A):1==A.length?c(i.constructor,y):d(A,y);D._meta={bases:A,hidden:i,chains:z,parents:$,ctor:i.constructor};D.superclass=o&&o.prototype;D.extend=a;D.createSubclass=f;D.prototype=s;s.constructor=D;s.getInherited=k;s.isInstanceOf=j;s.inherited=E;s.__inherited=l;if(b)s.declaredClass=b,g.setObject(b,D);if(z)for(K in z)if(s[K]&&
"string"==typeof z[K]&&K!=x)y=s[K]=h(K,A,"after"===z[K]),y.nom=K;return D}var q=g.mixin,u=Object.prototype,B=u.toString,t=new Function,v=0,x="constructor",E=b.config.isDebug?o:l;b.safeMixin=r.safeMixin=function(a,c){var b,d;for(b in c)if(d=c[b],(d!==u[b]||!(b in u))&&b!=x){if("[object Function]"==B.call(d))d.nom=b;a[b]=d}if(i("bug-for-in-skips-shadowed"))for(var f=g._extraNames,e=f.length;e;)if(b=f[--e],d=c[b],(d!==u[b]||!(b in u))&&b!=x){if("[object Function]"==B.call(d))d.nom=b;a[b]=d}return a};
return b.declare=r})},"dojo/dom":function(){define(["./sniff","./_base/window"],function(b,i){if(7>=b("ie"))try{document.execCommand("BackgroundImageCache",!1,!0)}catch(g){}var n={};n.byId=b("ie")?function(b,g){if("string"!=typeof b)return b;var j=g||i.doc,e=b&&j.getElementById(b);if(e&&(e.attributes.id.value==b||e.id==b))return e;j=j.all[b];if(!j||j.nodeName)j=[j];for(var a=0;e=j[a++];)if(e.attributes&&e.attributes.id&&e.attributes.id.value==b||e.id==b)return e}:function(b,g){return("string"==typeof b?
(g||i.doc).getElementById(b):b)||null};n.isDescendant=function(b,g){try{b=n.byId(b);for(g=n.byId(g);b;){if(b==g)return!0;b=b.parentNode}}catch(j){}return!1};b.add("css-user-select",function(b,g,j){if(!j)return!1;var b=j.style,g=["Khtml","O","Moz","Webkit"],j=g.length,e="userSelect";do if("undefined"!==typeof b[e])return e;while(j--&&(e=g[j]+"UserSelect"));return!1});var l=b("css-user-select");n.setSelectable=l?function(b,g){n.byId(b).style[l]=g?"":"none"}:function(b,g){var b=n.byId(b),j=b.getElementsByTagName("*"),
e=j.length;if(g)for(b.removeAttribute("unselectable");e--;)j[e].removeAttribute("unselectable");else for(b.setAttribute("unselectable","on");e--;)j[e].setAttribute("unselectable","on")};return n})},"dojo/_base/browser":function(){require.has&&require.has.add("config-selectorEngine","acme");define("../ready,./kernel,./connect,./unload,./window,./event,./html,./NodeList,../query,./xhr,./fx".split(","),function(b){return b})},"dojo/selector/acme":function(){define(["../dom","../sniff","../_base/array",
"../_base/lang","../_base/window"],function(b,i,g,n,l){var k=n.trim,o=g.forEach,j="BackCompat"==l.doc.compatMode,e=!1,a=function(){return!0},f=function(a){for(var a=0<=">~+".indexOf(a.slice(-1))?a+" * ":a+" ",c=function(c,b){return k(a.slice(c,b))},b=[],d=-1,f=-1,m=-1,h=-1,p=-1,g=-1,j=-1,l,o="",i="",s,n=0,x=a.length,r=null,q=null,v=function(){if(0<=g)r.id=c(g,n).replace(/\\/g,""),g=-1;if(0<=j){var a=j==n?null:c(j,n);r[0>">~+".indexOf(a)?"tag":"oper"]=a;j=-1}0<=p&&(r.classes.push(c(p+1,n).replace(/\\/g,
"")),p=-1)};o=i,i=a.charAt(n),n<x;n++)if("\\"!=o)if(r||(s=n,r={query:null,pseudos:[],attrs:[],classes:[],tag:null,oper:null,id:null,getTag:function(){return e?this.otag:this.tag}},j=n),l)i==l&&(l=null);else if("'"==i||'"'==i)l=i;else if(0<=d)if("]"==i){q.attr?q.matchFor=c(m||d+1,n):q.attr=c(d+1,n);if((d=q.matchFor)&&('"'==d.charAt(0)||"'"==d.charAt(0)))q.matchFor=d.slice(1,-1);if(q.matchFor)q.matchFor=q.matchFor.replace(/\\/g,"");r.attrs.push(q);q=null;d=m=-1}else{if("="==i)m=0<="|~^$*".indexOf(o)?
o:"",q.type=m+i,q.attr=c(d+1,n-m.length),m=n+1}else if(0<=f){if(")"==i){if(0<=h)q.value=c(f+1,n);h=f=-1}}else if("#"==i)v(),g=n+1;else if("."==i)v(),p=n;else if(":"==i)v(),h=n;else if("["==i)v(),d=n,q={};else if("("==i)0<=h&&(q={name:c(h+1,n),value:null},r.pseudos.push(q)),f=n;else if(" "==i&&o!=i){v();0<=h&&r.pseudos.push({name:c(h+1,n)});r.loops=r.pseudos.length||r.attrs.length||r.classes.length;r.oquery=r.query=c(s,n);r.otag=r.tag=r.oper?null:r.tag||"*";if(r.tag)r.tag=r.tag.toUpperCase();if(b.length&&
b[b.length-1].oper)r.infixOper=b.pop(),r.query=r.infixOper.query+" "+r.query;b.push(r);r=null}return b},d=function(a,c){return!a?c:!c?a:function(){return a.apply(window,arguments)&&c.apply(window,arguments)}},c=function(a,c){var b=c||[];a&&b.push(a);return b},m=function(a){return 1==a.nodeType},h=function(a,c){return!a?"":"class"==c?a.className||"":"for"==c?a.htmlFor||"":"style"==c?a.style.cssText||"":(e?a.getAttribute(c):a.getAttribute(c,2))||""},p={"*=":function(a,c){return function(b){return 0<=
h(b,a).indexOf(c)}},"^=":function(a,c){return function(b){return 0==h(b,a).indexOf(c)}},"$=":function(a,c){return function(b){var b=" "+h(b,a),d=b.lastIndexOf(c);return-1<d&&d==b.length-c.length}},"~=":function(a,c){var b=" "+c+" ";return function(c){return 0<=(" "+h(c,a)+" ").indexOf(b)}},"|=":function(a,c){var b=c+"-";return function(d){d=h(d,a);return d==c||0==d.indexOf(b)}},"=":function(a,c){return function(b){return h(b,a)==c}}},s="undefined"==typeof l.doc.firstChild.nextElementSibling,r=!s?
"nextElementSibling":"nextSibling",q=!s?"previousElementSibling":"previousSibling",u=s?m:a,B=function(a){for(;a=a[q];)if(u(a))return!1;return!0},t=function(a){for(;a=a[r];)if(u(a))return!1;return!0},v=function(a){var c=a.parentNode,c=7!=c.nodeType?c:c.nextSibling,b=0,d=c.children||c.childNodes,f=a._i||a.getAttribute("_i")||-1,e=c._l||("undefined"!==typeof c.getAttribute?c.getAttribute("_l"):-1);if(!d)return-1;d=d.length;if(e==d&&0<=f&&0<=e)return f;i("ie")&&"undefined"!==typeof c.setAttribute?c.setAttribute("_l",
d):c._l=d;f=-1;for(c=c.firstElementChild||c.firstChild;c;c=c[r])if(u(c))i("ie")?c.setAttribute("_i",++b):c._i=++b,a===c&&(f=b);return f},x=function(a){return!(v(a)%2)},E=function(a){return v(a)%2},I={checked:function(){return function(a){return!!("checked"in a?a.checked:a.selected)}},disabled:function(){return function(a){return a.disabled}},enabled:function(){return function(a){return!a.disabled}},"first-child":function(){return B},"last-child":function(){return t},"only-child":function(){return function(a){return B(a)&&
t(a)}},empty:function(){return function(a){for(var c=a.childNodes,a=a.childNodes.length-1;0<=a;a--){var b=c[a].nodeType;if(1===b||3==b)return!1}return!0}},contains:function(a,c){var b=c.charAt(0);if('"'==b||"'"==b)c=c.slice(1,-1);return function(a){return 0<=a.innerHTML.indexOf(c)}},not:function(a,c){var b=f(c)[0],d={el:1};if("*"!=b.tag)d.tag=1;if(!b.classes.length)d.classes=1;var e=H(b,d);return function(a){return!e(a)}},"nth-child":function(a,c){var b=parseInt;if("odd"==c)return E;if("even"==c)return x;
if(-1!=c.indexOf("n")){var d=c.split("n",2),f=d[0]?"-"==d[0]?-1:b(d[0]):1,e=d[1]?b(d[1]):0,m=0,h=-1;0<f?0>e?e=e%f&&f+e%f:0<e&&(e>=f&&(m=e-e%f),e%=f):0>f&&(f*=-1,0<e&&(h=e,e%=f));if(0<f)return function(a){a=v(a);return a>=m&&(0>h||a<=h)&&a%f==e};c=e}var p=b(c);return function(a){return v(a)==p}}},J=9>i("ie")||9==i("ie")&&i("quirks")?function(a){var c=a.toLowerCase();"class"==c&&(a="className");return function(b){return e?b.getAttribute(a):b[a]||b[c]}}:function(a){return function(c){return c&&c.getAttribute&&
c.hasAttribute(a)}},H=function(c,b){if(!c)return a;var b=b||{},f=null;"el"in b||(f=d(f,m));"tag"in b||"*"!=c.tag&&(f=d(f,function(a){return a&&(e?a.tagName:a.tagName.toUpperCase())==c.getTag()}));"classes"in b||o(c.classes,function(a,c){var b=RegExp("(?:^|\\s)"+a+"(?:\\s|$)");f=d(f,function(a){return b.test(a.className)});f.count=c});"pseudos"in b||o(c.pseudos,function(a){var c=a.name;I[c]&&(f=d(f,I[c](c,a.value)))});"attrs"in b||o(c.attrs,function(a){var c,b=a.attr;a.type&&p[a.type]?c=p[a.type](b,
a.matchFor):b.length&&(c=J(b));c&&(f=d(f,c))});"id"in b||c.id&&(f=d(f,function(a){return!!a&&a.id==c.id}));f||"default"in b||(f=a);return f},M=function(a){return function(c,b,d){for(;c=c[r];)if(!s||m(c)){(!d||Q(c,d))&&a(c)&&b.push(c);break}return b}},Z=function(a){return function(c,b,d){for(c=c[r];c;){if(u(c)){if(d&&!Q(c,d))break;a(c)&&b.push(c)}c=c[r]}return b}},y=function(c){c=c||a;return function(a,b,d){for(var f=0,e=a.children||a.childNodes;a=e[f++];)u(a)&&(!d||Q(a,d))&&c(a,f)&&b.push(a);return b}},
D={},K=function(d){var f=D[d.query];if(f)return f;var e=d.infixOper,e=e?e.oper:"",m=H(d,{el:1}),h="*"==d.tag,p=l.doc.getElementsByClassName;if(e){p={el:1};if(h)p.tag=1;m=H(d,p);"+"==e?f=M(m):"~"==e?f=Z(m):">"==e&&(f=y(m))}else if(d.id)m=!d.loops&&h?a:H(d,{el:1,id:1}),f=function(a,f){var e=b.byId(d.id,a.ownerDocument||a);if(e&&m(e)){if(9==a.nodeType)return c(e,f);for(var h=e.parentNode;h&&!(h==a);)h=h.parentNode;if(h)return c(e,f)}};else if(p&&/\{\s*\[native code\]\s*\}/.test(""+p)&&d.classes.length&&
!j)var m=H(d,{el:1,classes:1,id:1}),g=d.classes.join(" "),f=function(a,b,d){for(var b=c(0,b),f,e=0,h=a.getElementsByClassName(g);f=h[e++];)m(f,a)&&Q(f,d)&&b.push(f);return b};else!h&&!d.loops?f=function(a,b,f){for(var b=c(0,b),e=0,m=d.getTag(),m=m?a.getElementsByTagName(m):[];a=m[e++];)Q(a,f)&&b.push(a);return b}:(m=H(d,{el:1,tag:1,id:1}),f=function(a,b,f){for(var b=c(0,b),e,h=0,p=(e=d.getTag())?a.getElementsByTagName(e):[];e=p[h++];)m(e,a)&&Q(e,f)&&b.push(e);return b});return D[d.query]=f},A={},
z={},L=function(a){var b=f(k(a));if(1==b.length){var d=K(b[0]);return function(a){if(a=d(a,[]))a.nozip=!0;return a}}return function(a){for(var a=c(a),d,f,e=b.length,m,h,p=0;p<e;p++){h=[];d=b[p];f=a.length-1;if(0<f)m={},h.nozip=!0;f=K(d);for(var g=0;d=a[g];g++)f(d,h,m);if(!h.length)break;a=h}return h}},$=i("ie")?"commentStrip":"nozip",T=!!l.doc.querySelectorAll,U=/\\[>~+]|n\+\d|([^ \\])?([>~+])([^ =])?/g,G=function(a,c,b,d){return b?(c?c+" ":"")+b+(d?" "+d:""):a},F=/([^[]*)([^\]]*])?/g,P=function(a,
c,b){return c.replace(U,G)+(b||"")},w=function(a,c){a=a.replace(F,P);if(T){var b=z[a];if(b&&!c)return b}if(b=A[a])return b;var b=a.charAt(0),d=-1==a.indexOf(" ");0<=a.indexOf("#")&&d&&(c=!0);if(T&&!c&&-1==">~+".indexOf(b)&&(!i("ie")||-1==a.indexOf(":"))&&!(j&&0<=a.indexOf("."))&&-1==a.indexOf(":contains")&&-1==a.indexOf(":checked")&&-1==a.indexOf("|=")){var f=0<=">~+".indexOf(a.charAt(a.length-1))?a+" *":a;return z[a]=function(c){try{if(!(9==c.nodeType||d))throw"";var b=c.querySelectorAll(f);b[$]=
!0;return b}catch(e){return w(a,!0)(c)}}}var e=a.match(/([^\s,](?:"(?:\\.|[^"])+"|'(?:\\.|[^'])+'|[^,])*)/g);return A[a]=2>e.length?L(a):function(a){for(var c=0,b=[],d;d=e[c++];)b=b.concat(L(d)(a));return b}},C=0,R=i("ie")?function(a){return e?a.getAttribute("_uid")||a.setAttribute("_uid",++C)||C:a.uniqueID}:function(a){return a._uid||(a._uid=++C)},Q=function(a,c){if(!c)return 1;var b=R(a);return!c[b]?c[b]=1:0},aa=function(a){if(a&&a.nozip)return a;var c=[];if(!a||!a.length)return c;a[0]&&c.push(a[0]);
if(2>a.length)return c;C++;var b,d;if(i("ie")&&e){var f=C+"";a[0].setAttribute("_zipIdx",f);for(b=1;d=a[b];b++)a[b].getAttribute("_zipIdx")!=f&&c.push(d),d.setAttribute("_zipIdx",f)}else if(i("ie")&&a.commentStrip)try{for(b=1;d=a[b];b++)m(d)&&c.push(d)}catch(h){}else{a[0]&&(a[0]._zipIdx=C);for(b=1;d=a[b];b++)a[b]._zipIdx!=C&&c.push(d),d._zipIdx=C}return c},V=function(a,c){c=c||l.doc;e="div"===(c.ownerDocument||c).createElement("div").tagName;var b=w(a)(c);return b&&b.nozip?b:aa(b)};V.filter=function(a,
c,d){for(var e=[],m=f(c),m=1==m.length&&!/[^\w#\.]/.test(c)?H(m[0]):function(a){return-1!=g.indexOf(V(c,b.byId(d)),a)},h=0,p;p=a[h];h++)m(p)&&e.push(p);return e};return V})},"dojo/errors/RequestTimeoutError":function(){define(["./create","./RequestError"],function(b,i){return b("RequestTimeoutError",null,i,{dojoType:"timeout"})})},"dojo/dom-style":function(){define("dojo/dom-style",["./sniff","./dom"],function(b,i){function g(c,d,e){d=d.toLowerCase();if(b("ie")||b("trident")){if("auto"==e){if("height"==
d)return c.offsetHeight;if("width"==d)return c.offsetWidth}if("fontweight"==d)switch(e){case 700:return"bold";default:return"normal"}}d in a||(a[d]=f.test(d));return a[d]?k(c,e):e}var n,l={};n=b("webkit")?function(a){var b;if(1==a.nodeType){var d=a.ownerDocument.defaultView;b=d.getComputedStyle(a,null);if(!b&&a.style)a.style.display="",b=d.getComputedStyle(a,null)}return b||{}}:b("ie")&&(9>b("ie")||b("quirks"))?function(a){return 1==a.nodeType&&a.currentStyle?a.currentStyle:{}}:function(a){return 1==
a.nodeType?a.ownerDocument.defaultView.getComputedStyle(a,null):{}};l.getComputedStyle=n;var k;k=b("ie")?function(a,b){if(!b)return 0;if("medium"==b)return 4;if(b.slice&&"px"==b.slice(-2))return parseFloat(b);var d=a.style,f=a.runtimeStyle,e=d.left,g=f.left;f.left=a.currentStyle.left;try{d.left=b,b=d.pixelLeft}catch(j){b=0}d.left=e;f.left=g;return b}:function(a,b){return parseFloat(b)||0};l.toPixelValue=k;var o=function(a,b){try{return a.filters.item("DXImageTransform.Microsoft.Alpha")}catch(d){return b?
{}:null}},j=9>b("ie")||10>b("ie")&&b("quirks")?function(a){try{return o(a).Opacity/100}catch(b){return 1}}:function(a){return n(a).opacity},e=9>b("ie")||10>b("ie")&&b("quirks")?function(a,b){var d=100*b,f=1==b;a.style.zoom=f?"":1;if(o(a))o(a,1).Opacity=d;else{if(f)return b;a.style.filter+=" progid:DXImageTransform.Microsoft.Alpha(Opacity="+d+")"}o(a,1).Enabled=!f;if("tr"==a.tagName.toLowerCase())for(d=a.firstChild;d;d=d.nextSibling)"td"==d.tagName.toLowerCase()&&e(d,b);return b}:function(a,b){return a.style.opacity=
b},a={left:!0,top:!0},f=/margin|padding|width|height|max|min|offset/,d={cssFloat:1,styleFloat:1,"float":1};l.get=function(a,b){var f=i.byId(a),e=arguments.length;if(2==e&&"opacity"==b)return j(f);var b=d[b]?"cssFloat"in f.style?"cssFloat":"styleFloat":b,k=l.getComputedStyle(f);return 1==e?k:g(f,b,k[b]||f.style[b])};l.set=function(a,b,f){var p=i.byId(a),g=arguments.length,j="opacity"==b,b=d[b]?"cssFloat"in p.style?"cssFloat":"styleFloat":b;if(3==g)return j?e(p,f):p.style[b]=f;for(var k in b)l.set(a,
k,b[k]);return l.getComputedStyle(p)};return l})},"dojo/dom-geometry":function(){define("dojo/dom-geometry",["./sniff","./_base/window","./dom","./dom-style"],function(b,i,g,n){function l(a,b,d,c,e,h){h=h||"px";a=a.style;if(!isNaN(b))a.left=b+h;if(!isNaN(d))a.top=d+h;if(0<=c)a.width=c+h;if(0<=e)a.height=e+h}function k(a){return"button"==a.tagName.toLowerCase()||"input"==a.tagName.toLowerCase()&&"button"==(a.getAttribute("type")||"").toLowerCase()}function o(a){return"border-box"==j.boxModel||"table"==
a.tagName.toLowerCase()||k(a)}var j={boxModel:"content-box"};if(b("ie"))j.boxModel="BackCompat"==document.compatMode?"border-box":"content-box";j.getPadExtents=function(a,b){var a=g.byId(a),d=b||n.getComputedStyle(a),c=n.toPixelValue,e=c(a,d.paddingLeft),h=c(a,d.paddingTop),p=c(a,d.paddingRight),d=c(a,d.paddingBottom);return{l:e,t:h,r:p,b:d,w:e+p,h:h+d}};j.getBorderExtents=function(a,b){var a=g.byId(a),d=n.toPixelValue,c=b||n.getComputedStyle(a),e="none"!=c.borderLeftStyle?d(a,c.borderLeftWidth):
0,h="none"!=c.borderTopStyle?d(a,c.borderTopWidth):0,p="none"!=c.borderRightStyle?d(a,c.borderRightWidth):0,d="none"!=c.borderBottomStyle?d(a,c.borderBottomWidth):0;return{l:e,t:h,r:p,b:d,w:e+p,h:h+d}};j.getPadBorderExtents=function(a,b){var a=g.byId(a),d=b||n.getComputedStyle(a),c=j.getPadExtents(a,d),d=j.getBorderExtents(a,d);return{l:c.l+d.l,t:c.t+d.t,r:c.r+d.r,b:c.b+d.b,w:c.w+d.w,h:c.h+d.h}};j.getMarginExtents=function(a,b){var a=g.byId(a),d=b||n.getComputedStyle(a),c=n.toPixelValue,e=c(a,d.marginLeft),
h=c(a,d.marginTop),p=c(a,d.marginRight),d=c(a,d.marginBottom);return{l:e,t:h,r:p,b:d,w:e+p,h:h+d}};j.getMarginBox=function(a,f){var a=g.byId(a),d=f||n.getComputedStyle(a),c=j.getMarginExtents(a,d),e=a.offsetLeft-c.l,h=a.offsetTop-c.t,p=a.parentNode,k=n.toPixelValue;if(b("mozilla")){var i=parseFloat(d.left),d=parseFloat(d.top);!isNaN(i)&&!isNaN(d)?(e=i,h=d):p&&p.style&&(p=n.getComputedStyle(p),"visible"!=p.overflow&&(e+="none"!=p.borderLeftStyle?k(a,p.borderLeftWidth):0,h+="none"!=p.borderTopStyle?
k(a,p.borderTopWidth):0))}else if((b("opera")||8==b("ie")&&!b("quirks"))&&p)p=n.getComputedStyle(p),e-="none"!=p.borderLeftStyle?k(a,p.borderLeftWidth):0,h-="none"!=p.borderTopStyle?k(a,p.borderTopWidth):0;return{l:e,t:h,w:a.offsetWidth+c.w,h:a.offsetHeight+c.h}};j.getContentBox=function(a,f){var a=g.byId(a),d=f||n.getComputedStyle(a),c=a.clientWidth,e=j.getPadExtents(a,d),h=j.getBorderExtents(a,d);c?(d=a.clientHeight,h.w=h.h=0):(c=a.offsetWidth,d=a.offsetHeight);b("opera")&&(e.l+=h.l,e.t+=h.t);return{l:e.l,
t:e.t,w:c-e.w-h.w,h:d-e.h-h.h}};j.setContentSize=function(a,b,d){var a=g.byId(a),c=b.w,b=b.h;o(a)&&(d=j.getPadBorderExtents(a,d),0<=c&&(c+=d.w),0<=b&&(b+=d.h));l(a,NaN,NaN,c,b)};var e={l:0,t:0,w:0,h:0};j.setMarginBox=function(a,f,d){var a=g.byId(a),c=d||n.getComputedStyle(a),d=f.w,m=f.h,h=o(a)?e:j.getPadBorderExtents(a,c),c=j.getMarginExtents(a,c);if(b("webkit")&&k(a)){var p=a.style;if(0<=d&&!p.width)p.width="4px";if(0<=m&&!p.height)p.height="4px"}0<=d&&(d=Math.max(d-h.w-c.w,0));0<=m&&(m=Math.max(m-
h.h-c.h,0));l(a,f.l,f.t,d,m)};j.isBodyLtr=function(a){a=a||i.doc;return"ltr"==(i.body(a).dir||a.documentElement.dir||"ltr").toLowerCase()};j.docScroll=function(a){var a=a||i.doc,f=i.doc.parentWindow||i.doc.defaultView;return"pageXOffset"in f?{x:f.pageXOffset,y:f.pageYOffset}:(f=b("quirks")?i.body(a):a.documentElement)&&{x:j.fixIeBiDiScrollLeft(f.scrollLeft||0,a),y:f.scrollTop||0}};if(b("ie"))j.getIeDocumentElementOffset=function(a){a=a||i.doc;a=a.documentElement;if(8>b("ie")){var f=a.getBoundingClientRect(),
d=f.left,f=f.top;7>b("ie")&&(d+=a.clientLeft,f+=a.clientTop);return{x:0>d?0:d,y:0>f?0:f}}return{x:0,y:0}};j.fixIeBiDiScrollLeft=function(a,f){var f=f||i.doc,d=b("ie");if(d&&!j.isBodyLtr(f)){var c=b("quirks"),e=c?i.body(f):f.documentElement,h=i.global;6==d&&!c&&h.frameElement&&e.scrollHeight>e.clientHeight&&(a+=e.clientLeft);return 8>d||c?a+e.clientWidth-e.scrollWidth:-a}return a};j.position=function(a,f){var a=g.byId(a),d=i.body(a.ownerDocument),c=a.getBoundingClientRect(),c={x:c.left,y:c.top,w:c.right-
c.left,h:c.bottom-c.top};if(9>b("ie")){var e=j.getIeDocumentElementOffset(a.ownerDocument);c.x-=e.x+(b("quirks")?d.clientLeft+d.offsetLeft:0);c.y-=e.y+(b("quirks")?d.clientTop+d.offsetTop:0)}f&&(d=j.docScroll(a.ownerDocument),c.x+=d.x,c.y+=d.y);return c};j.getMarginSize=function(a,b){var a=g.byId(a),d=j.getMarginExtents(a,b||n.getComputedStyle(a)),c=a.getBoundingClientRect();return{w:c.right-c.left+d.w,h:c.bottom-c.top+d.h}};j.normalizeEvent=function(a){if(!("layerX"in a))a.layerX=a.offsetX,a.layerY=
a.offsetY;if(!b("dom-addeventlistener")){var f=a.target,f=f&&f.ownerDocument||document,d=b("quirks")?f.body:f.documentElement,c=j.getIeDocumentElementOffset(f);a.pageX=a.clientX+j.fixIeBiDiScrollLeft(d.scrollLeft||0,f)-c.x;a.pageY=a.clientY+(d.scrollTop||0)-c.y}};return j})},"dojo/dom-prop":function(){define("exports,./_base/kernel,./sniff,./_base/lang,./dom,./dom-style,./dom-construct,./_base/connect".split(","),function(b,i,g,n,l,k,o,j){var e={},a=0,f=i._scopeName+"attrid";b.names={"class":"className",
"for":"htmlFor",tabindex:"tabIndex",readonly:"readOnly",colspan:"colSpan",frameborder:"frameBorder",rowspan:"rowSpan",valuetype:"valueType"};b.get=function(a,c){var a=l.byId(a),f=c.toLowerCase();return a[b.names[f]||c]};b.set=function(d,c,m){d=l.byId(d);if(2==arguments.length&&"string"!=typeof c){for(var h in c)b.set(d,h,c[h]);return d}h=c.toLowerCase();h=b.names[h]||c;if("style"==h&&"string"!=typeof m)return k.set(d,m),d;if("innerHTML"==h)return g("ie")&&d.tagName.toLowerCase()in{col:1,colgroup:1,
table:1,tbody:1,tfoot:1,thead:1,tr:1,title:1}?(o.empty(d),d.appendChild(o.toDom(m,d.ownerDocument))):d[h]=m,d;if(n.isFunction(m)){var p=d[f];p||(p=a++,d[f]=p);e[p]||(e[p]={});var i=e[p][h];if(i)j.disconnect(i);else try{delete d[h]}catch(r){}m?e[p][h]=j.connect(d,h,m):d[h]=null;return d}d[h]=m;return d}})},"dojo/when":function(){define(["./Deferred","./promise/Promise"],function(b,i){return function(g,n,l,k){var o=g&&"function"===typeof g.then,j=o&&g instanceof i;if(o){if(!j)o=new b(g.cancel),g.then(o.resolve,
o.reject,o.progress),g=o.promise}else return 1<arguments.length?n?n(g):g:(new b).resolve(g);return n||l||k?g.then(n,l,k):g}})},"dojo/dom-attr":function(){define("exports,./sniff,./_base/lang,./dom,./dom-style,./dom-prop".split(","),function(b,i,g,n,l,k){function o(a,b){var d=a.getAttributeNode&&a.getAttributeNode(b);return!!d&&d.specified}var j={innerHTML:1,className:1,htmlFor:i("ie"),value:1},e={classname:"class",htmlfor:"for",tabindex:"tabIndex",readonly:"readOnly"};b.has=function(a,b){var d=b.toLowerCase();
return j[k.names[d]||b]||o(n.byId(a),e[d]||b)};b.get=function(a,b){var a=n.byId(a),d=b.toLowerCase(),c=k.names[d]||b,m=a[c];if(j[c]&&"undefined"!=typeof m||"href"!=c&&("boolean"==typeof m||g.isFunction(m)))return m;d=e[d]||b;return o(a,d)?a.getAttribute(d):null};b.set=function(a,f,d){a=n.byId(a);if(2==arguments.length){for(var c in f)b.set(a,c,f[c]);return a}c=f.toLowerCase();var m=k.names[c]||f,h=j[m];if("style"==m&&"string"!=typeof d)return l.set(a,d),a;if(h||"boolean"==typeof d||g.isFunction(d))return k.set(a,
f,d);a.setAttribute(e[c]||f,d);return a};b.remove=function(a,b){n.byId(a).removeAttribute(e[b.toLowerCase()]||b)};b.getNodeProp=function(a,b){var a=n.byId(a),d=b.toLowerCase(),c=k.names[d]||b;if(c in a&&"href"!=c)return a[c];d=e[d]||b;return o(a,d)?a.getAttribute(d):null}})},"dojo/dom-construct":function(){define("exports,./_base/kernel,./sniff,./_base/window,./dom,./dom-attr,./on".split(","),function(b,i,g,n,l,k){function o(a,b){var c=b.parentNode;c&&c.insertBefore(a,b)}function j(a){if(a.canHaveChildren)try{a.innerHTML=
"";return}catch(b){}for(var c;c=a.lastChild;)e(c,a)}function e(a,b){a.firstChild&&j(a);b&&(g("ie")&&b.canHaveChildren&&"removeNode"in a?a.removeNode(!1):b.removeChild(a))}var a={option:["select"],tbody:["table"],thead:["table"],tfoot:["table"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","thead","tr"],legend:["fieldset"],caption:["table"],colgroup:["table"],col:["table","colgroup"],li:["ul"]},f=/<\s*([\w\:]+)/,d={},c=0,m="__"+i._scopeName+"ToDomId",h;for(h in a)if(a.hasOwnProperty(h))i=
a[h],i.pre="option"==h?'<select multiple="multiple">':"<"+i.join("><")+">",i.post="</"+i.reverse().join("></")+">";b.toDom=function(b,e){var e=e||n.doc,h=e[m];h||(e[m]=h=++c+"",d[h]=e.createElement("div"));var b=b+"",g=b.match(f),j=g?g[1].toLowerCase():"",h=d[h];if(g&&a[j]){g=a[j];h.innerHTML=g.pre+b+g.post;for(g=g.length;g;--g)h=h.firstChild}else h.innerHTML=b;if(1==h.childNodes.length)return h.removeChild(h.firstChild);for(j=e.createDocumentFragment();g=h.firstChild;)j.appendChild(g);return j};
b.place=function(a,c,d){c=l.byId(c);"string"==typeof a&&(a=/^\s*</.test(a)?b.toDom(a,c.ownerDocument):l.byId(a));if("number"==typeof d){var f=c.childNodes;!f.length||f.length<=d?c.appendChild(a):o(a,f[0>d?0:d])}else switch(d){case "before":o(a,c);break;case "after":d=a;(f=c.parentNode)&&(f.lastChild==c?f.appendChild(d):f.insertBefore(d,c.nextSibling));break;case "replace":c.parentNode.replaceChild(a,c);break;case "only":b.empty(c);c.appendChild(a);break;case "first":if(c.firstChild){o(a,c.firstChild);
break}default:c.appendChild(a)}return a};b.create=function(a,c,d,f){var e=n.doc;if(d)d=l.byId(d),e=d.ownerDocument;"string"==typeof a&&(a=e.createElement(a));c&&k.set(a,c);d&&b.place(a,d,f);return a};b.empty=function(a){j(l.byId(a))};b.destroy=function(a){(a=l.byId(a))&&e(a,a.parentNode)}})},"dojo/request/xhr":function(){define(["../errors/RequestError","./watch","./handlers","./util","../has"],function(b,i,g,n,l){function k(a,c){var d=a.xhr;a.status=a.xhr.status;a.text=d.responseText;if("xml"===
a.options.handleAs)a.data=d.responseXML;if(!c)try{g(a)}catch(f){c=f}c?this.reject(c):n.checkStatus(d.status)?this.resolve(a):(c=new b("Unable to load "+a.url+" status: "+d.status,a),this.reject(c))}function o(a){return this.xhr.getResponseHeader(a)}function j(h,g,p){var u=n.parseArgs(h,n.deepCreate(m,g),l("native-formdata")&&g&&g.data&&g.data instanceof FormData),h=u.url,g=u.options,B,t=n.deferred(u,d,e,a,k,function(){B&&B()}),v=u.xhr=j._create();if(!v)return t.cancel(new b("XHR was not created")),
p?t:t.promise;u.getHeader=o;f&&(B=f(v,t,u));var x=g.data,E=!g.sync,I=g.method;try{v.open(I,h,E,g.user||c,g.password||c);if(g.withCredentials)v.withCredentials=g.withCredentials;var J=g.headers,h="application/x-www-form-urlencoded";if(J)for(var H in J)"content-type"===H.toLowerCase()?h=J[H]:J[H]&&v.setRequestHeader(H,J[H]);h&&!1!==h&&v.setRequestHeader("Content-Type",h);(!J||!("X-Requested-With"in J))&&v.setRequestHeader("X-Requested-With","XMLHttpRequest");n.notify&&n.notify.emit("send",u,t.promise.cancel);
v.send(x)}catch(M){t.reject(M)}i(t);v=null;return p?t:t.promise}l.add("native-xhr",function(){return"undefined"!==typeof XMLHttpRequest});l.add("dojo-force-activex-xhr",function(){return l("activex")&&!document.addEventListener&&"file:"===window.location.protocol});l.add("native-xhr2",function(){if(l("native-xhr")){var a=new XMLHttpRequest;return"undefined"!==typeof a.addEventListener&&("undefined"===typeof opera||"undefined"!==typeof a.upload)}});l.add("native-formdata",function(){return"function"===
typeof FormData});var e,a,f,d;l("native-xhr2")?(e=function(){return!this.isFulfilled()},d=function(a,b){b.xhr.abort()},f=function(a,c,d){function f(){c.handleResponse(d)}function e(a){a=new b("Unable to load "+d.url+" status: "+a.target.status,d);c.handleResponse(d,a)}function h(a){if(a.lengthComputable)d.loaded=a.loaded,d.total=a.total,c.progress(d)}a.addEventListener("load",f,!1);a.addEventListener("error",e,!1);a.addEventListener("progress",h,!1);return function(){a.removeEventListener("load",
f,!1);a.removeEventListener("error",e,!1);a.removeEventListener("progress",h,!1);a=null}}):(e=function(a){return a.xhr.readyState},a=function(a){return 4===a.xhr.readyState},d=function(a,b){var c=b.xhr,d=typeof c.abort;("function"===d||"object"===d||"unknown"===d)&&c.abort()});var c,m={data:null,query:null,sync:!1,method:"GET"};j._create=function(){throw Error("XMLHTTP not available");};if(l("native-xhr")&&!l("dojo-force-activex-xhr"))j._create=function(){return new XMLHttpRequest};else if(l("activex"))try{new ActiveXObject("Msxml2.XMLHTTP"),
j._create=function(){return new ActiveXObject("Msxml2.XMLHTTP")}}catch(h){try{new ActiveXObject("Microsoft.XMLHTTP"),j._create=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}catch(p){}}n.addCommonMethods(j);return j})},"dojo/text":function(){define(["./_base/kernel","require","./has","./_base/xhr"],function(b,i,g,n){var l;l=function(a,f,d){n("GET",{url:a,sync:!!f,load:d,headers:b.config.textPluginHeaders||{}})};var k={},o=function(a){if(a){var a=a.replace(/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
""),b=a.match(/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im);b&&(a=b[1])}else a="";return a},j={},e={};b.cache=function(a,b,d){var c;"string"==typeof a?/\//.test(a)?(c=a,d=b):c=i.toUrl(a.replace(/\./g,"/")+(b?"/"+b:"")):(c=a+"",d=b);a=void 0!=d&&"string"!=typeof d?d.value:d;d=d&&d.sanitize;if("string"==typeof a)return k[c]=a,d?o(a):a;if(null===a)return delete k[c],null;c in k||l(c,!0,function(a){k[c]=a});return d?o(k[c]):k[c]};return{dynamic:!0,normalize:function(a,b){var d=a.split("!"),c=d[0];return(/^\./.test(c)?
b(c):c)+(d[1]?"!"+d[1]:"")},load:function(a,b,d){var a=a.split("!"),c=1<a.length,m=a[0],h=b.toUrl(a[0]),a="url:"+h,g=j,i=function(a){d(c?o(a):a)};m in k?g=k[m]:a in b.cache?g=b.cache[a]:h in k&&(g=k[h]);if(g===j)if(e[h])e[h].push(i);else{var n=e[h]=[i];l(h,!b.async,function(a){k[m]=k[h]=a;for(var b=0;b<n.length;)n[b++](a);delete e[h]})}else i(g)}}})},"dojo/keys":function(){define("dojo/keys",["./_base/kernel","./sniff"],function(b,i){return b.keys={BACKSPACE:8,TAB:9,CLEAR:12,ENTER:13,SHIFT:16,CTRL:17,
ALT:18,META:i("webkit")?91:224,PAUSE:19,CAPS_LOCK:20,ESCAPE:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT_ARROW:37,UP_ARROW:38,RIGHT_ARROW:39,DOWN_ARROW:40,INSERT:45,DELETE:46,HELP:47,LEFT_WINDOW:91,RIGHT_WINDOW:92,SELECT:93,NUMPAD_0:96,NUMPAD_1:97,NUMPAD_2:98,NUMPAD_3:99,NUMPAD_4:100,NUMPAD_5:101,NUMPAD_6:102,NUMPAD_7:103,NUMPAD_8:104,NUMPAD_9:105,NUMPAD_MULTIPLY:106,NUMPAD_PLUS:107,NUMPAD_ENTER:108,NUMPAD_MINUS:109,NUMPAD_PERIOD:110,NUMPAD_DIVIDE:111,F1:112,F2:113,F3:114,F4:115,F5:116,
F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,NUM_LOCK:144,SCROLL_LOCK:145,UP_DPAD:175,DOWN_DPAD:176,LEFT_DPAD:177,RIGHT_DPAD:178,copyKey:i("mac")&&!i("air")?i("safari")?91:224:17}})},"dojo/domReady":function(){define("dojo/domReady",["./has"],function(b){function i(a){e.push(a);j&&g()}function g(){if(!a){for(a=!0;e.length;)try{e.shift()(l)}catch(b){}a=!1;i._onQEmpty()}}var n=function(){return this}(),l=document,k={loaded:1,complete:1},o="string"!=typeof l.readyState,
j=!!k[l.readyState],e=[],a;i.load=function(a,b,c){i(c)};i._Q=e;i._onQEmpty=function(){};if(o)l.readyState="loading";if(!j){var f=[],d=function(a){a=a||n.event;if(!(j||"readystatechange"==a.type&&!k[l.readyState])){if(o)l.readyState="complete";j=1;g()}},c=function(a,b){a.addEventListener(b,d,!1);e.push(function(){a.removeEventListener(b,d,!1)})};if(!b("dom-addeventlistener")){var c=function(a,b){b="on"+b;a.attachEvent(b,d);e.push(function(){a.detachEvent(b,d)})},m=l.createElement("div");try{m.doScroll&&
null===n.frameElement&&f.push(function(){try{return m.doScroll("left"),1}catch(a){}})}catch(h){}}c(l,"DOMContentLoaded");c(n,"load");"onreadystatechange"in l?c(l,"readystatechange"):o||f.push(function(){return k[l.readyState]});if(f.length){var p=function(){if(!j){for(var a=f.length;a--;)if(f[a]()){d("poller");return}setTimeout(p,30)}};p()}}return i})},"dojo/_base/lang":function(){define(["./kernel","../has","../sniff"],function(b,i){i.add("bug-for-in-skips-shadowed",function(){for(var a in{toString:1})return 0;
return 1});var g=i("bug-for-in-skips-shadowed")?"hasOwnProperty.valueOf.isPrototypeOf.propertyIsEnumerable.toLocaleString.toString.constructor".split("."):[],n=g.length,l=function(a,f,d){var c,e=0,h=b.global;if(!d)if(a.length){c=a[e++];try{d=b.scopeMap[c]&&b.scopeMap[c][1]}catch(g){}d=d||(c in h?h[c]:f?h[c]={}:void 0)}else return h;for(;d&&(c=a[e++]);)d=c in d?d[c]:f?d[c]={}:void 0;return d},k=Object.prototype.toString,o=function(a,b,d){return(d||[]).concat(Array.prototype.slice.call(a,b||0))},j=
/\{([^\}]+)\}/g,e={_extraNames:g,_mixin:function(a,b,d){var c,e,h,j={};for(c in b)if(e=b[c],!(c in a)||a[c]!==e&&(!(c in j)||j[c]!==e))a[c]=d?d(e):e;if(i("bug-for-in-skips-shadowed")&&b)for(h=0;h<n;++h)if(c=g[h],e=b[c],!(c in a)||a[c]!==e&&(!(c in j)||j[c]!==e))a[c]=d?d(e):e;return a},mixin:function(a,b){a||(a={});for(var d=1,c=arguments.length;d<c;d++)e._mixin(a,arguments[d]);return a},setObject:function(a,b,d){var c=a.split("."),a=c.pop();return(d=l(c,!0,d))&&a?d[a]=b:void 0},getObject:function(a,
b,d){return l(a.split("."),b,d)},exists:function(a,b){return void 0!==e.getObject(a,!1,b)},isString:function(a){return"string"==typeof a||a instanceof String},isArray:function(a){return a&&(a instanceof Array||"array"==typeof a)},isFunction:function(a){return"[object Function]"===k.call(a)},isObject:function(a){return void 0!==a&&(null===a||"object"==typeof a||e.isArray(a)||e.isFunction(a))},isArrayLike:function(a){return a&&void 0!==a&&!e.isString(a)&&!e.isFunction(a)&&!(a.tagName&&"form"==a.tagName.toLowerCase())&&
(e.isArray(a)||isFinite(a.length))},isAlien:function(a){return a&&!e.isFunction(a)&&/\{\s*\[native code\]\s*\}/.test(""+a)},extend:function(a,b){for(var d=1,c=arguments.length;d<c;d++)e._mixin(a.prototype,arguments[d]);return a},_hitchArgs:function(a,f){var d=e._toArray(arguments,2),c=e.isString(f);return function(){var g=e._toArray(arguments),h=c?(a||b.global)[f]:f;return h&&h.apply(a||this,d.concat(g))}},hitch:function(a,f){if(2<arguments.length)return e._hitchArgs.apply(b,arguments);f||(f=a,a=
null);if(e.isString(f)){a=a||b.global;if(!a[f])throw['lang.hitch: scope["',f,'"] is null (scope="',a,'")'].join("");return function(){return a[f].apply(a,arguments||[])}}return!a?f:function(){return f.apply(a,arguments||[])}},delegate:function(){function a(){}return function(b,d){a.prototype=b;var c=new a;a.prototype=null;d&&e._mixin(c,d);return c}}(),_toArray:i("ie")?function(){function a(a,b,c){c=c||[];for(b=b||0;b<a.length;b++)c.push(a[b]);return c}return function(b){return(b.item?a:o).apply(this,
arguments)}}():o,partial:function(a){return e.hitch.apply(b,[null].concat(e._toArray(arguments)))},clone:function(a){if(!a||"object"!=typeof a||e.isFunction(a))return a;if(a.nodeType&&"cloneNode"in a)return a.cloneNode(!0);if(a instanceof Date)return new Date(a.getTime());if(a instanceof RegExp)return RegExp(a);var b,d,c;if(e.isArray(a)){b=[];for(d=0,c=a.length;d<c;++d)d in a&&b.push(e.clone(a[d]))}else b=a.constructor?new a.constructor:{};return e._mixin(b,a,e.clone)},trim:String.prototype.trim?
function(a){return a.trim()}:function(a){return a.replace(/^\s\s*/,"").replace(/\s\s*$/,"")},replace:function(a,b,d){return a.replace(d||j,e.isFunction(b)?b:function(a,d){return e.getObject(d,!1,b)})}};e.mixin(b,e);return e})},"dojo/request/util":function(){define("exports,../errors/RequestError,../errors/CancelError,../Deferred,../io-query,../_base/array,../_base/lang,../promise/Promise".split(","),function(b,i,g,n,l,k,o,j){function e(a){return f(a)}function a(a){return a.data||a.text}b.deepCopy=
function(a,c){for(var e in c){var f=a[e],g=c[e];f!==g&&(f&&"object"===typeof f&&g&&"object"===typeof g?b.deepCopy(f,g):a[e]=g)}return a};b.deepCreate=function(a,c){var c=c||{},e=o.delegate(a),f,g;for(f in a)(g=a[f])&&"object"===typeof g&&(e[f]=b.deepCreate(g,c[f]));return b.deepCopy(e,c)};var f=Object.freeze||function(a){return a};b.deferred=function(d,c,m,h,k,l){var r=new n(function(a){c&&c(r,d);return!a||!(a instanceof i)&&!(a instanceof g)?new g("Request canceled",d):a});r.response=d;r.isValid=
m;r.isReady=h;r.handleResponse=k;m=r.then(e).otherwise(function(a){a.response=d;throw a;});b.notify&&m.then(o.hitch(b.notify,"emit","load"),o.hitch(b.notify,"emit","error"));var h=m.then(a),k=new j,q;for(q in h)h.hasOwnProperty(q)&&(k[q]=h[q]);k.response=m;f(k);l&&r.then(function(a){l.call(r,a)},function(a){l.call(r,d,a)});r.promise=k;r.then=k.then;return r};b.addCommonMethods=function(a,b){k.forEach(b||["GET","POST","PUT","DELETE"],function(b){a[("DELETE"===b?"DEL":b).toLowerCase()]=function(c,e){e=
o.delegate(e||{});e.method=b;return a(c,e)}})};b.parseArgs=function(a,b,e){var f=b.data,g=b.query;if(f&&!e&&"object"===typeof f)b.data=l.objectToQuery(f);g?("object"===typeof g&&(g=l.objectToQuery(g)),b.preventCache&&(g+=(g?"&":"")+"request.preventCache="+ +new Date)):b.preventCache&&(g="request.preventCache="+ +new Date);a&&g&&(a+=(~a.indexOf("?")?"&":"?")+g);return{url:a,options:b,getHeader:function(){return null}}};b.checkStatus=function(a){a=a||0;return 200<=a&&300>a||304===a||1223===a||!a}})},
"dojo/Evented":function(){define(["./aspect","./on"],function(b,i){function g(){}var n=b.after;g.prototype={on:function(b,g){return i.parse(this,b,g,function(b,j){return n(b,"on"+j,g,!0)})},emit:function(b,g){var o=[this];o.push.apply(o,arguments);return i.emit.apply(i,o)}};return g})},"dojo/mouse":function(){define("dojo/mouse",["./_base/kernel","./on","./has","./dom","./_base/window"],function(b,i,g,n,l){function k(b,g){var e=function(a,e){return i(a,b,function(b){if(g)return g(b,e);if(!n.isDescendant(b.relatedTarget,
a))return e.call(this,b)})};e.bubble=function(a){return k(b,function(b,d){var c=a(b.target),e=b.relatedTarget;if(c&&c!=(e&&1==e.nodeType&&a(e)))return d.call(c,b)})};return e}g.add("dom-quirks",l.doc&&"BackCompat"==l.doc.compatMode);g.add("events-mouseenter",l.doc&&"onmouseenter"in l.doc.createElement("div"));g.add("events-mousewheel",l.doc&&"onmousewheel"in l.doc);l=g("dom-quirks")&&g("ie")||!g("dom-addeventlistener")?{LEFT:1,MIDDLE:4,RIGHT:2,isButton:function(b,g){return b.button&g},isLeft:function(b){return b.button&
1},isMiddle:function(b){return b.button&4},isRight:function(b){return b.button&2}}:{LEFT:0,MIDDLE:1,RIGHT:2,isButton:function(b,g){return b.button==g},isLeft:function(b){return 0==b.button},isMiddle:function(b){return 1==b.button},isRight:function(b){return 2==b.button}};b.mouseButtons=l;b=g("events-mousewheel")?"mousewheel":function(b,g){return i(b,"DOMMouseScroll",function(b){b.wheelDelta=-b.detail;g.call(this,b)})};return{_eventHandler:k,enter:k("mouseover"),leave:k("mouseout"),wheel:b,isLeft:l.isLeft,
isMiddle:l.isMiddle,isRight:l.isRight}})},"dojo/topic":function(){define("dojo/topic",["./Evented"],function(b){var i=new b;return{publish:function(b,n){return i.emit.apply(i,arguments)},subscribe:function(b,n){return i.on.apply(i,arguments)}}})},"dojo/_base/xhr":function(){define("./kernel,./sniff,require,../io-query,../dom,../dom-form,./Deferred,./config,./json,./lang,./array,../on,../aspect,../request/watch,../request/xhr,../request/util".split(","),function(b,i,g,n,l,k,o,j,e,a,f,d,c,m,h,p){b._xhrObj=
h._create;var s=b.config;b.objectToQuery=n.objectToQuery;b.queryToObject=n.queryToObject;b.fieldToObject=k.fieldToObject;b.formToObject=k.toObject;b.formToQuery=k.toQuery;b.formToJson=k.toJson;b._blockAsync=!1;var r=b._contentHandlers=b.contentHandlers={text:function(a){return a.responseText},json:function(a){return e.fromJson(a.responseText||null)},"json-comment-filtered":function(a){j.useCommentedJson||console.warn("Consider using the standard mimetype:application/json. json-commenting can introduce security issues. To decrease the chances of hijacking, use the standard the 'json' handler and prefix your json with: {}&&\nUse djConfig.useCommentedJson=true to turn off this message.");
var a=a.responseText,b=a.indexOf("/*"),c=a.lastIndexOf("*/");if(-1==b||-1==c)throw Error("JSON was not comment filtered");return e.fromJson(a.substring(b+2,c))},javascript:function(a){return b.eval(a.responseText)},xml:function(a){var b=a.responseXML;b&&i("dom-qsa2.1")&&!b.querySelectorAll&&i("dom-parser")&&(b=(new DOMParser).parseFromString(a.responseText,"application/xml"));if(i("ie")&&(!b||!b.documentElement)){var c=function(a){return"MSXML"+a+".DOMDocument"},c=["Microsoft.XMLDOM",c(6),c(4),c(3),
c(2)];f.some(c,function(c){try{var d=new ActiveXObject(c);d.async=!1;d.loadXML(a.responseText);b=d}catch(e){return!1}return!0})}return b},"json-comment-optional":function(a){return a.responseText&&/^[^{\[]*\/\*/.test(a.responseText)?r["json-comment-filtered"](a):r.json(a)}};b._ioSetArgs=function(c,d,e,f){var g={args:c,url:c.url},h=null;if(c.form){var h=l.byId(c.form),m=h.getAttributeNode("action");g.url=g.url||(m?m.value:null);h=k.toObject(h)}m=[{}];h&&m.push(h);c.content&&m.push(c.content);c.preventCache&&
m.push({"dojo.preventCache":(new Date).valueOf()});g.query=n.objectToQuery(a.mixin.apply(null,m));g.handleAs=c.handleAs||"text";var j=new o(function(a){a.canceled=!0;d&&d(a);var b=a.ioArgs.error;if(!b)b=Error("request cancelled"),b.dojoType="cancel",a.ioArgs.error=b;return b});j.addCallback(e);var i=c.load;i&&a.isFunction(i)&&j.addCallback(function(a){return i.call(c,a,g)});var p=c.error;p&&a.isFunction(p)&&j.addErrback(function(a){return p.call(c,a,g)});var q=c.handle;q&&a.isFunction(q)&&j.addBoth(function(a){return q.call(c,
a,g)});j.addErrback(function(a){return f(a,j)});s.ioPublish&&b.publish&&!1!==g.args.ioPublish&&(j.addCallbacks(function(a){b.publish("/dojo/io/load",[j,a]);return a},function(a){b.publish("/dojo/io/error",[j,a]);return a}),j.addBoth(function(a){b.publish("/dojo/io/done",[j,a]);return a}));j.ioArgs=g;return j};var q=function(a){a=r[a.ioArgs.handleAs](a.ioArgs.xhr);return void 0===a?null:a},u=function(a,b){b.ioArgs.args.failOk||console.error(a);return a},B=function(a){0>=t&&(t=0,s.ioPublish&&b.publish&&
(!a||a&&!1!==a.ioArgs.args.ioPublish)&&b.publish("/dojo/io/stop"))},t=0;c.after(m,"_onAction",function(){t-=1});c.after(m,"_onInFlight",B);b._ioCancelAll=m.cancelAll;b._ioNotifyStart=function(a){s.ioPublish&&b.publish&&!1!==a.ioArgs.args.ioPublish&&(t||b.publish("/dojo/io/start"),t+=1,b.publish("/dojo/io/send",[a]))};b._ioWatch=function(b,c,d,e){b.ioArgs.options=b.ioArgs.args;a.mixin(b,{response:b.ioArgs,isValid:function(){return c(b)},isReady:function(){return d(b)},handleResponse:function(){return e(b)}});
m(b);B(b)};b._ioAddQueryToUrl=function(a){if(a.query.length)a.url+=(-1==a.url.indexOf("?")?"?":"&")+a.query,a.query=null};b.xhr=function(a,c,d){var e,f=b._ioSetArgs(c,function(){e&&e.cancel()},q,u),g=f.ioArgs;"postData"in c?g.query=c.postData:"putData"in c?g.query=c.putData:"rawBody"in c?g.query=c.rawBody:(2<arguments.length&&!d||-1==="POST|PUT".indexOf(a.toUpperCase()))&&b._ioAddQueryToUrl(g);var m={method:a,handleAs:"text",timeout:c.timeout,withCredentials:c.withCredentials,ioArgs:g};if("undefined"!==
typeof c.headers)m.headers=c.headers;if("undefined"!==typeof c.contentType){if(!m.headers)m.headers={};m.headers["Content-Type"]=c.contentType}if("undefined"!==typeof g.query)m.data=g.query;if("undefined"!==typeof c.sync)m.sync=c.sync;b._ioNotifyStart(f);try{e=h(g.url,m,!0)}catch(j){return f.cancel(),f}f.ioArgs.xhr=e.response.xhr;e.then(function(){f.resolve(f)}).otherwise(function(a){g.error=a;if(a.response)a.status=a.response.status,a.responseText=a.response.text,a.xhr=a.response.xhr;f.reject(a)});
return f};b.xhrGet=function(a){return b.xhr("GET",a)};b.rawXhrPost=b.xhrPost=function(a){return b.xhr("POST",a,!0)};b.rawXhrPut=b.xhrPut=function(a){return b.xhr("PUT",a,!0)};b.xhrDelete=function(a){return b.xhr("DELETE",a)};b._isDocumentOk=function(a){return p.checkStatus(a.status)};b._getText=function(a){var c;b.xhrGet({url:a,sync:!0,load:function(a){c=a}});return c};a.mixin(b.xhr,{_xhrObj:b._xhrObj,fieldToObject:k.fieldToObject,formToObject:k.toObject,objectToQuery:n.objectToQuery,formToQuery:k.toQuery,
formToJson:k.toJson,queryToObject:n.queryToObject,contentHandlers:r,_ioSetArgs:b._ioSetArgs,_ioCancelAll:b._ioCancelAll,_ioNotifyStart:b._ioNotifyStart,_ioWatch:b._ioWatch,_ioAddQueryToUrl:b._ioAddQueryToUrl,_isDocumentOk:b._isDocumentOk,_getText:b._getText,get:b.xhrGet,post:b.xhrPost,put:b.xhrPut,del:b.xhrDelete});return b.xhr})},"dojo/loadInit":function(){define(["./_base/loader"],function(b){return{dynamic:0,normalize:function(b){return b},load:b.loadInit}})},"dojo/_base/unload":function(){define(["./kernel",
"./lang","../on"],function(b,i,g){var n=window,l={addOnWindowUnload:function(k,l){if(!b.windowUnloaded)g(n,"unload",b.windowUnloaded=function(){});g(n,"unload",i.hitch(k,l))},addOnUnload:function(b,l){g(n,"beforeunload",i.hitch(b,l))}};b.addOnWindowUnload=l.addOnWindowUnload;b.addOnUnload=l.addOnUnload;return l})},"dojo/Deferred":function(){define(["./has","./_base/lang","./errors/CancelError","./promise/Promise","./promise/instrumentation"],function(b,i,g,n,l){var k=Object.freeze||function(){},o=
function(a,b,e,g,k){2===b&&f.instrumentRejected&&0===a.length&&f.instrumentRejected(e,!1,g,k);for(k=0;k<a.length;k++)j(a[k],b,e,g)},j=function(b,c,g,h){var j=b[c],k=b.deferred;if(j)try{var i=j(g);if(0===c)"undefined"!==typeof i&&a(k,c,i);else{if(i&&"function"===typeof i.then){b.cancel=i.cancel;i.then(e(k,1),e(k,2),e(k,0));return}a(k,1,i)}}catch(l){a(k,2,l)}else a(k,c,g);2===c&&f.instrumentRejected&&f.instrumentRejected(g,!!j,h,k.promise)},e=function(b,c){return function(e){a(b,c,e)}},a=function(a,
b,e){if(!a.isCanceled())switch(b){case 0:a.progress(e);break;case 1:a.resolve(e);break;case 2:a.reject(e)}},f=function(a){var b=this.promise=new n,e=this,h,i,l,r=!1,q=[];Error.captureStackTrace&&(Error.captureStackTrace(e,f),Error.captureStackTrace(b,f));this.isResolved=b.isResolved=function(){return 1===h};this.isRejected=b.isRejected=function(){return 2===h};this.isFulfilled=b.isFulfilled=function(){return!!h};this.isCanceled=b.isCanceled=function(){return r};this.progress=function(a,d){if(h){if(!0===
d)throw Error("This deferred has already been fulfilled.");return b}o(q,0,a,null,e);return b};this.resolve=function(a,d){if(h){if(!0===d)throw Error("This deferred has already been fulfilled.");return b}o(q,h=1,i=a,null,e);q=null;return b};var u=this.reject=function(a,d){if(h){if(!0===d)throw Error("This deferred has already been fulfilled.");return b}Error.captureStackTrace&&Error.captureStackTrace(l={},u);o(q,h=2,i=a,l,e);q=null;return b};this.then=b.then=function(a,d,e){var g=[e,a,d];g.cancel=
b.cancel;g.deferred=new f(function(a){return g.cancel&&g.cancel(a)});h&&!q?j(g,h,i,l):q.push(g);return g.deferred.promise};this.cancel=b.cancel=function(b,c){if(h){if(!0===c)throw Error("This deferred has already been fulfilled.");}else{if(a)var e=a(b),b="undefined"===typeof e?b:e;r=!0;if(h){if(2===h&&i===b)return b}else return"undefined"===typeof b&&(b=new g),u(b),b}};k(b)};f.prototype.toString=function(){return"[object Deferred]"};l&&l(f);return f})},"dojo/_base/NodeList":function(){define("dojo/_base/NodeList",
["./kernel","../query","./array","./html","../NodeList-dom"],function(b,i,g){var i=i.NodeList,n=i.prototype;n.connect=i._adaptAsForEach(function(){return b.connect.apply(this,arguments)});n.coords=i._adaptAsMap(b.coords);i.events="blur,focus,change,click,error,keydown,keypress,keyup,load,mousedown,mouseenter,mouseleave,mousemove,mouseout,mouseover,mouseup,submit".split(",");g.forEach(i.events,function(b){var g="on"+b;n[g]=function(b,j){return this.connect(g,b,j)}});return b.NodeList=i})},"dojo/_base/Color":function(){define(["./kernel",
"./lang","./array","./config"],function(b,i,g,n){var l=b.Color=function(b){b&&this.setColor(b)};l.named={black:[0,0,0],silver:[192,192,192],gray:[128,128,128],white:[255,255,255],maroon:[128,0,0],red:[255,0,0],purple:[128,0,128],fuchsia:[255,0,255],green:[0,128,0],lime:[0,255,0],olive:[128,128,0],yellow:[255,255,0],navy:[0,0,128],blue:[0,0,255],teal:[0,128,128],aqua:[0,255,255],transparent:n.transparentColor||[0,0,0,0]};i.extend(l,{r:255,g:255,b:255,a:1,_set:function(b,g,j,e){this.r=b;this.g=g;this.b=
j;this.a=e},setColor:function(b){i.isString(b)?l.fromString(b,this):i.isArray(b)?l.fromArray(b,this):(this._set(b.r,b.g,b.b,b.a),b instanceof l||this.sanitize());return this},sanitize:function(){return this},toRgb:function(){return[this.r,this.g,this.b]},toRgba:function(){return[this.r,this.g,this.b,this.a]},toHex:function(){return"#"+g.map(["r","g","b"],function(b){b=this[b].toString(16);return 2>b.length?"0"+b:b},this).join("")},toCss:function(b){var g=this.r+", "+this.g+", "+this.b;return(b?"rgba("+
g+", "+this.a:"rgb("+g)+")"},toString:function(){return this.toCss(!0)}});l.blendColors=b.blendColors=function(b,i,j,e){var a=e||new l;g.forEach(["r","g","b","a"],function(e){a[e]=b[e]+(i[e]-b[e])*j;"a"!=e&&(a[e]=Math.round(a[e]))});return a.sanitize()};l.fromRgb=b.colorFromRgb=function(b,g){var j=b.toLowerCase().match(/^rgba?\(([\s\.,0-9]+)\)/);return j&&l.fromArray(j[1].split(/\s*,\s*/),g)};l.fromHex=b.colorFromHex=function(b,i){var j=i||new l,e=4==b.length?4:8,a=(1<<e)-1,b=Number("0x"+b.substr(1));
if(isNaN(b))return null;g.forEach(["b","g","r"],function(f){var d=b&a;b>>=e;j[f]=4==e?17*d:d});j.a=1;return j};l.fromArray=b.colorFromArray=function(b,g){var j=g||new l;j._set(Number(b[0]),Number(b[1]),Number(b[2]),Number(b[3]));if(isNaN(j.a))j.a=1;return j.sanitize()};l.fromString=b.colorFromString=function(b,g){var j=l.named[b];return j&&l.fromArray(j,g)||l.fromRgb(b,g)||l.fromHex(b,g)};return l})},"dojo/promise/instrumentation":function(){define(["./tracer","../has","../_base/lang","../_base/array"],
function(b,i,g,n){function l(a,b,e){var f="";a&&a.stack&&(f+=a.stack);b&&b.stack&&(f+="\n ----------------------------------------\n rejected"+b.stack.split("\n").slice(1).join("\n").replace(/^\s+/," "));e&&e.stack&&(f+="\n ----------------------------------------\n"+e.stack);console.error(a,f)}function k(a,b,e,f){b||l(a,e,f)}function o(b,c,g,h){n.some(e,function(a){if(a.error===b){if(c)a.handled=!0;return!0}})||e.push({error:b,rejection:g,handled:c,deferred:h,timestamp:(new Date).getTime()});
a||(a=setTimeout(j,f))}function j(){var b=(new Date).getTime(),c=b-f;e=n.filter(e,function(a){return a.timestamp<c?(a.handled||l(a.error,a.rejection,a.deferred),!1):!0});a=e.length?setTimeout(j,e[0].timestamp+f-b):!1}i.add("config-useDeferredInstrumentation","report-unhandled-rejections");var e=[],a=!1,f=1E3;return function(a){var c=i("config-useDeferredInstrumentation");if(c){b.on("resolved",g.hitch(console,"log","resolved"));b.on("rejected",g.hitch(console,"log","rejected"));b.on("progress",g.hitch(console,
"log","progress"));var e=[];"string"===typeof c&&(e=c.split(","),c=e.shift());if("report-rejections"===c)a.instrumentRejected=k;else if("report-unhandled-rejections"===c||!0===c||1===c)a.instrumentRejected=o,f=parseInt(e[0],10)||f;else throw Error("Unsupported instrumentation usage <"+c+">");}}})},"dojo/selector/_loader":function(){define("dojo/selector/_loader",["../has","require"],function(b,i){var g=document.createElement("div");b.add("dom-qsa2.1",!!g.querySelectorAll);b.add("dom-qsa3",function(){try{return g.innerHTML=
"<p class='TEST'></p>",1==g.querySelectorAll(".TEST:empty").length}catch(b){}});var n;return{load:function(g,k,o){var j=i,g="default"==g?b("config-selectorEngine")||"css3":g,g="css2"==g||"lite"==g?"./lite":"css2.1"==g?b("dom-qsa2.1")?"./lite":"./acme":"css3"==g?b("dom-qsa3")?"./lite":"./acme":"acme"==g?"./acme":(j=k)&&g;if("?"==g.charAt(g.length-1))var g=g.substring(0,g.length-1),e=!0;if(e&&(b("dom-compliant-qsa")||n))return o(n);j([g],function(a){"./lite"!=g&&(n=a);o(a)})}}})},"dojo/promise/Promise":function(){define("dojo/promise/Promise",
["../_base/lang"],function(b){function i(){throw new TypeError("abstract");}return b.extend(function(){},{then:function(){i()},cancel:function(){i()},isResolved:function(){i()},isRejected:function(){i()},isFulfilled:function(){i()},isCanceled:function(){i()},always:function(b){return this.then(b,b)},otherwise:function(b){return this.then(null,b)},trace:function(){return this},traceRejected:function(){return this},toString:function(){return"[object Promise]"}})})},"dojo/request/watch":function(){define("./util,../errors/RequestTimeoutError,../errors/CancelError,../_base/array,../_base/window,../has!host-browser?dom-addeventlistener?:../on:".split(","),
function(b,i,g,n,l,k){function o(){for(var b=+new Date,d=0,c;d<a.length&&(c=a[d]);d++){var g=c.response,h=g.options;if(c.isCanceled&&c.isCanceled()||c.isValid&&!c.isValid(g))a.splice(d--,1),j._onAction&&j._onAction();else if(c.isReady&&c.isReady(g))a.splice(d--,1),c.handleResponse(g),j._onAction&&j._onAction();else if(c.startTime&&c.startTime+(h.timeout||0)<b)a.splice(d--,1),c.cancel(new i("Timeout exceeded",g)),j._onAction&&j._onAction()}j._onInFlight&&j._onInFlight(c);a.length||(clearInterval(e),
e=null)}function j(b){if(b.response.options.timeout)b.startTime=+new Date;b.isFulfilled()||(a.push(b),e||(e=setInterval(o,50)),b.response.options.sync&&o())}var e=null,a=[];j.cancelAll=function(){try{n.forEach(a,function(a){try{a.cancel(new g("All requests canceled."))}catch(b){}})}catch(b){}};l&&k&&l.doc.attachEvent&&k(l.global,"unload",function(){j.cancelAll()});return j})},"dojo/on":function(){define(["./has!dom-addeventlistener?:./aspect","./_base/kernel","./has"],function(b,i,g){function n(a,
b,c,f,h){if(f=b.match(/(.*):(.*)/))return b=f[2],f=f[1],j.selector(f,b).call(h,a,c);g("touch")&&(e.test(b)&&(c=v(c)),!g("event-orientationchange")&&"orientationchange"==b&&(b="resize",a=window,c=v(c)));m&&(c=m(c));if(a.addEventListener){var i=b in d,k=i?d[b]:b;a.addEventListener(k,c,i);return{remove:function(){a.removeEventListener(k,c,i)}}}if(r&&a.attachEvent)return r(a,"on"+b,c);throw Error("Target must be an event emitter");}function l(){this.cancelable=!1}function k(){this.bubbles=!1}var o=window.ScriptEngineMajorVersion;
g.add("jscript",o&&o()+ScriptEngineMinorVersion()/10);g.add("event-orientationchange",g("touch")&&!g("android"));g.add("event-stopimmediatepropagation",window.Event&&!!window.Event.prototype&&!!window.Event.prototype.stopImmediatePropagation);g.add("event-focusin",function(a,b,c){return"onfocusin"in c});g("touch")&&g.add("touch-can-modify-event-delegate",function(){var a=function(){};a.prototype=document.createEvent("MouseEvents");try{var b=new a;b.target=null;return null===b.target}catch(c){return!1}});
var j=function(a,b,c,d){return"function"==typeof a.on&&"function"!=typeof b&&!a.nodeType?a.on(b,c):j.parse(a,b,c,n,d,this)};j.pausable=function(a,b,c,d){var e,a=j(a,b,function(){if(!e)return c.apply(this,arguments)},d);a.pause=function(){e=!0};a.resume=function(){e=!1};return a};j.once=function(a,b,c){var d=j(a,b,function(){d.remove();return c.apply(this,arguments)});return d};j.parse=function(a,b,c,d,e,f){if(b.call)return b.call(f,a,c);if(-1<b.indexOf(",")){for(var b=b.split(/\s*,\s*/),g=[],h=0,
j;j=b[h++];)g.push(d(a,j,c,e,f));g.remove=function(){for(var a=0;a<g.length;a++)g[a].remove()};return g}return d(a,b,c,e,f)};var e=/^touch/;j.selector=function(a,b,c){return function(d,e){function f(b){for(g=g&&g.matches?g:i.query;!g.matches(b,a,d);)if(b==d||!1===c||!(b=b.parentNode)||1!=b.nodeType)return;return b}var g="function"==typeof a?{matches:a}:this,h=b.bubble;return h?j(d,h(f),e):j(d,b,function(a){var b=f(a.target);if(b)return e.call(b,a)})}};var a=[].slice,f=j.emit=function(b,c,d){var e=
a.call(arguments,2),f="on"+c;if("parentNode"in b){var g=e[0]={},h;for(h in d)g[h]=d[h];g.preventDefault=l;g.stopPropagation=k;g.target=b;g.type=c;d=g}do b[f]&&b[f].apply(b,e);while(d&&d.bubbles&&(b=b.parentNode));return d&&d.cancelable&&d},d=g("event-focusin")?{}:{focusin:"focus",focusout:"blur"};if(!g("event-stopimmediatepropagation"))var c=function(){this.modified=this.immediatelyStopped=!0},m=function(a){return function(b){if(!b.immediatelyStopped)return b.stopImmediatePropagation=c,a.apply(this,
arguments)}};if(g("dom-addeventlistener"))j.emit=function(a,b,c){if(a.dispatchEvent&&document.createEvent){var d=(a.ownerDocument||document).createEvent("HTMLEvents");d.initEvent(b,!!c.bubbles,!!c.cancelable);for(var e in c)e in d||(d[e]=c[e]);return a.dispatchEvent(d)&&d}return f.apply(j,arguments)};else{j._fixEvent=function(a,b){if(!a)a=(b&&(b.ownerDocument||b.document||b).parentWindow||window).event;if(!a)return a;h&&a.type==h.type&&(a=h);if(!a.target){a.target=a.srcElement;a.currentTarget=b||
a.srcElement;if("mouseover"==a.type)a.relatedTarget=a.fromElement;if("mouseout"==a.type)a.relatedTarget=a.toElement;if(!a.stopPropagation)a.stopPropagation=q,a.preventDefault=u;switch(a.type){case "keypress":var c="charCode"in a?a.charCode:a.keyCode;10==c?(c=0,a.keyCode=13):13==c||27==c?c=0:3==c&&(c=99);a.charCode=c;c=a;c.keyChar=c.charCode?String.fromCharCode(c.charCode):"";c.charOrCode=c.keyChar||c.keyCode}}return a};var h,p=function(a){this.handle=a};p.prototype.remove=function(){delete _dojoIEListeners_[this.handle]};
var s=function(a){return function(b){var b=j._fixEvent(b,this),c=a.call(this,b);b.modified&&(h||setTimeout(function(){h=null}),h=b);return c}},r=function(a,c,d){d=s(d);if(((a.ownerDocument?a.ownerDocument.parentWindow:a.parentWindow||a.window||window)!=top||5.8>g("jscript"))&&!g("config-_allow_leaks")){"undefined"==typeof _dojoIEListeners_&&(_dojoIEListeners_=[]);var e=a[c];if(!e||!e.listeners){var f=e,e=Function("event","var callee = arguments.callee; for(var i = 0; i<callee.listeners.length; i++){var listener = _dojoIEListeners_[callee.listeners[i]]; if(listener){listener.call(this,event);}}");
e.listeners=[];a[c]=e;e.global=this;f&&e.listeners.push(_dojoIEListeners_.push(f)-1)}e.listeners.push(a=e.global._dojoIEListeners_.push(d)-1);return new p(a)}return b.after(a,c,d,!0)},q=function(){this.cancelBubble=!0},u=j._preventDefault=function(){this.bubbledKeyCode=this.keyCode;if(this.ctrlKey)try{this.keyCode=0}catch(a){}this.defaultPrevented=!0;this.returnValue=!1}}if(g("touch"))var B=function(){},t=window.orientation,v=function(a){return function(b){var c=b.corrected;if(!c){var d=b.type;try{delete b.type}catch(e){}if(b.type){if(g("touch-can-modify-event-delegate"))B.prototype=
b,c=new B;else{var c={},f;for(f in b)c[f]=b[f]}c.preventDefault=function(){b.preventDefault()};c.stopPropagation=function(){b.stopPropagation()}}else c=b,c.type=d;b.corrected=c;if("resize"==d){if(t==window.orientation)return null;t=window.orientation;c.type="orientationchange";return a.call(this,c)}if(!("rotation"in c))c.rotation=0,c.scale=1;var d=c.changedTouches[0],h;for(h in d)delete c[h],c[h]=d[h]}return a.call(this,c)}};return j})},"dojo/_base/sniff":function(){define(["./kernel","./lang","../sniff"],
function(b,i,g){b._name="browser";i.mixin(b,{isBrowser:!0,isFF:g("ff"),isIE:g("ie"),isKhtml:g("khtml"),isWebKit:g("webkit"),isMozilla:g("mozilla"),isMoz:g("mozilla"),isOpera:g("opera"),isSafari:g("safari"),isChrome:g("chrome"),isMac:g("mac"),isIos:g("ios"),isAndroid:g("android"),isWii:g("wii"),isQuirks:g("quirks"),isAir:g("air")});b.locale=b.locale||(g("ie")?navigator.userLanguage:navigator.language).toLowerCase();return g})},"dojo/errors/create":function(){define(["../_base/lang"],function(b){return function(i,
g,n,l){var n=n||Error,k=function(b){if(n===Error){Error.captureStackTrace&&Error.captureStackTrace(this,k);var j=Error.call(this,b),e;for(e in j)j.hasOwnProperty(e)&&(this[e]=j[e]);this.message=b;this.stack=j.stack}else n.apply(this,arguments);g&&g.apply(this,arguments)};k.prototype=b.delegate(n.prototype,l);k.prototype.name=i;return k.prototype.constructor=k}})},"dojo/_base/array":function(){define(["./kernel","../has","./lang"],function(b,i,g){function n(a){return o[a]=new Function("item","index",
"array",a)}function l(a){var b=!a;return function(d,c,e){var g=0,j=d&&d.length||0,i;j&&"string"==typeof d&&(d=d.split(""));"string"==typeof c&&(c=o[c]||n(c));if(e)for(;g<j;++g){if(i=!c.call(e,d[g],g,d),a^i)return!i}else for(;g<j;++g)if(i=!c(d[g],g,d),a^i)return!i;return b}}function k(a){var b=1,d=0,c=0;a||(b=d=c=-1);return function(g,h,i,k){if(k&&0<b)return e.lastIndexOf(g,h,i);var k=g&&g.length||0,l=a?k+c:d;i===j?i=a?d:k+c:0>i?(i=k+i,0>i&&(i=d)):i=i>=k?k+c:i;for(k&&"string"==typeof g&&(g=g.split(""));i!=
l;i+=b)if(g[i]==h)return i;return-1}}var o={},j,e={every:l(!1),some:l(!0),indexOf:k(!0),lastIndexOf:k(!1),forEach:function(a,b,d){var c=0,e=a&&a.length||0;e&&"string"==typeof a&&(a=a.split(""));"string"==typeof b&&(b=o[b]||n(b));if(d)for(;c<e;++c)b.call(d,a[c],c,a);else for(;c<e;++c)b(a[c],c,a)},map:function(a,b,d,c){var e=0,g=a&&a.length||0,c=new (c||Array)(g);g&&"string"==typeof a&&(a=a.split(""));"string"==typeof b&&(b=o[b]||n(b));if(d)for(;e<g;++e)c[e]=b.call(d,a[e],e,a);else for(;e<g;++e)c[e]=
b(a[e],e,a);return c},filter:function(a,b,d){var c=0,e=a&&a.length||0,g=[],j;e&&"string"==typeof a&&(a=a.split(""));"string"==typeof b&&(b=o[b]||n(b));if(d)for(;c<e;++c)j=a[c],b.call(d,j,c,a)&&g.push(j);else for(;c<e;++c)j=a[c],b(j,c,a)&&g.push(j);return g},clearCache:function(){o={}}};g.mixin(b,e);return e})},"dojo/_base/json":function(){define(["./kernel","../json"],function(b,i){b.fromJson=function(b){return eval("("+b+")")};b._escapeString=i.stringify;b.toJsonIndentStr="\t";b.toJson=function(g,
n){return i.stringify(g,function(b,g){if(g){var i=g.__json__||g.json;if("function"==typeof i)return i.call(g)}return g},n&&b.toJsonIndentStr)};return b})},"dojo/_base/window":function(){define("dojo/_base/window",["./kernel","./lang","../sniff"],function(b,i,g){var n={global:b.global,doc:b.global.document||null,body:function(g){g=g||b.doc;return g.body||g.getElementsByTagName("body")[0]},setContext:function(g,i){b.global=n.global=g;b.doc=n.doc=i},withGlobal:function(g,i,o,j){var e=b.global;try{return b.global=
n.global=g,n.withDoc.call(null,g.document,i,o,j)}finally{b.global=n.global=e}},withDoc:function(i,k,o,j){var e=n.doc,a=g("quirks"),f=g("ie"),d,c,m;try{b.doc=n.doc=i;b.isQuirks=g.add("quirks","BackCompat"==b.doc.compatMode,!0,!0);if(g("ie")&&(m=i.parentWindow)&&m.navigator)d=parseFloat(m.navigator.appVersion.split("MSIE ")[1])||void 0,(c=i.documentMode)&&5!=c&&Math.floor(d)!=c&&(d=c),b.isIE=g.add("ie",d,!0,!0);o&&"string"==typeof k&&(k=o[k]);return k.apply(o,j||[])}finally{b.doc=n.doc=e,b.isQuirks=
g.add("quirks",a,!0,!0),b.isIE=g.add("ie",f,!0,!0)}}};i.mixin(b,n);return n})},"dojo/dom-class":function(){define(["./_base/lang","./_base/array","./dom"],function(b,i,g){function n(b){if("string"==typeof b||b instanceof String){if(b&&!k.test(b))return o[0]=b,o;b=b.split(k);b.length&&!b[0]&&b.shift();b.length&&!b[b.length-1]&&b.pop();return b}return!b?[]:i.filter(b,function(a){return a})}var l,k=/\s+/,o=[""],j={};return l={contains:function(b,a){return 0<=(" "+g.byId(b).className+" ").indexOf(" "+
a+" ")},add:function(b,a){var b=g.byId(b),a=n(a),f=b.className,d,f=f?" "+f+" ":" ";d=f.length;for(var c=0,j=a.length,h;c<j;++c)(h=a[c])&&0>f.indexOf(" "+h+" ")&&(f+=h+" ");d<f.length&&(b.className=f.substr(1,f.length-2))},remove:function(e,a){var e=g.byId(e),f;if(void 0!==a){a=n(a);f=" "+e.className+" ";for(var d=0,c=a.length;d<c;++d)f=f.replace(" "+a[d]+" "," ");f=b.trim(f)}else f="";e.className!=f&&(e.className=f)},replace:function(b,a,f){b=g.byId(b);j.className=b.className;l.remove(j,f);l.add(j,
a);b.className!==j.className&&(b.className=j.className)},toggle:function(b,a,f){b=g.byId(b);if(void 0===f)for(var a=n(a),d=0,c=a.length,j;d<c;++d)j=a[d],l[l.contains(b,j)?"remove":"add"](b,j);else l[f?"add":"remove"](b,a);return f}}})},"dojo/_base/config":function(){define(["../has","require"],function(b,i){var g={},n=i.rawConfig,l;for(l in n)g[l]=n[l];return g})},"dojo/main":function(){define("./_base/kernel,./has,require,./sniff,./_base/lang,./_base/array,./_base/config,./ready,./_base/declare,./_base/connect,./_base/Deferred,./_base/json,./_base/Color,./has!dojo-firebug?./_firebug/firebug,./_base/browser,./_base/loader".split(","),
function(b,i,g,n,l,k,o,j){o.isDebug&&g(["./_firebug/firebug"]);var e=o.require;e&&(e=k.map(l.isArray(e)?e:[e],function(a){return a.replace(/\./g,"/")}),b.isAsync?g(e):j(1,function(){g(e)}));return b})},"dojo/_base/event":function(){define("dojo/_base/event",["./kernel","../on","../has","../dom-geometry"],function(b,i,g,n){if(i._fixEvent){var l=i._fixEvent;i._fixEvent=function(b,g){(b=l(b,g))&&n.normalizeEvent(b);return b}}var k={fix:function(b,g){return i._fixEvent?i._fixEvent(b,g):b},stop:function(b){g("dom-addeventlistener")||
b&&b.preventDefault?(b.preventDefault(),b.stopPropagation()):(b=b||window.event,b.cancelBubble=!0,i._preventDefault.call(b))}};b.fixEvent=k.fix;b.stopEvent=k.stop;return k})},"dojo/sniff":function(){define(["./has"],function(b){var i=navigator,g=i.userAgent,i=i.appVersion,n=parseFloat(i);b.add("air",0<=g.indexOf("AdobeAIR"));b.add("khtml",0<=i.indexOf("Konqueror")?n:void 0);b.add("webkit",parseFloat(g.split("WebKit/")[1])||void 0);b.add("chrome",parseFloat(g.split("Chrome/")[1])||void 0);b.add("safari",
0<=i.indexOf("Safari")&&!b("chrome")?parseFloat(i.split("Version/")[1]):void 0);b.add("mac",0<=i.indexOf("Macintosh"));b.add("quirks","BackCompat"==document.compatMode);b.add("ios",/iPhone|iPod|iPad/.test(g));b.add("android",parseFloat(g.split("Android ")[1])||void 0);b.add("trident",parseFloat(i.split("Trident/")[1])||void 0);if(!b("webkit")){0<=g.indexOf("Opera")&&b.add("opera",9.8<=n?parseFloat(g.split("Version/")[1])||n:n);0<=g.indexOf("Gecko")&&!b("khtml")&&!b("webkit")&&!b("trident")&&b.add("mozilla",
n);b("mozilla")&&b.add("ff",parseFloat(g.split("Firefox/")[1]||g.split("Minefield/")[1])||void 0);if(document.all&&!b("opera"))g=parseFloat(i.split("MSIE ")[1])||void 0,(i=document.documentMode)&&5!=i&&Math.floor(g)!=i&&(g=i),b.add("ie",g);b.add("wii","undefined"!=typeof opera&&opera.wiiremote)}return b})},"dojo/request/handlers":function(){define(["../json","../_base/kernel","../_base/array","../has","../selector/_loader"],function(b,i,g,n){function l(b){var a=j[b.options.handleAs];b.data=a?a(b):
b.data||b.text;return b}n.add("activex","undefined"!==typeof ActiveXObject);n.add("dom-parser",function(b){return"DOMParser"in b});var k;if(n("activex")){var o=["Msxml2.DOMDocument.6.0","Msxml2.DOMDocument.4.0","MSXML2.DOMDocument.3.0","MSXML.DOMDocument"];k=function(b){var a=b.data;a&&n("dom-qsa2.1")&&!a.querySelectorAll&&n("dom-parser")&&(a=(new DOMParser).parseFromString(b.text,"application/xml"));if(!a||!a.documentElement){var f=b.text;g.some(o,function(b){try{var c=new ActiveXObject(b);c.async=
!1;c.loadXML(f);a=c}catch(e){return!1}return!0})}return a}}var j={javascript:function(b){return i.eval(b.text||"")},json:function(e){return b.parse(e.text||null)},xml:k};l.register=function(b,a){j[b]=a};return l})},"dojo/aspect":function(){define([],function(){function b(b,e,a,f){var d=b[e],c="around"==e,g;if(c){var h=a(function(){return d.advice(this,arguments)});g={remove:function(){h&&(h=b=a=null)},advice:function(a,b){return h?h.apply(a,b):d.advice(a,b)}}}else g={remove:function(){if(g.advice){var c=
g.previous,d=g.next;if(!d&&!c)delete b[e];else if(c?c.next=d:b[e]=d,d)d.previous=c;b=a=g.advice=null}},id:n++,advice:a,receiveArguments:f};if(d&&!c)if("after"==e){for(;d.next&&(d=d.next););d.next=g;g.previous=d}else{if("before"==e)b[e]=g,g.next=d,d.previous=g}else b[e]=g;return g}function i(i){return function(e,a,f,d){var c=e[a],k;if(!c||c.target!=e){e[a]=k=function(){for(var a=n,b=arguments,c=k.before;c;)b=c.advice.apply(this,b)||b,c=c.next;if(k.around)var d=k.around.advice(this,b);for(c=k.after;c&&
c.id<a;){if(c.receiveArguments)var e=c.advice.apply(this,b),d=e===g?d:e;else d=c.advice.call(this,d,b);c=c.next}return d};if(c)k.around={advice:function(a,b){return c.apply(a,b)}};k.target=e}e=b(k||c,i,f,d);f=null;return e}}var g,n=0,l=i("after"),k=i("before"),o=i("around");return{before:k,around:o,after:l}})},"dojo/ready":function(){define(["./_base/kernel","./has","require","./domReady","./_base/lang"],function(b,i,g,n,l){var k=0,o=[],j=0,i=function(){k=1;b._postLoad=b.config.afterOnLoad=!0;e()},
e=function(){if(!j){for(j=1;k&&(!n||0==n._Q.length)&&g.idle()&&o.length;){var a=o.shift();try{a()}catch(b){}}j=0}};g.on("idle",e);if(n)n._onQEmpty=e;var a=b.ready=b.addOnLoad=function(a,c,f){var g=l._toArray(arguments);"number"!=typeof a?(f=c,c=a,a=1E3):g.shift();f=f?l.hitch.apply(b,g):function(){c()};f.priority=a;for(g=0;g<o.length&&a>=o[g].priority;g++);o.splice(g,0,f);e()},f=b.config.addOnLoad;if(f)a[l.isArray(f)?"apply":"call"](b,f);b.config.parseOnLoad&&!b.isAsync&&a(99,function(){b.parser||
(b.deprecated("Add explicit require(['dojo/parser']);","","2.0"),g(["dojo/parser"]))});n?n(i):i();return a})},"dojo/_base/connect":function(){define("dojo/_base/connect","./kernel,../on,../topic,../aspect,./event,../mouse,./sniff,./lang,../keys".split(","),function(b,i,g,n,l,k,o,j){function e(a,c,d,e,f){e=j.hitch(d,e);if(!a||!a.addEventListener&&!a.attachEvent)return n.after(a||b.global,c,e,!0);"string"==typeof c&&"on"==c.substring(0,2)&&(c=c.substring(2));if(!a)a=b.global;if(!f)switch(c){case "keypress":c=
m;break;case "mouseenter":c=k.enter;break;case "mouseleave":c=k.leave}return i(a,c,e,f)}function a(a){a.keyChar=a.charCode?String.fromCharCode(a.charCode):"";a.charOrCode=a.keyChar||a.keyCode}o.add("events-keypress-typed",function(){var a={charCode:0};try{a=document.createEvent("KeyboardEvent"),(a.initKeyboardEvent||a.initKeyEvent).call(a,"keypress",!0,!0,null,!1,!1,!1,!1,9,3)}catch(b){}return 0==a.charCode&&!o("opera")});var f={106:42,111:47,186:59,187:43,188:44,189:45,190:46,191:47,192:96,219:91,
220:92,221:93,222:39,229:113},d=o("mac")?"metaKey":"ctrlKey",c=function(b,c){var d=j.mixin({},b,c);a(d);d.preventDefault=function(){b.preventDefault()};d.stopPropagation=function(){b.stopPropagation()};return d},m;m=o("events-keypress-typed")?function(a,b){var d=i(a,"keydown",function(a){var d=a.keyCode,e=13!=d&&32!=d&&(27!=d||!o("ie"))&&(48>d||90<d)&&(96>d||111<d)&&(186>d||192<d)&&(219>d||222<d)&&229!=d;if(e||a.ctrlKey){e=e?0:d;if(a.ctrlKey){if(3==d||13==d)return b.call(a.currentTarget,a);e=95<e&&
106>e?e-48:!a.shiftKey&&65<=e&&90>=e?e+32:f[e]||e}d=c(a,{type:"keypress",faux:!0,charCode:e});b.call(a.currentTarget,d);if(o("ie"))try{a.keyCode=d.keyCode}catch(g){}}}),e=i(a,"keypress",function(a){var d=a.charCode,a=c(a,{charCode:32<=d?d:0,faux:!0});return b.call(this,a)});return{remove:function(){d.remove();e.remove()}}}:o("opera")?function(a,b){return i(a,"keypress",function(a){var d=a.which;3==d&&(d=99);d=32>d&&!a.shiftKey?0:d;a.ctrlKey&&!a.shiftKey&&65<=d&&90>=d&&(d+=32);return b.call(this,c(a,
{charCode:d}))})}:function(b,c){return i(b,"keypress",function(b){a(b);return c.call(this,b)})};var h={_keypress:m,connect:function(a,b,c,d,f){var g=arguments,h=[],i=0;h.push("string"==typeof g[0]?null:g[i++],g[i++]);var j=g[i+1];h.push("string"==typeof j||"function"==typeof j?g[i++]:null,g[i++]);for(j=g.length;i<j;i++)h.push(g[i]);return e.apply(this,h)},disconnect:function(a){a&&a.remove()},subscribe:function(a,b,c){return g.subscribe(a,j.hitch(b,c))},publish:function(a,b){return g.publish.apply(g,
[a].concat(b))},connectPublisher:function(a,b,c){var d=function(){h.publish(a,arguments)};return c?h.connect(b,c,d):h.connect(b,d)},isCopyKey:function(a){return a[d]}};h.unsubscribe=h.disconnect;j.mixin(b,h);return h})},"dojo/errors/CancelError":function(){define("dojo/errors/CancelError",["./create"],function(b){return b("CancelError",null,null,{dojoType:"cancel"})})}}});(function(){var b=this.require;b({cache:{}});!b.async&&b(["dojo"]);b.boot&&b.apply(null,b.boot)})();
| mit |
andreimaximov/algorithms | geeks-for-geeks/linked-lists/flatten-multi-level-list/flatten.py | 2785 | #!/usr/bin/env python
from collections import deque
class Node(object):
"""Represents a multi-level linked list node."""
def __init__(self, value):
self.value = value
self.next = None
self.child = None
def get(self, i):
"""Returns the ith node of the list."""
node = self
while i > 0 and node is not None:
node = node.next
i -= 1
return node
def __eq__(self, other):
"""Checks if two lists are identical. Does not check for cycles."""
# Check these nodes
if not isinstance(other, Node) or self.value != other.value:
return False
# Check next
if self.next is not None and self.next != other.next:
return False
elif self.next is None and other.next is not None:
return False
# Check child
if self.child is not None and self.child != other.child:
return False
elif self.child is None and other.child is not None:
return False
return True
def __ne__(self, other):
return not self == other
@staticmethod
def build(iterable):
"""Creates a single level linked list from an iterable."""
head = Node(None)
tail = head
for x in iterable:
tail.next = Node(x)
tail = tail.next
return head.next
def flatten(node):
"""Flattens a multi-level linked list.
Args:
node (Node): The head of the multi-level list we want to flatten
Returns:
Node: The head of the flattened list
"""
if node is None:
return None
head = Node(None)
tail = head
queue = deque([node])
while len(queue) > 0:
node = queue.popleft()
tail.next = node
while node is not None:
tail = node
if node.child is not None:
queue.append(node.child)
node.child = None
node = node.next
return head.next
def main():
# Create the levels
one = Node.build([10, 5, 12, 7, 11])
two = [Node.build([4, 20, 13]), Node.build([17, 6])]
three = [Node.build([2]), Node.build([16]), Node.build([9, 8])]
four = [Node.build([3]), Node.build([19, 15])]
# Link the levels together
one.child = two[0]
one.get(3).child = two[1]
two[0].get(1).child = three[0]
two[0].get(2).child = three[1]
two[1].child = three[2]
three[1].child = four[0]
three[2].child = four[1]
# Create the expectation and ensure flatten works correctly
expect = Node.build([10, 5, 12, 7, 11, 4, 20, 13,
17, 6, 2, 16, 9, 8, 3, 19, 15])
assert flatten(one) == expect
if __name__ == '__main__':
main()
| mit |
shakuu/Homework | DesignPatterns/Workshop/FastAndFurious-AuthorSolution/FastAndFurious.ConsoleApplication/Engine/Contracts/IStrategyProvider.cs | 166 | namespace FastAndFurious.ConsoleApplication.Engine.Contracts
{
public interface IStrategyProvider
{
IStrategy GetStrategy(string command);
}
}
| mit |
RobertTheNerd/sc2geeks | web-api/website/service/src/main/java/api/sc2geeks/entity/ReplayWithRelatedInfo.java | 1544 | package api.sc2geeks.entity;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: robert
* Date: 5/3/12
* Time: 10:24 PM
* To change this template use File | Settings | File Templates.
*/
public class ReplayWithRelatedInfo
{
private Replay replay;
private List<Replay> replaysInSeries;
private List<Replay> replaysOnMap;
private List<Replay> replaysOfMatchup;
private List<Replay> replaysFromPlayer1;
private List<Replay> replaysFromPlayer2;
public Replay getReplay()
{
return replay;
}
public void setReplay(Replay replay)
{
this.replay = replay;
}
public List<Replay> getReplaysInSeries()
{
return replaysInSeries;
}
public void setReplaysInSeries(List<Replay> replaysInSeries)
{
this.replaysInSeries = replaysInSeries;
}
public List<Replay> getReplaysOnMap()
{
return replaysOnMap;
}
public void setReplaysOnMap(List<Replay> replaysOnMap)
{
this.replaysOnMap = replaysOnMap;
}
public List<Replay> getReplaysOfMatchup()
{
return replaysOfMatchup;
}
public void setReplaysOfMatchup(List<Replay> replaysOfMatchup)
{
this.replaysOfMatchup = replaysOfMatchup;
}
public List<Replay> getReplaysFromPlayer1()
{
return replaysFromPlayer1;
}
public void setReplaysFromPlayer1(List<Replay> replaysFromPlayer1)
{
this.replaysFromPlayer1 = replaysFromPlayer1;
}
public List<Replay> getReplaysFromPlayer2()
{
return replaysFromPlayer2;
}
public void setReplaysFromPlayer2(List<Replay> replaysFromPlayer2)
{
this.replaysFromPlayer2 = replaysFromPlayer2;
}
}
| mit |
raskolnikova/infomaps | node_modules/devextreme/data/local_store.js | 3384 | /**
* DevExtreme (data/local_store.js)
* Version: 16.2.6
* Build date: Tue Mar 28 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var $ = require("jquery"),
Class = require("../core/class"),
abstract = Class.abstract,
errors = require("./errors").errors,
ArrayStore = require("./array_store");
var LocalStoreBackend = Class.inherit({
ctor: function(store, storeOptions) {
this._store = store;
this._dirty = !!storeOptions.data;
this.save();
var immediate = this._immediate = storeOptions.immediate;
var flushInterval = Math.max(100, storeOptions.flushInterval || 1e4);
if (!immediate) {
var saveProxy = $.proxy(this.save, this);
setInterval(saveProxy, flushInterval);
$(window).on("beforeunload", saveProxy);
if (window.cordova) {
document.addEventListener("pause", saveProxy, false)
}
}
},
notifyChanged: function() {
this._dirty = true;
if (this._immediate) {
this.save()
}
},
load: function() {
this._store._array = this._loadImpl();
this._dirty = false
},
save: function() {
if (!this._dirty) {
return
}
this._saveImpl(this._store._array);
this._dirty = false
},
_loadImpl: abstract,
_saveImpl: abstract
});
var DomLocalStoreBackend = LocalStoreBackend.inherit({
ctor: function(store, storeOptions) {
var name = storeOptions.name;
if (!name) {
throw errors.Error("E4013")
}
this._key = "dx-data-localStore-" + name;
this.callBase(store, storeOptions)
},
_loadImpl: function() {
var raw = localStorage.getItem(this._key);
if (raw) {
return JSON.parse(raw)
}
return []
},
_saveImpl: function(array) {
if (!array.length) {
localStorage.removeItem(this._key)
} else {
localStorage.setItem(this._key, JSON.stringify(array))
}
}
});
var localStoreBackends = {
dom: DomLocalStoreBackend
};
var LocalStore = ArrayStore.inherit({
ctor: function(options) {
if ("string" === typeof options) {
options = {
name: options
}
} else {
options = options || {}
}
this.callBase(options);
this._backend = new localStoreBackends[options.backend || "dom"](this, options);
this._backend.load()
},
clear: function() {
this.callBase();
this._backend.notifyChanged()
},
_insertImpl: function(values) {
var b = this._backend;
return this.callBase(values).done($.proxy(b.notifyChanged, b))
},
_updateImpl: function(key, values) {
var b = this._backend;
return this.callBase(key, values).done($.proxy(b.notifyChanged, b))
},
_removeImpl: function(key) {
var b = this._backend;
return this.callBase(key).done($.proxy(b.notifyChanged, b))
}
}, "local");
module.exports = LocalStore;
module.exports.default = module.exports;
| mit |
monochromegane/dragon-imports | file_info.go | 606 | package dragon
import (
"io/ioutil"
"os"
"path/filepath"
)
type fileInfo struct {
path string
os.FileInfo
}
func (f fileInfo) isDir(follow bool) bool {
if follow && f.isSymlink() {
_, err := ioutil.ReadDir(filepath.Join(f.path, f.FileInfo.Name()))
return err == nil
}
return f.FileInfo.IsDir()
}
func (f fileInfo) isSymlink() bool {
return f.FileInfo.Mode()&os.ModeSymlink == os.ModeSymlink
}
func (f fileInfo) isNamedPipe() bool {
return f.FileInfo.Mode()&os.ModeNamedPipe == os.ModeNamedPipe
}
func newFileInfo(path string, info os.FileInfo) fileInfo {
return fileInfo{path, info}
}
| mit |
Prestaul/charting | dataset.js | 2687 | function Dataset(data, firstIndex, length) {
this.setData(data, firstIndex, length);
}
Dataset.prototype = {
setData: function(data, firstIndex, length) {
if(!(data instanceof Array && data.length >= 2))
throw new Error('Data provided to a Dataset must be of type Array and have a length of at least two.');
this.data = data;
this.firstIndex = 0;
this.length = this.data.length;
return this.reset(firstIndex, length);
},
reset: function(firstIndex, length) {
if(arguments.length >= 1) {
this.firstIndex = Math.min(Math.max(0, firstIndex^0), this.data.length - 2);
}
length = length^0 || this.length;
this.length = Math.min(Math.max(2, length), this.data.length - this.firstIndex);
this._cache = {};
return this;
},
cache: function(key, getter, args) {
return this._cache[key] || (this._cache[key] = getter.apply(this, args || []));
},
getValue: function(index, seriesName) {
return this.getSeries(seriesName)[index - this.firstIndex];
},
getLastIndex: function() {
return this.firstIndex + this.length - 1;
},
getSeries: function(seriesName) {
return this.cache(seriesName, function() {
return this.data
.slice(this.firstIndex, this.firstIndex + this.length)
.map(function(row) {
return (seriesName in row) ? row[seriesName] : null;
});
});
},
getMappedSeries: function(seriesName, key, mapper) {
return this.cache(seriesName + '~' + key, function() {
return this.getSeries(seriesName).map(mapper);
});
},
getNumericSeries: function(seriesName) {
return this.getMappedSeries(seriesName, 'numeric', function(value) {
return parseFloat(value, 10);
});
},
getIntegerSeries: function(seriesName) {
return this.getMappedSeries(seriesName, 'integers', function(value) {
return value.getTime ? value.getTime() : value ^ 0;
});
},
getMin: function(seriesName) {
return this.cache(seriesName + '~min', function() {
var min = Number.MAX_VALUE,
series = this.getNumericSeries(seriesName),
i = series.length;
while(i--) if(series[i] < min && !(isNaN || Number.isNaN)(series[i])) min = series[i];
return (min === Number.MAX_VALUE) ? 0 : min;
});
},
getMax: function(seriesName) {
return this.cache(seriesName + '~max', function() {
var max = Number.MIN_VALUE,
series = this.getNumericSeries(seriesName),
i = series.length;
while(i--) if(series[i] > max && !(isNaN || Number.isNaN)(series[i])) max = series[i];
return (max === Number.MIN_VALUE) ? 0 : max;
});
},
generateLoserSeries: function(seriesName) {
this.getMappedSeries(seriesName, 'losers', function(value) {
return -value;
});
return this;
}
};
module.exports = Dataset;
| mit |
fraguada/three.js | examples/js/shaders/NormalMapShader.js | 1293 | console.warn( "THREE.NormalMapShader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
/**
* Normal map shader
* - compute normals from heightmap
*/
THREE.NormalMapShader = {
uniforms: {
"heightMap": { value: null },
"resolution": { value: new THREE.Vector2( 512, 512 ) },
"scale": { value: new THREE.Vector2( 1, 1 ) },
"height": { value: 0.05 }
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
" vUv = uv;",
" gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform float height;",
"uniform vec2 resolution;",
"uniform sampler2D heightMap;",
"varying vec2 vUv;",
"void main() {",
" float val = texture2D( heightMap, vUv ).x;",
" float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x;",
" float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x;",
" gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 );",
"}"
].join( "\n" )
};
| mit |
rayneh/VS2017MG | thrift/ThriftExample/JavaClient.java | 2610 | /*
* This version of the Thrift Java Tutorial has been simplified by
* ronald.moore@h-da.de
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// Generated code
import simpleTutorial.*;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TSSLTransportFactory.TSSLTransportParameters;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
public class JavaClient {
public static void main(String [] args) {
try {
TTransport transport = new TSocket("localhost", 9090);
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
Calculator.Client client = new Calculator.Client(protocol);
perform(client);
transport.close();
} catch (TException x) {
x.printStackTrace();
}
}
private static void perform(Calculator.Client client) throws TException
{
// test the add method
int sum = client.add(1,1);
System.out.println("1+1=" + sum);
// Test the calculate method (which requires setup).
// First, test the exception...
Work work = new Work();
work.op = Operation.DIVIDE;
work.num1 = 1;
work.num2 = 0;
try {
int quotient = client.calculate(1, work);
System.out.println("Whoa we can divide by 0");
} catch (InvalidOperation io) {
System.out.println("Invalid operation: " + io.why);
}
// Then test "normal" operation
work.op = Operation.SUBTRACT;
work.num1 = 15;
work.num2 = 10;
try {
int diff = client.calculate(1, work);
System.out.println("15-10=" + diff);
} catch (InvalidOperation io) {
System.out.println("Invalid operation: " + io.why);
}
}
}
| mit |
LUI-3/website | app/smarty/sysplugins/smarty_internal_runtime_getincludepath.php | 5109 | <?php
/**
* Smarty read include path plugin
*
* @package Smarty
* @subpackage PluginsInternal
* @author Monte Ohrt
*/
/**
* Smarty Internal Read Include Path Class
*
* @package Smarty
* @subpackage PluginsInternal
*/
class Smarty_Internal_Runtime_GetIncludePath
{
/**
* include path cache
*
* @var string
*/
public $_include_path = '';
/**
* include path directory cache
*
* @var array
*/
public $_include_dirs = array();
/**
* include path directory cache
*
* @var array
*/
public $_user_dirs = array();
/**
* stream cache
*
* @var string[]
*/
public $isFile = array();
/**
* stream cache
*
* @var string[]
*/
public $isPath = array();
/**
* stream cache
*
* @var int[]
*/
public $number = array();
/**
* status cache
*
* @var bool
*/
public $_has_stream_include = null;
/**
* Number for array index
*
* @var int
*/
public $counter = 0;
/**
* Check if include path was updated
*
* @param \Smarty $smarty
*
* @return bool
*/
public function isNewIncludePath(Smarty $smarty)
{
$_i_path = get_include_path();
if ($this->_include_path != $_i_path) {
$this->_include_dirs = array();
$this->_include_path = $_i_path;
$_dirs = (array) explode(PATH_SEPARATOR, $_i_path);
foreach ($_dirs as $_path) {
if (is_dir($_path)) {
$this->_include_dirs[] = $smarty->_realpath($_path . DS, true);
}
}
return true;
}
return false;
}
/**
* return array with include path directories
*
* @param \Smarty $smarty
*
* @return array
*/
public function getIncludePathDirs(Smarty $smarty)
{
$this->isNewIncludePath($smarty);
return $this->_include_dirs;
}
/**
* Return full file path from PHP include_path
*
* @param string[] $dirs
* @param string $file
* @param \Smarty $smarty
*
* @return bool|string full filepath or false
*
*/
public function getIncludePath($dirs, $file, Smarty $smarty)
{
//if (!(isset($this->_has_stream_include) ? $this->_has_stream_include : $this->_has_stream_include = false)) {
if (!(isset($this->_has_stream_include) ? $this->_has_stream_include : $this->_has_stream_include = function_exists('stream_resolve_include_path'))) {
$this->isNewIncludePath($smarty);
}
// try PHP include_path
foreach ($dirs as $dir) {
$dir_n = isset($this->number[$dir]) ? $this->number[$dir] : $this->number[$dir] = $this->counter ++;
if (isset($this->isFile[$dir_n][$file])) {
if ($this->isFile[$dir_n][$file]) {
return $this->isFile[$dir_n][$file];
} else {
continue;
}
}
if (isset($this->_user_dirs[$dir_n])) {
if (false === $this->_user_dirs[$dir_n]) {
continue;
} else {
$dir = $this->_user_dirs[$dir_n];
}
} else {
if ($dir[0] == '/' || $dir[1] == ':') {
$dir = str_ireplace(getcwd(), '.', $dir);
if ($dir[0] == '/' || $dir[1] == ':') {
$this->_user_dirs[$dir_n] = false;
continue;
}
}
$dir = substr($dir, 2);
$this->_user_dirs[$dir_n] = $dir;
}
if ($this->_has_stream_include) {
$path = stream_resolve_include_path($dir . (isset($file) ? $file : ''));
if ($path) {
return $this->isFile[$dir_n][$file] = $path;
}
} else {
foreach ($this->_include_dirs as $key => $_i_path) {
$path = isset($this->isPath[$key][$dir_n]) ? $this->isPath[$key][$dir_n] : $this->isPath[$key][$dir_n] = is_dir($_dir_path = $_i_path .
$dir) ? $_dir_path : false;
if ($path === false) {
continue;
}
if (isset($file)) {
$_file = $this->isFile[$dir_n][$file] = (is_file($path . $file)) ? $path . $file : false;
if ($_file) {
return $_file;
}
} else {
// no file was given return directory path
return $path;
}
}
}
}
return false;
}
}
| mit |
dusenberrymw/Pine | test/test_pine.py | 5816 | #! /usr/bin/env python3
'''
Created on Sept 9, 2014
@author: dusenberrymw
'''
import math
import os
import sys
import unittest
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
# import pine.data
import pine.activation
import pine.network
import pine.trainer
import pine.util
# network.py
class TestNetwork(unittest.TestCase):
"""Testing for network.py"""
def setUp(self):
self.act_func = pine.activation.Logistic()
self.input_vector = [5,6,7]
self.neuron = pine.network.Neuron(3, self.act_func)
self.neuron.weights = [1,-2,3]
self.neuron.threshold = 4
local_output = sum([x*y for x,y in zip(self.input_vector, self.neuron.weights)]) + self.neuron.threshold
self.output = 1.0 / (1 + math.exp(-1.0*local_output)) #0.99999999999
self.layer = pine.network.Layer()
self.layer.neurons = [self.neuron, self.neuron]
def test_neuron_forward(self):
self.assertEqual(self.neuron.forward(self.input_vector), self.output)
def test_layer_forward(self):
self.assertEqual(self.layer.forward(self.input_vector),
[self.output, self.output])
def test_network_forward(self):
network = pine.network.Network()
network.layers.append(self.layer)
new_neuron = pine.network.Neuron(2,self.act_func)
new_neuron.weights = [1,-2]
new_neuron.threshold = 4
new_layer = pine.network.Layer()
new_layer.neurons = [self.neuron]
network.layers.append(new_layer)
local_output = sum([x*y for x,y in zip([self.output, self.output], self.neuron.weights)]) + self.neuron.threshold
out = [1.0 / (1 + math.exp(-1.0*local_output))]
self.assertEqual(network.forward(self.input_vector), out) #0.9525741275104728
def test_neuron_backward(self):
self.neuron.forward(self.input_vector)
self.neuron.output = 2
down_gradient = 3.2
chain_gradient = down_gradient * (2*(1-2))
weight_gradients = [chain_gradient*x for x in self.input_vector]
thresh_gradient = chain_gradient * 1
input_gradients = [chain_gradient*x for x in self.neuron.weights]
computed_gradients = self.neuron.backward(down_gradient)
self.assertEqual(self.neuron.weight_gradients, weight_gradients)
self.assertEqual(computed_gradients, input_gradients)
self.assertEqual(self.neuron.threshold_gradient, thresh_gradient)
def test_gradients(self):
layout = [3,5,2]
network = pine.util.create_network(layout, ['logistic']*2)
input_vector = [-2.3,3.1,-5.8]
target_output_vector = [0.4,1]
network.forward(input_vector)
cost_gradient_vec = network.cost_gradient(target_output_vector)
network.backward(cost_gradient_vec)
for layer in network.layers:
for neuron in layer.neurons:
# weight gradients check:
for i in range(len(neuron.weights)):
epsilon = 0.0001
old_theta = neuron.weights[i]
neuron.weights[i] = neuron.weights[i] + epsilon
network.forward(input_vector)
J1 = network.cost(target_output_vector)
neuron.weights[i] = old_theta - epsilon
network.forward(input_vector)
J2 = network.cost(target_output_vector)
estimated_gradient = (J1 - J2) / (2*epsilon)
diff = abs(neuron.weight_gradients[i] - estimated_gradient)
assert diff < 0.0001, "w difference: {}".format(diff)
# print("w difference: {}".format(diff))
# print("weight_gradient[i]: {}".format(neuron.weight_gradients[i]))
# print("estimated_gradient: {}".format(estimated_gradient))
neuron.weights[i] = old_theta
# threshold gradient check:
epsilon = 0.0001
old_theta = neuron.threshold
neuron.threshold = neuron.threshold + epsilon
network.forward(input_vector)
J1 = network.cost(target_output_vector)
neuron.threshold = old_theta - epsilon
network.forward(input_vector)
J2 = network.cost(target_output_vector)
estimated_gradient = (J1 - J2) / (2*epsilon)
diff = abs(neuron.threshold_gradient - estimated_gradient)
assert diff < 0.0001, "t difference: {}".format(diff)
# print("t difference: {}".format(diff))
neuron.threshold = old_theta
def test_reset_gradients(self):
network = pine.util.create_network([3,5,2], ['logistic']*2)
for layer in network.layers:
for neuron in layer.neurons:
for grad in neuron.weight_gradients:
self.assertEqual(grad, 0)
self.assertEqual(neuron.threshold_gradient, 0)
def tearDown(self):
pass
# util.py
class TestUtil(unittest.TestCase):
"""Testing for util"""
def setUp(self):
pass
def test_is_valid_function(self):
self.assertTrue(pine.util.is_valid_function("logistic"))
self.assertFalse(pine.util.is_valid_function("test"))
def tearDown(self):
pass
class TestActivation(unittest.TestCase):
"""Testing for activation"""
def setUp(self):
pass
def test_METHOD(self):
pass
def tearDown(self):
pass
class TestMODULE(unittest.TestCase):
"""Testing for MODULE"""
def setUp(self):
pass
def test_METHOD(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
| mit |
benny568/ClubWebsiteAppA2 | app/components/findUs.component.ts | 210 | /**
* Created by odalybr on 08/04/2016.
*/
import { Component } from 'angular2/core';
@Component({
templateUrl: '/app/htmltemplates/findUs.component.html'
})
export class FindUsComponent {
} | mit |
elliotchance/c2go | ast/label_stmt_test.go | 368 | package ast
import (
"testing"
)
func TestLabelStmt(t *testing.T) {
nodes := map[string]Node{
`0x7fe3ba82edb8 <line:18906:1, line:18907:22> 'end_getDigits'`: &LabelStmt{
Addr: 0x7fe3ba82edb8,
Pos: NewPositionFromString("line:18906:1, line:18907:22"),
Name: "end_getDigits",
ChildNodes: []Node{},
},
}
runNodeTests(t, nodes)
}
| mit |
Mulchman/DestinyRaidStatus | app/scripts/app.module.js | 245 | import angular from 'angular';
import { DrsAppModule } from './drsApp.module';
import { AppComponent } from './app.component';
export const AppModule = angular
.module('app', [
DrsAppModule
])
.component('app', AppComponent)
.name; | mit |
marko-js/marko | packages/translator-default/test/fixtures/attr-style/snapshots/html-expected.js | 1592 | import { t as _t } from "marko/src/runtime/html/index.js";
const _marko_componentType = "packages/translator-default/test/fixtures/attr-style/template.marko",
_marko_template = _t(_marko_componentType);
export default _marko_template;
import _marko_style_merge from "marko/src/runtime/helpers/style-value.js";
import _marko_attr from "marko/src/runtime/html/helpers/attr.js";
import _customTag from "./components/custom-tag.marko";
import _marko_tag from "marko/src/runtime/helpers/render-tag.js";
import _marko_dynamic_tag from "marko/src/runtime/helpers/dynamic-tag.js";
import _marko_renderer from "marko/src/runtime/components/renderer.js";
const _marko_component = {};
_marko_template._ = _marko_renderer(function (input, out, _componentDef, _component, state) {
out.w(`<div${_marko_attr("style", _marko_style_merge({
color: input.color
}))}></div>`);
out.w("<div style=width:100px;></div>");
out.w("<div style=\"color: green\"></div>");
_marko_tag(_customTag, {
"style": {
color: input.color
}
}, out, _componentDef, "3");
_marko_tag(_customTag, {
"style": {
width: 100
}
}, out, _componentDef, "4");
_marko_tag(_customTag, {
"style": "color: green"
}, out, _componentDef, "5");
_marko_dynamic_tag(out, input.test, () => ({
"style": {
color: "green"
},
"test": {
"style": {
color: "green"
},
"renderBody": out => {
out.w("Hello");
}
}
}), null, null, null, _componentDef, "6");
}, {
t: _marko_componentType,
i: true,
d: true
}, _marko_component); | mit |
rubygems/rubygems.org | app/controllers/notifiers_controller.rb | 1210 | class NotifiersController < ApplicationController
before_action :redirect_to_signin, unless: :signed_in?
def show
@ownerships = current_user.ownerships.by_indexed_gem_name
end
def update
to_enable_push, to_disable_push = notifier_options("push")
to_enable_owner, to_disable_owner = notifier_options("owner")
to_enable_ownership_request, to_disable_ownership_request = notifier_options("ownership_request")
current_user.transaction do
current_user.ownerships.update_push_notifier(to_enable_push, to_disable_push)
current_user.ownerships.update_owner_notifier(to_enable_owner, to_disable_owner)
current_user.ownerships.update_ownership_request_notifier(to_enable_ownership_request, to_disable_ownership_request)
Mailer.delay.notifiers_changed(current_user.id)
end
redirect_to notifier_path, notice: t(".update.success")
end
private
def notifier_params
params.require(:ownerships)
end
def notifier_options(param)
to_enable = []
to_disable = []
notifier_params.each do |ownership_id, notifier|
(notifier[param] == "off" ? to_disable : to_enable) << ownership_id.to_i
end
[to_enable, to_disable]
end
end
| mit |
picologic/project-dashboard | src/public/js/systemjs.config.js | 1751 | (function(global) {
var map = {
'app': 'app', // 'dist',
'@angular': 'node_modules/@angular',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs',
'shared': 'app/shared',
'dashboard': 'app/dashboard'
};
var barrels = [
'shared',
'shared/models',
'shared/services',
'dashboard',
'dashboard/project-filter',
'dashboard/task-list'
];
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
};
var ngPackageNames = [
'common',
'compiler',
'core',
'forms',
'http',
'platform-browser',
'platform-browser-dynamic',
'router',
'router-deprecated',
'upgrade'
];
function addBarrel(barrel) {
packages[barrel] = { main: 'index.js', defaultExtension: 'js' };
}
barrels.forEach(addBarrel);
function packIndex(pkgName) {
packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
}
function packUmd(pkgName) {
packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
}
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
ngPackageNames.forEach(setPackageConfig);
var config = {
map: map,
packages: packages
};
System.config(config);
})(this);
| mit |
AgentME/braincrunch | test/format.js | 8323 | /* @flow */
import assert from 'assert';
import {parse} from '../src/parse';
import {serialize} from '../src/serialize';
const ADD = 0, RIGHT = 1,
OUT = 2, IN = 3,
OPEN = 4, CLOSE = 5,
CLEAR = 6, MUL = 7,
SCAN_LEFT = 8, SCAN_RIGHT = 9;
describe('parse', function() {
describe('normal', function() {
it('add', function() {
assert.deepEqual(Array.from(parse('+++')), [{type: ADD, x: 3}]);
});
it('sub', function() {
assert.deepEqual(Array.from(parse('---')), [{type: ADD, x: -3}]);
});
it('right', function() {
assert.deepEqual(Array.from(parse('>>>')), [{type: RIGHT, x: 3}]);
});
it('left', function() {
assert.deepEqual(Array.from(parse('<<<')), [{type: RIGHT, x: -3}]);
});
it('in and out', function() {
assert.deepEqual(Array.from(parse('..,,,')), [
{type: OUT}, {type: OUT},
{type: IN}, {type: IN}, {type: IN}
]);
});
it('clear', function() {
assert.deepEqual(Array.from(parse('[-]')), [{type: CLEAR}]);
});
it('mul', function() {
assert.deepEqual(Array.from(parse('[-<++>>>+++<<]')), [
{type: MUL, x: -1, y: 2},
{type: MUL, x: 2, y: 3},
{type: CLEAR}
]);
});
it('clear after partial mul', function() {
assert.deepEqual(Array.from(parse('[<+>[-]-]')), [
{type: OPEN, pair: 6},
{type: RIGHT, x: -1},
{type: ADD, x: 1},
{type: RIGHT, x: 1},
{type: CLEAR},
{type: ADD, x: -1},
{type: CLOSE, pair: 0}
]);
});
it('backwards mul', function() {
assert.deepEqual(Array.from(parse('[<++>>>+++<<-]')), [
{type: MUL, x: -1, y: 2},
{type: MUL, x: 2, y: 3},
{type: CLEAR}
]);
});
it('improper mul', function() {
assert.deepEqual(Array.from(parse('[-<++>>>+++<<<]')), [
{type: OPEN, pair: 7}, {type: ADD, x: -1},
{type: RIGHT, x: -1}, {type: ADD, x: 2},
{type: RIGHT, x: 3}, {type: ADD, x: 3},
{type: RIGHT, x: -3}, {type: CLOSE, pair: 0}
]);
});
it("won't multiply with x = 0", function() {
assert.deepEqual(Array.from(parse('[-+++]')), [
{type: OPEN, pair: 2},
{type: ADD, x: 2},
{type: CLOSE, pair: 0}
]);
});
it('scan_left', function() {
assert.deepEqual(Array.from(parse('[<]')), [{type: SCAN_LEFT}]);
});
it('scan_left after partial scanner', function() {
assert.deepEqual(Array.from(parse('[[<]]')), [
{type: OPEN, pair: 2},
{type: SCAN_LEFT},
{type: CLOSE, pair: 0}
]);
});
it('scan_right', function() {
assert.deepEqual(Array.from(parse('[>]')), [{type: SCAN_RIGHT}]);
});
it('ignores enhanced syntax', function() {
assert.deepEqual(Array.from(parse('3>>.4<3:2*^')), [
{type: RIGHT, x: 2},
{type: OUT},
{type: RIGHT, x: -1}
]);
});
it('does not use // comments', function() {
assert.deepEqual(Array.from(parse('+//+\n+')), [
{type: ADD, x: 3}
]);
});
});
describe('enhanced', function() {
it('add', function() {
assert.deepEqual(Array.from(parse('3+', true)), [{type: ADD, x: 3}]);
});
it('add negative', function() {
assert.deepEqual(Array.from(parse('(3)+', true)), [{type: ADD, x: -3}]);
});
it('sub', function() {
assert.deepEqual(Array.from(parse('3-', true)), [{type: ADD, x: -3}]);
});
it('right', function() {
assert.deepEqual(Array.from(parse('3>', true)), [{type: RIGHT, x: 3}]);
});
it('right negative', function() {
assert.deepEqual(Array.from(parse('(3)>', true)), [{type: RIGHT, x: -3}]);
});
it('left', function() {
assert.deepEqual(Array.from(parse('3<', true)), [{type: RIGHT, x: -3}]);
});
it('in and out', function() {
assert.deepEqual(Array.from(parse('..,,,', true)), [
{type: OUT}, {type: OUT},
{type: IN}, {type: IN}, {type: IN}
]);
});
it('clear', function() {
assert.deepEqual(Array.from(parse('^', true)), [{type: CLEAR}]);
});
it('regular clear', function() {
assert.deepEqual(Array.from(parse('^[-]', true)), [
{type: CLEAR}, {type: CLEAR}
]);
});
it('mul', function() {
assert.deepEqual(Array.from(parse('(1):2*2:3*^', true)), [
{type: MUL, x: -1, y: 2},
{type: MUL, x: 2, y: 3},
{type: CLEAR}
]);
});
it("can't multiply with x = 0", function() {
assert.throws(() => {
parse('0:3*^', true);
});
});
it('many', function() {
assert.deepEqual(Array.from(parse('3>>.4<3:2*^', true)), [
{type: RIGHT, x: 4},
{type: OUT},
{type: RIGHT, x: -4},
{type: MUL, x: 3, y: 2}, {type: CLEAR}
]);
});
it('uses // comments', function() {
assert.deepEqual(Array.from(parse('+//+\n+', true)), [
{type: ADD, x: 2}
]);
});
});
});
describe('serialize', function() {
describe('normal', function() {
it('add', function() {
assert.strictEqual(serialize([{type: ADD, x: 3}]), '+++');
});
it('sub', function() {
assert.strictEqual(serialize([{type: ADD, x: -3}]), '---');
});
it('right', function() {
assert.strictEqual(serialize([{type: RIGHT, x: 3}]), '>>>');
});
it('left', function() {
assert.strictEqual(serialize([{type: RIGHT, x: -3}]), '<<<');
});
it('in and out', function() {
assert.strictEqual(serialize([
{type: OUT}, {type: OUT},
{type: IN}, {type: IN}, {type: IN}
]), '..,,,');
});
it('clear', function() {
assert.strictEqual(serialize([{type: CLEAR}]), '[-]');
});
it('mul', function() {
assert.strictEqual(serialize([
{type: MUL, x: -1, y: 2},
{type: MUL, x: 2, y: 3},
{type: CLEAR}
]), '[-<++>>>+++<<]');
});
it('improper mul', function() {
assert.throws(() => {
serialize([
{type: MUL, x: -1, y: 2},
{type: MUL, x: 2, y: 3},
{type: OUT}, {type: OUT},
{type: CLEAR}
]);
});
});
it('scan_left', function() {
assert.strictEqual(serialize([{type: SCAN_LEFT}]), '[<]');
});
it('scan_right', function() {
assert.strictEqual(serialize([{type: SCAN_RIGHT}]), '[>]');
});
});
describe('enhanced', function() {
it('single add', function() {
assert.strictEqual(serialize([{type: ADD, x: 1}], true), '+');
});
it('add', function() {
assert.strictEqual(serialize([{type: ADD, x: 3}], true), '3+');
});
it('single sub', function() {
assert.strictEqual(serialize([{type: ADD, x: -1}], true), '-');
});
it('sub', function() {
assert.strictEqual(serialize([{type: ADD, x: -3}], true), '3-');
});
it('single right', function() {
assert.strictEqual(serialize([{type: RIGHT, x: 1}], true), '>');
});
it('right', function() {
assert.strictEqual(serialize([{type: RIGHT, x: 3}], true), '3>');
});
it('single left', function() {
assert.strictEqual(serialize([{type: RIGHT, x: -1}], true), '<');
});
it('left', function() {
assert.strictEqual(serialize([{type: RIGHT, x: -3}], true), '3<');
});
it('in and out', function() {
assert.strictEqual(serialize([
{type: OUT}, {type: OUT},
{type: IN}, {type: IN}, {type: IN}
], true), '..,,,');
});
it('clear', function() {
assert.strictEqual(serialize([{type: CLEAR}], true), '^');
});
it('mul', function() {
assert.strictEqual(serialize([
{type: MUL, x: -1, y: 2},
{type: MUL, x: 2, y: 3},
{type: CLEAR}
], true), '(1):2*2:3*^');
});
it('improper mul', function() {
assert.throws(() => {
serialize([
{type: MUL, x: -1, y: 2},
{type: MUL, x: 2, y: 3},
{type: OUT}, {type: OUT},
{type: CLEAR}
], true);
});
});
it('scan_left', function() {
assert.strictEqual(serialize([{type: SCAN_LEFT}], true), '[<]');
});
it('scan_right', function() {
assert.strictEqual(serialize([{type: SCAN_RIGHT}], true), '[>]');
});
});
});
| mit |
sskre/bookshelf | fuel/app/views/book/_form.php | 2401 | <?php echo Form::open(array("class"=>"form-horizontal")); ?>
<fieldset>
<div class="form-group">
<?php echo Form::label('Title', 'title', array('class'=>'control-label')); ?>
<?php echo Form::input('title', Input::post('title', isset($book) ? $book->title : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Title')); ?>
</div>
<div class="form-group">
<?php echo Form::label('Isbn10', 'isbn10', array('class'=>'control-label')); ?>
<?php echo Form::input('isbn10', Input::post('isbn10', isset($book) ? $book->isbn10 : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Isbn10')); ?>
</div>
<div class="form-group">
<?php echo Form::label('Isbn13', 'isbn13', array('class'=>'control-label')); ?>
<?php echo Form::input('isbn13', Input::post('isbn13', isset($book) ? $book->isbn13 : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Isbn13')); ?>
</div>
<div class="form-group">
<?php echo Form::label('Publisher id', 'publisher_id', array('class'=>'control-label')); ?>
<?php echo Form::input('publisher_id', Input::post('publisher_id', isset($book) ? $book->publisher_id : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Publisher id')); ?>
</div>
<div class="form-group">
<?php echo Form::label('Released at', 'released_at', array('class'=>'control-label')); ?>
<?php echo Form::input('released_at', Input::post('released_at', isset($book) ? $book->released_at : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Released at')); ?>
</div>
<div class="form-group">
<?php echo Form::label('Owner user id', 'owner_user_id', array('class'=>'control-label')); ?>
<?php echo Form::input('owner_user_id', Input::post('owner_user_id', isset($book) ? $book->owner_user_id : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Owner user id')); ?>
</div>
<div class="form-group">
<?php echo Form::label('Status', 'status', array('class'=>'control-label')); ?>
<?php echo Form::input('status', Input::post('status', isset($book) ? $book->status : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Status')); ?>
</div>
<div class="form-group">
<label class='control-label'> </label>
<?php echo Form::submit('submit', 'Save', array('class' => 'btn btn-primary')); ?> </div>
</fieldset>
<?php echo Form::close(); ?> | mit |
robotex82/acts_as_time_versioned | spec/models/address_type_spec.rb | 130 | require 'spec_helper'
describe AddressType do
context 'validations' do
it { should validate_presence_of :name }
end
end
| mit |
alkammar/morkim | mfw/src/main/java/lib/morkim/mfw/repo/Filter.java | 412 | package lib.morkim.mfw.repo;
import java.util.HashMap;
import java.util.Set;
public abstract class Filter {
private HashMap<String, Object> map;
public Filter() {
map = new HashMap<String, Object>();
}
public void set(String key, Object value) {
map.put(key, value);
}
public Set<String> getKeys() {
return map.keySet();
}
public Object getValue(String key) {
return map.get(key);
}
} | mit |
KissKissBankBank/kitten | assets/javascripts/kitten/components/layout/grid/stories.js | 3792 | import React from 'react'
import { Grid, GridCol } from './index'
import { DocsPage } from 'storybook/docs-page'
export default {
title: 'Layout/Grid',
component: Grid,
decorators: [story => <div className="story-Container">{story()}</div>],
parameters: {
docs: {
page: () => (
<DocsPage filepath={__filename} importString="Grid, GridCol" />
),
},
},
}
const blockClasses = 'k-u-align-center has-overrides color-background'
export const Default = () => (
<>
<Grid className="k-u-margin-top-double">
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
</Grid>
<Grid className="k-u-margin-top-double">
<GridCol col="6">
<Grid>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
<GridCol col="1">
<div className={blockClasses}>col="1"</div>
</GridCol>
</Grid>
</GridCol>
<GridCol col="6">
<div className={blockClasses}>col="6"</div>
</GridCol>
</Grid>
<Grid className="k-u-margin-top-double">
<GridCol col-s="2">
<div className={blockClasses}>col-s="2"</div>
</GridCol>
<GridCol col-s="4">
<div className={blockClasses}>col-s="4"</div>
</GridCol>
<GridCol col-s="6">
<div className={blockClasses}>col-s="6"</div>
</GridCol>
</Grid>
<Grid className="k-u-margin-top-double">
<GridCol col-l="6">
<div className={blockClasses}>col-l="6"</div>
</GridCol>
<GridCol col-l="4" offset-l="2">
<div className={blockClasses}>col-l="4" offset-l="2"</div>
</GridCol>
</Grid>
</>
)
| mit |
mkzero/d3coder | js/menu_ui.js | 5523 | /**
* Localize the settings page
* curtesy of https://stackoverflow.com/a/25612056
*/
let localizeHtmlPage = function(){
let elems = document.getElementsByTagName('html');
for (let j = 0; j < elems.length; j++) {
let obj = elems[j];
let valStrH = obj.innerHTML.toString();
let valNewH = valStrH.replace(/__MSG_(\w+)__/g, function(match, v1) {
return v1 ? chrome.i18n.getMessage(v1) : "";
});
if(valNewH != valStrH)
{
obj.innerHTML = valNewH;
}
}
}();
var D3menu = {
/**
* Version number
*
* @var String
*/
version: "4.0.0",
/**
* list all functions. Needed to upgrade from older versions
* @var Array
*/
checkboxes: Array("functions_rot13",
"functions_timestamp",
"functions_crc32",
"functions_bin2hex",
"functions_bin2txt",
"functions_txt2hex",
"functions_hex2txt",
"functions_html_entity_decode",
"functions_htmlentities",
"functions_htmlspecialchars",
"functions_htmlspecialchars_decode",
"functions_uri_encode",
"functions_uri_decode",
"functions_md5",
"functions_sha1",
"functions_quoted_printable_decode",
"functions_quoted_printable_encode",
"functions_escapeshellarg",
"functions_base64_encode",
"functions_base64_decode",
"functions_unserialize",
"functions_leet_decode",
"functions_leet_encode",
"functions_reverse")
}
function upgrade() {
var clipboardSave, checkboxes = {}, version = D3menu.version;
chrome.storage.sync.get({version: false}, function(items) {
if (items.version) {
console.log("Upgrade: D3coder version " + version + " found.");
return;
}
console.log("Upgrade: New install or upgrade, checking local storage");
if (localStorage.getItem('message_type')) {
console.log("Upgrade: Found data in localStorage, starting upgrade");
clipboardSave = localStorage.getItem("message_automatic_clipboardcopy") == 1 ? true : false;
messageType = localStorage.getItem("message_type") ? localStorage.getItem("message_type") : "inplace";
// Fix for #25 when upgrading from an earlier version and having
// notifications set as message type
if(messageType == "notification") messageType = "inplace";
for (option of D3menu.checkboxes) {
checkboxes[option] = localStorage.getItem(option) == 1 ? true : false;
}
chrome.storage.sync.set(
{
checkboxes: checkboxes,
clipboardSave: clipboardSave,
messageType: messageType,
version: version
}, function(){
console.log("Upgrade: Saved converted values");
restore_options();
});
} else {
console.log("Upgrade: Couldn't find any values in localStorage");
}
});
}
function save_options() {
var checkboxes = {},
messageType = document.getElementById('message_type').value,
clipboardSave = document.getElementById("message_automatic_clipboardcopy").checked == true ? true : false;
for (option of document.querySelectorAll("input[id^='functions_'")) {
checkboxes[option.id] = document.getElementById(option.id).checked == true ? true : false;
}
chrome.storage.sync.set(
{
checkboxes: checkboxes,
messageType: messageType,
clipboardSave: clipboardSave,
version: D3menu.version
}, function() {
console.log("Save: Options saved to storage");
var status = document.getElementById('status');
status.textContent = chrome.i18n.getMessage('options_saved');
status.style.display = "block";
status.style.opacity = 1;
setTimeout(function() {
status.style.opacity = 0;
status.style.display = "block";
}, 2000);
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
console.log("Restore: Starting restore");
chrome.storage.sync.get({
checkboxes: [],
messageType: 'message',
clipboardSave: false,
version: 0
}, function(items) {
console.log("Restore: Loaded these items:");
console.log("Restore: Checkboxes", items.checkboxes);
console.log("Restore: Message Type", items.messageType);
console.log("Restore: Clipboard save", items.clipboardSave);
console.log("Restore: Version", items.version);
if (!items.version) {
console.log("No version found during startup, running upgrade");
upgrade();
} else {
document.getElementById("message_automatic_clipboardcopy").checked = items.clipboardSave;
document.getElementById("message_type").value = items.messageType;
for (checkbox in items.checkboxes) {
document.getElementById(checkbox).checked = items.checkboxes[checkbox];
}
}
});
}
document.addEventListener('DOMContentLoaded', restore_options);
for (tag of document.querySelectorAll("input, select")) {
tag.addEventListener('change', save_options);
} | mit |
leonjza/go-observe | cmd/submit.go | 1906 | package cmd
import (
"fmt"
"github.com/leonjza/go-observe/observatory"
"github.com/leonjza/go-observe/utils"
"github.com/spf13/cobra"
)
// variables for flags
var (
noHidden bool
forceRescan bool
)
// submitCmd represents the submit command
var submitCmd = &cobra.Command{
Use: "submit [url / hostname to submit]",
Short: "Submit a URL / Hostname to the Observatory for analysis",
Long: `Submits a URL or a Hostname to the Observatory for analysis.
If a URL / Hostname has previously been submitted to the Observatory,
then the API will respond with a "FINISHED". A rescan can be forced with
the --rescan flag.
Examples:
go-observe submit https://duckduckgo.com
go-observe submit duckduckgo.com --rescan
go-observe submit duckduckgo.com --rescan -n`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) <= 0 {
fmt.Println("Must provide a URL / Hostname to submit")
return
}
// validate the url/host
target, err := utils.ValidateAndGetURLHost(args[0])
if err != nil {
fmt.Printf("Failed to parse url/host with error: %s\n", err)
return
}
// Submit the analysis
response, err := observatory.SubmitObservatoryAnalysis(target, noHidden, forceRescan)
if err != nil {
fmt.Printf("Failed to send host for analysis for error: %s\n", err)
return
}
// check the response
if response.State == "FINISHED" {
fmt.Printf("Scan has already been finished on %s.\n", response.EndTime)
fmt.Printf("Use `go-observe results %s` to get scan results.\n", target)
} else {
fmt.Printf("Scan has been submitted and now has status: %s\n", response.State)
}
},
}
func init() {
RootCmd.AddCommand(submitCmd)
submitCmd.Flags().BoolVarP(&forceRescan, "rescan", "r", false, "Force a rescan from the Observatory")
submitCmd.Flags().BoolVarP(&noHidden, "no-hide", "n", false, "Remove the flag that hides scan results from the Observatory")
}
| mit |
nucleus-angular/form | equals-directive.js | 882 | /**
* Form validator for equals
*
* @module nag.form.validate.equals
* @ngdirective nagValidateEquals
*/
angular.module('nag.form.validate.equals', [])
.directive('nagValidateEquals', [
function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attributes, controller) {
var validate = function(value) {
if(dataValidation.validate('match', value, attributes.nagValidateEquals) === true) {
controller.$setValidity('nagEquals', true);
} else {
controller.$setValidity('nagEquals', false);
}
return value;
};
controller.$formatters.push(validate);
controller.$parsers.unshift(validate);
attributes.$observe('nagValidateEquals', function() {
validate(controller.$modelValue);
});
}
};
}
]);
| mit |
sopanhavuth-aka-sam/cecs343-project | GUI/src/Card9.java | 1261 | import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* Card Description:
* Finding the Lab
* Play in Elevators (16)
* Success: Get 1 Integrity pts
* Fail: nothing
* @author sam
*
*/
public class Card9 extends Card{
//constructor
public Card9() {
name = "Finding the Lab";
//no point requirement
checkReqPts = false;
//Play in Elevators (16)
checkReqLoc = true;
reqLocation.add(16);
//initialize image
try {
img = ImageIO.read(new File("img/card9.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
/*@Override
public Player play(Player player) {
//boolean flag identifying if the play successes or fail
boolean result = false;
//points and location validation: this determine if the play is successes
//or fail
if(checkReqPts) {
result = validatePts(player);
}
if(checkReqLoc) {
result = validateLoc(player);
}
//calling win() or fail() method base on "result"
if(result) {
return win(player);
}
else {
return fail(player);
}
}*/
@Override
public Player win(Player player) {
player.updateIntegrityPts(1);
return player;
}
@Override
//Fail: Nothing happen
public Player fail(Player player) {
return player;
}
} | mit |
srizzo/gm-google-map | src/js/directives/module.js | 12062 | angular.module('gm-google-map', [])
/**
* @description
*
* Shared map context. Publishes $scope.$setMap(map) and $scope.$getMap().
*
*/
.directive('gmMapContext', function() {
return {
scope: true,
restrict: 'EA',
controller: ["$scope", function ($scope) {
var _map;
$scope.$setMap = function (map) {
_map = map
}
$scope.$getMap = function () {
return _map
}
}]
}
})
/**
* @description
*
* Map Canvas. Publishes $scope.$setMap(map) and $scope.$getMap().
*
*/
.directive('gmMapCanvas', function() {
return {
scope: true,
restrict: 'EA',
require: '^?gmMapContext',
link: {
pre: function (scope, element, attrs) {
var disableDefaultUI = false
var styles = [
{
featureType: 'poi',
elementType: 'all',
stylers: [{ visibility: 'off' }]
}
]
if (attrs.disableDefaultUi)
disableDefaultUI = scope.$eval(attrs.disableDefaultUi)
if (attrs.styles)
styles = scope.$eval(attrs.styles)
var _map = new google.maps.Map(element[0], {
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: disableDefaultUI,
styles: styles
})
if (!scope.$setMap) {
scope.$setMap = function (map) {
_map = map
}
scope.$getMap = function () {
return _map
}
}
scope.$setMap(_map)
if (attrs.zoom) {
scope.$watch(attrs.zoom, function(current) {
_map.setZoom(current)
})
}
if (attrs.center) {
scope.$watch(attrs.center, function(current) {
if (current == null) {
return
}
_map.setCenter(new google.maps.LatLng(current.lat, current.lng))
}, true)
}
scope.safeApply = function(fn) {
var phase = scope.$root.$$phase
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn()
}
} else {
scope.$apply(fn)
}
}
angular.forEach(scope.$eval(attrs.listeners), function (listener, key) {
google.maps.event.addListener(_map, key, function () {
scope.safeApply(function () {
listener()
})
})
})
angular.forEach(scope.$eval(attrs.listenersOnce), function (listener, key) {
google.maps.event.addListenerOnce(_map, key, function () {
scope.safeApply(function () {
listener()
})
})
})
}
}
}
})
/**
* @description
*
* The sole purpose of the gmAddOns directive is to group gm-* directives / dom elements into a hidden element, preventing them from being displayed outside the map canvas
*
*/
.directive('gmAddOns', function() {
return {
scope: true,
restrict: 'EA',
compile: function (element) {
element.css("display", "none")
}
}
})
.directive('gmControl', function() {
return {
scope: true,
compile: function(element, attrs) {
if (typeof attrs.visible === 'undefined')
attrs.visible = "true"
return {
pre: function(scope, element, attrs) {
var domElement = element[0]
var map = scope.$getMap()
var position = attrs.position || "LEFT_TOP"
scope.$hide = function() {
var index = map.controls[google.maps.ControlPosition[position]].indexOf(domElement)
if (index > -1)
map.controls[google.maps.ControlPosition[position]].removeAt(index)
}
scope.$show = function() {
var index = map.controls[google.maps.ControlPosition[position]].indexOf(domElement)
if (index < 0)
map.controls[google.maps.ControlPosition[position]].push(domElement)
}
if (attrs.visible) {
scope.$watch(attrs.visible, function(current) {
if (current === true)
scope.$show()
else
scope.$hide()
})
}
}
}
}
}
})
/**
* @description
*
* InfoWindow. Expects $scope.$getMap() and $scope.$getMarker() to be available. Publishes $scope.$openInfoWindow() and $scope.$closeInfoWindow().
*
*/
.directive('gmInfoWindow', function() {
return {
scope: true,
compile: function() {
return {
pre: function(scope, element, attrs) {
var domElement = element[0]
var infoWindow = new google.maps.InfoWindow()
infoWindow.setContent(domElement)
if (attrs.closeclick) {
infoWindow.addListener('closeclick', function() {
scope.$apply(function() {
scope.$eval(attrs.closeclick)
})
})
}
scope.$openInfoWindow = function() {
infoWindow.open(scope.$getMap(), scope.$getMarker())
}
scope.$closeInfoWindow = function() {
infoWindow.close()
}
}
}
}
}
})
/**
* @description
*
* Overlapping Marker Spiderfier. Expects $scope.$getMap() to be available. Publishes $scope.$getOverlappingMarkerSpiderfier(). Triggers gm_oms_click google maps event when a marker is clicked.
*
* Requires https://cdn.rawgit.com/srizzo/OverlappingMarkerSpiderfier/0.3.3/dist/oms.min.js
*
*/
.directive('gmOverlappingMarkerSpiderfier', function() {
return {
restrict: 'AE',
scope: true,
compile: function () {
return {
pre: function(scope, element) {
element.css("display", "none")
var oms = new OverlappingMarkerSpiderfier(scope.$getMap(), {
keepSpiderfied: true
})
scope.$getOverlappingMarkerSpiderfier = function () {
return oms
}
scope.$on("gm_marker_created", function (event, marker) {
oms.addMarker(marker)
})
scope.$on("gm_marker_destroyed", function (event, marker) {
oms.removeMarker(marker)
})
oms.addListener('click', function(marker, event) {
scope.$apply(function() {
google.maps.event.trigger(marker, "gm_oms_click", event)
})
})
}
}
}
}
})
/**
* @description
*
* Marker. Expects $scope.$getMap() to be available. Publishes $scope.$getMarker(). Emits gm_marker_created and gm_marker_destroyed angularjs events.
*
*/
.directive('gmMarker', function() {
return {
restrict: 'AE',
scope: true,
compile: function() {
return {
pre: function(scope, element, attrs) {
var marker = new google.maps.Marker({
map: scope.$getMap(),
data: scope.$eval(attrs.data),
title: scope.$eval(attrs.title),
optimized: scope.$eval(attrs.optimized),
position: new google.maps.LatLng(scope.$eval(attrs.position).lat, scope.$eval(attrs.position).lng)
})
scope.$getMarker = function () {
return marker
}
if (attrs.position) {
var unbindPositionWatch = scope.$watch(attrs.position, function(current) {
marker.setPosition(new google.maps.LatLng(current.lat, current.lng))
})
}
if (attrs.icon) {
var unbindIconWatch = scope.$watch(attrs.icon, function(current) {
marker.setIcon(current)
})
}
scope.$emit("gm_marker_created", marker)
scope.$on("$destroy", function() {
unbindPositionWatch()
unbindIconWatch()
marker.setMap(null)
scope.$emit("gm_marker_destroyed", marker)
})
scope.safeApply = function(fn) {
var phase = scope.$root.$$phase
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn()
}
} else {
scope.$apply(fn)
}
}
angular.forEach(scope.$eval(attrs.listeners), function (listener, key) {
google.maps.event.addListener(marker, key, function () {
scope.safeApply(function () {
listener()
})
})
})
angular.forEach(scope.$eval(attrs.listenersOnce), function (listener, key) {
google.maps.event.addListenerOnce(marker, key, function () {
scope.safeApply(function () {
listener()
})
})
})
}
}
}
}
})
/**
* @description
*
* Polyline. Expects $scope.$getMap() to be available. Publishes $scope.$getPolyline(). Emits gm_polyline_created and gm_polyline_destroyed angularjs events.
*
*/
.directive('gmPolyline', function() {
return {
restrict: 'AE',
scope: true,
compile: function() {
return {
pre: function(scope, element, attrs) {
var polyline = new google.maps.Polyline({
map: scope.$getMap(),
data: scope.$eval(attrs.data),
path: scope.$eval(attrs.path),
geodesic: scope.$eval(attrs.geodesic),
strokeColor: scope.$eval(attrs.strokeColor),
strokeOpacity: scope.$eval(attrs.strokeOpacity),
strokeWeight: scope.$eval(attrs.strokeWeight)
})
scope.$getPolyline = function () {
return polyline
}
if (attrs.icon) {
var unbindIconWatch = scope.$watch(attrs.icon, function(current) {
polyline.setIcon(current)
})
}
scope.$emit("gm_polyline_created", polyline)
scope.$on("$destroy", function() {
unbindIconWatch()
polyline.setMap(null)
scope.$emit("gm_polyline_destroyed", polyline)
})
scope.safeApply = function(fn) {
var phase = scope.$root.$$phase
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn()
}
} else {
scope.$apply(fn)
}
}
angular.forEach(scope.$eval(attrs.listeners), function (listener, key) {
google.maps.event.addListener(polyline, key, function () {
scope.safeApply(function () {
listener()
})
})
})
angular.forEach(scope.$eval(attrs.listenersOnce), function (listener, key) {
google.maps.event.addListenerOnce(polyline, key, function () {
scope.safeApply(function () {
listener()
})
})
})
}
}
}
}
})
/**
* @description
*
* Adds listeners to google maps objects.
*
*/
.directive('gmAddListeners', function() {
return {
scope: true,
restrict: 'EA',
link: {
pre: function (scope, element, attrs) {
scope.safeApply = function(fn) {
var phase = scope.$root.$$phase
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn()
}
} else {
scope.$apply(fn)
}
}
var to = scope.$eval(attrs.to)
angular.forEach(scope.$eval(attrs.listeners), function (callback, key) {
google.maps.event.addListener(to, key, function () {
scope.safeApply(function () {
scope.$eval(callback)
})
})
})
angular.forEach(scope.$eval(attrs.listenersOnce), function (callback, key) {
google.maps.event.addListenerOnce(to, key, function () {
scope.safeApply(function () {
scope.$eval(callback)
})
})
})
}
}
}
})
| mit |
hyeonil/awesome-string | test/case/lower_case.js | 882 | import as from '../awesome-string';
import { expect } from 'chai';
describe('lowerCase', function() {
it('should return the lower case of a string', function() {
expect(as.lowerCase('Saturn')).to.be.equal('saturn');
expect(as.lowerCase('EARTH')).to.be.equal('earth');
expect(as.lowerCase('456')).to.be.equal('456');
expect(as.lowerCase('')).to.be.equal('');
});
it('should return the lower case of a string representation of an object', function() {
expect(as.lowerCase(['Venus'])).to.be.equal('venus');
expect(as.lowerCase({
toString: function() {
return 'Venus';
}
})).to.be.equal('venus');
});
it('should return empty string for null or undefined', function() {
expect(as.lowerCase()).to.be.equal('');
expect(as.lowerCase(undefined)).to.be.equal('');
expect(as.lowerCase(null)).to.be.equal('');
});
}); | mit |
orocrm/platform | src/Oro/Bundle/LocaleBundle/Tests/Unit/Form/Type/Stub/LocalizedFallbackValueCollectionTypeStub.php | 1305 | <?php
namespace Oro\Bundle\LocaleBundle\Tests\Unit\Form\Type\Stub;
use Oro\Bundle\LocaleBundle\Form\Type\LocalizedFallbackValueCollectionType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class LocalizedFallbackValueCollectionTypeStub extends AbstractType
{
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return LocalizedFallbackValueCollectionType::NAME;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'field' => 'string',
'entry_type' => TextType::class,
'entry_options' => [],
'allow_add' => true,
'allow_delete' => true,
'use_tabs' => false,
]);
$resolver->setNormalizer('entry_type', function () {
return LocalizedFallbackValueTypeStub::class;
});
$resolver->setNormalizer('entry_options', function () {
return [];
});
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return CollectionType::class;
}
}
| mit |
orocrm/platform | src/Oro/Bundle/UIBundle/Tests/Unit/Provider/ControllerClassProviderTest.php | 17122 | <?php
namespace Oro\Bundle\UIBundle\Tests\Unit\Provider;
use Oro\Bundle\UIBundle\Provider\ControllerClassProvider;
use Oro\Bundle\UIBundle\Tests\Unit\Fixture\Controller\SomeController;
use Oro\Bundle\UIBundle\Tests\Unit\Fixture\Controller\TestController;
use Oro\Bundle\UIBundle\Tests\Unit\Fixture\Controller\TestInvokeController;
use Oro\Component\Config\Cache\PhpConfigCacheAccessor;
use Oro\Component\Testing\TempDirExtension;
use ProxyManager\Proxy\VirtualProxyInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\Config\Resource\ReflectionClassResource;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RouterInterface;
class ControllerClassProviderTest extends \PHPUnit\Framework\TestCase
{
use TempDirExtension;
/** @var RouteCollection */
private $routeCollection;
/** @var KernelInterface|\PHPUnit\Framework\MockObject\MockObject */
private $kernel;
/** @var ContainerInterface|\PHPUnit\Framework\MockObject\MockObject */
private $container;
/** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
private $logger;
/** @var ControllerClassProvider */
private $controllerClassProvider;
/** @var string */
private $cacheFile;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->cacheFile = $this->getTempFile('ControllerClassProvider');
$this->routeCollection = new RouteCollection();
$this->kernel = $this->createMock(KernelInterface::class);
$this->container = $this->createMock(ContainerInterface::class);
$this->logger = $this->createMock(LoggerInterface::class);
$router = $this->createMock(RouterInterface::class);
$router->expects(self::any())
->method('getRouteCollection')
->willReturn($this->routeCollection);
$this->controllerClassProvider = new ControllerClassProvider(
$this->cacheFile,
true,
$router,
new ControllerNameParser($this->kernel),
$this->container,
$this->logger
);
}
/**
* @return BundleInterface
*/
private function getBundle(): BundleInterface
{
/** @var BundleInterface|\PHPUnit\Framework\MockObject\MockObject $bundle */
$bundle = $this->createMock(BundleInterface::class);
$bundle->expects(self::any())
->method('getNamespace')
->willReturn('Oro\Bundle\UIBundle\Tests\Unit\Fixture');
$bundle->expects(self::any())
->method('getName')
->willReturn('Acme');
return $bundle;
}
public function testGetControllers()
{
$this->routeCollection->add(
'route1',
new Route('route1', ['_controller' => TestController::class . '::someAction'])
);
$this->routeCollection->add(
'route2',
new Route('route2', ['_controller' => TestController::class . '::anotherAction'])
);
$this->routeCollection->add(
'route3',
new Route('route3', ['_controller' => SomeController::class . '::someAction'])
);
$this->routeCollection->add(
'route4',
new Route('route4', ['_controller' => 'some_controller.service_definition::anotherAction'])
);
$expectedControllers = [
'route1' => [TestController::class, 'someAction'],
'route2' => [TestController::class, 'anotherAction'],
'route3' => [SomeController::class, 'someAction'],
'route4' => [SomeController::class, 'anotherAction'],
];
$this->container->expects(self::once())
->method('has')
->with('some_controller.service_definition')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('some_controller.service_definition')
->willReturn(new SomeController());
$this->logger->expects(self::never())
->method('error');
self::assertSame(
$expectedControllers,
$this->controllerClassProvider->getControllers()
);
$dataAccessor = new PhpConfigCacheAccessor();
self::assertSame(
$expectedControllers,
$dataAccessor->load(new ConfigCache($this->cacheFile, false))
);
$meta = unserialize(file_get_contents($this->cacheFile . '.meta'));
self::assertCount(2, $meta);
self::assertInstanceOf(ReflectionClassResource::class, $meta[0]);
self::assertInstanceOf(ReflectionClassResource::class, $meta[1]);
}
public function testLoadForRouteWithoutController()
{
$this->routeCollection->add(
'test_route',
new Route('test')
);
$this->container->expects(self::never())
->method('has');
$this->logger->expects(self::never())
->method('error');
self::assertSame(
[],
$this->controllerClassProvider->getControllers()
);
}
public function testLoadForRouteWithNotSupportedController()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 123])
);
$this->container->expects(self::never())
->method('has');
$this->logger->expects(self::never())
->method('error');
self::assertSame(
[],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "class::method"
*/
public function testLoadClassMethod()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => TestController::class . '::someAction'])
);
$this->container->expects(self::never())
->method('has');
$this->logger->expects(self::never())
->method('error');
self::assertSame(
['test_route' => [TestController::class, 'someAction']],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "bundle:controller:action"
*/
public function testLoadBundleControllerAction()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'Acme:Test:some'])
);
$this->kernel->expects(self::once())
->method('getBundle')
->with('Acme')
->willReturn($this->getBundle());
$this->container->expects(self::never())
->method('has');
$this->logger->expects(self::never())
->method('error');
self::assertSame(
['test_route' => [TestController::class, 'someAction']],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "bundle:controller:action", but that cannot be parsed
*/
public function testLoadBundleControllerActionWithError()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'Acme:Undefined:some'])
);
$this->kernel->expects(self::once())
->method('getBundle')
->with('Acme')
->willReturn($this->getBundle());
$this->container->expects(self::never())
->method('has');
$this->logger->expects(self::once())
->method('error')
->willReturnCallback(function ($message, $context) {
self::assertEquals('Cannot extract controller for "test_route" route.', $message);
self::assertInstanceOf(\InvalidArgumentException::class, $context['exception']);
});
self::assertSame(
[],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "service:method"
*/
public function testLoadControllerAsService()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'test_controller:someAction'])
);
$this->container->expects(self::once())
->method('has')
->with('test_controller')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('test_controller')
->willReturn(new TestController());
$this->logger->expects(self::never())
->method('error');
self::assertSame(
['test_route' => [TestController::class, 'someAction']],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "service:method" and the controller service is lazy (initialized)
*/
public function testLoadControllerAsInitializedLazyService()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'test_controller:someAction'])
);
$service = $this->createMock(VirtualProxyInterface::class);
$service->expects(self::once())
->method('isProxyInitialized')
->willReturn(true);
$service->expects(self::never())
->method('initializeProxy');
$service->expects(self::once())
->method('getWrappedValueHolderValue')
->willReturn(new TestController());
$this->container->expects(self::once())
->method('has')
->with('test_controller')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('test_controller')
->willReturn($service);
$this->logger->expects(self::never())
->method('error');
self::assertSame(
['test_route' => [TestController::class, 'someAction']],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "service:method" and the controller service is lazy (not initialized)
*/
public function testLoadControllerAsNotInitializedLazyService()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'test_controller:someAction'])
);
$service = $this->createMock(VirtualProxyInterface::class);
$service->expects(self::once())
->method('isProxyInitialized')
->willReturn(false);
$service->expects(self::once())
->method('initializeProxy');
$service->expects(self::once())
->method('getWrappedValueHolderValue')
->willReturn(new TestController());
$this->container->expects(self::once())
->method('has')
->with('test_controller')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('test_controller')
->willReturn($service);
$this->logger->expects(self::never())
->method('error');
self::assertSame(
['test_route' => [TestController::class, 'someAction']],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "service:method" when service does not exist
*/
public function testLoadControllerAsServiceWhenServiceDoesNotExist()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'test_controller:someAction'])
);
$this->container->expects(self::once())
->method('has')
->with('test_controller')
->willReturn(false);
$this->logger->expects(self::once())
->method('error')
->willReturnCallback(function ($message, $context) {
self::assertEquals('Cannot extract controller for "test_route" route.', $message);
/** @var \InvalidArgumentException $exception */
$exception = $context['exception'];
self::assertInstanceOf(\InvalidArgumentException::class, $exception);
self::assertEquals('Undefined controller service "test_controller".', $exception->getMessage());
});
self::assertSame(
[],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "service"
*/
public function testLoadControllerAsServiceWithInvokeMethod()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'test_controller'])
);
$this->container->expects(self::once())
->method('has')
->with('test_controller')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('test_controller')
->willReturn(new TestInvokeController());
$this->logger->expects(self::never())
->method('error');
self::assertSame(
['test_route' => [TestInvokeController::class, '__invoke']],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "service" when service does not exist
*/
public function testLoadControllerAsServiceWithInvokeMethodWhenServiceDoesNotExist()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'test_controller'])
);
$this->container->expects(self::once())
->method('has')
->with('test_controller')
->willReturn(false);
$this->logger->expects(self::once())
->method('error')
->willReturnCallback(function ($message, $context) {
self::assertEquals('Cannot extract controller for "test_route" route.', $message);
/** @var \InvalidArgumentException $exception */
$exception = $context['exception'];
self::assertInstanceOf(\InvalidArgumentException::class, $exception);
self::assertEquals('Undefined controller service "test_controller".', $exception->getMessage());
});
self::assertSame(
[],
$this->controllerClassProvider->getControllers()
);
}
/**
* test for controller defined as "service" when "__invoke" method does not exist
*/
public function testLoadControllerAsServiceWithInvokeMethodWhenInvokeMethodDoesNotExist()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'test_controller'])
);
$this->container->expects(self::once())
->method('has')
->with('test_controller')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('test_controller')
->willReturn(new TestController());
$this->logger->expects(self::once())
->method('error')
->willReturnCallback(function ($message, $context) {
self::assertEquals('Cannot extract controller for "test_route" route.', $message);
/** @var \InvalidArgumentException $exception */
$exception = $context['exception'];
self::assertInstanceOf(\InvalidArgumentException::class, $exception);
self::assertEquals(
sprintf('Controller class "%s" should have "__invoke" method.', TestController::class),
$exception->getMessage()
);
});
self::assertSame(
[],
$this->controllerClassProvider->getControllers()
);
}
/**
* test case when the controller service should be ignored
*/
public function testLoadControllerAsIgnoredService()
{
$this->routeCollection->add(
'test_route',
new Route('test', ['_controller' => 'web_profiler.controller'])
);
$this->container->expects(self::once())
->method('has')
->with('web_profiler.controller')
->willReturn(true);
$this->container->expects(self::never())
->method('get');
$this->logger->expects(self::never())
->method('error');
self::assertSame(
[],
$this->controllerClassProvider->getControllers()
);
}
}
| mit |
seripap/vainglory | dist/models/resources/actors.js | 2099 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = [{
"name": "Adagio",
"serverName": "*Adagio*"
}, {
"name": "Alpha",
"serverName": "*Alpha*"
}, {
"name": "Ardan",
"serverName": "*Ardan*"
}, {
"name": "Baptiste",
"serverName": "*Baptiste*"
}, {
"name": "Baron",
"serverName": "*Baron*"
}, {
"name": "Blackfeather",
"serverName": "*Blackfeather*"
}, {
"name": "Catherine",
"serverName": "*Catherine*"
}, {
"name": "Celeste",
"serverName": "*Celeste*"
}, {
"name": "Churnwalker",
"serverName": "*Churnwalker*"
}, {
"name": "Flicker",
"serverName": "*Flicker*"
}, {
"name": "Fortress",
"serverName": "*Fortress*"
}, {
"name": "Glaive",
"serverName": "*Glaive*"
}, {
"name": "Grace",
"serverName": "*Grace*"
}, {
"name": "Grumpjaw",
"serverName": "*Grumpjaw*"
}, {
"name": "Gwen",
"serverName": "*Gwen*"
}, {
"name": "Krul",
"serverName": "*Hero009*"
}, {
"name": "Krul",
"serverName": "*Krul*"
}, {
"name": "Skaarf",
"serverName": "*Hero010*"
}, {
"name": "Skaarf",
"serverName": "*Skaarf*"
}, {
"name": "Rona",
"serverName": "*Hero016*"
}, {
"name": "Rona",
"serverName": "*Rona*"
}, {
"name": "Reza",
"serverName": "*Reza*"
}, {
"name": "Idris",
"serverName": "*Idris*"
}, {
"name": "Joule",
"serverName": "*Joule*"
}, {
"name": "Kestrel",
"serverName": "*Kestrel*"
}, {
"name": "Koshka",
"serverName": "*Koshka*"
}, {
"name": "Lance",
"serverName": "*Lance*"
}, {
"name": "Lyra",
"serverName": "*Lyra*"
}, {
"name": "Ozo",
"serverName": "*Ozo*"
}, {
"name": "Petal",
"serverName": "*Petal*"
}, {
"name": "Phinn",
"serverName": "*Phinn*"
}, {
"name": "Reim",
"serverName": "*Reim*"
}, {
"name": "Ringo",
"serverName": "*Ringo*"
}, {
"name": "SAW",
"serverName": "*SAW*"
}, {
"name": "Samuel",
"serverName": "*Samuel*"
}, {
"name": "Taka",
"serverName": "*Sayoc*"
}, {
"name": "Taka",
"serverName": "*Taka*"
}, {
"name": "Skye",
"serverName": "*Skye*"
}, {
"name": "Vox",
"serverName": "*Vox*"
}]; | mit |
swarajgiri/express-bootstrap | bootstrap/app.js | 2490 | 'use strict';
const express = require('express'),
config = require('../cfg'),
app = express(),
exphbs = require('express-handlebars'),
compress = require('compression'),
hpp = require('hpp'),
bodyParser = require('body-parser'),
log = require('./logger'),
minions = require('../minions');
// Set config
app.set('config', config);
app.use(bodyParser.urlencoded({
extended: true
}));
// Prevent parameter pollution
app.use(hpp());
// Use gzip
app.use(compress());
app.set('etag', 'strong');
// Set views dir
app.set('views', app.get('config').paths.templates);
// Serve static files
app.use('/static', express.static(app.get('config').paths.static));
// Configure handlebars
const hbs = exphbs.create({
extname:'hbs',
layoutsDir: app.get('config').paths.templates + '/layouts',
defaultLayout: 'main',
partialsDir: [
app.get('config').paths.templates + '/partials/'
]
});
// Initialize engine
app.engine('hbs', hbs.engine);
// Set engine
app.set('view engine', 'hbs');
// Enable view cache
app.enable('view cache');
// Set config
app.set('config', config);
// INIT minions
app.set('minions', minions(config));
// Load routes
require('../web/routes')(app);
// Trust the X-Forwarded-* header
app.enable('trust proxy');
// Create a simple representation of request data
app.use((req, res, next) => {
req.logdata = {
'method': req.method,
'url' : req.url,
'query' : req.query,
'body' : req.body,
'ip' : req.ip
};
next();
});
// Log all requests
app.use((req, res, next) => {
log.info('Request', req.logdata);
next();
});
// Set req._data = {}
app.use((req, res, next) => {
req._data = {};
next();
});
// Handle 404
app.use((req, res) => {
log.warn('404', {
'method': req.method,
'url' : req.url,
'query' : req.query,
'ip' : req.ip
});
res.status(404);
res.send('404: Page not found');
});
// Handle 500 errors
app.use((err, req, res, next) => {
if (! err) {
return next();
}
log.error('500', {
'method': req.method,
'url' : req.url,
'query' : req.query,
'ip' : req.ip,
'error' : err
});
res.status(500);
res.send('500: Internal server error');
});
app.listen(app.get('config').web.port);
log.info('Listening on port %s', app.get('config').web.port);
| mit |
bericp1/pop-culture | public/quiz/QuizResource.js | 372 | /*exported QuizQuizResource */
var QuizQuizResource = (function(){
'use strict';
return ['$resource', function($resource){
return $resource(
'/quiz/quiz/:_id',
{'_id':'@_id'},
{
'deleteAll': {
method: 'DELETE',
isArray: true,
params: {
'_id': '*'
}
}
}
);
}];
})();
| mit |
pib/hamsterdrop | demos/vector/bullet.js | 6664 |
/**
* The Render Engine
* Example Game: Spaceroids - an Asteroids clone
*
* The bullet object
*
* @author: Brett Fattori (brettf@renderengine.com)
*
* @author: $Author: bfattori $
* @version: $Revision: 1449 $
*
* Copyright (c) 2010 Brett Fattori (brettf@renderengine.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.
*
*/
Engine.include("/components/component.mover2d.js");
Engine.include("/components/component.vector2d.js");
Engine.include("/components/component.collider.js");
Engine.include("/engine/engine.object2d.js");
Engine.initObject("SpaceroidsBullet", "Object2D", function() {
/**
* @class The bullet object.
*
* @param player {Spaceroids.Player} The player object this bullet comes from,
*/
var SpaceroidsBullet = Object2D.extend({
player: null,
field: null,
rot: null,
constructor: function(player) {
this.base("Bullet");
// This is a hack!
this.field = Spaceroids;
// Track the player that created us
this.player = player;
this.rot = player.getRotation();
// Add components to move and draw the bullet
this.add(Mover2DComponent.create("move"));
this.add(Vector2DComponent.create("draw"));
this.add(ColliderComponent.create("collide", this.field.collisionModel));
this.getComponent("collide").setCollisionMask(Math2.parseBin("100"));
// Get the player's position and rotation,
// then position this at the tip of the ship
// moving away from it
var p_mover = this.player.getComponent("move");
var c_mover = this.getComponent("move");
var c_draw = this.getComponent("draw");
c_draw.setPoints(SpaceroidsBullet.shape);
c_draw.setLineStyle("white");
c_draw.setFillStyle("white");
var r = p_mover.getRotation();
var dir = Math2D.getDirectionVector(Point2D.ZERO, SpaceroidsBullet.tip, r);
var p = Point2D.create(p_mover.getPosition());
var dPos = Point2D.create(dir).mul(10);
c_mover.setPosition(p.add(dPos));
c_mover.setVelocity(dir.mul(8));
c_mover.setCheckLag(false);
dir.destroy();
p.destroy();
dPos.destroy();
},
release: function() {
this.base();
this.player = null;
},
/**
* Destroy a bullet, removing it from the list of objects
* in the last collision model node.
*/
destroy: function() {
Spaceroids.collisionModel.removeObject(this);
this.base();
},
/**
* Returns the bullet position
* @type Point2D
*/
getPosition: function() {
return this.getComponent("move").getPosition();
},
getRenderPosition: function() {
return this.getComponent("move").getRenderPosition();
},
/**
* Returns the last position of the bullet
* @type Point2D
*/
getLastPosition: function() {
return this.getComponent("move").getLastPosition();
},
/**
* Set the position of the bullet.
*
* @param point {Point2D} The position of the bullet.
*/
setPosition: function(point) {
this.base(point);
this.getComponent("move").setPosition(point);
},
/**
* Update the host object to reflect the state of the bullet.
*
* @param renderContext {RenderContext} The rendering context
* @param time {Number} The engine time in milliseconds
*/
update: function(renderContext, time) {
var c_mover = this.getComponent("move");
// Particle trail
this.field.pEngine.addParticle(BulletParticle.create(this.getPosition(), this.rot, 45, "#fff", 250));
// Is this bullet in field any more?
var p = c_mover.getPosition();
var bBox = Rectangle2D.create(p.x, p.y, 2, 2);
if (!this.field.inField(p, bBox))
{
this.player.removeBullet(this);
this.destroy();
bBox.destroy();
return;
}
renderContext.pushTransform();
this.base(renderContext, time);
renderContext.popTransform();
bBox.destroy();
},
/**
* Called whenever an object is located in the PCL which might
* be in a collision state with this bullet. Checks for collisions
* with rocks and UFO's.
*
* @param obj {HostObject} The object that the bullet might be in a
* collision state with.
*
* @returns <tt>ColliderComponent.STOP</tt> if the collision was handled,
* otherwise <tt>ColliderComponent.CONTINUE</tt> if the other
* objects in the PCL should be tested.
*/
onCollide: function(obj) {
if ((SpaceroidsRock.isInstance(obj)) &&
( (obj.getWorldBox().containsPoint(this.getPosition())) ||
(Math2D.lineBoxCollision(this.getPosition(), this.getLastPosition(), obj.getWorldBox())) )
)
{
// Kill the rock
obj.kill();
// Remove the bullet
this.player.removeBullet(this);
this.destroy();
// All set
return ColliderComponent.STOP;
}
return ColliderComponent.CONTINUE;
}
}, {
/**
* Get the class name of this object
*
* @type String
*/
getClassName: function() {
return "SpaceroidsBullet";
},
// Why we have this, I don't know...
shape: [ Point2D.create(-1, -1), Point2D.create( 1, -1),
Point2D.create( 1, 1), Point2D.create(-1, 1)],
// The tip of the player at zero rotation (up)
tip: Point2D.create(0, -1)
});
return SpaceroidsBullet;
}); | mit |
DazzyG/HolidayCards | app/src/main/java/uk/co/dazcorp/android/holidaycards/CardContainer.java | 18206 | package uk.co.dazcorp.android.holidaycards;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import java.util.Random;
/**
* Created by kikoso https://github.com/kikoso/Swipeable-Cards/
* Modified by gentd on 22/04/2015.
*
* Now displays a list of cards that repeats
* This is accomplished by animating the removed card to the back of the stack
*/
public class CardContainer extends AdapterView<ListAdapter> {
public interface CardChangedListener {
void onCurrentCardChanged(int currentCard);
}
public static final int INVALID_POINTER_ID = -1;
private int mActivePointerId = INVALID_POINTER_ID;
private static final double DISORDERED_MAX_ROTATION_RADIANS = Math.PI / 64;
private final DataSetObserver mDataSetObserver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
clearStack();
ensureFull();
}
@Override
public void onInvalidated() {
super.onInvalidated();
clearStack();
}
};
private final Random mRandom = new Random();
private final Rect boundsRect = new Rect();
private final Rect childRect = new Rect();
private final Matrix mMatrix = new Matrix();
//TODO: determine max dynamically based on device speed
private int mMaxVisible = 10;
private GestureDetector mGestureDetector;
private int mFlingSlop;
private Orientations.Orientation mOrientation;
private ListAdapter mListAdapter;
private float mLastTouchX;
private float mLastTouchY;
private View mTopCard;
private int mTouchSlop;
private int mGravity;
private int mNextAdapterPosition;
private boolean mDragging;
private CardChangedListener mCardChangedListener;
public CardContainer(Context context) {
super(context);
setOrientation(Orientations.Orientation.Disordered);
setGravity(Gravity.CENTER);
init();
}
public CardContainer(Context context, AttributeSet attrs) {
super(context, attrs);
initFromXml(attrs);
init();
}
public CardContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initFromXml(attrs);
init();
}
private void init() {
ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());
mFlingSlop = viewConfiguration.getScaledMinimumFlingVelocity();
mTouchSlop = viewConfiguration.getScaledTouchSlop();
mGestureDetector = new GestureDetector(getContext(), new GestureListener());
}
private void initFromXml(AttributeSet attr) {
TypedArray a = getContext().obtainStyledAttributes(attr,
R.styleable.CardContainer);
setGravity(a.getInteger(R.styleable.CardContainer_android_gravity, Gravity.CENTER));
int orientation = a.getInteger(R.styleable.CardContainer_orientation, 1);
setOrientation(Orientations.Orientation.fromIndex(orientation));
a.recycle();
}
public CardChangedListener getCardChangedListener() {
return mCardChangedListener;
}
public void setCardChangedListener(
CardChangedListener cardChangedListener) {
mCardChangedListener = cardChangedListener;
}
@Override
public ListAdapter getAdapter() {
return mListAdapter;
}
@Override
public void setAdapter(ListAdapter adapter) {
if (mListAdapter != null)
mListAdapter.unregisterDataSetObserver(mDataSetObserver);
clearStack();
mTopCard = null;
mListAdapter = adapter;
mNextAdapterPosition = 0;
adapter.registerDataSetObserver(mDataSetObserver);
ensureFull();
if (getChildCount() != 0) {
mTopCard = getChildAt(getChildCount() - 1);
mTopCard.setLayerType(LAYER_TYPE_HARDWARE, null);
}
requestLayout();
}
private void ensureFull() {
while (mNextAdapterPosition < mListAdapter.getCount() && getChildCount() < mMaxVisible) {
View view = mListAdapter.getView(mNextAdapterPosition, null, this);
view.setLayerType(LAYER_TYPE_SOFTWARE, null);
if(mOrientation == Orientations.Orientation.Disordered) {
view.setRotation(getDisorderedRotation());
}
addViewInLayout(view, 0, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
mListAdapter.getItemViewType(mNextAdapterPosition)), false);
requestLayout();
view.setTag(mNextAdapterPosition);
mNextAdapterPosition += 1;
}
}
private void clearStack() {
removeAllViewsInLayout();
mNextAdapterPosition = 0;
mTopCard = null;
}
public Orientations.Orientation getOrientation() {
return mOrientation;
}
public void setOrientation(Orientations.Orientation orientation) {
if (orientation == null)
throw new NullPointerException("Orientation may not be null");
if(mOrientation != orientation) {
this.mOrientation = orientation;
if(orientation == Orientations.Orientation.Disordered) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.setRotation(getDisorderedRotation());
}
}
else {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.setRotation(0);
}
}
requestLayout();
}
}
private float getDisorderedRotation() {
return (float) Math.toDegrees(mRandom.nextGaussian() * DISORDERED_MAX_ROTATION_RADIANS);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int requestedWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
int requestedHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
int childWidth, childHeight;
if (mOrientation == Orientations.Orientation.Disordered) {
int R1, R2;
if (requestedWidth >= requestedHeight) {
R1 = requestedHeight;
R2 = requestedWidth;
} else {
R1 = requestedWidth;
R2 = requestedHeight;
}
childWidth = (int) ((R1 * Math.cos(DISORDERED_MAX_ROTATION_RADIANS) - R2 * Math.sin(DISORDERED_MAX_ROTATION_RADIANS)) / Math.cos(2 * DISORDERED_MAX_ROTATION_RADIANS));
childHeight = (int) ((R2 * Math.cos(DISORDERED_MAX_ROTATION_RADIANS) - R1 * Math.sin(DISORDERED_MAX_ROTATION_RADIANS)) / Math.cos(2 * DISORDERED_MAX_ROTATION_RADIANS));
} else {
childWidth = requestedWidth;
childHeight = requestedHeight;
}
int childWidthMeasureSpec, childHeightMeasureSpec;
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.AT_MOST);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST);
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
assert child != null;
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
for (int i = 0; i < getChildCount(); i++) {
boundsRect.set(0, 0, getWidth(), getHeight());
View view = getChildAt(i);
int w, h;
w = view.getMeasuredWidth();
h = view.getMeasuredHeight();
Gravity.apply(mGravity, w, h, boundsRect, childRect);
view.layout(childRect.left, childRect.top, childRect.right, childRect.bottom);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mTopCard == null) {
return false;
}
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
Log.d("Touch Event", MotionEvent.actionToString(event.getActionMasked()) + " ");
final int pointerIndex;
final float x, y;
final float dx, dy;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mTopCard.getHitRect(childRect);
pointerIndex = event.getActionIndex();
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
if (!childRect.contains((int) x, (int) y)) {
return false;
}
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = event.getPointerId(pointerIndex);
float[] points = new float[]{x - mTopCard.getLeft(), y - mTopCard.getTop()};
mTopCard.getMatrix().invert(mMatrix);
mMatrix.mapPoints(points);
mTopCard.setPivotX(points[0]);
mTopCard.setPivotY(points[1]);
break;
case MotionEvent.ACTION_MOVE:
pointerIndex = event.findPointerIndex(mActivePointerId);
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
dx = x - mLastTouchX;
dy = y - mLastTouchY;
if (Math.abs(dx) > mTouchSlop || Math.abs(dy) > mTouchSlop) {
mDragging = true;
}
if(!mDragging) {
return true;
}
mTopCard.setTranslationX(mTopCard.getTranslationX() + dx);
mTopCard.setTranslationY(mTopCard.getTranslationY() + dy);
mTopCard.setRotation(40 * mTopCard.getTranslationX() / (getWidth() / 2.f));
mLastTouchX = x;
mLastTouchY = y;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (!mDragging) {
return true;
}
mDragging = false;
mActivePointerId = INVALID_POINTER_ID;
ValueAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mTopCard,
PropertyValuesHolder.ofFloat("translationX", 0),
PropertyValuesHolder.ofFloat("translationY", 0),
PropertyValuesHolder.ofFloat("rotation", (float) Math.toDegrees(mRandom.nextGaussian() * DISORDERED_MAX_ROTATION_RADIANS)),
PropertyValuesHolder.ofFloat("pivotX", mTopCard.getWidth() / 2.f),
PropertyValuesHolder.ofFloat("pivotY", mTopCard.getHeight() / 2.f)
).setDuration(250);
animator.setInterpolator(new AccelerateInterpolator());
animator.start();
break;
case MotionEvent.ACTION_POINTER_UP:
pointerIndex = event.getActionIndex();
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = event.getX(newPointerIndex);
mLastTouchY = event.getY(newPointerIndex);
mActivePointerId = event.getPointerId(newPointerIndex);
}
break;
}
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mTopCard == null) {
return false;
}
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
final int pointerIndex;
final float x, y;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mTopCard.getHitRect(childRect);
pointerIndex = event.getActionIndex();
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
if (!childRect.contains((int) x, (int) y)) {
return false;
}
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = event.getPointerId(pointerIndex);
break;
case MotionEvent.ACTION_MOVE:
pointerIndex = event.findPointerIndex(mActivePointerId);
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
if (Math.abs(x - mLastTouchX) > mTouchSlop || Math.abs(y - mLastTouchY) > mTouchSlop) {
float[] points = new float[]{x - mTopCard.getLeft(), y - mTopCard.getTop()};
mTopCard.getMatrix().invert(mMatrix);
mMatrix.mapPoints(points);
mTopCard.setPivotX(points[0]);
mTopCard.setPivotY(points[1]);
return true;
}
}
return false;
}
@Override
public View getSelectedView() {
throw new UnsupportedOperationException();
}
@Override
public void setSelection(int position) {
throw new UnsupportedOperationException();
}
public void setGravity(int gravity) {
mGravity = gravity;
}
public static class LayoutParams extends ViewGroup.LayoutParams {
int viewType;
public LayoutParams(int w, int h, int viewType) {
super(w, h);
this.viewType = viewType;
}
}
private class GestureListener extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.d("Fling", "Fling with " + velocityX + ", " + velocityY);
final View topCard = mTopCard;
float dx = e2.getX() - e1.getX();
if (Math.abs(dx) > mTouchSlop &&
Math.abs(velocityX) > Math.abs(velocityY) &&
Math.abs(velocityX) > mFlingSlop * 3) {
float targetX = topCard.getX();
float targetY = topCard.getY();
long duration = 0;
boundsRect.set(0 - topCard.getWidth() - 100, 0 - topCard.getHeight() - 100, getWidth() + 100, getHeight() + 100);
while (boundsRect.contains((int) targetX, (int) targetY)) {
targetX += velocityX / 10;
targetY += velocityY / 10;
duration += 100;
}
duration = Math.min(500, duration);
mTopCard = getChildAt(getChildCount() - 2);
if(mTopCard != null)
mTopCard.setLayerType(LAYER_TYPE_HARDWARE, null);
// Animate the card to the back of the stack
topCard.animate()
.setDuration(duration)
.alpha(.75f)
.setInterpolator(new LinearInterpolator())
.x(targetX)
.y(targetY)
.rotation(Math.copySign(45, velocityX))
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if(mCardChangedListener != null) {
mCardChangedListener.onCurrentCardChanged(
(Integer) mTopCard.getTag());
}
for (int i = 0; i <= getChildCount() - 2; i++) {
getChildAt(0).bringToFront();
}
ValueAnimator animator = ObjectAnimator.ofPropertyValuesHolder(topCard,
PropertyValuesHolder.ofFloat("translationX", 0),
PropertyValuesHolder.ofFloat("translationY", 0),
PropertyValuesHolder.ofFloat("rotation", (float) Math.toDegrees(mRandom.nextGaussian() * DISORDERED_MAX_ROTATION_RADIANS)),
PropertyValuesHolder.ofFloat("pivotX", topCard.getWidth() / 2.f),
PropertyValuesHolder.ofFloat("pivotY", topCard.getHeight() / 2.f),
PropertyValuesHolder.ofFloat("alpha", 1f)
).setDuration(250);
animator.setInterpolator(new DecelerateInterpolator());
animator.start();
}
@Override
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
});
return true;
} else
return false;
}
}
} | mit |
asiboro/asiboro.github.io | vsdoc/search--/s_2930.js | 81 | search_result['2930']=["topic_000000000000070A.html","CompanyVideoDto Class",""]; | mit |
townie/KeithWebber_LeadMailer | spec/models/identity_spec.rb | 265 | require 'spec_helper'
describe Identity do
it { should belong_to(:user) }
it { should validate_presence_of(:user_id) }
it { should validate_presence_of(:uid) }
it { should validate_presence_of(:provider) }
it { should validate_presence_of(:uid) }
end
| mit |
SimplyCpp/examples | random_util/program.cpp | 718 | //Sample provided by Fabio Galuppo
//October 2016
//http://www.simplycpp.com
//compile clang++: (Apple LLVM version 8.0.0 (clang-800.0.38))
//clang++ -Wall -O2 -std=c++14 -o program.exe program.cpp sample1.cpp sample2.cpp sample3.cpp
//compile g++: (g++ (GCC) 5.3.0)
//g++ -Wall -O2 -std=c++14 -o program.exe program.cpp sample1.cpp sample2.cpp sample3.cpp
//compile msvc: (Visual C++ 2015 Update 3 - Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1)
//cl.exe /EHsc /Ox /std:c++14 program.cpp sample1.cpp sample2.cpp sample3.cpp /link /out:program.exe
#include "sample1.hpp"
#include "sample2.hpp"
#include "sample3.hpp"
int main()
{
sample1_main();
sample2_main();
sample3_main();
return 0;
} | mit |
hasadna/anyway | anyway/widgets/suburban_widgets/most_severe_accidents_widget.py | 2348 | import logging
from typing import Dict
from flask_babel import _
from anyway.request_params import RequestParams
from anyway.backend_constants import AccidentSeverity, AccidentType
from anyway.widgets.suburban_widgets.most_severe_accidents_table_widget import (
get_most_severe_accidents_with_entities,
)
from anyway.models import AccidentMarkerView
from anyway.widgets.widget import register
from anyway.widgets.suburban_widgets.sub_urban_widget import SubUrbanWidget
@register
class MostSevereAccidentsWidget(SubUrbanWidget):
name: str = "most_severe_accidents"
def __init__(self, request_params: RequestParams):
super().__init__(request_params, type(self).name)
self.rank = 3
self.information = "Most recent fatal and severe accidents displayed on a map. Up to 10 accidents are presented."
def generate_items(self) -> None:
self.items = MostSevereAccidentsWidget.get_most_severe_accidents(
AccidentMarkerView,
self.request_params.location_info,
self.request_params.start_time,
self.request_params.end_time,
)
@staticmethod
def get_most_severe_accidents(table_obj, filters, start_time, end_time, limit=10):
entities = (
"longitude",
"latitude",
"accident_severity",
"accident_timestamp",
"accident_type",
)
items = get_most_severe_accidents_with_entities(
table_obj, filters, entities, start_time, end_time, limit
)
for item in items:
item["accident_severity"] = _(AccidentSeverity(item["accident_severity"]).get_label())
return items
@staticmethod
def localize_items(request_params: RequestParams, items: Dict) -> Dict:
for item in items["data"]["items"]:
try:
item["accident_type"] = _(AccidentType(item["accident_type"]).get_label())
except KeyError:
logging.exception(
f"MostSevereAccidentsWidget.localize_items: Exception while translating {item}."
)
return items
# adding calls to _() for pybabel extraction
_("Most recent fatal and severe accidents displayed on a map. Up to 10 accidents are presented.")
| mit |
mmalecki/node-authorized-keys | test/authorized-keys-test.js | 1005 | var assert = require('assert'),
vows = require('vows'),
AuthorizedKeys = require('../');
var testKey = { type: 'ssh-rsa', content: 'mykey', name: 'maciej' };
vows.describe('authorized-keys').addBatch({
'When using `authorized-keys`': {
'with a new `AuthorizedKeys` object': {
topic: new AuthorizedKeys(),
'there should be no keys': function (keys) {
assert.lengthOf(keys.keys, 0);
},
'after adding a key to it': {
topic: function (keys) {
keys.add(testKey);
return keys;
},
'it should be there': function (keys) {
assert.lengthOf(keys.keys, 1);
assert.deepEqual(keys.keys[0], new AuthorizedKeys.Key(testKey));
},
'it should be searchable by name': function (keys) {
var search = keys.getByName(testKey.name);
assert.lengthOf(search, 1);
assert.deepEqual(search[0], new AuthorizedKeys.Key(testKey));
}
}
}
}
}).export(module);
| mit |
gejiawen/test-async | collections/reduce/2.2.js | 1170 | /**
* @file: 2.2
* @author: gejiawen
* @date: 15/10/26 23:02
* @description: 2.2
*/
var async = require('async');
var t = require('../../t');
var log = t.log;
/**
* Reduce可以让我们给定一个初始值,用它与集合中的每一个元素做运算,最后得到一个值。
* reduce从左向右来遍历元素,如果想从右向左,可使用reduceRight。
*/
//reduce(arr, memo, iterator(memo,item,callback), callback(err,result))
//alias: inject, foldl
var arr = [1, 3, 5];
/**
* 通过t.inc做一个累加器,参与reduce的计算
*
* 通过t.inc将数组的每一个元素先自增1,然后再经过reduce进行累加运算
*/
async.reduce(arr, 100, function (memo, item, callback) {
log('2.2 enter: ' + memo + ',' + item);
t.inc(item, function (err, n) {
log('2.2 handle: ', n);
callback(null, memo + n);
});
}, function (err, result) {
log('2.2 err: ', err);
log('2.2 result: ', result);
});
//45.293> 2.2 enter: 100,1
//45.504> 2.2 handle: 2
//45.506> 2.2 enter: 102,3
//45.715> 2.2 handle: 4
//45.715> 2.2 enter: 106,5
//45.920> 2.2 handle: 6
//45.920> 2.2 err: null
//45.921> 2.2 result: 112
| mit |
kartikpalani/Smart-Energy-Hackathon | YARA-SmartOp/js/i18n/chart.locale-fa.js | 1525 | (function ($) {
/**
* jqChart Persian Translation
* http://www.jqchart.com/
*
* In order to use a particular language pack, you need to include the javascript language
* pack to the head of your page, after the jQuery library reference (since language
* packs depend on jQuery) and after referencing the jqChart javascript file.
*
* <script src="../js/jquery.min.js" type="text/javascript"></script>
* <script src="../js/jquery.jqChart.min.js" type="text/javascript"></script>
* <script src="../js/i18n/chart.locale-xx.js" type="text/javascript"></script>
**/
$.jqChartDateFormat = {
dayNames: [
"يک", "دو", "سه", "چهار", "پنج", "جمع", "شنب",
"يکشنبه", "دوشنبه", "سه شنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"ژانويه", "فوريه", "مارس", "آوريل", "مه", "ژوئن", "ژوئيه", "اوت", "سپتامبر", "اکتبر", "نوامبر", "December"
],
amPm: ["ب.ظ", "ب.ظ", "ق.ظ", "ق.ظ"],
s: function (j) { return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th' },
masks: {
shortDate: "m/d/yyyy",
shortTime: "h:MM TT",
longTime: "h:MM:ss TT"
}
};
})(jQuery);
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_netapp/lib/2020-11-01/generated/azure_mgmt_netapp/models/hourly_schedule.rb | 1859 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::NetApp::Mgmt::V2020_11_01
module Models
#
# Hourly Schedule properties
#
class HourlySchedule
include MsRestAzure
# @return [Integer] Hourly snapshot count to keep
attr_accessor :snapshots_to_keep
# @return [Integer] Indicates which minute snapshot should be taken
attr_accessor :minute
# @return [Integer] Resource size in bytes, current storage usage for the
# volume in bytes
attr_accessor :used_bytes
#
# Mapper for HourlySchedule class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'hourlySchedule',
type: {
name: 'Composite',
class_name: 'HourlySchedule',
model_properties: {
snapshots_to_keep: {
client_side_validation: true,
required: false,
serialized_name: 'snapshotsToKeep',
type: {
name: 'Number'
}
},
minute: {
client_side_validation: true,
required: false,
serialized_name: 'minute',
type: {
name: 'Number'
}
},
used_bytes: {
client_side_validation: true,
required: false,
serialized_name: 'usedBytes',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| mit |
cakemanager/cakeadmin-adminbar | src/Controller/AdminBarController.php | 1179 | <?php
/**
* CakeManager (http://cakemanager.org)
* Copyright (c) http://cakemanager.org
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) http://cakemanager.org
* @link http://cakemanager.org CakeManager Project
* @since 1.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace AdminBar\Controller;
use AdminBar\Controller\AppController as BaseController;
use Cake\Routing\Router;
class AdminBarController extends BaseController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('AdminBar.AdminBar');
}
public function index()
{
if ($this->request->is('ajax')) {
if ($this->request->is('post')) {
$request = $this->request->data('request');
$requestParams = Router::parse($request);
$this->AdminBar->createAdminBar($requestParams);
$this->layout = 'AdminBar.ajax';
}
}
}
} | mit |
LambertPark/A_NScreen | NScreen/app/src/main/java/com/stvn/nscreen/vod/VodMainOtherTabFragment.java | 39320 | package com.stvn.nscreen.vod;
import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.jjiya.android.common.Constants;
import com.jjiya.android.common.IOnBackPressedListener;
import com.jjiya.android.common.JYSharedPreferences;
import com.jjiya.android.common.ListViewDataObject;
import com.jjiya.android.http.BitmapLruCache;
import com.jjiya.android.http.JYStringRequest;
import com.stvn.nscreen.R;
import com.stvn.nscreen.bean.SubCategoryObject;
import com.stvn.nscreen.util.CMAlertUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* A simple {@link Fragment} subclass.
*/
public class VodMainOtherTabFragment extends VodMainBaseFragment implements View.OnClickListener, IOnBackPressedListener {
private static final String tag = VodMainOtherTabFragment.class.getSimpleName();
private static VodMainOtherTabFragment mInstance;
private JYSharedPreferences mPref;
// network
private String mCategoryId;
private RequestQueue mRequestQueue;
private ProgressDialog mProgressDialog;
private ImageLoader mImageLoader;
private SubCategoryObject mCurrCategoryObject;
private BroadcastReceiver mBroadcastReceiver;
private boolean isNeedReloadData; // 성인인증.
// gui
private GridView mGridView;
private VodMainGridViewAdapter mAdapter;
private TextView mCategoryNameTextView;
private LinearLayout mTabbar;
private LinearLayout mTab1; // 실시간 인기순위. requestItems=daily
private LinearLayout mTab2; // 주간 인기순위. requestItems=weekly
private String mRequestItems; // default = daily
//
private List<JSONObject> categorys;
private FrameLayout mCategoryBgFramelayout;
private ImageButton mCategoryButton;
private VodMainOtherListViewAdapter mCategoryAdapter;
private ListView mCategoryListView;
//
//// private Map<String, String> mCateDepth1;
//// private Map<String, String> mCateDepth2;
//// private Map<String, String> mCateDepth3;
// private Map<String, String> mCateDepth4;
//
private ArrayList<JSONObject> mCateDepths1;
private ArrayList<JSONObject> mCateDepths2;
private ArrayList<JSONObject> mCateDepths3;
public VodMainOtherTabFragment() {
// Required empty public constructor
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
isNeedReloadData = true;
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("I_AM_ADULT");
getActivity().registerReceiver(mBroadcastReceiver, intentFilter);
}
@Override
public void onDetach() {
super.onDetach();
if ( mBroadcastReceiver != null ) {
getActivity().unregisterReceiver(mBroadcastReceiver);
}
}
@Override
public void onResume() {
super.onResume();
if ( isNeedReloadData == true ) {
isNeedReloadData = false;
if ( getiMyTabNumber() == 1 ) {
textView2.performClick();
} else if ( getiMyTabNumber() == 2 ) {
textView3.performClick();
} else if ( getiMyTabNumber() == 3 ) {
textView4.performClick();
} else if ( getiMyTabNumber() == 4 ) {
if (mPref.isAdultVerification() == false) {
mTab1TextView.performClick();
} else {
textView5.performClick();
}
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_vod_main_order_tab, container, false);
setMyContext(this.getActivity());
Bundle param = getArguments();
String tabId = param.getString("tabId");
int iTabId = Integer.valueOf(tabId);
mCategoryId = param.getString("categoryId");
categorys = new ArrayList<JSONObject>();
mCurrCategoryObject = new SubCategoryObject();
mInstance = this;
if ( mPref == null ) {
mPref = new JYSharedPreferences(this.getActivity());
}
mRequestQueue = Volley.newRequestQueue(this.getActivity());
ImageLoader.ImageCache imageCache = new BitmapLruCache();
mImageLoader = new ImageLoader(mRequestQueue, imageCache);
// 먼저 공통 뷰 초기화 부터 해준다. (Left버튼, Right버튼, GNB)
view = initializeBaseView(view, iTabId);
// 공통 뷰 초기화가 끝났으면, 이놈을 위한 초기화를 한다.
view = initializeView(view);
return view;
}
private View initializeView(View view) {
mCategoryNameTextView = (TextView) view.findViewById(R.id.vod_main_orther_category_choice_textview);
mTabbar = (LinearLayout)view.findViewById(R.id.vod_main_other_tabbar_linearlayout);
mTab1 = (LinearLayout)view.findViewById(R.id.vod_main_other_tab1_linearlayout);
mTab2 = (LinearLayout)view.findViewById(R.id.vod_main_other_tab2_linearlayout);
mTab1.setSelected(true);
mTab2.setSelected(false);
mTab1.setOnClickListener(this);
mTab2.setOnClickListener(this);
mRequestItems = "daily";
mAdapter = new VodMainGridViewAdapter(this, mInstance.getActivity(), null);
mGridView = (GridView)view.findViewById(R.id.vod_main_gridview);
mGridView.setAdapter(mAdapter);
//mGridView.setOnItemClickListener(assetItemClickListener);
mCategoryBgFramelayout = (FrameLayout)view.findViewById(R.id.vod_main_other_category_bg_framelayout);
mCategoryBgFramelayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCategoryBgFramelayout.setVisibility(View.GONE);
}
});
mCategoryButton = (ImageButton)view.findViewById(R.id.vod_main_orther_category_choice_imageButton);
mCategoryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int count = mCategoryAdapter.getCount();
if ( count == 0 ) {
categorys.clear();
requestGetCategoryTree(true);
} else {
mCategoryBgFramelayout.setVisibility(View.VISIBLE);
}
}
});
mCategoryAdapter = new VodMainOtherListViewAdapter(mInstance.getActivity(), null);
mCategoryListView = (ListView)view.findViewById(R.id.vod_main_other_category_listview);
mCategoryListView.setAdapter(mCategoryAdapter);
mCategoryListView.setOnItemClickListener(mCategoryItemClickListener);
mCateDepths1 = new ArrayList<JSONObject>();
mCateDepths2 = new ArrayList<JSONObject>();
mCateDepths3 = new ArrayList<JSONObject>();
// 카테고리 요청. 추천.
requestGetCategoryTree(false);
return view;
}
@Override
public void onClick(View v) {
switch ( v.getId() ) {
case R.id.vod_main_other_tab1_linearlayout: { // 실시간 인기순위.
mTab1.setSelected(true);
mTab2.setSelected(false);
mAdapter.clear();
mRequestItems = "daily";
requestGetPopularityChart();
} break;
case R.id.vod_main_other_tab2_linearlayout: { // 주간 인기순위.
mTab1.setSelected(false);
mTab2.setSelected(true);
mAdapter.clear();
mRequestItems = "weekly";
requestGetPopularityChart();
} break;
}
}
// private AdapterView.OnItemClickListener assetItemClickListener = new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListViewDataObject item = (ListViewDataObject)mAdapter.getItem(position);
// String assetId = "";
// try {
// JSONObject jo = new JSONObject(item.sJson);
// assetId = jo.getString("assetId");
// } catch (JSONException e) {
// e.printStackTrace();
// }
// Intent intent = new Intent(mInstance.getActivity(), com.stvn.nscreen.vod.VodDetailActivity.class);
// intent.putExtra("assetId", assetId);
// startActivity(intent);
// }
// };
// 카테고리 요청.
// 추천
// http://192.168.40.5:8080/HApplicationServer/getCategoryTree.xml?version=1&categoryProfile=4&categoryId=713228&depth=3&traverseType=DFS
private void requestGetCategoryTree(final boolean showCategoryView) {
final String thisTurnCategoriId;
if ( showCategoryView == false ) {
thisTurnCategoriId = mCategoryId;
} else {
thisTurnCategoriId = mPref.getValue(Constants.CATEGORY_ID_TAB2, "");
mCategoryId = thisTurnCategoriId;
}
mProgressDialog = ProgressDialog.show(mInstance.getActivity(), "", getString(R.string.wait_a_moment));
String url = mPref.getWebhasServerUrl() + "/getCategoryTree.json?version=1&terminalKey="+mPref.getWebhasTerminalKey()
+"&categoryProfile=4&categoryId="
//+mCategoryId+"&depth=4&traverseType=DFS";
+thisTurnCategoriId+"&depth=4&traverseType=DFS";
JYStringRequest request = new JYStringRequest(mPref, Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mProgressDialog.dismiss();
try {
JSONObject first = new JSONObject(response);
int resultCode = first.getInt("resultCode");
String errorString = first.getString("errorString");
JSONArray categoryList = first.getJSONArray("categoryList");
for ( int i = 0; i < categoryList.length(); i++ ) {
JSONObject category = (JSONObject)categoryList.get(i);
category.put("isOpened", false);
// viewerType : 20 이면 에셋인데, 트리에 나온다.
categorys.add(category);
}
if ( categoryList.length() > 1 ) {
categorys.remove(0);
}
JSONObject category = (JSONObject)categorys.get(0);
if ( showCategoryView == false ) {
mCategoryNameTextView.setText(category.getString("categoryName"));
mCurrCategoryObject.setsCategoryId(category.getString("categoryId"));
mCurrCategoryObject.setsAdultCategory(category.getString("adultCategory"));
mCurrCategoryObject.setsCategoryName(category.getString("categoryName"));
mCurrCategoryObject.setsLeaf(category.getString("leaf"));
mCurrCategoryObject.setsParentCategoryId(category.getString("parentCategoryId"));
mCurrCategoryObject.setsViewerType(category.getString("viewerType"));
}
processRequest();
for ( int i = 0; i < categorys.size(); i++ ) {
JSONObject loopCategory = (JSONObject)categorys.get(i);
String categoryId = loopCategory.getString("categoryId");
String parentCategoryId = loopCategory.getString("parentCategoryId");
boolean leaf = loopCategory.getBoolean("leaf");
//if ( mCategoryId.equals(parentCategoryId) ) {
if ( thisTurnCategoriId.equals(parentCategoryId) ) {
loopCategory.put("isOpened", false);
mCateDepths1.add(loopCategory);
ListViewDataObject obj = new ListViewDataObject(0, 1, loopCategory.toString());
mCategoryAdapter.addItem(obj);
}
}
//list2treee();
list2tree();
if ( showCategoryView == true ) {
mCategoryBgFramelayout.setVisibility(View.VISIBLE);
}
} catch ( JSONException e ) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mProgressDialog.dismiss();
if (error instanceof TimeoutError) {
Toast.makeText(mInstance.getActivity(), mInstance.getString(R.string.error_network_timeout), Toast.LENGTH_LONG).show();
} else if (error instanceof NoConnectionError) {
Toast.makeText(mInstance.getActivity(), mInstance.getString(R.string.error_network_noconnectionerror), Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
Toast.makeText(mInstance.getActivity(), mInstance.getString(R.string.error_network_servererror), Toast.LENGTH_LONG).show();
} else if (error instanceof NetworkError) {
Toast.makeText(mInstance.getActivity(), mInstance.getString(R.string.error_network_networkerrorr), Toast.LENGTH_LONG).show();
}
if ( mPref.isLogging() ) { VolleyLog.d(tag, "onErrorResponse(): " + error.getMessage()); }
}
}) {
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
if ( mPref.isLogging() ) { Log.d(tag, "getParams()" + params.toString()); }
return params;
}
};
mRequestQueue.add(request);
}
private AdapterView.OnItemClickListener mCategoryItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(tag, "mItemClickListener() " + position);
ListViewDataObject dobj = (ListViewDataObject) mCategoryAdapter.getItem(position);
try {
JSONObject jo = new JSONObject(dobj.sJson);
String categoryId = jo.getString("categoryId");
String adultCategory = jo.getString("adultCategory");
String categoryName = jo.getString("categoryName");
String sleaf = jo.getString("leaf");
boolean leaf = jo.getBoolean("leaf");
String parentCategoryId = jo.getString("parentCategoryId");
String viewerType = jo.getString("viewerType");
if ( leaf == true || ( leaf == false && "30".equals(viewerType)) ) { // 하부카테고리가 없으므로 닫을 것.
mCategoryBgFramelayout.setVisibility(View.GONE);
mCategoryId = categoryId;
//mCategoryAdapter.clear();
//mCategoryAdapter.notifyDataSetChanged();
mCategoryNameTextView.setText(categoryName);
mCurrCategoryObject.setsCategoryId(categoryId);
mCurrCategoryObject.setsAdultCategory(adultCategory);
mCurrCategoryObject.setsCategoryName(categoryName);
mCurrCategoryObject.setsLeaf(sleaf);
mCurrCategoryObject.setsParentCategoryId(parentCategoryId);
mCurrCategoryObject.setsViewerType(viewerType);
mAdapter.clear();
mAdapter.notifyDataSetChanged();
processRequest();
} else { // 하부카테고리가 있으므로 닫지 말것.
boolean isOpened = jo.getBoolean("isOpened");
String thisCategoryId = jo.getString("categoryId");
JSONObject newJo = new JSONObject(jo.toString());
if ( isOpened == true ) {
newJo.put("isOpened", false);
ListViewDataObject obj = new ListViewDataObject(0, dobj.iKey, newJo.toString());
mCategoryAdapter.set(position, obj);
if ( dobj.iKey == 1 ) {
// close tree. remove 2 depth
int iFindedPosi = getPositionWithCategoryId(categoryId);
while ( iFindedPosi != -1 ) {
mCategoryAdapter.remove(iFindedPosi);
iFindedPosi = getPositionWithCategoryId(categoryId);
}
} else if ( dobj.iKey == 2 ) {
// close tree. remove 3 depth
int iFindedPosi = getPositionWithCategoryId(categoryId);
while ( iFindedPosi != -1 ) {
mCategoryAdapter.remove(iFindedPosi);
iFindedPosi = getPositionWithCategoryId(categoryId);
}
}
} else {
newJo.put("isOpened", true);
ListViewDataObject obj = new ListViewDataObject(0, dobj.iKey, newJo.toString());
mCategoryAdapter.set(position, obj);
if ( dobj.iKey == 1 ) {
// append 2 depth
int iLoop = position+1;
for ( int i = 0; i < mCateDepths2.size(); i++ ) {
JSONObject loopJo = mCateDepths2.get(i);
String loopParentCategoryId = loopJo.getString("parentCategoryId");
if ( thisCategoryId.equals(loopParentCategoryId) ) {
ListViewDataObject new2Depth = new ListViewDataObject(0, 2, loopJo.toString());
mCategoryAdapter.addItem(iLoop, new2Depth);
iLoop++;
}
}
} else if ( dobj.iKey == 2 ) {
// append 3 depth
int iLoop = position+1;
for ( int i = 0; i < mCateDepths3.size(); i++ ) {
JSONObject loopJo = mCateDepths3.get(i);
String loopParentCategoryId = loopJo.getString("parentCategoryId");
if ( thisCategoryId.equals(loopParentCategoryId) ) {
ListViewDataObject new2Depth = new ListViewDataObject(0, 3, loopJo.toString());
mCategoryAdapter.addItem(iLoop, new2Depth);
iLoop++;
}
}
}
}
//list2tree();
mCategoryAdapter.notifyDataSetInvalidated();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
private int getPositionWithCategoryId(String categoryId){
int rtn = -1;
try {
for (int i = 0; i < mCategoryAdapter.getCount(); i++ ) {
ListViewDataObject loopObj = (ListViewDataObject) mCategoryAdapter.getItem(i);
JSONObject loopJo = new JSONObject(loopObj.sJson);
String loopParentCategoryId = loopJo.getString("parentCategoryId");
if (categoryId.equals(loopParentCategoryId)) {
return i;
}
}
} catch ( JSONException e ) {
e.printStackTrace();
}
return rtn;
}
// 이건 한번만 호출하자.
private void list2tree(){
try {
for ( int i = 0; i < mCateDepths1.size(); i++ ) {
JSONObject category = mCateDepths1.get(i);
if ( category.getBoolean("leaf") == false) {
String categoryId = category.getString("categoryId");
append2Depth(categoryId);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void append2Depth(String categoryId){
try {
for ( int i = 0; i < categorys.size(); i++ ) {
JSONObject category = (JSONObject)categorys.get(i);
String parentCategoryId = category.getString("parentCategoryId");
if ( categoryId.equals(parentCategoryId) ) {
mCateDepths2.add(category);
boolean leaf = category.getBoolean("leaf");
if ( category.getBoolean("leaf") == false ) {
String thisCategoryId = category.getString("categoryId");
append3Depth(thisCategoryId);
}
}
}
} catch ( JSONException e ) {
e.printStackTrace();
}
}
private void append3Depth(String categoryId){
try {
for ( int i = 0; i < categorys.size(); i++ ) {
JSONObject category = (JSONObject)categorys.get(i);
String parentCategoryId = category.getString("parentCategoryId");
if ( categoryId.equals(parentCategoryId) ) {
mCateDepths3.add(category);
}
}
} catch ( JSONException e ) {
e.printStackTrace();
}
}
private JSONObject getCategoryWithCategoryId(String cid) {
try {
for ( int i = 0; i < categorys.size(); i++ ) {
JSONObject category = (JSONObject)categorys.get(i);
String categoryId = category.getString("categoryId");
if ( cid.equals(categoryId) ) {
return category;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private int getCategoryIndxWithCategoryId(String cid) {
try {
for ( int i = 0; i < categorys.size(); i++ ) {
JSONObject category = (JSONObject)categorys.get(i);
String categoryId = category.getString("categoryId");
if ( cid.equals(categoryId) ) {
return i;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
private void processRequest() {
/**
ViewerType = 30, 1031, getContentGroupList (보통 리스트)
ViewerType = 200, getPopularityChart (인기순위)
ViewerType = 41, getBundleProductList (묶음)
ViewerType = 310, recommendContentGroupByAssetId (연관)
*/
mTabbar.setVisibility(View.GONE);
//Toast.makeText(mInstance.getActivity(), "ViewerType: " + mCurrCategoryObject.getsViewerType(), Toast.LENGTH_LONG).show();
if ("200".equals(mCurrCategoryObject.getsViewerType())) {
mTabbar.setVisibility(View.VISIBLE);
requestGetPopularityChart();
} else {
mTabbar.setVisibility(View.GONE);
requestGetContentGroupList();
// if ( "0".equals(mCurrCategoryObject.getsViewerType())
// || "10".equals(mCurrCategoryObject.getsViewerType())
// || "20".equals(mCurrCategoryObject.getsViewerType())
// || "30".equals(mCurrCategoryObject.getsViewerType())
// || "60".equals(mCurrCategoryObject.getsViewerType())
// || "1031".equals(mCurrCategoryObject.getsViewerType()) ) {
// requestGetContentGroupList();
// } else if ( "200".equals(mCurrCategoryObject.getsViewerType()) ) {
// mTabbar.setVisibility(View.VISIBLE);
// requestGetPopularityChart();
// } else if ( "41".equals(mCurrCategoryObject.getsViewerType()) ) {
// //
// } else if ( "310".equals(mCurrCategoryObject.getsViewerType()) ) {
// //
// } else {
//
}
}
/**
* http://192.168.40.5:8080/HApplicationServer/getPopularityChart.xml?version=1&terminalKey=9CED3A20FB6A4D7FF35D1AC965F988D2&categoryId=713230&requestItems=weekly
*
* */
// 인기 TOP 20
private void requestGetPopularityChart() {
//String url = mPref.getWebhasServerUrl() + "/getPopularityChart.xml?version=1&terminalKey="+mPref.getWebhasTerminalKey()+"&categoryId=713230&requestItems=weekly";
String url = mPref.getWebhasServerUrl() + "/getPopularityChart.json?version=1&terminalKey="+mPref.getWebhasTerminalKey()+"&categoryId="+mCurrCategoryObject.getsCategoryId()+"&requestItems="+mRequestItems;
JYStringRequest request = new JYStringRequest(mPref, Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
String resultCode = jo.getString("resultCode");
if ( Constants.CODE_WEBHAS_OK.equals(resultCode) ) {
if ( "daily".equals(mRequestItems) ) {
JSONObject dailyChart = jo.getJSONObject("dailyChart");
JSONArray popularityList = dailyChart.getJSONArray("popularityList");
for ( int i = 0; i < popularityList.length(); i++ ) {
JSONObject popularity = popularityList.getJSONObject(i);
ListViewDataObject obj = new ListViewDataObject(i, i, popularity.toString());
mAdapter.addItem(obj);
}
} else if ( "weekly".equals(mRequestItems) ) {
JSONObject weeklyChart = jo.getJSONObject("weeklyChart");
JSONArray popularityList = weeklyChart.getJSONArray("popularityList");
for ( int i = 0; i < popularityList.length(); i++ ) {
JSONObject popularity = popularityList.getJSONObject(i);
ListViewDataObject obj = new ListViewDataObject(i, i, popularity.toString());
mAdapter.addItem(obj);
}
}
} else {
String errorString = jo.getString("errorString");
StringBuilder sb = new StringBuilder();
sb.append("API: action\nresultCode: ").append(resultCode).append("\nerrorString: ").append(errorString);
AlertDialog.Builder alert = new AlertDialog.Builder(mInstance.getActivity());
alert.setPositiveButton("알림", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setMessage(sb.toString());
alert.show();
}
} catch ( JSONException e ) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mProgressDialog.dismiss();
if ( mPref.isLogging() ) { VolleyLog.d(tag, "onErrorResponse(): " + error.getMessage()); }
}
}) {
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("version", String.valueOf(1));
params.put("areaCode", String.valueOf(0));
if ( mPref.isLogging() ) { Log.d(tag, "getParams()" + params.toString()); }
return params;
}
};
mRequestQueue.add(request);
}
//
private void requestGetContentGroupList() {
String url = mPref.getWebhasServerUrl() + "/getContentGroupList.json?version=1&terminalKey="+mPref.getWebhasTerminalKey()+"&contentGroupProfile=2&sortType=notSet"
+ "&categoryId="+mCurrCategoryObject.getsCategoryId();
JYStringRequest request = new JYStringRequest(mPref, Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
String resultCode = jo.getString("resultCode");
if ( Constants.CODE_WEBHAS_OK.equals(resultCode) ) {
JSONArray contentGroupList = jo.getJSONArray("contentGroupList");
for ( int i = 0; i < contentGroupList.length(); i++ ) {
JSONObject contentGroup = contentGroupList.getJSONObject(i);
ListViewDataObject obj = new ListViewDataObject(i, i, contentGroup.toString());
mAdapter.addItem(obj);
}
} else {
String errorString = jo.getString("errorString");
// StringBuilder sb = new StringBuilder();
// sb.append("API: action\nresultCode: ").append(resultCode).append("\nerrorString: ").append(errorString);
// AlertDialog.Builder alert = new AlertDialog.Builder(mInstance.getActivity());
// alert.setPositiveButton("알림", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// });
// alert.setMessage(sb.toString());
// alert.show();
String alertTitle = "안내";
String alertMsg1 = "목록이 없습니다.";
String alertMsg2 = "";
CMAlertUtil.Alert1(mInstance.getActivity(), alertTitle, alertMsg1, alertMsg2, true, false, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}, true);
}
} catch ( JSONException e ) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//mProgressDialog.dismiss();
if ( mPref.isLogging() ) { VolleyLog.d(tag, "onErrorResponse(): " + error.getMessage()); }
}
}) {
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
if ( mPref.isLogging() ) { Log.d(tag, "getParams()" + params.toString()); }
return params;
}
};
mRequestQueue.add(request);
}
//
private void startActivityAssetOrBundle(String assetId, JSONObject product){
try {
String purchasedTime = product.getString("purchasedTime");
if ( purchasedTime.length() > 0 ) {
String productId = product.getString("productId");
Intent intent = new Intent(getActivity(), VodDetailBundleActivity.class);
intent.putExtra("productType", "Bundle");
intent.putExtra("productId", productId);
intent.putExtra("assetId", assetId);
getActivity().startActivity(intent);
} else {
Intent intent = new Intent(this.getActivity(), VodDetailActivity.class);
intent.putExtra("assetId", assetId);
getActivity().startActivity(intent);
}
} catch ( JSONException e ) {
e.printStackTrace();
}
}
// VodMainGridViewAdapter에서 포스터를 클릭했을때 타는 메소드.
// assetInfo를 요청해서, 구매한 VOD인지를 알아낸다.
// 만약 구매 했다면, VodDetailBundleActivity로 이동.
// 만약 구매 안했다면, VodDetailActivity로 이동.
public void onClickBundulPoster(String primaryAssetId) {
mProgressDialog = ProgressDialog.show(mInstance.getActivity(), "", getString(R.string.wait_a_moment));
String terminalKey = mPref.getWebhasTerminalKey();
String encAssetId = null;
try {
encAssetId = URLDecoder.decode(primaryAssetId, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String url = mPref.getWebhasServerUrl() + "/getAssetInfo.json?version=1&terminalKey="+terminalKey+"&assetProfile=9&assetId="+encAssetId;
JYStringRequest request = new JYStringRequest(mPref, Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mProgressDialog.dismiss();
boolean needJumpAsset = true;
try {
JSONObject jo = new JSONObject(response);
JSONObject asset = jo.getJSONObject("asset");
JSONArray productList = asset.getJSONArray("productList");
for ( int i = 0; i < productList.length(); i++ ) {
JSONObject product = (JSONObject)productList.get(i);
String productType = product.getString("productType");
if ( "Bundle".equals(productType) ) {
String assetId = asset.getString("assetId");
startActivityAssetOrBundle(assetId,product);
needJumpAsset = false;
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if ( needJumpAsset == true ) {
// 예외 처리임. 원래 번들(묶음)이면, 여기까지 오면 안되고 위에서 startActivityAssetOrBundle()로 가야된다.
// 묶음상품이였다가, 묶음상품이 아니라고 풀리는 경우가 있다고 해서 아래의 예외 처리 함.
try {
JSONObject jo = new JSONObject(response);
JSONObject asset = jo.getJSONObject("asset");
String assetId = asset.getString("assetId");
Intent intent = new Intent(mInstance.getActivity(), VodDetailActivity.class);
intent.putExtra("assetId", assetId);
getActivity().startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mProgressDialog.dismiss();
if ( mPref.isLogging() ) { VolleyLog.d(tag, "onErrorResponse(): " + error.getMessage()); }
}
}) {
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("version", String.valueOf(1));
params.put("areaCode", String.valueOf(0));
if ( mPref.isLogging() ) { Log.d(tag, "getParams()" + params.toString()); }
return params;
}
};
mRequestQueue.add(request);
}
/**
* IOnBackPressedListener
*/
@Override
public void onBackPressedCallback() {
mTab1TextView.performClick();
}
}
| mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_78/safe/CWE_78__SESSION__func_preg_replace__cat-interpretation_simple_quote.php | 1199 | <?php
/*
Safe sample
input : get the UserData field of $_SESSION
SANITIZE : use of preg_replace
construction : interpretation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = $_SESSION['UserData'];
$tainted = preg_replace('/\'/', '', $tainted);
$query = "cat ' $tainted '";
$ret = system($query);
?> | mit |