answer stringlengths 15 1.25M |
|---|
#include "zflyembodymerger.h"
#include <iostream>
#include <QList>
#include <QDebug>
#include "zjsonobject.h"
#include "zjsonarray.h"
#include "zjsonparser.h"
#include "zjsonfactory.h"
ZFlyEmBodyMerger::ZFlyEmBodyMerger()
{
}
uint64_t ZFlyEmBodyMerger::getFinalLabel(uint64_t label) const
{
return mapLabel(m_mapList, label);
}
std::set<uint64_t> ZFlyEmBodyMerger::getFinalLabel(
const std::set<uint64_t> labelSet) const
{
std::set<uint64_t> mapped;
for (std::set<uint64_t>::const_iterator iter = labelSet.begin();
iter != labelSet.end(); ++iter) {
mapped.insert(getFinalLabel(*iter));
}
return mapped;
}
ZFlyEmBodyMerger::TLabelMap ZFlyEmBodyMerger::getFinalMap() const
{
ZFlyEmBodyMerger::TLabelMap labelMap;
#if 0
QSet<uint64_t> mappedSet;
for (TLabelMapList::const_iterator iter = m_mapList.begin();
iter != m_mapList.end(); ++iter) {
const TLabelMap ¤tLabelMap = *iter;
for (TLabelMap::const_iterator mapIter = currentLabelMap.begin();
mapIter != currentLabelMap.end(); ++mapIter) {
mappedSet.insert(mapIter.value());
}
}
#endif
// std::cout << "Body merger:" << std::endl;
for (TLabelMapList::const_iterator iter = m_mapList.begin();
iter != m_mapList.end(); ++iter) {
const TLabelMap ¤tLabelMap = *iter;
for (TLabelMap::const_iterator mapIter = currentLabelMap.begin();
mapIter != currentLabelMap.end(); ++mapIter) {
if (!labelMap.contains(mapIter.key())) {
labelMap[mapIter.key()] = getFinalLabel(mapIter.key());
}
}
}
return labelMap;
}
uint64_t ZFlyEmBodyMerger::mapLabel(const TLabelMap &labelMap, uint64_t label)
{
if (labelMap.contains(label)) {
return labelMap[label];
}
return label;
}
uint64_t ZFlyEmBodyMerger::mapLabel(
const TLabelMapList &labelMap, uint64_t label)
{
uint64_t finalLabel = label;
for (TLabelMapList::const_iterator iter = labelMap.begin();
iter != labelMap.end(); ++iter) {
const TLabelMap ¤tLabelMap = *iter;
finalLabel = mapLabel(currentLabelMap, finalLabel);
}
return finalLabel;
}
void ZFlyEmBodyMerger::pushMap(uint64_t label1, uint64_t label2)
{
TLabelMap labelMap;
labelMap[label1] = label2;
pushMap(labelMap);
}
void ZFlyEmBodyMerger::pushMap(const TLabelMap &map)
{
if (!map.isEmpty()) {
m_mapList.append(map);
}
}
void ZFlyEmBodyMerger::pushMap(const TLabelSet &labelSet)
{
if (labelSet.size() > 1) {
uint64_t minLabel = 0;
for (TLabelSet::const_iterator iter = labelSet.begin();
iter != labelSet.end(); ++iter) {
if (minLabel == 0 || minLabel > *iter) {
minLabel = *iter;
}
}
TLabelMap labelMap;
if (minLabel > 0) {
for (TLabelSet::const_iterator iter = labelSet.begin();
iter != labelSet.end(); ++iter) {
if (*iter != minLabel) {
labelMap[*iter] = minLabel;
}
}
pushMap(labelMap);
}
}
}
ZFlyEmBodyMerger::TLabelMap ZFlyEmBodyMerger::undo()
{
TLabelMap labelMap;
if (!m_mapList.isEmpty()) {
labelMap = m_mapList.takeLast();
m_undoneMapStack.push(labelMap);
}
return labelMap;
}
void ZFlyEmBodyMerger::redo()
{
if (!m_undoneMapStack.isEmpty()) {
TLabelMap labelMap = m_undoneMapStack.pop();
pushMap(labelMap);
}
}
void ZFlyEmBodyMerger::print() const
{
int index = 1;
std::cout << "Body merger:" << std::endl;
for (TLabelMapList::const_iterator iter = m_mapList.begin();
iter != m_mapList.end(); ++iter, ++index) {
const TLabelMap ¤tLabelMap = *iter;
std::cout << "--" << index << "--" << std::endl;
for (TLabelMap::const_iterator mapIter = currentLabelMap.begin();
mapIter != currentLabelMap.end(); ++mapIter) {
std::cout << mapIter.key() << " -> " << mapIter.value() << std::endl;
}
}
}
void ZFlyEmBodyMerger::clear()
{
m_mapList.clear();
m_undoneMapStack.clear();
}
bool ZFlyEmBodyMerger::isMerged(uint64_t label) const
{
QSet<uint64_t> labelSet;
for (TLabelMapList::const_iterator iter = m_mapList.begin();
iter != m_mapList.end(); ++iter) {
const TLabelMap ¤tLabelMap = *iter;
// std::cout << "--" << index << "--" << std::endl;
for (TLabelMap::const_iterator mapIter = currentLabelMap.begin();
mapIter != currentLabelMap.end(); ++mapIter) {
labelSet.insert(mapIter.key());
labelSet.insert(mapIter.value());
// std::cout << mapIter.key() << " -> " << mapIter.value() << std::endl;
}
}
return labelSet.contains(label);
}
//ZJsonObject ZFlyEmBodyMerger::toJsonObject() const
//void ZFlyEmBodyMerger::loadJsonObject(const ZJsonObject &obj)
ZJsonArray ZFlyEmBodyMerger::toJsonArray() const
{
return ZJsonFactory::MakeJsonArray(getFinalMap());
}
void ZFlyEmBodyMerger::loadJson(const ZJsonArray &obj)
{
clear();
if (!obj.isEmpty()) {
TLabelMap labelMap;
for (size_t i = 0; i < obj.size(); ++i) {
ZJsonArray pairJson(obj.at(i), ZJsonValue::<API key>);
int64_t key = ZJsonParser::integerValue(pairJson.at(0));
int64_t value = ZJsonParser::integerValue(pairJson.at(1));
if (key > 0 && value > 0) {
labelMap[(uint64_t) key] = (uint64_t) value;
}
}
pushMap(labelMap);
}
}
std::string ZFlyEmBodyMerger::toJsonString() const
{
return toJsonArray().dumpString(0);
}
void ZFlyEmBodyMerger::decodeJsonString(const std::string &str)
{
ZJsonArray obj;
obj.decodeString(str.c_str());
loadJson(obj);
}
QList<uint64_t> ZFlyEmBodyMerger::<API key>(uint64_t finalLabel) const
{
QList<uint64_t> list = getFinalMap().keys(finalLabel);
list.append(finalLabel);
#ifdef _DEBUG_
qDebug() << list;
#endif
return list;
}
QSet<uint64_t> ZFlyEmBodyMerger::getOriginalLabelSet(uint64_t finalLabel) const
{
QSet<uint64_t> labelSet;
QList<uint64_t> labelList = <API key>(finalLabel);
for (QList<uint64_t>::const_iterator iter = labelList.begin();
iter != labelList.end(); ++iter) {
uint64_t label = *iter;
labelSet.insert(label);
}
// labelSet.fromList(<API key>(finalLabel));
#ifdef _DEBUG_
qDebug() << labelSet;
#endif
return labelSet;
}
bool ZFlyEmBodyMerger::isEmpty() const
{
return m_mapList.isEmpty();
} |
#include "AbstractMeshNode.hpp"
#include <iostream>
#include <GL/glew.h>
#include <glm/mat4x4.hpp>
#include "../renderer/Mesh.hpp"
#include "../renderer/MeshRenderer.hpp"
#include "../renderer/ShaderProgram.hpp"
using namespace std;
AbstractMeshNode::AbstractMeshNode(MeshRenderer& renderer, Mesh& mesh)
: renderer(renderer), mesh(mesh) {
// Create the VAO
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, mesh.getVBO());
glBindBuffer(<API key>, mesh.getIBO());
renderer.setVertexAttribs();
glBindVertexArray(0);
}
AbstractMeshNode::AbstractMeshNode(const AbstractMeshNode& orig)
: AbstractMeshNode(orig.renderer, orig.mesh) {
}
AbstractMeshNode::~AbstractMeshNode() {
}
void AbstractMeshNode::render(glm::mat4 base) {
renderer.render(mesh, vao, base);
} |
import functools
import unittest2
from sentry import app
from sentry.db import get_backend
def with_settings(**settings):
def wrapped(func):
@functools.wraps(func)
def _wrapped(*args, **kwargs):
defaults = {}
for k, v in settings.iteritems():
defaults[k] = app.config.get(k)
app.config[k] = v
try:
return func(*args, **kwargs)
finally:
for k, v in defaults.iteritems():
app.config[k] = v
return _wrapped
return wrapped
class BaseTest(unittest2.TestCase):
def setUp(self):
# XXX: might be a better way to do do this
app.config['DATASTORE'] = {
'ENGINE': 'sentry.db.backends.redis.RedisBackend',
'OPTIONS': {
'db': 9
}
}
app.config['CLIENT'] = 'sentry.client.base.SentryClient'
app.db = get_backend(app)
# Flush the Redis instance
app.db.conn.flushdb()
self.client = app.test_client() |
input:-webkit-autofill {
color: #003274 !important;
background-color: #ffffff;
}
#login {
width: 300px;
margin: 0 auto;
font-family: bob-regular;
color: #003274;
}
#login input
{
direction: ltr;
background: #ffffff;
font-weight: bold;
font-size: 13pt;
}
#login input:hover
{
background-color: #C2DCFF;
}
.dtmail {
margin-bottom: 10px;
}
#login a
{
color: #003274;
text-decoration: none;
}
#login a:hover
{
text-decoration: underline;
}
#login input[type='text'],[type='password']
{
color: #003274 !important;
border: 1px solid #0249A5;
padding: 15px 25px;
font-family: Helvetica, Arial, Tahoma, Geneva,Sens-Sarif;
}
#login input[type='submit']
{
color: #003274;
border: 1px solid #0249A5;
margin-top: 15px;
padding: 15px 30px;
margin-right: 80px;
margin-bottom: 10px;
}
body {
font-family: Helvetica, Arial, Tahoma, Geneva,Sens-Sarif;
} |
#include "Tuple.h"
namespace yarpl {
std::atomic<int> Tuple::createdCount;
std::atomic<int> Tuple::destroyedCount;
std::atomic<int> Tuple::instanceCount;
} |
# -*- coding: utf-8 -*-
"""Tests for cookiecutter's output directory customization feature."""
import pytest
from cookiecutter import main
@pytest.fixture
def context():
"""Fixture to return a valid context as known from a cookiecutter.json."""
return {
u'cookiecutter': {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
}
@pytest.fixture
def output_dir(tmpdir):
return str(tmpdir.mkdir('output'))
@pytest.fixture
def template(tmpdir):
template_dir = tmpdir.mkdir('template')
template_dir.join('cookiecutter.json').ensure(file=True)
return str(template_dir)
@pytest.fixture(autouse=True)
def mock_gen_context(mocker, context):
mocker.patch('cookiecutter.main.generate_context', return_value=context)
@pytest.fixture(autouse=True)
def mock_prompt(mocker):
mocker.patch('cookiecutter.main.prompt_for_config')
@pytest.fixture(autouse=True)
def mock_replay(mocker):
mocker.patch('cookiecutter.main.dump')
def test_api_invocation(mocker, template, output_dir, context):
mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
main.cookiecutter(template, output_dir=output_dir)
mock_gen_files.<API key>(
repo_dir=template,
context=context,
overwrite_if_exists=False,
skip_if_file_exists=False,
output_dir=output_dir
)
def <API key>(mocker, template, context):
mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
main.cookiecutter(template)
mock_gen_files.<API key>(
repo_dir=template,
context=context,
overwrite_if_exists=False,
skip_if_file_exists=False,
output_dir='.'
) |
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
if (!common.hasCrypto) {
common.skip('missing crypto');
return;
}
const crypto = require('crypto');
// Test hashing
const a1 = crypto.createHash('sha1').update('Test123').digest('hex');
const a2 = crypto.createHash('sha256').update('Test123').digest('base64');
const a3 = crypto.createHash('sha512').update('Test123').digest(); // buffer
const a4 = crypto.createHash('sha1').update('Test123').digest('buffer');
// stream interface
let a5 = crypto.createHash('sha512');
a5.end('Test123');
a5 = a5.read();
let a6 = crypto.createHash('sha512');
a6.write('Te');
a6.write('st');
a6.write('123');
a6.end();
a6 = a6.read();
let a7 = crypto.createHash('sha512');
a7.end();
a7 = a7.read();
let a8 = crypto.createHash('sha512');
a8.write('');
a8.end();
a8 = a8.read();
if (!common.hasFipsCrypto) {
const a0 = crypto.createHash('md5').update('Test123').digest('latin1');
assert.strictEqual(
a0,
'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c',
'Test MD5 as latin1'
);
}
assert.strictEqual(a1, '<SHA1-like>', 'Test SHA1');
assert.strictEqual(a2, '<API key>+y+hq5R8dnx9l4=',
'Test SHA256 as base64');
assert.deepStrictEqual(
a3,
Buffer.from(
'\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' +
'\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' +
'\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' +
'\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' +
'\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'',
'latin1'),
'Test SHA512 as assumed buffer');
assert.deepStrictEqual(
a4,
Buffer.from('<SHA1-like>', 'hex'),
'Test SHA1'
);
// stream interface should produce the same result.
assert.deepStrictEqual(a5, a3, 'stream interface is consistent');
assert.deepStrictEqual(a6, a3, 'stream interface is consistent');
assert.notStrictEqual(a7, undefined, 'no data should return data');
assert.notStrictEqual(a8, undefined, 'empty string should generate data');
// Test multiple updates to same hash
const h1 = crypto.createHash('sha1').update('Test123').digest('hex');
const h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex');
assert.strictEqual(h1, h2, 'multipled updates');
// Test hashing for binary files
const fn = path.join(common.fixturesDir, 'sample.png');
const sha1Hash = crypto.createHash('sha1');
const fileStream = fs.createReadStream(fn);
fileStream.on('data', function(data) {
sha1Hash.update(data);
});
fileStream.on('close', function() {
assert.strictEqual(sha1Hash.digest('hex'),
'<SHA1-like>',
'Test SHA1 of sample.png');
});
// Issue #2227: unknown digest method should throw an error.
assert.throws(function() {
crypto.createHash('xyzzy');
}, /Digest method not supported/);
// Default UTF-8 encoding
const hutf8 = crypto.createHash('sha512').update('УТФ-8 text').digest('hex');
assert.strictEqual(
hutf8,
'<SHA256-like>' +
'<SHA256-like>');
assert.notStrictEqual(
hutf8,
crypto.createHash('sha512').update('УТФ-8 text', 'latin1').digest('hex'));
const h3 = crypto.createHash('sha256');
h3.digest();
assert.throws(function() {
h3.digest();
}, /Digest already called/);
assert.throws(function() {
h3.update('foo');
}, /Digest already called/);
assert.throws(function() {
crypto.createHash('sha256').digest('ucs2');
}, /^Error: hash\.digest\(\) does not support UTF-16$/); |
Behavior = new (function() {
var that = this;
// initial values do not matter because they are set by this.resetBehavior()
var behavior_name = "";
var <API key> = "";
var tags = "";
var author = "";
var creation_date = "";
var private_variables = []; // {key, value}
var default_userdata = []; // {key, value}
var private_functions = []; // {name, params}
var behavior_parameters = []; // {type, name, default, label, hint, additional}
var interface_outcomes = [];
var <API key> = [];
var <API key> = [];
var manual_code_import = "";
var manual_code_init = "";
var manual_code_create = "";
var manual_code_func = "";
var comment_notes = [];
var root_sm = undefined;
this.getBehaviorName = function() {
return behavior_name;
}
this.setBehaviorName = function(_behavior_name) {
behavior_name = _behavior_name;
}
this.<API key> = function() {
return <API key>;
}
this.<API key> = function(<API key>) {
<API key> = <API key>;
}
this.getTags = function() {
return tags;
}
this.setTags = function(_tags) {
tags = _tags;
}
this.getAuthor = function() {
return author;
}
this.setAuthor = function(_author) {
author = _author;
}
this.getCreationDate = function() {
return creation_date;
}
this.setCreationDate = function(_creation_date) {
creation_date = _creation_date;
}
this.getPrivateVariables = function() {
return private_variables;
}
this.setPrivateVariables = function(_private_variables) {
private_variables = _private_variables;
}
this.<API key> = function(old_key, new_key, new_value) {
for (var i = private_variables.length - 1; i >= 0; i
if (private_variables[i].key == old_key) {
private_variables[i].key = new_key;
private_variables[i].value = new_value;
}
};
}
this.getDefaultUserdata = function() {
return default_userdata;
}
this.setDefaultUserdata = function(_default_userdata) {
default_userdata = _default_userdata;
}
this.<API key> = function(old_key, new_key, new_value) {
for (var i = default_userdata.length - 1; i >= 0; i
if (default_userdata[i].key == old_key) {
default_userdata[i].key = new_key;
default_userdata[i].value = new_value;
}
};
}
this.getPrivateFunctions = function() {
return private_functions;
}
this.setPrivateFunctions = function(_private_functions) {
private_functions = _private_functions;
}
this.<API key> = function(old_name, new_name, new_params) {
for (var i = private_functions.length - 1; i >= 0; i
if (private_functions[i].name == old_name) {
private_functions[i].name = new_name;
private_functions[i].params = new_params;
}
};
}
this.<API key> = function() {
return behavior_parameters;
}
this.<API key> = function(<API key>) {
behavior_parameters = <API key>;
}
this.<API key> = function(old_name, new_value, key) {
for (var i = behavior_parameters.length - 1; i >= 0; i
if (behavior_parameters[i].name == old_name) {
if (key == "name")
behavior_parameters[i].name = new_value;
else if (key == "type")
behavior_parameters[i].type = new_value;
else if (key == "default")
behavior_parameters[i].default = new_value;
else if (key == "label")
behavior_parameters[i].label = new_value;
else if (key == "hint")
behavior_parameters[i].hint = new_value;
else if (key == "additional")
behavior_parameters[i].additional = new_value;
}
};
}
this.<API key> = function(target_name) {
var to_remove = behavior_parameters.findElement(function(element) {
return element.name == target_name;
});
behavior_parameters.remove(to_remove);
}
this.<API key> = function() {
return interface_outcomes;
}
this.addInterfaceOutcome = function(to_add) {
interface_outcomes.push(to_add);
root_sm.addOutcome(to_add);
}
this.<API key> = function(to_remove) {
interface_outcomes.remove(to_remove);
root_sm.removeOutcome(to_remove);
}
this.<API key> = function(old_value, new_value) {
for (var i = interface_outcomes.length - 1; i >= 0; i
if (interface_outcomes[i] == old_value) {
interface_outcomes[i] = new_value;
root_sm.updateOutcome(old_value, new_value);
}
};
}
this.<API key> = function() {
return <API key>;
}
this.<API key> = function(<API key>) {
<API key> = <API key>;
root_sm.setInputKeys(<API key>);
}
this.<API key> = function(key) {
<API key>.push(key);
root_sm.setInputKeys(<API key>);
}
this.<API key> = function(key) {
<API key>.remove(key);
root_sm.setInputKeys(<API key>);
}
this.<API key> = function(old_value, new_value) {
for (var i = <API key>.length - 1; i >= 0; i
if (<API key>[i] == old_value) {
<API key>[i] = new_value;
root_sm.getInputKeys().remove(old_value);
root_sm.getInputKeys().push(new_value);
}
};
}
this.<API key> = function() {
return <API key>;
}
this.<API key> = function(<API key>) {
<API key> = <API key>;
root_sm.setOutputKeys(<API key>);
}
this.<API key> = function(key) {
<API key>.push(key);
root_sm.setOutputKeys(<API key>);
}
this.<API key> = function(key) {
<API key>.remove(key);
root_sm.setOutputKeys(<API key>);
}
this.<API key> = function(old_value, new_value) {
for (var i = <API key>.length - 1; i >= 0; i
if (<API key>[i] == old_value)
<API key>[i] = new_value;
root_sm.getOutputKeys().remove(old_value);
root_sm.getOutputKeys().push(new_value);
};
}
this.getManualCodeImport = function() {
return manual_code_import;
}
this.setManualCodeImport = function(_manual_code_import) {
manual_code_import = _manual_code_import;
}
this.getManualCodeInit = function() {
return manual_code_init;
}
this.setManualCodeInit = function(_manual_code_init) {
manual_code_init = _manual_code_init;
}
this.getManualCodeCreate = function() {
return manual_code_create;
}
this.setManualCodeCreate = function(_manual_code_create) {
manual_code_create = _manual_code_create;
}
this.getManualCodeFunc = function() {
return manual_code_func;
}
this.setManualCodeFunc = function(_manual_code_func) {
manual_code_func = _manual_code_func;
}
this.getCommentNotes = function() {
return comment_notes;
}
this.addCommentNote = function(new_note) {
comment_notes.push(new_note);
}
this.removeCommentNote = function(note) {
comment_notes.remove(note);
}
this.clearCommentNotes = function() {
comment_notes = [];
}
this.getStatemachine = function() {
if (root_sm == undefined) {
T.debugWarn("Trying to access undefined root state machine!");
}
return root_sm;
}
this.setStatemachine = function(_root_sm) {
root_sm = _root_sm;
}
this.resetBehavior = function() {
behavior_name = "";
<API key> = "";
author = "";
creation_date = "";
private_variables = []; // {key, value}
default_userdata = []; // {key, value}
private_functions = []; // {name, params}
behavior_parameters = []; // {type, name, default, label, hint, additional}
interface_outcomes = [];
<API key> = [];
<API key> = [];
manual_code_import = "";
manual_code_init = "";
manual_code_create = "";
manual_code_func = "";
comment_notes = [];
root_sm = new Statemachine("", new <API key>([], [], []));
}
this.createNames = function() {
var result = {
behavior_name: '',
rosnode_name: '',
class_name: '',
file_name: ''
};
var namespace = (UI.Settings.getPackageNamespace() != '')? UI.Settings.getPackageNamespace() + "_" : "";
result.behavior_name = behavior_name;
result.rosnode_name = namespace + 'behavior_' + behavior_name.toLowerCase().replace(/ /g, "_");
result.class_name = behavior_name.replace(/ /g, "") + 'SM';
result.file_name = behavior_name.toLowerCase().replace(/ /g, "_") + '_sm.py';
result.file_name_tmp = behavior_name.toLowerCase().replace(/ /g, "_") + '_sm_tmp.py';
return result;
}
this.createStructureInfo = function() {
var result = [];
<API key>(root_sm, result);
return result;
}
var <API key> = function(s, info) {
var result = {};
result.path = s.getStatePath();
result.outcomes = s.getOutcomes();
result.transitions = [];
if (s.getContainer() != undefined) {
result.autonomy = s.getAutonomy();
var transitions = s.getContainer().getTransitions();
for (var i=0; i<result.outcomes.length; i++) {
var transition = transitions.findElement(function(element) {
return element.getFrom().getStateName() == s.getStateName() && element.getOutcome() == result.outcomes[i];
});
var target_name = transition.getTo().getStateName();
if (s.getContainer().isConcurrent() && transition.getTo().getStateClass() == ':CONDITION') {
target_name = target_name.split('
}
result.transitions.push(target_name);
}
}
result.children = [];
if (s instanceof BehaviorState) {
s = s.<API key>();
}
if (s instanceof Statemachine) {
var children = s.getStates();
for (var c=0; c<children.length; c++) {
var child = children[c];
result.children.push(children[c].getStateName());
<API key>(children[c], info);
}
}
info.push(result);
}
}) (); |
#pragma once
#include <vector>
#include <Poco/SharedPtr.h>
#include "model/Location.h"
#include "model/Gateway.h"
#include "service/Single.h"
#include "service/Relation.h"
namespace BeeeOn {
/**
* Locations management.
*/
class LocationService {
public:
typedef Poco::SharedPtr<LocationService> Ptr;
virtual ~LocationService();
virtual void createIn(RelationWithData<Location, Gateway> &input) = 0;
virtual bool fetchFrom(Relation<Location, Gateway> &input) = 0;
virtual void fetchBy(Relation<std::vector<Location>, Gateway> &input) = 0;
virtual bool updateIn(RelationWithData<Location, Gateway> &input) = 0;
virtual bool remove(Single<Location> &input) = 0;
virtual bool removeFrom(Relation<Location, Gateway> &input) = 0;
};
} |
from __future__ import with_statement
import datetime
import logging
import pytz
import rdflib
from django.conf import settings
from humfrey.update.transform.base import Transform
from humfrey.update.uploader import Uploader
from humfrey.sparql.endpoint import Endpoint
from humfrey.utils.namespaces import NS
logger = logging.getLogger(__name__)
class Upload(Transform):
formats = {
'rdf': 'xml',
'n3': 'n3',
'ttl': 'n3',
'nt': 'nt',
}
created_query = """
SELECT ?date WHERE {
GRAPH %(graph)s {
%(graph)s dcterms:created ?date
}
}
"""
site_timezone = pytz.timezone(settings.TIME_ZONE)
def __init__(self, graph_name, method='PUT'):
self.graph_name = rdflib.URIRef(graph_name)
self.method = method
def execute(self, transform_manager, input):
transform_manager.start(self, [input])
logger.debug("Starting upload of %r", input)
extension = input.rsplit('.', 1)[-1]
try:
serializer = self.formats[extension]
except KeyError:
logger.exception("Unrecognized RDF extension: %r", extension)
raise
graph = rdflib.ConjunctiveGraph()
graph.parse(open(input, 'r'),
format=serializer,
publicID=self.graph_name)
logger.debug("Parsed graph")
datetime_now = self.site_timezone.localize(datetime.datetime.now().replace(microsecond=0))
modified = graph.value(self.graph_name, NS['dcterms'].modified,
default=rdflib.Literal(datetime_now))
created = graph.value(self.graph_name, NS['dcterms'].created)
if not created:
logger.debug("Getting created date from %r", transform_manager.store.query_endpoint)
endpoint = Endpoint(transform_manager.store.query_endpoint)
results = list(endpoint.query(self.created_query % {'graph': self.graph_name.n3()}))
if results:
created = results[0].date
else:
created = modified
graph += (
(self.graph_name, NS.rdf.type, NS.sd.Graph),
(self.graph_name, NS.dcterms.modified, modified),
(self.graph_name, NS.dcterms.created, created),
)
logger.debug("About to serialize")
output = transform_manager('rdf')
with open(output, 'w') as f:
graph.serialize(f)
logger.debug("Serialization done; about to upload")
uploader = Uploader()
uploader.upload(stores=(transform_manager.store,),
graph_name=self.graph_name,
filename=output,
method=self.method,
mimetype='application/rdf+xml')
logger.debug("Upload complete")
transform_manager.end([self.graph_name])
transform_manager.touched_graph(self.graph_name) |
# Table of Contents (2)
## Description and main features
This extension adds a small button in the main toolbar, which enables to collect all running headers in the notebook and display them in a floating window.

The table of contents is automatically updated when modifications occur in the notebook. The toc window can be moved and resized, the table of contents can be collapsed or the window can be completely hidden. The position, dimensions, and states (that is 'collapsed' and 'hidden' states) are remembered (actually stored in the notebook's metadata) and restored on the next session. The floating window also provides two links in its header for further functionalities:
- the "n" link toggles automatic numerotation of all header lines
- the "t" link toggles a toc cell in the notebook, which contains the actual table of contents, possibly with the numerotation of the different sections.
The state of these two toggles is memorized and restored on reload.

## Configuration
The initial configuration can be given using the IPython-contrib nbextensions facility. The maximum depth of headers to display on toc can be precised there (with a default of 4), as well as the state of the toc cell (default: false, ie not present) and the numbering of headers (true by default). The differents states and position of the floating window have reasonable defaults and can be modfied per notebook).
# Testing
- At loading of the notebook, configuration and initial rendering of the table of contents were fired on the event "notebook_loaded.Notebook". Curiously, it happened that this event was either not always fired or detected. Thus I rely here on a combination of "notebook_loaded.Notebook" and "kernel_ready.Kernel" instead.
- This extension also includes a quick workaround as described in https://github.com/ipython-contrib/<API key>/issues/429
## History
- This extension was adapted by minrk https://github.com/minrk/ipython_extensions
from https://gist.github.com/magican/5574556
- Added to the ipython-contrib/<API key> repo by @JanSchulz
- @junasch, automatic update on markdown rendering,
- @JanSchulz, enable maths in headers links
- @jfbercher december 06, 2015
- @jfbercher december 24, 2015 -- nested numbering in toc-window, following the fix by [@paulovn](https://github.com/minrk/ipython_extensions/pull/53) in @minrk's repo. December 30-31, updated config in toc2.yaml to enable choosing the initial visible state of toc_window via a checkbox ; and now resizable.
- @slonik-az february 13, 2016. rewritten toc numberings (more robust version), fixed problems with skipped heading levels, some code cleanup
- @jfbercher february 21, 2016. Fixed some issues when resizing the toc window. Now avoid overflows, clip the text and add a scrollbar.
- @jfbercher february 22, 2016. Add current toc number to headings anchors. This enable to get unique anchors for recurring headings with the same text. An anchor with the original ID is still created and can be used (but toc uses the new ones!). It is also possible to directly add an html anchor within the heading text. This is taken into account when building toc links (see comments in code). |
#include "ash/system/tray/<API key>.h"
namespace ash {
SystemTrayNotifier::SystemTrayNotifier() {
}
SystemTrayNotifier::~SystemTrayNotifier() {
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.RemoveObserver(observer);
}
void SystemTrayNotifier::AddAudioObserver(AudioObserver* observer) {
audio_observers_.AddObserver(observer);
}
void SystemTrayNotifier::RemoveAudioObserver(AudioObserver* observer) {
audio_observers_.RemoveObserver(observer);
}
void SystemTrayNotifier::<API key>(BluetoothObserver* observer) {
<API key>.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(BluetoothObserver* observer) {
<API key>.RemoveObserver(observer);
}
void SystemTrayNotifier::<API key>(BrightnessObserver* observer) {
<API key>.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(
BrightnessObserver* observer) {
<API key>.RemoveObserver(observer);
}
void SystemTrayNotifier::AddCapsLockObserver(CapsLockObserver* observer) {
<API key>.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(CapsLockObserver* observer) {
<API key>.RemoveObserver(observer);
}
void SystemTrayNotifier::AddClockObserver(ClockObserver* observer) {
clock_observers_.AddObserver(observer);
}
void SystemTrayNotifier::RemoveClockObserver(ClockObserver* observer) {
clock_observers_.RemoveObserver(observer);
}
void SystemTrayNotifier::AddDriveObserver(DriveObserver* observer) {
drive_observers_.AddObserver(observer);
}
void SystemTrayNotifier::RemoveDriveObserver(DriveObserver* observer) {
drive_observers_.RemoveObserver(observer);
}
void SystemTrayNotifier::AddIMEObserver(IMEObserver* observer) {
ime_observers_.AddObserver(observer);
}
void SystemTrayNotifier::RemoveIMEObserver(IMEObserver* observer) {
ime_observers_.RemoveObserver(observer);
}
void SystemTrayNotifier::AddLocaleObserver(LocaleObserver* observer) {
locale_observers_.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(LocaleObserver* observer) {
locale_observers_.RemoveObserver(observer);
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.RemoveObserver(observer);
}
void SystemTrayNotifier::<API key>(
PowerStatusObserver* observer) {
<API key>.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(
PowerStatusObserver* observer) {
<API key>.RemoveObserver(observer);
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.RemoveObserver(observer);
}
void SystemTrayNotifier::AddUpdateObserver(UpdateObserver* observer) {
update_observers_.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(UpdateObserver* observer) {
update_observers_.RemoveObserver(observer);
}
void SystemTrayNotifier::AddUserObserver(UserObserver* observer) {
user_observers_.AddObserver(observer);
}
void SystemTrayNotifier::RemoveUserObserver(UserObserver* observer) {
user_observers_.RemoveObserver(observer);
}
#if defined(OS_CHROMEOS)
void SystemTrayNotifier::AddNetworkObserver(NetworkObserver* observer) {
network_observers_.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(NetworkObserver* observer) {
network_observers_.RemoveObserver(observer);
}
void SystemTrayNotifier::AddVpnObserver(NetworkObserver* observer) {
vpn_observers_.AddObserver(observer);
}
void SystemTrayNotifier::RemoveVpnObserver(NetworkObserver* observer) {
vpn_observers_.RemoveObserver(observer);
}
void SystemTrayNotifier::AddSmsObserver(SmsObserver* observer) {
sms_observers_.AddObserver(observer);
}
void SystemTrayNotifier::RemoveSmsObserver(SmsObserver* observer) {
sms_observers_.RemoveObserver(observer);
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.RemoveObserver(observer);
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.AddObserver(observer);
}
void SystemTrayNotifier::<API key>(
<API key>* observer) {
<API key>.RemoveObserver(observer);
}
#endif
void SystemTrayNotifier::<API key>(
<API key> notify) {
FOR_EACH_OBSERVER(
<API key>,
<API key>,
<API key>(notify));
}
void SystemTrayNotifier::NotifyVolumeChanged(float level) {
FOR_EACH_OBSERVER(AudioObserver,
audio_observers_,
OnVolumeChanged(level));
}
void SystemTrayNotifier::NotifyMuteToggled() {
FOR_EACH_OBSERVER(AudioObserver,
audio_observers_,
OnMuteToggled());
}
void SystemTrayNotifier::<API key>() {
FOR_EACH_OBSERVER(BluetoothObserver,
<API key>,
OnBluetoothRefresh());
}
void SystemTrayNotifier::<API key>() {
FOR_EACH_OBSERVER(BluetoothObserver,
<API key>,
<API key>());
}
void SystemTrayNotifier::<API key>(double level,
bool user_initiated) {
FOR_EACH_OBSERVER(
BrightnessObserver,
<API key>,
OnBrightnessChanged(level, user_initiated));
}
void SystemTrayNotifier::<API key>(
bool enabled,
bool <API key>) {
FOR_EACH_OBSERVER(CapsLockObserver,
<API key>,
OnCapsLockChanged(enabled, <API key>));
}
void SystemTrayNotifier::NotifyRefreshClock() {
FOR_EACH_OBSERVER(ClockObserver, clock_observers_, Refresh());
}
void SystemTrayNotifier::<API key>() {
FOR_EACH_OBSERVER(ClockObserver,
clock_observers_,
OnDateFormatChanged());
}
void SystemTrayNotifier::<API key>() {
FOR_EACH_OBSERVER(ClockObserver,
clock_observers_,
<API key>());
}
void SystemTrayNotifier::NotifyRefreshDrive(<API key>& list) {
FOR_EACH_OBSERVER(DriveObserver,
drive_observers_,
OnDriveRefresh(list));
}
void SystemTrayNotifier::NotifyRefreshIME(bool show_message) {
FOR_EACH_OBSERVER(IMEObserver,
ime_observers_,
OnIMERefresh(show_message));
}
void SystemTrayNotifier::<API key>(bool show_login_button) {
FOR_EACH_OBSERVER(<API key>,
<API key>,
<API key>(show_login_button));
}
void SystemTrayNotifier::NotifyLocaleChanged(
LocaleObserver::Delegate* delegate,
const std::string& cur_locale,
const std::string& from_locale,
const std::string& to_locale) {
FOR_EACH_OBSERVER(
LocaleObserver,
locale_observers_,
OnLocaleChanged(delegate, cur_locale, from_locale, to_locale));
}
void SystemTrayNotifier::<API key>(
const PowerSupplyStatus& power_status) {
FOR_EACH_OBSERVER(PowerStatusObserver,
<API key>,
<API key>(power_status));
}
void SystemTrayNotifier::<API key>() {
FOR_EACH_OBSERVER(<API key>,
<API key>,
<API key>());
}
void SystemTrayNotifier::<API key>() {
FOR_EACH_OBSERVER(<API key>,
<API key>,
<API key>());
}
void SystemTrayNotifier::<API key>(
UpdateObserver::UpdateSeverity severity) {
FOR_EACH_OBSERVER(UpdateObserver,
update_observers_,
OnUpdateRecommended(severity));
}
void SystemTrayNotifier::NotifyUserUpdate() {
FOR_EACH_OBSERVER(UserObserver,
user_observers_,
OnUserUpdate());
}
#if defined(OS_CHROMEOS)
void SystemTrayNotifier::<API key>(const NetworkIconInfo &info) {
FOR_EACH_OBSERVER(NetworkObserver,
network_observers_,
OnNetworkRefresh(info));
}
void SystemTrayNotifier::<API key>(
NetworkTrayDelegate* delegate,
NetworkObserver::MessageType message_type,
NetworkObserver::NetworkType network_type,
const base::string16& title,
const base::string16& message,
const std::vector<base::string16>& links) {
FOR_EACH_OBSERVER(NetworkObserver,
network_observers_,
SetNetworkMessage(
delegate,
message_type,
network_type,
title,
message,
links));
}
void SystemTrayNotifier::<API key>(
NetworkObserver::MessageType message_type) {
FOR_EACH_OBSERVER(NetworkObserver,
network_observers_,
ClearNetworkMessage(message_type));
}
void SystemTrayNotifier::<API key>(const NetworkIconInfo &info) {
FOR_EACH_OBSERVER(NetworkObserver,
vpn_observers_,
OnNetworkRefresh(info));
}
void SystemTrayNotifier::<API key>() {
FOR_EACH_OBSERVER(NetworkObserver,
network_observers_,
OnWillToggleWifi());
}
void SystemTrayNotifier::NotifyAddSmsMessage(
const base::DictionaryValue& message) {
FOR_EACH_OBSERVER(SmsObserver, sms_observers_, AddMessage(message));
}
void SystemTrayNotifier::<API key>() {
FOR_EACH_OBSERVER(<API key>, <API key>,
<API key>());
}
void SystemTrayNotifier::<API key>(
const base::Closure& stop_callback,
const base::string16& sharing_app_name) {
FOR_EACH_OBSERVER(<API key>, <API key>,
<API key>(stop_callback, sharing_app_name));
}
void SystemTrayNotifier::<API key>() {
FOR_EACH_OBSERVER(<API key>, <API key>,
OnScreenCaptureStop());
}
#endif // OS_CHROMEOS
} // namespace ash |
package edu.stanford.isis.atb.domain.template;
/**
* @author Vitaliy Semeshko
*/
public enum GeometricShapeType {
Point,
Circle,
Polyline,
Ellipse,
MultiPoint;
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: <API key>.cpp
Label Definition File: <API key>.label.xml
Template File: sources-sinks-65a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete []
* Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer
*
* */
#include "std_testcase.h"
namespace <API key>
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(twoIntsStruct * data);
void bad()
{
twoIntsStruct * data;
/* define a function pointer */
void (*funcPtr) (twoIntsStruct *) = badSink;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (twoIntsStruct *)malloc(100*sizeof(twoIntsStruct));
if (data == NULL) {exit(-1);}
/* use the function pointer */
funcPtr(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(twoIntsStruct * data);
static void goodG2B()
{
twoIntsStruct * data;
void (*funcPtr) (twoIntsStruct *) = goodG2BSink;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory using new [] */
data = new twoIntsStruct[100];
funcPtr(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(twoIntsStruct * data);
static void goodB2G()
{
twoIntsStruct * data;
void (*funcPtr) (twoIntsStruct *) = goodB2GSink;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (twoIntsStruct *)malloc(100*sizeof(twoIntsStruct));
if (data == NULL) {exit(-1);}
funcPtr(data);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace <API key>; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif |
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
class ActiveSupport::TestCase
self.<API key> = true
self.<API key> = false
end |
{-
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.0
Kubernetes API version: v1.9.12
Generated by Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
-}
{-|
Module : Kubernetes.OpenAPI.API.Certificates
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE <API key> #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -<API key> -<API key> -<API key> #-}
module Kubernetes.OpenAPI.API.Certificates where
import Kubernetes.OpenAPI.Core
import Kubernetes.OpenAPI.MimeTypes
import Kubernetes.OpenAPI.Model as M
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep)
import qualified Data.Foldable as P
import qualified Data.Map as Map
import qualified Data.Maybe as P
import qualified Data.Proxy as P (Proxy(..))
import qualified Data.Set as Set
import qualified Data.String as P
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Time as TI
import qualified Network.HTTP.Client.MultipartFormData as NH
import qualified Network.HTTP.Media as ME
import qualified Network.HTTP.Types as NH
import qualified Web.FormUrlEncoded as WH
import qualified Web.HttpApiData as WH
import Data.Text (Text)
import GHC.Base ((<|>))
import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor)
import qualified Prelude as P
-- * Operations
-- ** Certificates
-- | @GET \/apis\/certificates.k8s.io\/@
-- get information of a group
-- AuthMethod: '<API key>
getAPIGroup
:: Accept accept -- ^ request accept ('MimeType')
-> KubernetesRequest GetAPIGroup MimeNoContent V1APIGroup accept
getAPIGroup _ =
_mkRequest "GET" ["/apis/certificates.k8s.io/"]
`_hasAuthType` (P.Proxy :: P.Proxy <API key>)
data GetAPIGroup
-- | @application/json@
instance Consumes GetAPIGroup MimeJSON
-- | @application/yaml@
instance Consumes GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Consumes GetAPIGroup <API key>
-- | @application/json@
instance Produces GetAPIGroup MimeJSON
-- | @application/yaml@
instance Produces GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Produces GetAPIGroup <API key> |
#pragma once
#include "buildnumber.h" // defines VERSION_INT
// VERSION_INT is defined in buildnumber.h and is written to by the builder, inserting the current build number.
// VERSION_INT is used for the 3rd component eg. 4.1.1.[36]
// The product and file version could be different.
// For example, VIZ 4.0 works with max files version 4.2
// 3ds Max internal version number is managed using the following scheme:
// Major = Main release number (ex. 3ds Max 2013 (SimCity) = 15).
// Minor = Product Update; PUs would typically be starting at 1
// Point = Build Number (this always increments for a major release
// Example for Elwood = 17:
// First Release Product Update would be: 17.1.<build>.0
// Second Release Product Update would be: 17.2.<build>.0
// Etc.
#ifndef MAX_VERSION_MAJOR
#define MAX_VERSION_MAJOR 17
#endif
#ifndef MAX_VERSION_MINOR
#define MAX_VERSION_MINOR 0
#endif
#ifndef MAX_VERSION_POINT
#define MAX_VERSION_POINT VERSION_INT
#endif
// MAX Product version
#ifndef <API key>
#define <API key> 17
#endif
#ifndef <API key>
#define <API key> 0
#endif
#ifndef <API key>
#define <API key> VERSION_INT
#endif
#ifndef <API key>
#define <API key> 2015
#endif
// <API key> is an alternative for MAX_RELEASE (plugapi.h)
// Define it when you want the "branded" (UI) version number to be different
// from the internal one.
//#define <API key> 10900
// This should be left blank for the main release, and any subsequent HF up until the first Service Pack.
// Service Pack 1, and any subsequent HF up until the next Service Pack, would then need to be labeled "SP1",
// then the same thing starting with Service Pack 2, which would be labeled "SP2", etc.
#ifndef <API key>
#define <API key> "\0"
#endif
// HF number is only informative, that's the last number in the version info. It is always 0 for public releases.
#ifndef MAX_HF_NUMBER
#define MAX_HF_NUMBER 0
#endif
#define _MAX_VERSION(a, b, c,d) a##b##c##d
#define MAX_VERSION _MAX_VERSION(MAX_VERSION_MAJOR, MAX_VERSION_MINOR, VERSION_INT, MAX_HF_NUMBER) |
#include "chrome/browser/sync/test/integration/sync_test.h"
#include <vector>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/<API key>.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/values.h"
#include "chrome/browser/bookmarks/<API key>.h"
#include "chrome/browser/bookmarks/<API key>.h"
#include "chrome/browser/google/google_url_tracker.h"
#include "chrome/browser/history/<API key>.h"
#include "chrome/browser/invalidation/<API key>.h"
#include "chrome/browser/invalidation/<API key>.h"
#include "chrome/browser/lifetime/<API key>.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/search_engines/<API key>.h"
#include "chrome/browser/search_engines/<API key>.h"
#include "chrome/browser/sync/<API key>.h"
#include "chrome/browser/sync/test/integration/<API key>.h"
#include "chrome/browser/sync/test/integration/<API key>.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/<API key>.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/encryptor/os_crypt.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_browser_thread.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/base/<API key>.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/<API key>.h"
#include "net/proxy/proxy_service.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/url_request/<API key>.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/<API key>.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/<API key>.h"
#include "sync/engine/sync_scheduler_impl.h"
#include "sync/notifier/p2p_invalidator.h"
#include "sync/protocol/sync.pb.h"
#include "sync/test/fake_server/fake_server.h"
#include "sync/test/fake_server/<API key>.h"
#include "url/gurl.h"
using content::BrowserThread;
using invalidation::<API key>;
namespace switches {
const char <API key>[] = "<API key>";
const char kSyncUserForTest[] = "sync-user-for-test";
const char <API key>[] = "<API key>";
const char <API key>[] = "<API key>";
}
// Helper class that checks whether a sync test server is running or not.
class <API key> : public net::URLFetcherDelegate {
public:
<API key>() : running_(false) {}
virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE {
std::string data;
source->GetResponseAsString(&data);
running_ =
(source->GetStatus().status() == net::URLRequestStatus::SUCCESS &&
source->GetResponseCode() == 200 && data.find("ok") == 0);
base::MessageLoop::current()->Quit();
}
bool running() const { return running_; }
private:
bool running_;
};
void <API key>(
base::WaitableEvent* done,
net::<API key>* <API key>,
const net::ProxyConfig& proxy_config) {
net::ProxyService* proxy_service =
<API key>-><API key>()->proxy_service();
proxy_service->ResetConfigService(
new net::<API key>(proxy_config));
done->Signal();
}
KeyedService* <API key>(content::BrowserContext* context) {
Profile* profile = static_cast<Profile*>(context);
return new invalidation::<API key>(profile);
}
SyncTest::SyncTest(TestType test_type)
: test_type_(test_type),
server_type_(<API key>),
num_clients_(-1),
use_verifier_(true),
<API key>(true),
test_server_handle_(base::kNullProcessHandle) {
<API key>::AssociateWithTest(this);
switch (test_type_) {
case SINGLE_CLIENT: {
num_clients_ = 1;
break;
}
case TWO_CLIENT: {
num_clients_ = 2;
break;
}
case MULTIPLE_CLIENT: {
num_clients_ = 3;
break;
}
}
}
SyncTest::~SyncTest() {}
void SyncTest::SetUp() {
CommandLine* cl = CommandLine::ForCurrentProcess();
if (cl->HasSwitch(switches::<API key>)) {
ReadPasswordFile();
} else if (cl->HasSwitch(switches::kSyncUserForTest) &&
cl->HasSwitch(switches::<API key>)) {
username_ = cl->GetSwitchValueASCII(switches::kSyncUserForTest);
password_ = cl->GetSwitchValueASCII(switches::<API key>);
} else {
username_ = "user@gmail.com";
password_ = "password";
}
// Only set |server_type_| if it hasn't already been set. This allows for
// <API key> tests to set this value in each test class.
if (server_type_ == <API key>) {
if (!cl->HasSwitch(switches::kSyncServiceURL) &&
!cl->HasSwitch(switches::<API key>)) {
// If neither a sync server URL nor a sync server command line is
// provided, start up a local python sync test server and point Chrome
// to its URL. This is the most common configuration, and the only
// one that makes sense for most developers.
server_type_ = LOCAL_PYTHON_SERVER;
} else if (cl->HasSwitch(switches::kSyncServiceURL) &&
cl->HasSwitch(switches::<API key>)) {
// If a sync server URL and a sync server command line are provided,
// start up a local sync server by running the command line. Chrome
// will connect to the server at the URL that was provided.
server_type_ = LOCAL_LIVE_SERVER;
} else if (cl->HasSwitch(switches::kSyncServiceURL) &&
!cl->HasSwitch(switches::<API key>)) {
// If a sync server URL is provided, but not a server command line,
// it is assumed that the server is already running. Chrome will
// automatically connect to it at the URL provided. There is nothing
// to do here.
server_type_ = <API key>;
} else {
// If a sync server command line is provided, but not a server URL,
// we flag an error.
LOG(FATAL) << "Can't figure out how to run a server.";
}
}
if (username_.empty() || password_.empty())
LOG(FATAL) << "Cannot run sync tests without GAIA credentials.";
// Mock the Mac Keychain service. The real Keychain can block on user input.
#if defined(OS_MACOSX)
OSCrypt::UseMockKeychain(true);
#endif
// Start up a sync test server if one is needed and setup mock gaia responses.
// Note: This must be done prior to the call to SetupClients() because we want
// the mock gaia responses to be available before GaiaUrls is initialized.
<API key>();
// Yield control back to the <API key> framework.
<API key>::SetUp();
}
void SyncTest::TearDown() {
// Clear any mock gaia responses that might have been set.
<API key>();
// Allow the <API key> framework to perform its tear down.
<API key>::TearDown();
// Stop the local python test server. This is a no-op if one wasn't started.
<API key>();
// Stop the local sync test server. This is a no-op if one wasn't started.
<API key>();
}
void SyncTest::SetUpCommandLine(CommandLine* cl) {
AddTestSwitches(cl);
<API key>(cl);
}
void SyncTest::AddTestSwitches(CommandLine* cl) {
// Disable non-essential access of external network resources.
if (!cl->HasSwitch(switches::<API key>))
cl->AppendSwitch(switches::<API key>);
if (!cl->HasSwitch(switches::<API key>))
cl->AppendSwitch(switches::<API key>);
// TODO(sync): Fix enable_disable_test.cc to play nice with priority
// preferences.
if (!cl->HasSwitch(switches::<API key>))
cl->AppendSwitch(switches::<API key>);
}
void SyncTest::<API key>(CommandLine* cl) {}
// static
Profile* SyncTest::MakeProfile(const base::FilePath::StringType name) {
base::FilePath path;
PathService::Get(chrome::DIR_USER_DATA, &path);
path = path.Append(name);
if (!base::PathExists(path))
CHECK(base::CreateDirectory(path));
Profile* profile =
Profile::CreateProfile(path, NULL, Profile::<API key>);
g_browser_process->profile_manager()-><API key>(profile,
true,
true);
return profile;
}
Profile* SyncTest::GetProfile(int index) {
if (profiles_.empty())
LOG(FATAL) << "SetupClients() has not yet been called.";
if (index < 0 || index >= static_cast<int>(profiles_.size()))
LOG(FATAL) << "GetProfile(): Index is out of bounds.";
return profiles_[index];
}
Browser* SyncTest::GetBrowser(int index) {
if (browsers_.empty())
LOG(FATAL) << "SetupClients() has not yet been called.";
if (index < 0 || index >= static_cast<int>(browsers_.size()))
LOG(FATAL) << "GetBrowser(): Index is out of bounds.";
return browsers_[index];
}
<API key>* SyncTest::GetClient(int index) {
if (clients_.empty())
LOG(FATAL) << "SetupClients() has not yet been called.";
if (index < 0 || index >= static_cast<int>(clients_.size()))
LOG(FATAL) << "GetClient(): Index is out of bounds.";
return clients_[index];
}
Profile* SyncTest::verifier() {
if (verifier_ == NULL)
LOG(FATAL) << "SetupClients() has not yet been called.";
return verifier_;
}
void SyncTest::DisableVerifier() {
use_verifier_ = false;
}
bool SyncTest::SetupClients() {
if (num_clients_ <= 0)
LOG(FATAL) << "num_clients_ incorrectly initialized.";
if (!profiles_.empty() || !browsers_.empty() || !clients_.empty())
LOG(FATAL) << "SetupClients() has already been called.";
// Create the required number of sync profiles, browsers and clients.
profiles_.resize(num_clients_);
browsers_.resize(num_clients_);
clients_.resize(num_clients_);
for (int i = 0; i < num_clients_; ++i) {
InitializeInstance(i);
}
// Create the verifier profile.
verifier_ = MakeProfile(FILE_PATH_LITERAL("Verifier"));
test::<API key>(
<API key>::GetForProfile(verifier()));
ui_test_utils::<API key>(<API key>::GetForProfile(
verifier(), Profile::EXPLICIT_ACCESS));
ui_test_utils::<API key>(
<API key>::GetForProfile(verifier()));
return (verifier_ != NULL);
}
void SyncTest::InitializeInstance(int index) {
profiles_[index] = MakeProfile(
base::StringPrintf(FILE_PATH_LITERAL("Profile%d"), index));
EXPECT_FALSE(GetProfile(index) == NULL) << "Could not create Profile "
<< index << ".";
browsers_[index] = new Browser(Browser::CreateParams(
GetProfile(index), chrome::GetActiveDesktop()));
EXPECT_FALSE(GetBrowser(index) == NULL) << "Could not create Browser "
<< index << ".";
invalidation::<API key>* <API key> =
static_cast<invalidation::<API key>*>(
<API key>::GetInstance()-><API key>(
GetProfile(index), <API key>));
<API key>->UpdateCredentials(username_, password_);
// Make sure the ProfileSyncService has been created before creating the
// <API key> - some tests expect the ProfileSyncService to
// already exist.
ProfileSyncService* <API key> =
<API key>::GetForProfile(GetProfile(index));
if (server_type_ == <API key>) {
// TODO(pvalenzuela): Run the fake server via EmbeddedTestServer.
<API key>-><API key>(
make_scoped_ptr<syncer::NetworkResources>(
new fake_server::<API key>(fake_server_.get())));
}
clients_[index] =
<API key>::<API key>(
GetProfile(index),
username_,
password_,
<API key>);
EXPECT_FALSE(GetClient(index) == NULL) << "Could not create Client "
<< index << ".";
test::<API key>(
<API key>::GetForProfile(GetProfile(index)));
ui_test_utils::<API key>(<API key>::GetForProfile(
GetProfile(index), Profile::EXPLICIT_ACCESS));
ui_test_utils::<API key>(
<API key>::GetForProfile(GetProfile(index)));
}
bool SyncTest::SetupSync() {
// Create sync profiles and clients if they haven't already been created.
if (profiles_.empty()) {
if (!SetupClients())
LOG(FATAL) << "SetupClients() failed.";
}
// Sync each of the profiles.
for (int i = 0; i < num_clients_; ++i) {
if (!GetClient(i)->SetupSync())
LOG(FATAL) << "SetupSync() failed.";
}
// Because clients may modify sync data as part of startup (for example local
// session-releated data is rewritten), we need to ensure all startup-based
// changes have propagated between the clients.
AwaitQuiescence();
return true;
}
void SyncTest::CleanUpOnMainThread() {
for (size_t i = 0; i < clients_.size(); ++i) {
clients_[i]->service()->DisableForUser();
}
// Some of the pending messages might rely on browser windows still being
// around, so run messages both before and after closing all browsers.
content::<API key>();
// Close all browser windows.
chrome::CloseAllBrowsers();
content::<API key>();
// All browsers should be closed at this point, or else we could see memory
// corruption in QuitBrowser().
CHECK_EQ(0U, chrome::<API key>());
clients_.clear();
}
void SyncTest::<API key>() {
// We don't take a reference to |resolver|, but <API key>
// does, so effectively assumes ownership.
net::<API key>* resolver =
new net::<API key>(host_resolver());
resolver->AllowDirectLookup("*.google.com");
// On Linux, we use Chromium's NSS implementation which uses the following
// hosts for certificate verification. Without these overrides, running the
// integration tests on Linux causes error as we make external DNS lookups.
resolver->AllowDirectLookup("*.thawte.com");
resolver->AllowDirectLookup("*.geotrust.com");
resolver->AllowDirectLookup("*.gstatic.com");
<API key>.reset(
new net::<API key>(resolver));
}
void SyncTest::<API key>() {
<API key>.reset();
}
void SyncTest::ReadPasswordFile() {
CommandLine* cl = CommandLine::ForCurrentProcess();
password_file_ = cl->GetSwitchValuePath(switches::<API key>);
if (password_file_.empty())
LOG(FATAL) << "Can't run live server test without specifying
<< switches::<API key> << "=<filename>";
std::string file_contents;
base::ReadFileToString(password_file_, &file_contents);
ASSERT_NE(file_contents, "") << "Password file \""
<< password_file_.value() << "\" does not exist.";
std::vector<std::string> tokens;
std::string delimiters = "\r\n";
Tokenize(file_contents, delimiters, &tokens);
ASSERT_EQ(2U, tokens.size()) << "Password file \""
<< password_file_.value()
<< "\" must contain exactly two lines of text.";
username_ = tokens[0];
password_ = tokens[1];
}
void SyncTest::<API key>() {
factory_.reset(new net::<API key>());
fake_factory_.reset(new net::<API key>(factory_.get()));
fake_factory_->SetFakeResponse(
GaiaUrls::GetInstance()->get_user_info_url(),
"email=user@gmail.com\ndisplayEmail=user@gmail.com",
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
fake_factory_->SetFakeResponse(
GaiaUrls::GetInstance()-><API key>(),
"auth",
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
fake_factory_->SetFakeResponse(
GURL(GoogleURLTracker::<API key>),
".google.com",
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
fake_factory_->SetFakeResponse(
GaiaUrls::GetInstance()-><API key>(),
"some_response",
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
fake_factory_->SetFakeResponse(
GaiaUrls::GetInstance()->oauth2_token_url(),
"{"
" \"refresh_token\": \"rt1\","
" \"access_token\": \"at1\","
" \"expires_in\": 3600,"
" \"token_type\": \"Bearer\""
"}",
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
fake_factory_->SetFakeResponse(
GaiaUrls::GetInstance()->oauth_user_info_url(),
"{"
" \"id\": \"12345\""
"}",
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
fake_factory_->SetFakeResponse(
GaiaUrls::GetInstance()->oauth1_login_url(),
"SID=sid\nLSID=lsid\nAuth=auth_token",
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
fake_factory_->SetFakeResponse(
GaiaUrls::GetInstance()->oauth2_revoke_url(),
"",
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
}
void SyncTest::<API key>(const std::string& response_data,
net::HttpStatusCode response_code,
net::URLRequestStatus::Status status) {
ASSERT_TRUE(NULL != fake_factory_.get());
fake_factory_->SetFakeResponse(GaiaUrls::GetInstance()->oauth2_token_url(),
response_data, response_code, status);
}
void SyncTest::<API key>() {
// Clear any mock gaia responses that might have been set.
if (fake_factory_) {
fake_factory_->ClearFakeResponses();
fake_factory_.reset();
}
// Cancel any outstanding URL fetches and destroy the <API key> we
// created.
net::URLFetcher::CancelAll();
factory_.reset();
}
// Start up a local sync server based on the value of server_type_, which
// was determined from the command line parameters.
void SyncTest::<API key>() {
if (server_type_ == LOCAL_PYTHON_SERVER) {
if (!<API key>())
LOG(FATAL) << "Failed to set up local python sync and XMPP servers";
<API key>();
} else if (server_type_ == LOCAL_LIVE_SERVER) {
// Using mock gaia credentials requires the use of a mock XMPP server.
if (username_ == "user@gmail.com" && !<API key>())
LOG(FATAL) << "Failed to set up local python XMPP server";
if (!<API key>())
LOG(FATAL) << "Failed to set up local test server";
} else if (server_type_ == <API key>) {
fake_server_.reset(new fake_server::FakeServer());
// Similar to LOCAL_LIVE_SERVER, we must start this for XMPP.
<API key>();
<API key>();
} else if (server_type_ == <API key>) {
// Nothing to do; we'll just talk to the URL we were given.
} else {
LOG(FATAL) << "Don't know which server environment to run test in.";
}
}
bool SyncTest::<API key>() {
EXPECT_TRUE(sync_server_.Start())
<< "Could not launch local python test server.";
CommandLine* cl = CommandLine::ForCurrentProcess();
if (server_type_ == LOCAL_PYTHON_SERVER) {
std::string sync_service_url = sync_server_.GetURL("chromiumsync").spec();
cl->AppendSwitchASCII(switches::kSyncServiceURL, sync_service_url);
DVLOG(1) << "Started local python sync server at " << sync_service_url;
}
int xmpp_port = 0;
if (!sync_server_.server_data().GetInteger("xmpp_port", &xmpp_port)) {
LOG(ERROR) << "Could not find valid xmpp_port value";
return false;
}
if ((xmpp_port <= 0) || (xmpp_port > kuint16max)) {
LOG(ERROR) << "Invalid xmpp port: " << xmpp_port;
return false;
}
net::HostPortPair xmpp_host_port_pair(sync_server_.host_port_pair());
xmpp_host_port_pair.set_port(xmpp_port);
xmpp_port_.reset(new net::ScopedPortException(xmpp_port));
if (!cl->HasSwitch(switches::<API key>)) {
cl->AppendSwitchASCII(switches::<API key>,
xmpp_host_port_pair.ToString());
// The local XMPP server only supports insecure connections.
cl->AppendSwitch(switches::<API key>);
}
DVLOG(1) << "Started local python XMPP server at "
<< xmpp_host_port_pair.ToString();
return true;
}
bool SyncTest::<API key>() {
CommandLine* cl = CommandLine::ForCurrentProcess();
CommandLine::StringType <API key> = cl-><API key>(
switches::<API key>);
CommandLine::StringVector <API key>;
CommandLine::StringType delimiters(FILE_PATH_LITERAL(" "));
Tokenize(<API key>, delimiters, &<API key>);
CommandLine server_cmdline(<API key>);
base::LaunchOptions options;
#if defined(OS_WIN)
options.start_hidden = true;
#endif
if (!base::LaunchProcess(server_cmdline, options, &test_server_handle_))
LOG(ERROR) << "Could not launch local test server.";
const base::TimeDelta kMaxWaitTime = TestTimeouts::action_max_timeout();
const int kNumIntervals = 15;
if (<API key>(kMaxWaitTime, kNumIntervals)) {
DVLOG(1) << "Started local test server at "
<< cl->GetSwitchValueASCII(switches::kSyncServiceURL) << ".";
return true;
} else {
LOG(ERROR) << "Could not start local test server at "
<< cl->GetSwitchValueASCII(switches::kSyncServiceURL) << ".";
return false;
}
}
bool SyncTest::<API key>() {
if (!sync_server_.Stop()) {
LOG(ERROR) << "Could not stop local python test server.";
return false;
}
xmpp_port_.reset();
return true;
}
bool SyncTest::<API key>() {
if (test_server_handle_ != base::kNullProcessHandle) {
EXPECT_TRUE(base::KillProcess(test_server_handle_, 0, false))
<< "Could not stop local test server.";
base::CloseProcessHandle(test_server_handle_);
test_server_handle_ = base::kNullProcessHandle;
}
return true;
}
bool SyncTest::<API key>(base::TimeDelta wait, int intervals) {
for (int i = 0; i < intervals; ++i) {
if (IsTestServerRunning())
return true;
base::PlatformThread::Sleep(wait / intervals);
}
return false;
}
bool SyncTest::IsTestServerRunning() {
CommandLine* cl = CommandLine::ForCurrentProcess();
std::string sync_url = cl->GetSwitchValueASCII(switches::kSyncServiceURL);
GURL sync_url_status(sync_url.append("/healthz"));
<API key> delegate;
scoped_ptr<net::URLFetcher> fetcher(net::URLFetcher::Create(
sync_url_status, net::URLFetcher::GET, &delegate));
fetcher->SetLoadFlags(net::LOAD_DISABLE_CACHE |
net::<API key> |
net::<API key>);
fetcher->SetRequestContext(g_browser_process-><API key>());
fetcher->Start();
content::RunMessageLoop();
return delegate.running();
}
void SyncTest::EnableNetwork(Profile* profile) {
SetProxyConfig(profile->GetRequestContext(),
net::ProxyConfig::CreateDirect());
if (<API key>) {
<API key>();
}
net::<API key>::<API key>();
}
void SyncTest::DisableNetwork(Profile* profile) {
<API key>();
// Set the current proxy configuration to a nonexistent proxy to effectively
// disable networking.
net::ProxyConfig config;
config.proxy_rules().ParseFromString("http=127.0.0.1:0");
SetProxyConfig(profile->GetRequestContext(), config);
net::<API key>::<API key>();
}
bool SyncTest::EnableEncryption(int index) {
return GetClient(index)->EnableEncryption();
}
bool SyncTest::<API key>(int index) {
return GetClient(index)-><API key>();
}
bool SyncTest::AwaitQuiescence() {
return <API key>::AwaitQuiescence(clients());
}
bool SyncTest::<API key>() const {
EXPECT_NE(<API key>, server_type_);
// Supported only if we're using the python testserver.
return server_type_ == LOCAL_PYTHON_SERVER;
}
void SyncTest::<API key>() {
ASSERT_TRUE(<API key>());
std::string path = "chromiumsync/<API key>";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Notifications disabled",
UTF16ToASCII(browser()->tab_strip_model()-><API key>()->
GetTitle()));
}
void SyncTest::<API key>() {
<API key>();
<API key> = false;
}
void SyncTest::<API key>() {
ASSERT_TRUE(<API key>());
std::string path = "chromiumsync/enablenotifications";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Notifications enabled",
UTF16ToASCII(browser()->tab_strip_model()-><API key>()->
GetTitle()));
}
void SyncTest::EnableNotifications() {
<API key>();
<API key> = true;
}
void SyncTest::TriggerNotification(syncer::ModelTypeSet changed_types) {
ASSERT_TRUE(<API key>());
const std::string& data =
syncer::P2PNotificationData(
"from_server",
syncer::NOTIFY_ALL,
syncer::<API key>::InvalidateAll(
syncer::<API key>(changed_types))).ToString();
const std::string& path =
std::string("chromiumsync/sendnotification?channel=") +
syncer::<API key> + "&data=" + data;
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Notification sent",
UTF16ToASCII(browser()->tab_strip_model()-><API key>()->
GetTitle()));
}
bool SyncTest::<API key>() const {
EXPECT_NE(<API key>, server_type_);
// Supported only if we're using the python testserver.
return server_type_ == LOCAL_PYTHON_SERVER;
}
void SyncTest::<API key>(syncer::ModelTypeSet model_types) {
ASSERT_TRUE(<API key>());
std::string path = "chromiumsync/migrate";
char joiner = '?';
for (syncer::ModelTypeSet::Iterator it = model_types.First();
it.Good(); it.Inc()) {
path.append(
base::StringPrintf(
"%ctype=%d", joiner,
syncer::<API key>(it.Get())));
joiner = '&';
}
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Migration: 200",
UTF16ToASCII(browser()->tab_strip_model()-><API key>()->
GetTitle()));
}
void SyncTest::<API key>() {
ASSERT_TRUE(<API key>());
std::string path = "chromiumsync/birthdayerror";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Birthday error",
UTF16ToASCII(browser()->tab_strip_model()-><API key>()->
GetTitle()));
}
void SyncTest::<API key>() {
ASSERT_TRUE(<API key>());
std::string path = "chromiumsync/transienterror";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Transient error",
UTF16ToASCII(browser()->tab_strip_model()-><API key>()->
GetTitle()));
}
void SyncTest::TriggerAuthState(<API key> auth_state) {
ASSERT_TRUE(<API key>());
std::string path = "chromiumsync/cred";
path.append(auth_state == AUTHENTICATED_TRUE ? "?valid=True" :
"?valid=False");
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
}
void SyncTest::<API key>() {
ASSERT_TRUE(<API key>());
std::string path = "chromiumsync/xmppcred";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
}
namespace {
sync_pb::SyncEnums::ErrorType
<API key>(
syncer::<API key> error) {
switch (error) {
case syncer::SYNC_SUCCESS:
return sync_pb::SyncEnums::SUCCESS;
case syncer::NOT_MY_BIRTHDAY:
return sync_pb::SyncEnums::NOT_MY_BIRTHDAY;
case syncer::THROTTLED:
return sync_pb::SyncEnums::THROTTLED;
case syncer::CLEAR_PENDING:
return sync_pb::SyncEnums::CLEAR_PENDING;
case syncer::TRANSIENT_ERROR:
return sync_pb::SyncEnums::TRANSIENT_ERROR;
case syncer::MIGRATION_DONE:
return sync_pb::SyncEnums::MIGRATION_DONE;
case syncer::UNKNOWN_ERROR:
return sync_pb::SyncEnums::UNKNOWN;
default:
NOTREACHED();
return sync_pb::SyncEnums::UNKNOWN;
}
}
sync_pb::SyncEnums::Action <API key>(
const syncer::ClientAction& action) {
switch (action) {
case syncer::UPGRADE_CLIENT:
return sync_pb::SyncEnums::UPGRADE_CLIENT;
case syncer::<API key>:
return sync_pb::SyncEnums::<API key>;
case syncer::<API key>:
return sync_pb::SyncEnums::<API key>;
case syncer::<API key>:
return sync_pb::SyncEnums::<API key>;
case syncer::<API key>:
return sync_pb::SyncEnums::<API key>;
case syncer::UNKNOWN_ACTION:
return sync_pb::SyncEnums::UNKNOWN_ACTION;
default:
NOTREACHED();
return sync_pb::SyncEnums::UNKNOWN_ACTION;
}
}
} // namespace
void SyncTest::TriggerSyncError(const syncer::SyncProtocolError& error,
SyncErrorFrequency frequency) {
ASSERT_TRUE(<API key>());
std::string path = "chromiumsync/error";
int error_type =
static_cast<int>(<API key>(
error.error_type));
int action = static_cast<int>(<API key>(
error.action));
path.append(base::StringPrintf("?error=%d", error_type));
path.append(base::StringPrintf("&action=%d", action));
path.append(base::StringPrintf("&error_description=%s",
error.error_description.c_str()));
path.append(base::StringPrintf("&url=%s", error.url.c_str()));
path.append(base::StringPrintf("&frequency=%d", frequency));
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
std::string output = UTF16ToASCII(
browser()->tab_strip_model()-><API key>()->GetTitle());
ASSERT_TRUE(output.find("SetError: 200") != base::string16::npos);
}
void SyncTest::<API key>() {
ASSERT_TRUE(<API key>());
std::string path = "chromiumsync/<API key>";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Synced Bookmarks",
UTF16ToASCII(browser()->tab_strip_model()-><API key>()->
GetTitle()));
}
void SyncTest::SetProxyConfig(net::<API key>* context_getter,
const net::ProxyConfig& proxy_config) {
base::WaitableEvent done(false, false);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&<API key>, &done,
make_scoped_refptr(context_getter), proxy_config));
done.Wait();
}
void SyncTest::UseFakeServer() {
DCHECK_EQ(<API key>, server_type_);
server_type_ = <API key>;
} |
<?php
namespace Xi\Algorithm;
class Luhn
{
/**
* Returns the given number with luhn algorithm applied.
*
* For example 456 becomes 4564.
*
* @param integer $number
* @return integer
*/
public function generate($number)
{
$stack = 0;
$digits = str_split(strrev($number), 1);
foreach ($digits as $key => $value) {
if ($key % 2 === 0) {
$value = array_sum(str_split($value * 2, 1));
}
$stack += $value;
}
$stack %= 10;
if ($stack !== 0) {
$stack -= 10;
}
return (int) (implode('', array_reverse($digits)) . abs($stack));
}
/**
* Validates the given number.
*
* @param integer $number
* @return boolean
*/
public function validate($number)
{
$original = substr($number, 0, strlen($number) - 1);
return $this->generate($original) === $number;
}
} |
package blog.absyn;
/**
* @author leili
* @date Apr 22, 2012
*
*/
abstract public class EvidenceStmt extends Stmt {
/**
* @param p
*/
public EvidenceStmt(int p) {
this(0, p);
}
/**
* @param line
* @param pos
*/
public EvidenceStmt(int line, int pos) {
super(line, pos);
}
} |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function <API key>(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _ansiRegex = require('ansi-regex');
var _ansiRegex2 = <API key>(_ansiRegex);
var ANSIRegex = undefined;
ANSIRegex = (0, _ansiRegex2['default'])();
/**
* @typedef {Object} mapANSIEscapeCodes
* @property {Numbex} Index of the escape code in the plain string equivalent of the input string.
* @property {String} ANSI escape code.
*/
/**
* Produces a list of the escape codes contained in the input string.
*
* @param {String} input
* @return {mapANSIEscapeCodes~code[]}
*/
exports['default'] = function (input) {
var match = undefined,
matches = undefined,
offset = undefined;
offset = 0;
matches = [];
while ((match = ANSIRegex.exec(input)) !== null) {
matches.push({
index: match.index - offset,
code: match[0]
});
offset += match[0].length;
}
return matches;
};
module.exports = exports['default'];
//# sourceMappingURL=mapANSIEscapeCodes.js.map |
var specs = require('jungles-data');
var data = require('./index')({
host: '127.0.0.1',
port: '5432',
user: 'jungles_test',
password: '1234',
database: 'jungles_test',
});
var client = data.client;
client.query('DROP TABLE IF EXISTS instances; DROP TABLE IF EXISTS settings;', function (err, result) {
data.setup(function (err) {
var test_data = {
boards: ['category', '/boards', 'Boards', '{0}', JSON.stringify({ color: 'red' })],
blades: ['category', '/blades', 'Blades', '{1}', JSON.stringify({ color: 'blue' })],
skateboard: ['product', '/boards/skateboard', 'Skateboard', '{0, 0}', JSON.stringify({})],
wheel: ['part', '/boards/skateboard/wheel', 'Wheel', '{0, 0, 0}', JSON.stringify({})],
};
var settings = {
bail: true,
beforeEach: function (done) {
client.query('BEGIN');
client.query('DELETE FROM instances');
client.query('INSERT INTO instances(type, path, name, sort, data) values($1, $2, $3, $4, $5);', test_data.boards);
client.query('INSERT INTO instances(type, path, name, sort, data) values($1, $2, $3, $4, $5);', test_data.blades);
client.query('INSERT INTO instances(type, path, name, sort, data) values($1, $2, $3, $4, $5);', test_data.skateboard);
client.query('INSERT INTO instances(type, path, name, sort, data) values($1, $2, $3, $4, $5);', test_data.wheel);
client.query('COMMIT', function () { done(); });
},
};
specs(data, settings);
});
}); |
<?php
return array(
// This should be an array of module namespaces used in the application.
'modules' => array(
'Application',
'Book',
),
// These are various options for the listeners attached to the ModuleManager
'<API key>' => array(
// This should be an array of paths in which modules reside.
// If a string key is provided, the listener will consider that a module
// namespace, the value of that key the specific path to that module's
// Module class.
'module_paths' => array(
'./module',
'./vendor',
),
// An array of paths from which to glob configuration files after
// modules are loaded. These effectively overide configuration
// provided by modules themselves. Paths may use GLOB_BRACE notation.
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
// Whether or not to enable a configuration cache.
// If enabled, the merged configuration will be cached and used in
// subsequent requests.
//'<API key>' => $booleanValue,
// The key used to create the configuration cache file name.
//'config_cache_key' => $stringKey,
// Whether or not to enable a module class map cache.
// If enabled, creates a module class map cache which will be used
// by in future requests, to reduce the autoloading process.
//'<API key>' => $booleanValue,
// The key used to create the class map cache file name.
//'<API key>' => $stringKey,
// The path in which to cache merged configuration.
//'cache_dir' => $stringPath,
// Whether or not to enable modules dependency checking.
// Enabled by default, prevents usage of modules that depend on other modules
// that weren't loaded.
// 'check_dependencies' => true,
),
// Used to create an own service manager. May contain one or more child arrays.
//'<API key>' => array(
// array(
// 'service_manager' => $<API key>,
// 'config_key' => $stringConfigKey,
// 'interface' => $<API key>,
// 'method' => $<API key>,
// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
// 'service_manager' => array(),
); |
<?php
/**
* Customer.
*/
class <API key> {
public static function createFromOrder( WC_Order $order ) {
$customer = $order->get_user();
if ( $customer ) {
return self::createFromUser( $customer );
}
return self::<API key>( $order );
}
public static function createFromUser( WP_User $user ) {
switch ( $user->getGender() ) {
case '1':
$gender = 1;
break;
case '2':
$gender = 2;
break;
default:
$gender = 0;
}
$aCustomer = new self();
$aCustomer->email = $user->user_email;
$aCustomer->type = 'e';
$aCustomer->gender = $gender;
$aCustomer->id = $user->ID;
$aCustomer->first_name = $user->first_name;
$aCustomer->last_name = $user->last_name;
if ( ( $birthday = $user->getDob() ) != null ) {
$aCustomer->birthday = <API key>::fromDateTime( new DateTime( $birthday ) );
}
$aCustomer->date_joined = <API key>::fromDateTime( new DateTime( $user->user_registered ) );
return $aCustomer;
}
public static function <API key>( WC_Order $order ) {
$aCustomer = new self();
$aCustomer->email = WC_Aplazame::_m_or_a( $order, 'get_billing_email', 'billing_email' );
$aCustomer->type = 'g';
$aCustomer->gender = 0;
return $aCustomer;
}
} |
package org.chromium.chrome.browser.document;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.Log;
import org.chromium.chrome.browser.ChromeApplication;
import org.chromium.chrome.browser.IntentHandler;
import org.chromium.chrome.browser.Tab;
import org.chromium.chrome.browser.TabState;
import org.chromium.chrome.browser.UrlConstants;
import org.chromium.chrome.browser.tab.ChromeTab;
import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.document.TabDelegate;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.base.PageTransition;
/**
* Provides Tabs to a DocumentTabModel.
* TODO(dfalcantara): delete or refactor this after upstreaming.
*/
public class TabDelegateImpl implements TabDelegate {
private static final String TAG = "cr.document";
private boolean mIsIncognito;
/**
* Creates a TabDelegate.
* @param incognito Whether or not the TabDelegate handles the creation of incognito tabs.
*/
public TabDelegateImpl(boolean incognito) {
mIsIncognito = incognito;
}
@Override
public boolean <API key>() {
return true;
}
/**
* Creates a frozen Tab. This Tab is not meant to be used or unfrozen -- it is only used as a
* placeholder until the real Tab can be created.
* The index is ignored in DocumentMode because Android handles the ordering of Tabs.
*/
@Override
public Tab createFrozenTab(TabState state, int id, int index) {
return ChromeTab.<API key>(id, null, state.isIncognito(), null,
Tab.INVALID_TAB_ID, state);
}
@Override
public Tab <API key>(
WebContents webContents, int parentId, TabLaunchType type) {
<API key>(webContents, parentId, type, webContents.getUrl());
return null;
}
@Override
public Tab <API key>(
WebContents webContents, int parentId, TabLaunchType type, String url) {
<API key>(
webContents, parentId, type, url, DocumentMetricIds.<API key>);
return null;
}
/**
* Creates a Tab to host the given WebContents asynchronously.
* @param webContents WebContents that has been pre-created.
* @param parentId ID of the parent Tab.
* @param type Launch type for the Tab.
* @param url URL to display in the WebContents.
* @param startedBy See {@link DocumentMetricIds}.
*/
public void <API key>(
WebContents webContents, int parentId, TabLaunchType type, String url, int startedBy) {
// Tabs can't be launched in affiliated mode when a webcontents exists.
assert type != TabLaunchType.<API key>;
if (url == null) url = "";
Context context = ApplicationStatus.<API key>();
int pageTransition = startedBy == DocumentMetricIds.<API key>
? PageTransition.RELOAD : PageTransition.AUTO_TOPLEVEL;
// TODO(dfalcantara): Pipe information about paused WebContents from native.
boolean isWebContentsPaused =
startedBy != DocumentMetricIds.<API key>;
if (FeatureUtilities.isDocumentMode(context)) {
PendingDocumentData data = new PendingDocumentData();
data.webContents = webContents;
data.webContentsPaused = isWebContentsPaused;
// Determine information about the parent Activity.
Tab parentTab = parentId == Tab.INVALID_TAB_ID ? null
: ChromeApplication.<API key>().getTabById(parentId);
Activity parentActivity = getActivityFromTab(parentTab);
<API key>.<API key>(parentActivity, mIsIncognito,
<API key>.<API key>, url, startedBy, pageTransition,
data);
} else {
// TODO(dfalcantara): Unify the document-mode path with this path so that both go
// through the <API key> via an Intent.
Intent tabbedIntent = new Intent(Intent.ACTION_VIEW);
tabbedIntent.setClass(context, <API key>.class);
tabbedIntent.setData(Uri.parse(url));
tabbedIntent.putExtra(IntentHandler.<API key>, mIsIncognito);
tabbedIntent.putExtra(IntentHandler.EXTRA_WEB_CONTENTS, webContents);
tabbedIntent.putExtra(IntentHandler.<API key>, isWebContentsPaused);
tabbedIntent.putExtra(IntentHandler.<API key>, pageTransition);
tabbedIntent.putExtra(IntentHandler.EXTRA_PARENT_TAB_ID, parentId);
tabbedIntent.setFlags(Intent.<API key>);
IntentHandler.<API key>(tabbedIntent, context);
}
}
@Override
public Tab launchUrl(String url, TabLaunchType type) {
return createNewTab(new LoadUrlParams(url), type, null);
}
@Override
public Tab launchNTP() {
return createNewTab(new LoadUrlParams(UrlConstants.NTP_URL, PageTransition.AUTO_TOPLEVEL),
TabLaunchType.<API key>, null);
}
@Override
public Tab createNewTab(LoadUrlParams loadUrlParams, TabLaunchType type, Tab parent) {
// Figure out how the page will be launched.
int launchMode;
if (TextUtils.equals(UrlConstants.NTP_URL, loadUrlParams.getUrl())) {
launchMode = <API key>.<API key>;
} else if (type == TabLaunchType.<API key>) {
if (!parent.isIncognito() && mIsIncognito) {
// Incognito tabs opened from regular tabs open in the foreground for privacy
// concerns.
launchMode = <API key>.<API key>;
} else {
launchMode = <API key>.<API key>;
}
} else {
launchMode = <API key>.<API key>;
}
// Classify the startup type.
int documentStartedBy = DocumentMetricIds.STARTED_BY_UNKNOWN;
if (parent != null && TextUtils.equals(UrlConstants.NTP_URL, parent.getUrl())) {
documentStartedBy = DocumentMetricIds.<API key>;
} else if (type == TabLaunchType.<API key>
|| type == TabLaunchType.<API key>) {
documentStartedBy = DocumentMetricIds.<API key>;
} else if (type == TabLaunchType.<API key>) {
documentStartedBy = DocumentMetricIds.<API key>;
}
if (FeatureUtilities.isDocumentMode(ApplicationStatus.<API key>())) {
<API key>(loadUrlParams, type, parent, launchMode, documentStartedBy, null);
} else {
Log.e(TAG, "TabDelegateImpl.createNewTab() not implemented.");
}
// Tab is created aysnchronously. Can't return it yet.
return null;
}
@Override
public void <API key>(LoadUrlParams loadUrlParams, TabLaunchType type,
Tab parent, int documentLaunchMode, int documentStartedBy, Integer requestId) {
// Pack up everything.
PendingDocumentData params = null;
if (loadUrlParams.getPostData() != null
|| loadUrlParams.getVerbatimHeaders() != null
|| loadUrlParams.getReferrer() != null
|| requestId != null) {
params = new PendingDocumentData();
params.postData = loadUrlParams.getPostData();
params.extraHeaders = loadUrlParams.getVerbatimHeaders();
params.referrer = loadUrlParams.getReferrer();
params.requestId = requestId == null ? 0 : requestId.intValue();
}
<API key>.<API key>(getActivityFromTab(parent), mIsIncognito,
documentLaunchMode, loadUrlParams.getUrl(), documentStartedBy,
loadUrlParams.getTransitionType(), params);
}
private Activity getActivityFromTab(Tab tab) {
return tab == null || tab.getWindowAndroid() == null
? null : tab.getWindowAndroid().getActivity().get();
}
} |
#ifndef <API key>
#define <API key>
#include "base/message_loop/<API key>.h"
#include "ui/aura/aura_export.h"
#include "ui/aura/window.h"
namespace aura {
class Window;
namespace client {
// An interface implemented by an object which handles nested dispatchers.
class AURA_EXPORT DispatcherClient {
public:
virtual void RunWithDispatcher(base::<API key>* dispatcher,
aura::Window* associated_window) = 0;
virtual void <API key>() = 0;
};
AURA_EXPORT void SetDispatcherClient(Window* root_window,
DispatcherClient* client);
AURA_EXPORT DispatcherClient* GetDispatcherClient(Window* root_window);
} // namespace client
} // namespace aura
#endif // <API key> |
#include "<API key>.h"
#include "<API key>.h"
#include <QFileDialog>
#include "zstack.hxx"
#include "zimage.h"
#include "biocytin/zstackprojector.h"
<API key>::<API key>(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::<API key>)
{
ui->setupUi(this);
setWindowTitle("New Project: Preprocess Tif Stacks");
ui->filenameCommon->setDisabled(true);
ui->messages->setDisabled(true);
ui->processButton->setVisible(false);
ui->progressBar->setVisible(false);
connect(ui->openStacksButton,SIGNAL(clicked()),this,SLOT(openTifStacks()));
connect(ui->filenameCommon,SIGNAL(returnPressed()),this,SLOT(<API key>()));
connect(ui->processButton,SIGNAL(clicked()),this,SLOT(processStacks()));
}
<API key>::~<API key>()
{
delete ui;
}
void <API key>::openTifStacks()
{
QString fileName = QFileDialog::getOpenFileName(this,"Select one tif stack",NULL,"*[0-9]?.tif");
if (!fileName.isEmpty()) {
QFileInfo fInfo(fileName);
filenameCommon = fInfo.fileName().remove(QRegExp("([0-9]+).tif"));
filenameDir = fInfo.absoluteDir();
displayStackInfo();
}
}
void <API key>::<API key>()
{
filenameCommon = ui->filenameCommon->text();
filenameCommon.remove("\n");
stackFilenames.clear();
displayStackInfo();
}
void <API key>::displayStackInfo()
{
ui->filenameCommon->setText(filenameCommon);
ui->messages->append(tr("Tif stack directory: ")+filenameDir.absolutePath());
ui->messages->append(tr("Tif filename common: ")+filenameCommon);
QStringList filter;
filter <<filenameCommon.append("([0-9]).tif");
//get all stack files
filenameDir.setNameFilters(filter);
stackFilenames = filenameDir.entryList();
ui->messages->append(tr("Found ")+QString::number(stackFilenames.size())+tr(" stacks:"));
for (int i=0; i<stackFilenames.size();i++) {
ui->messages->append(stackFilenames.at(i));
}
ui->filenameCommon->setDisabled(false);
ui->messages->setDisabled(false);
if (stackFilenames.size() >0) {
ui->processButton->setVisible(true);
} else {
ui->processButton->setVisible(false);
}
}
void <API key>::processStacks()
{
Biocytin::ZStackProjector projector;
int nfiles = stackFilenames.size();
ui->messages->append("Processing stacks...");
ui->progressBar->setVisible(true);
ui->progressBar->setMinimum(0);
ui->progressBar->setMaximum(nfiles);
for (int i=0; i< nfiles; i++) {
ui->messages->append(tr("Reading ")+stackFilenames.at(i));
ui->progressBar->setValue(i);
QCoreApplication::processEvents();
QString filepath = filenameDir.filePath(stackFilenames.at(i));
//read the stack
ZStack stack;
stack.load(filepath.toStdString());
//create 2D projection
QString projFilename = filepath .remove(".tif")+".Proj.tif";
ui->messages->append(tr("Creating a 2D projection and saving to ")+projFilename);
QCoreApplication::processEvents();
ZStack* proj = projector.project(
&stack, NeuTube::<API key>, false, 0);
proj->save(projFilename.toStdString());
delete proj;
/*
ZImage image(C_Stack::width(stack), C_Stack::height(stack));
Image_Array ima;
ima.array = stack->array;
switch (C_Stack::kind(stack)) {
case GREY:
image.setData(ima.array8);
break;
case COLOR:
image.setData(ima.arrayc);
break;
default:
break;
}
*/
}
ui->progressBar->setVisible(false);
} |
import { CodeMapNode } from "../../../codeCharta.model"
import { Store } from "../../../state/store/store"
import * as codeMapHelper from "../../../util/codeMapHelper"
import { <API key> } from "./<API key>.pipe"
describe("<API key>", () => {
beforeEach(() => {
Store["initialize"]()
})
it("should return undefined for leaf nodes", () => {
const fakeNode = {} as unknown as CodeMapNode
expect(new <API key>().transform(fakeNode)).toBe(undefined)
})
it("should return default color if getMarkingColor returns undefined", () => {
const fakeNode = { children: [{}] } as unknown as CodeMapNode
jest.spyOn(codeMapHelper, "getMarkingColor").mockImplementation(() => {})
expect(new <API key>().transform(fakeNode)).toBe(<API key>.defaultColor)
})
it("should return color of getMarkingColor", () => {
const fakeNode = { children: [{}] } as unknown as CodeMapNode
jest.spyOn(codeMapHelper, "getMarkingColor").mockImplementation(() => "#123456")
expect(new <API key>().transform(fakeNode)).toBe("#123456")
})
}) |
<?php
namespace frontend\modules\User\controllers;
use yii\web\Controller;
class DefaultController extends Controller
{
public function actionIndex()
{
return $this->render('index');
}
} |
<?php
namespace Weikit\Models;
use Illuminate\Database\Eloquent\Model;
class MenuItem extends Model
{
} |
(function($) {
$(document).ready(function(){
if ($(".select_address").length) {
$('input#order_use_billing').unbind("click");
$(".inner").hide();
$(".inner input").prop("disabled", true);
$(".inner select").prop("disabled", true);
if ($('input#order_use_billing').is(':checked')) {
$("#shipping .select_address").hide();
}
$('input#order_use_billing').click(function() {
if ($(this).is(':checked')) {
$("#shipping .select_address").hide();
hide_address_form('shipping');
} else {
$("#shipping .select_address").show();
if ($("input[name='order[ship_address_id]']:checked").val() == '0') {
show_address_form('shipping');
}
}
});
$("input[name='order[bill_address_id]']:radio").change(function(){
if ($("input[name='order[bill_address_id]']:checked").val() == '0') {
show_address_form('billing');
} else {
hide_address_form('billing');
}
});
$("input[name='order[ship_address_id]']:radio").change(function(){
if ($("input[name='order[ship_address_id]']:checked").val() == '0') {
show_address_form('shipping');
} else {
hide_address_form('shipping');
}
});
}
});
function hide_address_form(address_type){
$("#" + address_type + " .inner").hide();
$("#" + address_type + " .inner input").prop("disabled", true);
$("#" + address_type + " .inner select").prop("disabled", true);
}
function show_address_form(address_type){
$("#" + address_type + " .inner").show();
$("#" + address_type + " .inner input").prop("disabled", false);
$("#" + address_type + " .inner select").prop("disabled", false);
}
})(jQuery); |
--TEST
bson_encode() array
--SKIPIF
<?php require_once dirname(__FILE__) ."/skipif.inc"; ?>
--FILE
<?php
// BSON document: length
$expected = pack('V', 23);
// element: UTF-8 string
$expected .= pack('Ca*xVa*x', 2, '0', 7, 'foobar');
// element: boolean
$expected .= pack('Ca*xC', 8, '1', 1);
// BSON document: end
$expected .= pack('x');
var_dump($expected === bson_encode(array('foobar', true)));
?>
--EXPECT
bool(true) |
<?php
namespace ClubsORM\om;
use \BasePeer;
use \Criteria;
use \PDO;
use \PDOStatement;
use \Propel;
use \PropelException;
use \PropelPDO;
use ClubsORM\Profiles;
use ClubsORM\ProfilesPeer;
use ClubsORM\map\ProfilesTableMap;
/**
* Base static class for performing query and update operations on the 'profiles' table.
*
*
*
* @package propel.generator.clubs.om
*/
abstract class BaseProfilesPeer {
/** the default database name for this class */
const DATABASE_NAME = 'clubs';
/** the table name for this class */
const TABLE_NAME = 'profiles';
/** the related Propel class for this table */
const OM_CLASS = 'ClubsORM\\Profiles';
/** A class that can be returned by this peer. */
const CLASS_DEFAULT = 'clubs.Profiles';
/** the related TableMap class for this table */
const TM_CLASS = 'ProfilesTableMap';
/** The total number of columns. */
const NUM_COLUMNS = 8;
/** The number of lazy-loaded columns. */
const <API key> = 0;
/** The number of columns to hydrate (NUM_COLUMNS - <API key>) */
const NUM_HYDRATE_COLUMNS = 8;
/** the column name for the ORGANIZATION_ID field */
const ORGANIZATION_ID = 'profiles.ORGANIZATION_ID';
/** the column name for the CATEGORY_ID field */
const CATEGORY_ID = 'profiles.CATEGORY_ID';
/** the column name for the CLUB_MEETING_ID field */
const CLUB_MEETING_ID = 'profiles.CLUB_MEETING_ID';
/** the column name for the DESCRIPTION field */
const DESCRIPTION = 'profiles.DESCRIPTION';
/** the column name for the URL field */
const URL = 'profiles.URL';
/** the column name for the EMAIL field */
const EMAIL = 'profiles.EMAIL';
/** the column name for the PROJECT_NUM field */
const PROJECT_NUM = 'profiles.PROJECT_NUM';
/** the column name for the ACTIVE field */
const ACTIVE = 'profiles.ACTIVE';
/** The default string format for model objects of the related table **/
const <API key> = 'YAML';
/**
* An identiy map to hold any loaded instances of Profiles objects.
* This must be public so that other peer classes can access this when hydrating from JOIN
* queries.
* @var array Profiles[]
*/
public static $instances = array();
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('OrganizationId', 'CategoryId', 'ClubMeetingId', 'Description', 'Url', 'Email', 'ProjectNum', 'Active', ),
BasePeer::TYPE_STUDLYPHPNAME => array ('organizationId', 'categoryId', 'clubMeetingId', 'description', 'url', 'email', 'projectNum', 'active', ),
BasePeer::TYPE_COLNAME => array (self::ORGANIZATION_ID, self::CATEGORY_ID, self::CLUB_MEETING_ID, self::DESCRIPTION, self::URL, self::EMAIL, self::PROJECT_NUM, self::ACTIVE, ),
BasePeer::TYPE_RAW_COLNAME => array ('ORGANIZATION_ID', 'CATEGORY_ID', 'CLUB_MEETING_ID', 'DESCRIPTION', 'URL', 'EMAIL', 'PROJECT_NUM', 'ACTIVE', ),
BasePeer::TYPE_FIELDNAME => array ('organization_id', 'category_id', 'club_meeting_id', 'description', 'url', 'email', 'project_num', 'active', ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
protected static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('OrganizationId' => 0, 'CategoryId' => 1, 'ClubMeetingId' => 2, 'Description' => 3, 'Url' => 4, 'Email' => 5, 'ProjectNum' => 6, 'Active' => 7, ),
BasePeer::TYPE_STUDLYPHPNAME => array ('organizationId' => 0, 'categoryId' => 1, 'clubMeetingId' => 2, 'description' => 3, 'url' => 4, 'email' => 5, 'projectNum' => 6, 'active' => 7, ),
BasePeer::TYPE_COLNAME => array (self::ORGANIZATION_ID => 0, self::CATEGORY_ID => 1, self::CLUB_MEETING_ID => 2, self::DESCRIPTION => 3, self::URL => 4, self::EMAIL => 5, self::PROJECT_NUM => 6, self::ACTIVE => 7, ),
BasePeer::TYPE_RAW_COLNAME => array ('ORGANIZATION_ID' => 0, 'CATEGORY_ID' => 1, 'CLUB_MEETING_ID' => 2, 'DESCRIPTION' => 3, 'URL' => 4, 'EMAIL' => 5, 'PROJECT_NUM' => 6, 'ACTIVE' => 7, ),
BasePeer::TYPE_FIELDNAME => array ('organization_id' => 0, 'category_id' => 1, 'club_meeting_id' => 2, 'description' => 3, 'url' => 4, 'email' => 5, 'project_num' => 6, 'active' => 7, ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, )
);
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
* @throws PropelException - if the specified name could not be found in the fieldname mappings.
*/
static public function translateFieldName($name, $fromType, $toType)
{
$toNames = self::getFieldNames($toType);
$key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true));
}
return $toNames[$key];
}
/**
* Returns an array of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
* @return array A list of field names
*/
static public function getFieldNames($type = BasePeer::TYPE_PHPNAME)
{
if (!array_key_exists($type, self::$fieldNames)) {
throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.');
}
return self::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. ProfilesPeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(ProfilesPeer::TABLE_NAME.'.', $alias.'.', $column);
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param Criteria $criteria object containing the columns to add.
* @param string $alias optional table alias
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria, $alias = null)
{
if (null === $alias) {
$criteria->addSelectColumn(ProfilesPeer::ORGANIZATION_ID);
$criteria->addSelectColumn(ProfilesPeer::CATEGORY_ID);
$criteria->addSelectColumn(ProfilesPeer::CLUB_MEETING_ID);
$criteria->addSelectColumn(ProfilesPeer::DESCRIPTION);
$criteria->addSelectColumn(ProfilesPeer::URL);
$criteria->addSelectColumn(ProfilesPeer::EMAIL);
$criteria->addSelectColumn(ProfilesPeer::PROJECT_NUM);
$criteria->addSelectColumn(ProfilesPeer::ACTIVE);
} else {
$criteria->addSelectColumn($alias . '.ORGANIZATION_ID');
$criteria->addSelectColumn($alias . '.CATEGORY_ID');
$criteria->addSelectColumn($alias . '.CLUB_MEETING_ID');
$criteria->addSelectColumn($alias . '.DESCRIPTION');
$criteria->addSelectColumn($alias . '.URL');
$criteria->addSelectColumn($alias . '.EMAIL');
$criteria->addSelectColumn($alias . '.PROJECT_NUM');
$criteria->addSelectColumn($alias . '.ACTIVE');
}
}
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
* @param PropelPDO $con
* @return int Number of matching rows.
*/
public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null)
{
// we may modify criteria, so copy it first
$criteria = clone $criteria;
// We need to set the primary table name, since in the case that there are no WHERE columns
// it will be impossible for the BasePeer::createSelectSql() method to determine which
// tables go into the FROM clause.
$criteria->setPrimaryTableName(ProfilesPeer::TABLE_NAME);
if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->setDistinct();
}
if (!$criteria->hasSelectClause()) {
ProfilesPeer::addSelectColumns($criteria);
}
$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count
$criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName
if ($con === null) {
$con = Propel::getConnection(ProfilesPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
// BasePeer returns a PDOStatement
$stmt = BasePeer::doCount($criteria, $con);
if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$count = (int) $row[0];
} else {
$count = 0; // no rows returned; we infer that means 0 matches.
}
$stmt->closeCursor();
return $count;
}
/**
* Selects one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param PropelPDO $con
* @return Profiles
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne(Criteria $criteria, PropelPDO $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit(1);
$objects = ProfilesPeer::doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Selects several row from the DB.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param PropelPDO $con
* @return array Array of selected Objects
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect(Criteria $criteria, PropelPDO $con = null)
{
return ProfilesPeer::populateObjects(ProfilesPeer::doSelectStmt($criteria, $con));
}
/**
* Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement.
*
* Use this method directly if you want to work with an executed statement durirectly (for example
* to perform your own object hydration).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param PropelPDO $con The connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return PDOStatement The executed PDOStatement object.
* @see BasePeer::doSelect()
*/
public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(ProfilesPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
if (!$criteria->hasSelectClause()) {
$criteria = clone $criteria;
ProfilesPeer::addSelectColumns($criteria);
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
// BasePeer returns a PDOStatement
return BasePeer::doSelect($criteria, $con);
}
/**
* Adds an object to the instance pool.
*
* Propel keeps cached copies of objects in an instance pool when they are retrieved
* from the database. In some cases -- especially when you override doSelect*()
* methods in your stub classes -- you may need to explicitly add objects
* to the cache in order to ensure that the same objects are always returned by doSelect*()
* and retrieveByPK*() calls.
*
* @param Profiles $value A Profiles object.
* @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally).
*/
public static function addInstanceToPool($obj, $key = null)
{
if (Propel::<API key>()) {
if ($key === null) {
$key = (string) $obj->getOrganizationId();
}
self::$instances[$key] = $obj;
}
}
/**
* Removes an object from the instance pool.
*
* Propel keeps cached copies of objects in an instance pool when they are retrieved
* from the database. In some cases -- especially when you override doDelete
* methods in your stub classes -- you may need to explicitly remove objects
* from the cache in order to prevent returning objects that no longer exist.
*
* @param mixed $value A Profiles object or a primary key value.
*/
public static function <API key>($value)
{
if (Propel::<API key>() && $value !== null) {
if (is_object($value) && $value instanceof Profiles) {
$key = (string) $value->getOrganizationId();
} elseif (is_scalar($value)) {
// assume we've been passed a primary key
$key = (string) $value;
} else {
$e = new PropelException("Invalid value passed to <API key>(). Expected primary key or Profiles object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true)));
throw $e;
}
unset(self::$instances[$key]);
}
} // <API key>()
/**
* Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
*
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, a serialize()d version of the primary key will be returned.
*
* @param string $key The key (@see getPrimaryKeyHash()) for this instance.
* @return Profiles Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled.
* @see getPrimaryKeyHash()
*/
public static function getInstanceFromPool($key)
{
if (Propel::<API key>()) {
if (isset(self::$instances[$key])) {
return self::$instances[$key];
}
}
return null; // just to be explicit
}
/**
* Clear the instance pool.
*
* @return void
*/
public static function clearInstancePool()
{
self::$instances = array();
}
/**
* Method to invalidate the instance pool of all tables related to profiles
* by a foreign key with ON DELETE CASCADE
*/
public static function <API key>()
{
}
/**
* Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
*
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, a serialize()d version of the primary key will be returned.
*
* @param array $row PropelPDO resultset row.
* @param int $startcol The 0-based offset for reading from the resultset row.
* @return string A string version of PK or NULL if the components of primary key in result array are all null.
*/
public static function <API key>($row, $startcol = 0)
{
// If the PK cannot be derived from the row, return NULL.
if ($row[$startcol] === null) {
return null;
}
return (string) $row[$startcol];
}
/**
* Retrieves the primary key from the DB resultset row
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, an array of the primary key columns will be returned.
*
* @param array $row PropelPDO resultset row.
* @param int $startcol The 0-based offset for reading from the resultset row.
* @return mixed The primary key of the row
*/
public static function <API key>($row, $startcol = 0)
{
return (int) $row[$startcol];
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(PDOStatement $stmt)
{
$results = array();
// set the class once to avoid overhead in the loop
$cls = ProfilesPeer::getOMClass(false);
// populate the object(s)
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$key = ProfilesPeer::<API key>($row, 0);
if (null !== ($obj = ProfilesPeer::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// $obj->hydrate($row, 0, true); // rehydrate
$results[] = $obj;
} else {
$obj = new $cls();
$obj->hydrate($row);
$results[] = $obj;
ProfilesPeer::addInstanceToPool($obj, $key);
} // if key exists
}
$stmt->closeCursor();
return $results;
}
/**
* Populates an object of the default type or an object that inherit from the default.
*
* @param array $row PropelPDO resultset row.
* @param int $startcol The 0-based offset for reading from the resultset row.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return array (Profiles object, last column rank)
*/
public static function populateObject($row, $startcol = 0)
{
$key = ProfilesPeer::<API key>($row, $startcol);
if (null !== ($obj = ProfilesPeer::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// $obj->hydrate($row, $startcol, true); // rehydrate
$col = $startcol + ProfilesPeer::NUM_HYDRATE_COLUMNS;
} else {
$cls = ProfilesPeer::OM_CLASS;
$obj = new $cls();
$col = $obj->hydrate($row, $startcol);
ProfilesPeer::addInstanceToPool($obj, $key);
}
return array($obj, $col);
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME);
}
/**
* Add a TableMap instance to the database for this peer class.
*/
public static function buildTableMap()
{
$dbMap = Propel::getDatabaseMap(BaseProfilesPeer::DATABASE_NAME);
if (!$dbMap->hasTable(BaseProfilesPeer::TABLE_NAME))
{
$dbMap->addTableObject(new ProfilesTableMap());
}
}
/**
* The class that the Peer will make instances of.
*
* If $withPrefix is true, the returned path
* uses a dot-path notation which is tranalted into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @param boolean $withPrefix Whether or not to return the path with the class name
* @return string path.to.ClassName
*/
public static function getOMClass($withPrefix = true)
{
return $withPrefix ? ProfilesPeer::CLASS_DEFAULT : ProfilesPeer::OM_CLASS;
}
/**
* Performs an INSERT on the database, given a Profiles or Criteria object.
*
* @param mixed $values Criteria or Profiles object containing data that is used to create the INSERT statement.
* @param PropelPDO $con the PropelPDO connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($values, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(ProfilesPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from Profiles object
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->beginTransaction();
$pk = BasePeer::doInsert($criteria, $con);
$con->commit();
} catch(PropelException $e) {
$con->rollBack();
throw $e;
}
return $pk;
}
/**
* Performs an UPDATE on the database, given a Profiles or Criteria object.
*
* @param mixed $values Criteria or Profiles object containing data that is used to create the UPDATE statement.
* @param PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate($values, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(ProfilesPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$selectCriteria = new Criteria(self::DATABASE_NAME);
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison(ProfilesPeer::ORGANIZATION_ID);
$value = $criteria->remove(ProfilesPeer::ORGANIZATION_ID);
if ($value) {
$selectCriteria->add(ProfilesPeer::ORGANIZATION_ID, $value, $comparison);
} else {
$selectCriteria->setPrimaryTableName(ProfilesPeer::TABLE_NAME);
}
} else { // $values is Profiles object
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
return BasePeer::doUpdate($selectCriteria, $criteria, $con);
}
/**
* Deletes all rows from the profiles table.
*
* @param PropelPDO $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll(PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(ProfilesPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->beginTransaction();
$affectedRows += BasePeer::doDeleteAll(ProfilesPeer::TABLE_NAME, $con, ProfilesPeer::DATABASE_NAME);
// Because this db requires some delete cascade/set null emulation, we have to
// clear the cached instance *after* the emulation has happened (since
// instances get re-added by the select statement contained therein).
ProfilesPeer::clearInstancePool();
ProfilesPeer::<API key>();
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
/**
* Performs a DELETE on the database, given a Profiles or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or Profiles object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param PropelPDO $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(ProfilesPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
if ($values instanceof Criteria) {
// invalidate the cache for all objects of this type, since we have no
// way of knowing (without running a query) what objects should be invalidated
// from the cache based on this Criteria.
ProfilesPeer::clearInstancePool();
// rename for clarity
$criteria = clone $values;
} elseif ($values instanceof Profiles) { // it's a model object
// invalidate the cache for this single object
ProfilesPeer::<API key>($values);
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(ProfilesPeer::ORGANIZATION_ID, (array) $values, Criteria::IN);
// invalidate the cache for this object(s)
foreach ((array) $values as $singleval) {
ProfilesPeer::<API key>($singleval);
}
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->beginTransaction();
$affectedRows += BasePeer::doDelete($criteria, $con);
ProfilesPeer::<API key>();
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
/**
* Validates all modified columns of given Profiles object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param Profiles $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate($obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(ProfilesPeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(ProfilesPeer::TABLE_NAME);
if (! is_array($cols)) {
$cols = array($cols);
}
foreach ($cols as $colName) {
if ($tableMap->containsColumn($colName)) {
$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
return BasePeer::doValidate(ProfilesPeer::DATABASE_NAME, ProfilesPeer::TABLE_NAME, $columns);
}
/**
* Retrieve a single object by pkey.
*
* @param int $pk the primary key.
* @param PropelPDO $con the connection to use
* @return Profiles
*/
public static function retrieveByPK($pk, PropelPDO $con = null)
{
if (null !== ($obj = ProfilesPeer::getInstanceFromPool((string) $pk))) {
return $obj;
}
if ($con === null) {
$con = Propel::getConnection(ProfilesPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
$criteria = new Criteria(ProfilesPeer::DATABASE_NAME);
$criteria->add(ProfilesPeer::ORGANIZATION_ID, $pk);
$v = ProfilesPeer::doSelect($criteria, $con);
return !empty($v) > 0 ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param PropelPDO $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function retrieveByPKs($pks, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(ProfilesPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
$objs = null;
if (empty($pks)) {
$objs = array();
} else {
$criteria = new Criteria(ProfilesPeer::DATABASE_NAME);
$criteria->add(ProfilesPeer::ORGANIZATION_ID, $pks, Criteria::IN);
$objs = ProfilesPeer::doSelect($criteria, $con);
}
return $objs;
}
} // BaseProfilesPeer
// This is the static code needed to register the TableMap for this table with the main Propel class.
BaseProfilesPeer::buildTableMap(); |
<?php
try {
print getenv('ORACLE_HOME')."\n";
print var_export($_ENV,1 )."\n";
$user = "isitestools";
$pass = "iseegeeisitet00ls";
//$dbh = new PDO('oci:dbname=icgdb.fas.harvard.edu:1521/isitestools;charset=UTF8', $user, $pass);
$dbh = new PDO('oci:dbname=icgdbdev.fas.harvard.edu;charset=UTF8', $user, $pass);
foreach($dbh->query('SELECT * from QUIZMO_QUIZ where rownum = 1') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>\n\n";
die();
}
?> |
# python
from distutils.core import setup
setup(
name = 'zplot',
packages = ['zplot'],
version = '1.41',
description = 'A simple graph-creation library',
author = 'Remzi H. Arpaci-Dusseau',
author_email = 'remzi.arpacidusseau@gmail.com',
url = 'https://github.com/z-plot/z-plot',
download_url = 'https://github.com/z-plot/z-plot/tarball/1.4',
keywords = ['plotting', 'graphing', 'postscript', 'svg'],
classifiers = [],
) |
SERVICE_COMMAND="${SYNOPKG_PKGDEST}/bin/syncthing -home=${SYNOPKG_PKGVAR}"
SVC_BACKGROUND=y
SVC_WRITE_PID=y
GROUP="sc-syncthing"
service_prestart ()
{
# Read additional startup options from /usr/local/syncthing/var/options.conf
if [ -f ${SYNOPKG_PKGVAR}/options.conf ]; then
. ${SYNOPKG_PKGVAR}/options.conf
SERVICE_COMMAND="${SERVICE_COMMAND} ${SYNCTHING_OPTIONS}"
fi
# Required: set $HOME environment variable
HOME=${SYNOPKG_PKGVAR}
export HOME
} |
import express from 'express';
import graphQLHTTP from 'express-graphql';
import path from 'path';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import {Schema} from './data/schema';
const APP_PORT = 8888;
const GRAPHQL_PORT = 8080;
// Expose a GraphQL endpoint
var graphQLServer = express();
graphQLServer.use('/', graphQLHTTP({schema: Schema, pretty: true}));
graphQLServer.listen(GRAPHQL_PORT, () => console.log(
`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}`
));
// Serve the Relay app
var compiler = webpack({
entry: path.resolve(__dirname, 'js', 'app.js'),
eslint: {
configFile: '.eslintrc'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {stage: 0, plugins: ['./build/babelRelayPlugin']}
},
{
test: /\.js$/,
loader: 'eslint'
},
{
test: /\.less$/,
loader: 'style!css?modules&importLoaders=1' +
'&localIdentName=[name]__[local]___[hash:base64:5]!less'
}
]
},
output: {filename: 'app.js', path: '/'}
});
var app = new WebpackDevServer(compiler, {
contentBase: '/public/',
proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`},
publicPath: '/js/',
stats: {colors: true}
});
// Serve static resources
app.use('/', express.static('public'));
app.use('/node_modules/react', express.static('node_modules/react'));
app.use(
'/node_modules/react-relay',
express.static('node_modules/react-relay')
);
app.listen(process.env.PORT || APP_PORT, () => {
console.log(`App is now running on http://localhost:${APP_PORT}`);
}); |
/*global exports:true, require:true, global:true*/
(function () {
'use strict';
var Syntax,
Precedence,
BinaryPrecedence,
SourceNode,
estraverse,
esutils,
isArray,
base,
indent,
json,
renumber,
hexadecimal,
quotes,
escapeless,
newline,
space,
parentheses,
semicolons,
safeConcatenation,
directive,
extra,
parse,
sourceMap,
sourceCode,
preserveBlankLines,
FORMAT_MINIFY,
FORMAT_DEFAULTS;
estraverse = require('estraverse');
esutils = require('esutils');
Syntax = estraverse.Syntax;
// Generation is done by generateExpression.
function isExpression(node) {
return CodeGenerator.Expression.hasOwnProperty(node.type);
}
// Generation is done by generateStatement.
function isStatement(node) {
return CodeGenerator.Statement.hasOwnProperty(node.type);
}
Precedence = {
Sequence: 0,
Yield: 1,
Await: 1,
Assignment: 1,
Conditional: 2,
ArrowFunction: 2,
LogicalOR: 3,
LogicalAND: 4,
BitwiseOR: 5,
BitwiseXOR: 6,
BitwiseAND: 7,
Equality: 8,
Relational: 9,
BitwiseSHIFT: 10,
Additive: 11,
Multiplicative: 12,
Unary: 13,
Postfix: 14,
Call: 15,
New: 16,
TaggedTemplate: 17,
Member: 18,
Primary: 19
};
BinaryPrecedence = {
'||': Precedence.LogicalOR,
'&&': Precedence.LogicalAND,
'|': Precedence.BitwiseOR,
'^': Precedence.BitwiseXOR,
'&': Precedence.BitwiseAND,
'==': Precedence.Equality,
'!=': Precedence.Equality,
'===': Precedence.Equality,
'!==': Precedence.Equality,
'is': Precedence.Equality,
'isnt': Precedence.Equality,
'<': Precedence.Relational,
'>': Precedence.Relational,
'<=': Precedence.Relational,
'>=': Precedence.Relational,
'in': Precedence.Relational,
'instanceof': Precedence.Relational,
'<<': Precedence.BitwiseSHIFT,
'>>': Precedence.BitwiseSHIFT,
'>>>': Precedence.BitwiseSHIFT,
'+': Precedence.Additive,
'-': Precedence.Additive,
'*': Precedence.Multiplicative,
'%': Precedence.Multiplicative,
'/': Precedence.Multiplicative
};
//Flags
var F_ALLOW_IN = 1,
F_ALLOW_CALL = 1 << 1,
<API key> = 1 << 2,
F_FUNC_BODY = 1 << 3,
F_DIRECTIVE_CTX = 1 << 4,
F_SEMICOLON_OPT = 1 << 5;
//Expression flag sets
//NOTE: Flag order:
// F_ALLOW_IN
// F_ALLOW_CALL
// <API key>
var E_FTT = F_ALLOW_CALL | <API key>,
E_TTF = F_ALLOW_IN | F_ALLOW_CALL,
E_TTT = F_ALLOW_IN | F_ALLOW_CALL | <API key>,
E_TFF = F_ALLOW_IN,
E_FFT = <API key>,
E_TFT = F_ALLOW_IN | <API key>;
//Statement flag sets
//NOTE: Flag order:
// F_ALLOW_IN
// F_FUNC_BODY
// F_DIRECTIVE_CTX
// F_SEMICOLON_OPT
var S_TFFF = F_ALLOW_IN,
S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT,
S_FFFF = 0x00,
S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX,
S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
function getDefaultOptions() {
// default options
return {
indent: null,
base: null,
parse: null,
comment: false,
format: {
indent: {
style: ' ',
base: 0,
<API key>: false
},
newline: '\n',
space: ' ',
json: false,
renumber: false,
hexadecimal: false,
quotes: 'single',
escapeless: false,
compact: false,
parentheses: true,
semicolons: true,
safeConcatenation: false,
preserveBlankLines: false
},
moz: {
<API key>: false,
starlessGenerator: false
},
sourceMap: null,
sourceMapRoot: null,
sourceMapWithCode: false,
directive: false,
raw: true,
verbatim: null,
sourceCode: null
};
}
function stringRepeat(str, num) {
var result = '';
for (num |= 0; num > 0; num >>>= 1, str += str) {
if (num & 1) {
result += str;
}
}
return result;
}
isArray = Array.isArray;
if (!isArray) {
isArray = function isArray(array) {
return Object.prototype.toString.call(array) === '[object Array]';
};
}
function hasLineTerminator(str) {
return (/[\r\n]/g).test(str);
}
function <API key>(str) {
var len = str.length;
return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1));
}
function merge(target, override) {
var key;
for (key in override) {
if (override.hasOwnProperty(key)) {
target[key] = override[key];
}
}
return target;
}
function updateDeeply(target, override) {
var key, val;
function isHashObject(target) {
return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp);
}
for (key in override) {
if (override.hasOwnProperty(key)) {
val = override[key];
if (isHashObject(val)) {
if (isHashObject(target[key])) {
updateDeeply(target[key], val);
} else {
target[key] = updateDeeply({}, val);
}
} else {
target[key] = val;
}
}
}
return target;
}
function generateNumber(value) {
var result, point, temp, exponent, pos;
if (value !== value) {
throw new Error('Numeric literal whose value is NaN');
}
if (value < 0 || (value === 0 && 1 / value < 0)) {
throw new Error('Numeric literal whose value is negative');
}
if (value === 1 / 0) {
return json ? 'null' : renumber ? '1e400' : '1e+400';
}
result = '' + value;
if (!renumber || result.length < 3) {
return result;
}
point = result.indexOf('.');
if (!json && result.charCodeAt(0) === 0x30 && point === 1) {
point = 0;
result = result.slice(1);
}
temp = result;
result = result.replace('e+', 'e');
exponent = 0;
if ((pos = temp.indexOf('e')) > 0) {
exponent = +temp.slice(pos + 1);
temp = temp.slice(0, pos);
}
if (point >= 0) {
exponent -= temp.length - point - 1;
temp = +(temp.slice(0, point) + temp.slice(point + 1)) + '';
}
pos = 0;
while (temp.charCodeAt(temp.length + pos - 1) === 0x30 ) {
--pos;
}
if (pos !== 0) {
exponent -= pos;
temp = temp.slice(0, pos);
}
if (exponent !== 0) {
temp += 'e' + exponent;
}
if ((temp.length < result.length ||
(hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) &&
+temp === value) {
result = temp;
}
return result;
}
// Generate valid RegExp expression.
function <API key>(ch, previousIsBackslash) {
// not handling '\' and handling \u2028 or \u2029 to unicode escape sequence
if ((ch & ~1) === 0x2028) {
return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029');
} else if (ch === 10 || ch === 13) { // \n, \r
return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r');
}
return String.fromCharCode(ch);
}
function generateRegExp(reg) {
var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash;
result = reg.toString();
if (reg.source) {
// extract flag from toString result
match = result.match(/\/([^/]*)$/);
if (!match) {
return result;
}
flags = match[1];
result = '';
characterInBrack = false;
previousIsBackslash = false;
for (i = 0, iz = reg.source.length; i < iz; ++i) {
ch = reg.source.charCodeAt(i);
if (!previousIsBackslash) {
if (characterInBrack) {
if (ch === 93) {
characterInBrack = false;
}
} else {
if (ch === 47) {
result += '\\';
} else if (ch === 91) {
characterInBrack = true;
}
}
result += <API key>(ch, previousIsBackslash);
previousIsBackslash = ch === 92;
} else {
// if new RegExp("\\\n') is provided, create /\n/
result += <API key>(ch, previousIsBackslash);
// prevent like /\\[/]/
previousIsBackslash = false;
}
}
return '/' + result + '/' + flags;
}
return result;
}
function <API key>(code, next) {
var hex;
if (code === 0x08 ) {
return '\\b';
}
if (code === 0x0C ) {
return '\\f';
}
if (code === 0x09 ) {
return '\\t';
}
hex = code.toString(16).toUpperCase();
if (json || code > 0xFF) {
return '\\u' + '0000'.slice(hex.length) + hex;
} else if (code === 0x0000 && !esutils.code.isDecimalDigit(next)) {
return '\\0';
} else if (code === 0x000B ) { // '\v'
return '\\x0B';
} else {
return '\\x' + '00'.slice(hex.length) + hex;
}
}
function <API key>(code) {
if (code === 0x5C ) {
return '\\\\';
}
if (code === 0x0A ) {
return '\\n';
}
if (code === 0x0D ) {
return '\\r';
}
if (code === 0x2028) {
return '\\u2028';
}
if (code === 0x2029) {
return '\\u2029';
}
throw new Error('Incorrectly classified character');
}
function escapeDirective(str) {
var i, iz, code, quote;
quote = quotes === 'double' ? '"' : '\'';
for (i = 0, iz = str.length; i < iz; ++i) {
code = str.charCodeAt(i);
if (code === 0x27 ) {
quote = '"';
break;
} else if (code === 0x22 ) {
quote = '\'';
break;
} else if (code === 0x5C ) {
++i;
}
}
return quote + str + quote;
}
function escapeString(str) {
var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote;
for (i = 0, len = str.length; i < len; ++i) {
code = str.charCodeAt(i);
if (code === 0x27 ) {
++singleQuotes;
} else if (code === 0x22 ) {
++doubleQuotes;
} else if (code === 0x2F && json) {
result += '\\';
} else if (esutils.code.isLineTerminator(code) || code === 0x5C ) {
result += <API key>(code);
continue;
} else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 0x20 || !json && !escapeless && (code < 0x20 || code > 0x7E ))) {
result += <API key>(code, str.charCodeAt(i + 1));
continue;
}
result += String.fromCharCode(code);
}
single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes));
quote = single ? '\'' : '"';
if (!(single ? singleQuotes : doubleQuotes)) {
return quote + result + quote;
}
str = result;
result = quote;
for (i = 0, len = str.length; i < len; ++i) {
code = str.charCodeAt(i);
if ((code === 0x27 && single) || (code === 0x22 && !single)) {
result += '\\';
}
result += String.fromCharCode(code);
}
return result + quote;
}
/**
* flatten an array to a string, where the array can contain
* either strings or nested arrays
*/
function flattenToString(arr) {
var i, iz, elem, result = '';
for (i = 0, iz = arr.length; i < iz; ++i) {
elem = arr[i];
result += isArray(elem) ? flattenToString(elem) : elem;
}
return result;
}
/**
* convert generated to a SourceNode when source maps are enabled.
*/
function <API key>(generated, node) {
if (!sourceMap) {
// with no source maps, generated is either an
// array or a string. if an array, flatten it.
// if a string, just return it
if (isArray(generated)) {
return flattenToString(generated);
} else {
return generated;
}
}
if (node == null) {
if (generated instanceof SourceNode) {
return generated;
} else {
node = {};
}
}
if (node.loc == null) {
return new SourceNode(null, null, sourceMap, generated, node.name || null);
}
return new SourceNode(node.loc.start.line, node.loc.start.column, (sourceMap === true ? node.loc.source || null : sourceMap), generated, node.name || null);
}
function noEmptySpace() {
return (space) ? space : ' ';
}
function join(left, right) {
var leftSource,
rightSource,
leftCharCode,
rightCharCode;
leftSource = <API key>(left).toString();
if (leftSource.length === 0) {
return [right];
}
rightSource = <API key>(right).toString();
if (rightSource.length === 0) {
return [left];
}
leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
rightCharCode = rightSource.charCodeAt(0);
if ((leftCharCode === 0x2B || leftCharCode === 0x2D ) && leftCharCode === rightCharCode ||
esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) ||
leftCharCode === 0x2F && rightCharCode === 0x69 ) { // infix word operators all start with `i`
return [left, noEmptySpace(), right];
} else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) ||
esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) {
return [left, right];
}
return [left, space, right];
}
function addIndent(stmt, indent) {
var baseSourceNode = typeof indent === 'undefined' ? base : indent;
// use SourceNode so it does not break source-maps mappings
// this will make sure that the line is kept when indentation is added
if (sourceMap) {
baseSourceNode = new SourceNode(
stmt.line,
0,
stmt.source || null,
base,
null
);
}
return [baseSourceNode, stmt];
}
function withIndent(fn) {
var previousBase;
previousBase = base;
base += indent;
fn(base);
base = previousBase;
}
function calculateSpaces(str) {
var i;
for (i = str.length - 1; i >= 0; --i) {
if (esutils.code.isLineTerminator(str.charCodeAt(i))) {
break;
}
}
return (str.length - 1) - i;
}
function <API key>(value, specialBase) {
var array, i, len, line, j, spaces, previousBase, sn;
array = value.split(/\r\n|[\r\n]/);
spaces = Number.MAX_VALUE;
// first line doesn't have indentation
for (i = 1, len = array.length; i < len; ++i) {
line = array[i];
j = 0;
while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) {
++j;
}
if (spaces > j) {
spaces = j;
}
}
if (typeof specialBase !== 'undefined') {
// pattern like
// var t = 20; /*
// * this is comment
// */
previousBase = base;
if (array[1][spaces] === '*') {
specialBase += ' ';
}
base = specialBase;
} else {
if (spaces & 1) {
// If spaces are odd number, above pattern is considered.
// We waste 1 space.
--spaces;
}
previousBase = base;
}
for (i = 1, len = array.length; i < len; ++i) {
sn = <API key>(addIndent(array[i].slice(spaces)));
array[i] = sourceMap ? sn.join('') : sn;
}
base = previousBase;
return array.join('\n');
}
function generateComment(comment, specialBase) {
if (comment.type === 'Line') {
if (<API key>(comment.value)) {
return '//' + comment.value;
} else {
// Always use LineTerminator
var result = '//' + comment.value;
if (!preserveBlankLines) {
result += '\n';
}
return result;
}
}
if (extra.format.indent.<API key> && /[\n\r]/.test(comment.value)) {
return <API key>('/*' + comment.value + '*/', specialBase);
}
return '/*' + comment.value + '*/';
}
function addComments(stmt, result) {
var i, len, comment, save, tailingToStatement, specialBase, fragment,
extRange, range, prevRange, prefix, infix, suffix, count;
if (stmt.leadingComments && stmt.leadingComments.length > 0) {
save = result;
if (preserveBlankLines) {
comment = stmt.leadingComments[0];
result = [];
extRange = comment.extendedRange;
range = comment.range;
prefix = sourceCode.substring(extRange[0], range[0]);
count = (prefix.match(/\n/g) || []).length;
if (count > 0) {
result.push(stringRepeat('\n', count));
result.push(addIndent(generateComment(comment)));
} else {
result.push(prefix);
result.push(generateComment(comment));
}
prevRange = range;
for (i = 1, len = stmt.leadingComments.length; i < len; i++) {
comment = stmt.leadingComments[i];
range = comment.range;
infix = sourceCode.substring(prevRange[1], range[0]);
count = (infix.match(/\n/g) || []).length;
result.push(stringRepeat('\n', count));
result.push(addIndent(generateComment(comment)));
prevRange = range;
}
suffix = sourceCode.substring(range[1], extRange[1]);
count = (suffix.match(/\n/g) || []).length;
result.push(stringRepeat('\n', count));
} else {
comment = stmt.leadingComments[0];
result = [];
if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) {
result.push('\n');
}
result.push(generateComment(comment));
if (!<API key>(<API key>(result).toString())) {
result.push('\n');
}
for (i = 1, len = stmt.leadingComments.length; i < len; ++i) {
comment = stmt.leadingComments[i];
fragment = [generateComment(comment)];
if (!<API key>(<API key>(fragment).toString())) {
fragment.push('\n');
}
result.push(addIndent(fragment));
}
}
result.push(addIndent(save));
}
if (stmt.trailingComments) {
if (preserveBlankLines) {
comment = stmt.trailingComments[0];
extRange = comment.extendedRange;
range = comment.range;
prefix = sourceCode.substring(extRange[0], range[0]);
count = (prefix.match(/\n/g) || []).length;
if (count > 0) {
result.push(stringRepeat('\n', count));
result.push(addIndent(generateComment(comment)));
} else {
result.push(prefix);
result.push(generateComment(comment));
}
} else {
tailingToStatement = !<API key>(<API key>(result).toString());
specialBase = stringRepeat(' ', calculateSpaces(<API key>([base, result, indent]).toString()));
for (i = 0, len = stmt.trailingComments.length; i < len; ++i) {
comment = stmt.trailingComments[i];
if (tailingToStatement) {
// We assume target like following script
// var t = 20; /**
// * This is comment of t
// */
if (i === 0) {
// first case
result = [result, indent];
} else {
result = [result, specialBase];
}
result.push(generateComment(comment, specialBase));
} else {
result = [result, addIndent(generateComment(comment))];
}
if (i !== len - 1 && !<API key>(<API key>(result).toString())) {
result = [result, '\n'];
}
}
}
}
return result;
}
function generateBlankLines(start, end, result) {
var j, newlineCount = 0;
for (j = start; j < end; j++) {
if (sourceCode[j] === '\n') {
newlineCount++;
}
}
for (j = 1; j < newlineCount; j++) {
result.push(newline);
}
}
function parenthesize(text, current, should) {
if (current < should) {
return ['(', text, ')'];
}
return text;
}
function <API key>(string) {
var i, iz, result;
result = string.split(/\r\n|\n/);
for (i = 1, iz = result.length; i < iz; i++) {
result[i] = newline + base + result[i];
}
return result;
}
function generateVerbatim(expr, precedence) {
var verbatim, result, prec;
verbatim = expr[extra.verbatim];
if (typeof verbatim === 'string') {
result = parenthesize(<API key>(verbatim), Precedence.Sequence, precedence);
} else {
// verbatim is object
result = <API key>(verbatim.content);
prec = (verbatim.precedence != null) ? verbatim.precedence : Precedence.Sequence;
result = parenthesize(result, prec, precedence);
}
return <API key>(result, expr);
}
function CodeGenerator() {
}
// Helpers.
CodeGenerator.prototype.maybeBlock = function(stmt, flags) {
var result, noLeadingComment, that = this;
noLeadingComment = !extra.comment || !stmt.leadingComments;
if (stmt.type === Syntax.BlockStatement && noLeadingComment) {
return [space, this.generateStatement(stmt, flags)];
}
if (stmt.type === Syntax.EmptyStatement && noLeadingComment) {
return ';';
}
withIndent(function () {
result = [
newline,
addIndent(that.generateStatement(stmt, flags))
];
});
return result;
};
CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) {
var ends = <API key>(<API key>(result).toString());
if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) {
return [result, space];
}
if (ends) {
return [result, base];
}
return [result, newline, base];
};
function generateIdentifier(node) {
return <API key>(node.name, node);
}
function generateAsyncPrefix(node, spaceRequired) {
return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : '';
}
function generateStarSuffix(node) {
var isGenerator = node.generator && !extra.moz.starlessGenerator;
return isGenerator ? '*' + space : '';
}
function <API key>(prop) {
var func = prop.value;
if (func.async) {
return generateAsyncPrefix(func, !prop.computed);
} else {
// avoid space before method name
return generateStarSuffix(func) ? '*' : '';
}
}
CodeGenerator.prototype.generatePattern = function (node, precedence, flags) {
if (node.type === Syntax.Identifier) {
return generateIdentifier(node);
}
return this.generateExpression(node, precedence, flags);
};
CodeGenerator.prototype.<API key> = function (node) {
var i, iz, result, hasDefault;
hasDefault = false;
if (node.type === Syntax.<API key> &&
!node.rest && (!node.defaults || node.defaults.length === 0) &&
node.params.length === 1 && node.params[0].type === Syntax.Identifier) {
// arg => { } case
result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])];
} else {
result = node.type === Syntax.<API key> ? [generateAsyncPrefix(node, false)] : [];
result.push('(');
if (node.defaults) {
hasDefault = true;
}
for (i = 0, iz = node.params.length; i < iz; ++i) {
if (hasDefault && node.defaults[i]) {
// Handle default values.
result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT));
} else {
result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT));
}
if (i + 1 < iz) {
result.push(',' + space);
}
}
if (node.rest) {
if (node.params.length) {
result.push(',' + space);
}
result.push('...');
result.push(generateIdentifier(node.rest));
}
result.push(')');
}
return result;
};
CodeGenerator.prototype.<API key> = function (node) {
var result, expr;
result = this.<API key>(node);
if (node.type === Syntax.<API key>) {
result.push(space);
result.push('=>');
}
if (node.expression) {
result.push(space);
expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT);
if (expr.toString().charAt(0) === '{') {
expr = ['(', expr, ')'];
}
result.push(expr);
} else {
result.push(this.maybeBlock(node.body, S_TTFF));
}
return result;
};
CodeGenerator.prototype.<API key> = function (operator, stmt, flags) {
var result = ['for' + space + '('], that = this;
withIndent(function () {
if (stmt.left.type === Syntax.VariableDeclaration) {
withIndent(function () {
result.push(stmt.left.kind + noEmptySpace());
result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF));
});
} else {
result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT));
}
result = join(result, operator);
result = [join(
result,
that.generateExpression(stmt.right, Precedence.Sequence, E_TTT)
), ')'];
});
result.push(this.maybeBlock(stmt.body, flags));
return result;
};
CodeGenerator.prototype.generatePropertyKey = function (expr, computed) {
var result = [];
if (computed) {
result.push('[');
}
result.push(this.generateExpression(expr, Precedence.Sequence, E_TTT));
if (computed) {
result.push(']');
}
return result;
};
CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) {
if (Precedence.Assignment < precedence) {
flags |= F_ALLOW_IN;
}
return parenthesize(
[
this.generateExpression(left, Precedence.Call, flags),
space + operator + space,
this.generateExpression(right, Precedence.Assignment, flags)
],
Precedence.Assignment,
precedence
);
};
CodeGenerator.prototype.semicolon = function (flags) {
if (!semicolons && flags & F_SEMICOLON_OPT) {
return '';
}
return ';';
};
// Statements.
CodeGenerator.Statement = {
BlockStatement: function (stmt, flags) {
var range, content, result = ['{', newline], that = this;
withIndent(function () {
// handle functions without any code
if (stmt.body.length === 0 && preserveBlankLines) {
range = stmt.range;
if (range[1] - range[0] > 2) {
content = sourceCode.substring(range[0] + 1, range[1] - 1);
if (content[0] === '\n') {
result = ['{'];
}
result.push(content);
}
}
var i, iz, fragment, bodyFlags;
bodyFlags = S_TFFF;
if (flags & F_FUNC_BODY) {
bodyFlags |= F_DIRECTIVE_CTX;
}
for (i = 0, iz = stmt.body.length; i < iz; ++i) {
if (preserveBlankLines) {
// handle spaces before the first line
if (i === 0) {
if (stmt.body[0].leadingComments) {
range = stmt.body[0].leadingComments[0].extendedRange;
content = sourceCode.substring(range[0], range[1]);
if (content[0] === '\n') {
result = ['{'];
}
}
if (!stmt.body[0].leadingComments) {
generateBlankLines(stmt.range[0], stmt.body[0].range[0], result);
}
}
// handle spaces between lines
if (i > 0) {
if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
}
}
}
if (i === iz - 1) {
bodyFlags |= F_SEMICOLON_OPT;
}
if (stmt.body[i].leadingComments && preserveBlankLines) {
fragment = that.generateStatement(stmt.body[i], bodyFlags);
} else {
fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags));
}
result.push(fragment);
if (!<API key>(<API key>(fragment).toString())) {
if (preserveBlankLines && i < iz - 1) {
// don't add a new line if there are leading coments
// in the next statement
if (!stmt.body[i + 1].leadingComments) {
result.push(newline);
}
} else {
result.push(newline);
}
}
if (preserveBlankLines) {
// handle spaces after the last line
if (i === iz - 1) {
if (!stmt.body[i].trailingComments) {
generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
}
}
}
}
});
result.push(addIndent('}'));
return result;
},
BreakStatement: function (stmt, flags) {
if (stmt.label) {
return 'break ' + stmt.label.name + this.semicolon(flags);
}
return 'break' + this.semicolon(flags);
},
ContinueStatement: function (stmt, flags) {
if (stmt.label) {
return 'continue ' + stmt.label.name + this.semicolon(flags);
}
return 'continue' + this.semicolon(flags);
},
ClassBody: function (stmt, flags) {
var result = [ '{', newline], that = this;
withIndent(function (indent) {
var i, iz;
for (i = 0, iz = stmt.body.length; i < iz; ++i) {
result.push(
addIndent(
that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT),
indent
)
);
if (i + 1 < iz) {
result.push(newline);
}
}
});
if (!<API key>(<API key>(result).toString())) {
result.push(newline);
}
result.push(base);
result.push('}');
return result;
},
ClassDeclaration: function (stmt, flags) {
var result, fragment;
result = ['class'];
if (stmt.id) {
result = join(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT));
}
if (stmt.superClass) {
fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Assignment, E_TTT));
result = join(result, fragment);
}
result.push(space);
result.push(this.generateStatement(stmt.body, S_TFFT));
return result;
},
DirectiveStatement: function (stmt, flags) {
if (extra.raw && stmt.raw) {
return stmt.raw + this.semicolon(flags);
}
return escapeDirective(stmt.directive) + this.semicolon(flags);
},
DoWhileStatement: function (stmt, flags) {
// Because `do 42 while (cond)` is Syntax Error. We need semicolon.
var result = join('do', this.maybeBlock(stmt.body, S_TFFF));
result = this.maybeBlockSuffix(stmt.body, result);
return join(result, [
'while' + space + '(',
this.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
')' + this.semicolon(flags)
]);
},
CatchClause: function (stmt, flags) {
var result, that = this;
withIndent(function () {
var guard;
result = [
'catch' + space + '(',
that.generateExpression(stmt.param, Precedence.Sequence, E_TTT),
')'
];
if (stmt.guard) {
guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT);
result.splice(2, 0, ' if ', guard);
}
});
result.push(this.maybeBlock(stmt.body, S_TFFF));
return result;
},
DebuggerStatement: function (stmt, flags) {
return 'debugger' + this.semicolon(flags);
},
EmptyStatement: function (stmt, flags) {
return ';';
},
<API key>: function (stmt, flags) {
var result = [ 'export' ], bodyFlags;
bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
// export default <API key>[Default]
// export default <API key>[In] ;
result = join(result, 'default');
if (isStatement(stmt.declaration)) {
result = join(result, this.generateStatement(stmt.declaration, bodyFlags));
} else {
result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags));
}
return result;
},
<API key>: function (stmt, flags) {
var result = [ 'export' ], bodyFlags, that = this;
bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
// export VariableStatement
// export Declaration[Default]
if (stmt.declaration) {
return join(result, this.generateStatement(stmt.declaration, bodyFlags));
}
// export ExportClause[NoReference] FromClause ;
// export ExportClause ;
if (stmt.specifiers) {
if (stmt.specifiers.length === 0) {
result = join(result, '{' + space + '}');
} else if (stmt.specifiers[0].type === Syntax.<API key>) {
result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));
} else {
result = join(result, '{');
withIndent(function (indent) {
var i, iz;
result.push(newline);
for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) {
result.push(
addIndent(
that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT),
indent
)
);
if (i + 1 < iz) {
result.push(',' + newline);
}
}
});
if (!<API key>(<API key>(result).toString())) {
result.push(newline);
}
result.push(base + '}');
}
if (stmt.source) {
result = join(result, [
'from' + space,
// ModuleSpecifier
this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
this.semicolon(flags)
]);
} else {
result.push(this.semicolon(flags));
}
}
return result;
},
<API key>: function (stmt, flags) {
// export * FromClause ;
return [
'export' + space,
'*' + space,
'from' + space,
// ModuleSpecifier
this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
this.semicolon(flags)
];
},
ExpressionStatement: function (stmt, flags) {
var result, fragment;
function isClassPrefixed(fragment) {
var code;
if (fragment.slice(0, 5) !== 'class') {
return false;
}
code = fragment.charCodeAt(5);
return code === 0x7B || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code);
}
function isFunctionPrefixed(fragment) {
var code;
if (fragment.slice(0, 8) !== 'function') {
return false;
}
code = fragment.charCodeAt(8);
return code === 0x28 || esutils.code.isWhiteSpace(code) || code === 0x2A || esutils.code.isLineTerminator(code);
}
function isAsyncPrefixed(fragment) {
var code, i, iz;
if (fragment.slice(0, 5) !== 'async') {
return false;
}
if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) {
return false;
}
for (i = 6, iz = fragment.length; i < iz; ++i) {
if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) {
break;
}
}
if (i === iz) {
return false;
}
if (fragment.slice(i, i + 8) !== 'function') {
return false;
}
code = fragment.charCodeAt(i + 8);
return code === 0x28 || esutils.code.isWhiteSpace(code) || code === 0x2A || esutils.code.isLineTerminator(code);
}
result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)];
// 12.4 '{', 'function', 'class' is not allowed in this position.
// wrap expression with parentheses
fragment = <API key>(result).toString();
if (fragment.charCodeAt(0) === 0x7B || // ObjectExpression
isClassPrefixed(fragment) ||
isFunctionPrefixed(fragment) ||
isAsyncPrefixed(fragment) ||
(directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string')) {
result = ['(', result, ')' + this.semicolon(flags)];
} else {
result.push(this.semicolon(flags));
}
return result;
},
ImportDeclaration: function (stmt, flags) {
// ES6: 15.2.1 valid import declarations:
// - import ImportClause FromClause ;
// - import ModuleSpecifier ;
var result, cursor, that = this;
// If no ImportClause is present,
// this should be `import ModuleSpecifier` so skip `from`
// ModuleSpecifier is StringLiteral.
if (stmt.specifiers.length === 0) {
// import ModuleSpecifier ;
return [
'import',
space,
// ModuleSpecifier
this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
this.semicolon(flags)
];
}
// import ImportClause FromClause ;
result = [
'import'
];
cursor = 0;
// ImportedBinding
if (stmt.specifiers[cursor].type === Syntax.<API key>) {
result = join(result, [
this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
]);
++cursor;
}
if (stmt.specifiers[cursor]) {
if (cursor !== 0) {
result.push(',');
}
if (stmt.specifiers[cursor].type === Syntax.<API key>) {
// NameSpaceImport
result = join(result, [
space,
this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
]);
} else {
// NamedImports
result.push(space + '{');
if ((stmt.specifiers.length - cursor) === 1) {
// import { ... } from "...";
result.push(space);
result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT));
result.push(space + '}' + space);
} else {
// import {
// } from "...";
withIndent(function (indent) {
var i, iz;
result.push(newline);
for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {
result.push(
addIndent(
that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT),
indent
)
);
if (i + 1 < iz) {
result.push(',' + newline);
}
}
});
if (!<API key>(<API key>(result).toString())) {
result.push(newline);
}
result.push(base + '}' + space);
}
}
}
result = join(result, [
'from' + space,
// ModuleSpecifier
this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
this.semicolon(flags)
]);
return result;
},
VariableDeclarator: function (stmt, flags) {
var itemFlags = (flags & F_ALLOW_IN) ? E_TTT : E_FTT;
if (stmt.init) {
return [
this.generateExpression(stmt.id, Precedence.Assignment, itemFlags),
space,
'=',
space,
this.generateExpression(stmt.init, Precedence.Assignment, itemFlags)
];
}
return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags);
},
VariableDeclaration: function (stmt, flags) {
// VariableDeclarator is typed as Statement,
// but joined with comma (not LineTerminator).
// So if comment is attached to target node, we should specialize.
var result, i, iz, node, bodyFlags, that = this;
result = [ stmt.kind ];
bodyFlags = (flags & F_ALLOW_IN) ? S_TFFF : S_FFFF;
function block() {
node = stmt.declarations[0];
if (extra.comment && node.leadingComments) {
result.push('\n');
result.push(addIndent(that.generateStatement(node, bodyFlags)));
} else {
result.push(noEmptySpace());
result.push(that.generateStatement(node, bodyFlags));
}
for (i = 1, iz = stmt.declarations.length; i < iz; ++i) {
node = stmt.declarations[i];
if (extra.comment && node.leadingComments) {
result.push(',' + newline);
result.push(addIndent(that.generateStatement(node, bodyFlags)));
} else {
result.push(',' + space);
result.push(that.generateStatement(node, bodyFlags));
}
}
}
if (stmt.declarations.length > 1) {
withIndent(block);
} else {
block();
}
result.push(this.semicolon(flags));
return result;
},
ThrowStatement: function (stmt, flags) {
return [join(
'throw',
this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
), this.semicolon(flags)];
},
TryStatement: function (stmt, flags) {
var result, i, iz, guardedHandlers;
result = ['try', this.maybeBlock(stmt.block, S_TFFF)];
result = this.maybeBlockSuffix(stmt.block, result);
if (stmt.handlers) {
// old interface
for (i = 0, iz = stmt.handlers.length; i < iz; ++i) {
result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF));
if (stmt.finalizer || i + 1 !== iz) {
result = this.maybeBlockSuffix(stmt.handlers[i].body, result);
}
}
} else {
guardedHandlers = stmt.guardedHandlers || [];
for (i = 0, iz = guardedHandlers.length; i < iz; ++i) {
result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF));
if (stmt.finalizer || i + 1 !== iz) {
result = this.maybeBlockSuffix(guardedHandlers[i].body, result);
}
}
// new interface
if (stmt.handler) {
if (isArray(stmt.handler)) {
for (i = 0, iz = stmt.handler.length; i < iz; ++i) {
result = join(result, this.generateStatement(stmt.handler[i], S_TFFF));
if (stmt.finalizer || i + 1 !== iz) {
result = this.maybeBlockSuffix(stmt.handler[i].body, result);
}
}
} else {
result = join(result, this.generateStatement(stmt.handler, S_TFFF));
if (stmt.finalizer) {
result = this.maybeBlockSuffix(stmt.handler.body, result);
}
}
}
}
if (stmt.finalizer) {
result = join(result, ['finally', this.maybeBlock(stmt.finalizer, S_TFFF)]);
}
return result;
},
SwitchStatement: function (stmt, flags) {
var result, fragment, i, iz, bodyFlags, that = this;
withIndent(function () {
result = [
'switch' + space + '(',
that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT),
')' + space + '{' + newline
];
});
if (stmt.cases) {
bodyFlags = S_TFFF;
for (i = 0, iz = stmt.cases.length; i < iz; ++i) {
if (i === iz - 1) {
bodyFlags |= F_SEMICOLON_OPT;
}
fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags));
result.push(fragment);
if (!<API key>(<API key>(fragment).toString())) {
result.push(newline);
}
}
}
result.push(addIndent('}'));
return result;
},
SwitchCase: function (stmt, flags) {
var result, fragment, i, iz, bodyFlags, that = this;
withIndent(function () {
if (stmt.test) {
result = [
join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)),
':'
];
} else {
result = ['default:'];
}
i = 0;
iz = stmt.consequent.length;
if (iz && stmt.consequent[0].type === Syntax.BlockStatement) {
fragment = that.maybeBlock(stmt.consequent[0], S_TFFF);
result.push(fragment);
i = 1;
}
if (i !== iz && !<API key>(<API key>(result).toString())) {
result.push(newline);
}
bodyFlags = S_TFFF;
for (; i < iz; ++i) {
if (i === iz - 1 && flags & F_SEMICOLON_OPT) {
bodyFlags |= F_SEMICOLON_OPT;
}
fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags));
result.push(fragment);
if (i + 1 !== iz && !<API key>(<API key>(fragment).toString())) {
result.push(newline);
}
}
});
return result;
},
IfStatement: function (stmt, flags) {
var result, bodyFlags, semicolonOptional, that = this;
withIndent(function () {
result = [
'if' + space + '(',
that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
')'
];
});
semicolonOptional = flags & F_SEMICOLON_OPT;
bodyFlags = S_TFFF;
if (semicolonOptional) {
bodyFlags |= F_SEMICOLON_OPT;
}
if (stmt.alternate) {
result.push(this.maybeBlock(stmt.consequent, S_TFFF));
result = this.maybeBlockSuffix(stmt.consequent, result);
if (stmt.alternate.type === Syntax.IfStatement) {
result = join(result, ['else ', this.generateStatement(stmt.alternate, bodyFlags)]);
} else {
result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags)));
}
} else {
result.push(this.maybeBlock(stmt.consequent, bodyFlags));
}
return result;
},
ForStatement: function (stmt, flags) {
var result, that = this;
withIndent(function () {
result = ['for' + space + '('];
if (stmt.init) {
if (stmt.init.type === Syntax.VariableDeclaration) {
result.push(that.generateStatement(stmt.init, S_FFFF));
} else {
// F_ALLOW_IN becomes false.
result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT));
result.push(';');
}
} else {
result.push(';');
}
if (stmt.test) {
result.push(space);
result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT));
result.push(';');
} else {
result.push(';');
}
if (stmt.update) {
result.push(space);
result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT));
result.push(')');
} else {
result.push(')');
}
});
result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
return result;
},
ForInStatement: function (stmt, flags) {
return this.<API key>('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
},
ForOfStatement: function (stmt, flags) {
return this.<API key>('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
},
LabeledStatement: function (stmt, flags) {
return [stmt.label.name + ':', this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)];
},
Program: function (stmt, flags) {
var result, fragment, i, iz, bodyFlags;
iz = stmt.body.length;
result = [safeConcatenation && iz > 0 ? '\n' : ''];
bodyFlags = S_TFTF;
for (i = 0; i < iz; ++i) {
if (!safeConcatenation && i === iz - 1) {
bodyFlags |= F_SEMICOLON_OPT;
}
if (preserveBlankLines) {
// handle spaces before the first line
if (i === 0) {
if (!stmt.body[0].leadingComments) {
generateBlankLines(stmt.range[0], stmt.body[i].range[0], result);
}
}
// handle spaces between lines
if (i > 0) {
if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
}
}
}
fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags));
result.push(fragment);
if (i + 1 < iz && !<API key>(<API key>(fragment).toString())) {
if (preserveBlankLines) {
if (!stmt.body[i + 1].leadingComments) {
result.push(newline);
}
} else {
result.push(newline);
}
}
if (preserveBlankLines) {
// handle spaces after the last line
if (i === iz - 1) {
if (!stmt.body[i].trailingComments) {
generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
}
}
}
}
return result;
},
FunctionDeclaration: function (stmt, flags) {
return [
generateAsyncPrefix(stmt, true),
'function',
generateStarSuffix(stmt) || noEmptySpace(),
stmt.id ? generateIdentifier(stmt.id) : '',
this.<API key>(stmt)
];
},
ReturnStatement: function (stmt, flags) {
if (stmt.argument) {
return [join(
'return',
this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
), this.semicolon(flags)];
}
return ['return' + this.semicolon(flags)];
},
WhileStatement: function (stmt, flags) {
var result, that = this;
withIndent(function () {
result = [
'while' + space + '(',
that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
')'
];
});
result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
return result;
},
WithStatement: function (stmt, flags) {
var result, that = this;
withIndent(function () {
result = [
'with' + space + '(',
that.generateExpression(stmt.object, Precedence.Sequence, E_TTT),
')'
];
});
result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
return result;
}
};
merge(CodeGenerator.prototype, CodeGenerator.Statement);
// Expressions.
CodeGenerator.Expression = {
SequenceExpression: function (expr, precedence, flags) {
var result, i, iz;
if (Precedence.Sequence < precedence) {
flags |= F_ALLOW_IN;
}
result = [];
for (i = 0, iz = expr.expressions.length; i < iz; ++i) {
result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags));
if (i + 1 < iz) {
result.push(',' + space);
}
}
return parenthesize(result, Precedence.Sequence, precedence);
},
<API key>: function (expr, precedence, flags) {
return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags);
},
<API key>: function (expr, precedence, flags) {
return parenthesize(this.<API key>(expr), Precedence.ArrowFunction, precedence);
},
<API key>: function (expr, precedence, flags) {
if (Precedence.Conditional < precedence) {
flags |= F_ALLOW_IN;
}
return parenthesize(
[
this.generateExpression(expr.test, Precedence.LogicalOR, flags),
space + '?' + space,
this.generateExpression(expr.consequent, Precedence.Assignment, flags),
space + ':' + space,
this.generateExpression(expr.alternate, Precedence.Assignment, flags)
],
Precedence.Conditional,
precedence
);
},
LogicalExpression: function (expr, precedence, flags) {
return this.BinaryExpression(expr, precedence, flags);
},
BinaryExpression: function (expr, precedence, flags) {
var result, currentPrecedence, fragment, leftSource;
currentPrecedence = BinaryPrecedence[expr.operator];
if (currentPrecedence < precedence) {
flags |= F_ALLOW_IN;
}
fragment = this.generateExpression(expr.left, currentPrecedence, flags);
leftSource = fragment.toString();
if (leftSource.charCodeAt(leftSource.length - 1) === 0x2F && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) {
result = [fragment, noEmptySpace(), expr.operator];
} else {
result = join(fragment, expr.operator);
}
fragment = this.generateExpression(expr.right, currentPrecedence + 1, flags);
if (expr.operator === '/' && fragment.toString().charAt(0) === '/' ||
expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!
// If '/' concats with '/' or `<` concats with `!--`, it is interpreted as comment start
result.push(noEmptySpace());
result.push(fragment);
} else {
result = join(result, fragment);
}
if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) {
return ['(', result, ')'];
}
return parenthesize(result, currentPrecedence, precedence);
},
CallExpression: function (expr, precedence, flags) {
var result, i, iz;
// <API key> becomes false.
result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)];
result.push('(');
for (i = 0, iz = expr['arguments'].length; i < iz; ++i) {
result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
if (i + 1 < iz) {
result.push(',' + space);
}
}
result.push(')');
if (!(flags & F_ALLOW_CALL)) {
return ['(', result, ')'];
}
return parenthesize(result, Precedence.Call, precedence);
},
NewExpression: function (expr, precedence, flags) {
var result, length, i, iz, itemFlags;
length = expr['arguments'].length;
// F_ALLOW_CALL becomes false.
// <API key> may become false.
itemFlags = (flags & <API key> && !parentheses && length === 0) ? E_TFT : E_TFF;
result = join(
'new',
this.generateExpression(expr.callee, Precedence.New, itemFlags)
);
if (!(flags & <API key>) || parentheses || length > 0) {
result.push('(');
for (i = 0, iz = length; i < iz; ++i) {
result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
if (i + 1 < iz) {
result.push(',' + space);
}
}
result.push(')');
}
return parenthesize(result, Precedence.New, precedence);
},
MemberExpression: function (expr, precedence, flags) {
var result, fragment;
// <API key> becomes false.
result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)];
if (expr.computed) {
result.push('[');
result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT));
result.push(']');
} else {
if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') {
fragment = <API key>(result).toString();
// When the following conditions are all true,
// 1. No floating point
// 2. Don't have exponents
// 3. The last character is a decimal digit
// 4. Not hexadecimal OR octal number literal
// we should add a floating point.
if (
fragment.indexOf('.') < 0 &&
!/[eExX]/.test(fragment) &&
esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) &&
!(fragment.length >= 2 && fragment.charCodeAt(0) === 48)
) {
result.push('.');
}
}
result.push('.');
result.push(generateIdentifier(expr.property));
}
return parenthesize(result, Precedence.Member, precedence);
},
MetaProperty: function (expr, precedence, flags) {
var result;
result = [];
if (typeof expr.meta === 'string') {
result.push(expr.meta);
} else {
result.push(expr.meta.name);
}
result.push('.');
if (typeof expr.property === 'string') {
result.push(expr.property);
} else {
result.push(expr.property.name);
}
return parenthesize(result, Precedence.Member, precedence);
},
UnaryExpression: function (expr, precedence, flags) {
var result, fragment, rightCharCode, leftSource, leftCharCode;
fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT);
if (space === '') {
result = join(expr.operator, fragment);
} else {
result = [expr.operator];
if (expr.operator.length > 2) {
// delete, void, typeof
// get `typeof []`, not `typeof[]`
result = join(result, fragment);
} else {
// Prevent inserting spaces between operator and argument if it is unnecessary
// like, `!cond`
leftSource = <API key>(result).toString();
leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
rightCharCode = fragment.toString().charCodeAt(0);
if (((leftCharCode === 0x2B || leftCharCode === 0x2D ) && leftCharCode === rightCharCode) ||
(esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode))) {
result.push(noEmptySpace());
result.push(fragment);
} else {
result.push(fragment);
}
}
}
return parenthesize(result, Precedence.Unary, precedence);
},
YieldExpression: function (expr, precedence, flags) {
var result;
if (expr.delegate) {
result = 'yield*';
} else {
result = 'yield';
}
if (expr.argument) {
result = join(
result,
this.generateExpression(expr.argument, Precedence.Yield, E_TTT)
);
}
return parenthesize(result, Precedence.Yield, precedence);
},
AwaitExpression: function (expr, precedence, flags) {
var result = join(
expr.all ? 'await*' : 'await',
this.generateExpression(expr.argument, Precedence.Await, E_TTT)
);
return parenthesize(result, Precedence.Await, precedence);
},
UpdateExpression: function (expr, precedence, flags) {
if (expr.prefix) {
return parenthesize(
[
expr.operator,
this.generateExpression(expr.argument, Precedence.Unary, E_TTT)
],
Precedence.Unary,
precedence
);
}
return parenthesize(
[
this.generateExpression(expr.argument, Precedence.Postfix, E_TTT),
expr.operator
],
Precedence.Postfix,
precedence
);
},
FunctionExpression: function (expr, precedence, flags) {
var result = [
generateAsyncPrefix(expr, true),
'function'
];
if (expr.id) {
result.push(generateStarSuffix(expr) || noEmptySpace());
result.push(generateIdentifier(expr.id));
} else {
result.push(generateStarSuffix(expr) || space);
}
result.push(this.<API key>(expr));
return result;
},
ArrayPattern: function (expr, precedence, flags) {
return this.ArrayExpression(expr, precedence, flags, true);
},
ArrayExpression: function (expr, precedence, flags, isPattern) {
var result, multiline, that = this;
if (!expr.elements.length) {
return '[]';
}
multiline = isPattern ? false : expr.elements.length > 1;
result = ['[', multiline ? newline : ''];
withIndent(function (indent) {
var i, iz;
for (i = 0, iz = expr.elements.length; i < iz; ++i) {
if (!expr.elements[i]) {
if (multiline) {
result.push(indent);
}
if (i + 1 === iz) {
result.push(',');
}
} else {
var fragment = that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT);
if (multiline) {
result.push(addIndent(fragment, indent));
} else {
result.push(fragment);
}
}
if (i + 1 < iz) {
result.push(',' + (multiline ? newline : space));
}
}
});
if (multiline && !<API key>(<API key>(result).toString())) {
result.push(newline);
}
result.push(multiline ? base : '');
result.push(']');
return result;
},
RestElement: function(expr, precedence, flags) {
return '...' + this.generatePattern(expr.argument);
},
ClassExpression: function (expr, precedence, flags) {
var result, fragment;
result = ['class'];
if (expr.id) {
result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));
}
if (expr.superClass) {
fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Assignment, E_TTT));
result = join(result, fragment);
}
result.push(space);
result.push(this.generateStatement(expr.body, S_TFFT));
return result;
},
MethodDefinition: function (expr, precedence, flags) {
var result, fragment;
if (expr['static']) {
result = ['static' + space];
} else {
result = [];
}
if (expr.kind === 'get' || expr.kind === 'set') {
fragment = [
join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)),
this.<API key>(expr.value)
];
} else {
fragment = [
<API key>(expr),
this.generatePropertyKey(expr.key, expr.computed),
this.<API key>(expr.value)
];
}
return join(result, fragment);
},
Property: function (expr, precedence, flags) {
if (expr.kind === 'get' || expr.kind === 'set') {
return [
expr.kind, noEmptySpace(),
this.generatePropertyKey(expr.key, expr.computed),
this.<API key>(expr.value)
];
}
if (expr.shorthand && expr.value.type === 'Identifier') {
return this.generatePropertyKey(expr.key, expr.computed);
}
if (expr.shorthand && expr.value.type !== 'Identifier') {
return this.generateExpression(expr.value, Precedence.Assignment, E_TTT);
}
if (expr.method) {
return [
<API key>(expr),
this.generatePropertyKey(expr.key, expr.computed),
this.<API key>(expr.value)
];
}
return [
this.generatePropertyKey(expr.key, expr.computed),
':' + space,
this.generateExpression(expr.value, Precedence.Assignment, E_TTT)
];
},
ObjectExpression: function (expr, precedence, flags) {
var multiline, result, fragment, that = this;
if (!expr.properties.length) {
return '{}';
}
multiline = expr.properties.length > 1;
withIndent(function () {
fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT);
});
if (!multiline) {
// issues 4
// Do not transform from
// dejavu.Class.declare({
// method2: function () {}
// dejavu.Class.declare({method2: function () {
if (!hasLineTerminator(<API key>(fragment).toString())) {
return [ '{', space, fragment, space, '}' ];
}
}
withIndent(function (indent) {
var i, iz;
result = [ '{', newline, addIndent(fragment, indent) ];
if (multiline) {
result.push(',' + newline);
for (i = 1, iz = expr.properties.length; i < iz; ++i) {
result.push(addIndent(
that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT),
indent
));
if (i + 1 < iz) {
result.push(',' + newline);
}
}
}
});
if (!<API key>(<API key>(result).toString())) {
result.push(newline);
}
result.push(base);
result.push('}');
return result;
},
AssignmentPattern: function(expr, precedence, flags) {
return this.generateAssignment(expr.left, expr.right, '=', precedence, flags);
},
ObjectPattern: function (expr, precedence, flags) {
var result, i, iz, multiline, property, that = this;
if (!expr.properties.length) {
return '{}';
}
multiline = false;
if (expr.properties.length === 1) {
property = expr.properties[0];
if (property.value.type !== Syntax.Identifier) {
multiline = true;
}
} else {
for (i = 0, iz = expr.properties.length; i < iz; ++i) {
property = expr.properties[i];
if (!property.shorthand) {
multiline = true;
break;
}
}
}
result = ['{', multiline ? newline : '' ];
withIndent(function (indent) {
var i, iz;
for (i = 0, iz = expr.properties.length; i < iz; ++i) {
var fragment = that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT);
if (multiline) {
result.push(addIndent(fragment, indent));
} else {
result.push(fragment);
}
if (i + 1 < iz) {
result.push(',' + (multiline ? newline : space));
}
}
});
if (multiline && !<API key>(<API key>(result).toString())) {
result.push(newline);
}
result.push(multiline ? base : '');
result.push('}');
return result;
},
ThisExpression: function (expr, precedence, flags) {
return 'this';
},
Super: function (expr, precedence, flags) {
return 'super';
},
Identifier: function (expr, precedence, flags) {
return generateIdentifier(expr);
},
<API key>: function (expr, precedence, flags) {
return generateIdentifier(expr.id || expr.local);
},
<API key>: function (expr, precedence, flags) {
var result = ['*'];
var id = expr.id || expr.local;
if (id) {
result.push(space + 'as' + noEmptySpace() + generateIdentifier(id));
}
return result;
},
ImportSpecifier: function (expr, precedence, flags) {
var imported = expr.imported;
var result = [ imported.name ];
var local = expr.local;
if (local && local.name !== imported.name) {
result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(local));
}
return result;
},
ExportSpecifier: function (expr, precedence, flags) {
var local = expr.local;
var result = [ local.name ];
var exported = expr.exported;
if (exported && exported.name !== local.name) {
result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(exported));
}
return result;
},
Literal: function (expr, precedence, flags) {
var raw;
if (expr.hasOwnProperty('raw') && parse && extra.raw) {
try {
raw = parse(expr.raw).body[0].expression;
if (raw.type === Syntax.Literal) {
if (raw.value === expr.value) {
return expr.raw;
}
}
} catch (e) {
// not use raw property
}
}
if (expr.value === null) {
return 'null';
}
if (typeof expr.value === 'string') {
return escapeString(expr.value);
}
if (typeof expr.value === 'number') {
return generateNumber(expr.value);
}
if (typeof expr.value === 'boolean') {
return expr.value ? 'true' : 'false';
}
if (expr.regex) {
return '/' + expr.regex.pattern + '/' + expr.regex.flags;
}
return generateRegExp(expr.value);
},
GeneratorExpression: function (expr, precedence, flags) {
return this.<API key>(expr, precedence, flags);
},
<API key>: function (expr, precedence, flags) {
// GeneratorExpression should be parenthesized with (...), <API key> with [...]
var result, i, iz, fragment, that = this;
result = (expr.type === Syntax.GeneratorExpression) ? ['('] : ['['];
if (extra.moz.<API key>) {
fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
result.push(fragment);
}
if (expr.blocks) {
withIndent(function () {
for (i = 0, iz = expr.blocks.length; i < iz; ++i) {
fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT);
if (i > 0 || extra.moz.<API key>) {
result = join(result, fragment);
} else {
result.push(fragment);
}
}
});
}
if (expr.filter) {
result = join(result, 'if' + space);
fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);
result = join(result, [ '(', fragment, ')' ]);
}
if (!extra.moz.<API key>) {
fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
result = join(result, fragment);
}
result.push((expr.type === Syntax.GeneratorExpression) ? ')' : ']');
return result;
},
ComprehensionBlock: function (expr, precedence, flags) {
var fragment;
if (expr.left.type === Syntax.VariableDeclaration) {
fragment = [
expr.left.kind, noEmptySpace(),
this.generateStatement(expr.left.declarations[0], S_FFFF)
];
} else {
fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT);
}
fragment = join(fragment, expr.of ? 'of' : 'in');
fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT));
return [ 'for' + space + '(', fragment, ')' ];
},
SpreadElement: function (expr, precedence, flags) {
return [
'...',
this.generateExpression(expr.argument, Precedence.Assignment, E_TTT)
];
},
<API key>: function (expr, precedence, flags) {
var itemFlags = E_TTF;
if (!(flags & F_ALLOW_CALL)) {
itemFlags = E_TFF;
}
var result = [
this.generateExpression(expr.tag, Precedence.Call, itemFlags),
this.generateExpression(expr.quasi, Precedence.Primary, E_FFT)
];
return parenthesize(result, Precedence.TaggedTemplate, precedence);
},
TemplateElement: function (expr, precedence, flags) {
// Don't use "cooked". Since tagged template can use raw template
// representation. So if we do so, it breaks the script semantics.
return expr.value.raw;
},
TemplateLiteral: function (expr, precedence, flags) {
var result, i, iz;
result = [ '`' ];
for (i = 0, iz = expr.quasis.length; i < iz; ++i) {
result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT));
if (i + 1 < iz) {
result.push('${' + space);
result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT));
result.push(space + '}');
}
}
result.push('`');
return result;
},
ModuleSpecifier: function (expr, precedence, flags) {
return this.Literal(expr, precedence, flags);
}
};
merge(CodeGenerator.prototype, CodeGenerator.Expression);
CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) {
var result, type;
type = expr.type || Syntax.Property;
if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) {
return generateVerbatim(expr, precedence);
}
result = this[type](expr, precedence, flags);
if (extra.comment) {
result = addComments(expr, result);
}
return <API key>(result, expr);
};
CodeGenerator.prototype.generateStatement = function (stmt, flags) {
var result,
fragment;
result = this[stmt.type](stmt, flags);
// Attach comments
if (extra.comment) {
result = addComments(stmt, result);
}
fragment = <API key>(result).toString();
if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') {
result = sourceMap ? <API key>(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, '');
}
return <API key>(result, stmt);
};
function generateInternal(node) {
var codegen;
codegen = new CodeGenerator();
if (isStatement(node)) {
return codegen.generateStatement(node, S_TFFF);
}
if (isExpression(node)) {
return codegen.generateExpression(node, Precedence.Sequence, E_TTT);
}
throw new Error('Unknown node type: ' + node.type);
}
function generate(node, options) {
var defaultOptions = getDefaultOptions(), result, pair;
if (options != null) {
// Obsolete options
// `options.indent`
// `options.base`
// Instead of them, we can use `option.format.indent`.
if (typeof options.indent === 'string') {
defaultOptions.format.indent.style = options.indent;
}
if (typeof options.base === 'number') {
defaultOptions.format.indent.base = options.base;
}
options = updateDeeply(defaultOptions, options);
indent = options.format.indent.style;
if (typeof options.base === 'string') {
base = options.base;
} else {
base = stringRepeat(indent, options.format.indent.base);
}
} else {
options = defaultOptions;
indent = options.format.indent.style;
base = stringRepeat(indent, options.format.indent.base);
}
json = options.format.json;
renumber = options.format.renumber;
hexadecimal = json ? false : options.format.hexadecimal;
quotes = json ? 'double' : options.format.quotes;
escapeless = options.format.escapeless;
newline = options.format.newline;
space = options.format.space;
if (options.format.compact) {
newline = space = indent = base = '';
}
parentheses = options.format.parentheses;
semicolons = options.format.semicolons;
safeConcatenation = options.format.safeConcatenation;
directive = options.directive;
parse = json ? null : options.parse;
sourceMap = options.sourceMap;
sourceCode = options.sourceCode;
preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null;
extra = options;
if (sourceMap) {
if (!exports.browser) {
// We assume environment is node.js
// And prevent from including source-map by browserify
SourceNode = require('source-map').SourceNode;
} else {
SourceNode = global.sourceMap.SourceNode;
}
// convert newline to a SourceNode in order to work with sourceMaps
newline = <API key>(newline);
}
result = generateInternal(node);
if (!sourceMap) {
pair = {code: result.toString(), map: null};
return options.sourceMapWithCode ? pair : pair.code;
}
pair = result.<API key>({
file: options.file,
sourceRoot: options.sourceMapRoot
});
if (options.sourceContent) {
pair.map.setSourceContent(options.sourceMap,
options.sourceContent);
}
if (options.sourceMapWithCode) {
return pair;
}
return pair.map.toString();
}
FORMAT_MINIFY = {
indent: {
style: '',
base: 0
},
renumber: true,
hexadecimal: true,
quotes: 'auto',
escapeless: true,
compact: true,
parentheses: false,
semicolons: false
};
FORMAT_DEFAULTS = getDefaultOptions().format;
exports.version = require('./package.json').version;
exports.generate = generate;
exports.attachComments = estraverse.attachComments;
exports.Precedence = updateDeeply({}, Precedence);
exports.browser = false;
exports.FORMAT_MINIFY = FORMAT_MINIFY;
exports.FORMAT_DEFAULTS = FORMAT_DEFAULTS;
}());
/* vim: set sw=4 ts=4 et tw=80 : */ |
package sagan.site.projects;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for {@link Release}
*/
public class ReleaseTests {
@Test
public void <API key>() {
assertThatThrownBy(() -> new Release(null)).isInstanceOf(<API key>.class)
.hasMessage("Version should not be null");
}
@Test
public void <API key>() {
assertThatThrownBy(() -> new Release(Version.of("1.2.0-SNAPSHOT"), true)).isInstanceOf(<API key>.class)
.hasMessage("Only Generally Available releases can be marked as current");
}
@Test
public void <API key>() {
Release release = new Release(Version.of("1.2.0"));
assertThat(release.isCurrent()).isFalse();
}
@Test
public void <API key>() {
Release release = new Release(Version.of("2.3.0"));
assertThat(release.getRepository()).isEqualTo(Repository.RELEASE);
assertThat(release.<API key>()).isTrue();
Release milestone = new Release(Version.of("2.3.0-M1"));
assertThat(milestone.getRepository()).isEqualTo(Repository.MILESTONE);
assertThat(milestone.isPreRelease()).isTrue();
Release snapshot = new Release(Version.of("2.3.0-SNAPSHOT"));
assertThat(snapshot.getRepository()).isEqualTo(Repository.SNAPSHOT);
assertThat(snapshot.isSnapshot()).isTrue();
}
@Test
public void <API key>() {
Release oneOneGa = new Release(Version.of("1.1.0"), true);
Release oneTwoGa = new Release(Version.of("1.2.0"));
Release oneTwoM2 = new Release(Version.of("1.2.0-M2"));
Release oneTwoSnapshot = new Release(Version.of("1.2.0-SNAPSHOT"));
Release oneThreeGa = new Release(Version.of("1.3.0"));
List<Release> releases = Stream.of(oneOneGa, oneTwoGa, oneTwoM2, oneTwoSnapshot, oneThreeGa).sorted().collect(Collectors.toList());
assertThat(releases).containsExactly(oneThreeGa, oneTwoGa, oneTwoSnapshot, oneTwoM2, oneOneGa);
}
@Test
public void <API key>() {
Release release = new Release(Version.of("1.2.0"));
release.setRefDocUrl("https://example.org/ref/{version}/index.html");
release.setApiDocUrl("https://example.org/api/{version}/index.html");
assertThat(release.expandRefDocUrl()).isEqualTo("https://example.org/ref/1.2.0/index.html");
assertThat(release.expandApiDocUrl()).isEqualTo("https://example.org/api/1.2.0/index.html");
}
@Test
public void <API key>() {
Release release = new Release(Version.of("1.2.0"), true);
release.setRefDocUrl("https://example.org/ref/{version}/index.html");
release.setApiDocUrl("https://example.org/api/{version}/index.html");
assertThat(release.expandRefDocUrl()).isEqualTo("https://example.org/ref/current/index.html");
assertThat(release.expandApiDocUrl()).isEqualTo("https://example.org/api/current/index.html");
}
} |
--TEST
Test for PHP-408: MongoBinData custom type is returned as -128.
--SKIPIF
<?php require_once dirname(__FILE__) ."/skipif.inc"; ?>
--FILE
<?php
require_once dirname(__FILE__) ."/../utils.inc";
$mongo = mongo();
$coll = $mongo->selectCollection('phpunit', 'mongobindata');
$coll->drop();
$types = array(
MongoBinData::FUNC,
MongoBinData::BYTE_ARRAY,
MongoBinData::UUID,
MongoBinData::MD5,
MongoBinData::CUSTOM
);
foreach($types as $type) {
$doc = array("bin" => new MongoBinData("asdf", $type));
$coll->insert($doc);
var_dump($doc["bin"]->type == $type);
}
$cursor = $coll->find();
foreach ($cursor as $result) {
var_dump($result["bin"]->type);
}
$coll->drop();
?>
--EXPECT
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
int(1)
int(2)
int(3)
int(5)
int(128) |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using Plainion.Validation;
using RaynMaker.Entities.Figures;
namespace RaynMaker.Entities
{
public class Company : EntityBase
{
private string myName;
private string myHomepage;
private string mySector;
private string myCountry;
public Company()
{
Guid = System.Guid.NewGuid().ToString();
Stocks = new List<Stock>();
References = new <API key><Reference>();
CurrentAssets = new List<CurrentAssets>();
TotalLiabilities = new List<TotalLiabilities>();
Dividends = new List<Dividend>();
EBITs = new List<EBIT>();
Equities = new List<Equity>();
InterestExpenses = new List<InterestExpense>();
CurrentLiabilities = new List<CurrentLiabilities>();
NetIncomes = new List<NetIncome>();
Revenues = new List<Revenue>();
SharesOutstandings = new List<SharesOutstanding>();
Tags = new <API key><Tag>();
}
[Required]
public string Guid { get; internal set; }
[Required]
public string Name
{
get { return myName; }
set { SetProperty( ref myName, value ); }
}
[Url]
public string Homepage
{
get { return myHomepage; }
set { SetProperty( ref myHomepage, value ); }
}
public string Sector
{
get { return mySector; }
set { SetProperty( ref mySector, value ); }
}
public string Country
{
get { return myCountry; }
set { SetProperty( ref myCountry, value ); }
}
[ValidateObject]
public virtual <API key><Reference> References { get; private set; }
[ValidateObject]
public virtual IList<Stock> Stocks { get; private set; }
[ValidateObject]
public virtual IList<CurrentAssets> CurrentAssets { get; private set; }
[ValidateObject]
public virtual IList<TotalLiabilities> TotalLiabilities { get; private set; }
[ValidateObject]
public virtual IList<Dividend> Dividends { get; private set; }
[ValidateObject]
public virtual IList<EBIT> EBITs { get; private set; }
[ValidateObject]
public virtual IList<Equity> Equities { get; private set; }
[ValidateObject]
public virtual IList<InterestExpense> InterestExpenses { get; private set; }
[ValidateObject]
public virtual IList<CurrentLiabilities> CurrentLiabilities { get; private set; }
[ValidateObject]
public virtual IList<NetIncome> NetIncomes { get; private set; }
[ValidateObject]
public virtual IList<Revenue> Revenues { get; private set; }
[ValidateObject]
public virtual IList<SharesOutstanding> SharesOutstandings { get; private set; }
[ValidateObject]
public virtual <API key><Tag> Tags { get; private set; }
}
} |
#ifndef <API key>
#define <API key>
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "chrome/browser/google_apis/<API key>.h"
#include "chrome/browser/google_apis/<API key>.h"
#include "chrome/browser/google_apis/<API key>.h"
#include "chrome/browser/google_apis/<API key>.h"
class GURL;
class Profile;
namespace base {
class FilePath;
}
namespace net {
class <API key>;
} // namespace net
namespace google_apis {
class AuthService;
class OperationRunner;
// This class provides documents feed service calls for WAPI (codename for
// DocumentsList API).
// Details of API call are abstracted in each operation class and this class
// works as a thin wrapper for the API.
class GDataWapiService : public <API key>,
public AuthServiceObserver,
public <API key> {
public:
// DriveFileSystem.
// |<API key>| is used to initialize URLFetcher.
// |base_url| is used to generate URLs for communicating with the WAPI
// |custom_user_agent| is used for the User-Agent header in HTTP
// requests issued through the service if the value is not empty.
GDataWapiService(net::<API key>* <API key>,
const GURL& base_url,
const std::string& custom_user_agent);
virtual ~GDataWapiService();
AuthService* <API key>();
// <API key> Overrides
virtual void Initialize(Profile* profile) OVERRIDE;
virtual void AddObserver(<API key>* observer) OVERRIDE;
virtual void RemoveObserver(<API key>* observer) OVERRIDE;
virtual bool CanStartOperation() const OVERRIDE;
virtual void CancelAll() OVERRIDE;
virtual bool CancelForFilePath(const base::FilePath& file_path) OVERRIDE;
virtual <API key> <API key>() const OVERRIDE;
virtual bool HasAccessToken() const OVERRIDE;
virtual bool HasRefreshToken() const OVERRIDE;
virtual void ClearAccessToken() OVERRIDE;
virtual void ClearRefreshToken() OVERRIDE;
virtual std::string GetRootResourceId() const OVERRIDE;
virtual void GetAllResourceList(
const <API key>& callback) OVERRIDE;
virtual void <API key>(
const std::string& <API key>,
const <API key>& callback) OVERRIDE;
virtual void Search(
const std::string& search_query,
const <API key>& callback) OVERRIDE;
virtual void SearchInDirectory(
const std::string& search_query,
const std::string& <API key>,
const <API key>& callback) OVERRIDE;
virtual void GetChangeList(
int64 start_changestamp,
const <API key>& callback) OVERRIDE;
virtual void <API key>(
const GURL& override_url,
const <API key>& callback) OVERRIDE;
virtual void GetResourceEntry(
const std::string& resource_id,
const <API key>& callback) OVERRIDE;
virtual void GetAccountMetadata(
const <API key>& callback) OVERRIDE;
virtual void GetAboutResource(
const <API key>& callback) OVERRIDE;
virtual void GetAppList(const GetAppListCallback& callback) OVERRIDE;
virtual void DeleteResource(const std::string& resource_id,
const std::string& etag,
const EntryActionCallback& callback) OVERRIDE;
virtual void DownloadFile(
const base::FilePath& virtual_path,
const base::FilePath& local_cache_path,
const GURL& download_url,
const <API key>& <API key>,
const GetContentCallback& <API key>,
const ProgressCallback& progress_callback) OVERRIDE;
virtual void CopyHostedDocument(
const std::string& resource_id,
const std::string& new_name,
const <API key>& callback) OVERRIDE;
virtual void RenameResource(
const std::string& resource_id,
const std::string& new_name,
const EntryActionCallback& callback) OVERRIDE;
virtual void <API key>(
const std::string& parent_resource_id,
const std::string& resource_id,
const EntryActionCallback& callback) OVERRIDE;
virtual void <API key>(
const std::string& parent_resource_id,
const std::string& resource_id,
const EntryActionCallback& callback) OVERRIDE;
virtual void AddNewDirectory(
const std::string& parent_resource_id,
const std::string& directory_name,
const <API key>& callback) OVERRIDE;
virtual void <API key>(
const base::FilePath& drive_file_path,
const std::string& content_type,
int64 content_length,
const std::string& parent_resource_id,
const std::string& title,
const <API key>& callback) OVERRIDE;
virtual void <API key>(
const base::FilePath& drive_file_path,
const std::string& content_type,
int64 content_length,
const std::string& resource_id,
const std::string& etag,
const <API key>& callback) OVERRIDE;
virtual void ResumeUpload(
UploadMode upload_mode,
const base::FilePath& drive_file_path,
const GURL& upload_url,
int64 start_position,
int64 end_position,
int64 content_length,
const std::string& content_type,
const scoped_refptr<net::IOBuffer>& buf,
const UploadRangeCallback& callback,
const ProgressCallback& progress_callback) OVERRIDE;
virtual void GetUploadStatus(
UploadMode upload_mode,
const base::FilePath& drive_file_path,
const GURL& upload_url,
int64 content_length,
const UploadRangeCallback& callback) OVERRIDE;
virtual void AuthorizeApp(
const std::string& resource_id,
const std::string& app_id,
const <API key>& callback) OVERRIDE;
private:
OperationRegistry* operation_registry() const;
// AuthService::Observer override.
virtual void OnO<API key>() OVERRIDE;
// <API key> Overrides
virtual void OnProgressUpdate(
const <API key>& list) OVERRIDE;
net::<API key>* <API key>; // Not owned.
scoped_ptr<OperationRunner> runner_;
ObserverList<<API key>> observers_;
// Operation objects should hold a copy of this, rather than a const
// reference, as they may outlive this object.
const <API key> url_generator_;
const std::string custom_user_agent_;
<API key>(GDataWapiService);
};
} // namespace google_apis
#endif // <API key> |
// RUN: %clang_cc1 -D__ARM_FEATURE_SVE -D__ARM_FEATURE_SVE2 -triple <API key> -target-feature +sve2 -<API key> -S -O1 -Werror -Wall -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -D__ARM_FEATURE_SVE -D__ARM_FEATURE_SVE2 -<API key> -triple <API key> -target-feature +sve2 -<API key> -S -O1 -Werror -Wall -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -D__ARM_FEATURE_SVE -triple <API key> -target-feature +sve -<API key> -fsyntax-only -verify -<API key>=error %s
// RUN: %clang_cc1 -D__ARM_FEATURE_SVE -<API key> -triple <API key> -target-feature +sve -<API key> -fsyntax-only -verify=overload -<API key>=error %s
#include <arm_sve.h>
#ifdef <API key>
// A simple used,unused... macro, long enough to represent any SVE builtin.
#define SVE_ACLE_FUNC(A1, A2_UNUSED, A3, A4_UNUSED) A1
#else
#define SVE_ACLE_FUNC(A1, A2, A3, A4) A1##A2##A3##A4
#endif
void <API key>(svbool_t pg, svuint32_t bases, svint32_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 4 x i32> %data to <vscale x 4 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv4i16.nxv4i32(<vscale x 4 x i16> [[TRUNC]], <vscale x 4 x i1> [[PG]], <vscale x 4 x i32> %bases, i64 0)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function 'svstnt1h_scatter'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u32base, , _s32)(pg, bases, data);
}
void <API key>(svbool_t pg, svuint64_t bases, svint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv2i16.nxv2i64(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], <vscale x 2 x i64> %bases, i64 0)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function 'svstnt1h_scatter'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u64base, , _s64)(pg, bases, data);
}
void <API key>(svbool_t pg, svuint32_t bases, svuint32_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 4 x i32> %data to <vscale x 4 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv4i16.nxv4i32(<vscale x 4 x i16> [[TRUNC]], <vscale x 4 x i1> [[PG]], <vscale x 4 x i32> %bases, i64 0)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function 'svstnt1h_scatter'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u32base, , _u32)(pg, bases, data);
}
void <API key>(svbool_t pg, svuint64_t bases, svuint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv2i16.nxv2i64(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], <vscale x 2 x i64> %bases, i64 0)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function 'svstnt1h_scatter'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u64base, , _u64)(pg, bases, data);
}
void <API key>(svbool_t pg, int16_t *base, svint64_t offsets, svint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.nxv2i16(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], i16* %base, <vscale x 2 x i64> %offsets)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, s64, offset, _s64)(pg, base, offsets, data);
}
void <API key>(svbool_t pg, uint16_t *base, svint64_t offsets, svuint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.nxv2i16(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], i16* %base, <vscale x 2 x i64> %offsets)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, s64, offset, _u64)(pg, base, offsets, data);
}
void <API key>(svbool_t pg, int16_t *base, svuint32_t offsets, svint32_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 4 x i32> %data to <vscale x 4 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.uxtw.nxv4i16(<vscale x 4 x i16> [[TRUNC]], <vscale x 4 x i1> [[PG]], i16* %base, <vscale x 4 x i32> %offsets)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, u32, offset, _s32)(pg, base, offsets, data);
}
void <API key>(svbool_t pg, int16_t *base, svuint64_t offsets, svint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.nxv2i16(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], i16* %base, <vscale x 2 x i64> %offsets)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, u64, offset, _s64)(pg, base, offsets, data);
}
void <API key>(svbool_t pg, uint16_t *base, svuint32_t offsets, svuint32_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 4 x i32> %data to <vscale x 4 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.uxtw.nxv4i16(<vscale x 4 x i16> [[TRUNC]], <vscale x 4 x i1> [[PG]], i16* %base, <vscale x 4 x i32> %offsets)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, u32, offset, _u32)(pg, base, offsets, data);
}
void <API key>(svbool_t pg, uint16_t *base, svuint64_t offsets, svuint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.nxv2i16(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], i16* %base, <vscale x 2 x i64> %offsets)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, u64, offset, _u64)(pg, base, offsets, data);
}
void <API key>(svbool_t pg, svuint32_t bases, int64_t offset, svint32_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 4 x i32> %data to <vscale x 4 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv4i16.nxv4i32(<vscale x 4 x i16> [[TRUNC]], <vscale x 4 x i1> [[PG]], <vscale x 4 x i32> %bases, i64 %offset)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u32base, _offset, _s32)(pg, bases, offset, data);
}
void <API key>(svbool_t pg, svuint64_t bases, int64_t offset, svint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv2i16.nxv2i64(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], <vscale x 2 x i64> %bases, i64 %offset)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u64base, _offset, _s64)(pg, bases, offset, data);
}
void <API key>(svbool_t pg, svuint32_t bases, int64_t offset, svuint32_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 4 x i32> %data to <vscale x 4 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv4i16.nxv4i32(<vscale x 4 x i16> [[TRUNC]], <vscale x 4 x i1> [[PG]], <vscale x 4 x i32> %bases, i64 %offset)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u32base, _offset, _u32)(pg, bases, offset, data);
}
void <API key>(svbool_t pg, svuint64_t bases, int64_t offset, svuint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv2i16.nxv2i64(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], <vscale x 2 x i64> %bases, i64 %offset)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u64base, _offset, _u64)(pg, bases, offset, data);
}
void <API key>(svbool_t pg, int16_t *base, svint64_t indices, svint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.index.nxv2i16(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], i16* %base, <vscale x 2 x i64> %indices)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, s64, index, _s64)(pg, base, indices, data);
}
void <API key>(svbool_t pg, uint16_t *base, svint64_t indices, svuint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.index.nxv2i16(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], i16* %base, <vscale x 2 x i64> %indices)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, s64, index, _u64)(pg, base, indices, data);
}
void <API key>(svbool_t pg, int16_t *base, svuint64_t indices, svint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.index.nxv2i16(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], i16* %base, <vscale x 2 x i64> %indices)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, u64, index, _s64)(pg, base, indices, data);
}
void <API key>(svbool_t pg, uint16_t *base, svuint64_t indices, svuint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.index.nxv2i16(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], i16* %base, <vscale x 2 x i64> %indices)
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter_, u64, index, _u64)(pg, base, indices, data);
}
void <API key>(svbool_t pg, svuint32_t bases, int64_t index, svint32_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 4 x i32> %data to <vscale x 4 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg)
// CHECK-DAG: [[SHL:%.*]] = shl i64 %index, 1
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv4i16.nxv4i32(<vscale x 4 x i16> [[TRUNC]], <vscale x 4 x i1> [[PG]], <vscale x 4 x i32> %bases, i64 [[SHL]])
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u32base, _index, _s32)(pg, bases, index, data);
}
void <API key>(svbool_t pg, svuint64_t bases, int64_t index, svint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK-DAG: [[SHL:%.*]] = shl i64 %index, 1
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv2i16.nxv2i64(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], <vscale x 2 x i64> %bases, i64 [[SHL]])
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u64base, _index, _s64)(pg, bases, index, data);
}
void <API key>(svbool_t pg, svuint32_t bases, int64_t index, svuint32_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 4 x i32> %data to <vscale x 4 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg)
// CHECK-DAG: [[SHL:%.*]] = shl i64 %index, 1
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv4i16.nxv4i32(<vscale x 4 x i16> [[TRUNC]], <vscale x 4 x i1> [[PG]], <vscale x 4 x i32> %bases, i64 [[SHL]])
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u32base, _index, _u32)(pg, bases, index, data);
}
void <API key>(svbool_t pg, svuint64_t bases, int64_t index, svuint64_t data) {
// CHECK-LABEL: <API key>
// CHECK-DAG: [[TRUNC:%.*]] = trunc <vscale x 2 x i64> %data to <vscale x 2 x i16>
// CHECK-DAG: [[PG:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg)
// CHECK-DAG: [[SHL:%.*]] = shl i64 %index, 1
// CHECK: call void @llvm.aarch64.sve.stnt1.scatter.scalar.offset.nxv2i16.nxv2i64(<vscale x 2 x i16> [[TRUNC]], <vscale x 2 x i1> [[PG]], <vscale x 2 x i64> %bases, i64 [[SHL]])
// CHECK: ret void
// overload-warning@+2 {{implicit declaration of function '<API key>'}}
// expected-warning@+1 {{implicit declaration of function '<API key>'}}
return SVE_ACLE_FUNC(svstnt1h_scatter, _u64base, _index, _u64)(pg, bases, index, data);
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: <API key>.c
Label Definition File: <API key>.label.xml
Template File: sources-sinks-54e.tmpl.c
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Set data to a small, non-zero number (two)
* Sinks: square
* GoodSink: Ensure there will not be an overflow before squaring data
* BadSink : Square data, which can lead to overflow
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
#include <math.h>
#ifndef OMITBAD
void <API key>(int data)
{
{
/* POTENTIAL FLAW: if (data*data) > INT_MAX, this will overflow */
int result = data * data;
printIntLine(result);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void <API key>(int data)
{
{
/* POTENTIAL FLAW: if (data*data) > INT_MAX, this will overflow */
int result = data * data;
printIntLine(result);
}
}
/* goodB2G uses the BadSource with the GoodSink */
void <API key>(int data)
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data > INT_MIN && abs(data) < (long)sqrt((double)INT_MAX))
{
int result = data * data;
printIntLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
#endif /* OMITGOOD */ |
<?php
namespace common\libs\fileuploader\actions;
use common\libs\fileuploader\elfinder\elFinder;
use common\libs\fileuploader\elfinder\elFinderConnector;
use yii\base\Action;
use \Yii;
/**
* Class FileConnectorAction
* @package common\actions
*/
class FileConnectorAction extends Action
{
private $basePath;
public $path = '';
public function init()
{
parent::init();
$this->basePath = Yii::getAlias('@files') . DIRECTORY_SEPARATOR;
}
public function run()
{
$this->controller-><API key> = false;
$opts = [
'roots' => [
[
'driver' => 'LocalFileSystem',
'path' => $this->basePath . $this->path . DIRECTORY_SEPARATOR,
'URL' => Yii::$app->getRequest()->getHostInfo() . '/files/' . $this->path . '/',
]
]
];
$connector = new elFinderConnector(new elFinder($opts));
$connector->run();
exit();
}
} |
<?php
namespace Hyphenator\Cache;
class ArrayCache implements CacheInterface
{
protected $cache = array();
public function fetch($cacheKey)
{
if (!array_key_exists($cacheKey, $this->cache)) {
return false;
}
return $this->cache[$cacheKey];
}
public function store($cacheKey, $data)
{
$this->cache[$cacheKey] = $data;
return true;
}
} |
#include <fstream>
#include <iostream>
#include <limits>
#include <common/math.h>
#include "magic_var_operation.h"
#include "pws_circuit_parser.h"
using namespace std;
static const bool DEBUG_MODE = true;
bool a = false;
typedef map<string, int>::iterator ConstMapIt;
typedef map<int, CVar*>::iterator CVarIt;
typedef vector<CConst*>::iterator CConstIt;
#define ASSERT_RETURN(pws, expected, parseContext) \
if (!assert(pws, expected, parseContext)) \
return;
#define IF_INVALID_RETURN(maybe) if (!maybe.isValid()) return;
static void
parseError(const string& msg)
{
if (DEBUG_MODE)
cerr << "PARSE ERROR - " << msg << endl;
}
static bool
assert(Tokenizer& pws, string expected, string parseCtx)
{
string token;
pws >> token;
if (token != expected){
stringstream ss("Missing '");
ss << expected << "' in " << parseCtx << ".";
parseError(ss.str());
return false;
}
return true;
}
template<class T> void
clearVector(vector<T>& vec)
{
typename vector<T>::iterator it;
for (it = vec.begin(); it != vec.end(); ++it)
delete *it;
vec.clear();
}
template<class T1, class T2> void
clearPairVector(vector< pair<T1, T2*> >& vec)
{
typename vector< pair<T1, T2*> >::iterator it;
for (it = vec.begin(); it != vec.end(); ++it)
delete it->second;
vec.clear();
}
template<class T1, class T2> void
clearMap(map<T1, T2*>& m)
{
typename map<T1, T2*>::iterator it;
for (it = m.begin(); it != m.end(); ++it)
delete it->second;
m.clear();
}
PWSCircuitParser::
PWSCircuitParser(const mpz_t p)
: varMap(), inOutVarsMap(), outConstantDesc(), constants(),
constMap(), token(), circuitDesc(), outputGateBegin(0)
{
mpz_init(prime);
mpz_set(prime, p);
}
void PWSCircuitParser::
clear()
{
clearPrivate();
clearIndexes();
circuitDesc.clear();
clearPairVector(magicOps);
opCount.clear();
}
const CircuitDescription& PWSCircuitParser::
<API key>() const
{
return circuitDesc;
}
void PWSCircuitParser::
parse(const string& pwsFileName)
{
clear();
ifstream pwsFile(pwsFileName.c_str());
if (!pwsFile.is_open()){
parseError("Couldn't open pws file: " + pwsFileName);
return;
}
int i =0;
Tokenizer pws(pwsFile);
while (pws.hasNext())
{
pws >> token;
if (token == "P")
parsePolyConstraint(pws);
else if (token == "<I")
parseLessThanInt(pws);
else if (token == "<F")
parseLessThanFloat(pws);
else if (token == "!=")
parseNotEqual(pws);
else if (token == "/")
parseDivide(pws);
else if (token[0] == '/' && token[1] == '/')
pws.ignoreLine();
}
pwsFile.close();
makeOutputLayer();
<API key>();
//printMemoryStats();
clearPrivate();
}
void PWSCircuitParser::
makeOutputLayer()
{
outputGateBegin = numeric_limits<int>::max();
int outputLayer = 0;
typedef vector<<API key>>::iterator COutIt;
for (COutIt it = outConstantDesc.begin();
it != outConstantDesc.end();
++it)
{
outputLayer = max(it->first.layer, outputLayer);
}
int numOutputs = 0;
for (CVarIt it = inOutVarsMap.begin(); it != inOutVarsMap.end(); ++it)
{
const CVar* cVar = it->second;
if (cVar->isOutput() && cVar->isBound())
{
outputGateBegin = min(outputGateBegin, cVar->name);
outputLayer = max(cVar->minLayer, outputLayer);
}
}
//cout << outputLayer << endl;
//cout << "NUMOutCONS: " << outConstantDesc.size() << endl;
for (COutIt it = outConstantDesc.begin();
it != outConstantDesc.end();
++it)
{
GatePosition newPos = promoteGate(it->first, outputLayer);
outConstants[it->second].push_back(newPos.name);
}
//cout << "Promoted outputs." << endl;
for (CVarIt it = inOutVarsMap.begin(); it != inOutVarsMap.end(); ++it)
{
CVar* cVar = it->second;
if (cVar->isOutput() && cVar->isBound())
{
promotePrimitive(*cVar, outputLayer);
}
}
}
void PWSCircuitParser::
<API key>()
{
// IO Vars
for (CVarIt it = inOutVarsMap.begin(); it != inOutVarsMap.end(); ++it)
{
CVar* cVar = it->second;
if (cVar->isBound())
{
if (cVar->isOutput())
outGates[cVar->name] = cVar->gateIndex.back();
else if (cVar->isInput())
inGates[cVar->name] = cVar->gateIndex.front();
}
}
// Magic Vars
for (CVarIt it = varMap.begin(); it != varMap.end(); ++it)
{
CVar* cVar = it->second;
if (cVar->isBound() && cVar->isMagic())
magicGates.push_back(cVar->gateIndex.front());
}
// Input Constants
for (CConstIt it = constants.begin(); it != constants.end(); ++it)
{
CConst* cons = *it;
if (cons->isBound())
inConstants.push_back(pair<string, int>(cons->value, cons->gateIndex.front()));
}
}
LayerDescription& PWSCircuitParser::
getLayer(int layerNum)
{
while (circuitDesc.size() <= (size_t) layerNum)
circuitDesc.push_back(LayerDescription());
return circuitDesc[layerNum];
}
GateDescription& PWSCircuitParser::
getGate(const GatePosition pos)
{
return getLayer(pos.layer)[pos.name];
}
GatePosition PWSCircuitParser::
getGate(CPrimitive& p, int layer)
{
addToCircuit(p);
if (layer == 0)
layer = p.minLayer;
return promotePrimitive(p, layer);
}
GatePosition PWSCircuitParser::
getGate(const Primitive& p, int layer)
{
return getGate(getCircuitPrimitive(p), layer);
}
CPrimitive& PWSCircuitParser::
getCircuitPrimitive(const Primitive& p)
{
if (p.isConstant())
return *getCircuitConstant(p).value();
else
return *getCircuitVariable(p).value();
}
Maybe<CVar*> PWSCircuitParser::
getCircuitVariable(const Primitive& p)
{
Maybe<CVar*> out;
if (p.isVariable())
out = getVarMap(p)[p.idx];
return out;
}
Maybe<CConst*> PWSCircuitParser::
getCircuitConstant(const Primitive& p)
{
Maybe<CConst*> out;
if (p.isConstant())
out = constants[p.idx];
return out;
}
void PWSCircuitParser::
getOpGuard(vector<int>& guard)
{
guard.clear();
guard.reserve(circuitDesc.size());
CircuitDescription::const_iterator it;
for (it = circuitDesc.begin(); it != circuitDesc.end(); ++it)
{
guard.push_back(it->size());
}
}
map<int, CVar*>& PWSCircuitParser::
getVarMap(const Primitive& p)
{
if (p.isInputOutput())
return inOutVarsMap;
else
return varMap;
}
void PWSCircuitParser::
clearPrivate()
{
clearMap(varMap);
clearMap(inOutVarsMap);
outConstantDesc.clear();
clearVector(constants);
constMap.clear();
// Unbound all gates now that we've cleared the primitives they were bound to.
typedef CircuitDescription::iterator LayerIt;
typedef LayerDescription::iterator GateIt;
for (LayerIt lit = circuitDesc.begin(); lit != circuitDesc.end(); ++lit)
{
LayerDescription& layer = *lit;
for (GateIt git = layer.begin(); git != layer.end(); ++git)
git->unbind();
}
}
void PWSCircuitParser::
clearIndexes()
{
outConstants.clear();
inConstants.clear();
inGates.clear();
outGates.clear();
magicGates.clear();
}
GatePosition PWSCircuitParser::
addGate(GateDescription::OpType op, int in1, int in2, int outLayerNum)
{
LayerDescription& outLayer = getLayer(outLayerNum);
GateDescription gOut(op, outLayerNum, outLayer.size(), in1, in2);
outLayer.push_back(gOut);
return gOut.pos;
}
void PWSCircuitParser::
addToCircuit(CPrimitive& p)
{
if (!p.isBound())
bindVariable(p.toPrimitive(), addGate(GateDescription::CONSTANT, 0, 0, 0));
}
CVar& PWSCircuitParser::
addVariable(CVar::VarType type, int name)
{
CVar testVar(type, name);
map<int, CVar*>& vMap = getVarMap(testVar.toPrimitive());
map<int, CVar*>::iterator it = vMap.find(name);
if (it == vMap.end())
{
vMap[name] = new CVar(testVar);;
}
return *vMap[name];
}
CConst& PWSCircuitParser::
addConstant(mpz_t constant)
{
char* val;
int numChars = gmp_asprintf(&val, "%Zd", constant);
string constStr(val);
CConst& con = addConstant(constStr);
void (*freefunc) (void *, size_t);
<API key> (NULL, NULL, &freefunc);
freefunc(val, (numChars + 1) * sizeof(char));
return con;
}
CConst& PWSCircuitParser::
addConstant(int constant)
{
stringstream ss;
ss << constant;
return addConstant(ss.str());
}
CConst& PWSCircuitParser::
addConstant(const string& constant)
{
ConstMapIt it = constMap.find(constant);
if (it == constMap.end())
{
constants.push_back(new CConst(constant, constants.size()));
constMap[constant] = constants.size() - 1;
}
return *constants[constMap[constant]];
}
void PWSCircuitParser::
addMagicOp(MagicVarOperation* op, vector<int>& guard)
{
magicOps.push_back(pair<vector<int>, MagicVarOperation*>(guard, op));
}
GatePosition PWSCircuitParser::
promotePrimitive(CPrimitive& p, int layer)
{
while (layer > p.maxLayer)
{
CPrimitive& zero = addConstant(0);
GatePosition g = makeGate(GateDescription::ADD, p, zero, p.maxLayer);
getGate(g).bind(p.toPrimitive());
p.gateIndex.push_back(g.name);
p.maxLayer++;
}
return GatePosition(layer, p.gateIndex[layer - p.minLayer]);
}
GatePosition PWSCircuitParser::
promoteGate(const GatePosition g, int layer)
{
Maybe<Primitive> boundPrimitive = getGate(g).boundPrimitive;
if (boundPrimitive.isValid())
{
CPrimitive& p = getCircuitPrimitive(boundPrimitive.value());
return promotePrimitive(p, layer);
}
GatePosition gatePos = g;
while (layer > gatePos.layer)
{
CPrimitive& zero = addConstant(0);
GatePosition zeroGate = getGate(zero, gatePos.layer);
gatePos = addGate(GateDescription::ADD, gatePos.name, zeroGate.name, gatePos.layer + 1);
}
return gatePos;
}
void PWSCircuitParser::
bindVariable(const Primitive& var, const GatePosition gate)
{
CPrimitive& v = getCircuitPrimitive(var);
if (v.isBound())
{
int layer = v.minLayer;
vector<int>::iterator it = v.gateIndex.begin();
for (; it != v.gateIndex.end(); ++it)
{
getGate(GatePosition(layer, *it)).unbind();
}
}
getCircuitPrimitive(var).bind(gate);
getGate(gate).bind(var);
}
void PWSCircuitParser::
bindOutputConstant(const GatePosition outGate, int val)
{
stringstream ss;
ss << val;
<API key> desc(outGate, ss.str());
outConstantDesc.push_back(desc);
}
void PWSCircuitParser::
bindOutputConstant(const Primitive val, const GatePosition outGate)
{
Maybe<CConst*> cConst = getCircuitConstant(val);
if (cConst.isValid())
{
<API key> desc(outGate, cConst.value()->value);
outConstantDesc.push_back(desc);
}
}
Primitive PWSCircuitParser::
makeMagic(const Primitive var)
{
Maybe<CVar*> cVar = getCircuitVariable(var);
if (!cVar.isValid())
return var;
cVar.value()->makeMagic();
return var;
}
GatePosition PWSCircuitParser::
makeGate(const GateDescription::OpType op, const GatePosition in1, const GatePosition in2)
{
if (in1.layer != in2.layer)
{
int layer = max(in1.layer, in2.layer);
GatePosition gate1 = promoteGate(in1, layer);
GatePosition gate2 = promoteGate(in2, layer);
return addGate(op, gate1.name, gate2.name, layer + 1);
}
else
{
return addGate(op, in1.name, in2.name, in1.layer + 1);
}
}
GatePosition PWSCircuitParser::
makeGate(const GateDescription::OpType op, CPrimitive& in1, CPrimitive& in2, int inLayerNum)
{
GatePosition g1 = getGate(in1, inLayerNum);
GatePosition g2 = getGate(in2, inLayerNum);
return addGate(op, g1.name, g2.name, inLayerNum + 1);
}
GatePosition PWSCircuitParser::
makeGate(const GateDescription::OpType op, const Primitive& p1, const Primitive& p2)
{
CPrimitive& in1 = getCircuitPrimitive(p1);
CPrimitive& in2 = getCircuitPrimitive(p2);
return makeGate(op, in1, in2, in1.minMatchingLayer(in2));
}
GatePosition PWSCircuitParser::
makeSubGate(const GatePosition in1, const GatePosition in2)
{
return makeGate(GateDescription::ADD, in1, negateGate(in2));
}
GatePosition PWSCircuitParser::
makeZeroOrOtherGate(CPrimitive& var, mpz_t other)
{
mpz_t tmp;
mpz_init_set(tmp, other);
mpz_neg(tmp, tmp);
GatePosition otherConstGate = getGate(addConstant(tmp));
GatePosition varGate = getGate(var);
GatePosition nzTerm = makeGate(GateDescription::ADD, otherConstGate, varGate);
GatePosition zOrOtherGate = makeGate(GateDescription::MUL, varGate, nzTerm);
bindOutputConstant(zOrOtherGate, 0);
mpz_clear(tmp);
return zOrOtherGate;
}
GatePosition PWSCircuitParser::
negatePrimitive(const Primitive& p)
{
if (p.isConstant())
{
string constant = constants[p.idx]->value;
string negConstant;
if (constant[0] == '-')
negConstant = constant.substr(1);
else
negConstant = "-" + constant;
return getGate(addConstant(negConstant));
}
else
{
return negateGate(getGate(addConstant(-1)));
}
}
GatePosition PWSCircuitParser::
negateGate(const GatePosition g)
{
GatePosition neg1Gate = getGate(addConstant(-1), g.layer);
return addGate(GateDescription::MUL, g.name, neg1Gate.name, g.layer + 1);
}
Maybe<Primitive> PWSCircuitParser::
parsePrimitive(Tokenizer& pws)
{
pws >> token;
if ((token[0] >= '0' && token[0] <= '9') || token[0] == '-')
return parseConst(token);
else
return parseVar(token);
}
GatePosition PWSCircuitParser::
reduce(const GateDescription::OpType op, const vector<GatePosition>& terms)
{
if (terms.empty())
return getGate(addConstant(0));
if (terms.size() == 1)
return terms[0];
vector<GatePosition> in;
vector<GatePosition> out;
typedef vector<GatePosition>::const_iterator GDescIt;
int inLayer = 0;
for (GDescIt it = terms.begin(); it != terms.end(); ++it)
inLayer = max(inLayer, it->layer);
for (GDescIt it = terms.begin(); it != terms.end(); ++it)
in.push_back(promoteGate(*it, inLayer));
while (in.size() > 1)
{
out.clear();
size_t startIdx = 0;
if ((in.size() & 1) == 1)
{
out.push_back(promoteGate(in[0], inLayer + 1));
startIdx = 1;
}
for (size_t i = startIdx; i < in.size(); i += 2)
out.push_back(addGate(op, in[i].name, in[i+1].name, inLayer + 1));
in.swap(out);
inLayer++;
}
// Careful about returning local references
return in[0];
}
Maybe<Primitive> PWSCircuitParser::
parseVar(const string& token)
{
Maybe<Primitive> p;
if (token.empty())
{
parseError("empty variable.");
p.invalidate();
return p;
}
Maybe<CVar::VarType> varType;
switch(token[0])
{
case 'I':
varType = CVar::INPUT;
break;
case 'O':
varType = CVar::OUTPUT;
break;
case 'V':
varType = CVar::TEMP;
break;
case 'M':
varType = CVar::MAGIC;
break;
default:
varType.invalidate();
break;
}
if (varType.isValid())
{
if (token.size() <= 1)
{
parseError("variable: " + token);
p.invalidate();
}
else
{
int name = atoi(token.c_str() + 1);
if (name < 0)
{
parseError("variable: " + name);
p.invalidate();
}
else
{
CVar& var = addVariable(varType.value(), name);
p = var.toPrimitive();
}
}
}
return p;
}
Maybe<Primitive> PWSCircuitParser::
parseConst(const string& token)
{
// First test that it's a valid constant.
mpq_t tmp;
mpq_init(tmp);
int idx = -1;
Maybe<Primitive> p;
if (mpq_set_str(tmp, token.c_str(), 10) != 0)
{
parseError(token + " is not a valid constant.");
p.invalidate();
}
else
{
int idx = addConstant(token).name;
p.validate();
p.value().makeConstant(idx);
}
mpq_clear(tmp);
return p;
}
Maybe<GatePosition> PWSCircuitParser::
parsePoly(Tokenizer& pws, const string end)
{
bool abort = false;
vector<GatePosition> terms;
//cout << "[ParsePoly] begin END: " << end << endl;
while (pws.hasNext())
{
pws >> token;
//cout << "[ParsePoly] TOKEN: " << token << endl;
if (token == "+")
{
if (terms.empty())
{
parseError("Unexpected '+' in polynomial definition.");
abort = true;
break;
}
//cout << "[ParsePoly] NEW TERM" << endl;
}
else if (token == end)
{
//cout << "[ParsePoly] TOKEN == END" << endl;
break;
}
else
{
pws.rewind();
Maybe<GatePosition> term = parsePolyTerm(pws);
if (term.isValid())
terms.push_back(term.value());
}
}
if (abort || terms.empty())
return Maybe<GatePosition>();
if (terms.size() == 1)
return Maybe<GatePosition>(terms[0]);
opCount.numAdds += terms.size() - 1;
return Maybe<GatePosition>(reduce(GateDescription::ADD, terms));
}
Maybe<GatePosition> PWSCircuitParser::
parsePolyTerm(Tokenizer& pws)
{
vector<GatePosition> vars;
bool abort = false;
bool negate = false;
//cout << "[ParseTerm] begin" << endl;
while (pws.hasNext())
{
pws >> token;
//cout << "[ParseTerm] token: " << token << endl;
if (token == "(")
{
Maybe<GatePosition> gate = parsePoly(pws);
if (!gate.isValid())
{
abort = true;
break;
}
vars.push_back(gate.value());
}
else if (token == "E" || token == ")")
{
pws.rewind();
break;
}
else if (token == "*")
{
if (vars.empty())
{
parseError("Unexpected '*' in polynomial definition.");
abort = true;
break;
}
}
else if (token == "+")
{
if (vars.empty())
{
parseError("Unexpected '+' in polynomial definition.");
abort = true;
}
else
{
pws.rewind();
}
break;
}
else if (token == "-")
{
negate = true;
continue;
}
else
{
pws.rewind();
Maybe<Primitive> p = parsePrimitive(pws);
if (!p.isValid())
{
abort = true;
break;
}
vars.push_back(getGate(p.value()));
}
if (negate)
{
vars.back() = negateGate(vars.back());
negate = false;
}
}
//cout << "[ParseTerm] end" << endl;
if (abort || vars.empty())
return Maybe<GatePosition>();
if (vars.size() == 1)
return Maybe<GatePosition>(vars[0]);
opCount.numMults += vars.size() - 1;
//cout << "[ParseTerm] end" << endl;
return Maybe<GatePosition>(reduce(GateDescription::MUL, vars));
}
void PWSCircuitParser::
parsePolyConstraint(Tokenizer& pws)
{
Maybe<Primitive> p = parsePrimitive(pws);
if (!p.isValid())
{
parseError("No primitive on lhs of polynomial.");
return;
}
ASSERT_RETURN(pws, "=", "polynomial definition");
Maybe<GatePosition> gate = parsePoly(pws, "E");
if (gate.isValid())
{
if (p.value().isVariable())
bindVariable(p.value(), gate.value());
else
bindOutputConstant(p.value(), gate.value());
}
}
void PWSCircuitParser::
parseLessThanInt(Tokenizer& pws)
{
vector<int> opGuard;
getOpGuard(opGuard);
ASSERT_RETURN(pws, "N_0", "less than int.");
Maybe<Primitive> n0 = parsePrimitive(pws);
IF_INVALID_RETURN(n0);
ASSERT_RETURN(pws, "N", "less than int.");
int nVars;
pws >> nVars;
nVars
ASSERT_RETURN(pws, "Mlt", "less than int.");
Maybe<Primitive> mlt = parsePrimitive(pws);
IF_INVALID_RETURN(mlt);
ASSERT_RETURN(pws, "Meq", "less than int.");
Maybe<Primitive> meq = parsePrimitive(pws);
IF_INVALID_RETURN(meq);
ASSERT_RETURN(pws, "Mgt", "less than int.");
Maybe<Primitive> mgt = parsePrimitive(pws);
IF_INVALID_RETURN(mgt);
ASSERT_RETURN(pws, "X1", "less than int.");
Maybe<Primitive> x1 = parsePrimitive(pws);
IF_INVALID_RETURN(x1);
ASSERT_RETURN(pws, "X2", "less than int.");
Maybe<Primitive> x2 = parsePrimitive(pws);
IF_INVALID_RETURN(x2);
ASSERT_RETURN(pws, "Y", "less than int.");
Maybe<Primitive> y = parsePrimitive(pws);
IF_INVALID_RETURN(y);
vector<Primitive> ns;
mpz_t num;
mpz_init_set_si(num, 1);
vector<GatePosition> nis;
for (int i = 0; i < nVars; i++)
{
CVar& ni = addVariable(CVar::MAGIC, n0.value().idx + i);
ni.makeMagic();
// This is contrary to the standard.
// Constraint: Ni * (Ni + 2^i) = 0
makeZeroOrOtherGate(ni, num);
nis.push_back(getGate(ni));
mpz_mul_2exp(num, num, 1);
}
mpz_neg(num, num);
nis.push_back(getGate(addConstant(num)));
makeMagic(mlt.value());
makeMagic(meq.value());
makeMagic(mgt.value());
// Constraint: Mlt * (1 - Mlt) = 0
mpz_set_ui(num, 1);
makeZeroOrOtherGate(getCircuitPrimitive(mlt.value()), num);
makeZeroOrOtherGate(getCircuitPrimitive(meq.value()), num);
makeZeroOrOtherGate(getCircuitPrimitive(mgt.value()), num);
// Constraint Mlt + Meq + Mgt = 1
vector<GatePosition> ms;
ms.push_back(getGate(mlt.value()));
ms.push_back(getGate(meq.value()));
ms.push_back(getGate(mgt.value()));
bindOutputConstant(reduce(GateDescription::ADD, ms), 1);
GatePosition sumNis = reduce(GateDescription::ADD, nis);
GatePosition x1Subx2 = makeSubGate(getGate(x1.value()), getGate(x2.value()));
GatePosition x2Subx1 = makeSubGate(getGate(x2.value()), getGate(x1.value()));
// Constraint: Mlt * (x2 - x1 + n0 + n1 + ... - 2^N) = 0
bindOutputConstant(
makeGate(GateDescription::MUL,
ms[0],
makeGate(GateDescription::ADD, sumNis, x2Subx1)),
0);
// Constraint: Mgt * (x1 - x2 + n0 + n1 + ... - 2^N) = 0
bindOutputConstant(
makeGate(GateDescription::MUL,
ms[2],
makeGate(GateDescription::ADD, sumNis, x1Subx2)),
0);
// Constraint: Meq * (x1 - x2) = 0
bindOutputConstant(makeGate(GateDescription::MUL, ms[1], x1Subx2), 0);
// Bind Y = Mlt
bindVariable(y.value(), ms[0]);
nis.pop_back();
addMagicOp(
new <API key>(
ms,
nis,
getGate(x1.value()),
getGate(x2.value())),
opGuard);
opCount.numCmps++;
mpz_clear(num);
}
void PWSCircuitParser::
parseLessThanFloat(Tokenizer& pws)
{
vector<int> opGuard;
getOpGuard(opGuard);
ASSERT_RETURN(pws, "N_0", "less than int.");
Maybe<Primitive> n0 = parsePrimitive(pws);
IF_INVALID_RETURN(n0);
ASSERT_RETURN(pws, "Na", "less than int.");
int nAVars;
pws >> nAVars;
ASSERT_RETURN(pws, "N", "less than int.");
Maybe<Primitive> n = parsePrimitive(pws);
IF_INVALID_RETURN(n);
ASSERT_RETURN(pws, "D_0", "less than int.");
Maybe<Primitive> d0 = parsePrimitive(pws);
IF_INVALID_RETURN(d0);
ASSERT_RETURN(pws, "Nb", "less than int.");
int nBVars;
pws >> nBVars;
ASSERT_RETURN(pws, "D", "less than int.");
Maybe<Primitive> d = parsePrimitive(pws);
IF_INVALID_RETURN(d);
ASSERT_RETURN(pws, "ND", "less than int.");
Maybe<Primitive> nd = parsePrimitive(pws);
IF_INVALID_RETURN(nd);
ASSERT_RETURN(pws, "Mlt", "less than int.");
Maybe<Primitive> mlt = parsePrimitive(pws);
IF_INVALID_RETURN(mlt);
ASSERT_RETURN(pws, "Meq", "less than int.");
Maybe<Primitive> meq = parsePrimitive(pws);
IF_INVALID_RETURN(meq);
ASSERT_RETURN(pws, "Mgt", "less than int.");
Maybe<Primitive> mgt = parsePrimitive(pws);
IF_INVALID_RETURN(mgt);
ASSERT_RETURN(pws, "X1", "less than int.");
Maybe<Primitive> x1 = parsePrimitive(pws);
IF_INVALID_RETURN(x1);
ASSERT_RETURN(pws, "X2", "less than int.");
Maybe<Primitive> x2 = parsePrimitive(pws);
IF_INVALID_RETURN(x2);
ASSERT_RETURN(pws, "Y", "less than int.");
Maybe<Primitive> y = parsePrimitive(pws);
IF_INVALID_RETURN(y);
vector<Primitive> ns;
mpz_t num, num2, inv;
mpz_init_set_si(num, 1);
mpz_init(num2);
mpz_init(inv);
vector<GatePosition> nis;
for (int i = 0; i < nAVars; i++)
{
CVar& ni = addVariable(CVar::MAGIC, n0.value().idx + i);
ni.makeMagic();
// Constraint: Ni * (Ni - 2^i) = 0
makeZeroOrOtherGate(ni, num);
nis.push_back(getGate(ni));
mpz_mul_2exp(num, num, 1);
}
mpz_neg(num, num);
nis.push_back(getGate(addConstant(num)));
// Constraint: N0 + N1 + ... - 2^Na
GatePosition nGate = reduce(GateDescription::ADD, nis);
bindVariable(n.value(), nGate);
vector<GatePosition> bitDis;
vector<GatePosition> dis;
mpz_set_ui(num, 1);
mpz_set_ui(num2, 1);
mpz_set_ui(inv, 2);
mpz_invert(inv, inv, prime);
for (int i = 0; i < nBVars + 1; i++)
{
CVar& di = addVariable(CVar::MAGIC, d0.value().idx + i);
di.makeMagic();
// Constraint: Di * (Di - 1) = 0
makeZeroOrOtherGate(di, num);
GatePosition constGate = getGate(addConstant(num2));
GatePosition diGate = getGate(di);
GatePosition diProdConstGate = makeGate(GateDescription::MUL, constGate, diGate);
bitDis.push_back(diGate);
dis.push_back(diProdConstGate);
modmult(num2, num2, inv, prime);
}
// Constraint: D0 + D1 + ... + DNa = 1
GatePosition diUniqueGate = reduce(GateDescription::ADD, bitDis);
bindOutputConstant(diUniqueGate, 1);
// Constraint: D0 + D1/2 + ... + Di/2^i = D
GatePosition dGate = reduce(GateDescription::ADD, dis);
bindVariable(d.value(), dGate);
// Constraint: ND = N * D
GatePosition ndGate = makeGate(GateDescription::MUL, nGate, dGate);
bindVariable(nd.value(), ndGate);
makeMagic(mlt.value());
makeMagic(meq.value());
makeMagic(mgt.value());
// Constraint: Mlt * (1 - Mlt) = 0
mpz_set_ui(num, 1);
makeZeroOrOtherGate(getCircuitPrimitive(mlt.value()), num);
makeZeroOrOtherGate(getCircuitPrimitive(meq.value()), num);
makeZeroOrOtherGate(getCircuitPrimitive(mgt.value()), num);
// Constraint Mlt + Meq + Mgt = 1
vector<GatePosition> ms;
ms.push_back(getGate(mlt.value()));
ms.push_back(getGate(meq.value()));
ms.push_back(getGate(mgt.value()));
bindOutputConstant(reduce(GateDescription::ADD, ms), 1);
GatePosition x1Subx2 = makeSubGate(getGate(x1.value()), getGate(x2.value()));
GatePosition x2Subx1 = makeSubGate(getGate(x2.value()), getGate(x1.value()));
// Constraint: Mlt * (x2 - x1 + ND) = 0
bindOutputConstant(
makeGate(GateDescription::MUL,
ms[0],
makeGate(GateDescription::ADD, ndGate, x2Subx1)),
0);
// Constraint: Mgt * (x1 - x2 + ND) = 0
bindOutputConstant(
makeGate(GateDescription::MUL,
ms[2],
makeGate(GateDescription::ADD, ndGate, x1Subx2)),
0);
// Constraint: Meq * (x1 - x2) = 0
bindOutputConstant(makeGate(GateDescription::MUL, ms[1], x1Subx2), 0);
// Bind Y = Mlt
bindVariable(y.value(), ms[0]);
nis.pop_back();
addMagicOp(
new <API key>(
ms,
nis,
bitDis,
getGate(x1.value()),
getGate(x2.value())),
opGuard);
opCount.numCmps++;
mpz_clear(num);
mpz_clear(num2);
mpz_clear(inv);
}
void PWSCircuitParser::
parseNotEqual(Tokenizer& pws)
{
// Record opguard first.
vector<int> opGuard;
getOpGuard(opGuard);
ASSERT_RETURN(pws, "M", "less than int.");
Maybe<Primitive> m = parsePrimitive(pws);
IF_INVALID_RETURN(m);
ASSERT_RETURN(pws, "X1", "less than int.");
Maybe<Primitive> x1 = parsePrimitive(pws);
IF_INVALID_RETURN(x1);
ASSERT_RETURN(pws, "X2", "less than int.");
Maybe<Primitive> x2 = parsePrimitive(pws);
IF_INVALID_RETURN(x2);
ASSERT_RETURN(pws, "Y", "less than int.");
Maybe<Primitive> y = parsePrimitive(pws);
IF_INVALID_RETURN(y);
makeMagic(m.value());
GatePosition mGate = getGate(m.value());
GatePosition x1Subx2 = makeSubGate(getGate(x1.value()), getGate(x2.value()));
GatePosition x2Subx1 = makeSubGate(getGate(x2.value()), getGate(x1.value()));
// Constraint: M * (X1 - X2) = Y.
GatePosition mTimesDiff = makeGate(GateDescription::MUL, mGate, x1Subx2);
// Gate: -(X1 - X2) * Y.
GatePosition negMTimesDiff = makeGate(GateDescription::MUL, mTimesDiff, x2Subx1);
// Constraint: (X1 - X2) - (X1 - X2) * Y = 0
GatePosition check = makeGate(GateDescription::ADD, negMTimesDiff, x1Subx2);
bindVariable(y.value(), mTimesDiff);
bindOutputConstant(check, 0);
addMagicOp(
new NotEqualOperation(
mGate,
getGate(x1.value()),
getGate(x2.value())),
opGuard);
opCount.numIneqs++;
}
void PWSCircuitParser::
parseDivide(Tokenizer& pws)
{
Maybe<Primitive> p = parsePrimitive(pws);
if (!p.isValid() || !p.value().isVariable())
{
parseError("No named variable on lhs of polynomial.");
return;
}
ASSERT_RETURN(pws, "=", "divide constraint.");
pws >> token;
Maybe<Primitive> dividend = parseVar(token);
IF_INVALID_RETURN(dividend);
ASSERT_RETURN(pws, "/", "divide constraint.");
pws >> token;
mpz_t divisor;
mpz_init(divisor);
if (mpz_set_str(divisor, token.c_str(), 10) == 0)
{
mpz_invert(divisor, divisor, prime);
GatePosition divisorGate = getGate(addConstant(divisor));
GatePosition dividendGate = getGate(dividend.value());
// This is an ugly hack to make this all work. We create a DIV_INT gate,
// which functions as a MUL gate, but with the additional information that
// the second operand is actually an integer to divide by.
GatePosition quotientGate = makeGate(GateDescription::DIV_INT, dividendGate, divisorGate);
bindVariable(p.value(), quotientGate);
}
else
{
parseError("No Divisor found.");
}
opCount.numIntDivs++;
mpz_clear(divisor);
}
void PWSCircuitParser::
<API key>()
{
cout << "=== CONSTANTS ===" << endl;
typedef vector<CConst*>::const_iterator CConstIt;
for (CConstIt it = constants.begin(); it != constants.end(); ++it)
{
if ((*it)->isBound())
printf("%02d || %s\n", (*it)->gateIndex.front(), (*it)->value.c_str());
}
cout << endl << "=== IO ===" << endl;
for (CVarIt it = inOutVarsMap.begin(); it != inOutVarsMap.end(); ++it)
{
CVar* cVar = it->second;
if (!cVar->isBound())
continue;
if (cVar->isInput())
{
printf("%02d || %s%d\n", cVar->gateIndex.front(),
cVar->varTypeStr().c_str(),
cVar->name);
}
else
{
printf("%02d || %s%d\n", cVar->gateIndex.back(),
cVar->varTypeStr().c_str(),
cVar->name);
}
}
cout << endl << "=== VARIABLES ===" << endl;
for (CVarIt it = varMap.begin(); it != varMap.end(); ++it)
{
CVar* cVar = it->second;
printf("%02d || %s%d\n", cVar->gateIndex.front(),
cVar->varTypeStr().c_str(),
cVar->name);
}
cout << endl << "=== OUT CONSTS ===" << endl;
for (size_t i = 0; i < outConstantDesc.size(); i++)
{
cout << outConstantDesc[i].first << ": " << outConstantDesc[i].second << endl;
}
cout << endl;
for (size_t i = 0; i < circuitDesc.size(); i++)
{
LayerDescription& layer = circuitDesc[i];
for (size_t j = 0; j < layer.size(); j++)
{
GateDescription& gate = layer[j];
printf("[%d] %s || %02d || %02d | %02d",
i,
gate.strOpType().c_str(),
gate.pos.name,
gate.in1,
gate.in2);
if (gate.isBound())
{
cout << " || " << getCircuitPrimitive(gate.boundPrimitive.value()) << endl;
}
else
{
cout << endl;
}
}
cout << endl;
}
}
template<class T> void
printMemoryStat(const string name, const T& container, size_t nLayers)
{
size_t nelems = container.size();
size_t nbytes = nelems * sizeof(typename T::const_iterator::value_type) + sizeof(T);
cout << name << nelems << " | " << (nbytes / 1024.0 / 1024.0) << " Mbytes." << endl;
}
template<> void
printMemoryStat(const string name, const vector<CConst*>& container, size_t nLayers)
{
const size_t avgNumChars = 10;
size_t nelems = container.size();
size_t nbytes = sizeof(vector<CConst*>) +
nelems * (sizeof(CConst*) + sizeof(CConst) + nLayers * sizeof(int) + avgNumChars);
cout << name << nelems << " | " << (nbytes / 1024.0 / 1024.0) << " Mbytes." << endl;
}
void PWSCircuitParser::
printMemoryStats() const
{
size_t nLayers = circuitDesc.size();
printMemoryStat("varMapsize: ", varMap, nLayers);
printMemoryStat("inoutvarsmapsize: ", inOutVarsMap, nLayers);
printMemoryStat("constsize: ", constants, nLayers);
printMemoryStat("constmapsize: ", constMap, nLayers);
printMemoryStat("outconstdescsize: ", outConstantDesc, nLayers);
printMemoryStat("circuitdescsize: ", circuitDesc, nLayers);
printMemoryStat("magicopssize: ", magicOps, nLayers);
/*
cout<< "varMapsize: " << varMap.size() << endl;;
cout<< "inoutvarsmapsize: " << inOutVarsMap.size() << endl;;
cout<< "constsize: " << constants.size() << endl;;
cout<< "constmapsize: " << constMap.size() << endl;;
cout<< "outconstdescsize: " << outConstantDesc.size() << endl;;
cout<< "circuitdescsize: " << circuitDesc.size() << endl;;
cout<< "magicopssize: " << magicOps.size() << endl;;
*/
} |
// SDLOnKeyboardInput.h
// SyncProxy
#import <Foundation/Foundation.h>
#import <AppLink/SDLRPCNotification.h>
#import <AppLink/SDLKeyboardEvent.h>
@interface SDLOnKeyboardInput : SDLRPCNotification {}
-(id) init;
-(id) initWithDictionary:(NSMutableDictionary*) dict;
@property(strong) SDLKeyboardEvent* event;
@property(strong) NSString* data;
@end |
<?php
require_once 'ZendL/Reflection/Docblock/Tag.php';
class <API key> implements Reflector
{
protected $_reflector = null;
protected $_startLine = null;
protected $_endLine = null;
protected $_docComment = null;
protected $_cleanDocComment = null;
protected $_longDescription = null;
protected $_shortDescription = null;
protected $_tags = array();
public static function export()
{
/* huh? */
}
public function __toString()
{
/* wha? */
}
public function __construct($commentOrReflector)
{
if ($commentOrReflector instanceof Reflector) {
$this->_reflector = $commentOrReflector;
if (!method_exists($commentOrReflector, 'getDocComment')) {
throw new <API key>('Reflector must contain method "getDocComment"');
}
$docComment = $commentOrReflector->getDocComment();
$lineCount = substr_count($docComment, "\n");
$this->_startLine = $this->_reflector->getStartLine() - $lineCount - 1;
$this->_endLine = $this->_reflector->getStartLine() - 1;
} elseif (is_string($commentOrReflector)) {
$docComment = $commentOrReflector;
} else {
throw new <API key>(get_class($this) . ' must have a (string) DocComment or a Reflector in the constructor.');
}
if ($docComment == '') {
throw new <API key>('DocComment cannot be empty.');
}
$this->_docComment = $docComment;
$this->_parse();
}
public function getContents()
{
return $this->_cleanDocComment;
}
public function getStartLine()
{
return $this->_startLine;
}
public function getEndLine()
{
return $this->_endLine;
}
public function getShortDescription()
{
return $this->_shortDescription;
}
public function getLongDescription()
{
return $this->_longDescription;
}
public function hasTag($name)
{
foreach ($this->_tags as $tag) {
if ($tag->getName() == $name) {
return true;
}
}
return false;
}
public function getTag($name)
{
foreach ($this->_tags as $tag) {
if ($tag->getName() == $name) {
return $tag;
}
}
return false;
}
public function getTags($filter = null)
{
if ($filter === null || !is_string($filter)) {
return $this->_tags;
}
$returnTags = array();
foreach ($this->_tags as $tag) {
if ($tag->getName() == $filter) {
$returnTags[] = $tag;
}
}
return $returnTags;
}
protected function _parse()
{
$docComment = $this->_docComment;
// First remove doc block line starters
$docComment = preg_replace('#[ \t]*(?:\/\*\*|\*\/|\*)?[ ]{0,1}(.*)?#', '$1', $docComment);
$docComment = ltrim($docComment, "\r\n"); // @todo should be changed to remove first and last empty line
$this->_cleanDocComment = $docComment;
// Next parse out the tags and descriptions
$parsedDocComment = $docComment;
$lineNumber = $<API key> = 0;
while (($newlinePos = strpos($parsedDocComment, "\n")) !== false) {
$lineNumber++;
$line = substr($parsedDocComment, 0, $newlinePos);
if ((strpos($line, '@') === 0) && (preg_match('#^(@\w+.*?)(\n)(?:@|\r?\n|$)#s', $parsedDocComment, $matches))) {
$this->_tags[] = <API key>::factory($matches[1]);
$parsedDocComment = str_replace($matches[1] . $matches[2], '', $parsedDocComment);
} else {
if ($lineNumber < 3 && !$<API key>) {
$this->_shortDescription .= $line . "\n";
} else {
$this->_longDescription .= $line . "\n";
}
if ($line == '') {
$<API key> = true;
}
$parsedDocComment = substr($parsedDocComment, $newlinePos + 1);
}
}
$this->_shortDescription = rtrim($this->_shortDescription);
$this->_longDescription = rtrim($this->_longDescription);
}
} |
module Network.PushbulletSpec (main, spec) where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction" $ do
it "should work fine" $ do
True `shouldBe` False |
module Spree
module Admin
class PaymentsController < Spree::Admin::BaseController
before_filter :load_order, :only => [:create, :new, :index, :fire]
before_filter :load_payment, :except => [:create, :new, :index]
before_filter :load_data
before_filter :<API key>
respond_to :html
def index
@payments = @order.payments
redirect_to <API key>(@order) if @payments.empty?
end
def new
@payment = @order.payments.build
end
def create
@payment = @order.payments.build(object_params)
if @payment.payment_method.is_a?(Spree::Gateway) && @payment.payment_method.<API key>? && params[:card].present? and params[:card] != 'new'
@payment.source = CreditCard.find_by_id(params[:card])
end
begin
unless @payment.save
redirect_to <API key>(@order)
return
end
if @order.completed?
@payment.process!
flash[:success] = flash_message_for(@payment, :<API key>)
redirect_to <API key>(@order)
else
#This is the first payment (admin created order)
until @order.completed?
@order.next!
end
flash[:success] = Spree.t(:new_order_completed)
redirect_to <API key>(@order)
end
rescue Spree::Core::GatewayError => e
flash[:error] = "#{e.message}"
redirect_to <API key>(@order)
end
end
def fire
return unless event = params[:e] and @payment.payment_source
# Because we have a transition method also called void, we do this to avoid conflicts.
event = "void_transaction" if event == "void"
if @payment.send("#{event}!")
flash[:success] = Spree.t(:payment_updated)
else
flash[:error] = Spree.t(:<API key>)
end
rescue Spree::Core::GatewayError => ge
flash[:error] = "#{ge.message}"
ensure
redirect_to <API key>(@order)
end
private
def object_params
if params[:payment] and params[:payment_source] and source_params = params.delete(:payment_source)[params[:payment][:payment_method_id]]
params[:payment][:source_attributes] = source_params
end
params[:payment]
end
def load_data
@amount = params[:amount] || load_order.total
@payment_methods = PaymentMethod.available(:back_end)
if @payment and @payment.payment_method
@payment_method = @payment.payment_method
else
@payment_method = @payment_methods.first
end
@previous_cards = @order.credit_cards.<API key>
end
# At this point admin should have passed through Customer Details step
# where order.next is called which leaves the order in payment step
# Orders in complete step also allows to access this controller
# Otherwise redirect user to that step
def <API key>
unless @order.billing_address.present?
flash[:notice] = Spree.t(:<API key>)
redirect_to <API key>(@order)
end
end
def load_order
@order = Order.find_by_number!(params[:order_id])
authorize! action, @order
@order
end
def load_payment
@payment = Payment.find(params[:id])
end
end
end
end |
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import unittest
# set the library path, otherwise upscaledb.so/.dll is not found
import os
import sys
import distutils.util
p = distutils.util.get_platform()
ps = ".%s-%s" % (p, sys.version[0:3])
sys.path.insert(0, os.path.join('build', 'lib' + ps))
sys.path.insert(1, os.path.join('..', 'build', 'lib' + ps))
import upscaledb
class TransactionTestCase(unittest.TestCase):
def testBeginAbort(self):
env = upscaledb.env()
env.create("test.db", upscaledb.<API key>)
db = env.create_db(1)
txn = upscaledb.txn(env)
txn.abort()
db.close()
def testBeginCommit(self):
env = upscaledb.env()
env.create("test.db", upscaledb.<API key>)
db = env.create_db(1)
txn = upscaledb.txn(env)
db.insert(txn, "key1", "value1")
db.insert(txn, "key2", "value2")
db.insert(txn, "key3", "value3")
db.erase(txn, "key1")
db.erase(txn, "key2")
try:
db.find(txn, "key1")
except upscaledb.error, (errno, strerror):
assert upscaledb.UPS_KEY_NOT_FOUND == errno
try:
db.find(txn, "key2")
except upscaledb.error, (errno, strerror):
assert upscaledb.UPS_KEY_NOT_FOUND == errno
txn.commit()
db.close()
def testCursor(self):
env = upscaledb.env()
env.create("test.db", upscaledb.<API key>)
db = env.create_db(1)
txn = upscaledb.txn(env)
c = upscaledb.cursor(db, txn)
c.insert("key1", "value1")
c.insert("key2", "value2")
c.insert("key3", "value3")
c.find("key1")
c.erase()
try:
c.find("key2")
except upscaledb.error, (errno, strerror):
assert upscaledb.UPS_KEY_NOT_FOUND == errno
c.close()
txn.commit()
db.close()
unittest.main() |
using Xunit;
namespace Rhino.Mocks.Tests.FieldsProblem
{
public class <API key>
{
[Fact]
public void <API key>()
{
TestObject testObject = MockRepository.GenerateStub<TestObject>();
Assert.Equal(0, testObject.IntProperty);
}
}
public class TestObject
{
private int _intProperty;
public virtual int IntProperty
{
get { return _intProperty; }
set { _intProperty = value; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using OpenCvSharp.Utilities;
namespace OpenCvSharp.CPlusPlus
{
<summary>
</summary>
internal class <API key> : DisposableCvObject, IStdVector<DMatch[]>
{
<summary>
Track whether Dispose has been called
</summary>
private bool disposed = false;
#region Init and Dispose
<summary>
</summary>
public <API key>()
{
ptr = NativeMethods.<API key>();
}
<summary>
</summary>
<param name="size"></param>
public <API key>(int size)
{
if (size < 0)
throw new <API key>(nameof(size));
ptr = NativeMethods.<API key>(new IntPtr(size));
}
<summary>
Clean up any resources being used.
</summary>
<param name="disposing">
If disposing equals true, the method has been called directly or indirectly by a user's code. Managed and unmanaged resources can be disposed.
If false, the method has been called by the runtime from inside the finalizer and you should not reference other objects. Only unmanaged resources can be disposed.
</param>
protected override void Dispose(bool disposing)
{
if (!disposed)
{
try
{
if (IsEnabledDispose)
{
NativeMethods.<API key>(ptr);
}
disposed = true;
}
finally
{
base.Dispose(disposing);
}
}
}
#endregion
#region Properties
<summary>
vector.size()
</summary>
public int Size1
{
get { return NativeMethods.<API key>(ptr).ToInt32(); }
}
public int Size { get { return Size1; } }
<summary>
vector[i].size()
</summary>
public long[] Size2
{
get
{
int size1 = Size1;
IntPtr[] size2Org = new IntPtr[size1];
NativeMethods.<API key>(ptr, size2Org);
long[] size2 = new long[size1];
for (int i = 0; i < size1; i++)
{
size2[i] = size2Org[i].ToInt64();
}
return size2;
}
}
<summary>
&vector[0]
</summary>
public IntPtr ElemPtr
{
get { return NativeMethods.<API key>(ptr); }
}
#endregion
#region Methods
<summary>
Converts std::vector to managed array
</summary>
<returns></returns>
public DMatch[][] ToArray()
{
int size1 = Size1;
if (size1 == 0)
return new DMatch[0][];
long[] size2 = Size2;
DMatch[][] ret = new DMatch[size1][];
for (int i = 0; i < size1; i++)
{
ret[i] = new DMatch[size2[i]];
}
using (ArrayAddress2<DMatch> retPtr = new ArrayAddress2<DMatch>(ret))
{
NativeMethods.<API key>(ptr, retPtr);
}
return ret;
}
#endregion
}
} |
package org.burroloco.donkey.trebuchet;
import org.burroloco.butcher.fixture.process.CommandRunner;
import static org.burroloco.donkey.glue.constants.DonkeyTestConstants.DIST;
import static org.junit.Assert.assertEquals;
public class DefaultDonkeyShell implements DonkeyShell {
CommandRunner runner;
public void run(String specification) {
int result = runner.run(DIST, "sh", "donkey.sh", specification);
assertEquals("donkey.sh return code", 0, result);
}
} |
#include <stdlib.h>
#include <stdio.h>
#include "wsq_runtime.h"
// An example demonstrating how to link and use the WSQ runtime system.
#include "port.h"
int main(int argc, char* argv[]) {
char addr[128];
//sprintf(addr, "fort2.csail.mit.edu | %d", PORT);
sprintf(addr, "localhost | %d", PORT);
WSQ_Init("");
WSQ_SetQueryName("proc1query");
WSQ_Pause();
printf("PAUSING WSQ engine, run compiled query manually...\n");
<API key>(1001);
WSQ_BeginSubgraph(101);
// Random tuples, 100Hz
WSQ_AddOp(1, "RandomSource", "","1", "1000 |foobar.schema");
// WSQ_AddOp(1, "ASCIIFileSource", "", "1", "-1 |foobar.schema|taq_10lines.dat");
WSQ_AddOp(2, "ConnectRemoteOut", "1", "", addr);
WSQ_EndSubgraph();
int pid = WSQ_EndTransaction();
if(pid ==0) { //pause version
// run the executable directly
printf("pid is 000000000000\n");
char cmd[128] = "WSQ_OPTLVL=3 WSQ_MAXSPEED=1 ./proc1query.exe";
system(cmd);
}
// sleep(1000);
//sleep(1);
//printf("Done Sleeping. Shutting down WSQ Engine...\n");
WSQ_Shutdown();
return 0;
} |
<!doctype html>
<!
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http:
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" content="Coffer">
<title>Coffer</title>
<!-- Place favicon.ico in the `app/` directory -->
<!-- Chrome for Android theme color -->
<meta name="theme-color" content="#2E3AA1">
<!-- Web Application Manifest -->
<link rel="manifest" href="manifest.json">
<!-- Tile color for Win8 -->
<meta name="<API key>" content="#3372DF">
<!-- Add to homescreen for Chrome on Android -->
<meta name="<API key>" content="yes">
<meta name="application-name" content="PSK">
<link rel="icon" href="/favicon.ico" type="image/x-icon">
<!-- Add to homescreen for Safari on iOS -->
<meta name="<API key>" content="yes">
<meta name="<API key>" content="black">
<meta name="<API key>" content="Coffer">
<link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png">
<!-- Tile icon for Win8 (144x144) -->
<meta name="<API key>" content="images/touch/<API key>.png">
<!-- build:css styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild-->
<!-- build:js bower_components/webcomponentsjs/webcomponents-lite.min.js -->
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
var storage = window.localStorage;
if(storage.getItem('setting.baseUrl') == null)
storage.setItem('setting.baseUrl', 'http://factory.hatiolab.com:8001/rest');
var userAgent = navigator.userAgent.toLowerCase();
// this.executeApp('cofferlink://');
// this.addTest();
// function addTest() {
// var obj = {
// 'id' : 'title_test',
// 'message' : 'message_test',
// 'time' : '2016-09-01 14:30'
// var arr = JSON.parse(storage.getItem('coffer.notification'));
// if(arr) {
// arr.push(obj);
// } else {
// arr = [];
// arr.push(obj);
// storage.setItem('coffer.notification', JSON.stringify(arr));
// var app = document.querySelector('#app');
// if(app) {
// app.$["coffer-header"].badge = JSON.parse(storage.getItem('coffer.notification')).length;
function checkLogin() {
if(storage.getItem('setting.user')) {
return true;
} else {
alert('login ~~~~~');
page('/login');
return false;
}
}
function importQrJs() {
var nowDate = new Date();
nowDate =nowDate.getTime();
var headID = document.<API key>("head")[0];
var jsNode = document.createElement('script');
jsNode.type = 'text/javascript';
jsNode.src = 'bower_components/qrjs/qr.js';
headID.appendChild(jsNode);
jsNode = document.createElement('script');
jsNode.type = 'text/javascript';
jsNode.src = 'bower_components/qr-code/src/qr-code.js';
headID.appendChild(jsNode);
}
function executeApp(url) {
// var userAgent = navigator.userAgent.toLowerCase();
if(userAgent.match('iphone') || userAgent.match('ipad') || userAgent.match('ipod')) {
// alert("userAgent : " + userAgent);
// <API key>(url,"362057947");
}else if(userAgent.match('android')) {
importQrJs();
// alert("userAgent : " + userAgent);
<API key>(url,"market://details?id=com.kakao.talk&hl=ko");
} else {
// alert("userAgent : " + userAgent);
if(userAgent.indexOf("chrome") != -1) {
// sendTokenId();
importQrJs();
} else if(userAgent.indexOf("safari") != -1) {
alert('safari');
} else if(userAgent.indexOf("firefox") != -1) {
alert('firefox');
} else if(userAgent.indexOf("msie 9") != -1 || userAgent.indexOf("msie 10") != -1 || userAgent.indexOf("msie 11") != -1) {
alert('IE');
} else {
alert('other');
}
}
}
function <API key>(bundleId,appstoreId)
{
var appstoreUrl = "http://itunes.apple.com/kr/app/id"+appstoreId+"?mt=8";
var url = bundleId + ":
var clickedAt = +new Date;
AppCheckTimer = setTimeout(function() {
if (+new Date - clickedAt < 2000)
{
location.href = appstoreUrl;
}
}, 1500);
location.href = url;
}
function exeApp(url) {
var appUriScheme = url;
document.location.href = appUriScheme;
}
function <API key>(url,marketUrl){
var openAt = +new Date;
setTimeout(
function() {
if (+new Date - openAt < 1000)
location.href = marketUrl;
}, 500);
exeApp(url);
// and_GoStore(marketUrl);
// $("#div_app").html("<iframe id='frm' src='"+url+"' width=0 height=0 frameborder=0></iframe>");
// setTimeout(function(){
// var div = $("#div_app");
// var iframe = $("#frm");
// if(iframe.length > 0){
// iframe.remove();
// },1000);
}
function <API key>(marketUrl) {
location.replace(marketUrl);
}
function and_GoStore(marketUrl) {
var clickedAt = new Date();
setTimeout(function() {
if (new Date() - clickedAt < 2000){
location.href = marketUrl;
}
}, 1500);
}
</script>
<script src="https://developers.kakao.com/sdk/js/kakao.min.js"></script>
<!-- endbuild -->
<!-- Because this project uses vulcanize this should be your only html import
in this file. All other imports should go in elements.html
<link rel="import" href="elements/elements.html">
<!-- For shared styles, shared-styles.html import in elements.html -->
<!-- <style is="custom-style" include="shared-styles"></style> -->
<style>
:host {
display: block;
position: relative;
padding-top: 80px;
padding-bottom: 64px;
}
iron-pages {
max-width: 1440px;
margin: 0 auto;margin-top:75px;
}
.announcer {
position: fixed;
height: 0;
overflow: hidden;
}
:host() .back-btn {
display: none;
}
[hidden] {
display: none !important;
}
.drawer-list {
margin: 0 20px;
}
.drawer-list a {
display: block;
padding: 0 16px;
line-height: 40px;
text-decoration: none;
color: var(--app-secondary-color);
}
.drawer-list a.iron-selected {
color: black;
font-weight: bold;
}
app-drawer {
z-index: 3;
}
footer {
position: absolute;
bottom: 0;
left: 0;
right: 0;
text-align: center;
margin: 20px;
line-height: 24px;
}
footer > a {
color: var(--app-secondary-color);
text-decoration: none;
}
footer > a:hover {
text-decoration: underline;
}
</style>
</head>
<body unresolved>
<span id="<API key>"></span>
<template is="dom-bind" id="app">
<<API key> categories="{{categories}}"></<API key>>
<things-setting id="setting" hidden></things-setting>
<!-- <script type="text/javascript">
// var app = document.querySelector('#content');
var setting = document.querySelector('#setting');
window.addEventListener('WebComponentsReady', function() {
if (setting){
setting.set('globals.baseUrl', 'http://factory.hatiolab.com:8001/rest');
}
});
</script>
<coffer-header id="coffer-header" categories="[[categories]]" route="[[route]]" params="[[params]]"></coffer-header>
<div class="content">
<iron-pages role="main" attr-for-selected="data-route" selected="{{route}}" selected-attribute="visible">
<coffer-home data-route="home" categories="[[categories]]"></coffer-home>
<coffer-unit-list data-route="unit-list"></coffer-unit-list>
<<API key> data-route="favorite-list"></<API key>>
<<API key> data-route="unit-detail-list" route="[[route]]" params="[[params]]"></<API key>>
<coffer-coffer-list data-route="coffer-list"></coffer-coffer-list>
<<API key> data-route="coffer-detail-list" route="[[route]]" params="[[params]]"></<API key>>
<coffer-login id="coffer-login" data-route="login" route="[[route]]" login-path="login" content-type="application/<API key>" success-route="/"></coffer-login>
<!-- <<API key> data-route="login"></<API key>> -->
<!-- <things-login id="coffer-login" data-route="login" route="[[route]]" title="Things" login-path="login" content-type="application/<API key>" success-route="/" <API key>="ID" <API key>="Password" submit-label="sign_up" reset-label="Reset"></things-login> -->
</iron-pages>
</div>
<paper-toast id="toast">
<span class="toast-hide-button" role="button" tabindex="0" onclick="app.$.toast.hide()">Ok</span>
</paper-toast>
</template>
<script src="scripts/app.js"></script>
</body>
</html> |
<?php
$form = $this->beginWidget(
'bootstrap.widgets.TbActiveForm', array(
'id' => 'image-form',
'<API key>' => false,
'<API key>' => true,
'type' => 'vertical',
'htmlOptions' => array('class' => 'well', 'enctype'=>'multipart/form-data'),
'inlineErrors' => true,
)
); ?>
<div class="alert alert-info">
<?php echo Yii::t('GalleryModule.gallery', 'Fields with'); ?>
<span class="required">*</span>
<?php echo Yii::t('GalleryModule.gallery', 'are required.'); ?>
</div>
<?php echo $form->errorSummary($model); ?>
<div class='row-fluid control-group <?php echo $model->hasErrors("category_id") ? "error" : ""; ?>'>
<?php echo $form->dropDownListRow($model, 'category_id', Category::model()->getFormattedList((int)Yii::app()->getModule('image')->mainCategory), array('empty' => Yii::t('GalleryModule.gallery', '--choose
</div>
<div class='row-fluid control-group <?php echo $model->hasErrors("name") ? "error" : ""; ?>'>
<?php echo $form->textFieldRow($model, 'name', array('class' => 'span7', 'maxlength' => 300, 'size' => 60)); ?>
</div>
<div class='row-fluid control-group <?php echo $model->hasErrors("file") ? "error" : ""; ?>'>
<?php if (!$model->isNewRecord) : ?>
<?php echo CHtml::image($model->getUrl(), $model->alt);?>
<?php endif; ?>
<img id="preview" src="#" class='img-polaroid' alt="current preview of image" />
<?php echo $form->fileFieldRow($model, 'file', array('class' => 'span7', 'maxlength' => 500, 'size' => 60, 'onchange' => 'readURL(this);')); ?>
</div>
<div class='row-fluid control-group <?php echo $model->hasErrors("alt") ? "error" : ""; ?>'>
<?php echo $form->textFieldRow($model, 'alt', array('class' => 'span7', 'maxlength' => 150, 'size' => 60)); ?>
</div>
<div class='row-fluid control-group <?php echo $model->hasErrors("type") ? "error" : ""; ?>'>
<?php echo $form->dropDownListRow($model, 'type', $model->getTypeList()); ?>
</div>
<div class='row-fluid control-group <?php echo $model->hasErrors("description") ? "error" : ""; ?>'>
<?php $form->textAreaRow($model, 'description', array('class' => 'span7')); ?>
</div>
<div class='row-fluid control-group <?php echo $model->hasErrors("status") ? "error" : ""; ?>'>
<?php echo $form->dropDownListRow($model, 'status', $model->statusList); ?>
</div>
<?php
$this->widget(
'bootstrap.widgets.TbButton', array(
'buttonType' => 'submit',
'type' => 'primary',
'label' => $model->isNewRecord ? Yii::t('GalleryModule.gallery', 'Create image') : Yii::t('GalleryModule.gallery', 'Save image'),
)
); ?>
<?php $this->endWidget(); ?>
<style>
#preview {
display: none;
max-width: 250px;
max-height: 250px;
}
</style>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result).show();
}
reader.readAsDataURL(input.files[0]);
}
}
</script> |
namespace FatturaElettronica.Tabelle
{
public class IdPaese : Tabella
{
public override Tabella[] List
{
get
{
return new Tabella[] {
new IdPaese { Nome = "Afghanistan", Codice = "AF" },
new IdPaese { Nome = "Isole Åland", Codice = "AX" },
new IdPaese { Nome = "Albania", Codice = "AL" },
new IdPaese { Nome = "Algeria", Codice = "DZ" },
new IdPaese { Nome = "Samoa Americane", Codice = "AS" },
new IdPaese { Nome = "Andorra", Codice = "AD" },
new IdPaese { Nome = "Angola", Codice = "AO" },
new IdPaese { Nome = "Anguilla", Codice = "AI" },
new IdPaese { Nome = "Antartide", Codice = "AQ" },
new IdPaese { Nome = "Antigua e Barbuda", Codice = "AG" },
new IdPaese { Nome = "Argentina", Codice = "AR" },
new IdPaese { Nome = "Armenia", Codice = "AM" },
new IdPaese { Nome = "Aruba", Codice = "AW" },
new IdPaese { Nome = "Australia", Codice = "AU" },
new IdPaese { Nome = "Austria", Codice = "AT" },
new IdPaese { Nome = "Azerbaigian", Codice = "AZ" },
new IdPaese { Nome = "Bahamas", Codice = "BS" },
new IdPaese { Nome = "Bahrein", Codice = "BH" },
new IdPaese { Nome = "Bangladesh", Codice = "BD" },
new IdPaese { Nome = "Barbados", Codice = "BB" },
new IdPaese { Nome = "Bielorussia", Codice = "BY" },
new IdPaese { Nome = "Belgio", Codice = "BE" },
new IdPaese { Nome = "Belize", Codice = "BZ" },
new IdPaese { Nome = "Benin", Codice = "BJ" },
new IdPaese { Nome = "Bermuda", Codice = "BM" },
new IdPaese { Nome = "Bhutan", Codice = "BT" },
new IdPaese { Nome = "Bolivia", Codice = "BO" },
new IdPaese { Nome = "Isole BES", Codice = "BQ" },
new IdPaese { Nome = "Bosnia ed Erzegovina", Codice = "BA" },
new IdPaese { Nome = "Botswana", Codice = "BW" },
new IdPaese { Nome = "Isola Bouvet", Codice = "BV" },
new IdPaese { Nome = "Brasile", Codice = "BR" },
new IdPaese { Nome = "Territori Britannici dell'Oceano Indiano", Codice = "IO" },
new IdPaese { Nome = "Brunei", Codice = "BN" },
new IdPaese { Nome = "Bulgaria", Codice = "BG" },
new IdPaese { Nome = "Burkina Faso", Codice = "BF" },
new IdPaese { Nome = "Burundi", Codice = "BI" },
new IdPaese { Nome = "Cambogia", Codice = "KH" },
new IdPaese { Nome = "Camerun", Codice = "CM" },
new IdPaese { Nome = "Canada", Codice = "CA" },
new IdPaese { Nome = "Capo Verde", Codice = "CV" },
new IdPaese { Nome = "Isole Cayman", Codice = "KY" },
new IdPaese { Nome = "Repubblica Centrafricana", Codice = "CF" },
new IdPaese { Nome = "Ciad", Codice = "TD" },
new IdPaese { Nome = "Cile", Codice = "CL" },
new IdPaese { Nome = "Cina", Codice = "CN" },
new IdPaese { Nome = "Isola del Natale", Codice = "CX" },
new IdPaese { Nome = "Isole Cocos e Keeling", Codice = "CC" },
new IdPaese { Nome = "Colombia", Codice = "CO" },
new IdPaese { Nome = "Comore", Codice = "KM" },
new IdPaese { Nome = "Congo", Codice = "CG" },
new IdPaese { Nome = "Repubblica Democratica del Congo", Codice = "CD" },
new IdPaese { Nome = "Isole Cook", Codice = "CK" },
new IdPaese { Nome = "Costa Rica", Codice = "CR" },
new IdPaese { Nome = "Costa d'Avorio", Codice = "CI" },
new IdPaese { Nome = "Croazia", Codice = "HR" },
new IdPaese { Nome = "Cuba", Codice = "CU" },
new IdPaese { Nome = "Curaçao", Codice = "CW" },
new IdPaese { Nome = "Cipro", Codice = "CY" },
new IdPaese { Nome = "Cechia", Codice = "CZ" },
new IdPaese { Nome = "Danimarka", Codice = "DK" },
new IdPaese { Nome = "Gibuti", Codice = "DJ" },
new IdPaese { Nome = "Dominica", Codice = "DM" },
new IdPaese { Nome = "Repubblica Dominicana", Codice = "DO" },
new IdPaese { Nome = "Ecuador", Codice = "EC" },
new IdPaese { Nome = "Egitto", Codice = "EG" },
new IdPaese { Nome = "El Salvador", Codice = "SV" },
new IdPaese { Nome = "Guinea Equatoriale", Codice = "GQ" },
new IdPaese { Nome = "Eritrea", Codice = "ER" },
new IdPaese { Nome = "Estonia", Codice = "EE" },
new IdPaese { Nome = "Etiopia", Codice = "ET" },
new IdPaese { Nome = "Isole Falkland", Codice = "FK" },
new IdPaese { Nome = "Isole Fær Øer", Codice = "FO" },
new IdPaese { Nome = "Figi", Codice = "FJ" },
new IdPaese { Nome = "Finlandia", Codice = "FI" },
new IdPaese { Nome = "Francia", Codice = "FR" },
new IdPaese { Nome = "Guyana Francese", Codice = "GF" },
new IdPaese { Nome = "Polinesia Francese", Codice = "PF" },
new IdPaese { Nome = "Territori Francesi del Sud", Codice = "TF" },
new IdPaese { Nome = "Gabon", Codice = "GA" },
new IdPaese { Nome = "Gambia", Codice = "GM" },
new IdPaese { Nome = "Georgia", Codice = "GE" },
new IdPaese { Nome = "Germania", Codice = "DE" },
new IdPaese { Nome = "Ghana", Codice = "GH" },
new IdPaese { Nome = "Gibilterra", Codice = "GI" },
new IdPaese { Nome = "Grecia", Codice = "GR" },
new IdPaese { Nome = "Groenlandia", Codice = "GL" },
new IdPaese { Nome = "Grenada", Codice = "GD" },
new IdPaese { Nome = "Guadalupa", Codice = "GP" },
new IdPaese { Nome = "Guam", Codice = "GU" },
new IdPaese { Nome = "Guatemala", Codice = "GT" },
new IdPaese { Nome = "Guernsey", Codice = "GG" },
new IdPaese { Nome = "Guinea", Codice = "GN" },
new IdPaese { Nome = "Guinea-Bissau", Codice = "GW" },
new IdPaese { Nome = "Guyana", Codice = "GY" },
new IdPaese { Nome = "Haiti", Codice = "HT" },
new IdPaese { Nome = "Isole Heard e McDonald", Codice = "HM" },
new IdPaese { Nome = "Città del Vaticano", Codice = "VA" },
new IdPaese { Nome = "Honduras", Codice = "HN" },
new IdPaese { Nome = "Hong Kong", Codice = "HK" },
new IdPaese { Nome = "Ungheria", Codice = "HU" },
new IdPaese { Nome = "Islanda", Codice = "IS" },
new IdPaese { Nome = "India", Codice = "IN" },
new IdPaese { Nome = "Indonesia", Codice = "ID" },
new IdPaese { Nome = "Iran", Codice = "IR" },
new IdPaese { Nome = "Iraq", Codice = "IQ" },
new IdPaese { Nome = "Irlanda", Codice = "IE" },
new IdPaese { Nome = "Isola di Man", Codice = "IM" },
new IdPaese { Nome = "Israele", Codice = "IL" },
new IdPaese { Nome = "Italia", Codice = "IT" },
new IdPaese { Nome = "Giamaica", Codice = "JM" },
new IdPaese { Nome = "Giappone", Codice = "JP" },
new IdPaese { Nome = "Jersey", Codice = "JE" },
new IdPaese { Nome = "Giordania", Codice = "JO" },
new IdPaese { Nome = "Kazakistan", Codice = "KZ" },
new IdPaese { Nome = "Kenya", Codice = "KE" },
new IdPaese { Nome = "Kiribati", Codice = "KI" },
new IdPaese { Nome = "Corea del Nord", Codice = "KP" },
new IdPaese { Nome = "Corea del Sud", Codice = "KR" },
new IdPaese { Nome = "Kuwait", Codice = "KW" },
new IdPaese { Nome = "Kirghizistan", Codice = "KG" },
new IdPaese { Nome = "Laos", Codice = "LA" },
new IdPaese { Nome = "Lettonia", Codice = "LV" },
new IdPaese { Nome = "Libano", Codice = "LB" },
new IdPaese { Nome = "Lesotho", Codice = "LS" },
new IdPaese { Nome = "Liberia", Codice = "LR" },
new IdPaese { Nome = "Libia", Codice = "LY" },
new IdPaese { Nome = "Liechtenstein", Codice = "LI" },
new IdPaese { Nome = "Lituania", Codice = "LT" },
new IdPaese { Nome = "Lussemburgo", Codice = "LU" },
new IdPaese { Nome = "Macao", Codice = "MO" },
new IdPaese { Nome = "Macedonia", Codice = "MK" },
new IdPaese { Nome = "Madagascar", Codice = "MG" },
new IdPaese { Nome = "Malawi", Codice = "MW" },
new IdPaese { Nome = "Malesia", Codice = "MY" },
new IdPaese { Nome = "Maldive", Codice = "MV" },
new IdPaese { Nome = "Mali", Codice = "ML" },
new IdPaese { Nome = "Malta", Codice = "MT" },
new IdPaese { Nome = "Isole Marshall", Codice = "MH" },
new IdPaese { Nome = "Martinica", Codice = "MQ" },
new IdPaese { Nome = "Mauritania", Codice = "MR" },
new IdPaese { Nome = "Mauritius", Codice = "MU" },
new IdPaese { Nome = "Mayotte", Codice = "YT" },
new IdPaese { Nome = "Messico", Codice = "MX" },
new IdPaese { Nome = "Micronesia", Codice = "FM" },
new IdPaese { Nome = "Moldavia", Codice = "MD" },
new IdPaese { Nome = "Monaco", Codice = "MC" },
new IdPaese { Nome = "Mongolia", Codice = "MN" },
new IdPaese { Nome = "Montenegro", Codice = "ME" },
new IdPaese { Nome = "Montserrat", Codice = "MS" },
new IdPaese { Nome = "Marocco", Codice = "MA" },
new IdPaese { Nome = "Mozambico", Codice = "MZ" },
new IdPaese { Nome = "Birmania", Codice = "MM" },
new IdPaese { Nome = "Namibia", Codice = "NA" },
new IdPaese { Nome = "Nauru", Codice = "NR" },
new IdPaese { Nome = "Nepal", Codice = "NP" },
new IdPaese { Nome = "Paesi Bassi", Codice = "NL" },
new IdPaese { Nome = "Nuova Caledonia", Codice = "NC" },
new IdPaese { Nome = "Nuova Zelanda", Codice = "NZ" },
new IdPaese { Nome = "Nicaragua", Codice = "NI" },
new IdPaese { Nome = "Niger", Codice = "NE" },
new IdPaese { Nome = "Nigeria", Codice = "NG" },
new IdPaese { Nome = "Niue", Codice = "NU" },
new IdPaese { Nome = "Isole Norfolk", Codice = "NF" },
new IdPaese { Nome = "Isole Marianne Settentrionali", Codice = "MP" },
new IdPaese { Nome = "Norvegia", Codice = "NO" },
new IdPaese { Nome = "Oman", Codice = "OM" },
new IdPaese { Nome = "Pakistan", Codice = "PK" },
new IdPaese { Nome = "Palau", Codice = "PW" },
new IdPaese { Nome = "Stato di Palestina", Codice = "PS" },
new IdPaese { Nome = "Panama", Codice = "PA" },
new IdPaese { Nome = "Papua Nuova Guinea", Codice = "PG" },
new IdPaese { Nome = "Paraguay", Codice = "PY" },
new IdPaese { Nome = "Perù", Codice = "PE" },
new IdPaese { Nome = "Filippine", Codice = "PH" },
new IdPaese { Nome = "Isole Pitcairn", Codice = "PN" },
new IdPaese { Nome = "Polonia", Codice = "PL" },
new IdPaese { Nome = "Portogallo", Codice = "PT" },
new IdPaese { Nome = "Porto Rico", Codice = "PR" },
new IdPaese { Nome = "Qatar", Codice = "QA" },
new IdPaese { Nome = "Réunion", Codice = "RE" },
new IdPaese { Nome = "Romania", Codice = "RO" },
new IdPaese { Nome = "Russia", Codice = "RU" },
new IdPaese { Nome = "Ruanda", Codice = "RW" },
new IdPaese { Nome = "Saint-Barthélemy", Codice = "BL" },
new IdPaese { Nome = "Sant'Elena, Isola di Acensione e Tristan da Cunha", Codice = "SH" },
new IdPaese { Nome = "Saint Kitts e Nevis", Codice = "KN" },
new IdPaese { Nome = "Santa Lucia", Codice = "LC" },
new IdPaese { Nome = "Saint-Martin", Codice = "MF" },
new IdPaese { Nome = "Saint-Pierre e Miquelon", Codice = "PM" },
new IdPaese { Nome = "Saint Vincent e Grenadine", Codice = "VC" },
new IdPaese { Nome = "Samoa", Codice = "WS" },
new IdPaese { Nome = "San Marino", Codice = "SM" },
new IdPaese { Nome = "Sao Tome e Principe", Codice = "ST" },
new IdPaese { Nome = "Arabia Saudita", Codice = "SA" },
new IdPaese { Nome = "Senegal", Codice = "SN" },
new IdPaese { Nome = "Serbia", Codice = "RS" },
new IdPaese { Nome = "Seychelles", Codice = "SC" },
new IdPaese { Nome = "Sierra Leone", Codice = "SL" },
new IdPaese { Nome = "Singapore", Codice = "SG" },
new IdPaese { Nome = "Sint Maarten", Codice = "SX" },
new IdPaese { Nome = "Slovacchia", Codice = "SK" },
new IdPaese { Nome = "Slovenia", Codice = "SI" },
new IdPaese { Nome = "Isole Solomon", Codice = "SB" },
new IdPaese { Nome = "Somalia", Codice = "SO" },
new IdPaese { Nome = "Sud Africa", Codice = "ZA" },
new IdPaese { Nome = "Georgia del Sud e Isole Sandwich meridionali", Codice = "GS" },
new IdPaese { Nome = "Sudan del Sud", Codice = "SS" },
new IdPaese { Nome = "Spagna", Codice = "ES" },
new IdPaese { Nome = "Sri Lanka", Codice = "LK" },
new IdPaese { Nome = "Sudan", Codice = "SD" },
new IdPaese { Nome = "Suriname", Codice = "SR" },
new IdPaese { Nome = "Svalbard e Jan Mayen", Codice = "SJ" },
new IdPaese { Nome = "Swaziland", Codice = "SZ" },
new IdPaese { Nome = "Svezia", Codice = "SE" },
new IdPaese { Nome = "Svizzera", Codice = "CH" },
new IdPaese { Nome = "Siria", Codice = "SY" },
new IdPaese { Nome = "Taiwan (Repubblica di Cina)", Codice = "TW" },
new IdPaese { Nome = "Tagikistan", Codice = "TJ" },
new IdPaese { Nome = "Tanzania", Codice = "TZ" },
new IdPaese { Nome = "Tailandia", Codice = "TH" },
new IdPaese { Nome = "Timor Est", Codice = "TL" },
new IdPaese { Nome = "Togo", Codice = "TG" },
new IdPaese { Nome = "Tokelau", Codice = "TK" },
new IdPaese { Nome = "Tonga", Codice = "TO" },
new IdPaese { Nome = "Trinidad e Tobago", Codice = "TT" },
new IdPaese { Nome = "Tunisia", Codice = "TN" },
new IdPaese { Nome = "Turchia", Codice = "TR" },
new IdPaese { Nome = "Turkmenistan", Codice = "TM" },
new IdPaese { Nome = "Isole Turks e Caicos", Codice = "TC" },
new IdPaese { Nome = "Tuvalu", Codice = "TV" },
new IdPaese { Nome = "Uganda", Codice = "UG" },
new IdPaese { Nome = "Ucraina", Codice = "UA" },
new IdPaese { Nome = "Emirati Arabi Uniti", Codice = "AE" },
new IdPaese { Nome = "Regno Unito", Codice = "GB" },
new IdPaese { Nome = "Stati Uniti", Codice = "US" },
new IdPaese { Nome = "Isole Minor Esterne degli Stati Uniti", Codice = "UM" },
new IdPaese { Nome = "Uruguay", Codice = "UY" },
new IdPaese { Nome = "Uzbekistan", Codice = "UZ" },
new IdPaese { Nome = "Vanuatu", Codice = "VU" },
new IdPaese { Nome = "Venezuela", Codice = "VE" },
new IdPaese { Nome = "Vietnam", Codice = "VN" },
new IdPaese { Nome = "Isole Vergini britanniche", Codice = "VG" },
new IdPaese { Nome = "Isole Vergini americane", Codice = "VI" },
new IdPaese { Nome = "Wallis e Futuna", Codice = "WF" },
new IdPaese { Nome = "Sahara Occidentale", Codice = "EH" },
new IdPaese { Nome = "Yemen", Codice = "YE" },
new IdPaese { Nome = "Zambia", Codice = "ZM" },
new IdPaese { Nome = "Zimbabwe", Codice = "ZW" },
new IdPaese { Nome = "Kosovo", Codice = "XK" },
};
}
}
}
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: <API key>.cpp
Label Definition File: <API key>.label.xml
Template File: sources-sinks-43.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete []
* Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file
*
* */
#include "std_testcase.h"
namespace <API key>
{
#ifndef OMITBAD
void badSource(long * &data)
{
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)malloc(100*sizeof(long));
if (data == NULL) {exit(-1);}
}
void bad()
{
long * data;
/* Initialize data*/
data = NULL;
badSource(data);
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSource(long * &data)
{
/* FIX: Allocate memory using new [] */
data = new long[100];
}
static void goodG2B()
{
long * data;
/* Initialize data*/
data = NULL;
goodG2BSource(data);
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2GSource(long * &data)
{
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)malloc(100*sizeof(long));
if (data == NULL) {exit(-1);}
}
static void goodB2G()
{
long * data;
/* Initialize data*/
data = NULL;
goodB2GSource(data);
/* FIX: Free memory using free() */
free(data);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace <API key>; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .datagroup import MODNAME
from .datagroup1D import DataGroup1D
class DataGroupXanes(DataGroup1D):
"""DataGroup for XANES scans"""
def __init__(self, kwsd=None, _larch=None):
super(DataGroupXanes, self).__init__(kwsd=kwsd, _larch=_larch)
LARCH
def datagroup_xan(kwsd=None, _larch=None):
"""utility to perform wrapped operations on a list of XANES data
groups"""
return DataGroupXanes(kwsd=kwsd, _larch=_larch)
def registerLarchPlugin():
return (MODNAME, {'datagroup_xan' : datagroup_xan})
if __name__ == '__main__':
pass |
from django.conf import settings
# Safe User import for Django < 1.5
try:
from django.contrib.auth import get_user_model
except ImportError:
from django.contrib.auth.models import User
else:
User = get_user_model()
# Safe version of settings.AUTH_USER_MODEL for Django < 1.5
auth_user_model = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') |
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Date parser test — 100<=x<=999 and 0<=y<=69 and 100<=z<=999 — 400/29/812</title>
<script src="../date_test.js"></script>
<p>Failed (Script did not run)</p>
<script>
test_date("400/29/812", 404, 6, 19, 22, 0, 0)
</script>
</html> |
<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Class Unicode.Property
</title>
<meta name="viewport" content="width=device-width">
<meta name="title" content="Class Unicode.Property
">
<meta name="generator" content="docfx 2.18.2.0">
<link rel="shortcut icon" href="../../favicon.ico">
<link rel="stylesheet" href="../../styles/docfx.vendor.css">
<link rel="stylesheet" href="../../styles/docfx.css">
<link rel="stylesheet" href="../../styles/main.css">
<meta property="docfx:navrel" content="../../toc.html">
<meta property="docfx:tocrel" content="../toc.html">
</head>
<body data-spy="scroll" data-target="#affix">
<div id="wrapper">
<header>
<nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../index.html">
<img id="logo" class="svg" src="../../logo.svg" alt="">
</a>
</div>
<div class="collapse navbar-collapse" id="navbar">
<form class="navbar-form navbar-right" role="search" id="search">
<div class="form-group">
<input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
</div>
</form>
</div>
</div>
</nav>
<div class="subnav navbar navbar-default">
<div class="container hide-when-search" id="breadcrumb">
<ul class="breadcrumb">
<li></li>
</ul>
</div>
</div>
</header>
<div role="main" class="container body-content hide-when-search">
<div class="sidenav hide-when-search">
<a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
<div class="sidetoggle collapse" id="sidetoggle">
<div id="sidetoc"></div>
</div>
</div>
<div class="article row grid-right">
<div class="col-md-10">
<article class="content wrap" id="_content" data-uid="NStack.Unicode.Property">
<h1 id="<API key>" data-uid="NStack.Unicode.Property">Class Unicode.Property
</h1>
<div class="markdown level0 summary"><p>Static class containing the proeprty-based tables.</p>
</div>
<div class="markdown level0 conceptual"></div>
<div class="inheritance">
<h5>Inheritance</h5>
<div class="level0"><span class="xref">System.Object</span></div>
<div class="level1"><span class="xref">Unicode.Property</span></div>
</div>
<h6><strong>Namespace</strong>: <a class="xref" href="../NStack.html">NStack</a></h6>
<h6><strong>Assembly</strong>: NStack.dll</h6>
<h5 id="<API key>">Syntax</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static class Unicode.Property</code></pre>
</div>
<h5 id="<API key>"><strong>Remarks</strong></h5>
<div class="markdown level0 remarks"><p>There are static properties that can be used to fetch RangeTables that identify characters that have a specific property, or you can use the <span class="xref">NStack.Unicode.Property.Get</span> method in this class to retrieve the range table by the property name</p></div>
<h3 id="properties">Properties
</h3>
<a id="<API key>" data-uid="NStack.Unicode.Property.ASCII_Hex_Digit*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.ASCII_Hex_Digit">ASCII_Hex_Digit</h4>
<div class="markdown level1 summary"><p>ASCII_Hex_Digit is the set of Unicode characters with property ASCII_Hex_Digit.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable ASCII_Hex_Digit { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Bidi_Control*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Bidi_Control">Bidi_Control</h4>
<div class="markdown level1 summary"><p>Bidi_Control is the set of Unicode characters with property Bidi_Control.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Bidi_Control { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Dash*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Dash">Dash</h4>
<div class="markdown level1 summary"><p>Dash is the set of Unicode characters with property Dash.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Dash { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Deprecated*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Deprecated">Deprecated</h4>
<div class="markdown level1 summary"><p>Deprecated is the set of Unicode characters with property Deprecated.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Deprecated { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Diacritic*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Diacritic">Diacritic</h4>
<div class="markdown level1 summary"><p>Diacritic is the set of Unicode characters with property Diacritic.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Diacritic { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Extender*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Extender">Extender</h4>
<div class="markdown level1 summary"><p>Extender is the set of Unicode characters with property Extender.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Extender { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Hex_Digit*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Hex_Digit">Hex_Digit</h4>
<div class="markdown level1 summary"><p>Hex_Digit is the set of Unicode characters with property Hex_Digit.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Hex_Digit { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Hyphen*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Hyphen">Hyphen</h4>
<div class="markdown level1 summary"><p>Hyphen is the set of Unicode characters with property Hyphen.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Hyphen { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Ideographic*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Ideographic">Ideographic</h4>
<div class="markdown level1 summary"><p>Ideographic is the set of Unicode characters with property Ideographic.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Ideographic { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.IDS_Binary_Operator*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.IDS_Binary_Operator">IDS_Binary_Operator</h4>
<div class="markdown level1 summary"><p>IDS_Binary_Operator is the set of Unicode characters with property IDS_Binary_Operator.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable IDS_Binary_Operator { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.<API key>*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.<API key>"><API key></h4>
<div class="markdown level1 summary"><p><API key> is the set of Unicode characters with property <API key>.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable <API key> { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Join_Control*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Join_Control">Join_Control</h4>
<div class="markdown level1 summary"><p>Join_Control is the set of Unicode characters with property Join_Control.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Join_Control { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.<API key>*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.<API key>"><API key></h4>
<div class="markdown level1 summary"><p><API key> is the set of Unicode characters with property <API key>.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable <API key> { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.<API key>*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.<API key>"><API key></h4>
<div class="markdown level1 summary"><p><API key> is the set of Unicode characters with property <API key>.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable <API key> { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Other_Alphabetic*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Other_Alphabetic">Other_Alphabetic</h4>
<div class="markdown level1 summary"><p>Other_Alphabetic is the set of Unicode characters with property Other_Alphabetic.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Other_Alphabetic { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.<API key>*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.<API key>"><API key></h4>
<div class="markdown level1 summary"><p><API key> is the set of Unicode characters with property <API key>.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable <API key> { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.<API key>*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.<API key>"><API key></h4>
<div class="markdown level1 summary"><p><API key> is the set of Unicode characters with property <API key>.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable <API key> { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Other_ID_Continue*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Other_ID_Continue">Other_ID_Continue</h4>
<div class="markdown level1 summary"><p>Other_ID_Continue is the set of Unicode characters with property Other_ID_Continue.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Other_ID_Continue { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Other_ID_Start*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Other_ID_Start">Other_ID_Start</h4>
<div class="markdown level1 summary"><p>Other_ID_Start is the set of Unicode characters with property Other_ID_Start.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Other_ID_Start { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Other_Lowercase*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Other_Lowercase">Other_Lowercase</h4>
<div class="markdown level1 summary"><p>Other_Lowercase is the set of Unicode characters with property Other_Lowercase.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Other_Lowercase { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Other_Math*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Other_Math">Other_Math</h4>
<div class="markdown level1 summary"><p>Other_Math is the set of Unicode characters with property Other_Math.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Other_Math { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Other_Uppercase*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Other_Uppercase">Other_Uppercase</h4>
<div class="markdown level1 summary"><p>Other_Uppercase is the set of Unicode characters with property Other_Uppercase.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Other_Uppercase { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Pattern_Syntax*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Pattern_Syntax">Pattern_Syntax</h4>
<div class="markdown level1 summary"><p>Pattern_Syntax is the set of Unicode characters with property Pattern_Syntax.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Pattern_Syntax { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Pattern_White_Space*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Pattern_White_Space">Pattern_White_Space</h4>
<div class="markdown level1 summary"><p>Pattern_White_Space is the set of Unicode characters with property Pattern_White_Space.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Pattern_White_Space { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.<API key>*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.<API key>"><API key></h4>
<div class="markdown level1 summary"><p><API key> is the set of Unicode characters with property <API key>.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable <API key> { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Quotation_Mark*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Quotation_Mark">Quotation_Mark</h4>
<div class="markdown level1 summary"><p>Quotation_Mark is the set of Unicode characters with property Quotation_Mark.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Quotation_Mark { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Radical*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Radical">Radical</h4>
<div class="markdown level1 summary"><p>Radical is the set of Unicode characters with property Radical.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Radical { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Sentence_Terminal*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Sentence_Terminal">Sentence_Terminal</h4>
<div class="markdown level1 summary"><p>Sentence_Terminal is the set of Unicode characters with property Sentence_Terminal.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Sentence_Terminal { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Soft_Dotted*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Soft_Dotted">Soft_Dotted</h4>
<div class="markdown level1 summary"><p>Soft_Dotted is the set of Unicode characters with property Soft_Dotted.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Soft_Dotted { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.STerm*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.STerm">STerm</h4>
<div class="markdown level1 summary"><p>STerm is an alias for Sentence_Terminal.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable STerm { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.<API key>*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.<API key>"><API key></h4>
<div class="markdown level1 summary"><p><API key> is the set of Unicode characters with property <API key>.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable <API key> { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Unified_Ideograph*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Unified_Ideograph">Unified_Ideograph</h4>
<div class="markdown level1 summary"><p>Unified_Ideograph is the set of Unicode characters with property Unified_Ideograph.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Unified_Ideograph { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.Variation_Selector*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Variation_Selector">Variation_Selector</h4>
<div class="markdown level1 summary"><p>Variation_Selector is the set of Unicode characters with property Variation_Selector.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Variation_Selector { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<a id="<API key>" data-uid="NStack.Unicode.Property.White_Space*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.White_Space">White_Space</h4>
<div class="markdown level1 summary"><p>White_Space is the set of Unicode characters with property White_Space.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable White_Space { get; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
<h3 id="methods">Methods
</h3>
<a id="<API key>" data-uid="NStack.Unicode.Property.Get*"></a>
<h4 id="<API key>" data-uid="NStack.Unicode.Property.Get(System.String)">Get(String)</h4>
<div class="markdown level1 summary"><p>Retrieves the specified RangeTable having that property.</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static NStack.Unicode.RangeTable Get (string propertyName);</code></pre>
</div>
<h5 class="parameters">Parameters</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">System.String</span></td>
<td><span class="parametername">propertyName</span></td>
<td><p>The property name.</p>
</td>
</tr>
</tbody>
</table>
<h5 class="returns">Returns</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td><p>To be added.</p>
</td>
</tr>
</tbody>
</table>
</article>
</div>
<div class="hidden-sm col-md-2" role="complementary">
<div class="sideaffix">
<div class="contribution">
<ul class="nav">
</ul>
</div>
<nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
<!-- <p><a class="back-to-top" href="#top">Back to top</a><p> -->
</nav>
</div>
</div>
</div>
</div>
<footer>
<div class="grad-bottom"></div>
<div class="footer">
<div class="container">
<span class="pull-right">
<a href="#top">Back to top</a>
</span>
<span>Copyright © 2015-2017 Microsoft<br>Generated by <strong>DocFX</strong></span>
</div>
</div>
</footer>
</div>
<script type="text/javascript" src="../../styles/docfx.vendor.js"></script>
<script type="text/javascript" src="../../styles/docfx.js"></script>
<script type="text/javascript" src="../../styles/main.js"></script>
</body>
</html> |
package com.aspirephile.laundro.review;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.aspirephile.laundro.R;
import com.aspirephile.laundro.db.LaundroDb;
import com.aspirephile.laundro.db.async.<API key>;
import com.aspirephile.laundro.db.tables.Review;
import com.aspirephile.shared.debug.Logger;
import com.aspirephile.shared.debug.NullPointerAsserter;
import java.util.List;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link <API key>}
* interface.
*/
public class ReviewListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, SearchView.OnQueryTextListener {
private static final String ARG_COLUMN_COUNT = "column-count";
private static final String ARG_SERVICE_ID = "serviceId";
private static final String ARG_USER_ID = "userId";
private Logger l = new Logger(ReviewListFragment.class);
private NullPointerAsserter asserter = new NullPointerAsserter(l);
private int mColumnCount = 1;
private <API key> mListener;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
private long serviceId, userId;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ReviewListFragment() {
serviceId = -1;
userId = -1;
}
@SuppressWarnings("unused")
public static ReviewListFragment newInstance(int columnCount, long serviceId, long userId) {
ReviewListFragment fragment = new ReviewListFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
args.putLong(ARG_SERVICE_ID, serviceId);
args.putLong(ARG_USER_ID, userId);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
l.onCreate();
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
serviceId = getArguments().getLong(ARG_SERVICE_ID);
userId = getArguments().getLong(ARG_USER_ID);
}
onRefresh();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.<API key>, container, false);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.srl_comment_list);
swipeRefreshLayout.<API key>(this);
// Set the adapter
recyclerView = (RecyclerView) view.findViewById(R.id.rv_comment_list);
Context context = view.getContext();
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof <API key>) {
mListener = (<API key>) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement <API key>");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onRefresh() {
l.d("onRefresh");
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setRefreshing(true);
}
if (serviceId != -1 && userId != -1) {
l.d("Fetching reviews for serviceId: " + serviceId + " and userId=" + userId);
LaundroDb.getReviewManager().getAllReviews(serviceId, userId).queryInBackground(new <API key>() {
@Override
public void onQueryComplete(Cursor c, SQLException e) {
if (e != null) {
mListener.<API key>(e);
} else {
List<Review> list = LaundroDb.getReviewManager().getRowsFromResult(c);
l.i("Point query completed with " + list.size() + " results");
if (asserter.assertPointer(recyclerView))
recyclerView.setAdapter(new <API key>(list, mListener));
swipeRefreshLayout.setRefreshing(false);
}
}
});
}
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
public interface <API key> {
void <API key>(Review item);
void <API key>(SQLException e);
}
} |
# modification, are permitted provided that the following conditions are
# met:
# the distribution.
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import IECore
import Gaffer
import GafferTest
import GafferUI
import GafferUITest
class GadgetTest( GafferUITest.TestCase ) :
def testTransform( self ) :
g = GafferUI.TextGadget( "hello" )
self.assertEqual( g.getTransform(), IECore.M44f() )
t = IECore.M44f.createScaled( IECore.V3f( 2 ) )
g.setTransform( t )
self.assertEqual( g.getTransform(), t )
c1 = GafferUI.LinearContainer()
c1.addChild( g )
c2 = GafferUI.LinearContainer()
c2.addChild( c1 )
t2 = IECore.M44f.createTranslated( IECore.V3f( 1, 2, 3 ) )
c2.setTransform( t2 )
self.assertEqual( g.fullTransform(), t * t2 )
self.assertEqual( g.fullTransform( c1 ), t )
def testToolTip( self ) :
g = GafferUI.TextGadget( "hello" )
self.assertEqual( g.getToolTip( IECore.LineSegment3f() ), "" )
g.setToolTip( "hi" )
self.assertEqual( g.getToolTip( IECore.LineSegment3f() ), "hi" )
def <API key>( self ) :
class MyGadget( GafferUI.Gadget ) :
def __init__( self ) :
GafferUI.Gadget.__init__( self )
def bound( self ) :
return IECore.Box3f( IECore.V3f( -20, 10, 2 ), IECore.V3f( 10, 15, 5 ) )
mg = MyGadget()
# we can't call the methods of the gadget directly in python to test the
# bindings, as that doesn't prove anything (we're no exercising the virtual
# method override code in the wrapper). instead cause c++ to call through
# for us by adding our gadget to a parent and making calls to the parent.
c = GafferUI.IndividualContainer()
c.addChild( mg )
self.assertEqual( c.bound().size(), mg.bound().size() )
def testStyle( self ) :
g = GafferUI.TextGadget( "test" )
l = GafferUI.LinearContainer()
l.addChild( g )
self.assertEqual( g.getStyle(), None )
self.assertEqual( l.getStyle(), None )
self.failUnless( g.style().isSame( GafferUI.Style.getDefaultStyle() ) )
self.failUnless( l.style().isSame( GafferUI.Style.getDefaultStyle() ) )
s = GafferUI.StandardStyle()
l.setStyle( s )
self.failUnless( l.getStyle().isSame( s ) )
self.assertEqual( g.getStyle(), None )
self.failUnless( g.style().isSame( s ) )
self.failUnless( l.style().isSame( s ) )
def <API key>( self ) :
self.<API key>( GafferUI )
self.<API key>( GafferUITest )
def <API key>( self ) :
g = GafferUI.Gadget()
cs = GafferTest.CapturingSlot( g.renderRequestSignal() )
self.assertEqual( len( cs ), 0 )
s = GafferUI.StandardStyle()
g.setStyle( s )
self.assertEqual( len( cs ), 1 )
self.assertTrue( cs[0][0].isSame( g ) )
s2 = GafferUI.StandardStyle()
g.setStyle( s2 )
self.assertEqual( len( cs ), 2 )
self.assertTrue( cs[1][0].isSame( g ) )
s2.setColor( GafferUI.StandardStyle.Color.BackgroundColor, IECore.Color3f( 1 ) )
self.assertEqual( len( cs ), 3 )
self.assertTrue( cs[2][0].isSame( g ) )
def testHighlighting( self ) :
g = GafferUI.Gadget()
self.assertEqual( g.getHighlighted(), False )
g.setHighlighted( True )
self.assertEqual( g.getHighlighted(), True )
g.setHighlighted( False )
self.assertEqual( g.getHighlighted(), False )
cs = GafferTest.CapturingSlot( g.renderRequestSignal() )
g.setHighlighted( False )
self.assertEqual( len( cs ), 0 )
g.setHighlighted( True )
self.assertEqual( len( cs ), 1 )
self.assertTrue( cs[0][0].isSame( g ) )
def testVisibility( self ) :
g1 = GafferUI.Gadget()
self.assertEqual( g1.getVisible(), True )
self.assertEqual( g1.visible(), True )
g1.setVisible( False )
self.assertEqual( g1.getVisible(), False )
self.assertEqual( g1.visible(), False )
g2 = GafferUI.Gadget()
g1.addChild( g2 )
self.assertEqual( g2.getVisible(), True )
self.assertEqual( g2.visible(), False )
g1.setVisible( True )
self.assertEqual( g2.visible(), True )
g3 = GafferUI.Gadget()
g2.addChild( g3 )
self.assertEqual( g3.getVisible(), True )
self.assertEqual( g3.visible(), True )
g1.setVisible( False )
self.assertEqual( g3.getVisible(), True )
self.assertEqual( g3.visible(), False )
self.assertEqual( g3.visible( relativeTo = g2 ), True )
self.assertEqual( g3.visible( relativeTo = g1 ), True )
def <API key>( self ) :
g = GafferUI.Gadget()
cs = GafferTest.CapturingSlot( g.renderRequestSignal() )
self.assertEqual( len( cs ), 0 )
g.setVisible( True )
self.assertEqual( len( cs ), 0 )
g.setVisible( False )
self.assertEqual( len( cs ), 1 )
self.assertEqual( cs[0][0], g )
g.setVisible( False )
self.assertEqual( len( cs ), 1 )
self.assertEqual( cs[0][0], g )
g.setVisible( True )
self.assertEqual( len( cs ), 2 )
self.assertEqual( cs[1][0], g )
def <API key>( self ) :
g = GafferUI.Gadget()
t = GafferUI.TextGadget( "text" )
g.addChild( t )
b = t.bound()
self.assertEqual( g.bound(), b )
t.setVisible( False )
# we still want to know what the bound would be for t,
# even when it's hidden.
self.assertEqual( t.bound(), b )
# but we don't want it taken into account when computing
# the parent bound.
self.assertEqual( g.bound(), IECore.Box3f() )
def <API key>( self ) :
g = GafferUI.Gadget()
g["a"] = GafferUI.Gadget()
g["a"]["c"] = GafferUI.Gadget()
g["b"] = GafferUI.Gadget()
events = []
def visibilityChanged( gadget ) :
events.append( ( gadget, gadget.visible() ) )
connnections = [
g.<API key>().connect( visibilityChanged ),
g["a"].<API key>().connect( visibilityChanged ),
g["a"]["c"].<API key>().connect( visibilityChanged ),
g["b"].<API key>().connect( visibilityChanged ),
]
g["b"].setVisible( True )
self.assertEqual( len( events ), 0 )
g["b"].setVisible( False )
self.assertEqual( len( events ), 1 )
self.assertEqual( events[0], ( g["b"], False ) )
g["b"].setVisible( True )
self.assertEqual( len( events ), 2 )
self.assertEqual( events[1], ( g["b"], True ) )
g["a"].setVisible( True )
self.assertEqual( len( events ), 2 )
g["a"].setVisible( False )
self.assertEqual( len( events ), 4 )
self.assertEqual( events[-2], ( g["a"]["c"], False ) )
self.assertEqual( events[-1], ( g["a"], False ) )
g["a"].setVisible( True )
self.assertEqual( len( events ), 6 )
self.assertEqual( events[-2], ( g["a"]["c"], True ) )
self.assertEqual( events[-1], ( g["a"], True ) )
g["a"]["c"].setVisible( False )
self.assertEqual( len( events ), 7 )
self.assertEqual( events[-1], ( g["a"]["c"], False ) )
g.setVisible( False )
self.assertEqual( len( events ), 10 )
self.assertEqual( events[-3], ( g["a"], False ) )
self.assertEqual( events[-2], ( g["b"], False ) )
self.assertEqual( events[-1], ( g, False ) )
g["a"]["c"].setVisible( True )
self.assertEqual( len( events ), 10 )
if __name__ == "__main__":
unittest.main() |
import pcs
from socket import AF_INET, inet_ntop
import struct
import time
import pcs.packets.ipv4
import pcs.packets.igmpv2 as igmpv2
import pcs.packets.igmpv3 as igmpv3
#import pcs.packets.dvmrp
#import pcs.packets.mtrace
<API key> = 0x11
<API key> = 0x12
IGMP_DVMRP = 0x13
<API key> = 0x16
<API key> = 0x17
<API key> = 0x22
IGMP_MTRACE_REPLY = 0x1e
IGMP_MTRACE_QUERY = 0x1f
igmp_map = {
<API key>: igmpv2.igmpv2,
<API key>: igmpv2.igmpv2,
#IGMP_DVMRP: dvmrp.dvmrp,
<API key>: igmpv2.igmpv2,
<API key>: igmpv2.igmpv2,
#IGMP_MTRACE_REPLY: mtrace.reply,
#IGMP_MTRACE_QUERY: mtrace.query,
<API key>: igmpv3.report
}
descr = {
<API key>: "IGMPv2 Query",
<API key>: "IGMPv1 Report",
IGMP_DVMRP: "DVMRP",
<API key>: "IGMPv2 Report",
<API key>: "IGMPv2 Leave",
IGMP_MTRACE_REPLY: "MTRACE Reply",
IGMP_MTRACE_QUERY: "MTRACE Query",
<API key>: "IGMPv3 Report"
}
class igmp(pcs.Packet):
"""IGMP"""
_layout = pcs.Layout()
_map = igmp_map
_descr = descr
def __init__(self, bytes = None, timestamp = None, **kv):
""" Define the common IGMP encapsulation; see RFC 2236. """
type = pcs.Field("type", 8, discriminator=True)
code = pcs.Field("code", 8)
checksum = pcs.Field("checksum", 16)
pcs.Packet.__init__(self, [type, code, checksum], bytes = bytes, **kv)
self.description = "IGMP"
if timestamp is None:
self.timestamp = time.time()
else:
self.timestamp = timestamp
if bytes is not None:
offset = self.sizeof()
if self.type == <API key> and \
len(bytes) >= igmpv3.<API key>:
self.data = igmpv3.query(bytes[offset:len(bytes)],
timestamp = timestamp)
else:
# XXX Workaround Packet.next() -- it only returns something
# if it can discriminate.
self.data = self.next(bytes[offset:len(bytes)],
timestamp = timestamp)
if self.data is None:
self.data = payload.payload(bytes[offset:len(bytes)])
else:
self.data = None
def rdiscriminate(self, packet, discfieldname = None, map = igmp_map):
"""Reverse-map an encapsulated packet back to a discriminator
field value. Like next() only the first match is used."""
#print "reverse discriminating %s" % type(packet)
return pcs.Packet.rdiscriminate(self, packet, "type", map)
def calc_checksum(self):
"""Calculate and store the checksum for this IGMP header.
IGMP checksums are computed over payloads too."""
from pcs.packets.ipv4 import ipv4
self.checksum = 0
tmpbytes = self.bytes
if not self._head is None:
tmpbytes += self._head.collate_following(self)
self.checksum = ipv4.ipv4_cksum(tmpbytes)
def __str__(self):
"""Walk the entire packet and pretty print the values of the fields."""
retval = self._descr[self.type] + "\n"
for field in self._layout:
retval += "%s %s\n" % (field.name, field.value)
return retval |
program manyclaw
! Test function definitions
use <API key>
! Utility modules
use timer_module
use precision_module
implicit none
! Command line arguments
character(len=10) :: input_nx,input_ny,input_num_tests
! Local storage
integer :: num_tests
real(kind=TK) :: ave_time(4)
! Common block parameters
real(kind=sk) :: u,v
real(kind=sk) :: gamma,gamma1
common /advection_rp/ u,v
common /euler_rp/ gamma,gamma1
! Parse command line arguments
nx = 1028
ny = 1028
num_tests = 3
select case(iargc())
case(0)
continue
case(1)
call getarg(1,input_nx)
read(input_nx,'(I10)') nx
ny = nx
num_tests = 3
case(2)
call getarg(1,input_nx)
call getarg(2,input_ny)
read(input_nx,'(I10)') nx
read(input_ny,'(I10)') ny
case(3)
call getarg(1,input_nx)
call getarg(2,input_ny)
call getarg(3,input_num_tests)
read(input_nx,'(I10)') nx
read(input_ny,'(I10)') ny
read(input_num_tests,'(I10)') num_tests
case default
print *, "***ERROR*** Too many command line arguments!"
stop
end select
! Test advection Riemann solvers
num_states = 1
num_aux = 0
num_ghost = 2
num_waves = 1
u = 1.0_sk
v = 1.0_sk
ave_time(1) = <API key>(row_rp_advection,num_tests)
print *,"Advection row method 1 Riemann solver time = ",ave_time(1)," ms."
ave_time(1) = <API key>(row_rp_advection,num_tests)
print *,"Advection row method 2 Riemann solver time = ",ave_time(1)," ms."
ave_time(1) = <API key>(row_rp_advection,num_tests)
print *,"Advection row method 3 Riemann solver time = ",ave_time(1)," ms."
ave_time(2) = <API key>(ptwise_rp_advection,num_tests)
print *,"Advection ptwise Riemann solver time = ",ave_time(2)," ms."
! Test Euler Riemann solvers
num_states = 4
num_aux = 0
num_ghost = 2
num_waves = 4
gamma = 1.4_sk
gamma1 = 1.0_sk - gamma
ave_time(3) = <API key>(row_rp_euler,num_tests)
print *,"Euler row method 1 Riemann solver time = ",ave_time(3)," ms."
ave_time(3) = <API key>(row_rp_euler,num_tests)
print *,"Euler row method 2 Riemann solver time = ",ave_time(3)," ms."
ave_time(3) = <API key>(row_rp_euler,num_tests)
print *,"Euler row method 3 Riemann solver time = ",ave_time(3)," ms."
ave_time(4) = <API key>(ptwise_rp_euler,num_tests)
print *,"Euler ptwise Riemann solver time = ",ave_time(4)," ms."
end program manyclaw |
package glfw2
import (
gl "github.com/tHinqa/outside-opengl"
"testing"
)
var mode VidMode
func TestInit(t *testing.T) {
if Init() {
GetDesktopMode(&mode)
var major, minor, rev int
//TODO(t) Find out why 0.0.0
GetGLVersion(&major, &minor, &rev)
t.Logf("GLFW Version: %v.%v.%v", major, minor, rev)
t.Logf("%+v", mode)
if OpenWindow(mode.Width/2, mode.Height/2,
mode.RedBits, mode.GreenBits, mode.BlueBits,
0, 0, 0, Window) {
SetWindowTitle("Go GLFW 2")
SetWindowPos(mode.Width/2-mode.Width/4, mode.Height/2-mode.Height/4)
gl.Clear(gl.ColorBufferBit)
SwapBuffers()
Sleep(2.5) // seconds
t.Logf("Elapsed (including 2.5s sleep): %fs", GetTime())
GetTime() // discard
s := GetTime()
t.Logf("GetTime() call duration: ~%dns", int((GetTime()-s)*1e9))
} else {
t.Fatal("OpenWindow: Failed to Open Window")
}
Terminate()
} else {
t.Fatal("Init: Failed to initialize GLFW")
}
}
//TODO(t): Credits
func TestMode(t *testing.T) {
const MAX_NUM_MODES = 400
var (
dtmode VidMode
modes [MAX_NUM_MODES]VidMode
)
if !Init() {
t.Fail()
}
GetDesktopMode(&dtmode)
t.Logf("Desktop mode: %d x %d x %d\n",
dtmode.Width, dtmode.Height, dtmode.RedBits+
dtmode.GreenBits+dtmode.BlueBits)
//TODO(t): make slice
modecount := GetVideoModes(&modes[0], MAX_NUM_MODES)
t.Log("Available modes:")
for i := 0; i < modecount; i++ {
t.Logf("%3d: %d x %d x %d\n", i,
modes[i].Width, modes[i].Height, modes[i].RedBits+
modes[i].GreenBits+modes[i].BlueBits)
}
Terminate()
} |
/* NOTE - eventually this file will be automatically updated using a Perl script that understand
* the naming of test case files, functions, and namespaces.
*/
#include <time.h> /* for time() */
#include <stdlib.h> /* for srand() */
#include "std_testcase.h"
#include "testcases.h"
int main(int argc, char * argv[]) {
/* seed randomness */
srand( (unsigned)time(NULL) );
globalArgc = argc;
globalArgv = argv;
#ifndef OMITGOOD
/* Calling C good functions */
/* <API key> */
/* <API key> */
#ifdef __cplusplus
/* Calling C++ good functions */
/* <API key> */
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
printLine("Calling <API key>::good();");
<API key>::good();
/* <API key> */
#endif /* __cplusplus */
#endif /* OMITGOOD */
#ifndef OMITBAD
/* Calling C bad functions */
/* <API key> */
/* <API key> */
#ifdef __cplusplus
/* Calling C++ bad functions */
/* <API key> */
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
printLine("Calling <API key>::bad();");
<API key>::bad();
/* <API key> */
#endif /* __cplusplus */
#endif /* OMITBAD */
return 0;
} |
DATA_URL = '/notebook/'+document.location.pathname.split('/')[2]+'/';
CONTROL_URL = '/backend/'+document.location.pathname.split('/')[2]+'/';
INTERPRETER_URL = '/asyncnotebook/'+document.location.pathname.split('/')[2];
Notebook.Async = function() {
};
// Should Async be a class or not?
Notebook.Async.initialize = function() {
// eval json written to html body by server
var url = DATA_URL+'nbobject';
var success = function (res) {
if (res.orderlist == "orderlist"){ //no cells exists
Util.helperCell();
}
Notebook.Load.takeCellsData(res);
}
$.getJSON(url, success);
Notebook.Async.startEngine();
Notebook.Indicator.endMsg();
};
Notebook.Async.startEngine = function() {
var path = INTERPRETER_URL;
var data = JSON.stringify({method:'start'});
$.ajax({
url:path,
type:'POST',
data:data,
dataType:'json',
success: function(result) {
//engine started
//console.info(result)
},
error: function(result) {
//engine failed to start
//console.info(result)
}});
};
Notebook.Async.signalKernel = function(action) {
var self = Notebook.Async;
var path = INTERPRETER_URL;
var data = JSON.stringify({'method':action});
$.ajax({
url:path,
type:'POST',
data:data,
dataType:'json',
success:self.signalSuccess,
error:self.signalError});
};
Notebook.Async.signalSuccess = function(result) {
};
Notebook.Async.signalError = function(result) {
};
Notebook.Async.evalCell = function(cellid, input) {
var self = Notebook.Async;
var path = INTERPRETER_URL;
if (input == '?') {
var input = 'introspect?';
}
var data = JSON.stringify({method:'evaluate', 'cellid':cellid, 'input':input});
/*
$.post(path, data, self.evalSuccess, 'json')
*/
$.ajax({
url:path,
type:'POST',
data:data,
dataType:'json',
success:self.evalSuccess});
return;
};
Notebook.Async.evalSuccess = function(response) {
var self = Notebook.Async;
var t = Notebook.TreeBranch;
var cellid = response.cellid;
var incount = 'In[' + response.input_count + ']:';
var outcount = 'Out[' + response.input_count + ']:';
//$('#'+cellid)[0].saved = true; //not evaluating
//This is where numbering of cells could go.
$('#'+cellid)[0].numberLabel(incount);
var cellstyle = response.cellstyle;
var content = response.out + response.err;
t.spawnOutputCellNode(cellid, cellstyle, content, outcount);
$('#'+cellid)[0].evalResult();
Notebook.Save._save(self.evalSaveSuccess, self.evalSaveError);
};
Notebook.Async.evalError = function(response) {
};
Notebook.Async.evalSaveSuccess = function(response) {
};
Notebook.Async.evalSaveError = function(response) {
};
Notebook.Async.saveToDatabase = function(orderlist, cellsdata, success, error) {
var path = DATA_URL+'save';
var cells = JSON.stringify(cellsdata);
var orderlist = JSON.stringify(orderlist);
var data = {'orderlist':orderlist, 'cellsdata':cells};
$.ajax({
url:path,
type:'POST',
data:data,
dataType:'json',
success:success,
error:error});
};
Notebook.Async.deleteCells = function(mainid, ids) {
var path = BASE_URL+'deletecell';
var cellids = JSON.stringify(ids);
var data = {'cellids':cellids};
/*xxx: need to finish
var d = a.doXHR(path, {
method:'post',
headers:{'Content-Type':'application/<API key>'},
sendContent:data});
var delback = b.partial($(mainid).deleteCallback, mainid)
d.addCallbacks(delback, $(mainid).deleteErr);
return d;
*/
};
Notebook.Async.changeNotebookTitle = function(title, success, error) {
var path = DATA_URL+'title';
var data = {'newtitle':title};
$.ajax({
url:path,
type:'POST',
data:data,
dataType:'json',
success:success,
error:error});
};
/** completeName - for completing the name of a variable or function */
Notebook.Async.completeName = function(cellid, mode, input, success, error) {
//request match from server
// this ultimatly returns a list of 0 or more match possibilities
var path = INTERPRETER_URL;
var data = JSON.stringify({method:'complete', 'mode':mode, 'cellid':cellid, 'input':input});
$.ajax({
url:path,
type:'POST',
data:data,
dataType:'json',
success:success,
error:error});
};
//$(document).ready(Notebook.Async.initialize);
Notebook.__init__.Async = function() {
Notebook.Async.initialize();
}; |
# This file is part of Workspace.
# modification, are permitted provided that the following conditions are met:
# and/or other materials provided with the distribution.
# contributors may be used to endorse or promote products derived from this
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# application name
PROJECT_NAME := $(notdir $(PROJECT))
# Modules needed by the application
PROJECT_MODULES := modules/$(TARGET)/base \
modules/$(TARGET)/board \
modules/$(TARGET)/chip
# source files folder
PROJECT_SRC_FOLDERS := $(PROJECT)/src
# header files folder
PROJECT_INC_FOLDERS := $(PROJECT)/inc
# source files |
package edu.cornell.mannlib.vitro.webapp.controller.edit.listing;
import java.net.URLEncoder;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.cornell.mannlib.vitro.webapp.utils.JSPPageHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vedit.controller.BaseEditController;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.PropertyGroup;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyGroupDao;
public class <API key> extends BaseEditController {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(<API key>.class);
private static final boolean WITH_PROPERTIES = true;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
if (!is<API key>(request, response,
SimplePermission.EDIT_ONTOLOGY.ACTION)) {
return;
}
VitroRequest vreq = new VitroRequest(request);
PropertyGroupDao dao = vreq.<API key>().getPropertyGroupDao();
List<PropertyGroup> groups = dao.getPublicGroups(WITH_PROPERTIES);
Comparator<Property> comparator = new PropertySorter(vreq.getCollator());
List<String> results = new ArrayList<String>();
results.add("XX");
results.add("group");
results.add("display rank");
results.add("");
results.add("XX");
if (groups != null) {
for(PropertyGroup pg: groups) {
results.add("XX");
String publicName = pg.getName();
if ( StringUtils.isBlank(publicName) ) {
publicName = "(unnamed group)";
}
try {
results.add("<a href=\"./editForm?uri="+URLEncoder.encode(pg.getURI(),"UTF-8")+"&controller=PropertyGroup\">"+publicName+"</a>");
} catch (Exception e) {
results.add(publicName);
}
Integer t;
results.add(((t = Integer.valueOf(pg.getDisplayRank())) != -1) ? t.toString() : "");
results.add("");
results.add("XX");
List<Property> propertyList = pg.getPropertyList();
if (propertyList != null && propertyList.size() > 0) {
propertyList.sort(comparator);
results.add("+");
results.add("XX");
results.add("property");
results.add("");
results.add("");
results.add("@@entities");
Iterator<Property> propIt = propertyList.iterator();
while (propIt.hasNext()) {
Property prop = propIt.next();
results.add("XX");
String controllerStr = "propertyEdit";
String nameStr =
(prop.getLabel() == null)
? ""
: prop.getLabel();
if (prop instanceof ObjectProperty) {
nameStr = ((ObjectProperty) prop).getDomainPublic();
} else if (prop instanceof DataProperty) {
controllerStr = "datapropEdit";
nameStr = ((DataProperty) prop).getName();
}
if (prop.getURI() != null) {
try {
results.add("<a href=\"" + controllerStr +
"?uri="+URLEncoder.encode(
prop.getURI(),"UTF-8") +
"\">" + nameStr +"</a>");
} catch (Exception e) {
results.add(nameStr);
}
} else {
results.add(nameStr);
}
String exampleStr = "";
results.add(exampleStr);
String descriptionStr = "";
results.add(descriptionStr);
if (propIt.hasNext())
results.add("@@entities");
}
}
}
request.setAttribute("results",results);
}
request.setAttribute("columncount",new Integer(5));
request.setAttribute("suppressquery","true");
request.setAttribute("title","Property Groups");
request.setAttribute("<API key>", Controllers.RETRY_URL);
request.setAttribute("<API key>", "Add new property group");
request.setAttribute("<API key>", "PropertyGroup");
try {
JSPPageHandler.renderBasicPage(request, response, Controllers.HORIZONTAL_JSP);
} catch (Throwable t) {
t.printStackTrace();
}
}
private class PropertySorter implements Comparator<Property> {
Collator collator;
public PropertySorter(Collator collator) {
this.collator = collator;
}
public int compare(Property p1, Property p2) {
String name1 = getName(p1);
String name2 = getName(p2);
if (name1 == null && name2 != null) {
return 1;
} else if (name2 == null && name1 != null) {
return -1;
} else if (name1 == null && name2 == null) {
return 0;
}
return collator.compare(name1, name2);
}
private String getName(Property prop) {
if (prop instanceof ObjectProperty) {
return ((ObjectProperty) prop).getDomainPublic();
} else if (prop instanceof DataProperty) {
return ((DataProperty) prop).getName();
} else {
return prop.getLabel();
}
}
}
} |
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
$fruits1= array (
"fruits2" => array("d" => "orange", "e" => "banana", "f" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
<API key>($fruits,$fruits1);
echo json_encode($fruits);
?> |
Object.defineProperty(exports, "__esModule", { value: true });
var Event = /** @class */ (function () {
function Event(req, res, fullPath) {
this.preventDefault = false;
this.req = req;
this.res = res;
this.fullPath = fullPath;
}
Event.prototype.PreventDefault = function () {
this.preventDefault = true;
return this;
};
Event.prototype.IsPreventDefault = function () {
return this.preventDefault;
};
return Event;
}());
exports.Event = Event;
//# sourceMappingURL=Event.js.map |
<?php
return array(
'functions' => array(
'geoip_asnum_by_name',
'<API key>',
'<API key>',
'<API key>',
'<API key>',
'geoip_database_info',
'geoip_db_avail',
'geoip_db_filename',
'<API key>',
'<API key>',
'geoip_id_by_name',
'geoip_isp_by_name',
'<API key>',
'geoip_org_by_name',
'<API key>',
'<API key>',
'<API key>',
'<API key>',
'<API key>',
),
'constants' => array(
'<API key>',
'<API key>',
'<API key>',
'GEOIP_ORG_EDITION',
'GEOIP_ISP_EDITION',
'<API key>',
'<API key>',
'GEOIP_PROXY_EDITION',
'GEOIP_ASNUM_EDITION',
'<API key>',
'<API key>',
'GEOIP_UNKNOWN_SPEED',
'GEOIP_DIALUP_SPEED',
'<API key>',
'<API key>',
),
'description' => 'Geo IP Location',
); |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model frontend\models\HargaSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="harga-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'jenis_kendaraan') ?>
<?= $form->field($model, 'harga') ?>
<?= $form->field($model, 'create_date') ?>
<?= $form->field($model, 'update_date') ?>
<?php // echo $form->field($model, 'status') ?>
<?php // echo $form->field($model, 'approval') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div> |
package gov.nih.nci.ncicb.cadsr.bulkloader.persist;
public class PersisterStatus {
public static final PersisterStatus SUCCESS = new PersisterStatus(2, "Successfully Persisted");
public static final PersisterStatus FAILURE = new PersisterStatus(3, "Persistence failed");
private final int code;
private final String message;
private PersisterStatus(int _code, String _message) {
code = _code;
message = _message;
}
public String getMessage() {
return message;
}
public boolean isSuccessful() {
if (code == 0) return true;
switch (code % 2) {
case 0: return true;
default: return false;
}
}
public String toString() {
return message;
}
} |
"""
Tests for content parsing, and form-overloaded content parsing.
"""
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.sessions.middleware import SessionMiddleware
from django.core.handlers.wsgi import WSGIRequest
from django.test import TestCase
from rest_framework import status
from rest_framework.authentication import <API key>
from rest_framework.compat import patterns
from rest_framework.parsers import (
BaseParser,
FormParser,
MultiPartParser,
JSONParser
)
from rest_framework.request import Request, Empty
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework.test import APIRequestFactory, APIClient
from rest_framework.views import APIView
from rest_framework.compat import six
from io import BytesIO
import json
factory = APIRequestFactory()
class PlainTextParser(BaseParser):
media_type = 'text/plain'
def parse(self, stream, media_type=None, parser_context=None):
"""
Returns a 2-tuple of `(data, files)`.
`data` will simply be a string representing the body of the request.
`files` will always be `None`.
"""
return stream.read()
class <API key>(TestCase):
def test_method(self):
"""
Request methods should be same as underlying request.
"""
request = Request(factory.get('/'))
self.assertEqual(request.method, 'GET')
request = Request(factory.post('/'))
self.assertEqual(request.method, 'POST')
def <API key>(self):
"""
POST requests can be overloaded to another method by setting a
reserved form field
"""
request = Request(factory.post('/', {api_settings.<API key>: 'DELETE'}))
self.assertEqual(request.method, 'DELETE')
def <API key>(self):
"""
POST requests can also be overloaded to another method by setting
the <API key> header.
"""
request = Request(factory.post('/', {'foo': 'bar'}, <API key>='DELETE'))
self.assertEqual(request.method, 'DELETE')
request = Request(factory.get('/', {'foo': 'bar'}, <API key>='DELETE'))
self.assertEqual(request.method, 'DELETE')
class TestContentParsing(TestCase):
def <API key>(self):
"""
Ensure request.DATA returns empty QueryDict for GET request.
"""
request = Request(factory.get('/'))
self.assertEqual(request.DATA, {})
def <API key>(self):
"""
Ensure request.DATA returns empty QueryDict for HEAD request.
"""
request = Request(factory.head('/'))
self.assertEqual(request.DATA, {})
def <API key>(self):
"""
Ensure request.DATA returns content for POST request with form content.
"""
data = {'qwerty': 'uiop'}
request = Request(factory.post('/', data))
request.parsers = (FormParser(), MultiPartParser())
self.assertEqual(list(request.DATA.items()), list(data.items()))
def <API key>(self):
"""
Ensure request.DATA returns content for POST request with
non-form content.
"""
content = six.b('qwerty')
content_type = 'text/plain'
request = Request(factory.post('/', content, content_type=content_type))
request.parsers = (PlainTextParser(),)
self.assertEqual(request.DATA, content)
def <API key>(self):
"""
Ensure request.POST returns content for POST request with form content.
"""
data = {'qwerty': 'uiop'}
request = Request(factory.post('/', data))
request.parsers = (FormParser(), MultiPartParser())
self.assertEqual(list(request.POST.items()), list(data.items()))
def <API key>(self):
"""
Ensure request.DATA returns content for PUT request with form content.
"""
data = {'qwerty': 'uiop'}
request = Request(factory.put('/', data))
request.parsers = (FormParser(), MultiPartParser())
self.assertEqual(list(request.DATA.items()), list(data.items()))
def <API key>(self):
"""
Ensure request.DATA returns content for PUT request with
non-form content.
"""
content = six.b('qwerty')
content_type = 'text/plain'
request = Request(factory.put('/', content, content_type=content_type))
request.parsers = (PlainTextParser(), )
self.assertEqual(request.DATA, content)
def <API key>(self):
"""
Ensure request.DATA returns content for overloaded POST request.
"""
json_data = {'foobar': 'qwerty'}
content = json.dumps(json_data)
content_type = 'application/json'
form_data = {
api_settings.<API key>: content,
api_settings.<API key>: content_type
}
request = Request(factory.post('/', form_data))
request.parsers = (JSONParser(), )
self.assertEqual(request.DATA, json_data)
def <API key>(self):
"""
JSON POST via default web interface with unicode data
"""
# Note: environ and other variables here have simplified content compared to real Request
CONTENT = b'_content_type=application%2Fjson&_content=%7B%22request%22%3A+4%2C+%22firm%22%3A+1%2C+%22text%22%3A+%22%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82%21%22%7D'
environ = {
'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'application/<API key>',
'CONTENT_LENGTH': len(CONTENT),
'wsgi.input': BytesIO(CONTENT),
}
wsgi_request = WSGIRequest(environ=environ)
wsgi_request.<API key>()
parsers = (JSONParser(), FormParser(), MultiPartParser())
parser_context = {
'encoding': 'utf-8',
'kwargs': {},
'args': (),
}
request = Request(wsgi_request, parsers=parsers, parser_context=parser_context)
method = request.method
self.assertEqual(method, 'POST')
self.assertEqual(request._content_type, 'application/json')
self.assertEqual(request._stream.getvalue(), b'{"request": 4, "firm": 1, "text": "\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!"}')
self.assertEqual(request._data, Empty)
self.assertEqual(request._files, Empty)
# def <API key>(self):
# """
# Ensures request.POST can be accessed after request.DATA in
# form request.
# """
# data = {'qwerty': 'uiop'}
# request = factory.post('/', data=data)
# self.assertEqual(request.DATA.items(), data.items())
# self.assertEqual(request.POST.items(), data.items())
# def <API key>(self):
# """
# Ensures request.POST can be accessed after request.DATA in
# json request.
# """
# data = {'qwerty': 'uiop'}
# content = json.dumps(data)
# content_type = 'application/json'
# parsers = (JSONParser, )
# request = factory.post('/', content, content_type=content_type,
# parsers=parsers)
# self.assertEqual(request.DATA.items(), data.items())
# self.assertEqual(request.POST.items(), [])
# def <API key>(self):
# """
# Ensures request.POST can be accessed after request.DATA in overloaded
# json request.
# """
# data = {'qwerty': 'uiop'}
# content = json.dumps(data)
# content_type = 'application/json'
# parsers = (JSONParser, )
# form_data = {Request._CONTENT_PARAM: content,
# Request._CONTENTTYPE_PARAM: content_type}
# request = factory.post('/', form_data, parsers=parsers)
# self.assertEqual(request.DATA.items(), data.items())
# self.assertEqual(request.POST.items(), form_data.items())
# def <API key>(self):
# """
# Ensures request.DATA can be accessed after request.POST in
# form request.
# """
# data = {'qwerty': 'uiop'}
# parsers = (FormParser, MultiPartParser)
# request = factory.post('/', data, parsers=parsers)
# self.assertEqual(request.POST.items(), data.items())
# self.assertEqual(request.DATA.items(), data.items())
# def <API key>(self):
# """
# Ensures request.DATA can be accessed after request.POST in
# json request.
# """
# data = {'qwerty': 'uiop'}
# content = json.dumps(data)
# content_type = 'application/json'
# parsers = (JSONParser, )
# request = factory.post('/', content, content_type=content_type,
# parsers=parsers)
# self.assertEqual(request.POST.items(), [])
# self.assertEqual(request.DATA.items(), data.items())
# def <API key>(self):
# """
# Ensures request.DATA can be accessed after request.POST in overloaded
# json request
# """
# data = {'qwerty': 'uiop'}
# content = json.dumps(data)
# content_type = 'application/json'
# parsers = (JSONParser, )
# form_data = {Request._CONTENT_PARAM: content,
# Request._CONTENTTYPE_PARAM: content_type}
# request = factory.post('/', form_data, parsers=parsers)
# self.assertEqual(request.POST.items(), form_data.items())
# self.assertEqual(request.DATA.items(), data.items())
class MockView(APIView):
<API key> = (<API key>,)
def post(self, request):
if request.POST.get('app_scaffolding') is not None:
return Response(status=status.HTTP_200_OK)
return Response(status=status.<API key>)
urlpatterns = patterns('',
(r'^$', MockView.as_view()),
)
class <API key>(TestCase):
urls = 'rest_framework.tests.test_request'
def setUp(self):
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.username = 'john'
self.email = 'lennon@thebeatles.com'
self.password = 'password'
self.user = User.objects.create_user(self.username, self.email, self.password)
def <API key><API key>(self):
"""
Ensures request.POST exists after <API key> when user
doesn't log in.
"""
content = {'app_scaffolding': 'app_scaffolding'}
response = self.client.post('/', content)
self.assertEqual(status.HTTP_200_OK, response.status_code)
response = self.csrf_client.post('/', content)
self.assertEqual(status.HTTP_200_OK, response.status_code)
# def <API key><API key>(self):
# """Ensures request.POST exists after <API key> when user does log in"""
# self.client.login(username='john', password='password')
# self.csrf_client.login(username='john', password='password')
# content = {'app_scaffolding': 'app_scaffolding'}
# response = self.client.post('/', content)
# self.assertEqual(status.OK, response.status_code, "POST data is malformed")
# response = self.csrf_client.post('/', content)
# self.assertEqual(status.OK, response.status_code, "POST data is malformed")
class TestUserSetter(TestCase):
def setUp(self):
# Pass request object through session middleware so session is
# available to login and logout functions
self.request = Request(factory.get('/'))
SessionMiddleware().process_request(self.request)
User.objects.create_user('ringo', 'starr@thebeatles.com', 'yellow')
self.user = authenticate(username='ringo', password='yellow')
def <API key>(self):
self.request.user = self.user
self.assertEqual(self.request.user, self.user)
def test_user_can_login(self):
login(self.request, self.user)
self.assertEqual(self.request.user, self.user)
def <API key>(self):
self.request.user = self.user
self.assertFalse(self.request.user.is_anonymous())
logout(self.request)
self.assertTrue(self.request.user.is_anonymous())
class TestAuthSetter(TestCase):
def <API key>(self):
request = Request(factory.get('/'))
request.auth = 'DUMMY'
self.assertEqual(request.auth, 'DUMMY') |
C+ ENQ_TSYS
subroutine enq_tsys( lun, temps, nominal, s )
C
C Enquire the telescope system temperatures from the control tables
C
C Given:
C sample file logical unit number
integer lun
C Returned:
C eight nominal telescope system temperatures
real*4 temps( 1 )
C nominal value of rain gauge reading (usually 8 V)
real*4 nominal
C error status
integer s
C
C Information required for the system temps is found from the control
C tables of the sample file. This routine is only applicable
C to the Ryle telescope and returns all 1's for the CLFST.
C
C MEJ 08/09/92
C-
include '/mrao/post/include/control_tables.inc'
include '/mrao/post/include/samplib_errors.inc'
if ( s .ne. 0 ) return
call read_ct( lun, s )
if ( s .ne. 0 ) goto 999
if (ct_vers .le. 1) then
call enq_v1_tsys( temps, nominal, s )
elseif (ct_vers .eq. 2) then
call enq_v2_tsys( temps, nominal, s )
else
s = ILL_CONTTAB
goto 999
endif
return
999 call smp_wrerr( s, 'in subroutine ENQ_TSYS' )
return
end |
#import <ABI42_0_0React/<API key>.h>
@interface <API key> : <API key>
@end |
import logging
import fmcapi
def <API key>(fmc):
logging.info(
"Test <API key>. get, post, put, "
"delete <API key> Objects"
)
obj1 = fmcapi.DeviceHAFailoverMAC(fmc=fmc, ha_name="HaName")
obj1.p_interface(name="GigabitEthernet0/0", device_name="device_name")
obj1.failoverActiveMac = "0050.5686.718f"
obj1.failoverStandbyMac = "1050.5686.0c2e"
logging.info("DeviceHAFailoverMAC POST->")
logging.info(obj1.format_data())
obj1.post()
del obj1
obj1 = fmcapi.DeviceHAFailoverMAC(fmc=fmc)
obj1.edit(name="GigabitEthernet0/0", ha_name="HaName")
obj1.failoverStandbyMac = "0050.5686.0c2e"
logging.info("DeviceHAFailoverMAC PUT->")
logging.info(obj1.format_data())
del obj1
obj1 = fmcapi.DeviceHAFailoverMAC(fmc=fmc)
obj1.edit(name="GigabitEthernet0/0", ha_name="HaName")
obj1.delete() |
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>mne.datasets.brainstorm.bst_resting.data_path — MNE 0.11.0 documentation</title>
<link rel="stylesheet" href="../_static/basic.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/gallery.css" type="text/css" />
<link rel="stylesheet" href="../_static/bootswatch-3.3.4/flatly/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
<link rel="stylesheet" href="../_static/style.css" type="text/css" />
<script type="text/javascript">
var <API key> = {
URL_ROOT: '../',
VERSION: '0.11.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=<API key>"></script>
<script type="text/javascript" src="../_static/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../_static/js/jquery-fix.js"></script>
<script type="text/javascript" src="../_static/bootstrap-3.3.4/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../_static/bootstrap-sphinx.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="top" title="MNE 0.11.0 documentation" href="../index.html" />
<link rel="up" title="API Reference" href="../python_reference.html" />
<link rel="next" title="mne.datasets.brainstorm.bst_raw.data_path" href="mne.datasets.brainstorm.bst_raw.data_path.html" />
<link rel="prev" title="mne.datasets.brainstorm.bst_auditory.data_path" href="mne.datasets.brainstorm.bst_auditory.data_path.html" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-37225609-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https:
var s = document.<API key>('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript">
!function(d,s,id){var js,fjs=d.<API key>(s)[0];if(!d.getElementById(id)){js=d.createElement(s);
js.id=id;js.src="http://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.<API key>('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<link rel="canonical" href="https://mne.tools/stable/index.html" />
</head>
<body role="document">
<div id="navbar" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<!-- .btn-navbar is used as the toggle for collapsed navbar content -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html"><img src="../_static/mne_logo_small.png">
</a>
<span class="navbar-text navbar-version pull-left"><b>0.11.0</b></span>
</div>
<div class="collapse navbar-collapse nav-collapse">
<ul class="nav navbar-nav">
<li><a href="../tutorials.html">Tutorials</a></li>
<li><a href="../auto_examples/index.html">Gallery</a></li>
<li><a href="../manual/index.html">Manual</a></li>
<li><a href="../python_reference.html">API</a></li>
<li><a href="../faq.html">FAQ</a></li>
<li><a href="../cite.html">Cite</a></li>
<li class="dropdown globaltoc-container">
<a role="button"
id="dLabelGlobalToc"
data-toggle="dropdown"
data-target="
href="../index.html">Site <b class="caret"></b></a>
<ul class="dropdown-menu globaltoc"
role="menu"
aria-labelledby="dLabelGlobalToc"><ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../getting_started.html">Getting Started</a></li>
<li class="toctree-l1"><a class="reference internal" href="../whats_new.html">What’s new</a></li>
<li class="toctree-l1"><a class="reference internal" href="../cite.html">Cite MNE</a></li>
<li class="toctree-l1"><a class="reference internal" href="../references.html">Related publications</a></li>
<li class="toctree-l1"><a class="reference internal" href="../tutorials.html">Tutorials</a></li>
<li class="toctree-l1"><a class="reference internal" href="../auto_examples/index.html">Examples Gallery</a></li>
<li class="toctree-l1"><a class="reference internal" href="../manual/index.html">Manual</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../python_reference.html">API Reference</a></li>
<li class="toctree-l1"><a class="reference internal" href="../faq.html">Frequently Asked Questions</a></li>
<li class="toctree-l1"><a class="reference internal" href="../advanced_setup.html">Advanced installation and setup</a></li>
<li class="toctree-l1"><a class="reference internal" href="../mne_cpp.html">MNE with CPP</a></li>
</ul>
</ul>
</li>
<li class="dropdown">
<a role="button"
id="dLabelLocalToc"
data-toggle="dropdown"
data-target="
href="#">Page <b class="caret"></b></a>
<ul class="dropdown-menu localtoc"
role="menu"
aria-labelledby="dLabelLocalToc"><ul>
<li><a class="reference internal" href="#">mne.datasets.brainstorm.bst_resting.data_path</a></li>
</ul>
</ul>
</li>
</ul>
<form class="navbar-form navbar-right" action="../search.html" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="<API key>">
<p class="logo"><a href="../index.html">
<img class="logo" src="../_static/mne_logo_small.png" alt="Logo"/>
</a></p><ul>
<li><a class="reference internal" href="#">mne.datasets.brainstorm.bst_resting.data_path</a></li>
</ul>
<li>
<a href="mne.datasets.brainstorm.bst_auditory.data_path.html" title="Previous Chapter: mne.datasets.brainstorm.bst_auditory.data_path"><span class="glyphicon <API key> visible-sm"></span><span class="hidden-sm hidden-tablet">« mne.datasets....</span>
</a>
</li>
<li>
<a href="mne.datasets.brainstorm.bst_raw.data_path.html" title="Next Chapter: mne.datasets.brainstorm.bst_raw.data_path"><span class="glyphicon <API key> visible-sm"></span><span class="hidden-sm hidden-tablet">mne.datasets.... »</span>
</a>
</li>
<form action="../search.html" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="col-md-12">
<div class="section" id="<API key>">
<h1>mne.datasets.brainstorm.bst_resting.data_path<a class="headerlink" href="
<dl class="function">
<dt id="mne.datasets.brainstorm.bst_resting.data_path">
<code class="descclassname">mne.datasets.brainstorm.bst_resting.</code><code class="descname">data_path</code><span class="sig-paren">(</span><em>path=None</em>, <em>force_update=False</em>, <em>update_path=True</em>, <em>download=True</em>, <em>verbose=None</em><span class="sig-paren">)</span><a class="headerlink" href="
<dd><p>Get path to local copy of brainstorm (bst_resting) dataset</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>path</strong> : None | str</p>
<blockquote>
<div><p>Location of where to look for the brainstorm (bst_resting) dataset.
If None, the environment variable or config parameter
<API key> is used. If it doesn’t exist, the
“mne-python/examples” directory is used. If the brainstorm (bst_resting) dataset
is not found under the given path (e.g., as
“mne-python/examples/MNE-brainstorm-data”), the data
will be automatically downloaded to the specified folder.</p>
</div></blockquote>
<p><strong>force_update</strong> : bool</p>
<blockquote>
<div><p>Force update of the brainstorm (bst_resting) dataset even if a local copy exists.</p>
</div></blockquote>
<p><strong>update_path</strong> : bool | None</p>
<blockquote>
<div><p>If True, set the <API key> in mne-python
config to the given path. If None, the user is prompted.</p>
</div></blockquote>
<p><strong>download</strong> : bool</p>
<blockquote>
<div><p>If False and the brainstorm (bst_resting) dataset has not been downloaded yet,
it will not be downloaded and the path will be returned as
‘’ (empty string). This is mostly used for debugging purposes
and can be safely ignored by most users.</p>
</div></blockquote>
<p><strong>verbose</strong> : bool, str, int, or None</p>
<blockquote>
<div><p>If not None, override default verbose level (see mne.verbose).</p>
</div></blockquote>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>path</strong> : str</p>
<blockquote class="last">
<div><p>Path to brainstorm (bst_resting) dataset directory.</p>
</div></blockquote>
</td>
</tr>
</tbody>
</table>
</dd></dl>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-right">
<a href="#">Back to top</a>
<br/>
</p>
<p>
© Copyright 2012-2015, MNE Developers.<br/>
</p>
</div>
</footer>
<script src="https://mne.tools/versionwarning.js"></script>
</body>
</html> |
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname(dirname($vendorDir));
return array(
'yii\\swiftmailer\\' => array($vendorDir . '/yiisoft/yii2-swiftmailer'),
'yii\\gii\\' => array($vendorDir . '/yiisoft/yii2-gii'),
'yii\\faker\\' => array($vendorDir . '/yiisoft/yii2-faker'),
'yii\\debug\\' => array($vendorDir . '/yiisoft/yii2-debug'),
'yii\\composer\\' => array($vendorDir . '/yiisoft/yii2-composer'),
'yii\\codeception\\' => array($vendorDir . '/yiisoft/yii2-codeception'),
'yii\\bootstrap\\' => array($vendorDir . '/yiisoft/yii2-bootstrap'),
'yii\\' => array($vendorDir . '/yiisoft/yii2'),
'mootensai\\relation\\' => array($vendorDir . '/mootensai/yii2-relation-trait'),
'mootensai\\enhancedgii\\' => array($vendorDir . '/mootensai/yii2-enhanced-gii'),
'mootensai\\components\\' => array($vendorDir . '/mootensai/<API key>', $vendorDir . '/mootensai/yii2-jsblock'),
'mootensai\\behaviors\\' => array($vendorDir . '/mootensai/yii2-uuid-behavior'),
'mongosoft\\soapserver\\' => array($vendorDir . '/mongosoft/yii2-soap-server'),
'kartik\\widgets\\' => array($vendorDir . '/kartik-v/yii2-widgets'),
'kartik\\typeahead\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\touchspin\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\time\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\tabs\\' => array($vendorDir . '/kartik-v/yii2-tabs-x'),
'kartik\\switchinput\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\spinner\\' => array($vendorDir . '/kartik-v/yii2-widget-spinner'),
'kartik\\sidenav\\' => array($vendorDir . '/kartik-v/yii2-widget-sidenav'),
'kartik\\select2\\' => array($vendorDir . '/kartik-v/yii2-widget-select2'),
'kartik\\rating\\' => array($vendorDir . '/kartik-v/yii2-widget-rating'),
'kartik\\range\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\plugins\\tabs\\' => array($vendorDir . '/kartik-v/bootstrap-tabs-x'),
'kartik\\plugins\\fileinput\\' => array($vendorDir . '/kartik-v/bootstrap-fileinput'),
'kartik\\plugins\\depdrop\\' => array($vendorDir . '/kartik-v/dependent-dropdown'),
'kartik\\password\\' => array($vendorDir . '/kartik-v/yii2-password'),
'kartik\\mpdf\\' => array($vendorDir . '/kartik-v/yii2-mpdf'),
'kartik\\growl\\' => array($vendorDir . '/kartik-v/yii2-widget-growl'),
'kartik\\grid\\' => array($vendorDir . '/kartik-v/yii2-grid'),
'kartik\\form\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\file\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\export\\' => array($vendorDir . '/kartik-v/yii2-export'),
'kartik\\depdrop\\' => array($vendorDir . '/kartik-v/yii2-widget-depdrop'),
'kartik\\datetime\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\date\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\color\\' => array($vendorDir . '/kartik-v/<API key>'),
'kartik\\builder\\' => array($vendorDir . '/kartik-v/yii2-builder'),
'kartik\\base\\' => array($vendorDir . '/kartik-v/yii2-krajee-base'),
'kartik\\alert\\' => array($vendorDir . '/kartik-v/yii2-widget-alert'),
'kartik\\affix\\' => array($vendorDir . '/kartik-v/yii2-widget-affix'),
'kartik\\' => array($vendorDir . '/kartik-v/strength-meter'),
'cebe\\markdown\\' => array($vendorDir . '/cebe/markdown'),
'Wingu\\OctopusCore\\Reflection\\' => array($vendorDir . '/wingu/reflection/src'),
'PHP2WSDL\\' => array($vendorDir . '/php2wsdl/php2wsdl/src'),
'Faker\\' => array($vendorDir . '/fzaninotto/faker/src/Faker'),
'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'),
); |
"""Python interface to the Chandra Data Archive (CDA) web services and an
interface to a local disk copy of the Observation Catalog (Ocat).
"""
from pathlib import Path
import re
import warnings
import time
import requests
import numpy as np
import tables
from astropy.table import Table, MaskedColumn
from astropy.coordinates import SkyCoord
from mica.common import MICA_ARCHIVE
__all__ = ['<API key>', '<API key>',
'get_ocat_web', 'get_ocat_local']
OCAT_TABLE_PATH = Path(MICA_ARCHIVE) / 'ocat_target_table.h5'
OCAT_TABLE_CACHE = {}
URL_CDA_SERVICES = "https://cda.harvard.edu/srservices"
CDA_SERVICES = {
'prop_abstract': 'propAbstract',
'ocat_summary': 'ocatList',
'ocat_details': 'ocatDetails',
'archive_file_list': 'archiveFileList'}
# <SHA1-like>/pycda/obscat.py#L38
OCAT_UNITS = {
"app_exp": "ks",
"count_rate": "s**-1",
"est_cnt_rate": "s**-1",
"evfil_lo": "keV",
"evfil_ra": "keV",
"exp_time": "ks",
"f_time": "s",
"forder_cnt_rate": "s**-1",
"soe_roll": "degree",
"x_sim": "mm",
"y_off": "arcmin",
"z_off": "arcmin",
"z_sim": "mm",
}
RETURN_TYPE_DOCS = """If ``return_type='auto'`` the return type is determined by the rules:
- If ``obsid`` is provided
AND the obsid corresponds to an integer
AND the returned result has a single row
THEN the return type is ``dict``
ELSE the return tuple is a ``Table``.
If ``return_type='table'`` then always return a ``Table``."""
CDA_PARAM_DOCS = """Additional function args for CDA search parameters::
instrument=ACIS,ACIS-I,ACIS-S,HRC,HRC-I,HRC-S
grating=NONE,LETG,HETG
type=ER,TOO,CAL,GO,GTO,DDT
cycle=00,01,02,03,04, ...
category=SOLAR SYSTEM,
NORMAL GALAXIES,
STARS AND WD,
WD BINARIES AND CV,
BH AND NS BINARIES,
NORMAL GALAXIES
CLUSTERS OF GALAXIES,
ACTIVE GALAXIES AND QUASARS,
GALACTIC DIFFUSE EMISSION AND SURVEYS,
EXTRAGALACTIC DIFFUSE EMISSION AND SURVEYS
jointObservation= HST,XMM,Spitzer,NOAO,NRAO,NuSTAR,Suzaku,Swift,RXTE
status= archived,observed,scheduled, unobserved,untriggered,canceled,deleted
expMode= ACIS TE,ACIS CC,HRC Timing
grid = 'is not null' or 'is null'
Input coordinate specifications::
inputCoordFrame=J2000 (other options: b1950, bxxxx, ec1950, ecxxxx, galactic)
inputCoordEquinox=2000 (4 digit year)
These parameters are single text entries::
target: matches any part of target name
piName: matches any part of PI name
observer: matches any part of observer name
propNum: proposal number
propTitle: matches any part of proposal title
These parameters form a cone search; if you use one you should use them all::
lon
lat
radius (arcmin, default=1.0)
These parameters form a box search; one lon & one lat are required.
Open-ended ranges are allowed. (Such as lonMin=15 with no lonMax.)
::
lonMin
lonMax
latMin
latMax
These parameters are range lists, where the range is indicated by a hyphen (-).
Multiple ranges can be entered separated by commas::
obsid (eg. obsid=100,200-300,600-1000,1800)
seqNum
expTime
appExpTime
countRate
These parameters are date range lists, where the range is
indicated by a hyphen (/). Multiple ranges can be entered separated
by commas. Valid dates are in one of the following formats:
YYYY-MM-DD, YYYY-MM-DD hh:mm, or YYYY-MM-DD hh:mm:ss
::
startDate
releaseDate
These specify how the data is displayed and ordered::
outputCoordFrame=J2000 (other options: b1950, bxxxx, ec1950, ecxxxx, galactic)
outputCoordEquinox=2000 (4 digit year)
outputCoordUnits=decimal (other option: sexagesimal)
sortColumn=ra (other options:
dec,seqNum,instrument,grating,
appExpTime,expTime,
target,piName,observer,status,
startDate,releaseDate,
obsid,propNum,category,type,cycle)
sortOrder=ascending (other option: descending)
maxResults=# (the number of results after which to stop displaying)
Special parameters that change the output table contents are available for
full output (``summary=False``):
- ``acisWindows='true'``: return ACIS windows details for a single obsid
- ``rollReqs='true'``: return roll requirements for a single obsid
- ``timeReqs='true'``: return time requirements for a single obsid
"""
COMMON_PARAM_DOCS = """:param target_name: str, optional
Target name, used in SkyCoord.from_name() to define ``ra`` and ``dec``
if ``resolve_name`` is True, otherwise matches a substring of the
table column ``target_name`` (ignoring spaces).
:param resolve_name: bool, optional
If True, use ``target_name`` to resolve ``ra`` and ``dec``.
:param ra: float, optional
Right Ascension in decimal degrees
:param dec: float, optional
Declination in decimal degrees
:param radius: float, optional
Search radius in arcmin (default=1.0)"""
def html_to_text(html):
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, features='lxml')
text = soup.get_text()
text = re.sub(r'\n+', '\n', text)
return text
def clean_text(text):
out = text.encode('ascii', errors='ignore').decode('ascii')
out = out.replace('\n', ' ').replace('\r', '').strip()
return out
def <API key>(obsid, detector, level, dataset='flight', **params):
params['dataset'] = dataset
params['detector'] = detector
params['level'] = level
params['obsid'] = obsid
text = <API key>('archive_file_list', **params)
dat = Table.read(text.splitlines(), format='ascii.basic', delimiter='\t', guess=False)
# Original Filesize has commas for the thousands like 11,233,456
filesize = [int(x.replace(',', '')) for x in dat['Filesize']]
dat['Filesize'] = filesize
return dat
def <API key>(obsid=None, propnum=None, timeout=60):
"""Get a proposal abstract from the CDA services.
One of ``obsid`` or ``propnum`` must be provided.
:param obsid: int, str
Observation ID
:param propnum: str
Proposal number, including leading zeros e.g. '08900073'
:param timeout: int, float
Timeout in seconds for the request
:returns: dict
Dictionary of proposal abstract
"""
params = {}
if obsid is not None:
params['obsid'] = obsid
if propnum is not None:
params['propNum'] = propnum
if not params:
raise ValueError('must provide obsid or propnum')
html = <API key>('prop_abstract', timeout=timeout, **params)
text = html_to_text(html)
# Return value is a text string with these section header lines. Use them
# to split the text into sections.
delims = ['Proposal Title',
'Proposal Number',
'Principal Investigator',
'Abstract',
'']
out = {}
for delim0, delim1 in zip(delims[:-1], delims[1:]):
name = '_'.join(word.lower() for word in delim0.split())
if match := re.search(rf'{delim0}:(.+){delim1}:', text, re.DOTALL):
out[name] = clean_text(match.group(1))
else:
warnings.warn(f'failed to find {delim0} in result')
return out
def <API key>(params, obsid,
target_name, resolve_name,
ra, dec, radius):
"""Update params dict for CDA Ocat queries from specified keyword args.
"""
if obsid is not None:
params['obsid'] = obsid
if ra is not None:
params['ra'] = ra
if dec is not None:
params['dec'] = dec
if target_name is not None:
if resolve_name:
coord = SkyCoord.from_name(target_name)
params['ra'] = coord.ra.deg
params['dec'] = coord.dec.deg
else:
# SR services API uses "target" to select substrings of target_name
params['target'] = target_name
# For any positional search include the radius
if 'ra' in params and 'dec' in params:
params['radius'] = radius
return params
def get_ocat_web(obsid=None, *, summary=False,
target_name=None, resolve_name=False,
ra=None, dec=None, radius=1.0,
return_type='auto',
timeout=60, **params):
"""
Get the Ocat target table data from Chandra Data Archive web services.
{RETURN_TYPE_DOCS}
{CDA_PARAM_DOCS}
:param obsid: int, str
Observation ID or string with ObsId range or list of ObsIds
:param summary: bool
Return summary data (26 columns) instead of full data (124 columns)
{COMMON_PARAM_DOCS}
:param timeout: int, float
Timeout in seconds for the request (default=60)
:param return_type: str
Return type (default='auto' => Table or dict)
:param **params: dict
Parameters passed to CDA web service
:return: astropy Table or dict of the observation details
"""
# These special params change the returned data and should always be a table
if set(['acisWindows', 'rollReqs', 'timeReqs']) & set(params):
return_type = 'table'
if return_type not in ('auto', 'table'):
raise ValueError(f"invalid return_type {return_type!r}, must be 'auto' or 'table'")
<API key>(params, obsid,
target_name, resolve_name,
ra, dec, radius)
params['format'] = 'text'
# Force RA, Dec in sexagesimal because decimal returns only 3 decimal digits
# which is insufficient.
params['outputCoordUnits'] = 'sexagesimal'
service = 'ocat_summary' if summary else 'ocat_details'
text = <API key>(service, timeout=timeout, **params)
dat = <API key>(text, return_type, params.get('obsid'))
if dat is None:
# Query returned no rows. If a single obsid was specified with return_type
# of 'auto' then we would have expected to return a dict, but instead
# raise a ValueError. Otherwise we return an empty table with the right
# column names.
if return_type == 'auto' and _is_int(params.get('obsid')):
raise ValueError(f"failed to find obsid {params['obsid']}")
else:
dat = get_ocat_web(summary=summary, return_type='table', obsid=8000)[0:0]
# Change RA, Dec to decimal if those columns exist
try:
ra, dec = dat['ra'], dat['dec']
except KeyError:
pass
else:
sc = SkyCoord(ra, dec, unit='hr,deg')
dat['ra'] = sc.ra.deg
dat['dec'] = sc.dec.deg
return dat
get_ocat_web.__doc__ = get_ocat_web.__doc__.format(
RETURN_TYPE_DOCS=RETURN_TYPE_DOCS,
CDA_PARAM_DOCS=CDA_PARAM_DOCS,
COMMON_PARAM_DOCS=COMMON_PARAM_DOCS)
def <API key>(service, timeout=60, **params):
"""
Fetch all observation details from one of the CDA SRService pages
:param service: str
Name of the service ('prop_abstract', 'ocat_summary', 'ocat_details', 'archive_file_list')
:param timeout: int, float
Timeout in seconds for the request
:param **params: dict
Additional parameters to pass to the service
:return: str
Returned text from the service
"""
if service not in CDA_SERVICES:
raise ValueError(f'unknown service {service!r}, must be one of {list(CDA_SERVICES)}')
# Query the service and check for errors
url = f'{URL_CDA_SERVICES}/{CDA_SERVICES[service]}.do'
verbose = params.pop('verbose', False)
resp = requests.get(url, timeout=timeout, params=params)
if verbose:
print(f'GET {resp.url}')
if not resp.ok:
raise RuntimeError(f'got error {resp.status_code} for {resp.url}\n'
f'{html_to_text(resp.text)}')
return resp.text
def <API key>(text, return_type, obsid):
"""Get astropy Table or dict from the quasi-RDB text returned by the CDA services.
:param text: str
Text returned by the CDA services for a format='text' query
:param return_type: str
Return type (default='auto' => Table or dict)
:param obsid: int, str, None
Observation ID if provided
:return: astropy Table, dict, None
Table of the returned data, or dict if just one obsid selected, or None
if the query returned no data.
"""
lines = text.splitlines()
# Convert the type line to standard RDB
# First find the line that begins the column descriptions
for i, line in enumerate(lines):
if not line.startswith('
header_start = i
break
else:
return None
# The line with the lengths and types is next (header_start + 1)
ctypes = lines[header_start + 1].split("\t")
# Munge length descriptions back to standard RDB (from "20" to "20S" etc)
# while leaving the numeric types alone ("20N" stays "20N").
for j, ctype in enumerate(ctypes):
if not ctype.endswith("N"):
ctypes[j] = ctype + "S"
lines[header_start + 1] = "\t".join(ctypes)
dat = Table.read(lines, format='ascii.rdb', guess=False)
# Fix the column names
# Transform summary names to corresponding detail names.
trans = {'obs_id': 'obsid',
'grating': 'grat', 'instrument': 'instr', 'appr_exp': 'app_exp',
'exposure': 'exp_time', 'data_mode': 'datamode', 'exp_mode': 'mode',
'avg_cnt_rate': 'count_rate', 'public_release_date': 'public_avail',
'proposal_num': 'pr_num', 'science_category': 'category',
'alternate_group': 'alt_group', 'appr._triggers': 'alt_trig'}
names = (name.lower() for name in dat.colnames)
names = (name.replace(' (ks)', '') for name in names)
names = (name.replace(' ', '_') for name in names)
names = [trans.get(name, name) for name in names]
dat.rename_columns(dat.colnames, names)
# Apply units to the columns
for name, col in dat.columns.items():
if name in OCAT_UNITS:
col.info.unit = OCAT_UNITS[name]
# Possibly get just the first row as a dict
dat = _get_table_or_dict(return_type, obsid, dat)
return dat
def _is_int(val):
"""Check if a value looks like an integet."""
try:
return int(val) == float(val)
except (ValueError, TypeError):
return False
def _get_table_or_dict(return_type, obsid, dat):
# If obsid is a single integer and there was just one row then return the
# row as a dict.
if return_type not in ('auto', 'table'):
raise ValueError(f"invalid return_type {return_type!r}, must be 'auto' or 'table'")
if return_type == 'auto' and _is_int(obsid):
if len(dat) == 1:
dat = dict(dat[0])
else:
raise ValueError(f"failed to find obsid {obsid}")
return dat
def <API key>():
"""
Command line interface to write a local Ocat HDF5 file.
This overwrites the file from scratch each time.
"""
import argparse
from ska_helpers.retry import retry_call
parser = argparse.ArgumentParser(
description="Update target table")
parser.add_argument("--datafile",
default='ocat_target_table.h5')
opt = parser.parse_args()
retry_call(update_ocat_local, [opt.datafile], {"timeout": 120},
tries=3, delay=1)
def update_ocat_local(datafile, **params):
"""Write HDF5 ``datafile`` with the Ocat "details" data.
:param **params: dict
Parameters to filter ``<API key>`` query
"""
dat = get_ocat_web(**params)
# Encode unicode strings to bytes manually. Fixed in numpy 1.20.
# Eventually we will want just dat.<API key>().
for name, col in dat.columns.items():
if col.info.dtype.kind == 'U':
dat[name] = np.char.encode(col, 'utf-8')
dat.write(datafile, path='data', serialize_meta=True, overwrite=True,
format='hdf5', compression=True)
def get_ocat_local(obsid=None, *,
target_name=None, resolve_name=False,
ra=None, dec=None, radius=1.0,
return_type='auto',
datafile=None, where=None, **params):
where_parts = [] # build up bits of the where clause
if where is not None:
where_parts.append(where)
if datafile is None:
datafile = OCAT_TABLE_PATH
if obsid is not None:
where_parts.append(f"obsid=={obsid}")
if target_name is not None and resolve_name:
coord = SkyCoord.from_name(target_name)
ra = coord.ra.deg
dec = coord.dec.deg
if ra is not None and dec is not None:
d2r = np.pi / 180.0 # Degrees to radians
# Use great-circle distance to find targets within radius. This is
# accurate enough for this application.
where = (f'arccos(sin({ra * d2r})*sin(ra*{d2r}) + '
f'cos({ra * d2r})*cos(ra*{d2r})*cos({dec*d2r}-dec*{d2r}))'
f'< {radius / 60 * d2r}')
where_parts.append(where)
for col_name, value in params.items():
where_parts.append(f'{col_name}=={value!r}')
if where_parts:
dat = _table_read_where(datafile, where_parts)
else:
dat = _table_read_cached(datafile)
# Decode bytes to strings manually. Fixed in numpy 1.20.
# Eventually we will want just dat.<API key>().
for name, col in dat.columns.items():
zero_length = len(dat) == 0
if col.info.dtype.kind == 'S':
dat[name] = col.astype('U') if zero_length else np.char.decode(col, 'utf-8')
# Match target_name as a substring of the table target_name column.
if len(dat) > 0 and target_name is not None and not resolve_name:
target_name = target_name.lower().replace(' ', '')
# Numpy bug: np.char.replace(dat['target_name'], ' ', '') returns float
# array for a zero-length input, so we need the len(dat) > 0 above.
target_names = np.char.lower(np.char.replace(dat['target_name'], ' ', ''))
ok = np.char.find(target_names, target_name) != -1
dat = dat[ok]
# Apply units to the columns
for name, col in dat.columns.items():
if name in OCAT_UNITS:
col.info.unit = OCAT_UNITS[name]
# Possibly get just the first row as a dict
dat = _get_table_or_dict(return_type, obsid, dat)
return dat
get_ocat_local.__doc__ = get_ocat_local.__doc__.format(
RETURN_TYPE_DOCS=RETURN_TYPE_DOCS,
CDA_PARAM_DOCS=CDA_PARAM_DOCS,
COMMON_PARAM_DOCS=COMMON_PARAM_DOCS)
def _table_read_cached(datafile):
"""Read the Ocat target table from a cached local data file.
The cache expires after one hour.
"""
now_time = time.time()
if datafile in OCAT_TABLE_CACHE:
last_time = OCAT_TABLE_CACHE[datafile]['last_time']
if now_time - last_time < 3600:
return OCAT_TABLE_CACHE[datafile]['data']
dat = Table.read(datafile)
OCAT_TABLE_CACHE[datafile] = {'last_time': now_time, 'data': dat}
return dat
def _table_read_where(datafile, where_parts):
"""Read HDF5 ``datafile`` using read_where() and ``where_parts``.
"""
where = '&'.join(f'({where})' for where in where_parts)
with tables.open_file(datafile) as h5:
# PyTables is unhappy with all the column names that cannot be an
# object attribute, so squelch that warning.
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=tables.NaturalNameWarning)
dat = h5.root.data.read_where(where)
dat = Table(dat)
# Manually make MaskedColumn's as needed since we are not using Table.read()
# which handles this. This assumes a correspondence betweeen <name>.mask
# and <name>, but this is always true for the Ocat target table.
masked_names = [name for name in dat.colnames if name.endswith('.mask')]
for masked_name in masked_names:
name = masked_name[:-5]
dat[name] = MaskedColumn(dat[name], mask=dat[masked_name], dtype=dat[name].dtype)
dat.remove_column(masked_name)
return dat |
import torch
from torch.optim.optimizer import Optimizer, required
_available = False
try:
from pcl_embedding_bag import bf16_update
_available = True
except ImportError as e:
#print(e)
pass
def is_available():
return _available
class SplitSGD(Optimizer):
r"""Implements low precision stochastic gradient descent with extra state."""
def __init__(self, params, lr=required, momentum=0, dampening=0,
weight_decay=0, nesterov=False):
if not is_available():
raise ValueError("Module function 'bf16_update' not available for SplitSGD")
if lr is not required and lr < 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
if momentum != 0.0:
raise ValueError("Invalid momentum value: {}".format(momentum))
if weight_decay != 0.0:
raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
defaults = dict(lr=lr, momentum=momentum, dampening=dampening,
weight_decay=weight_decay, nesterov=nesterov)
if nesterov and (momentum <= 0 or dampening != 0):
raise ValueError("Nesterov momentum requires a momentum and zero dampening")
super(SplitSGD, self).__init__(params, defaults)
print("Using SplitSGD")
def __setstate__(self, state):
super(SplitSGD, self).__setstate__(state)
for group in self.param_groups:
group.setdefault('nesterov', False)
def step(self, closure=None):
"""Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
weight_decay = group['weight_decay']
momentum = group['momentum']
dampening = group['dampening']
nesterov = group['nesterov']
for p in group['params']:
if p.grad is None:
continue
d_p = p.grad.data
if p.dtype == torch.bfloat16:
param_state = self.state[p]
if 'low_bits' not in param_state:
buf = param_state['low_bits'] = torch.zeros_like(p.data, dtype=torch.short)
else:
buf = param_state['low_bits']
# if weight_decay != 0:
# d_p = d_p.add(weight_decay, p.data)
# if momentum != 0:
# param_state = self.state[p]
# if 'momentum_buffer' not in param_state:
# buf = param_state['momentum_buffer'] = torch.clone(d_p).detach()
# else:
# buf = param_state['momentum_buffer']
# buf.mul_(momentum).add_(1 - dampening, d_p)
# if nesterov:
# d_p = d_p.add(momentum, buf)
# else:
# d_p = buf
#p.data.add_(-group['lr'], d_p)
if p.dtype == torch.bfloat16:
bf16_update(p.data, buf, d_p, -group['lr'])
else:
p.data.add_(d_p, alpha=-group['lr'])
return loss |
//! stal-rs
//! Set algebra solver for Redis in Rust, based on
//! Description
//! `stal-rs` provide set operations and resolves them in [Redis][redis].
//! Usage
//! `stal-rs` has no dependencies. It produces a vector of Redis operations that
//! have to be run by the user.
//! ```rust
//! extern crate stal;
//! let foobar = stal::Set::Inter(vec![stal::Set::Key(b"foo".to_vec()), stal::Set::Key(b"bar".to_vec())]);
//! let foobar_nobaz = stal::Set::Diff(vec![foobar, stal::Set::Key(b"baz".to_vec())]);
//! let foobar_nobaz_andqux = stal::Set::Union(vec![stal::Set::Key(b"qux".to_vec()), foobar_nobaz]);
//! assert_eq!(
//! stal::Stal::new("SMEMBERS".to_string(), foobar_nobaz_andqux).solve(),
//! vec![
//! vec![b"MULTI".to_vec()],
//! vec![b"SINTERSTORE".to_vec(), b"stal:2".to_vec(), b"foo".to_vec(), b"bar".to_vec()],
//! vec![b"SDIFFSTORE".to_vec(), b"stal:1".to_vec(), b"stal:2".to_vec(), b"baz".to_vec()],
//! vec![b"SUNIONSTORE".to_vec(), b"stal:0".to_vec(), b"qux".to_vec(), b"stal:1".to_vec()],
//! vec![b"SMEMBERS".to_vec(), b"stal:0".to_vec()],
//! vec![b"DEL".to_vec(), b"stal:0".to_vec(), b"stal:1".to_vec(), b"stal:2".to_vec()],
//! vec![b"EXEC".to_vec()],
//! `stal-rs` translates the internal calls to `SUNION`, `SDIFF` and
//! `SINTER` into `SDIFFSTORE`, `SINTERSTORE` and `SUNIONSTORE` to
//! perform the underlying operations, and it takes care of generating
//! and deleting any temporary keys.
//! The outmost command can be any set operation, for example:
//! ```rust
//! extern crate stal;
//! let myset = stal::Set::Key(b"my set".to_vec());
//! stal::Stal::new("SCARD".to_string(), myset).solve();
//! If you want to preview the commands `Stal` will send to generate
//! the results, you can use `Stal.explain`:
//! ```rust
//! extern crate stal;
//! assert_eq!(
//! stal::Stal::new("SMEMBERS".to_string(),
//! stal::Set::Inter(vec![
//! stal::Set::Union(vec![
//! stal::Set::Key(b"foo".to_vec()),
//! stal::Set::Key(b"bar".to_vec()),
//! stal::Set::Key(b"baz".to_vec()),
//! ).explain(),
//! vec![
//! vec![b"SUNIONSTORE".to_vec(), b"stal:1".to_vec(), b"foo".to_vec(), b"bar".to_vec()],
//! vec![b"SINTERSTORE".to_vec(), b"stal:0".to_vec(), b"stal:1".to_vec(), b"baz".to_vec()],
//! vec![b"SMEMBERS".to_vec(), b"stal:0".to_vec()],
//! All commands are wrapped in a `MULTI/EXEC` transaction.
#![crate_name = "stal"]
#![crate_type = "lib"]
A set of values. It can be generated from a Redis key or from a set
operation based on other sets.
#[derive(Debug, Clone)]
pub enum Set {
A key
Key(Vec<u8>),
All the elements in any of the provided sets
Union(Vec<Set>),
All the elements in all the sets
Inter(Vec<Set>),
All the elements in the first set that are not in the other sets
Diff(Vec<Set>),
}
use Set::*;
impl Set {
Gets the commands to get a list of ids for this set
pub fn into_ids(self) -> Stal {
let (op, sets) = match self {
Key(_) => return Stal::from_template(vec![b"SMEMBERS".to_vec(), vec![]], vec![(self, 1)]),
Union(sets) => ("SUNION", sets),
Inter(sets) => ("SINTER", sets),
Diff(sets) => ("SDIFF", sets),
};
let mut command = vec![op.as_bytes().to_vec()];
command.extend(sets.iter().map(|_| vec![]).collect::<Vec<_>>());
let mut setv = vec![];
let mut i = 1;
for set in sets.into_iter() {
setv.push((set, i));
i += 1;
}
Stal::from_template(command, setv)
}
Gets the commands to get a list of ids for this set
pub fn ids(&self) -> Stal {
let (op, sets) = match *self {
Key(_) => return Stal::from_template(vec![b"SMEMBERS".to_vec(), vec![]], vec![(self.clone(), 1)]),
Union(ref sets) => ("SUNION", sets),
Inter(ref sets) => ("SINTER", sets),
Diff(ref sets) => ("SDIFF", sets),
};
let mut command = vec![op.as_bytes().to_vec()];
command.extend(sets.iter().map(|_| vec![]).collect::<Vec<_>>());
let mut setv = vec![];
for i in 0..sets.len() {
setv.push((sets[i].clone(), i + 1));
}
Stal::from_template(command, setv)
}
Maps the operation to its Redis command name.
fn command(&self) -> &'static str {
match *self {
Key(_) => unreachable!(),
Union(_) => "SUNIONSTORE",
Inter(_) => "SINTERSTORE",
Diff(_) => "SDIFFSTORE",
}
}
Appends the operation to `ops` and any temporary id created to `ids`.
Returns the key representing the set.
pub fn convert(&self, ids: &mut Vec<String>, ops: &mut Vec<Vec<Vec<u8>>>) -> Vec<u8> {
let sets = match *self {
Key(ref k) => return k.clone(),
Union(ref sets) => sets,
Inter(ref sets) => sets,
Diff(ref sets) => sets,
};
let mut op = Vec::with_capacity(2 + sets.len());
let id = format!("stal:{}", ids.len());
let r = id.as_bytes().to_vec();
ids.push(id);
op.push(self.command().as_bytes().to_vec());
op.push(r.clone());
op.extend(sets.into_iter().map(|s| s.convert(ids, ops)));
ops.push(op);
r
}
}
An operation to be executed on a set
#[derive(Debug)]
pub struct Stal {
A Redis command
command: Vec<Vec<u8>>,
Set in which execute the operation
sets: Vec<(Set, usize)>,
}
impl Stal {
pub fn new(operation: String, set: Set) -> Self {
Stal {
command: vec![operation.as_bytes().to_vec(), vec![]],
sets: vec![(set, 1)],
}
}
Takes an arbitrary command that uses one or more sets. The `command`
must have placeholders where the set keys should go. Each element
in `sets` specifies the position in the `command`.
pub fn from_template(command: Vec<Vec<u8>>, sets: Vec<(Set, usize)>) -> Self {
Stal {
command: command,
sets: sets,
}
}
fn add_ops(&self, ids: &mut Vec<String>, ops: &mut Vec<Vec<Vec<u8>>>) {
let mut command = self.command.clone();
for args in self.sets.iter() {
command.push(args.0.convert(ids, ops));
command.swap_remove(args.1);
}
ops.push(command);
}
Returns a list of operations to run. For debug only.
pub fn explain(&self) -> Vec<Vec<Vec<u8>>> {
let mut ids = vec![];
let mut ops = vec![];
self.add_ops(&mut ids, &mut ops);
ops
}
Returns a lit of operations, wrapped in a multi/exec.
The last operation is always exec, and the returned `usize` indicates
the return value of the `operation`.
pub fn solve(&self) -> (Vec<Vec<Vec<u8>>>, usize) {
let mut ids = vec![];
let mut ops = vec![vec![b"MULTI".to_vec()]];
self.add_ops(&mut ids, &mut ops);
let pos = ops.len() - 1;
if ids.len() > 0 {
let mut del = vec![b"DEL".to_vec()];
del.extend(ids.into_iter().map(|x| x.as_bytes().to_vec()));
ops.push(del);
}
ops.push(vec![b"EXEC".to_vec()]);
(ops, pos)
}
} |
import os
os.environ.setdefault("<API key>", "settings")
from django.core.wsgi import <API key>
application = <API key>() |
<param name="movie" value="<%= swfPath %>?inline=1">
<param name="quality" value="autohigh">
<param name="swliveconnect" value="true">
<param name="allowScriptAccess" value="always">
<param name="bgcolor" value="#001122">
<param name="allowFullScreen" value="false">
<param name="wmode" value="transparent">
<param name="tabindex" value="1">
<param name=FlashVars value="playbackId=<%= playbackId %>&callback=<%= callbackName %>" />
<embed
name="<%= cid %>"
type="application/x-shockwave-flash"
tabindex="1"
enablecontextmenu="false"
allowScriptAccess="always"
quality="autohigh"
pluginspage="http:
wmode="transparent"
swliveconnect="true"
type="application/x-shockwave-flash"
allowfullscreen="false"
bgcolor="#000000"
FlashVars="playbackId=<%= playbackId %>&callback=<%= callbackName %>"
src="<%= swfPath %>"
width="100%"
height="100%">
</embed> |
import System.Environment (getArgs)
import Data.List.Split (splitOn)
maxran :: Int -> Int -> [Int] -> [Int] -> Int
maxran x _ _ [] = x
maxran x c (y:ys) (z:zs) = maxran (max x d) d (ys ++ [z]) zs
where d = c - y + z
maxrange :: [String] -> Int
maxrange [ns, xs] = maxran (max 0 z) z zs (drop n ys)
where n = read ns
ys = map read (words xs)
zs = take n ys
z = sum zs
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (show . maxrange . splitOn ";") $ lines input |
import sys
import random
from test_base import *
class TestAtomic1(TestBase):
def generate(self):
self.clear_tag()
for iteration in range(10):
for n in range(10000):
tag = random.randint(0,9)
index = random.randint(0,1)
block_offset = random.randint(0,self.<API key>)
taddr = self.get_addr(tag,index,block_offset)
op = random.randint(0,10)
if op == 0:
self.send_sw(taddr)
elif op == 1:
self.send_lw(taddr)
elif op == 2:
self.send_amoswap_w(taddr)
elif op == 3:
self.send_amoadd_w(taddr)
elif op == 4:
self.send_amoxor_w(taddr)
elif op == 5:
self.send_amoand_w(taddr)
elif op == 6:
self.send_amoor_w(taddr)
elif op == 7:
self.send_amomin_w(taddr)
elif op == 8:
self.send_amomax_w(taddr)
elif op == 9:
self.send_amominu_w(taddr)
elif op == 10:
self.send_amomaxu_w(taddr)
# done
self.tg.done()
# main()
if __name__ == "__main__":
t = TestAtomic1()
t.generate() |
/**
* @file LiquidTransport.cpp
* Mixture-averaged transport properties for ideal gas mixtures.
*/
#include "cantera/transport/LiquidTransport.h"
#include "cantera/base/stringUtils.h"
using namespace std;
namespace Cantera
{
LiquidTransport::LiquidTransport(thermo_t* thermo, int ndim) :
Transport(thermo, ndim),
m_nsp2(0),
m_viscMixModel(0),
m_ionCondMixModel(0),
m_lambdaMixModel(0),
m_diffMixModel(0),
m_radiusMixModel(0),
m_iStateMF(-1),
concTot_(0.0),
concTot_tran_(0.0),
dens_(0.0),
m_temp(-1.0),
m_press(-1.0),
m_lambda(-1.0),
m_viscmix(-1.0),
m_ionCondmix(-1.0),
m_visc_mix_ok(false),
m_visc_temp_ok(false),
m_visc_conc_ok(false),
m_ionCond_mix_ok(false),
m_ionCond_temp_ok(false),
m_ionCond_conc_ok(false),
m_mobRat_mix_ok(false),
m_mobRat_temp_ok(false),
m_mobRat_conc_ok(false),
m_selfDiff_mix_ok(false),
m_selfDiff_temp_ok(false),
m_selfDiff_conc_ok(false),
m_radi_mix_ok(false),
m_radi_temp_ok(false),
m_radi_conc_ok(false),
m_diff_mix_ok(false),
m_diff_temp_ok(false),
m_lambda_temp_ok(false),
m_lambda_mix_ok(false),
m_mode(-1000),
m_debug(false)
{
}
LiquidTransport::LiquidTransport(const LiquidTransport& right) :
Transport(right.m_thermo, right.m_nDim),
m_nsp2(0),
m_viscMixModel(0),
m_ionCondMixModel(0),
m_lambdaMixModel(0),
m_diffMixModel(0),
m_radiusMixModel(0),
m_iStateMF(-1),
concTot_(0.0),
concTot_tran_(0.0),
dens_(0.0),
m_temp(-1.0),
m_press(-1.0),
m_lambda(-1.0),
m_viscmix(-1.0),
m_ionCondmix(-1.0),
m_visc_mix_ok(false),
m_visc_temp_ok(false),
m_visc_conc_ok(false),
m_ionCond_mix_ok(false),
m_ionCond_temp_ok(false),
m_ionCond_conc_ok(false),
m_mobRat_mix_ok(false),
m_mobRat_temp_ok(false),
m_mobRat_conc_ok(false),
m_selfDiff_mix_ok(false),
m_selfDiff_temp_ok(false),
m_selfDiff_conc_ok(false),
m_radi_mix_ok(false),
m_radi_temp_ok(false),
m_radi_conc_ok(false),
m_diff_mix_ok(false),
m_diff_temp_ok(false),
m_lambda_temp_ok(false),
m_lambda_mix_ok(false),
m_mode(-1000),
m_debug(false)
{
/*
* Use the assignment operator to do the brunt
* of the work for the copy constructor.
*/
*this = right;
}
LiquidTransport& LiquidTransport::operator=(const LiquidTransport& right)
{
if (&right == this) {
return *this;
}
Transport::operator=(right);
m_nsp2 = right.m_nsp2;
m_mw = right.m_mw;
m_viscTempDep_Ns = right.m_viscTempDep_Ns;
m_ionCondTempDep_Ns = right.m_ionCondTempDep_Ns;
m_mobRatTempDep_Ns = right.m_mobRatTempDep_Ns;
<API key> = right.<API key>;
m_lambdaTempDep_Ns = right.m_lambdaTempDep_Ns;
m_diffTempDep_Ns = right.m_diffTempDep_Ns;
m_radiusTempDep_Ns = right.m_radiusTempDep_Ns;
<API key> = right.<API key>;
m_Grad_X = right.m_Grad_X;
m_Grad_T = right.m_Grad_T;
m_Grad_V = right.m_Grad_V;
m_Grad_mu = right.m_Grad_mu;
m_bdiff = right.m_bdiff;
m_viscSpecies = right.m_viscSpecies;
m_ionCondSpecies = right.m_ionCondSpecies;
m_mobRatSpecies = right.m_mobRatSpecies;
m_selfDiffSpecies = right.m_selfDiffSpecies;
<API key> = right.<API key>;
m_lambdaSpecies = right.m_lambdaSpecies;
m_viscMixModel = right.m_viscMixModel;
m_ionCondMixModel = right.m_ionCondMixModel;
m_mobRatMixModel = right.m_mobRatMixModel;
m_selfDiffMixModel = right.m_selfDiffMixModel;
m_lambdaMixModel = right.m_lambdaMixModel;
m_diffMixModel = right.m_diffMixModel;
m_iStateMF = -1;
m_massfracs = right.m_massfracs;
m_massfracs_tran = right.m_massfracs_tran;
m_molefracs = right.m_molefracs;
m_molefracs_tran = right.m_molefracs_tran;
m_concentrations = right.m_concentrations;
m_actCoeff = right.m_actCoeff;
m_Grad_lnAC = right.m_Grad_lnAC;
m_chargeSpecies = right.m_chargeSpecies;
m_B = right.m_B;
m_A = right.m_A;
m_temp = right.m_temp;
m_press = right.m_press;
m_flux = right.m_flux;
m_Vdiff = right.m_Vdiff;
m_lambda = right.m_lambda;
m_viscmix = right.m_viscmix;
m_ionCondmix = right.m_ionCondmix;
m_mobRatMix = right.m_mobRatMix;
m_selfDiffMix = right.m_selfDiffMix;
m_spwork = right.m_spwork;
m_visc_mix_ok = false;
m_visc_temp_ok = false;
m_visc_conc_ok = false;
m_ionCond_mix_ok = false;
m_ionCond_temp_ok = false;
m_ionCond_conc_ok = false;
m_mobRat_mix_ok = false;
m_mobRat_temp_ok = false;
m_mobRat_conc_ok = false;
m_selfDiff_mix_ok = false;
m_selfDiff_temp_ok = false;
m_selfDiff_conc_ok = false;
m_radi_mix_ok = false;
m_radi_temp_ok = false;
m_radi_conc_ok = false;
m_diff_mix_ok = false;
m_diff_temp_ok = false;
m_lambda_temp_ok = false;
m_lambda_mix_ok = false;
m_mode = right.m_mode;
m_debug = right.m_debug;
m_nDim = right.m_nDim;
return *this;
}
Transport* LiquidTransport::<API key>() const
{
return new LiquidTransport(*this);
}
LiquidTransport::~LiquidTransport()
{
//These are constructed in TransportFactory::newLTP
for (size_t k = 0; k < m_nsp; k++) {
delete m_viscTempDep_Ns[k];
delete m_ionCondTempDep_Ns[k];
for (size_t j = 0; j < m_nsp; j++) {
delete <API key>[j][k];
}
for (size_t j=0; j < m_nsp2; j++) {
delete m_mobRatTempDep_Ns[j][k];
}
delete m_lambdaTempDep_Ns[k];
delete m_radiusTempDep_Ns[k];
delete m_diffTempDep_Ns[k];
//These are constructed in TransportFactory::newLTI
delete m_selfDiffMixModel[k];
}
for (size_t k = 0; k < m_nsp2; k++) {
delete m_mobRatMixModel[k];
}
delete m_viscMixModel;
delete m_ionCondMixModel;
delete m_lambdaMixModel;
delete m_diffMixModel;
}
bool LiquidTransport::initLiquid(<API key>& tr)
{
// Transfer quantitities from the database to the Transport object
m_thermo = tr.thermo;
m_velocityBasis = tr.velocityBasis_;
m_nsp = m_thermo->nSpecies();
m_nsp2 = m_nsp*m_nsp;
// Resize the local storage according to the number of species
m_mw.resize(m_nsp, 0.0);
m_viscSpecies.resize(m_nsp, 0.0);
m_viscTempDep_Ns.resize(m_nsp, 0);
m_ionCondSpecies.resize(m_nsp, 0.0);
m_ionCondTempDep_Ns.resize(m_nsp, 0);
m_mobRatTempDep_Ns.resize(m_nsp2);
m_mobRatMixModel.resize(m_nsp2);
m_mobRatSpecies.resize(m_nsp2, m_nsp, 0.0);
m_mobRatMix.resize(m_nsp2,0.0);
<API key>.resize(m_nsp);
m_selfDiffMixModel.resize(m_nsp);
m_selfDiffSpecies.resize(m_nsp, m_nsp, 0.0);
m_selfDiffMix.resize(m_nsp,0.0);
for (size_t k = 0; k < m_nsp; k++) {
<API key>[k].resize(m_nsp, 0);
}
for (size_t k = 0; k < m_nsp2; k++) {
m_mobRatTempDep_Ns[k].resize(m_nsp, 0);
}
m_lambdaSpecies.resize(m_nsp, 0.0);
m_lambdaTempDep_Ns.resize(m_nsp, 0);
<API key>.resize(m_nsp, 0.0);
m_radiusTempDep_Ns.resize(m_nsp, 0);
// Make a local copy of the molecular weights
m_mw = m_thermo->molecularWeights();
// First populate mixing rules and indices (NOTE, we transfer pointers of
// malloced quantities. We zero out pointers so that we only have one copy
// of the malloced quantity)
for (size_t k = 0; k < m_nsp; k++) {
m_selfDiffMixModel[k] = tr.selfDiffusion[k];
tr.selfDiffusion[k] = 0;
}
for (size_t k = 0; k < m_nsp2; k++) {
m_mobRatMixModel[k] = tr.mobilityRatio[k];
tr.mobilityRatio[k] = 0;
}
//for each species, assign viscosity model and coefficients
for (size_t k = 0; k < m_nsp; k++) {
LiquidTransportData& ltd = tr.LTData[k];
m_viscTempDep_Ns[k] = ltd.viscosity;
ltd.viscosity = 0;
m_ionCondTempDep_Ns[k] = ltd.ionConductivity;
ltd.ionConductivity = 0;
for (size_t j = 0; j < m_nsp2; j++) {
m_mobRatTempDep_Ns[j][k] = ltd.mobilityRatio[j];
ltd.mobilityRatio[j] = 0;
}
for (size_t j = 0; j < m_nsp; j++) {
<API key>[j][k] = ltd.selfDiffusion[j];
ltd.selfDiffusion[j] = 0;
}
m_lambdaTempDep_Ns[k] = ltd.thermalCond;
ltd.thermalCond = 0;
m_radiusTempDep_Ns[k] = ltd.hydroRadius;
ltd.hydroRadius = 0;
}
// Get the input Species Diffusivities. Note that species diffusivities are
// not what is needed. Rather the Stefan Boltzmann interaction parameters
// are needed for the current model. This section may, therefore, be
// extraneous.
m_diffTempDep_Ns.resize(m_nsp, 0);
//for each species, assign viscosity model and coefficients
for (size_t k = 0; k < m_nsp; k++) {
LiquidTransportData& ltd = tr.LTData[k];
if (ltd.speciesDiffusivity != 0) {
cout << "Warning: diffusion coefficient data for "
<< m_thermo->speciesName(k)
<< endl
<< "in the input file is not used for LiquidTransport model."
<< endl
<< "LiquidTransport model uses Stefan-Maxwell interaction "
<< endl
<< "parameters defined in the <transport> input block."
<< endl;
}
}
// Here we get interaction parameters from <API key> that were
// filled in TransportFactory::<API key>
// Interaction models are provided here for viscosity, thermal conductivity,
// species diffusivity and hydrodynamics radius (perhaps not needed in the
// present class).
m_viscMixModel = tr.viscosity;
tr.viscosity = 0;
m_ionCondMixModel = tr.ionConductivity;
tr.ionConductivity = 0;
m_lambdaMixModel = tr.thermalCond;
tr.thermalCond = 0;
m_diffMixModel = tr.speciesDiffusivity;
tr.speciesDiffusivity = 0;
if (! m_diffMixModel) {
throw CanteraError("LiquidTransport::initLiquid()",
"A speciesDiffusivity model is required in the transport block for the phase, but none was provided");
}
m_bdiff.resize(m_nsp,m_nsp, 0.0);
// Don't really need to update this here. It is updated in updateDiff_T()
m_diffMixModel->getMatrixTransProp(m_bdiff);
m_mode = tr.mode_;
m_massfracs.resize(m_nsp, 0.0);
m_massfracs_tran.resize(m_nsp, 0.0);
m_molefracs.resize(m_nsp, 0.0);
m_molefracs_tran.resize(m_nsp, 0.0);
m_concentrations.resize(m_nsp, 0.0);
m_actCoeff.resize(m_nsp, 0.0);
m_chargeSpecies.resize(m_nsp, 0.0);
for (size_t i = 0; i < m_nsp; i++) {
m_chargeSpecies[i] = m_thermo->charge(i);
}
m_volume_spec.resize(m_nsp, 0.0);
m_Grad_lnAC.resize(m_nDim * m_nsp, 0.0);
m_spwork.resize(m_nsp, 0.0);
// resize the internal gradient variables
m_Grad_X.resize(m_nDim * m_nsp, 0.0);
m_Grad_T.resize(m_nDim, 0.0);
m_Grad_V.resize(m_nDim, 0.0);
m_Grad_mu.resize(m_nDim * m_nsp, 0.0);
m_flux.resize(m_nsp, m_nDim, 0.0);
m_Vdiff.resize(m_nsp, m_nDim, 0.0);
// set all flags to false
m_visc_mix_ok = false;
m_visc_temp_ok = false;
m_visc_conc_ok = false;
m_ionCond_mix_ok = false;
m_ionCond_temp_ok = false;
m_ionCond_conc_ok = false;
m_mobRat_mix_ok = false;
m_mobRat_temp_ok = false;
m_mobRat_conc_ok = false;
m_selfDiff_mix_ok = false;
m_selfDiff_temp_ok = false;
m_selfDiff_conc_ok = false;
m_radi_temp_ok = false;
m_radi_conc_ok = false;
m_lambda_temp_ok = false;
m_lambda_mix_ok = false;
m_diff_temp_ok = false;
m_diff_mix_ok = false;
return true;
}
doublereal LiquidTransport::viscosity()
{
update_T();
update_C();
if (m_visc_mix_ok) {
return m_viscmix;
}
/// <API key> method
m_viscmix = m_viscMixModel->getMixTransProp(m_viscTempDep_Ns);
return m_viscmix;
}
void LiquidTransport::<API key>(doublereal* const visc)
{
update_T();
if (!m_visc_temp_ok) {
updateViscosity_T();
}
copy(m_viscSpecies.begin(), m_viscSpecies.end(), visc);
}
doublereal LiquidTransport::ionConductivity()
{
update_T();
update_C();
if (m_ionCond_mix_ok) {
return m_ionCondmix;
}
/// <API key> method
m_ionCondmix = m_ionCondMixModel->getMixTransProp(m_ionCondTempDep_Ns);
return m_ionCondmix;
}
void LiquidTransport::<API key>(doublereal* ionCond)
{
update_T();
if (!m_ionCond_temp_ok) {
<API key>();
}
copy(m_ionCondSpecies.begin(), m_ionCondSpecies.end(), ionCond);
}
void LiquidTransport::mobilityRatio(doublereal* mobRat)
{
update_T();
update_C();
// <API key> method
if (!m_mobRat_mix_ok) {
for (size_t k = 0; k < m_nsp2; k++) {
if (m_mobRatMixModel[k]) {
m_mobRatMix[k] = m_mobRatMixModel[k]->getMixTransProp(m_mobRatTempDep_Ns[k]);
if (m_mobRatMix[k] > 0.0) {
m_mobRatMix[k / m_nsp + m_nsp * (k % m_nsp)] = 1.0 / m_mobRatMix[k]; // Also must be off diagonal: k%(1+n)!=0, but then m_mobRatMixModel[k] shouldn't be initialized anyway
}
}
}
}
for (size_t k = 0; k < m_nsp2; k++) {
mobRat[k] = m_mobRatMix[k];
}
}
void LiquidTransport::<API key>(doublereal** mobRat)
{
update_T();
if (!m_mobRat_temp_ok) {
<API key>();
}
for (size_t k = 0; k < m_nsp2; k++) {
for (size_t j = 0; j < m_nsp; j++) {
mobRat[k][j] = m_mobRatSpecies(k,j);
}
}
}
void LiquidTransport::selfDiffusion(doublereal* const selfDiff)
{
update_T();
update_C();
if (!m_selfDiff_mix_ok) {
for (size_t k = 0; k < m_nsp; k++) {
m_selfDiffMix[k] = m_selfDiffMixModel[k]->getMixTransProp(<API key>[k]);
}
}
for (size_t k = 0; k < m_nsp; k++) {
selfDiff[k] = m_selfDiffMix[k];
}
}
void LiquidTransport::<API key>(doublereal** selfDiff)
{
update_T();
if (!m_selfDiff_temp_ok) {
<API key>();
}
for (size_t k=0; k<m_nsp; k++) {
for (size_t j=0; j < m_nsp; j++) {
selfDiff[k][j] = m_selfDiffSpecies(k,j);
}
}
}
void LiquidTransport::<API key>(doublereal* const radius)
{
update_T();
if (!m_radi_temp_ok) {
<API key>();
}
copy(<API key>.begin(), <API key>.end(), radius);
}
doublereal LiquidTransport::thermalConductivity()
{
update_T();
update_C();
if (!m_lambda_mix_ok) {
m_lambda = m_lambdaMixModel->getMixTransProp(m_lambdaTempDep_Ns);
m_cond_mix_ok = true;
}
return m_lambda;
}
void LiquidTransport::<API key>(doublereal* const dt)
{
for (size_t k = 0; k < m_nsp; k++) {
dt[k] = 0.0;
}
}
void LiquidTransport::getBinaryDiffCoeffs(size_t ld, doublereal* d)
{
if (ld != m_nsp) {
throw CanteraError("LiquidTransport::getBinaryDiffCoeffs",
"First argument does not correspond to number of species in model.\nDiff Coeff matrix may be misdimensioned");
}
update_T();
// if necessary, evaluate the binary diffusion coefficients
// from the polynomial fits
if (!m_diff_temp_ok) {
updateDiff_T();
}
for (size_t i = 0; i < m_nsp; i++) {
for (size_t j = 0; j < m_nsp; j++) {
d[ld*j + i] = 1.0 / m_bdiff(i,j);
}
}
}
void LiquidTransport::getMobilities(doublereal* const mobil)
{
getMixDiffCoeffs(m_spwork.data());
doublereal c1 = ElectronCharge / (Boltzmann * m_temp);
for (size_t k = 0; k < m_nsp; k++) {
mobil[k] = c1 * m_spwork[k];
}
}
void LiquidTransport::getFluidMobilities(doublereal* const mobil_f)
{
getMixDiffCoeffs(m_spwork.data());
doublereal c1 = 1.0 / (GasConstant * m_temp);
for (size_t k = 0; k < m_nsp; k++) {
mobil_f[k] = c1 * m_spwork[k];
}
}
void LiquidTransport::set_Grad_T(const doublereal* grad_T)
{
for (size_t a = 0; a < m_nDim; a++) {
m_Grad_T[a] = grad_T[a];
}
}
void LiquidTransport::set_Grad_V(const doublereal* grad_V)
{
for (size_t a = 0; a < m_nDim; a++) {
m_Grad_V[a] = grad_V[a];
}
}
void LiquidTransport::set_Grad_X(const doublereal* grad_X)
{
size_t itop = m_nDim * m_nsp;
for (size_t i = 0; i < itop; i++) {
m_Grad_X[i] = grad_X[i];
}
}
doublereal LiquidTransport::getElectricConduct()
{
vector_fp gradT(m_nDim,0.0);
vector_fp gradX(m_nDim * m_nsp);
vector_fp gradV(m_nDim);
for (size_t i = 0; i < m_nDim; i++) {
for (size_t k = 0; k < m_nsp; k++) {
gradX[ i*m_nDim + k] = 0.0;
}
gradV[i] = 1.0;
}
set_Grad_T(&gradT[0]);
set_Grad_X(&gradX[0]);
set_Grad_V(&gradV[0]);
vector_fp fluxes(m_nsp * m_nDim);
doublereal current;
getSpeciesFluxesExt(m_nDim, &fluxes[0]);
//sum over species charges, fluxes, Faraday to get current
// Since we want the scalar conductivity, we need only consider one-dim
for (size_t i = 0; i < 1; i++) {
current = 0.0;
for (size_t k = 0; k < m_nsp; k++) {
current += m_chargeSpecies[k] * Faraday * fluxes[k] / m_mw[k];
}
//divide by unit potential gradient
current /= - gradV[i];
}
return current;
}
void LiquidTransport::getElectricCurrent(int ndim,
const doublereal* grad_T,
int ldx,
const doublereal* grad_X,
int ldf,
const doublereal* grad_V,
doublereal* current)
{
set_Grad_T(grad_T);
set_Grad_X(grad_X);
set_Grad_V(grad_V);
vector_fp fluxes(m_nsp * m_nDim);
getSpeciesFluxesExt(ldf, &fluxes[0]);
//sum over species charges, fluxes, Faraday to get current
for (size_t i = 0; i < m_nDim; i++) {
current[i] = 0.0;
for (size_t k = 0; k < m_nsp; k++) {
current[i] += m_chargeSpecies[k] * Faraday * fluxes[k] / m_mw[k];
}
//divide by unit potential gradient
}
}
void LiquidTransport::getSpeciesVdiff(size_t ndim,
const doublereal* grad_T,
int ldx, const doublereal* grad_X,
int ldf, doublereal* Vdiff)
{
set_Grad_T(grad_T);
set_Grad_X(grad_X);
getSpeciesVdiffExt(ldf, Vdiff);
}
void LiquidTransport::getSpeciesVdiffES(size_t ndim,
const doublereal* grad_T,
int ldx,
const doublereal* grad_X,
int ldf,
const doublereal* grad_V,
doublereal* Vdiff)
{
set_Grad_T(grad_T);
set_Grad_X(grad_X);
set_Grad_V(grad_V);
getSpeciesVdiffExt(ldf, Vdiff);
}
void LiquidTransport::getSpeciesFluxes(size_t ndim,
const doublereal* const grad_T,
size_t ldx, const doublereal* const grad_X,
size_t ldf, doublereal* const fluxes)
{
set_Grad_T(grad_T);
set_Grad_X(grad_X);
getSpeciesFluxesExt(ldf, fluxes);
}
void LiquidTransport::getSpeciesFluxesES(size_t ndim,
const doublereal* grad_T,
size_t ldx,
const doublereal* grad_X,
size_t ldf,
const doublereal* grad_V,
doublereal* fluxes)
{
set_Grad_T(grad_T);
set_Grad_X(grad_X);
set_Grad_V(grad_V);
getSpeciesFluxesExt(ldf, fluxes);
}
void LiquidTransport::getSpeciesVdiffExt(size_t ldf, doublereal* Vdiff)
{
<API key>();
for (size_t n = 0; n < m_nDim; n++) {
for (size_t k = 0; k < m_nsp; k++) {
Vdiff[n*ldf + k] = m_Vdiff(k,n);
}
}
}
void LiquidTransport::getSpeciesFluxesExt(size_t ldf, doublereal* fluxes)
{
<API key>();
for (size_t n = 0; n < m_nDim; n++) {
for (size_t k = 0; k < m_nsp; k++) {
fluxes[n*ldf + k] = m_flux(k,n);
}
}
}
void LiquidTransport::getMixDiffCoeffs(doublereal* const d)
{
<API key>();
for (size_t n = 0; n < m_nDim; n++) {
for (size_t k = 0; k < m_nsp; k++) {
if (m_Grad_X[n*m_nsp + k] != 0.0) {
d[n*m_nsp + k] = - m_Vdiff(k,n) * m_molefracs[k]
/ m_Grad_X[n*m_nsp + k];
} else {
//avoid divide by zero with nonsensical response
d[n*m_nsp + k] = - 1.0;
}
}
}
}
bool LiquidTransport::update_T()
{
// First make a decision about whether we need to recalculate
doublereal t = m_thermo->temperature();
if (t == m_temp) {
return false;
}
// Next do a reality check on temperature value
if (t < 0.0) {
throw CanteraError("LiquidTransport::update_T()",
"negative temperature {}", t);
}
// Compute various direct functions of temperature
m_temp = t;
// temperature has changed so temp flags are flipped
m_visc_temp_ok = false;
m_ionCond_temp_ok = false;
m_mobRat_temp_ok = false;
m_selfDiff_temp_ok = false;
m_radi_temp_ok = false;
m_diff_temp_ok = false;
m_lambda_temp_ok = false;
// temperature has changed, so polynomial temperature
// interpolations will need to be reevaluated.
m_visc_conc_ok = false;
m_ionCond_conc_ok = false;
m_mobRat_conc_ok = false;
m_selfDiff_conc_ok = false;
// Mixture stuff needs to be evaluated
m_visc_mix_ok = false;
m_ionCond_mix_ok = false;
m_mobRat_mix_ok = false;
m_selfDiff_mix_ok = false;
m_diff_mix_ok = false;
m_lambda_mix_ok = false; //(don't need it because a lower lvl flag is set
return true;
}
bool LiquidTransport::update_C()
{
// If the pressure has changed then the concentrations have changed.
doublereal pres = m_thermo->pressure();
bool qReturn = true;
if (pres != m_press) {
qReturn = false;
m_press = pres;
}
int iStateNew = m_thermo->stateMFNumber();
if (iStateNew != m_iStateMF) {
qReturn = false;
m_thermo->getMassFractions(m_massfracs.data());
m_thermo->getMoleFractions(m_molefracs.data());
m_thermo->getConcentrations(m_concentrations.data());
concTot_ = 0.0;
concTot_tran_ = 0.0;
for (size_t k = 0; k < m_nsp; k++) {
m_molefracs[k] = std::max(0.0, m_molefracs[k]);
m_molefracs_tran[k] = std::max(Tiny, m_molefracs[k]);
m_massfracs_tran[k] = std::max(Tiny, m_massfracs[k]);
concTot_tran_ += m_molefracs_tran[k];
concTot_ += m_concentrations[k];
}
dens_ = m_thermo->density();
<API key> = m_thermo->meanMolecularWeight();
concTot_tran_ *= concTot_;
}
if (qReturn) {
return false;
}
// signal that <API key> quantities will need to be recomputed
// before use, and update the local mole fractions.
m_visc_conc_ok = false;
m_ionCond_conc_ok = false;
m_mobRat_conc_ok = false;
m_selfDiff_conc_ok = false;
// Mixture stuff needs to be evaluated
m_visc_mix_ok = false;
m_ionCond_mix_ok = false;
m_mobRat_mix_ok = false;
m_selfDiff_mix_ok = false;
m_diff_mix_ok = false;
m_lambda_mix_ok = false;
return true;
}
void LiquidTransport::updateCond_T()
{
for (size_t k = 0; k < m_nsp; k++) {
m_lambdaSpecies[k] = m_lambdaTempDep_Ns[k]->getSpeciesTransProp();
}
m_lambda_temp_ok = true;
m_lambda_mix_ok = false;
}
void LiquidTransport::updateDiff_T()
{
m_diffMixModel->getMatrixTransProp(m_bdiff);
m_diff_temp_ok = true;
m_diff_mix_ok = false;
}
void LiquidTransport::updateViscosities_C()
{
m_visc_conc_ok = true;
}
void LiquidTransport::updateViscosity_T()
{
for (size_t k = 0; k < m_nsp; k++) {
m_viscSpecies[k] = m_viscTempDep_Ns[k]->getSpeciesTransProp();
}
m_visc_temp_ok = true;
m_visc_mix_ok = false;
}
void LiquidTransport::<API key>()
{
m_ionCond_conc_ok = true;
}
void LiquidTransport::<API key>()
{
for (size_t k = 0; k < m_nsp; k++) {
m_ionCondSpecies[k] = m_ionCondTempDep_Ns[k]->getSpeciesTransProp();
}
m_ionCond_temp_ok = true;
m_ionCond_mix_ok = false;
}
void LiquidTransport::<API key>()
{
m_mobRat_conc_ok = true;
}
void LiquidTransport::<API key>()
{
for (size_t k = 0; k < m_nsp2; k++) {
for (size_t j = 0; j < m_nsp; j++) {
m_mobRatSpecies(k,j) = m_mobRatTempDep_Ns[k][j]->getSpeciesTransProp();
}
}
m_mobRat_temp_ok = true;
m_mobRat_mix_ok = false;
}
void LiquidTransport::<API key>()
{
m_selfDiff_conc_ok = true;
}
void LiquidTransport::<API key>()
{
for (size_t k = 0; k < m_nsp2; k++) {
for (size_t j = 0; j < m_nsp; j++) {
m_selfDiffSpecies(k,j) = <API key>[k][j]->getSpeciesTransProp();
}
}
m_selfDiff_temp_ok = true;
m_selfDiff_mix_ok = false;
}
void LiquidTransport::<API key>()
{
m_radi_conc_ok = true;
}
void LiquidTransport::<API key>()
{
for (size_t k = 0; k < m_nsp; k++) {
<API key>[k] = m_radiusTempDep_Ns[k]->getSpeciesTransProp();
}
m_radi_temp_ok = true;
m_radi_mix_ok = false;
}
void LiquidTransport::update_Grad_lnAC()
{
doublereal grad_T;
for (size_t k = 0; k < m_nDim; k++) {
grad_T = m_Grad_T[k];
size_t start = m_nsp*k;
m_thermo->getdlnActCoeffds(grad_T, &m_Grad_X[start], &m_Grad_lnAC[start]);
for (size_t i = 0; i < m_nsp; i++) {
if (m_molefracs[i] < 1.e-15) {
m_Grad_lnAC[start+i] = 0;
} else {
m_Grad_lnAC[start+i] += m_Grad_X[start+i]/m_molefracs[i];
}
}
}
return;
}
void LiquidTransport::<API key>()
{
doublereal tmp;
m_B.resize(m_nsp, m_nDim, 0.0);
m_A.resize(m_nsp, m_nsp, 0.0);
//! grab a local copy of the molecular weights
const vector_fp& M = m_thermo->molecularWeights();
//! grad a local copy of the ion molar volume (inverse total ion concentration)
const doublereal vol = m_thermo->molarVolume();
//! Update the temperature, concentrations and diffusion coefficients in the
//! mixture.
update_T();
update_C();
if (!m_diff_temp_ok) {
updateDiff_T();
}
double T = m_thermo->temperature();
update_Grad_lnAC();
m_thermo-><API key>(m_actCoeff.data());
/*
* Calculate the electrochemical potential gradient. This is the
* driving force for relative diffusional transport.
*
* Here we calculate
*
* X_i * (grad (mu_i) + S_i grad T - M_i / dens * grad P
*
* This is Eqn. 13-1 p. 318 Newman. The original equation is from
* Hershfeld, Curtis, and Bird.
*
* S_i is the partial molar entropy of species i. This term will cancel
* out a lot of the grad T terms in grad (mu_i), therefore simplifying
* the expression.
*
* Ok I think there may be many ways to do this. One way is to do it via basis
* functions, at the nodes, as a function of the variables in the problem.
*
* For calculation of molality based thermo systems, we current get
* the molar based values. This may change.
*
* Note, we have broken the symmetry of the matrix here, due to
* considerations involving species concentrations going to zero.
*/
for (size_t a = 0; a < m_nDim; a++) {
for (size_t i = 0; i < m_nsp; i++) {
m_Grad_mu[a*m_nsp + i] =
m_chargeSpecies[i] * Faraday * m_Grad_V[a]
+ GasConstant * T * m_Grad_lnAC[a*m_nsp+i];
}
}
if (m_thermo->activityConvention() == <API key>) {
int iSolvent = 0;
double mwSolvent = m_thermo->molecularWeight(iSolvent);
double mnaught = mwSolvent/ 1000.;
double lnmnaught = log(mnaught);
for (size_t a = 0; a < m_nDim; a++) {
for (size_t i = 1; i < m_nsp; i++) {
m_Grad_mu[a*m_nsp + i] -=
m_molefracs[i] * GasConstant * m_Grad_T[a] * lnmnaught;
}
}
}
// Just for Note, m_A(i,j) refers to the ith row and jth column.
// They are still fortran ordered, so that i varies fastest.
double condSum1;
const doublereal invRT = 1.0 / (GasConstant * T);
switch (m_nDim) {
case 1: // 1-D approximation
m_B(0,0) = 0.0;
// equation for the reference velocity
for (size_t j = 0; j < m_nsp; j++) {
if (m_velocityBasis == VB_MOLEAVG) {
m_A(0,j) = m_molefracs_tran[j];
} else if (m_velocityBasis == VB_MASSAVG) {
m_A(0,j) = m_massfracs_tran[j];
} else if ((m_velocityBasis >= 0)
&& (m_velocityBasis < static_cast<int>(m_nsp))) {
// use species number m_velocityBasis as reference velocity
if (m_velocityBasis == static_cast<int>(j)) {
m_A(0,j) = 1.0;
} else {
m_A(0,j) = 0.0;
}
} else {
throw CanteraError("LiquidTransport::<API key>",
"Unknown reference velocity provided.");
}
}
for (size_t i = 1; i < m_nsp; i++) {
m_B(i,0) = m_Grad_mu[i] * invRT;
m_A(i,i) = 0.0;
for (size_t j = 0; j < m_nsp; j++) {
if (j != i) {
tmp = m_molefracs_tran[j] * m_bdiff(i,j);
m_A(i,i) -= tmp;
m_A(i,j) = tmp;
}
}
}
// invert and solve the system Ax = b. Answer is in m_B
solve(m_A, m_B);
condSum1 = 0;
for (size_t i = 0; i < m_nsp; i++) {
condSum1 -= Faraday*m_chargeSpecies[i]*m_B(i,0)*m_molefracs_tran[i]/vol;
}
break;
case 2: // 2-D approximation
m_B(0,0) = 0.0;
m_B(0,1) = 0.0;
//equation for the reference velocity
for (size_t j = 0; j < m_nsp; j++) {
if (m_velocityBasis == VB_MOLEAVG) {
m_A(0,j) = m_molefracs_tran[j];
} else if (m_velocityBasis == VB_MASSAVG) {
m_A(0,j) = m_massfracs_tran[j];
} else if ((m_velocityBasis >= 0)
&& (m_velocityBasis < static_cast<int>(m_nsp))) {
// use species number m_velocityBasis as reference velocity
if (m_velocityBasis == static_cast<int>(j)) {
m_A(0,j) = 1.0;
} else {
m_A(0,j) = 0.0;
}
} else {
throw CanteraError("LiquidTransport::<API key>",
"Unknown reference velocity provided.");
}
}
for (size_t i = 1; i < m_nsp; i++) {
m_B(i,0) = m_Grad_mu[i] * invRT;
m_B(i,1) = m_Grad_mu[m_nsp + i] * invRT;
m_A(i,i) = 0.0;
for (size_t j = 0; j < m_nsp; j++) {
if (j != i) {
tmp = m_molefracs_tran[j] * m_bdiff(i,j);
m_A(i,i) -= tmp;
m_A(i,j) = tmp;
}
}
}
// invert and solve the system Ax = b. Answer is in m_B
solve(m_A, m_B);
break;
case 3: // 3-D approximation
m_B(0,0) = 0.0;
m_B(0,1) = 0.0;
m_B(0,2) = 0.0;
// equation for the reference velocity
for (size_t j = 0; j < m_nsp; j++) {
if (m_velocityBasis == VB_MOLEAVG) {
m_A(0,j) = m_molefracs_tran[j];
} else if (m_velocityBasis == VB_MASSAVG) {
m_A(0,j) = m_massfracs_tran[j];
} else if ((m_velocityBasis >= 0)
&& (m_velocityBasis < static_cast<int>(m_nsp))) {
// use species number m_velocityBasis as reference velocity
if (m_velocityBasis == static_cast<int>(j)) {
m_A(0,j) = 1.0;
} else {
m_A(0,j) = 0.0;
}
} else {
throw CanteraError("LiquidTransport::<API key>",
"Unknown reference velocity provided.");
}
}
for (size_t i = 1; i < m_nsp; i++) {
m_B(i,0) = m_Grad_mu[i] * invRT;
m_B(i,1) = m_Grad_mu[m_nsp + i] * invRT;
m_B(i,2) = m_Grad_mu[2*m_nsp + i] * invRT;
m_A(i,i) = 0.0;
for (size_t j = 0; j < m_nsp; j++) {
if (j != i) {
tmp = m_molefracs_tran[j] * m_bdiff(i,j);
m_A(i,i) -= tmp;
m_A(i,j) = tmp;
}
}
}
// invert and solve the system Ax = b. Answer is in m_B
solve(m_A, m_B);
break;
default:
throw CanteraError("routine", "not done");
}
for (size_t a = 0; a < m_nDim; a++) {
for (size_t j = 0; j < m_nsp; j++) {
m_Vdiff(j,a) = m_B(j,a);
m_flux(j,a) = concTot_ * M[j] * m_molefracs_tran[j] * m_B(j,a);
}
}
}
} |
// Package rest provides RESTful serialization of AWS requests and responses.
package rest
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"net/http"
"net/url"
"path"
"reflect"
"strconv"
"strings"
"time"
"github.com/revinate/etcd2s3/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr"
"github.com/revinate/etcd2s3/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request"
)
// RFC822 returns an RFC822 formatted timestamp for AWS protocols
const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT"
// Whether the byte value can be sent without escaping in AWS URLs
var noEscape [256]bool
var errValueNotSet = fmt.Errorf("value not set")
func init() {
for i := 0; i < len(noEscape); i++ {
// AWS expects every character except these to be escaped
noEscape[i] = (i >= 'A' && i <= 'Z') ||
(i >= 'a' && i <= 'z') ||
(i >= '0' && i <= '9') ||
i == '-' ||
i == '.' ||
i == '_' ||
i == '~'
}
}
// Build builds the REST component of a service request.
func Build(r *request.Request) {
if r.ParamsFilled() {
v := reflect.ValueOf(r.Params).Elem()
<API key>(r, v)
buildBody(r, v)
}
}
func <API key>(r *request.Request, v reflect.Value) {
query := r.HTTPRequest.URL.Query()
for i := 0; i < v.NumField(); i++ {
m := v.Field(i)
if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) {
continue
}
if m.IsValid() {
field := v.Type().Field(i)
name := field.Tag.Get("locationName")
if name == "" {
name = field.Name
}
if m.Kind() == reflect.Ptr {
m = m.Elem()
}
if !m.IsValid() {
continue
}
var err error
switch field.Tag.Get("location") {
case "headers": // header maps
err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag.Get("locationName"))
case "header":
err = buildHeader(&r.HTTPRequest.Header, m, name)
case "uri":
err = buildURI(r.HTTPRequest.URL, m, name)
case "querystring":
err = buildQueryString(query, m, name)
}
r.Error = err
}
if r.Error != nil {
return
}
}
r.HTTPRequest.URL.RawQuery = query.Encode()
updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path)
}
func buildBody(r *request.Request, v reflect.Value) {
if field, ok := v.Type().FieldByName("_"); ok {
if payloadName := field.Tag.Get("payload"); payloadName != "" {
pfield, _ := v.Type().FieldByName(payloadName)
if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
payload := reflect.Indirect(v.FieldByName(payloadName))
if payload.IsValid() && payload.Interface() != nil {
switch reader := payload.Interface().(type) {
case io.ReadSeeker:
r.SetReaderBody(reader)
case []byte:
r.SetBufferBody(reader)
case string:
r.SetStringBody(reader)
default:
r.Error = awserr.New("SerializationError",
"failed to encode REST request",
fmt.Errorf("unknown payload type %s", payload.Type()))
}
}
}
}
}
}
func buildHeader(header *http.Header, v reflect.Value, name string) error {
str, err := convertType(v)
if err == errValueNotSet {
return nil
} else if err != nil {
return awserr.New("SerializationError", "failed to encode REST request", err)
}
header.Add(name, str)
return nil
}
func buildHeaderMap(header *http.Header, v reflect.Value, prefix string) error {
for _, key := range v.MapKeys() {
str, err := convertType(v.MapIndex(key))
if err == errValueNotSet {
continue
} else if err != nil {
return awserr.New("SerializationError", "failed to encode REST request", err)
}
header.Add(prefix+key.String(), str)
}
return nil
}
func buildURI(u *url.URL, v reflect.Value, name string) error {
value, err := convertType(v)
if err == errValueNotSet {
return nil
} else if err != nil {
return awserr.New("SerializationError", "failed to encode REST request", err)
}
uri := u.Path
uri = strings.Replace(uri, "{"+name+"}", EscapePath(value, true), -1)
uri = strings.Replace(uri, "{"+name+"+}", EscapePath(value, false), -1)
u.Path = uri
return nil
}
func buildQueryString(query url.Values, v reflect.Value, name string) error {
switch value := v.Interface().(type) {
case []*string:
for _, item := range value {
query.Add(name, *item)
}
case map[string]*string:
for key, item := range value {
query.Add(key, *item)
}
case map[string][]*string:
for key, items := range value {
for _, item := range items {
query.Add(key, *item)
}
}
default:
str, err := convertType(v)
if err == errValueNotSet {
return nil
} else if err != nil {
return awserr.New("SerializationError", "failed to encode REST request", err)
}
query.Set(name, str)
}
return nil
}
func updatePath(url *url.URL, urlPath string) {
scheme, query := url.Scheme, url.RawQuery
hasSlash := strings.HasSuffix(urlPath, "/")
// clean up path
urlPath = path.Clean(urlPath)
if hasSlash && !strings.HasSuffix(urlPath, "/") {
urlPath += "/"
}
// get formatted URL minus scheme so we can build this into Opaque
url.Scheme, url.Path, url.RawQuery = "", "", ""
s := url.String()
url.Scheme = scheme
url.RawQuery = query
// build opaque URI
url.Opaque = s + urlPath
}
// EscapePath escapes part of a URL path in Amazon style
func EscapePath(path string, encodeSep bool) string {
var buf bytes.Buffer
for i := 0; i < len(path); i++ {
c := path[i]
if noEscape[c] || (c == '/' && !encodeSep) {
buf.WriteByte(c)
} else {
buf.WriteByte('%')
buf.WriteString(strings.ToUpper(strconv.FormatUint(uint64(c), 16)))
}
}
return buf.String()
}
func convertType(v reflect.Value) (string, error) {
v = reflect.Indirect(v)
if !v.IsValid() {
return "", errValueNotSet
}
var str string
switch value := v.Interface().(type) {
case string:
str = value
case []byte:
str = base64.StdEncoding.EncodeToString(value)
case bool:
str = strconv.FormatBool(value)
case int64:
str = strconv.FormatInt(value, 10)
case float64:
str = strconv.FormatFloat(value, 'f', -1, 64)
case time.Time:
str = value.UTC().Format(RFC822)
default:
err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type())
return "", err
}
return str, nil
} |
#cardDisplay {
color:red;
width:200px;
margin:50px;
}
.card {
color:black;
background-color:red;
width:150px;
display:inline;
margin:0px;
font-size:20px;
}
.card img {
width: 150px;
z-index: 1;
}
.ensuringCheck {
background: #333;
width: 120px;
left: 80px;
<API key>: 10px;
<API key>: 10px;
color: white;
text-align: center;
margin-top: 20px;
}
.card p {
margin: 0px;
position: relative;
margin-top: -40px;
margin-left: -70px;
z-index: 10000;
display: inline-block;
}
#cost {
border:2px solid black;
width:70px;
height:20px;
padding:3px;
}
#coin {
height:20px;
}
#number {
width:35px;
}
ul {
list-style-type: none;
}
#form {
margin:30px;
height: 480px;
}
#chosenCards
{
float:right;
clear:both;
width:750px;
display:inline-block;
}
#costs {
width:30px;
float:right;
margin-top:-26px;
}
/**
* Checkbox Two
*/
.checkboxTwo {
width: 120px;
height: 40px;
background: #333;
margin: 20px 60px;
border-radius: 50px;
position: relative;
}/**
* Create the line for the circle to move across
*/
.checkboxTwo:before {
content: '';
position: absolute;
top: 19px;
left: 14px;
height: 2px;
width: 90px;
background: #111;
}/**
* Create the circle to click
*/
.checkboxTwo label {
display: block;
width: 22px;
height: 22px;
border-radius: 50%;
-webkit-transition: all .5s ease;
-moz-transition: all .5s ease;
-o-transition: all .5s ease;
-ms-transition: all .5s ease;
transition: all .5s ease;
cursor: pointer;
position: absolute;
top: 9px;
z-index: 1;
left: 12px;
background: red;
}
.checkboxTwo input[type=checkbox]:checked + label {
left: 84px;
background: #26ca28;
}
/**
* Start by hiding the checkboxes
*/
form[name='cardType'] input[type=checkbox] {
visibility: hidden;
}
/**
* Checkbox Three
*/
.checkboxThree {
width: 120px;
height: 20px;
background: #333;
margin: 0px 0px;
border-radius: 50px;
position: relative;
}/**
* Create the text for the On position
*/
.checkboxThree:before {
content: 'yes';
position: absolute;
top: 0px;
left: 13px;
height: 2px;
color: #26ca28;
font-size: 16px;
}/**
* Create the label for the off position
*/
.checkboxThree:after {
content: 'no';
position: absolute;
top: 0px;
left: 84px;
height: 2px;
color: red;
font-size: 16px;
}/**
* Create the pill to click
*/
.checkboxThree label {
display: block;
width: 52px;
height: 20px;
border-radius: 50px;
<API key>: 0px;
<API key>: 0px;
-webkit-transition: all .5s ease;
-moz-transition: all .5s ease;
-o-transition: all .5s ease;
-ms-transition: all .5s ease;
transition: all .5s ease;
cursor: pointer;
position: absolute;
top: 0px;
z-index: 1;
left: -1px;
background: red;
}
/**
* Create the checkbox event for the label
*/
.checkboxThree input[type=checkbox]:checked + label {
left: 70px;
background: #26ca28;
border-radius: 50px;
<API key>: 0px;
<API key>: 0px;
} |
#include "UnitTests/UnitTests.h"
#include "Base/FastName.h"
#include "Base/RefPtr.h"
#include "Concurrency/Thread.h"
#include "Engine/EngineContext.h"
#include "FileSystem/KeyedArchive.h"
#include "Job/JobManager.h"
#include "Reflection/Reflection.h"
#include "Reflection/<API key>.h"
#include "UI/DataBinding/<API key>.h"
#include "UI/<API key>.h"
#include "UI/Events/<API key>.h"
#include "UI/Events/UIEventsSystem.h"
#include "UI/Flow/Private/<API key>.h"
#include "UI/Flow/Services/UIFlowSystemService.h"
#include "UI/Flow/UIFlowContext.h"
#include "UI/Flow/UIFlowController.h"
#include "UI/Flow/<API key>.h"
#include "UI/Flow/<API key>.h"
#include "UI/Flow/<API key>.h"
#include "UI/Flow/UIFlowStateSystem.h"
#include "UI/Flow/<API key>.h"
#include "UI/Flow/<API key>.h"
#include "UI/Flow/UIFlowViewComponent.h"
#include "UI/Flow/UIFlowViewSystem.h"
#include "UI/UIControl.h"
#include "UI/UIControlSystem.h"
#include "UI/UIGeometricData.h"
#include "UI/UIPackage.h"
#include "UI/UIPackageLoader.h"
#include "UI/UIScreen.h"
using namespace DAVA;
class DemoFlowController : public UIFlowController
{
<API key>(DemoFlowController, UIFlowController)
{
<API key><DemoFlowController>::Begin()
.<API key>()
.DestructorByPointer([](DemoFlowController* c) { SafeDelete(c); })
.End();
}
public:
uint32 testStep = 0;
bool first = true;
void Init(UIFlowContext* context) override
{
UIFlowController::Init(context);
testStep = context->GetData()->GetInt32("testStep");
testStep++;
}
void LoadResources(UIFlowContext* context, UIControl* view) override
{
UIFlowController::LoadResources(context, view);
testStep++;
}
void Activate(UIFlowContext* context, UIControl* view) override
{
UIFlowController::Activate(context, view);
testStep++;
}
void Process(float32 elapsedTime) override
{
UIFlowController::Process(elapsedTime);
if (first)
{
testStep++;
first = false;
}
}
bool ProcessEvent(const FastName& eventName, const Vector<Any>& params = Vector<Any>()) override
{
static const FastName incA("INC_A");
if (eventName == incA)
{
testStep++;
return true;
}
return UIFlowController::ProcessEvent(eventName, params);
}
void Deactivate(UIFlowContext* context, UIControl* view) override
{
testStep++;
UIFlowController::Deactivate(context, view);
}
void UnloadResources(UIFlowContext* context, UIControl* view) override
{
testStep++;
UIFlowController::UnloadResources(context, view);
}
void Release(UIFlowContext* context) override
{
testStep++;
context->GetData()->SetInt32("testStep", testStep);
UIFlowController::Release(context);
}
};
DAVA_TESTCLASS (UIFlowTest)
{
<API key>()
<API key>(DavaFramework)
<API key>("UIFlowContext.cpp")
<API key>("UIFlowController.cpp")
<API key>("<API key>.cpp")
<API key>("<API key>.cpp")
<API key>("UIFlowLuaController.cpp")
<API key>("UIFlowService.cpp")
<API key>("<API key>.cpp")
<API key>("UIFlowStateSystem.cpp")
<API key>("<API key>.cpp")
<API key>("<API key>.cpp")
<API key>("UIFlowUtils.cpp")
<API key>("UIFlowViewComponent.cpp")
<API key>("UIFlowViewSystem.cpp")
//TODO: Uncomment after we start test render in unit tests
//<API key>("<API key>.cpp")
//<API key>("<API key>.cpp")
//<API key>("<API key>.cpp")
<API key>();
static const int32 <API key> = 8;
RefPtr<UIControl> flowProto;
RefPtr<UIControl> uiRoot;
UIControlSystem* controlSys = nullptr;
UIFlowStateSystem* stateSys = nullptr;
<API key>* eventComp = nullptr;
UIFlowTest()
{
<API key>(DemoFlowController);
controlSys = GetEngineContext()->uiControlSystem;
RefPtr<UIScreen> screen(new UIScreen());
controlSys->SetScreen(screen.Get());
controlSys->Update();
{
DAVA::<API key> pkgBuilder;
DAVA::UIPackageLoader().LoadPackage("~res:/UI/Flow/Flow.yaml", &pkgBuilder);
flowProto = pkgBuilder.GetPackage()->GetControls().at(0);
}
{
DAVA::<API key> pkgBuilder;
DAVA::UIPackageLoader().LoadPackage("~res:/UI/Flow/Screen.yaml", &pkgBuilder);
uiRoot = pkgBuilder.GetPackage()->GetControls().at(0);
}
stateSys = controlSys->GetSystem<UIFlowStateSystem>();
eventComp = controlSys->GetSingleComponent<<API key>>();
}
~UIFlowTest()
{
controlSys->Reset();
}
void SystemsUpdate(float32 time = 0.f)
{
if (time > 0.f)
{
controlSys-><API key>(time);
}
else
{
controlSys->Update();
}
}
void <API key>()
{
while (stateSys->HasTransitions())
{
GetEngineContext()->jobManager->Update();
Thread::Sleep(10);
}
}
void SendEvent(const String& e)
{
eventComp->SendEvent(controlSys->GetScreen(), FastName(e), Any());
}
bool HasControl(const String& path)
{
return controlSys->GetScreen()->FindByPath(path) != nullptr;
}
void SetUp(const String& testName) override
{
stateSys->SetFlowRoot(flowProto->SafeClone().Get());
controlSys->GetScreen()->AddControl(uiRoot->SafeClone().Get());
}
void TearDown(const String& testName) override
{
stateSys->SetFlowRoot(nullptr);
stateSys->GetContext()->GetData()->DeleteAllKeys();
controlSys->GetScreen()->RemoveAllControls();
}
DAVA_TEST (SyncActivation)
{
<API key>* state = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state != nullptr);
stateSys->ActivateState(state, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state);
TEST_VERIFY(HasControl("**/View1"));
TEST_VERIFY(stateSys->IsStateActive(stateSys->FindStateByPath("^")));
TEST_VERIFY(stateSys->IsStateActive(stateSys->FindStateByPath("^/BasicGroup")));
TEST_VERIFY(stateSys->IsStateActive(stateSys->FindStateByPath("^/BasicGroup/State1")));
}
DAVA_TEST (AsyncActivation)
{
<API key>* state = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state != nullptr);
stateSys->ActivateState(state, true);
<API key>* transaction = stateSys-><API key>();
TEST_VERIFY(transaction != nullptr);
TEST_VERIFY(transaction->IsBackgroundLoading());
SystemsUpdate();
<API key>();
TEST_VERIFY(stateSys-><API key>() == state);
TEST_VERIFY(HasControl("**/View1"));
}
DAVA_TEST (SyncSwitchingState)
{
<API key>* state1 = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state1 != nullptr);
stateSys->ActivateState(state1, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state1);
TEST_VERIFY(HasControl("**/View1"));
<API key>* state2 = stateSys->FindStateByPath("^State2");
TEST_VERIFY(state2 != nullptr);
stateSys->ActivateState(state2, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state2);
TEST_VERIFY(HasControl("**/View2"));
TEST_VERIFY(!HasControl("**/View1"));
TEST_VERIFY(stateSys->IsStateActive(state2));
TEST_VERIFY(!stateSys->IsStateActive(state1));
}
DAVA_TEST (AsyncSwitchingState)
{
<API key>* state1 = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state1 != nullptr);
stateSys->ActivateState(state1, true);
SystemsUpdate();
<API key>();
TEST_VERIFY(stateSys-><API key>() == state1);
TEST_VERIFY(HasControl("**/View1"));
<API key>* state2 = stateSys->FindStateByPath("^State2");
TEST_VERIFY(state2 != nullptr);
stateSys->ActivateState(state2, true);
SystemsUpdate();
<API key>();
TEST_VERIFY(stateSys-><API key>() == state2);
TEST_VERIFY(HasControl("**/View2"));
TEST_VERIFY(!HasControl("**/View1"));
TEST_VERIFY(stateSys->IsStateActive(state2));
TEST_VERIFY(!stateSys->IsStateActive(state1));
}
DAVA_TEST (HistoryBack)
{
<API key>* state1 = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state1 != nullptr);
stateSys->ActivateState(state1, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state1);
<API key>* state2 = stateSys->FindStateByPath("^State2");
TEST_VERIFY(state2 != nullptr);
stateSys->ActivateState(state2, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state2);
// By system method
stateSys->HistoryBack();
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state1);
stateSys->ActivateState(state2, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state2);
// By event
SendEvent("BACK");
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state1);
}
DAVA_TEST (HistorySiblings)
{
<API key>* state1 = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state1 != nullptr);
stateSys->ActivateState(state1, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state1);
<API key>* sibling1 = stateSys->FindStateByPath("^Sibling1");
TEST_VERIFY(sibling1 != nullptr);
stateSys->ActivateState(sibling1, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == sibling1);
<API key>* sibling2 = stateSys->FindStateByPath("^Sibling2");
TEST_VERIFY(sibling2 != nullptr);
stateSys->ActivateState(sibling2, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == sibling2);
stateSys->HistoryBack();
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state1);
}
DAVA_TEST (HistoryTop)
{
<API key>* state1 = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state1 != nullptr);
stateSys->ActivateState(state1, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state1);
// Back from OnlyTop state
<API key>* stateTop = stateSys->FindStateByPath("^StateTop");
TEST_VERIFY(stateTop != nullptr);
stateSys->ActivateState(stateTop, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == stateTop);
stateSys->HistoryBack();
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state1);
// Switch OnlyTop state and go back
stateSys->ActivateState(stateTop, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == stateTop);
<API key>* state2 = stateSys->FindStateByPath("^State2");
TEST_VERIFY(state2 != nullptr);
stateSys->ActivateState(state2, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state2);
stateSys->HistoryBack();
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == state1);
}
DAVA_TEST (FlowService)
{
static const FastName serviceName("flow");
UIFlowContext* context = stateSys->GetContext();
TEST_VERIFY(context != nullptr);
<API key>* state = stateSys->FindStateByPath(".");
TEST_VERIFY(state != nullptr);
stateSys->ActivateState(state, false);
SystemsUpdate();
TEST_VERIFY(context->GetService<UIFlowSystemService>(serviceName) != nullptr);
stateSys->DeactivateAllStates();
SystemsUpdate();
TEST_VERIFY(context->GetService<UIFlowSystemService>(serviceName) == nullptr);
}
DAVA_TEST (LuaController)
{
UIFlowContext* context = stateSys->GetContext();
TEST_VERIFY(context != nullptr);
KeyedArchive* data = context->GetData();
TEST_VERIFY(data != nullptr);
data->SetInt32("testStep", 0);
<API key>* state = stateSys->FindStateByPath(".LuaCtrlTest");
TEST_VERIFY(state != nullptr);
stateSys->ActivateState(state, false);
SystemsUpdate();
KeyedArchive* model = data->GetArchive("model");
TEST_VERIFY(model != nullptr);
TEST_VERIFY(model->GetInt32("a") == 1);
SendEvent("INC_A");
SystemsUpdate();
TEST_VERIFY(model->GetInt32("a") == 2);
stateSys->DeactivateAllStates();
SystemsUpdate();
model = data->GetArchive("model");
TEST_VERIFY(model->Count() == 0);
TEST_VERIFY(data->GetInt32("testStep") == <API key>);
}
DAVA_TEST (NativeController)
{
UIFlowContext* context = stateSys->GetContext();
TEST_VERIFY(context != nullptr);
KeyedArchive* data = context->GetData();
TEST_VERIFY(data != nullptr);
data->SetInt32("testStep", 0);
<API key>* state = stateSys->FindStateByPath(".NativeCtrlTest");
TEST_VERIFY(state != nullptr);
stateSys->ActivateState(state, false);
SystemsUpdate();
SendEvent("INC_A");
SystemsUpdate();
stateSys->DeactivateAllStates();
SystemsUpdate();
TEST_VERIFY(data->GetInt32("testStep") == <API key>);
}
DAVA_TEST (MultipleStates)
{
<API key>* state = stateSys->FindStateByPath(".");
TEST_VERIFY(state != nullptr);
stateSys->ActivateState(state, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == stateSys->FindStateByPath("./DefaultState"));
state = stateSys->FindStateByPath("^/SubState");
TEST_VERIFY(state != nullptr);
stateSys->PreloadState(state, false);
<API key>* transaction = stateSys-><API key>();
TEST_VERIFY(transaction != nullptr);
TEST_VERIFY(transaction->IsOnlyLoad());
SystemsUpdate();
TEST_VERIFY(stateSys->IsStateLoaded(state));
stateSys->ActivateState(state, false);
SystemsUpdate();
TEST_VERIFY(stateSys->IsStateActive(state));
stateSys->DeactivateState(state, false);
SystemsUpdate();
TEST_VERIFY(stateSys->IsStateActive(state) == false);
}
DAVA_TEST (TransitionsByEvents)
{
<API key>* state = stateSys->FindStateByPath(".");
TEST_VERIFY(state != nullptr);
stateSys->ActivateState(state, false);
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == stateSys->FindStateByPath("./DefaultState"));
SendEvent("STATE1");
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == stateSys->FindStateByPath("^State1"));
SendEvent("STATE2");
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == stateSys->FindStateByPath("^State2"));
SendEvent("BASIC_GROUP");
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == stateSys->FindStateByPath("^State1"));
SendEvent("STATE2_BG");
SystemsUpdate();
<API key>();
TEST_VERIFY(stateSys-><API key>() == stateSys->FindStateByPath("^State2"));
SendEvent("FWD_STATE1");
SystemsUpdate();
SystemsUpdate();
TEST_VERIFY(stateSys-><API key>() == stateSys->FindStateByPath("^State1"));
SendEvent("SUBSTATE");
SystemsUpdate();
TEST_VERIFY(stateSys->IsStateActive(stateSys->FindStateByPath("^/SubState")));
SendEvent("SUBSTATE_OFF");
SystemsUpdate();
TEST_VERIFY(!stateSys->IsStateActive(stateSys->FindStateByPath("^/SubState")));
}
DAVA_TEST (ControllerComponent)
{
<API key>* state = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state != nullptr);
UIControl* stateControl = state->GetControl();
<API key>* ctrlCom = stateControl-><API key><<API key>>();
ctrlCom-><API key>("<API key>");
ctrlCom->SetLuaScriptPath("~res:/<API key>.lua");
stateSys->ActivateState(state, false);
SystemsUpdate();
<API key>* ctrlSys = controlSys->GetSystem<<API key>>();
TEST_VERIFY(ctrlSys->GetController(ctrlCom) == nullptr);
stateControl->RemoveComponent<<API key>>();
}
DAVA_TEST (ViewComponent)
{
<API key>* state = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state != nullptr);
UIControl* stateControl = state->GetControl();
UIFlowViewComponent* viewCom = stateControl-><API key><UIFlowViewComponent>();
viewCom->SetViewYaml("~res:/<API key>.yaml");
viewCom->SetControlName("WRONG_CONTROL_NAME");
viewCom->SetContainerPath("^/<API key>");
stateSys->ActivateState(state, false);
SystemsUpdate();
UIFlowViewSystem* viewSys = controlSys->GetSystem<UIFlowViewSystem>();
TEST_VERIFY(viewSys->GetLinkedView(viewCom) == nullptr);
stateControl->RemoveComponent<UIFlowViewComponent>();
}
DAVA_TEST (<API key>)
{
static const String TRANSITION_STR("EVENT,Activate,^;EVENT2,SendEvent,EVENT;");
<API key>* state = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state != nullptr);
UIControl* stateControl = state->GetControl();
<API key>* transCom = stateControl-><API key><<API key>>();
transCom-><API key>(TRANSITION_STR);
stateSys->ActivateState(state, false);
SystemsUpdate();
const <API key>::TransitionMap& transMap = transCom->GetTransitionMap();
TEST_VERIFY(transMap.size() == 2);
TEST_VERIFY(transMap[0].event == FastName("EVENT"));
TEST_VERIFY(transMap[0].operation == <API key>::ACTIVATE_STATE);
TEST_VERIFY(transMap[0].statePath == "^");
TEST_VERIFY(transMap[1].event == FastName("EVENT2"));
TEST_VERIFY(transMap[1].operation == <API key>::SEND_EVENT);
TEST_VERIFY(transMap[1].sendEvent == FastName("EVENT"));
transCom->SetTransitionMap(transMap);
TEST_VERIFY(transCom-><API key>() == TRANSITION_STR);
}
DAVA_TEST (StateComponent)
{
static const String EVENTS_STR("EVENT1;EVENT2;");
static const String SERVICES_STR("flow,UIFlowSystemService;wrong,WRONG_SERVICE;");
<API key>* state = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state != nullptr);
state-><API key>(EVENTS_STR);
state-><API key>(EVENTS_STR);
state-><API key>(SERVICES_STR);
stateSys->ActivateState(state, false);
SystemsUpdate();
const Vector<FastName>& activateEvents = state->GetActivateEvents();
TEST_VERIFY(activateEvents.size() == 2);
TEST_VERIFY(activateEvents[0] == FastName("EVENT1"));
TEST_VERIFY(activateEvents[1] == FastName("EVENT2"));
state->SetActivateEvents(activateEvents);
TEST_VERIFY(state-><API key>() == EVENTS_STR);
const Vector<FastName>& deactivateEvents = state->GetDeactivateEvents();
TEST_VERIFY(deactivateEvents.size() == 2);
TEST_VERIFY(deactivateEvents[0] == FastName("EVENT1"));
TEST_VERIFY(deactivateEvents[1] == FastName("EVENT2"));
state->SetDeactivateEvents(deactivateEvents);
TEST_VERIFY(state-><API key>() == EVENTS_STR);
const Vector<<API key>::ServiceDescriptor>& services = state->GetServices();
TEST_VERIFY(services.size() == 2);
TEST_VERIFY(services[0].name == "flow");
TEST_VERIFY(services[0].nativeType == "UIFlowSystemService");
TEST_VERIFY(services[1].name == "wrong");
TEST_VERIFY(services[1].nativeType == "WRONG_SERVICE");
state->SetServices(services);
TEST_VERIFY(state->GetServicesAsString() == SERVICES_STR);
}
DAVA_TEST (DataBinding)
{
UIFlowContext* context = stateSys->GetContext();
TEST_VERIFY(context != nullptr);
KeyedArchive* data = context->GetData();
TEST_VERIFY(data != nullptr);
RefPtr<KeyedArchive> model(new KeyedArchive());
model->SetInt32("a", 1);
data->SetArchive("model", model.Get());
<API key>* state = stateSys->FindStateByPath(".State1");
TEST_VERIFY(state != nullptr);
UIControl* stateControl = state->GetControl();
UIFlowViewComponent* viewCom = stateControl->GetComponent<UIFlowViewComponent>();
TEST_VERIFY(viewCom != nullptr);
viewCom->SetModelName("model");
viewCom->SetModelScope("{b = 2}");
stateSys->ActivateState(state, false);
SystemsUpdate();
UIControl* view = controlSys->GetScreen()->FindByPath("**/View1");
<API key>* dataCom = view->GetComponent<<API key>>(0);
TEST_VERIFY(dataCom != nullptr);
TEST_VERIFY(dataCom->GetSourceType() == <API key>::FROM_REFLECTION);
TEST_VERIFY(dataCom->GetData().IsValid());
TEST_VERIFY(dataCom->GetData().GetField("a").IsValid());
<API key>* scopeCom = view->GetComponent<<API key>>(1);
TEST_VERIFY(scopeCom != nullptr);
TEST_VERIFY(scopeCom->GetSourceType() == <API key>::FROM_EXPRESSION);
TEST_VERIFY(scopeCom->GetSource() == "{b = 2}");
}
DAVA_TEST (TransitionEffects)
{
<API key>* state = stateSys->FindStateByPath("./DefaultState");
TEST_VERIFY(state != nullptr);
stateSys->ActivateState(state, false);
<API key>* transaction = stateSys-><API key>();
TEST_VERIFY(transaction != nullptr);
<API key> effectCfg;
transaction->SetEffectConfig(effectCfg);
SystemsUpdate(); // Apply transaction
SystemsUpdate(); // Apply transition effect
TEST_VERIFY(stateSys-><API key>() == state);
// TODO: Make test for rendering in separate application (TestBed)
// const float32 HALF_TIME = 0.051f;
// const Array<String, 8> STATES = {
// "./Effects/Static",
// "^/Effects/FadeAlpha",
// "^/Effects/Fade",
// "^/Effects/Scale",
// "^/Effects/Flip",
// "^/Effects/MoveLeft",
// "^/Effects/MoveRight",
// "^/Effects/Static"
// <API key>* state = nullptr;
// for (const String& statePath : STATES)
// state = stateSys->FindStateByPath(statePath);
// TEST_VERIFY(state != nullptr);
// stateSys->ActivateState(state, false);
// SystemsUpdate(HALF_TIME);
// controlSys->Draw();
// SystemsUpdate(HALF_TIME);
// controlSys->Draw();
// TEST_VERIFY(stateSys-><API key>() == state);
// // Deactivate all states with transitions and make sure that transitions complete
// stateSys->DeactivateAllStates();
// SystemsUpdate(HALF_TIME);
// controlSys->Draw();
// TEST_VERIFY(stateSys-><API key>() == nullptr);
}
}; |
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\<API key>;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Application\Model\Users;
class AjaxController extends <API key>
{
private $usersTable;
private $configArray = array(
'driver' => 'Mysqli',
'database' => 'supermed',
'username' => 'root',
'password' => 'kopsow82',
'hostname' => 'localhost',
'charset' => 'utf8'
);
public function getUsersTable()
{
if (!$this->usersTable) {
$sm = $this->getServiceLocator();
$this->usersTable = $sm->get('Users\Model\UsersTable');
}
return $this->usersTable;
}
public function emailCheckAction()
{
$request = $this->getRequest();
$result = NULL;
if ($request->isXmlHttpRequest()) {
$result = $this->getUsersTable()->checkEmail($request->getPost('email'));
}
return new JsonModel(array(
'msg' => $result,
));
}
public function listNameAction()
{
$request = $this->getRequest();
//$search = $request->getPost('name');
$search = 'Woj';
$dbAdapter = new \Zend\Db\Adapter\Adapter($this->configArray);
$statement = $dbAdapter->query('SELECT * FROM users WHERE name like "'.$search.'%"');
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[$res['id']] = $res['name'];
}
return new JsonModel(array(
'msg' => $selectData,
));
}
public function listSurnameAction()
{
$request = $this->getRequest();
$search = $request->getPost('surname');
$selectData = array();
if ($search != null)
{
$dbAdapter = new \Zend\Db\Adapter\Adapter($this->configArray);
$statement = $dbAdapter->query('SELECT * FROM users WHERE surname like "'.$search.'%"');
$result = $statement->execute();
foreach ($result as $res) {
$selectData[] = array(
'id'=>$res['id'],
'email'=>$res['email'],
'login' => $res['login']);
}
}
return new JsonModel(array(
json_encode($selectData)
));
}
public function indexAction()
{
return new ViewModel();
}
} |
<?php
namespace chegamos\entity\repository;
use chegamos\entity\Config;
use chegamos\entity\factory\UserFactory;
use chegamos\entity\factory\UserListFactory;
use chegamos\rest\Request;
class UserRepository
{
private $config;
private $requestType;
private $request;
public function __construct(Config $config)
{
if (!empty($config)) {
$this->config = $config;
}
$this->setup();
}
public function get($id = null)
{
if (!empty($id)) {
$this->byId($id);
}
$this->getPath();
$this->request->setVerb('GET');
$userJsonString = $this->config
->getRestClient()
->execute($this->request);
$this->setup();
$userJsonObject = json_decode($userJsonString);
return UserFactory::generate($userJsonObject->user);
}
public function getAll()
{
$this->getPath();
$this->request->setVerb('GET');
$userListJsonString = $this->config
->getRestClient()
->execute($this->request);
$this->setup();
$userListJsonObject = json_decode($userListJsonString);
return UserListFactory::generate($userListJsonObject->search);
}
public function withDetails()
{
$this->requestType = 'details';
return $this;
}
public function withReviews()
{
$this->requestType = 'reviews';
return $this;
}
public function byId($id)
{
$this->request->addParam('id', $id);
return $this;
}
public function byName($name)
{
$this->requestType = 'usersByName';
$this->request->addQueryItem("name", $name);
return $this;
}
public function byEmail($email)
{
$this->requestType = 'usersByEmail';
$this->request->addQueryItem("email", $email);
return $this;
}
public function page($page)
{
$this->request->addQueryItem("page", $page);
return $this;
}
private function setup()
{
$this->request = new Request();
$this->request->setBaseUrl($this->config->getBaseUrl());
$this->request->addQueryItem("type", "json");
$basicAuth = $this->config->getBasicAuth();
if (!empty($basicAuth)) {
$this->request->setHeader($basicAuth->getHeader());
}
$this->requestType = "details";
}
private function getQueryString()
{
return http_build_query($this->query);
}
private function getPath()
{
switch ($this->requestType) {
case 'usersByName':
$this->request->setPath("search/users/byname");
break;
case 'usersByEmail':
$this->request->setPath("search/users/byemail");
break;
case 'details':
$this->request->setPath("users/".$this->request->getParam('id'));
break;
case 'reviews':
$this->request->setPath(
"users/".$this->request->getParam('id').'/reviews'
);
break;
}
return $this->request->getPath();
}
} |
<?php
class Duration {
var $_LongNames = array('year','month','week','day','hour','minute','second');
var $_ShortNames = array('yr','mth','wk','day','hr','min','sec');
var $_Steps = array(31557600,2592000,604800,86400,3600,60,1);
var $names, $steps, $terse;
function Duration() { $this->__construct(); }
function __construct() {
$this->names =& $this->_LongNames;
$this->steps =& $this->_Steps;
$this->terse = false;
}
function short($bool = true) {
if($bool)
$this->names =& $this->_ShortNames;
else
$this->names =& $this->_LongNames;
}
function terse($terse = true) {
$this->terse = $terse;
}
function Now() {
$gtod = gettimeofday();
$now = bcadd($gtod['sec'], bcdiv($gtod['usec'], 1000000, 6), 6);
return $now;
}
function Diff($now, $then) {
return bcsub($now, $then, 6);
}
function Age($when) {
return $this->_age($when);
}
function AgeAsArray($when) {
$arr = $this->_age($when);
return $arr[2];
}
function AgeAsHash($when) {
$arr = $this->_age($when);
return $arr[1];
}
function AgeAsString($when) {
$arr = $this->_age($when);
return $arr[0];
}
private function _age($when, $step = 0, &$str = "", &$arr = array(), &$arr2 = array()) {
if($when > 0 && $step < count($this->steps)) {
if($when >= $this->steps[$step]) {
$span = floor($when / $this->steps[$step]);
$when %= $this->steps[$step];
$arr[$this->_LongNames[$step]."s"] = $span;
$arr2[] = $span." ".$this->names[$step].($span==1?"":"s");
if($this->terse && !empty($str))
$str .= " ";
else if(!empty($str) && $when != 0)
$str .= ", ";
else if(!empty($str) && $when == 0 && count($arr) < 3)
$str .= " and ";
else if(!empty($str) && $when == 0 && count($arr) >= 3)
$str .= ", and ";
$str .= $span." ".$this->names[$step].($span==1?"":"s");
}
list($str, $arr) = $this->_age($when, $step + 1, &$str, &$arr, &$arr2);
}
return array((!empty($str)?$str:"less than 1 second"), &$arr, &$arr2);
}
}
if (!function_exists('jddayofweek')) {
function jddayofweek($a_jd,$a_mode){
$tmp = get_jd_dmy($a_jd) ;
$a_time = "$tmp[0]/$tmp[1]/$tmp[2]" ;
switch($a_mode) {
case 1:
return strftime("%A, %d, %y",strtotime("$a_time")) ;
case 2:
return strftime("%a",strtotime("$a_time")) ;
default:
return strftime("%w",strtotime("$a_time")) ;
}
}
}
function simpleDate($params, &$smarty) {
$t = ceil($params['time']);
$n = time()+21600;
$s = "";
if($n == $t)
return 'Now';
$n -= $n%86400;
if($t >= $n) {
return 'Today';
}
$n -= 86400;
if($t >= $n) {
return 'Yesterday';
}
$n -= (86400-6); # Week prior
if($t >= $n) {
/* $m = intval(strftime("%m", $t));
$d = intval(strftime("%d", $t));
$y = intval(strftime("%Y", $t));
$h = intval(strftime("%H", $t));
$min = intval(strftime("%M", $t));
$s = intval(strftime("%S", $t));
$a = ((14 - $m)/12);
$y = $y + 4800 - $a;
$m = $m + (12*$a) - 3;
# JDN in Gregorian
$jdn = $d + ((153*$m+2)/5) + (365*$y) + ($y/4) - ($y/100) + ($y/400) - 32045 + ( (($h-12)/24) + ($min/1440) + ($s/86400) );
# JDN in Julian
#$jdn = $d + ((153*$m+2)/5) + (365*$y) + ($y/4) - 32083;
return $jdn; */
return strftime("%A", $t);
}
$n = time();
$n -= $n%86400;
$n -= 365.25 * 86400;
if($t >= $n) {
return strftime("%B %e", $t);
}
return strftime("%B %e, %Y", $t);
}
function age($params, &$smarty) {
$d = new Duration();
$d->short();
$d->terse();
$a = $d->AgeAsArray(ceil($d->Diff(time(), $params["time"])));
if(isset($params['steps'])) {
return join(' ', array_slice($a, 0, $params['steps']));
}
return join(' ', $a);
}
?> |
import System.Environment (getArgs)
r1 :: [Int]
r1 = [1, 0, 0, 0, 1, 1]
r2 :: [Int]
r2 = [1, 0, 1, 0, 1, 1]
bnot :: Int -> Int
bnot 0 = 1
bnot _ = 0
pmod6 :: Int -> Int
pmod6 x | mod x 6 == 0 = 6
| otherwise = mod x 6
locks :: [Int] -> Int
locks [0, _] = 0
locks [x, 0] = x
locks [x, 1] = x-1
locks [x, y] | x > 6 && mod y 2 == 0 = div x 6 * 3 + locks [pmod6 x, y]
| x > 6 = div x 6 * 4 + locks [pmod6 x, y]
| mod y 2 == 0 = sum (init xs) + bnot (last xs)
| otherwise = sum (init ys) + bnot (last ys)
where xs = take x r1
ys = take x r2
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (show . locks . map read . words) $ lines input |
#include <dlfcn.h>
#include <string.h>
#include "ld.h"
#include <stdio.h>
int SHLIB_load( SHLIB *lib, const char *name )
{
lib->last_error = 0;
lib->handle = dlopen( name, RTLD_NOW );
if (!lib->handle) {
char *ret;
ret = dlerror();
if (ret)
lib->last_error = strdup( ret );
}
return lib->handle == 0;
}
void * SHLIB_get_proc_addr( SHLIB *lib, const char *symbol )
{
void *ret;
ret = dlsym( lib->handle, symbol );
if (!ret) {
char *ret;
ret = dlerror();
if (ret)
lib->last_error = strdup( ret );
}
return ret;
}
int SHLIB_unload( SHLIB *lib )
{
if (lib->handle) {
dlclose( lib->handle );
lib->handle = 0;
}
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.