file_name
large_stringlengths 4
140
| prefix
large_stringlengths 0
12.1k
| suffix
large_stringlengths 0
12k
| middle
large_stringlengths 0
7.51k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
leap.js | /**
* Copyright (c) 2013, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
var assert = require("assert");
var types = require("ast-types");
var n = types.namedTypes;
var b = types.builders;
var inherits = require("util").inherits;
function Entry() {
assert.ok(this instanceof Entry);
}
function FunctionEntry(returnLoc) {
Entry.call(this);
n.Literal.assert(returnLoc);
Object.defineProperties(this, {
returnLoc: { value: returnLoc }
});
}
inherits(FunctionEntry, Entry);
exports.FunctionEntry = FunctionEntry;
function | (breakLoc, continueLoc, label) {
Entry.call(this);
n.Literal.assert(breakLoc);
n.Literal.assert(continueLoc);
if (label) {
n.Identifier.assert(label);
} else {
label = null;
}
Object.defineProperties(this, {
breakLoc: { value: breakLoc },
continueLoc: { value: continueLoc },
label: { value: label }
});
}
inherits(LoopEntry, Entry);
exports.LoopEntry = LoopEntry;
function SwitchEntry(breakLoc) {
Entry.call(this);
n.Literal.assert(breakLoc);
Object.defineProperties(this, {
breakLoc: { value: breakLoc }
});
}
inherits(SwitchEntry, Entry);
exports.SwitchEntry = SwitchEntry;
function TryEntry(catchEntry, finallyEntry) {
Entry.call(this);
if (catchEntry) {
assert.ok(catchEntry instanceof CatchEntry);
} else {
catchEntry = null;
}
if (finallyEntry) {
assert.ok(finallyEntry instanceof FinallyEntry);
} else {
finallyEntry = null;
}
Object.defineProperties(this, {
catchEntry: { value: catchEntry },
finallyEntry: { value: finallyEntry }
});
}
inherits(TryEntry, Entry);
exports.TryEntry = TryEntry;
function CatchEntry(firstLoc, paramId) {
Entry.call(this);
n.Literal.assert(firstLoc);
n.Identifier.assert(paramId);
Object.defineProperties(this, {
firstLoc: { value: firstLoc },
paramId: { value: paramId }
});
}
inherits(CatchEntry, Entry);
exports.CatchEntry = CatchEntry;
function FinallyEntry(firstLoc, nextLocTempVar) {
Entry.call(this);
n.Literal.assert(firstLoc);
n.Identifier.assert(nextLocTempVar);
Object.defineProperties(this, {
firstLoc: { value: firstLoc },
nextLocTempVar: { value: nextLocTempVar }
});
}
inherits(FinallyEntry, Entry);
exports.FinallyEntry = FinallyEntry;
function LeapManager(emitter) {
assert.ok(this instanceof LeapManager);
var Emitter = require("./emit").Emitter;
assert.ok(emitter instanceof Emitter);
Object.defineProperties(this, {
emitter: { value: emitter },
entryStack: {
value: [new FunctionEntry(emitter.finalLoc)]
}
});
}
var LMp = LeapManager.prototype;
exports.LeapManager = LeapManager;
LMp.withEntry = function(entry, callback) {
assert.ok(entry instanceof Entry);
this.entryStack.push(entry);
try {
callback.call(this.emitter);
} finally {
var popped = this.entryStack.pop();
assert.strictEqual(popped, entry);
}
};
LMp._leapToEntry = function(predicate, defaultLoc) {
var entry, loc;
var finallyEntries = [];
var skipNextTryEntry = null;
for (var i = this.entryStack.length - 1; i >= 0; --i) {
entry = this.entryStack[i];
if (entry instanceof CatchEntry ||
entry instanceof FinallyEntry) {
// If we are inside of a catch or finally block, then we must
// have exited the try block already, so we shouldn't consider
// the next TryStatement as a handler for this throw.
skipNextTryEntry = entry;
} else if (entry instanceof TryEntry) {
if (skipNextTryEntry) {
// If an exception was thrown from inside a catch block and this
// try statement has a finally block, make sure we execute that
// finally block.
if (skipNextTryEntry instanceof CatchEntry &&
entry.finallyEntry) {
finallyEntries.push(entry.finallyEntry);
}
skipNextTryEntry = null;
} else if ((loc = predicate.call(this, entry))) {
break;
} else if (entry.finallyEntry) {
finallyEntries.push(entry.finallyEntry);
}
} else if ((loc = predicate.call(this, entry))) {
break;
}
}
if (loc) {
// fall through
} else if (defaultLoc) {
loc = defaultLoc;
} else {
return null;
}
n.Literal.assert(loc);
var finallyEntry;
while ((finallyEntry = finallyEntries.pop())) {
this.emitter.emitAssign(finallyEntry.nextLocTempVar, loc);
loc = finallyEntry.firstLoc;
}
return loc;
};
function getLeapLocation(entry, property, label) {
var loc = entry[property];
if (loc) {
if (label) {
if (entry.label &&
entry.label.name === label.name) {
return loc;
}
} else {
return loc;
}
}
return null;
}
LMp.emitBreak = function(label) {
var loc = this._leapToEntry(function(entry) {
return getLeapLocation(entry, "breakLoc", label);
});
if (loc === null) {
throw new Error("illegal break statement");
}
this.emitter.clearPendingException();
this.emitter.jump(loc);
};
LMp.emitContinue = function(label) {
var loc = this._leapToEntry(function(entry) {
return getLeapLocation(entry, "continueLoc", label);
});
if (loc === null) {
throw new Error("illegal continue statement");
}
this.emitter.clearPendingException();
this.emitter.jump(loc);
};
| LoopEntry | identifier_name |
leap.js | /**
* Copyright (c) 2013, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
var assert = require("assert");
var types = require("ast-types");
var n = types.namedTypes;
var b = types.builders;
var inherits = require("util").inherits;
function Entry() {
assert.ok(this instanceof Entry);
}
function FunctionEntry(returnLoc) {
Entry.call(this);
n.Literal.assert(returnLoc);
Object.defineProperties(this, {
returnLoc: { value: returnLoc }
});
}
inherits(FunctionEntry, Entry);
exports.FunctionEntry = FunctionEntry;
function LoopEntry(breakLoc, continueLoc, label) {
Entry.call(this);
n.Literal.assert(breakLoc);
n.Literal.assert(continueLoc);
if (label) {
n.Identifier.assert(label);
} else {
label = null;
}
Object.defineProperties(this, {
breakLoc: { value: breakLoc },
continueLoc: { value: continueLoc },
label: { value: label }
});
}
inherits(LoopEntry, Entry);
exports.LoopEntry = LoopEntry;
function SwitchEntry(breakLoc) {
Entry.call(this);
n.Literal.assert(breakLoc);
Object.defineProperties(this, {
breakLoc: { value: breakLoc }
});
}
inherits(SwitchEntry, Entry);
exports.SwitchEntry = SwitchEntry;
function TryEntry(catchEntry, finallyEntry) |
inherits(TryEntry, Entry);
exports.TryEntry = TryEntry;
function CatchEntry(firstLoc, paramId) {
Entry.call(this);
n.Literal.assert(firstLoc);
n.Identifier.assert(paramId);
Object.defineProperties(this, {
firstLoc: { value: firstLoc },
paramId: { value: paramId }
});
}
inherits(CatchEntry, Entry);
exports.CatchEntry = CatchEntry;
function FinallyEntry(firstLoc, nextLocTempVar) {
Entry.call(this);
n.Literal.assert(firstLoc);
n.Identifier.assert(nextLocTempVar);
Object.defineProperties(this, {
firstLoc: { value: firstLoc },
nextLocTempVar: { value: nextLocTempVar }
});
}
inherits(FinallyEntry, Entry);
exports.FinallyEntry = FinallyEntry;
function LeapManager(emitter) {
assert.ok(this instanceof LeapManager);
var Emitter = require("./emit").Emitter;
assert.ok(emitter instanceof Emitter);
Object.defineProperties(this, {
emitter: { value: emitter },
entryStack: {
value: [new FunctionEntry(emitter.finalLoc)]
}
});
}
var LMp = LeapManager.prototype;
exports.LeapManager = LeapManager;
LMp.withEntry = function(entry, callback) {
assert.ok(entry instanceof Entry);
this.entryStack.push(entry);
try {
callback.call(this.emitter);
} finally {
var popped = this.entryStack.pop();
assert.strictEqual(popped, entry);
}
};
LMp._leapToEntry = function(predicate, defaultLoc) {
var entry, loc;
var finallyEntries = [];
var skipNextTryEntry = null;
for (var i = this.entryStack.length - 1; i >= 0; --i) {
entry = this.entryStack[i];
if (entry instanceof CatchEntry ||
entry instanceof FinallyEntry) {
// If we are inside of a catch or finally block, then we must
// have exited the try block already, so we shouldn't consider
// the next TryStatement as a handler for this throw.
skipNextTryEntry = entry;
} else if (entry instanceof TryEntry) {
if (skipNextTryEntry) {
// If an exception was thrown from inside a catch block and this
// try statement has a finally block, make sure we execute that
// finally block.
if (skipNextTryEntry instanceof CatchEntry &&
entry.finallyEntry) {
finallyEntries.push(entry.finallyEntry);
}
skipNextTryEntry = null;
} else if ((loc = predicate.call(this, entry))) {
break;
} else if (entry.finallyEntry) {
finallyEntries.push(entry.finallyEntry);
}
} else if ((loc = predicate.call(this, entry))) {
break;
}
}
if (loc) {
// fall through
} else if (defaultLoc) {
loc = defaultLoc;
} else {
return null;
}
n.Literal.assert(loc);
var finallyEntry;
while ((finallyEntry = finallyEntries.pop())) {
this.emitter.emitAssign(finallyEntry.nextLocTempVar, loc);
loc = finallyEntry.firstLoc;
}
return loc;
};
function getLeapLocation(entry, property, label) {
var loc = entry[property];
if (loc) {
if (label) {
if (entry.label &&
entry.label.name === label.name) {
return loc;
}
} else {
return loc;
}
}
return null;
}
LMp.emitBreak = function(label) {
var loc = this._leapToEntry(function(entry) {
return getLeapLocation(entry, "breakLoc", label);
});
if (loc === null) {
throw new Error("illegal break statement");
}
this.emitter.clearPendingException();
this.emitter.jump(loc);
};
LMp.emitContinue = function(label) {
var loc = this._leapToEntry(function(entry) {
return getLeapLocation(entry, "continueLoc", label);
});
if (loc === null) {
throw new Error("illegal continue statement");
}
this.emitter.clearPendingException();
this.emitter.jump(loc);
};
| {
Entry.call(this);
if (catchEntry) {
assert.ok(catchEntry instanceof CatchEntry);
} else {
catchEntry = null;
}
if (finallyEntry) {
assert.ok(finallyEntry instanceof FinallyEntry);
} else {
finallyEntry = null;
}
Object.defineProperties(this, {
catchEntry: { value: catchEntry },
finallyEntry: { value: finallyEntry }
});
} | identifier_body |
test_users.py | # Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from lxml import etree
from nova.api.openstack.compute.contrib import users
from nova.auth.manager import User, Project
from nova import test
from nova.tests.api.openstack import fakes
from nova import utils
def fake_init(self):
|
class UsersTest(test.TestCase):
def setUp(self):
super(UsersTest, self).setUp()
self.flags(verbose=True)
self.stubs.Set(users.Controller, '__init__',
fake_init)
fakes.FakeAuthManager.clear_fakes()
fakes.FakeAuthManager.projects = dict(testacct=Project('testacct',
'testacct',
'id1',
'test',
[]))
fakes.FakeAuthDatabase.data = {}
fakes.stub_out_networking(self.stubs)
fakes.stub_out_rate_limiting(self.stubs)
fakes.stub_out_auth(self.stubs)
fakemgr = fakes.FakeAuthManager()
fakemgr.add_user(User('id1', 'guy1', 'acc1', 'secret1', False))
fakemgr.add_user(User('id2', 'guy2', 'acc2', 'secret2', True))
self.controller = users.Controller()
def test_get_user_list(self):
req = fakes.HTTPRequest.blank('/v2/fake/users')
res_dict = self.controller.index(req)
self.assertEqual(len(res_dict['users']), 2)
def test_get_user_by_id(self):
req = fakes.HTTPRequest.blank('/v2/fake/users/id2')
res_dict = self.controller.show(req, 'id2')
self.assertEqual(res_dict['user']['id'], 'id2')
self.assertEqual(res_dict['user']['name'], 'guy2')
self.assertEqual(res_dict['user']['secret'], 'secret2')
self.assertEqual(res_dict['user']['admin'], True)
def test_user_delete(self):
req = fakes.HTTPRequest.blank('/v2/fake/users/id1')
self.controller.delete(req, 'id1')
self.assertTrue('id1' not in [u.id for u in
fakes.FakeAuthManager.auth_data])
def test_user_create(self):
secret = utils.generate_password()
body = dict(user=dict(name='test_guy',
access='acc3',
secret=secret,
admin=True))
req = fakes.HTTPRequest.blank('/v2/fake/users')
res_dict = self.controller.create(req, body)
# NOTE(justinsb): This is a questionable assertion in general
# fake sets id=name, but others might not...
self.assertEqual(res_dict['user']['id'], 'test_guy')
self.assertEqual(res_dict['user']['name'], 'test_guy')
self.assertEqual(res_dict['user']['access'], 'acc3')
self.assertEqual(res_dict['user']['secret'], secret)
self.assertEqual(res_dict['user']['admin'], True)
self.assertTrue('test_guy' in [u.id for u in
fakes.FakeAuthManager.auth_data])
self.assertEqual(len(fakes.FakeAuthManager.auth_data), 3)
def test_user_update(self):
new_secret = utils.generate_password()
body = dict(user=dict(name='guy2',
access='acc2',
secret=new_secret))
req = fakes.HTTPRequest.blank('/v2/fake/users/id2')
res_dict = self.controller.update(req, 'id2', body)
self.assertEqual(res_dict['user']['id'], 'id2')
self.assertEqual(res_dict['user']['name'], 'guy2')
self.assertEqual(res_dict['user']['access'], 'acc2')
self.assertEqual(res_dict['user']['secret'], new_secret)
self.assertEqual(res_dict['user']['admin'], True)
class TestUsersXMLSerializer(test.TestCase):
def test_index(self):
serializer = users.UsersTemplate()
fixture = {'users': [{'id': 'id1',
'name': 'guy1',
'secret': 'secret1',
'admin': False},
{'id': 'id2',
'name': 'guy2',
'secret': 'secret2',
'admin': True}]}
output = serializer.serialize(fixture)
res_tree = etree.XML(output)
self.assertEqual(res_tree.tag, 'users')
self.assertEqual(len(res_tree), 2)
self.assertEqual(res_tree[0].tag, 'user')
self.assertEqual(res_tree[0].get('id'), 'id1')
self.assertEqual(res_tree[1].tag, 'user')
self.assertEqual(res_tree[1].get('id'), 'id2')
def test_show(self):
serializer = users.UserTemplate()
fixture = {'user': {'id': 'id2',
'name': 'guy2',
'secret': 'secret2',
'admin': True}}
output = serializer.serialize(fixture)
res_tree = etree.XML(output)
self.assertEqual(res_tree.tag, 'user')
self.assertEqual(res_tree.get('id'), 'id2')
self.assertEqual(res_tree.get('name'), 'guy2')
self.assertEqual(res_tree.get('secret'), 'secret2')
self.assertEqual(res_tree.get('admin'), 'True')
| self.manager = fakes.FakeAuthManager() | identifier_body |
test_users.py | # Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from lxml import etree
from nova.api.openstack.compute.contrib import users
from nova.auth.manager import User, Project
from nova import test
from nova.tests.api.openstack import fakes
from nova import utils
def fake_init(self):
self.manager = fakes.FakeAuthManager()
class UsersTest(test.TestCase):
def setUp(self):
super(UsersTest, self).setUp()
self.flags(verbose=True)
self.stubs.Set(users.Controller, '__init__',
fake_init)
fakes.FakeAuthManager.clear_fakes()
fakes.FakeAuthManager.projects = dict(testacct=Project('testacct',
'testacct',
'id1',
'test',
[]))
fakes.FakeAuthDatabase.data = {}
fakes.stub_out_networking(self.stubs)
fakes.stub_out_rate_limiting(self.stubs)
fakes.stub_out_auth(self.stubs)
fakemgr = fakes.FakeAuthManager()
fakemgr.add_user(User('id1', 'guy1', 'acc1', 'secret1', False))
fakemgr.add_user(User('id2', 'guy2', 'acc2', 'secret2', True))
self.controller = users.Controller()
def test_get_user_list(self):
req = fakes.HTTPRequest.blank('/v2/fake/users')
res_dict = self.controller.index(req)
self.assertEqual(len(res_dict['users']), 2)
def test_get_user_by_id(self):
req = fakes.HTTPRequest.blank('/v2/fake/users/id2')
res_dict = self.controller.show(req, 'id2')
self.assertEqual(res_dict['user']['id'], 'id2')
self.assertEqual(res_dict['user']['name'], 'guy2')
self.assertEqual(res_dict['user']['secret'], 'secret2')
self.assertEqual(res_dict['user']['admin'], True)
def test_user_delete(self):
req = fakes.HTTPRequest.blank('/v2/fake/users/id1')
self.controller.delete(req, 'id1')
self.assertTrue('id1' not in [u.id for u in
fakes.FakeAuthManager.auth_data])
def test_user_create(self):
secret = utils.generate_password()
body = dict(user=dict(name='test_guy',
access='acc3',
secret=secret,
admin=True))
req = fakes.HTTPRequest.blank('/v2/fake/users')
res_dict = self.controller.create(req, body)
# NOTE(justinsb): This is a questionable assertion in general
# fake sets id=name, but others might not...
self.assertEqual(res_dict['user']['id'], 'test_guy')
self.assertEqual(res_dict['user']['name'], 'test_guy')
self.assertEqual(res_dict['user']['access'], 'acc3')
self.assertEqual(res_dict['user']['secret'], secret)
self.assertEqual(res_dict['user']['admin'], True)
self.assertTrue('test_guy' in [u.id for u in
fakes.FakeAuthManager.auth_data])
self.assertEqual(len(fakes.FakeAuthManager.auth_data), 3)
def test_user_update(self):
new_secret = utils.generate_password()
body = dict(user=dict(name='guy2',
access='acc2',
secret=new_secret))
req = fakes.HTTPRequest.blank('/v2/fake/users/id2')
res_dict = self.controller.update(req, 'id2', body)
self.assertEqual(res_dict['user']['id'], 'id2')
self.assertEqual(res_dict['user']['name'], 'guy2')
self.assertEqual(res_dict['user']['access'], 'acc2')
self.assertEqual(res_dict['user']['secret'], new_secret)
self.assertEqual(res_dict['user']['admin'], True)
class TestUsersXMLSerializer(test.TestCase):
def | (self):
serializer = users.UsersTemplate()
fixture = {'users': [{'id': 'id1',
'name': 'guy1',
'secret': 'secret1',
'admin': False},
{'id': 'id2',
'name': 'guy2',
'secret': 'secret2',
'admin': True}]}
output = serializer.serialize(fixture)
res_tree = etree.XML(output)
self.assertEqual(res_tree.tag, 'users')
self.assertEqual(len(res_tree), 2)
self.assertEqual(res_tree[0].tag, 'user')
self.assertEqual(res_tree[0].get('id'), 'id1')
self.assertEqual(res_tree[1].tag, 'user')
self.assertEqual(res_tree[1].get('id'), 'id2')
def test_show(self):
serializer = users.UserTemplate()
fixture = {'user': {'id': 'id2',
'name': 'guy2',
'secret': 'secret2',
'admin': True}}
output = serializer.serialize(fixture)
res_tree = etree.XML(output)
self.assertEqual(res_tree.tag, 'user')
self.assertEqual(res_tree.get('id'), 'id2')
self.assertEqual(res_tree.get('name'), 'guy2')
self.assertEqual(res_tree.get('secret'), 'secret2')
self.assertEqual(res_tree.get('admin'), 'True')
| test_index | identifier_name |
test_users.py | # Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from lxml import etree
from nova.api.openstack.compute.contrib import users
from nova.auth.manager import User, Project
from nova import test
from nova.tests.api.openstack import fakes
from nova import utils
def fake_init(self):
self.manager = fakes.FakeAuthManager()
class UsersTest(test.TestCase):
def setUp(self):
super(UsersTest, self).setUp()
self.flags(verbose=True)
self.stubs.Set(users.Controller, '__init__',
fake_init)
fakes.FakeAuthManager.clear_fakes()
fakes.FakeAuthManager.projects = dict(testacct=Project('testacct',
'testacct',
'id1',
'test',
[]))
fakes.FakeAuthDatabase.data = {}
fakes.stub_out_networking(self.stubs)
fakes.stub_out_rate_limiting(self.stubs)
fakes.stub_out_auth(self.stubs)
fakemgr = fakes.FakeAuthManager()
fakemgr.add_user(User('id1', 'guy1', 'acc1', 'secret1', False))
fakemgr.add_user(User('id2', 'guy2', 'acc2', 'secret2', True))
self.controller = users.Controller()
def test_get_user_list(self):
req = fakes.HTTPRequest.blank('/v2/fake/users')
res_dict = self.controller.index(req)
self.assertEqual(len(res_dict['users']), 2)
def test_get_user_by_id(self):
req = fakes.HTTPRequest.blank('/v2/fake/users/id2')
res_dict = self.controller.show(req, 'id2')
self.assertEqual(res_dict['user']['id'], 'id2')
self.assertEqual(res_dict['user']['name'], 'guy2')
self.assertEqual(res_dict['user']['secret'], 'secret2')
self.assertEqual(res_dict['user']['admin'], True)
def test_user_delete(self):
req = fakes.HTTPRequest.blank('/v2/fake/users/id1')
self.controller.delete(req, 'id1') | def test_user_create(self):
secret = utils.generate_password()
body = dict(user=dict(name='test_guy',
access='acc3',
secret=secret,
admin=True))
req = fakes.HTTPRequest.blank('/v2/fake/users')
res_dict = self.controller.create(req, body)
# NOTE(justinsb): This is a questionable assertion in general
# fake sets id=name, but others might not...
self.assertEqual(res_dict['user']['id'], 'test_guy')
self.assertEqual(res_dict['user']['name'], 'test_guy')
self.assertEqual(res_dict['user']['access'], 'acc3')
self.assertEqual(res_dict['user']['secret'], secret)
self.assertEqual(res_dict['user']['admin'], True)
self.assertTrue('test_guy' in [u.id for u in
fakes.FakeAuthManager.auth_data])
self.assertEqual(len(fakes.FakeAuthManager.auth_data), 3)
def test_user_update(self):
new_secret = utils.generate_password()
body = dict(user=dict(name='guy2',
access='acc2',
secret=new_secret))
req = fakes.HTTPRequest.blank('/v2/fake/users/id2')
res_dict = self.controller.update(req, 'id2', body)
self.assertEqual(res_dict['user']['id'], 'id2')
self.assertEqual(res_dict['user']['name'], 'guy2')
self.assertEqual(res_dict['user']['access'], 'acc2')
self.assertEqual(res_dict['user']['secret'], new_secret)
self.assertEqual(res_dict['user']['admin'], True)
class TestUsersXMLSerializer(test.TestCase):
def test_index(self):
serializer = users.UsersTemplate()
fixture = {'users': [{'id': 'id1',
'name': 'guy1',
'secret': 'secret1',
'admin': False},
{'id': 'id2',
'name': 'guy2',
'secret': 'secret2',
'admin': True}]}
output = serializer.serialize(fixture)
res_tree = etree.XML(output)
self.assertEqual(res_tree.tag, 'users')
self.assertEqual(len(res_tree), 2)
self.assertEqual(res_tree[0].tag, 'user')
self.assertEqual(res_tree[0].get('id'), 'id1')
self.assertEqual(res_tree[1].tag, 'user')
self.assertEqual(res_tree[1].get('id'), 'id2')
def test_show(self):
serializer = users.UserTemplate()
fixture = {'user': {'id': 'id2',
'name': 'guy2',
'secret': 'secret2',
'admin': True}}
output = serializer.serialize(fixture)
res_tree = etree.XML(output)
self.assertEqual(res_tree.tag, 'user')
self.assertEqual(res_tree.get('id'), 'id2')
self.assertEqual(res_tree.get('name'), 'guy2')
self.assertEqual(res_tree.get('secret'), 'secret2')
self.assertEqual(res_tree.get('admin'), 'True') |
self.assertTrue('id1' not in [u.id for u in
fakes.FakeAuthManager.auth_data])
| random_line_split |
electronTypes.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// #######################################################################
// ### ###
// ### electron.d.ts types we need in a common layer for reuse ###
// ### (copied from Electron 11.x) ###
// ### ###
// #######################################################################
export interface MessageBoxOptions {
/**
* Content of the message box.
*/
message: string;
/**
* Can be `"none"`, `"info"`, `"error"`, `"question"` or `"warning"`. On Windows,
* `"question"` displays the same icon as `"info"`, unless you set an icon using
* the `"icon"` option. On macOS, both `"warning"` and `"error"` display the same
* warning icon.
*/
type?: string;
/**
* Array of texts for buttons. On Windows, an empty array will result in one button
* labeled "OK".
*/
buttons?: string[];
/**
* Index of the button in the buttons array which will be selected by default when
* the message box opens.
*/
defaultId?: number;
/**
* Title of the message box, some platforms will not show it.
*/
title?: string;
/**
* Extra information of the message.
*/
detail?: string;
/**
* If provided, the message box will include a checkbox with the given label.
*/
checkboxLabel?: string;
/**
* Initial checked state of the checkbox. `false` by default.
*/
checkboxChecked?: boolean;
// icon?: NativeImage;
/**
* The index of the button to be used to cancel the dialog, via the `Esc` key. By
* default this is assigned to the first button with "cancel" or "no" as the label.
* If no such labeled buttons exist and this option is not set, `0` will be used as
* the return value.
*/
cancelId?: number;
/**
* On Windows Electron will try to figure out which one of the `buttons` are common
* buttons (like "Cancel" or "Yes"), and show the others as command links in the
* dialog. This can make the dialog appear in the style of modern Windows apps. If
* you don't like this behavior, you can set `noLink` to `true`.
*/
noLink?: boolean;
/**
* Normalize the keyboard access keys across platforms. Default is `false`.
* Enabling this assumes `&` is used in the button labels for the placement of the
* keyboard shortcut access key and labels will be converted so they work correctly
* on each platform, `&` characters are removed on macOS, converted to `_` on
* Linux, and left untouched on Windows. For example, a button label of `Vie&w`
* will be converted to `Vie_w` on Linux and `View` on macOS and can be selected
* via `Alt-W` on Windows and Linux.
*/
normalizeAccessKeys?: boolean;
}
export interface MessageBoxReturnValue {
/**
* The index of the clicked button.
*/
response: number; |
export interface OpenDevToolsOptions {
/**
* Opens the devtools with specified dock state, can be `right`, `bottom`,
* `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's
* possible to dock back. In `detach` mode it's not.
*/
mode: ('right' | 'bottom' | 'undocked' | 'detach');
/**
* Whether to bring the opened devtools window to the foreground. The default is
* `true`.
*/
activate?: boolean;
}
export interface SaveDialogOptions {
title?: string;
/**
* Absolute directory path, absolute file path, or file name to use by default.
*/
defaultPath?: string;
/**
* Custom label for the confirmation button, when left empty the default label will
* be used.
*/
buttonLabel?: string;
filters?: FileFilter[];
/**
* Message to display above text fields.
*
* @platform darwin
*/
message?: string;
/**
* Custom label for the text displayed in front of the filename text field.
*
* @platform darwin
*/
nameFieldLabel?: string;
/**
* Show the tags input box, defaults to `true`.
*
* @platform darwin
*/
showsTagField?: boolean;
properties?: Array<'showHiddenFiles' | 'createDirectory' | 'treatPackageAsDirectory' | 'showOverwriteConfirmation' | 'dontAddToRecent'>;
/**
* Create a security scoped bookmark when packaged for the Mac App Store. If this
* option is enabled and the file doesn't already exist a blank file will be
* created at the chosen path.
*
* @platform darwin,mas
*/
securityScopedBookmarks?: boolean;
}
export interface OpenDialogOptions {
title?: string;
defaultPath?: string;
/**
* Custom label for the confirmation button, when left empty the default label will
* be used.
*/
buttonLabel?: string;
filters?: FileFilter[];
/**
* Contains which features the dialog should use. The following values are
* supported:
*/
properties?: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'showHiddenFiles' | 'createDirectory' | 'promptToCreate' | 'noResolveAliases' | 'treatPackageAsDirectory' | 'dontAddToRecent'>;
/**
* Message to display above input boxes.
*
* @platform darwin
*/
message?: string;
/**
* Create security scoped bookmarks when packaged for the Mac App Store.
*
* @platform darwin,mas
*/
securityScopedBookmarks?: boolean;
}
export interface OpenDialogReturnValue {
/**
* whether or not the dialog was canceled.
*/
canceled: boolean;
/**
* An array of file paths chosen by the user. If the dialog is cancelled this will
* be an empty array.
*/
filePaths: string[];
/**
* An array matching the `filePaths` array of base64 encoded strings which contains
* security scoped bookmark data. `securityScopedBookmarks` must be enabled for
* this to be populated. (For return values, see table here.)
*
* @platform darwin,mas
*/
bookmarks?: string[];
}
export interface SaveDialogReturnValue {
/**
* whether or not the dialog was canceled.
*/
canceled: boolean;
/**
* If the dialog is canceled, this will be `undefined`.
*/
filePath?: string;
/**
* Base64 encoded string which contains the security scoped bookmark data for the
* saved file. `securityScopedBookmarks` must be enabled for this to be present.
* (For return values, see table here.)
*
* @platform darwin,mas
*/
bookmark?: string;
}
export interface FileFilter {
// Docs: https://electronjs.org/docs/api/structures/file-filter
extensions: string[];
name: string;
}
export interface InputEvent {
// Docs: https://electronjs.org/docs/api/structures/input-event
/**
* An array of modifiers of the event, can be `shift`, `control`, `ctrl`, `alt`,
* `meta`, `command`, `cmd`, `isKeypad`, `isAutoRepeat`, `leftButtonDown`,
* `middleButtonDown`, `rightButtonDown`, `capsLock`, `numLock`, `left`, `right`.
*/
modifiers?: Array<'shift' | 'control' | 'ctrl' | 'alt' | 'meta' | 'command' | 'cmd' | 'isKeypad' | 'isAutoRepeat' | 'leftButtonDown' | 'middleButtonDown' | 'rightButtonDown' | 'capsLock' | 'numLock' | 'left' | 'right'>;
}
export interface MouseInputEvent extends InputEvent {
// Docs: https://electronjs.org/docs/api/structures/mouse-input-event
/**
* The button pressed, can be `left`, `middle`, `right`.
*/
button?: ('left' | 'middle' | 'right');
clickCount?: number;
globalX?: number;
globalY?: number;
movementX?: number;
movementY?: number;
/**
* The type of the event, can be `mouseDown`, `mouseUp`, `mouseEnter`,
* `mouseLeave`, `contextMenu`, `mouseWheel` or `mouseMove`.
*/
type: ('mouseDown' | 'mouseUp' | 'mouseEnter' | 'mouseLeave' | 'contextMenu' | 'mouseWheel' | 'mouseMove');
x: number;
y: number;
} | /**
* The checked state of the checkbox if `checkboxLabel` was set. Otherwise `false`.
*/
checkboxChecked: boolean;
} | random_line_split |
lib.rs | //! Implementation of Rust panics via process aborts
//!
//! When compared to the implementation via unwinding, this crate is *much*
//! simpler! That being said, it's not quite as versatile, but here goes!
#![no_std]
#![unstable(feature = "panic_abort", issue = "32837")]
#![doc(issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
#![panic_runtime]
#![allow(unused_features)]
#![feature(core_intrinsics)]
#![feature(nll)]
#![feature(panic_runtime)]
#![feature(std_internals)]
#![feature(staged_api)]
#![feature(rustc_attrs)]
#![feature(asm)]
#![feature(c_unwind)]
#[cfg(target_os = "android")]
mod android;
use core::any::Any;
use core::panic::BoxMeUp;
#[rustc_std_internal_symbol]
#[allow(improper_ctypes_definitions)]
pub unsafe extern "C" fn __rust_panic_cleanup(_: *mut u8) -> *mut (dyn Any + Send + 'static) {
unreachable!()
}
// "Leak" the payload and shim to the relevant abort on the platform in question.
#[rustc_std_internal_symbol]
pub unsafe extern "C-unwind" fn __rust_start_panic(_payload: *mut &mut dyn BoxMeUp) -> u32 {
// Android has the ability to attach a message as part of the abort.
#[cfg(target_os = "android")]
android::android_set_abort_message(_payload);
abort();
| } else if #[cfg(any(target_os = "hermit",
all(target_vendor = "fortanix", target_env = "sgx")
))] {
unsafe fn abort() -> ! {
// call std::sys::abort_internal
extern "C" {
pub fn __rust_abort() -> !;
}
__rust_abort();
}
} else if #[cfg(all(windows, not(miri)))] {
// On Windows, use the processor-specific __fastfail mechanism. In Windows 8
// and later, this will terminate the process immediately without running any
// in-process exception handlers. In earlier versions of Windows, this
// sequence of instructions will be treated as an access violation,
// terminating the process but without necessarily bypassing all exception
// handlers.
//
// https://docs.microsoft.com/en-us/cpp/intrinsics/fastfail
//
// Note: this is the same implementation as in libstd's `abort_internal`
unsafe fn abort() -> ! {
const FAST_FAIL_FATAL_APP_EXIT: usize = 7;
cfg_if::cfg_if! {
if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
asm!("int $$0x29", in("ecx") FAST_FAIL_FATAL_APP_EXIT);
} else if #[cfg(all(target_arch = "arm", target_feature = "thumb-mode"))] {
asm!(".inst 0xDEFB", in("r0") FAST_FAIL_FATAL_APP_EXIT);
} else if #[cfg(target_arch = "aarch64")] {
asm!("brk 0xF003", in("x0") FAST_FAIL_FATAL_APP_EXIT);
} else {
core::intrinsics::abort();
}
}
core::intrinsics::unreachable();
}
} else {
unsafe fn abort() -> ! {
core::intrinsics::abort();
}
}
}
}
// This... is a bit of an oddity. The tl;dr; is that this is required to link
// correctly, the longer explanation is below.
//
// Right now the binaries of libcore/libstd that we ship are all compiled with
// `-C panic=unwind`. This is done to ensure that the binaries are maximally
// compatible with as many situations as possible. The compiler, however,
// requires a "personality function" for all functions compiled with `-C
// panic=unwind`. This personality function is hardcoded to the symbol
// `rust_eh_personality` and is defined by the `eh_personality` lang item.
//
// So... why not just define that lang item here? Good question! The way that
// panic runtimes are linked in is actually a little subtle in that they're
// "sort of" in the compiler's crate store, but only actually linked if another
// isn't actually linked. This ends up meaning that both this crate and the
// panic_unwind crate can appear in the compiler's crate store, and if both
// define the `eh_personality` lang item then that'll hit an error.
//
// To handle this the compiler only requires the `eh_personality` is defined if
// the panic runtime being linked in is the unwinding runtime, and otherwise
// it's not required to be defined (rightfully so). In this case, however, this
// library just defines this symbol so there's at least some personality
// somewhere.
//
// Essentially this symbol is just defined to get wired up to libcore/libstd
// binaries, but it should never be called as we don't link in an unwinding
// runtime at all.
pub mod personalities {
#[rustc_std_internal_symbol]
#[cfg(not(any(
all(target_arch = "wasm32", not(target_os = "emscripten"),),
all(target_os = "windows", target_env = "gnu", target_arch = "x86_64",),
)))]
pub extern "C" fn rust_eh_personality() {}
// On x86_64-pc-windows-gnu we use our own personality function that needs
// to return `ExceptionContinueSearch` as we're passing on all our frames.
#[rustc_std_internal_symbol]
#[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86_64"))]
pub extern "C" fn rust_eh_personality(
_record: usize,
_frame: usize,
_context: usize,
_dispatcher: usize,
) -> u32 {
1 // `ExceptionContinueSearch`
}
// Similar to above, this corresponds to the `eh_catch_typeinfo` lang item
// that's only used on Emscripten currently.
//
// Since panics don't generate exceptions and foreign exceptions are
// currently UB with -C panic=abort (although this may be subject to
// change), any catch_unwind calls will never use this typeinfo.
#[rustc_std_internal_symbol]
#[allow(non_upper_case_globals)]
#[cfg(target_os = "emscripten")]
static rust_eh_catch_typeinfo: [usize; 2] = [0; 2];
// These two are called by our startup objects on i686-pc-windows-gnu, but
// they don't need to do anything so the bodies are nops.
#[rustc_std_internal_symbol]
#[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86"))]
pub extern "C" fn rust_eh_register_frames() {}
#[rustc_std_internal_symbol]
#[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86"))]
pub extern "C" fn rust_eh_unregister_frames() {}
} | cfg_if::cfg_if! {
if #[cfg(unix)] {
unsafe fn abort() -> ! {
libc::abort();
} | random_line_split |
lib.rs | //! Implementation of Rust panics via process aborts
//!
//! When compared to the implementation via unwinding, this crate is *much*
//! simpler! That being said, it's not quite as versatile, but here goes!
#![no_std]
#![unstable(feature = "panic_abort", issue = "32837")]
#![doc(issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
#![panic_runtime]
#![allow(unused_features)]
#![feature(core_intrinsics)]
#![feature(nll)]
#![feature(panic_runtime)]
#![feature(std_internals)]
#![feature(staged_api)]
#![feature(rustc_attrs)]
#![feature(asm)]
#![feature(c_unwind)]
#[cfg(target_os = "android")]
mod android;
use core::any::Any;
use core::panic::BoxMeUp;
#[rustc_std_internal_symbol]
#[allow(improper_ctypes_definitions)]
pub unsafe extern "C" fn __rust_panic_cleanup(_: *mut u8) -> *mut (dyn Any + Send + 'static) |
// "Leak" the payload and shim to the relevant abort on the platform in question.
#[rustc_std_internal_symbol]
pub unsafe extern "C-unwind" fn __rust_start_panic(_payload: *mut &mut dyn BoxMeUp) -> u32 {
// Android has the ability to attach a message as part of the abort.
#[cfg(target_os = "android")]
android::android_set_abort_message(_payload);
abort();
cfg_if::cfg_if! {
if #[cfg(unix)] {
unsafe fn abort() -> ! {
libc::abort();
}
} else if #[cfg(any(target_os = "hermit",
all(target_vendor = "fortanix", target_env = "sgx")
))] {
unsafe fn abort() -> ! {
// call std::sys::abort_internal
extern "C" {
pub fn __rust_abort() -> !;
}
__rust_abort();
}
} else if #[cfg(all(windows, not(miri)))] {
// On Windows, use the processor-specific __fastfail mechanism. In Windows 8
// and later, this will terminate the process immediately without running any
// in-process exception handlers. In earlier versions of Windows, this
// sequence of instructions will be treated as an access violation,
// terminating the process but without necessarily bypassing all exception
// handlers.
//
// https://docs.microsoft.com/en-us/cpp/intrinsics/fastfail
//
// Note: this is the same implementation as in libstd's `abort_internal`
unsafe fn abort() -> ! {
const FAST_FAIL_FATAL_APP_EXIT: usize = 7;
cfg_if::cfg_if! {
if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
asm!("int $$0x29", in("ecx") FAST_FAIL_FATAL_APP_EXIT);
} else if #[cfg(all(target_arch = "arm", target_feature = "thumb-mode"))] {
asm!(".inst 0xDEFB", in("r0") FAST_FAIL_FATAL_APP_EXIT);
} else if #[cfg(target_arch = "aarch64")] {
asm!("brk 0xF003", in("x0") FAST_FAIL_FATAL_APP_EXIT);
} else {
core::intrinsics::abort();
}
}
core::intrinsics::unreachable();
}
} else {
unsafe fn abort() -> ! {
core::intrinsics::abort();
}
}
}
}
// This... is a bit of an oddity. The tl;dr; is that this is required to link
// correctly, the longer explanation is below.
//
// Right now the binaries of libcore/libstd that we ship are all compiled with
// `-C panic=unwind`. This is done to ensure that the binaries are maximally
// compatible with as many situations as possible. The compiler, however,
// requires a "personality function" for all functions compiled with `-C
// panic=unwind`. This personality function is hardcoded to the symbol
// `rust_eh_personality` and is defined by the `eh_personality` lang item.
//
// So... why not just define that lang item here? Good question! The way that
// panic runtimes are linked in is actually a little subtle in that they're
// "sort of" in the compiler's crate store, but only actually linked if another
// isn't actually linked. This ends up meaning that both this crate and the
// panic_unwind crate can appear in the compiler's crate store, and if both
// define the `eh_personality` lang item then that'll hit an error.
//
// To handle this the compiler only requires the `eh_personality` is defined if
// the panic runtime being linked in is the unwinding runtime, and otherwise
// it's not required to be defined (rightfully so). In this case, however, this
// library just defines this symbol so there's at least some personality
// somewhere.
//
// Essentially this symbol is just defined to get wired up to libcore/libstd
// binaries, but it should never be called as we don't link in an unwinding
// runtime at all.
pub mod personalities {
#[rustc_std_internal_symbol]
#[cfg(not(any(
all(target_arch = "wasm32", not(target_os = "emscripten"),),
all(target_os = "windows", target_env = "gnu", target_arch = "x86_64",),
)))]
pub extern "C" fn rust_eh_personality() {}
// On x86_64-pc-windows-gnu we use our own personality function that needs
// to return `ExceptionContinueSearch` as we're passing on all our frames.
#[rustc_std_internal_symbol]
#[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86_64"))]
pub extern "C" fn rust_eh_personality(
_record: usize,
_frame: usize,
_context: usize,
_dispatcher: usize,
) -> u32 {
1 // `ExceptionContinueSearch`
}
// Similar to above, this corresponds to the `eh_catch_typeinfo` lang item
// that's only used on Emscripten currently.
//
// Since panics don't generate exceptions and foreign exceptions are
// currently UB with -C panic=abort (although this may be subject to
// change), any catch_unwind calls will never use this typeinfo.
#[rustc_std_internal_symbol]
#[allow(non_upper_case_globals)]
#[cfg(target_os = "emscripten")]
static rust_eh_catch_typeinfo: [usize; 2] = [0; 2];
// These two are called by our startup objects on i686-pc-windows-gnu, but
// they don't need to do anything so the bodies are nops.
#[rustc_std_internal_symbol]
#[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86"))]
pub extern "C" fn rust_eh_register_frames() {}
#[rustc_std_internal_symbol]
#[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86"))]
pub extern "C" fn rust_eh_unregister_frames() {}
}
| {
unreachable!()
} | identifier_body |
lib.rs | //! Implementation of Rust panics via process aborts
//!
//! When compared to the implementation via unwinding, this crate is *much*
//! simpler! That being said, it's not quite as versatile, but here goes!
#![no_std]
#![unstable(feature = "panic_abort", issue = "32837")]
#![doc(issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
#![panic_runtime]
#![allow(unused_features)]
#![feature(core_intrinsics)]
#![feature(nll)]
#![feature(panic_runtime)]
#![feature(std_internals)]
#![feature(staged_api)]
#![feature(rustc_attrs)]
#![feature(asm)]
#![feature(c_unwind)]
#[cfg(target_os = "android")]
mod android;
use core::any::Any;
use core::panic::BoxMeUp;
#[rustc_std_internal_symbol]
#[allow(improper_ctypes_definitions)]
pub unsafe extern "C" fn __rust_panic_cleanup(_: *mut u8) -> *mut (dyn Any + Send + 'static) {
unreachable!()
}
// "Leak" the payload and shim to the relevant abort on the platform in question.
#[rustc_std_internal_symbol]
pub unsafe extern "C-unwind" fn __rust_start_panic(_payload: *mut &mut dyn BoxMeUp) -> u32 {
// Android has the ability to attach a message as part of the abort.
#[cfg(target_os = "android")]
android::android_set_abort_message(_payload);
abort();
cfg_if::cfg_if! {
if #[cfg(unix)] {
unsafe fn abort() -> ! {
libc::abort();
}
} else if #[cfg(any(target_os = "hermit",
all(target_vendor = "fortanix", target_env = "sgx")
))] {
unsafe fn abort() -> ! {
// call std::sys::abort_internal
extern "C" {
pub fn __rust_abort() -> !;
}
__rust_abort();
}
} else if #[cfg(all(windows, not(miri)))] {
// On Windows, use the processor-specific __fastfail mechanism. In Windows 8
// and later, this will terminate the process immediately without running any
// in-process exception handlers. In earlier versions of Windows, this
// sequence of instructions will be treated as an access violation,
// terminating the process but without necessarily bypassing all exception
// handlers.
//
// https://docs.microsoft.com/en-us/cpp/intrinsics/fastfail
//
// Note: this is the same implementation as in libstd's `abort_internal`
unsafe fn abort() -> ! {
const FAST_FAIL_FATAL_APP_EXIT: usize = 7;
cfg_if::cfg_if! {
if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
asm!("int $$0x29", in("ecx") FAST_FAIL_FATAL_APP_EXIT);
} else if #[cfg(all(target_arch = "arm", target_feature = "thumb-mode"))] {
asm!(".inst 0xDEFB", in("r0") FAST_FAIL_FATAL_APP_EXIT);
} else if #[cfg(target_arch = "aarch64")] {
asm!("brk 0xF003", in("x0") FAST_FAIL_FATAL_APP_EXIT);
} else {
core::intrinsics::abort();
}
}
core::intrinsics::unreachable();
}
} else {
unsafe fn abort() -> ! {
core::intrinsics::abort();
}
}
}
}
// This... is a bit of an oddity. The tl;dr; is that this is required to link
// correctly, the longer explanation is below.
//
// Right now the binaries of libcore/libstd that we ship are all compiled with
// `-C panic=unwind`. This is done to ensure that the binaries are maximally
// compatible with as many situations as possible. The compiler, however,
// requires a "personality function" for all functions compiled with `-C
// panic=unwind`. This personality function is hardcoded to the symbol
// `rust_eh_personality` and is defined by the `eh_personality` lang item.
//
// So... why not just define that lang item here? Good question! The way that
// panic runtimes are linked in is actually a little subtle in that they're
// "sort of" in the compiler's crate store, but only actually linked if another
// isn't actually linked. This ends up meaning that both this crate and the
// panic_unwind crate can appear in the compiler's crate store, and if both
// define the `eh_personality` lang item then that'll hit an error.
//
// To handle this the compiler only requires the `eh_personality` is defined if
// the panic runtime being linked in is the unwinding runtime, and otherwise
// it's not required to be defined (rightfully so). In this case, however, this
// library just defines this symbol so there's at least some personality
// somewhere.
//
// Essentially this symbol is just defined to get wired up to libcore/libstd
// binaries, but it should never be called as we don't link in an unwinding
// runtime at all.
pub mod personalities {
#[rustc_std_internal_symbol]
#[cfg(not(any(
all(target_arch = "wasm32", not(target_os = "emscripten"),),
all(target_os = "windows", target_env = "gnu", target_arch = "x86_64",),
)))]
pub extern "C" fn rust_eh_personality() {}
// On x86_64-pc-windows-gnu we use our own personality function that needs
// to return `ExceptionContinueSearch` as we're passing on all our frames.
#[rustc_std_internal_symbol]
#[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86_64"))]
pub extern "C" fn rust_eh_personality(
_record: usize,
_frame: usize,
_context: usize,
_dispatcher: usize,
) -> u32 {
1 // `ExceptionContinueSearch`
}
// Similar to above, this corresponds to the `eh_catch_typeinfo` lang item
// that's only used on Emscripten currently.
//
// Since panics don't generate exceptions and foreign exceptions are
// currently UB with -C panic=abort (although this may be subject to
// change), any catch_unwind calls will never use this typeinfo.
#[rustc_std_internal_symbol]
#[allow(non_upper_case_globals)]
#[cfg(target_os = "emscripten")]
static rust_eh_catch_typeinfo: [usize; 2] = [0; 2];
// These two are called by our startup objects on i686-pc-windows-gnu, but
// they don't need to do anything so the bodies are nops.
#[rustc_std_internal_symbol]
#[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86"))]
pub extern "C" fn | () {}
#[rustc_std_internal_symbol]
#[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86"))]
pub extern "C" fn rust_eh_unregister_frames() {}
}
| rust_eh_register_frames | identifier_name |
order_by_step.js | /**
* @license
* Copyright 2015 The Lovefield Project Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. | goog.provide('lf.proc.OrderByStep');
goog.require('lf.Order');
goog.require('lf.fn');
goog.require('lf.fn.AggregatedColumn');
goog.require('lf.proc.PhysicalQueryPlanNode');
goog.require('lf.query.SelectContext');
/**
* @constructor @struct
* @extends {lf.proc.PhysicalQueryPlanNode}
*
* @param {!Array<!lf.query.SelectContext.OrderBy>} orderBy
*/
lf.proc.OrderByStep = function(orderBy) {
lf.proc.OrderByStep.base(this, 'constructor',
lf.proc.PhysicalQueryPlanNode.ANY,
lf.proc.PhysicalQueryPlanNode.ExecType.FIRST_CHILD);
/** @type {!Array<!lf.query.SelectContext.OrderBy>} */
this.orderBy = orderBy;
};
goog.inherits(lf.proc.OrderByStep, lf.proc.PhysicalQueryPlanNode);
/** @override */
lf.proc.OrderByStep.prototype.toString = function() {
return 'order_by(' +
lf.query.SelectContext.orderByToString(this.orderBy) + ')';
};
/** @override */
lf.proc.OrderByStep.prototype.execInternal = function(journal, relations) {
if (relations.length == 1) {
var distinctColumn = this.findDistinctColumn_(relations[0]);
// If such a column exists, sort the results of the lf.fn.distinct
// aggregator instead, since this is what will be used in the returned
// result.
var relationToSort = goog.isNull(distinctColumn) ?
relations[0] :
relations[0].getAggregationResult(distinctColumn);
relationToSort.entries.sort(this.entryComparatorFn_.bind(this));
} else { // if (relations.length > 1) {
relations.sort(this.relationComparatorFn_.bind(this));
}
return relations;
};
/**
* Determines whether sorting is requested on a column that has been aggregated
* with lf.fn.distinct (if any).
* @param {!lf.proc.Relation} relation The input relation.
* @return {?lf.schema.Column} The DISTINCT aggregated column or null if no such
* column was found.
* @private
*/
lf.proc.OrderByStep.prototype.findDistinctColumn_ = function(relation) {
var distinctColumn = null;
for (var i = 0; i < this.orderBy.length; i++) {
var tempDistinctColumn = lf.fn.distinct(
/** @type {!lf.schema.BaseColumn} */ (this.orderBy[i].column));
if (relation.hasAggregationResult(tempDistinctColumn)) {
distinctColumn = tempDistinctColumn;
break;
}
}
return distinctColumn;
};
/**
* @param {!function(!lf.schema.Column):*} getLeftPayload
* @param {!function(!lf.schema.Column):*} getRightPayload
* @return {number} -1 if a should precede b, 1 if b should precede a, 0 if a
* and b are determined to be equal.
* @private
*/
lf.proc.OrderByStep.prototype.comparator_ = function(
getLeftPayload, getRightPayload) {
var order = null;
var leftPayload = null;
var rightPayload = null;
var comparisonIndex = -1;
do {
comparisonIndex++;
var column = this.orderBy[comparisonIndex].column;
order = this.orderBy[comparisonIndex].order;
leftPayload = getLeftPayload(column);
rightPayload = getRightPayload(column);
} while (leftPayload == rightPayload &&
comparisonIndex + 1 < this.orderBy.length);
var result = (leftPayload < rightPayload) ? -1 :
(leftPayload > rightPayload) ? 1 : 0;
result = order == lf.Order.ASC ? result : -result;
return result;
};
/**
* Comparator function used for sorting relations.
*
* @param {!lf.proc.Relation} lhs The first operand.
* @param {!lf.proc.Relation} rhs The second operand.
* @return {number} -1 if a should precede b, 1 if b should precede a, 0 if a
* and b are determined to be equal.
* @private
*/
lf.proc.OrderByStep.prototype.relationComparatorFn_ = function(lhs, rhs) {
// NOTE: See NOTE in entryComparatorFn_ on why two separate functions are
// passed in this.comparator_ instead of using one method and binding to lhs
// and to rhs respectively.
return this.comparator_(
function(column) {
// If relations are sorted based on a non-aggregated column, choose
// the last entry of each relation as a representative row (same as
// SQLlite).
return column instanceof lf.fn.AggregatedColumn ?
lhs.getAggregationResult(column) :
lhs.entries[lhs.entries.length - 1].getField(column);
},
function(column) {
return column instanceof lf.fn.AggregatedColumn ?
rhs.getAggregationResult(column) :
rhs.entries[rhs.entries.length - 1].getField(column);
});
};
/**
* Comparator function used for sorting entries within a single relation.
*
* @param {!lf.proc.RelationEntry} lhs The first operand.
* @param {!lf.proc.RelationEntry} rhs The second operand.
* @return {number} -1 if a should precede b, 1 if b should precede a, 0 if a
* and b are determined to be equal.
* @private
*/
lf.proc.OrderByStep.prototype.entryComparatorFn_ = function(lhs, rhs) {
// NOTE: Avoiding on purpose to create a getPayload(operand, column) method
// here, and binding it once to lhs and once to rhs, because it turns out that
// Function.bind() is significantly hurting performance (measured on
// Chrome 40).
return this.comparator_(
function(column) { return lhs.getField(column); },
function(column) { return rhs.getField(column); });
}; | */ | random_line_split |
order_by_step.js | /**
* @license
* Copyright 2015 The Lovefield Project Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('lf.proc.OrderByStep');
goog.require('lf.Order');
goog.require('lf.fn');
goog.require('lf.fn.AggregatedColumn');
goog.require('lf.proc.PhysicalQueryPlanNode');
goog.require('lf.query.SelectContext');
/**
* @constructor @struct
* @extends {lf.proc.PhysicalQueryPlanNode}
*
* @param {!Array<!lf.query.SelectContext.OrderBy>} orderBy
*/
lf.proc.OrderByStep = function(orderBy) {
lf.proc.OrderByStep.base(this, 'constructor',
lf.proc.PhysicalQueryPlanNode.ANY,
lf.proc.PhysicalQueryPlanNode.ExecType.FIRST_CHILD);
/** @type {!Array<!lf.query.SelectContext.OrderBy>} */
this.orderBy = orderBy;
};
goog.inherits(lf.proc.OrderByStep, lf.proc.PhysicalQueryPlanNode);
/** @override */
lf.proc.OrderByStep.prototype.toString = function() {
return 'order_by(' +
lf.query.SelectContext.orderByToString(this.orderBy) + ')';
};
/** @override */
lf.proc.OrderByStep.prototype.execInternal = function(journal, relations) {
if (relations.length == 1) | else { // if (relations.length > 1) {
relations.sort(this.relationComparatorFn_.bind(this));
}
return relations;
};
/**
* Determines whether sorting is requested on a column that has been aggregated
* with lf.fn.distinct (if any).
* @param {!lf.proc.Relation} relation The input relation.
* @return {?lf.schema.Column} The DISTINCT aggregated column or null if no such
* column was found.
* @private
*/
lf.proc.OrderByStep.prototype.findDistinctColumn_ = function(relation) {
var distinctColumn = null;
for (var i = 0; i < this.orderBy.length; i++) {
var tempDistinctColumn = lf.fn.distinct(
/** @type {!lf.schema.BaseColumn} */ (this.orderBy[i].column));
if (relation.hasAggregationResult(tempDistinctColumn)) {
distinctColumn = tempDistinctColumn;
break;
}
}
return distinctColumn;
};
/**
* @param {!function(!lf.schema.Column):*} getLeftPayload
* @param {!function(!lf.schema.Column):*} getRightPayload
* @return {number} -1 if a should precede b, 1 if b should precede a, 0 if a
* and b are determined to be equal.
* @private
*/
lf.proc.OrderByStep.prototype.comparator_ = function(
getLeftPayload, getRightPayload) {
var order = null;
var leftPayload = null;
var rightPayload = null;
var comparisonIndex = -1;
do {
comparisonIndex++;
var column = this.orderBy[comparisonIndex].column;
order = this.orderBy[comparisonIndex].order;
leftPayload = getLeftPayload(column);
rightPayload = getRightPayload(column);
} while (leftPayload == rightPayload &&
comparisonIndex + 1 < this.orderBy.length);
var result = (leftPayload < rightPayload) ? -1 :
(leftPayload > rightPayload) ? 1 : 0;
result = order == lf.Order.ASC ? result : -result;
return result;
};
/**
* Comparator function used for sorting relations.
*
* @param {!lf.proc.Relation} lhs The first operand.
* @param {!lf.proc.Relation} rhs The second operand.
* @return {number} -1 if a should precede b, 1 if b should precede a, 0 if a
* and b are determined to be equal.
* @private
*/
lf.proc.OrderByStep.prototype.relationComparatorFn_ = function(lhs, rhs) {
// NOTE: See NOTE in entryComparatorFn_ on why two separate functions are
// passed in this.comparator_ instead of using one method and binding to lhs
// and to rhs respectively.
return this.comparator_(
function(column) {
// If relations are sorted based on a non-aggregated column, choose
// the last entry of each relation as a representative row (same as
// SQLlite).
return column instanceof lf.fn.AggregatedColumn ?
lhs.getAggregationResult(column) :
lhs.entries[lhs.entries.length - 1].getField(column);
},
function(column) {
return column instanceof lf.fn.AggregatedColumn ?
rhs.getAggregationResult(column) :
rhs.entries[rhs.entries.length - 1].getField(column);
});
};
/**
* Comparator function used for sorting entries within a single relation.
*
* @param {!lf.proc.RelationEntry} lhs The first operand.
* @param {!lf.proc.RelationEntry} rhs The second operand.
* @return {number} -1 if a should precede b, 1 if b should precede a, 0 if a
* and b are determined to be equal.
* @private
*/
lf.proc.OrderByStep.prototype.entryComparatorFn_ = function(lhs, rhs) {
// NOTE: Avoiding on purpose to create a getPayload(operand, column) method
// here, and binding it once to lhs and once to rhs, because it turns out that
// Function.bind() is significantly hurting performance (measured on
// Chrome 40).
return this.comparator_(
function(column) { return lhs.getField(column); },
function(column) { return rhs.getField(column); });
};
| {
var distinctColumn = this.findDistinctColumn_(relations[0]);
// If such a column exists, sort the results of the lf.fn.distinct
// aggregator instead, since this is what will be used in the returned
// result.
var relationToSort = goog.isNull(distinctColumn) ?
relations[0] :
relations[0].getAggregationResult(distinctColumn);
relationToSort.entries.sort(this.entryComparatorFn_.bind(this));
} | conditional_block |
transformers.js | var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
through = require('through'),
filesize = require('file-size');
function browserify(file, options) {
var source = [];
function write(data) {
source.push(data);
};
function | (file, options) {
var renderTemplate = function(options, stats) {
var si = options.size.representation === 'si',
computedSize = filesize(stats.size, {
fixed: options.size.decimals,
spacer: options.size.spacer
}),
jsonOptions = JSON.stringify(options),
jsonStats = JSON.stringify(stats),
prettySize = (options.size.unit === 'human') ?
computedSize.human({ si: si }) :
computedSize.to(options.size.unit, si),
template = options.output.file.template;
return template.replace('%file%', path.basename(file))
.replace('%fullname%', file)
.replace('%size%', prettySize)
.replace('%stats%', jsonStats)
.replace('%atime%', stats.atime)
.replace('%mtime%', stats.mtime)
.replace('%unit%', options.size.unit)
.replace('%decimals%', options.size.decimals)
.replace('%options%', jsonOptions);
};
var fileStat = function(err, stats) {
if (err) {
console.error('Failure to extract file stats', file, err);
return;
}
if (options.output.file) {
var result = '',
prependHeader = renderTemplate(options, stats);
try {
result = [prependHeader, source.join('')].join('');
} catch (error) {
error.message += ' in "' + file + '"';
this.emit('error', error);
}
this.queue(result);
this.queue(null);
}
}.bind(this);
fs.stat(file, fileStat);
}
return (function transform(file, options) {
var options = _.extend({
size: {
unit: 'human',
decimals: '2',
spacer: ' ',
representation: 'si'
},
output: {
file: {
template: [
'',
'/* =========================== ',
' * > File: %file%',
' * > Size: %size%',
' * > Modified: %mtime%',
' * =========================== */',
''
].join('\n')
}
}
}, options);
return through(_.partial(write), _.partial(end, file, options));
})(file, options);
};
module.exports = {
browserify: browserify
};
| end | identifier_name |
transformers.js | var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
through = require('through'),
filesize = require('file-size');
function browserify(file, options) {
var source = [];
function write(data) | ;
function end(file, options) {
var renderTemplate = function(options, stats) {
var si = options.size.representation === 'si',
computedSize = filesize(stats.size, {
fixed: options.size.decimals,
spacer: options.size.spacer
}),
jsonOptions = JSON.stringify(options),
jsonStats = JSON.stringify(stats),
prettySize = (options.size.unit === 'human') ?
computedSize.human({ si: si }) :
computedSize.to(options.size.unit, si),
template = options.output.file.template;
return template.replace('%file%', path.basename(file))
.replace('%fullname%', file)
.replace('%size%', prettySize)
.replace('%stats%', jsonStats)
.replace('%atime%', stats.atime)
.replace('%mtime%', stats.mtime)
.replace('%unit%', options.size.unit)
.replace('%decimals%', options.size.decimals)
.replace('%options%', jsonOptions);
};
var fileStat = function(err, stats) {
if (err) {
console.error('Failure to extract file stats', file, err);
return;
}
if (options.output.file) {
var result = '',
prependHeader = renderTemplate(options, stats);
try {
result = [prependHeader, source.join('')].join('');
} catch (error) {
error.message += ' in "' + file + '"';
this.emit('error', error);
}
this.queue(result);
this.queue(null);
}
}.bind(this);
fs.stat(file, fileStat);
}
return (function transform(file, options) {
var options = _.extend({
size: {
unit: 'human',
decimals: '2',
spacer: ' ',
representation: 'si'
},
output: {
file: {
template: [
'',
'/* =========================== ',
' * > File: %file%',
' * > Size: %size%',
' * > Modified: %mtime%',
' * =========================== */',
''
].join('\n')
}
}
}, options);
return through(_.partial(write), _.partial(end, file, options));
})(file, options);
};
module.exports = {
browserify: browserify
};
| {
source.push(data);
} | identifier_body |
transformers.js | var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
through = require('through'),
filesize = require('file-size');
function browserify(file, options) {
var source = [];
function write(data) {
source.push(data);
};
function end(file, options) {
var renderTemplate = function(options, stats) {
var si = options.size.representation === 'si',
computedSize = filesize(stats.size, {
fixed: options.size.decimals,
spacer: options.size.spacer
}),
jsonOptions = JSON.stringify(options),
jsonStats = JSON.stringify(stats),
prettySize = (options.size.unit === 'human') ?
computedSize.human({ si: si }) :
computedSize.to(options.size.unit, si),
template = options.output.file.template;
return template.replace('%file%', path.basename(file))
.replace('%fullname%', file)
.replace('%size%', prettySize)
.replace('%stats%', jsonStats)
.replace('%atime%', stats.atime)
.replace('%mtime%', stats.mtime)
.replace('%unit%', options.size.unit)
.replace('%decimals%', options.size.decimals)
.replace('%options%', jsonOptions);
};
var fileStat = function(err, stats) {
if (err) {
console.error('Failure to extract file stats', file, err);
return;
}
if (options.output.file) |
}.bind(this);
fs.stat(file, fileStat);
}
return (function transform(file, options) {
var options = _.extend({
size: {
unit: 'human',
decimals: '2',
spacer: ' ',
representation: 'si'
},
output: {
file: {
template: [
'',
'/* =========================== ',
' * > File: %file%',
' * > Size: %size%',
' * > Modified: %mtime%',
' * =========================== */',
''
].join('\n')
}
}
}, options);
return through(_.partial(write), _.partial(end, file, options));
})(file, options);
};
module.exports = {
browserify: browserify
};
| {
var result = '',
prependHeader = renderTemplate(options, stats);
try {
result = [prependHeader, source.join('')].join('');
} catch (error) {
error.message += ' in "' + file + '"';
this.emit('error', error);
}
this.queue(result);
this.queue(null);
} | conditional_block |
transformers.js | var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
through = require('through'),
filesize = require('file-size');
function browserify(file, options) {
var source = [];
function write(data) {
source.push(data);
};
function end(file, options) {
var renderTemplate = function(options, stats) {
var si = options.size.representation === 'si',
computedSize = filesize(stats.size, {
fixed: options.size.decimals,
spacer: options.size.spacer
}),
jsonOptions = JSON.stringify(options),
jsonStats = JSON.stringify(stats),
prettySize = (options.size.unit === 'human') ?
computedSize.human({ si: si }) :
computedSize.to(options.size.unit, si),
template = options.output.file.template;
return template.replace('%file%', path.basename(file))
.replace('%fullname%', file)
.replace('%size%', prettySize)
.replace('%stats%', jsonStats)
.replace('%atime%', stats.atime)
.replace('%mtime%', stats.mtime)
.replace('%unit%', options.size.unit)
.replace('%decimals%', options.size.decimals)
.replace('%options%', jsonOptions);
};
var fileStat = function(err, stats) {
if (err) {
console.error('Failure to extract file stats', file, err);
return;
}
| prependHeader = renderTemplate(options, stats);
try {
result = [prependHeader, source.join('')].join('');
} catch (error) {
error.message += ' in "' + file + '"';
this.emit('error', error);
}
this.queue(result);
this.queue(null);
}
}.bind(this);
fs.stat(file, fileStat);
}
return (function transform(file, options) {
var options = _.extend({
size: {
unit: 'human',
decimals: '2',
spacer: ' ',
representation: 'si'
},
output: {
file: {
template: [
'',
'/* =========================== ',
' * > File: %file%',
' * > Size: %size%',
' * > Modified: %mtime%',
' * =========================== */',
''
].join('\n')
}
}
}, options);
return through(_.partial(write), _.partial(end, file, options));
})(file, options);
};
module.exports = {
browserify: browserify
}; | if (options.output.file) {
var result = '', | random_line_split |
main.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use std::{
fs::{self, File},
io::{BufRead, BufReader},
path::Path,
};
use ::ndarray::{Array, ArrayD, Axis};
use image::{FilterType, GenericImageView};
use anyhow::Context as _;
use tvm::runtime::graph_rt::GraphRt;
use tvm::*;
fn main() -> anyhow::Result<()> {
let ctx = Context::cpu(0);
println!("{}", concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png"));
let img = image::open(concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png"))
.context("Failed to open cat.png")?;
println!("original image dimensions: {:?}", img.dimensions());
// for bigger size images, one needs to first resize to 256x256
// with `img.resize_exact` method and then `image.crop` to 224x224
let img = img.resize(224, 224, FilterType::Nearest).to_rgb();
println!("resized image dimensions: {:?}", img.dimensions());
let mut pixels: Vec<f32> = vec![];
for pixel in img.pixels() {
let tmp = pixel.data;
// normalize the RGB channels using mean, std of imagenet1k
let tmp = [
(tmp[0] as f32 - 123.0) / 58.395, // R
(tmp[1] as f32 - 117.0) / 57.12, // G
(tmp[2] as f32 - 104.0) / 57.375, // B
];
for e in &tmp {
pixels.push(*e);
}
}
let arr = Array::from_shape_vec((224, 224, 3), pixels)?;
let arr: ArrayD<f32> = arr.permuted_axes([2, 0, 1]).into_dyn();
// make arr shape as [1, 3, 224, 224] acceptable to resnet
let arr = arr.insert_axis(Axis(0));
// create input tensor from rust's ndarray
let input = NDArray::from_rust_ndarray(&arr, Context::cpu(0), DataType::float(32, 1))?;
println!(
"input shape is {:?}, len: {}, size: {}",
input.shape(),
input.len(),
input.size(),
);
let graph = fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/deploy_graph.json"))
.context("Failed to open graph")?;
// load the built module
let lib = Module::load(&Path::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/deploy_lib.so"
)))?;
let mut graph_rt = GraphRt::create_from_parts(&graph, lib, ctx)?;
// parse parameters and convert to TVMByteArray
let params: Vec<u8> = fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/deploy_param.params"))?;
println!("param bytes: {}", params.len());
graph_rt.load_params(¶ms)?;
graph_rt.set_input("data", input)?;
graph_rt.run()?;
// prepare to get the output
let output_shape = &[1, 1000];
let output = NDArray::empty(output_shape, Context::cpu(0), DataType::float(32, 1));
graph_rt.get_output_into(0, output.clone())?;
// flatten the output as Vec<f32>
let output = output.to_vec::<f32>()?;
// find the maximum entry in the output and its index
let (argmax, max_prob) = output
.iter()
.copied()
.enumerate()
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.unwrap();
// create a hash map of (class id, class name)
let file = File::open("synset.txt").context("failed to open synset")?;
let synset: Vec<String> = BufReader::new(file)
.lines()
.into_iter()
.map(|x| x.expect("readline failed"))
.collect();
let label = &synset[argmax];
println!(
"input image belongs to the class `{}` with probability {}",
label, max_prob
);
Ok(())
} | random_line_split |
|
main.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use std::{
fs::{self, File},
io::{BufRead, BufReader},
path::Path,
};
use ::ndarray::{Array, ArrayD, Axis};
use image::{FilterType, GenericImageView};
use anyhow::Context as _;
use tvm::runtime::graph_rt::GraphRt;
use tvm::*;
fn | () -> anyhow::Result<()> {
let ctx = Context::cpu(0);
println!("{}", concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png"));
let img = image::open(concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png"))
.context("Failed to open cat.png")?;
println!("original image dimensions: {:?}", img.dimensions());
// for bigger size images, one needs to first resize to 256x256
// with `img.resize_exact` method and then `image.crop` to 224x224
let img = img.resize(224, 224, FilterType::Nearest).to_rgb();
println!("resized image dimensions: {:?}", img.dimensions());
let mut pixels: Vec<f32> = vec![];
for pixel in img.pixels() {
let tmp = pixel.data;
// normalize the RGB channels using mean, std of imagenet1k
let tmp = [
(tmp[0] as f32 - 123.0) / 58.395, // R
(tmp[1] as f32 - 117.0) / 57.12, // G
(tmp[2] as f32 - 104.0) / 57.375, // B
];
for e in &tmp {
pixels.push(*e);
}
}
let arr = Array::from_shape_vec((224, 224, 3), pixels)?;
let arr: ArrayD<f32> = arr.permuted_axes([2, 0, 1]).into_dyn();
// make arr shape as [1, 3, 224, 224] acceptable to resnet
let arr = arr.insert_axis(Axis(0));
// create input tensor from rust's ndarray
let input = NDArray::from_rust_ndarray(&arr, Context::cpu(0), DataType::float(32, 1))?;
println!(
"input shape is {:?}, len: {}, size: {}",
input.shape(),
input.len(),
input.size(),
);
let graph = fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/deploy_graph.json"))
.context("Failed to open graph")?;
// load the built module
let lib = Module::load(&Path::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/deploy_lib.so"
)))?;
let mut graph_rt = GraphRt::create_from_parts(&graph, lib, ctx)?;
// parse parameters and convert to TVMByteArray
let params: Vec<u8> = fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/deploy_param.params"))?;
println!("param bytes: {}", params.len());
graph_rt.load_params(¶ms)?;
graph_rt.set_input("data", input)?;
graph_rt.run()?;
// prepare to get the output
let output_shape = &[1, 1000];
let output = NDArray::empty(output_shape, Context::cpu(0), DataType::float(32, 1));
graph_rt.get_output_into(0, output.clone())?;
// flatten the output as Vec<f32>
let output = output.to_vec::<f32>()?;
// find the maximum entry in the output and its index
let (argmax, max_prob) = output
.iter()
.copied()
.enumerate()
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.unwrap();
// create a hash map of (class id, class name)
let file = File::open("synset.txt").context("failed to open synset")?;
let synset: Vec<String> = BufReader::new(file)
.lines()
.into_iter()
.map(|x| x.expect("readline failed"))
.collect();
let label = &synset[argmax];
println!(
"input image belongs to the class `{}` with probability {}",
label, max_prob
);
Ok(())
}
| main | identifier_name |
main.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use std::{
fs::{self, File},
io::{BufRead, BufReader},
path::Path,
};
use ::ndarray::{Array, ArrayD, Axis};
use image::{FilterType, GenericImageView};
use anyhow::Context as _;
use tvm::runtime::graph_rt::GraphRt;
use tvm::*;
fn main() -> anyhow::Result<()> | ];
for e in &tmp {
pixels.push(*e);
}
}
let arr = Array::from_shape_vec((224, 224, 3), pixels)?;
let arr: ArrayD<f32> = arr.permuted_axes([2, 0, 1]).into_dyn();
// make arr shape as [1, 3, 224, 224] acceptable to resnet
let arr = arr.insert_axis(Axis(0));
// create input tensor from rust's ndarray
let input = NDArray::from_rust_ndarray(&arr, Context::cpu(0), DataType::float(32, 1))?;
println!(
"input shape is {:?}, len: {}, size: {}",
input.shape(),
input.len(),
input.size(),
);
let graph = fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/deploy_graph.json"))
.context("Failed to open graph")?;
// load the built module
let lib = Module::load(&Path::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/deploy_lib.so"
)))?;
let mut graph_rt = GraphRt::create_from_parts(&graph, lib, ctx)?;
// parse parameters and convert to TVMByteArray
let params: Vec<u8> = fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/deploy_param.params"))?;
println!("param bytes: {}", params.len());
graph_rt.load_params(¶ms)?;
graph_rt.set_input("data", input)?;
graph_rt.run()?;
// prepare to get the output
let output_shape = &[1, 1000];
let output = NDArray::empty(output_shape, Context::cpu(0), DataType::float(32, 1));
graph_rt.get_output_into(0, output.clone())?;
// flatten the output as Vec<f32>
let output = output.to_vec::<f32>()?;
// find the maximum entry in the output and its index
let (argmax, max_prob) = output
.iter()
.copied()
.enumerate()
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.unwrap();
// create a hash map of (class id, class name)
let file = File::open("synset.txt").context("failed to open synset")?;
let synset: Vec<String> = BufReader::new(file)
.lines()
.into_iter()
.map(|x| x.expect("readline failed"))
.collect();
let label = &synset[argmax];
println!(
"input image belongs to the class `{}` with probability {}",
label, max_prob
);
Ok(())
}
| {
let ctx = Context::cpu(0);
println!("{}", concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png"));
let img = image::open(concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png"))
.context("Failed to open cat.png")?;
println!("original image dimensions: {:?}", img.dimensions());
// for bigger size images, one needs to first resize to 256x256
// with `img.resize_exact` method and then `image.crop` to 224x224
let img = img.resize(224, 224, FilterType::Nearest).to_rgb();
println!("resized image dimensions: {:?}", img.dimensions());
let mut pixels: Vec<f32> = vec![];
for pixel in img.pixels() {
let tmp = pixel.data;
// normalize the RGB channels using mean, std of imagenet1k
let tmp = [
(tmp[0] as f32 - 123.0) / 58.395, // R
(tmp[1] as f32 - 117.0) / 57.12, // G
(tmp[2] as f32 - 104.0) / 57.375, // B | identifier_body |
main.rs | #![deny(
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unused_import_braces,
unused_qualifications,
unsafe_code,
dead_code,
unused_results,
)]
extern crate clap;
extern crate rand;
extern crate time;
extern crate ctrlc;
extern crate serde;
extern crate serde_json;
extern crate websocket;
mod options;
pub mod math;
pub mod message;
pub mod server;
use websocket::Client;
use websocket::client::request::Url;
use std::sync::{Arc, RwLock};
use std::sync::mpsc::channel;
use server::{listen, start_game_loop};
pub use options::Options;
fn | () {
let opts = Options::parse();
let cont = Arc::new(RwLock::new(true));
{
let host = opts.host.clone();
let port = opts.port;
let cont = cont.clone();
ctrlc::set_handler(move || {
println!("Ctrl+C received, terminating...");
*cont.write().unwrap() = false;
let _ = Client::connect(Url::parse(&format!("ws://{}:{}", host, port)[..]).unwrap());
});
}
// Create the channel which will allow the game loop to recieve messages.
let (tx, rx) = channel();
let game_loop_handle = start_game_loop(rx, &cont);
listen(&opts.host, opts.port, tx, &cont);
if let Err(error) = game_loop_handle.join() {
println!("Game loop thread failed: {:?}", error);
}
}
| main | identifier_name |
main.rs | #![deny(
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unused_import_braces,
unused_qualifications,
unsafe_code,
dead_code,
unused_results,
)]
extern crate clap;
extern crate rand;
extern crate time;
extern crate ctrlc;
extern crate serde;
extern crate serde_json;
extern crate websocket;
mod options;
pub mod math;
pub mod message;
pub mod server;
use websocket::Client;
use websocket::client::request::Url;
use std::sync::{Arc, RwLock};
use std::sync::mpsc::channel;
use server::{listen, start_game_loop};
pub use options::Options;
fn main() {
let opts = Options::parse();
let cont = Arc::new(RwLock::new(true));
{
let host = opts.host.clone();
let port = opts.port;
let cont = cont.clone();
ctrlc::set_handler(move || {
println!("Ctrl+C received, terminating...");
*cont.write().unwrap() = false;
let _ = Client::connect(Url::parse(&format!("ws://{}:{}", host, port)[..]).unwrap());
});
}
// Create the channel which will allow the game loop to recieve messages.
let (tx, rx) = channel();
let game_loop_handle = start_game_loop(rx, &cont);
listen(&opts.host, opts.port, tx, &cont);
if let Err(error) = game_loop_handle.join() |
}
| {
println!("Game loop thread failed: {:?}", error);
} | conditional_block |
main.rs | #![deny(
missing_debug_implementations, | unused_import_braces,
unused_qualifications,
unsafe_code,
dead_code,
unused_results,
)]
extern crate clap;
extern crate rand;
extern crate time;
extern crate ctrlc;
extern crate serde;
extern crate serde_json;
extern crate websocket;
mod options;
pub mod math;
pub mod message;
pub mod server;
use websocket::Client;
use websocket::client::request::Url;
use std::sync::{Arc, RwLock};
use std::sync::mpsc::channel;
use server::{listen, start_game_loop};
pub use options::Options;
fn main() {
let opts = Options::parse();
let cont = Arc::new(RwLock::new(true));
{
let host = opts.host.clone();
let port = opts.port;
let cont = cont.clone();
ctrlc::set_handler(move || {
println!("Ctrl+C received, terminating...");
*cont.write().unwrap() = false;
let _ = Client::connect(Url::parse(&format!("ws://{}:{}", host, port)[..]).unwrap());
});
}
// Create the channel which will allow the game loop to recieve messages.
let (tx, rx) = channel();
let game_loop_handle = start_game_loop(rx, &cont);
listen(&opts.host, opts.port, tx, &cont);
if let Err(error) = game_loop_handle.join() {
println!("Game loop thread failed: {:?}", error);
}
} | missing_copy_implementations,
trivial_casts,
trivial_numeric_casts, | random_line_split |
main.rs | #![deny(
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unused_import_braces,
unused_qualifications,
unsafe_code,
dead_code,
unused_results,
)]
extern crate clap;
extern crate rand;
extern crate time;
extern crate ctrlc;
extern crate serde;
extern crate serde_json;
extern crate websocket;
mod options;
pub mod math;
pub mod message;
pub mod server;
use websocket::Client;
use websocket::client::request::Url;
use std::sync::{Arc, RwLock};
use std::sync::mpsc::channel;
use server::{listen, start_game_loop};
pub use options::Options;
fn main() | listen(&opts.host, opts.port, tx, &cont);
if let Err(error) = game_loop_handle.join() {
println!("Game loop thread failed: {:?}", error);
}
}
| {
let opts = Options::parse();
let cont = Arc::new(RwLock::new(true));
{
let host = opts.host.clone();
let port = opts.port;
let cont = cont.clone();
ctrlc::set_handler(move || {
println!("Ctrl+C received, terminating...");
*cont.write().unwrap() = false;
let _ = Client::connect(Url::parse(&format!("ws://{}:{}", host, port)[..]).unwrap());
});
}
// Create the channel which will allow the game loop to recieve messages.
let (tx, rx) = channel();
let game_loop_handle = start_game_loop(rx, &cont); | identifier_body |
collisionDetector.js | Intersection;
areObjectsCloseEnough = _collisionDistancePrecheck(bitmap1,bitmap2);
if ( !areObjectsCloseEnough ) {
return false;
}
intersection = checkRectCollision(bitmap1,bitmap2);
if ( !intersection ) {
return false;
}
alphaThreshold = alphaThreshold || 0;
alphaThreshold = Math.min(0.99999,alphaThreshold);
//setting the canvas size
collisionCanvas.width = intersection.width;
collisionCanvas.height = intersection.height;
collisionCanvas2.width = intersection.width;
collisionCanvas2.height = intersection.height;
imageData1 = _intersectingImagePart(intersection,bitmap1,collisionCtx,1);
imageData2 = _intersectingImagePart(intersection,bitmap2,collisionCtx2,2);
//compare the alpha values to the threshold and return the result
// = true if pixels are both > alphaThreshold at one coordinate
pixelIntersection = _compareAlphaValues(imageData1,imageData2,intersection.width,intersection.height,alphaThreshold, getRect);
if ( pixelIntersection ) {
pixelIntersection.x += intersection.x;
pixelIntersection.x2 += intersection.x;
pixelIntersection.y += intersection.y;
pixelIntersection.y2 += intersection.y;
} else {
return false;
}
| module.Collisions.checkPixelCollision = checkPixelCollision;
var _collisionDistancePrecheck = function(bitmap1,bitmap2) {
var ir1,ir2,b1,b2;
b1 = bitmap1.localToGlobal(0,0);
b2 = bitmap2.localToGlobal(0,0);
ir1 = bitmap1 instanceof createjs.Bitmap
? {width:bitmap1.image.width, height:bitmap1.image.height}
: bitmap1.spriteSheet.getFrame(bitmap1.currentFrame).rect;
ir2 = bitmap2 instanceof createjs.Bitmap
? {width:bitmap2.image.width, height:bitmap2.image.height}
: bitmap2.spriteSheet.getFrame(bitmap2.currentFrame).rect;
//precheck if objects are even close enough
return ( Math.abs(b2.x-b1.x) < ir2.width *bitmap2.scaleX+ir1.width *bitmap1.scaleX
&& Math.abs(b2.y-b1.y) < ir2.height*bitmap2.scaleY+ir1.height*bitmap2.scaleY )
}
var _intersectingImagePart = function(intersetion,bitmap,ctx,i) {
var bl, image, frameName, sr;
if ( bitmap instanceof createjs.Bitmap ) {
image = bitmap.image;
} else if ( bitmap instanceof createjs.Sprite ) {
frame = bitmap.spriteSheet.getFrame( bitmap.currentFrame )
frameName = frame.image.src + ':' +
frame.rect.x + ':' + frame.rect.y + ':' +
frame.rect.width + ':' + frame.rect.height;// + ':' + frame.rect.regX + ':' + frame.rect.regY
if ( cachedBAFrames[frameName] ) {
image = cachedBAFrames[frameName];
} else {
cachedBAFrames[frameName] = image = createjs.SpriteSheetUtils.extractFrame(bitmap.spriteSheet,bitmap.currentFrame);
}
}
bl = bitmap.globalToLocal(intersetion.x,intersetion.y);
ctx.restore();
ctx.save();
//ctx.clearRect(0,0,intersetion.width,intersetion.height);
ctx.rotate(_getParentalCumulatedProperty(bitmap,'rotation')*(Math.PI/180));
ctx.scale(_getParentalCumulatedProperty(bitmap,'scaleX','*'),_getParentalCumulatedProperty(bitmap,'scaleY','*'));
ctx.translate(-bl.x-intersetion['rect'+i].regX,-bl.y-intersetion['rect'+i].regY);
if ( (sr = bitmap.sourceRect) != undefined ) {
ctx.drawImage(image,sr.x,sr.y,sr.width,sr.height,0,0,sr.width,sr.height);
} else {
ctx.drawImage(image,0,0,image.width,image.height);
}
return ctx.getImageData(0, 0, intersetion.width, intersetion.height).data;
}
var _compareAlphaValues = function(imageData1,imageData2,width,height,alphaThreshold,getRect) {
var alpha1, alpha2, x, y, offset = 3,
pixelRect = {x:Infinity,y:Infinity,x2:-Infinity,y2:-Infinity};
// parsing through the pixels checking for an alpha match
// TODO: intelligent parsing, not just from 0 to end!
for ( y = 0; y < height; ++y) {
for ( x = 0; x < width; ++x) {
alpha1 = imageData1.length > offset+1 ? imageData1[offset] / 255 : 0;
alpha2 = imageData2.length > offset+1 ? imageData2[offset] / 255 : 0;
if ( alpha1 > alphaThreshold && alpha2 > alphaThreshold ) {
if ( getRect ) {
if ( x < pixelRect.x ) pixelRect.x = x;
if ( x > pixelRect.x2 ) pixelRect.x2 = x;
if ( y < pixelRect.y ) pixelRect.y = y;
if ( y > pixelRect.y2 ) pixelRect.y2 = y;
} else {
return {x:x,y:y,width:1,height:1};
}
}
offset += 4;
}
}
if ( pixelRect.x != Infinity ) {
pixelRect.width = pixelRect.x2 - pixelRect.x + 1;
pixelRect.height = pixelRect.y2 - pixelRect.y + 1;
return pixelRect;
}
return null;
}
// this is needed to paint the intersection part correctly,
// if the tested bitmap is a child to a rotated/scaled parent
// this was not painted correctly before
var _getParentalCumulatedProperty = function(child,propName,operation) {
operation = operation || '+';
if ( child.parent && child.parent[propName] ) {
var cp = child[propName];
var pp = _getParentalCumulatedProperty(child.parent,propName,operation);
if ( operation == '*' ) {
return cp * pp;
} else {
return cp + pp;
}
}
return child[propName];
}
var calculateCircleRectIntersection = function(circ, rect) {
var dist;
var cY = circ.center.y, cX = circ.center.x;
var rY = rect.y + rect.height/2, rX = rect.x + rect.width/2;
var rD = Math.sqrt(rect.width/2*rect.width/2+rect.height/2*rect.height/2);
var min = rD + circ.radius;
dist = Math.sqrt((cX-rX)*(cX-rX)+(cY-rY)*(cY-rY));
if(dist > (rD+circ.radius)) return null;
else {
var dist1, dist2, dist3, dist4;
dist1 = Math.sqrt((cX-rect.x)*(cX-rect.x)+(cY-rect.y)*(cY-rect.y));
dist2 = Math.sqrt((cX-rect.x-rect.width)*(cX-rect.x-rect.width)+(cY-rect.y)*(cY-rect.y));
dist3 = Math.sqrt((cX-rect.x)*(cX-rect.x)+(cY-rect.y-rect.height)*(cY-rect.y-rect.height));
dist4 = Math.sqrt((cX-rect.x-rect.width)*(cX-rect.x-rect.width)+(cY-rect.y-rect.height)*(cY-rect.y-rect.height));
//circlue is touching a corner
if(dist1 < circ.radius|| dist2 < circ.radius|| dist3 < circ.radius|| dist4 < circ.radius) {
return {hit: true};
}
else if(cX >= rect.x && cX <= (rect.x + rect.width) && Math.abs(rY - cY) < (circ.radius + rect.height/2)) {
return {hit: true};
}
else if(cY >= rect.y && cY <= (rect.y + rect.height) && Math.abs(rX - cX) < (circ.radius + rect.width/2)) {
return {hit: true};
}
else {
return null;
}
}
//dist2 = Math.sqrt((cX-rect.x-rect.width)*(cX-rect.x-rect.width)+(cY-rect.y)*(cY-rect.y));
//dist3 = Math.sqrt((cX-rect.x)*(cX-rect.x)+(cY-rect.y-rect.height)*(cY-rect.y-rect.height));
//dist4 = Math.sqrt((cX-rect.x-rect.width)*(cX-rect.x-rect.width)+(cY-rect.y-rect.height)*(cY-rect.y-rect.height));
}
module.Collisions.calculateCircleRectIntersection = calculateCircleRectIntersection;
var calculateCircleIntersection = function(circ1, circ2) {
var dist = Math.sqrt((circ1.center.x-circ2.center.x)*(circ1.center.x-circ2.center.x) + (circ1.center.y-circ2.center.y)*(circ1.center.y-circ2.center.y));
if(dist < (circ | return pixelIntersection;
} | random_line_split |
index.ts | /*
* Copyright (c) 2016-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc.- initial API and implementation
*/
import {Argument} from "./spi/decorator/parameter";
import {Parameter} from "./spi/decorator/parameter";
import {ArgumentProcessor} from "./spi/decorator/argument-processor";
import {Log} from "./spi/log/log";
import {CheDir} from "./internal/dir/che-dir";
import {CheTest} from "./internal/test/che-test";
import {CheAction} from "./internal/action/che-action";
import {ErrorMessage} from "./spi/error/error-message";
/**
* Entry point of this library providing commands.
* @author Florent Benoit
*/
export class EntryPoint {
args: Array<string>; |
@Parameter({names: ["--logger-debug"], description: "Enable the logger in debug mode"})
debugLogger : boolean;
@Parameter({names: ["--logger-prefix-off"], description: "Disable prefix mode in logging"})
prefixOffLogger : boolean;
constructor() {
this.args = ArgumentProcessor.inject(this, process.argv.slice(2));
process.on('SIGINT', () => {
Log.getLogger().warn('CTRL-C hit, exiting...');
process.exit(1);
});
}
/**
* Run this entry point and analyze args to dispatch to the correct entry.
*/
run() : void {
// turn into debugging mode
if (this.debugLogger) {
Log.enableDebug();
}
if (this.prefixOffLogger) {
Log.disablePrefix();
}
try {
var promise : Promise<any>;
switch(this.commandName) {
case 'che-test':
let cheTest: CheTest = new CheTest(this.args);
promise = cheTest.run();
break;
case 'che-action':
let cheAction: CheAction = new CheAction(this.args);
promise = cheAction.run();
break;
case 'che-dir':
let cheDir: CheDir = new CheDir(this.args);
promise = cheDir.run();
break;
default:
Log.getLogger().error('Invalid choice of command-name');
process.exit(1);
}
// handle error of the promise
promise.catch((error) => {
let exitCode : number = 1;
if (error instanceof ErrorMessage) {
exitCode = error.getExitCode();
error = error.getError();
}
try {
let errorMessage = JSON.parse(error);
if (errorMessage.message) {
Log.getLogger().error(errorMessage.message);
} else {
Log.getLogger().error(error.toString());
}
} catch (e) {
Log.getLogger().error(error.toString());
if (error instanceof TypeError || error instanceof SyntaxError) {
console.log(error.stack);
}
}
process.exit(exitCode);
});
} catch (e) {
Log.getLogger().error(e);
if (e instanceof TypeError || e instanceof SyntaxError) {
console.log(e.stack);
}
}
}
}
// call run method
new EntryPoint().run(); |
@Argument({description: "Name of the command to execute from this entry point."})
commandName : string; | random_line_split |
index.ts | /*
* Copyright (c) 2016-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc.- initial API and implementation
*/
import {Argument} from "./spi/decorator/parameter";
import {Parameter} from "./spi/decorator/parameter";
import {ArgumentProcessor} from "./spi/decorator/argument-processor";
import {Log} from "./spi/log/log";
import {CheDir} from "./internal/dir/che-dir";
import {CheTest} from "./internal/test/che-test";
import {CheAction} from "./internal/action/che-action";
import {ErrorMessage} from "./spi/error/error-message";
/**
* Entry point of this library providing commands.
* @author Florent Benoit
*/
export class EntryPoint {
args: Array<string>;
@Argument({description: "Name of the command to execute from this entry point."})
commandName : string;
@Parameter({names: ["--logger-debug"], description: "Enable the logger in debug mode"})
debugLogger : boolean;
@Parameter({names: ["--logger-prefix-off"], description: "Disable prefix mode in logging"})
prefixOffLogger : boolean;
constructor() {
this.args = ArgumentProcessor.inject(this, process.argv.slice(2));
process.on('SIGINT', () => {
Log.getLogger().warn('CTRL-C hit, exiting...');
process.exit(1);
});
}
/**
* Run this entry point and analyze args to dispatch to the correct entry.
*/
run() : void | promise = cheAction.run();
break;
case 'che-dir':
let cheDir: CheDir = new CheDir(this.args);
promise = cheDir.run();
break;
default:
Log.getLogger().error('Invalid choice of command-name');
process.exit(1);
}
// handle error of the promise
promise.catch((error) => {
let exitCode : number = 1;
if (error instanceof ErrorMessage) {
exitCode = error.getExitCode();
error = error.getError();
}
try {
let errorMessage = JSON.parse(error);
if (errorMessage.message) {
Log.getLogger().error(errorMessage.message);
} else {
Log.getLogger().error(error.toString());
}
} catch (e) {
Log.getLogger().error(error.toString());
if (error instanceof TypeError || error instanceof SyntaxError) {
console.log(error.stack);
}
}
process.exit(exitCode);
});
} catch (e) {
Log.getLogger().error(e);
if (e instanceof TypeError || e instanceof SyntaxError) {
console.log(e.stack);
}
}
}
}
// call run method
new EntryPoint().run();
| {
// turn into debugging mode
if (this.debugLogger) {
Log.enableDebug();
}
if (this.prefixOffLogger) {
Log.disablePrefix();
}
try {
var promise : Promise<any>;
switch(this.commandName) {
case 'che-test':
let cheTest: CheTest = new CheTest(this.args);
promise = cheTest.run();
break;
case 'che-action':
let cheAction: CheAction = new CheAction(this.args); | identifier_body |
index.ts | /*
* Copyright (c) 2016-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc.- initial API and implementation
*/
import {Argument} from "./spi/decorator/parameter";
import {Parameter} from "./spi/decorator/parameter";
import {ArgumentProcessor} from "./spi/decorator/argument-processor";
import {Log} from "./spi/log/log";
import {CheDir} from "./internal/dir/che-dir";
import {CheTest} from "./internal/test/che-test";
import {CheAction} from "./internal/action/che-action";
import {ErrorMessage} from "./spi/error/error-message";
/**
* Entry point of this library providing commands.
* @author Florent Benoit
*/
export class EntryPoint {
args: Array<string>;
@Argument({description: "Name of the command to execute from this entry point."})
commandName : string;
@Parameter({names: ["--logger-debug"], description: "Enable the logger in debug mode"})
debugLogger : boolean;
@Parameter({names: ["--logger-prefix-off"], description: "Disable prefix mode in logging"})
prefixOffLogger : boolean;
constructor() {
this.args = ArgumentProcessor.inject(this, process.argv.slice(2));
process.on('SIGINT', () => {
Log.getLogger().warn('CTRL-C hit, exiting...');
process.exit(1);
});
}
/**
* Run this entry point and analyze args to dispatch to the correct entry.
*/
run() : void {
// turn into debugging mode
if (this.debugLogger) {
Log.enableDebug();
}
if (this.prefixOffLogger) {
Log.disablePrefix();
}
try {
var promise : Promise<any>;
switch(this.commandName) {
case 'che-test':
let cheTest: CheTest = new CheTest(this.args);
promise = cheTest.run();
break;
case 'che-action':
let cheAction: CheAction = new CheAction(this.args);
promise = cheAction.run();
break;
case 'che-dir':
let cheDir: CheDir = new CheDir(this.args);
promise = cheDir.run();
break;
default:
Log.getLogger().error('Invalid choice of command-name');
process.exit(1);
}
// handle error of the promise
promise.catch((error) => {
let exitCode : number = 1;
if (error instanceof ErrorMessage) {
exitCode = error.getExitCode();
error = error.getError();
}
try {
let errorMessage = JSON.parse(error);
if (errorMessage.message) | else {
Log.getLogger().error(error.toString());
}
} catch (e) {
Log.getLogger().error(error.toString());
if (error instanceof TypeError || error instanceof SyntaxError) {
console.log(error.stack);
}
}
process.exit(exitCode);
});
} catch (e) {
Log.getLogger().error(e);
if (e instanceof TypeError || e instanceof SyntaxError) {
console.log(e.stack);
}
}
}
}
// call run method
new EntryPoint().run();
| {
Log.getLogger().error(errorMessage.message);
} | conditional_block |
index.ts | /*
* Copyright (c) 2016-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc.- initial API and implementation
*/
import {Argument} from "./spi/decorator/parameter";
import {Parameter} from "./spi/decorator/parameter";
import {ArgumentProcessor} from "./spi/decorator/argument-processor";
import {Log} from "./spi/log/log";
import {CheDir} from "./internal/dir/che-dir";
import {CheTest} from "./internal/test/che-test";
import {CheAction} from "./internal/action/che-action";
import {ErrorMessage} from "./spi/error/error-message";
/**
* Entry point of this library providing commands.
* @author Florent Benoit
*/
export class EntryPoint {
args: Array<string>;
@Argument({description: "Name of the command to execute from this entry point."})
commandName : string;
@Parameter({names: ["--logger-debug"], description: "Enable the logger in debug mode"})
debugLogger : boolean;
@Parameter({names: ["--logger-prefix-off"], description: "Disable prefix mode in logging"})
prefixOffLogger : boolean;
constructor() {
this.args = ArgumentProcessor.inject(this, process.argv.slice(2));
process.on('SIGINT', () => {
Log.getLogger().warn('CTRL-C hit, exiting...');
process.exit(1);
});
}
/**
* Run this entry point and analyze args to dispatch to the correct entry.
*/
| () : void {
// turn into debugging mode
if (this.debugLogger) {
Log.enableDebug();
}
if (this.prefixOffLogger) {
Log.disablePrefix();
}
try {
var promise : Promise<any>;
switch(this.commandName) {
case 'che-test':
let cheTest: CheTest = new CheTest(this.args);
promise = cheTest.run();
break;
case 'che-action':
let cheAction: CheAction = new CheAction(this.args);
promise = cheAction.run();
break;
case 'che-dir':
let cheDir: CheDir = new CheDir(this.args);
promise = cheDir.run();
break;
default:
Log.getLogger().error('Invalid choice of command-name');
process.exit(1);
}
// handle error of the promise
promise.catch((error) => {
let exitCode : number = 1;
if (error instanceof ErrorMessage) {
exitCode = error.getExitCode();
error = error.getError();
}
try {
let errorMessage = JSON.parse(error);
if (errorMessage.message) {
Log.getLogger().error(errorMessage.message);
} else {
Log.getLogger().error(error.toString());
}
} catch (e) {
Log.getLogger().error(error.toString());
if (error instanceof TypeError || error instanceof SyntaxError) {
console.log(error.stack);
}
}
process.exit(exitCode);
});
} catch (e) {
Log.getLogger().error(e);
if (e instanceof TypeError || e instanceof SyntaxError) {
console.log(e.stack);
}
}
}
}
// call run method
new EntryPoint().run();
| run | identifier_name |
sourcemap-locator.js | var ajax = require('ajax')
var Future = require("async-future")
var decodeDataUrl = require("./decodeDataUrl")
exports.fromUrl = function(sourceUrl, toSource) {
return ajax(sourceUrl, true).then(function(response) {
return fromSourceOrHeaders(response.headers, response.text, toSource)
})
}
exports.fromSource = function(sourceText, toSource) {
return fromSourceOrHeaders({}, sourceText, toSource)
}
function fromSourceOrHeaders(headers, sourceText, toSource) {
if(toSource === undefined) toSource = false
var sourcemapUrl = getSourceMapUrl(headers, sourceText)
if(sourcemapUrl === undefined) {
return Future(undefined)
} else if(toSource) {
if(sourcemapUrl.indexOf('data:') === 0) {
return Future(decodeDataUrl(sourcemapUrl))
} else {
return ajax(sourcemapUrl).then(function(response) {
return Future(response.text)
})
}
} else {
return Future(sourcemapUrl)
} |
exports.cacheGet = ajax.cacheGet
exports.cacheSet = ajax.cacheSet
var URL_PATTERN = '(((?:http|https|file)://)?[^\\s)]+|javascript:.*)'
var SOURCE_MAP_PATTERN_PART = " sourceMappingURL=("+URL_PATTERN+")"
var SOURCE_MAP_PATTERN1 = "\/\/#"+SOURCE_MAP_PATTERN_PART
var SOURCE_MAP_PATTERN2 = "\/\/@"+SOURCE_MAP_PATTERN_PART
function getSourceMapUrl(headers, content) {
if(headers['SourceMap'] !== undefined) {
return headers['SourceMap']
} else if(headers['X-SourceMap']) {
return headers['X-SourceMap']
} else {
var match = content.match(SOURCE_MAP_PATTERN1)
if(match !== null) return match[1]
match = content.match(SOURCE_MAP_PATTERN2)
if(match !== null) return match[1]
}
} | } | random_line_split |
sourcemap-locator.js | var ajax = require('ajax')
var Future = require("async-future")
var decodeDataUrl = require("./decodeDataUrl")
exports.fromUrl = function(sourceUrl, toSource) {
return ajax(sourceUrl, true).then(function(response) {
return fromSourceOrHeaders(response.headers, response.text, toSource)
})
}
exports.fromSource = function(sourceText, toSource) {
return fromSourceOrHeaders({}, sourceText, toSource)
}
function fromSourceOrHeaders(headers, sourceText, toSource) |
exports.cacheGet = ajax.cacheGet
exports.cacheSet = ajax.cacheSet
var URL_PATTERN = '(((?:http|https|file)://)?[^\\s)]+|javascript:.*)'
var SOURCE_MAP_PATTERN_PART = " sourceMappingURL=("+URL_PATTERN+")"
var SOURCE_MAP_PATTERN1 = "\/\/#"+SOURCE_MAP_PATTERN_PART
var SOURCE_MAP_PATTERN2 = "\/\/@"+SOURCE_MAP_PATTERN_PART
function getSourceMapUrl(headers, content) {
if(headers['SourceMap'] !== undefined) {
return headers['SourceMap']
} else if(headers['X-SourceMap']) {
return headers['X-SourceMap']
} else {
var match = content.match(SOURCE_MAP_PATTERN1)
if(match !== null) return match[1]
match = content.match(SOURCE_MAP_PATTERN2)
if(match !== null) return match[1]
}
} | {
if(toSource === undefined) toSource = false
var sourcemapUrl = getSourceMapUrl(headers, sourceText)
if(sourcemapUrl === undefined) {
return Future(undefined)
} else if(toSource) {
if(sourcemapUrl.indexOf('data:') === 0) {
return Future(decodeDataUrl(sourcemapUrl))
} else {
return ajax(sourcemapUrl).then(function(response) {
return Future(response.text)
})
}
} else {
return Future(sourcemapUrl)
}
} | identifier_body |
sourcemap-locator.js | var ajax = require('ajax')
var Future = require("async-future")
var decodeDataUrl = require("./decodeDataUrl")
exports.fromUrl = function(sourceUrl, toSource) {
return ajax(sourceUrl, true).then(function(response) {
return fromSourceOrHeaders(response.headers, response.text, toSource)
})
}
exports.fromSource = function(sourceText, toSource) {
return fromSourceOrHeaders({}, sourceText, toSource)
}
function | (headers, sourceText, toSource) {
if(toSource === undefined) toSource = false
var sourcemapUrl = getSourceMapUrl(headers, sourceText)
if(sourcemapUrl === undefined) {
return Future(undefined)
} else if(toSource) {
if(sourcemapUrl.indexOf('data:') === 0) {
return Future(decodeDataUrl(sourcemapUrl))
} else {
return ajax(sourcemapUrl).then(function(response) {
return Future(response.text)
})
}
} else {
return Future(sourcemapUrl)
}
}
exports.cacheGet = ajax.cacheGet
exports.cacheSet = ajax.cacheSet
var URL_PATTERN = '(((?:http|https|file)://)?[^\\s)]+|javascript:.*)'
var SOURCE_MAP_PATTERN_PART = " sourceMappingURL=("+URL_PATTERN+")"
var SOURCE_MAP_PATTERN1 = "\/\/#"+SOURCE_MAP_PATTERN_PART
var SOURCE_MAP_PATTERN2 = "\/\/@"+SOURCE_MAP_PATTERN_PART
function getSourceMapUrl(headers, content) {
if(headers['SourceMap'] !== undefined) {
return headers['SourceMap']
} else if(headers['X-SourceMap']) {
return headers['X-SourceMap']
} else {
var match = content.match(SOURCE_MAP_PATTERN1)
if(match !== null) return match[1]
match = content.match(SOURCE_MAP_PATTERN2)
if(match !== null) return match[1]
}
} | fromSourceOrHeaders | identifier_name |
exceptions.py | from datetime import datetime
class PanoplyException(Exception):
def __init__(self, args=None, retryable=True):
super(PanoplyException, self).__init__(args)
self.retryable = retryable
class IncorrectParamError(Exception):
def __init__(self, msg: str = "Incorrect input parametr"):
super().__init__(msg)
class | (Exception):
def __init__(self, message, code, exception_cls,
phase, source_type, source_id, database_id):
super().__init__(message)
self.message = message
self.code = code
self.phase = phase
self.source_type = source_type
self.source_id = source_id
self.database_id = database_id
self.exception_cls = exception_cls
self.created_at = datetime.utcnow()
class TokenValidationException(PanoplyException):
def __init__(self, original_error, args=None, retryable=True):
super().__init__(args, retryable)
self.original_error = original_error
| DataSourceException | identifier_name |
exceptions.py | from datetime import datetime
class PanoplyException(Exception):
|
class IncorrectParamError(Exception):
def __init__(self, msg: str = "Incorrect input parametr"):
super().__init__(msg)
class DataSourceException(Exception):
def __init__(self, message, code, exception_cls,
phase, source_type, source_id, database_id):
super().__init__(message)
self.message = message
self.code = code
self.phase = phase
self.source_type = source_type
self.source_id = source_id
self.database_id = database_id
self.exception_cls = exception_cls
self.created_at = datetime.utcnow()
class TokenValidationException(PanoplyException):
def __init__(self, original_error, args=None, retryable=True):
super().__init__(args, retryable)
self.original_error = original_error
| def __init__(self, args=None, retryable=True):
super(PanoplyException, self).__init__(args)
self.retryable = retryable | identifier_body |
exceptions.py | from datetime import datetime
class PanoplyException(Exception):
def __init__(self, args=None, retryable=True):
super(PanoplyException, self).__init__(args)
self.retryable = retryable
| class IncorrectParamError(Exception):
def __init__(self, msg: str = "Incorrect input parametr"):
super().__init__(msg)
class DataSourceException(Exception):
def __init__(self, message, code, exception_cls,
phase, source_type, source_id, database_id):
super().__init__(message)
self.message = message
self.code = code
self.phase = phase
self.source_type = source_type
self.source_id = source_id
self.database_id = database_id
self.exception_cls = exception_cls
self.created_at = datetime.utcnow()
class TokenValidationException(PanoplyException):
def __init__(self, original_error, args=None, retryable=True):
super().__init__(args, retryable)
self.original_error = original_error | random_line_split |
|
decode.rs | //! Utilities for decoding a C4FM signal into symbols.
use bits;
use consts;
/// Decodes symbol from sample at each symbol instant.
#[derive(Copy, Clone)]
pub struct Decoder {
/// Sample index into current symbol period.
pos: usize,
/// Decider used for decoding symbol at each symbol instant.
decider: Decider,
}
impl Decoder {
/// Create a new `Decoder` with the given symbol decider, initialized to decode the
/// first symbol after the frame sync has been detected.
pub fn new(decider: Decider) -> Decoder {
Decoder {
// The frame sync sequence is detected one sample after its last symbol
// instant (i.e., the first sample in the next symbol period after the
// sequence), so take that sample into account.
pos: 1,
decider: decider,
}
}
/// Examine the given sample and, based on the symbol clock, decode it into a symbol
/// or do nothing.
pub fn feed(&mut self, s: f32) -> Option<bits::Dibit> {
self.pos += 1;
self.pos %= consts::SYMBOL_PERIOD;
if self.pos == 0 {
Some(self.decider.decide(s))
} else {
None
}
}
}
/// Decides which symbol a sample represents with a threshold method.
#[derive(Copy, Clone)]
pub struct Decider { | mthresh: f32,
/// Lower threshold.
nthresh: f32,
}
impl Decider {
/// Create a new Decider with the given positive threshold, mid threshold, and
/// negative threshold.
pub fn new(pthresh: f32, mthresh: f32, nthresh: f32) -> Decider {
Decider {
pthresh: pthresh,
mthresh: mthresh,
nthresh: nthresh,
}
}
/// Decide which symbol the given sample looks closest to.
pub fn decide(&self, sample: f32) -> bits::Dibit {
if sample > self.pthresh {
bits::Dibit::new(0b01)
} else if sample > self.mthresh && sample <= self.pthresh {
bits::Dibit::new(0b00)
} else if sample <= self.mthresh && sample > self.nthresh {
bits::Dibit::new(0b10)
} else {
bits::Dibit::new(0b11)
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_decider() {
let d = Decider::new(-0.004, -0.1, -0.196);
assert_eq!(d.decide(0.044).bits(), 0b01);
assert_eq!(d.decide(-0.052).bits(), 0b00);
assert_eq!(d.decide(-0.148).bits(), 0b10);
assert_eq!(d.decide(-0.244).bits(), 0b11);
}
#[test]
fn test_decoder() {
let mut d = Decoder::new(Decider::new(0.0, 0.0, 0.0));
assert!(d.feed(0.2099609375000000).is_none());
assert!(d.feed(0.2165222167968750).is_none());
assert!(d.feed(0.2179870605468750).is_none());
assert!(d.feed(0.2152709960937500).is_none());
assert!(d.feed(0.2094726562500000).is_none());
assert!(d.feed(0.2018737792968750).is_none());
assert!(d.feed(0.1937255859375000).is_none());
assert!(d.feed(0.1861572265625000).is_none());
assert!(d.feed(0.1799926757812500).is_some());
assert!(d.feed(0.1752929687500000).is_none());
assert!(d.feed(0.1726684570312500).is_none());
assert!(d.feed(0.1720886230468750).is_none());
assert!(d.feed(0.1732177734375000).is_none());
assert!(d.feed(0.1754455566406250).is_none());
assert!(d.feed(0.1780395507812500).is_none());
assert!(d.feed(0.1803588867187500).is_none());
assert!(d.feed(0.1817321777343750).is_none());
assert!(d.feed(0.1816711425781250).is_none());
assert!(d.feed(0.1799926757812500).is_some());
}
} | /// Upper threshold.
pthresh: f32,
/// Middle threshold. | random_line_split |
decode.rs | //! Utilities for decoding a C4FM signal into symbols.
use bits;
use consts;
/// Decodes symbol from sample at each symbol instant.
#[derive(Copy, Clone)]
pub struct Decoder {
/// Sample index into current symbol period.
pos: usize,
/// Decider used for decoding symbol at each symbol instant.
decider: Decider,
}
impl Decoder {
/// Create a new `Decoder` with the given symbol decider, initialized to decode the
/// first symbol after the frame sync has been detected.
pub fn new(decider: Decider) -> Decoder {
Decoder {
// The frame sync sequence is detected one sample after its last symbol
// instant (i.e., the first sample in the next symbol period after the
// sequence), so take that sample into account.
pos: 1,
decider: decider,
}
}
/// Examine the given sample and, based on the symbol clock, decode it into a symbol
/// or do nothing.
pub fn feed(&mut self, s: f32) -> Option<bits::Dibit> {
self.pos += 1;
self.pos %= consts::SYMBOL_PERIOD;
if self.pos == 0 {
Some(self.decider.decide(s))
} else {
None
}
}
}
/// Decides which symbol a sample represents with a threshold method.
#[derive(Copy, Clone)]
pub struct Decider {
/// Upper threshold.
pthresh: f32,
/// Middle threshold.
mthresh: f32,
/// Lower threshold.
nthresh: f32,
}
impl Decider {
/// Create a new Decider with the given positive threshold, mid threshold, and
/// negative threshold.
pub fn new(pthresh: f32, mthresh: f32, nthresh: f32) -> Decider {
Decider {
pthresh: pthresh,
mthresh: mthresh,
nthresh: nthresh,
}
}
/// Decide which symbol the given sample looks closest to.
pub fn decide(&self, sample: f32) -> bits::Dibit {
if sample > self.pthresh {
bits::Dibit::new(0b01)
} else if sample > self.mthresh && sample <= self.pthresh {
bits::Dibit::new(0b00)
} else if sample <= self.mthresh && sample > self.nthresh | else {
bits::Dibit::new(0b11)
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_decider() {
let d = Decider::new(-0.004, -0.1, -0.196);
assert_eq!(d.decide(0.044).bits(), 0b01);
assert_eq!(d.decide(-0.052).bits(), 0b00);
assert_eq!(d.decide(-0.148).bits(), 0b10);
assert_eq!(d.decide(-0.244).bits(), 0b11);
}
#[test]
fn test_decoder() {
let mut d = Decoder::new(Decider::new(0.0, 0.0, 0.0));
assert!(d.feed(0.2099609375000000).is_none());
assert!(d.feed(0.2165222167968750).is_none());
assert!(d.feed(0.2179870605468750).is_none());
assert!(d.feed(0.2152709960937500).is_none());
assert!(d.feed(0.2094726562500000).is_none());
assert!(d.feed(0.2018737792968750).is_none());
assert!(d.feed(0.1937255859375000).is_none());
assert!(d.feed(0.1861572265625000).is_none());
assert!(d.feed(0.1799926757812500).is_some());
assert!(d.feed(0.1752929687500000).is_none());
assert!(d.feed(0.1726684570312500).is_none());
assert!(d.feed(0.1720886230468750).is_none());
assert!(d.feed(0.1732177734375000).is_none());
assert!(d.feed(0.1754455566406250).is_none());
assert!(d.feed(0.1780395507812500).is_none());
assert!(d.feed(0.1803588867187500).is_none());
assert!(d.feed(0.1817321777343750).is_none());
assert!(d.feed(0.1816711425781250).is_none());
assert!(d.feed(0.1799926757812500).is_some());
}
}
| {
bits::Dibit::new(0b10)
} | conditional_block |
decode.rs | //! Utilities for decoding a C4FM signal into symbols.
use bits;
use consts;
/// Decodes symbol from sample at each symbol instant.
#[derive(Copy, Clone)]
pub struct Decoder {
/// Sample index into current symbol period.
pos: usize,
/// Decider used for decoding symbol at each symbol instant.
decider: Decider,
}
impl Decoder {
/// Create a new `Decoder` with the given symbol decider, initialized to decode the
/// first symbol after the frame sync has been detected.
pub fn new(decider: Decider) -> Decoder {
Decoder {
// The frame sync sequence is detected one sample after its last symbol
// instant (i.e., the first sample in the next symbol period after the
// sequence), so take that sample into account.
pos: 1,
decider: decider,
}
}
/// Examine the given sample and, based on the symbol clock, decode it into a symbol
/// or do nothing.
pub fn feed(&mut self, s: f32) -> Option<bits::Dibit> {
self.pos += 1;
self.pos %= consts::SYMBOL_PERIOD;
if self.pos == 0 {
Some(self.decider.decide(s))
} else {
None
}
}
}
/// Decides which symbol a sample represents with a threshold method.
#[derive(Copy, Clone)]
pub struct Decider {
/// Upper threshold.
pthresh: f32,
/// Middle threshold.
mthresh: f32,
/// Lower threshold.
nthresh: f32,
}
impl Decider {
/// Create a new Decider with the given positive threshold, mid threshold, and
/// negative threshold.
pub fn new(pthresh: f32, mthresh: f32, nthresh: f32) -> Decider {
Decider {
pthresh: pthresh,
mthresh: mthresh,
nthresh: nthresh,
}
}
/// Decide which symbol the given sample looks closest to.
pub fn decide(&self, sample: f32) -> bits::Dibit |
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_decider() {
let d = Decider::new(-0.004, -0.1, -0.196);
assert_eq!(d.decide(0.044).bits(), 0b01);
assert_eq!(d.decide(-0.052).bits(), 0b00);
assert_eq!(d.decide(-0.148).bits(), 0b10);
assert_eq!(d.decide(-0.244).bits(), 0b11);
}
#[test]
fn test_decoder() {
let mut d = Decoder::new(Decider::new(0.0, 0.0, 0.0));
assert!(d.feed(0.2099609375000000).is_none());
assert!(d.feed(0.2165222167968750).is_none());
assert!(d.feed(0.2179870605468750).is_none());
assert!(d.feed(0.2152709960937500).is_none());
assert!(d.feed(0.2094726562500000).is_none());
assert!(d.feed(0.2018737792968750).is_none());
assert!(d.feed(0.1937255859375000).is_none());
assert!(d.feed(0.1861572265625000).is_none());
assert!(d.feed(0.1799926757812500).is_some());
assert!(d.feed(0.1752929687500000).is_none());
assert!(d.feed(0.1726684570312500).is_none());
assert!(d.feed(0.1720886230468750).is_none());
assert!(d.feed(0.1732177734375000).is_none());
assert!(d.feed(0.1754455566406250).is_none());
assert!(d.feed(0.1780395507812500).is_none());
assert!(d.feed(0.1803588867187500).is_none());
assert!(d.feed(0.1817321777343750).is_none());
assert!(d.feed(0.1816711425781250).is_none());
assert!(d.feed(0.1799926757812500).is_some());
}
}
| {
if sample > self.pthresh {
bits::Dibit::new(0b01)
} else if sample > self.mthresh && sample <= self.pthresh {
bits::Dibit::new(0b00)
} else if sample <= self.mthresh && sample > self.nthresh {
bits::Dibit::new(0b10)
} else {
bits::Dibit::new(0b11)
}
} | identifier_body |
decode.rs | //! Utilities for decoding a C4FM signal into symbols.
use bits;
use consts;
/// Decodes symbol from sample at each symbol instant.
#[derive(Copy, Clone)]
pub struct Decoder {
/// Sample index into current symbol period.
pos: usize,
/// Decider used for decoding symbol at each symbol instant.
decider: Decider,
}
impl Decoder {
/// Create a new `Decoder` with the given symbol decider, initialized to decode the
/// first symbol after the frame sync has been detected.
pub fn new(decider: Decider) -> Decoder {
Decoder {
// The frame sync sequence is detected one sample after its last symbol
// instant (i.e., the first sample in the next symbol period after the
// sequence), so take that sample into account.
pos: 1,
decider: decider,
}
}
/// Examine the given sample and, based on the symbol clock, decode it into a symbol
/// or do nothing.
pub fn feed(&mut self, s: f32) -> Option<bits::Dibit> {
self.pos += 1;
self.pos %= consts::SYMBOL_PERIOD;
if self.pos == 0 {
Some(self.decider.decide(s))
} else {
None
}
}
}
/// Decides which symbol a sample represents with a threshold method.
#[derive(Copy, Clone)]
pub struct Decider {
/// Upper threshold.
pthresh: f32,
/// Middle threshold.
mthresh: f32,
/// Lower threshold.
nthresh: f32,
}
impl Decider {
/// Create a new Decider with the given positive threshold, mid threshold, and
/// negative threshold.
pub fn new(pthresh: f32, mthresh: f32, nthresh: f32) -> Decider {
Decider {
pthresh: pthresh,
mthresh: mthresh,
nthresh: nthresh,
}
}
/// Decide which symbol the given sample looks closest to.
pub fn decide(&self, sample: f32) -> bits::Dibit {
if sample > self.pthresh {
bits::Dibit::new(0b01)
} else if sample > self.mthresh && sample <= self.pthresh {
bits::Dibit::new(0b00)
} else if sample <= self.mthresh && sample > self.nthresh {
bits::Dibit::new(0b10)
} else {
bits::Dibit::new(0b11)
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_decider() {
let d = Decider::new(-0.004, -0.1, -0.196);
assert_eq!(d.decide(0.044).bits(), 0b01);
assert_eq!(d.decide(-0.052).bits(), 0b00);
assert_eq!(d.decide(-0.148).bits(), 0b10);
assert_eq!(d.decide(-0.244).bits(), 0b11);
}
#[test]
fn | () {
let mut d = Decoder::new(Decider::new(0.0, 0.0, 0.0));
assert!(d.feed(0.2099609375000000).is_none());
assert!(d.feed(0.2165222167968750).is_none());
assert!(d.feed(0.2179870605468750).is_none());
assert!(d.feed(0.2152709960937500).is_none());
assert!(d.feed(0.2094726562500000).is_none());
assert!(d.feed(0.2018737792968750).is_none());
assert!(d.feed(0.1937255859375000).is_none());
assert!(d.feed(0.1861572265625000).is_none());
assert!(d.feed(0.1799926757812500).is_some());
assert!(d.feed(0.1752929687500000).is_none());
assert!(d.feed(0.1726684570312500).is_none());
assert!(d.feed(0.1720886230468750).is_none());
assert!(d.feed(0.1732177734375000).is_none());
assert!(d.feed(0.1754455566406250).is_none());
assert!(d.feed(0.1780395507812500).is_none());
assert!(d.feed(0.1803588867187500).is_none());
assert!(d.feed(0.1817321777343750).is_none());
assert!(d.feed(0.1816711425781250).is_none());
assert!(d.feed(0.1799926757812500).is_some());
}
}
| test_decoder | identifier_name |
screen.py | import time
from pygame.locals import *
import gui
MOUSE_LEFT_BUTTON = 1
MOUSE_MIDDLE_BUTTON = 2
MOUSE_RIGHT_BUTTON = 3
MOUSE_WHEELUP = 4
MOUSE_WHEELDOWN = 5
class Screen(object):
"""Base gui screen class
every game screen class should inherit from this one
"""
__triggers = []
__old_hover = None
__hover = None
__hover_changed = False
def __init__(self):
pass
def log_info(self, message):
"""Prints an INFO message to standard output"""
ts = int(time.time())
print("# INFO %i ... %s" % (ts, message))
def log_error(self, message):
"""Prints an ERROR message to standard output"""
ts = int(time.time())
print("! ERROR %i ... %s" % (ts, message))
def reset_triggers_list(self):
"""Clears the screen's trigger list"""
self.__triggers = []
def add_trigger(self, trigger):
"""Appends given trigger to the end of screen's trigger list"""
if not trigger.has_key('hover_id'):
trigger['hover_id'] = None
self.__triggers.append(trigger)
def list_triggers(self):
"""Returns the screen's list of triggers"""
return self.__triggers
def get_timestamp(self, zoom = 1):
"""Returns an actual timestamp"""
return int(time.time() * zoom)
def get_image(self, img_key, subkey1 = None, subkey2 = None, subkey3 = None):
"""Returns an image object from GUI engine, identified by its key(s)"""
return gui.GUI.get_image(img_key, subkey1, subkey2, subkey3)
def redraw_flip(self):
"""Redraws the screen, takes care about mouse cursor and flips the graphic buffer to display"""
self.draw()
gui.GUI.highlight_triggers(self.list_triggers())
gui.GUI.flip()
def redraw_noflip(self):
"""Redraws the screen, takes care about mouse cursor but doesn't flip the buffer to display"""
self.draw()
gui.GUI.highlight_triggers(self.list_triggers())
def prepare(self):
"""This method should be implemented by screens that require some
special actions each time before the screen is run.
For example to reset screen to a well known state to prevent unexpected behaviour.
"""
pass
def draw(self):
"""All static graphic output should be implemented in this method.
Unless there is only a dynamic graphic (animations),
every screen should implement this method.
"""
pass
def animate(self):
"""Entry point for Screen animations, e.g. ship trajectory on MainScreen.
GUI engine calls this method periodically
Animations should be time-dependant - such screens have to implement the timing!
"""
pass
def get_escape_trigger(self):
"""Returns standard trigger for sending escape action"""
return {'action': "ESCAPE"}
def on_mousebuttonup(self, event):
"""Default implementation of mouse click event serving.
Checks the mouse wheel events (up and down scrolling) and regular mouse buttons.
If the event's subject is the left mouse button it checks the mouse position against the trigger list and
returns the first trigger where mouse positions is within its rectangle.
There is a good chance that no screen would have to override this method.
"""
if event.button == MOUSE_MIDDLE_BUTTON:
print event
elif event.button == MOUSE_WHEELUP:
return {'action': "SCROLL_UP"}
elif event.button == MOUSE_WHEELDOWN:
return {'action': "SCROLL_DOWN"}
else:
triggers_list = self.list_triggers()
for trigger in triggers_list:
if trigger['rect'].collidepoint(event.pos):
if event.button == MOUSE_LEFT_BUTTON:
|
elif event.button == MOUSE_RIGHT_BUTTON:
return {'action': "help", 'help': trigger['action']}
def on_keydown(self, event):
"""Default implementation of a keyboard event handling.
If keypress is detected by a GUI engine it calls this method.
The pressed key is checked against the trigger list.
Returns the first trigger where the key matches the pressed or
None if no trigger matches the keypress
There is a good chance that no screen would have to override this method.
"""
print("@ screen.Screen::on_keydown()")
print(" scancode = %i" % event.scancode)
print(" key = %i" % event.key)
if event.key == K_ESCAPE:
return {'action': "ESCAPE"}
else:
triggers_list = self.list_triggers()
for trigger in triggers_list:
if trigger.has_key('key') and trigger['key'] == event.key:
return trigger
return {'action': "key", 'key': event.key}
def update_hover(self, mouse_pos):
"""This method is invoked by a GUI engine on every pure mouse move
and right before the screen's on_mousemotion() method.
Mouse position is checked against screen's trigger list.
If hover is detected (=mouse position is inside the trigger's rectangle)
the trigger is copied and can be returned by get_hover() method
Also if the previously stored value is different than the new one,
the __hover_changed flag is set to True
The idea is to handle mouse hover detection separately,
so other methods could rely on get_hover() and hover_changed() methods.
Probably no screen should require to override this method.
"""
for trigger in self.list_triggers():
if trigger.has_key('hover_id') and trigger['rect'].collidepoint(mouse_pos):
if self.__hover != trigger:
self.__hover_changed = True
self.__hover = trigger
break
def get_hover(self):
"""Returns the current hover trigger"""
return self.__hover
def hover_changed(self):
"""Returns True if screen's hover has changed since last call of this method"""
if self.__hover_changed:
self.__hover_changed = False
return True
else:
return False
def on_mousemotion(self, event):
"""Invoked by a GUI engine on every pure (non-dragging) mouse move.
Currently no screen requires to override this empty implementation.
"""
pass
def get_drag_item(self, mouse_pos):
""""""
for trigger in self.list_triggers():
if trigger.has_key('drag_id') and trigger['rect'].collidepoint(mouse_pos):
return trigger['drag_id']
return None
def on_mousedrag(self, drag_item, pos, rel):
"""Invoked by a GUI engine when left mouse button is being held, drag item is set and mouse moves"""
pass
def on_mousedrop(self, drag_item, (mouse_x, mouse_y)):
"""Invoked by a GUI engine when mouse dragging stops
(drag item was set and left mouse button was released).
"""
pass
def process_trigger(self, trigger):
"""Empty implementation of a trigger handling
If a screen trigger is positively evaluated
(e.g. returned from on_mousebuttonup() or on_keydown() methods)
it's passed as a trigger argument to this method
Every screen should override this method to handle the proper actions.
"""
pass
def enter(self):
""" Called by GUI engine right before gui_client::run_screen() is invoked
Suitable for saving initial state that can be reveresed by the screen's cancel() method
"""
pass
def leave_confirm(self):
""" Called by GUI engine when CONFIRM trigger is activated
Every screen that sends data to the game server should implement this method
"""
pass
def leave_cancel(self):
""" Called by GUI engine when ESCAPE trigger is activated
This is the right place to implement things like getting the screen to state before any changes were made
"""
pass
| trigger['mouse_pos'] = event.pos
return trigger | conditional_block |
screen.py | import time
from pygame.locals import *
import gui
MOUSE_LEFT_BUTTON = 1
MOUSE_MIDDLE_BUTTON = 2
MOUSE_RIGHT_BUTTON = 3
MOUSE_WHEELUP = 4
MOUSE_WHEELDOWN = 5
class Screen(object):
"""Base gui screen class
every game screen class should inherit from this one
"""
__triggers = []
__old_hover = None
__hover = None
__hover_changed = False
def __init__(self):
pass
def log_info(self, message):
"""Prints an INFO message to standard output"""
ts = int(time.time())
print("# INFO %i ... %s" % (ts, message))
def log_error(self, message):
"""Prints an ERROR message to standard output"""
ts = int(time.time())
print("! ERROR %i ... %s" % (ts, message))
def reset_triggers_list(self):
"""Clears the screen's trigger list"""
self.__triggers = []
def add_trigger(self, trigger):
"""Appends given trigger to the end of screen's trigger list"""
if not trigger.has_key('hover_id'):
trigger['hover_id'] = None
self.__triggers.append(trigger)
def list_triggers(self):
"""Returns the screen's list of triggers"""
return self.__triggers
def get_timestamp(self, zoom = 1):
"""Returns an actual timestamp"""
return int(time.time() * zoom)
def get_image(self, img_key, subkey1 = None, subkey2 = None, subkey3 = None):
"""Returns an image object from GUI engine, identified by its key(s)"""
return gui.GUI.get_image(img_key, subkey1, subkey2, subkey3)
def redraw_flip(self):
"""Redraws the screen, takes care about mouse cursor and flips the graphic buffer to display"""
self.draw()
gui.GUI.highlight_triggers(self.list_triggers())
gui.GUI.flip()
def redraw_noflip(self):
"""Redraws the screen, takes care about mouse cursor but doesn't flip the buffer to display"""
self.draw()
gui.GUI.highlight_triggers(self.list_triggers())
def prepare(self):
"""This method should be implemented by screens that require some
special actions each time before the screen is run.
For example to reset screen to a well known state to prevent unexpected behaviour.
"""
pass
def draw(self):
"""All static graphic output should be implemented in this method.
Unless there is only a dynamic graphic (animations),
every screen should implement this method.
"""
pass
def animate(self):
"""Entry point for Screen animations, e.g. ship trajectory on MainScreen.
GUI engine calls this method periodically
Animations should be time-dependant - such screens have to implement the timing!
"""
pass
def get_escape_trigger(self):
"""Returns standard trigger for sending escape action"""
return {'action': "ESCAPE"}
def on_mousebuttonup(self, event):
"""Default implementation of mouse click event serving.
Checks the mouse wheel events (up and down scrolling) and regular mouse buttons.
If the event's subject is the left mouse button it checks the mouse position against the trigger list and
returns the first trigger where mouse positions is within its rectangle.
There is a good chance that no screen would have to override this method.
"""
if event.button == MOUSE_MIDDLE_BUTTON:
print event
elif event.button == MOUSE_WHEELUP:
return {'action': "SCROLL_UP"}
elif event.button == MOUSE_WHEELDOWN:
return {'action': "SCROLL_DOWN"}
else:
triggers_list = self.list_triggers()
for trigger in triggers_list:
if trigger['rect'].collidepoint(event.pos):
if event.button == MOUSE_LEFT_BUTTON:
trigger['mouse_pos'] = event.pos
return trigger
elif event.button == MOUSE_RIGHT_BUTTON:
return {'action': "help", 'help': trigger['action']}
def on_keydown(self, event):
"""Default implementation of a keyboard event handling.
If keypress is detected by a GUI engine it calls this method.
The pressed key is checked against the trigger list.
Returns the first trigger where the key matches the pressed or
None if no trigger matches the keypress
There is a good chance that no screen would have to override this method.
"""
print("@ screen.Screen::on_keydown()")
print(" scancode = %i" % event.scancode)
print(" key = %i" % event.key)
if event.key == K_ESCAPE:
return {'action': "ESCAPE"}
else:
triggers_list = self.list_triggers()
for trigger in triggers_list:
if trigger.has_key('key') and trigger['key'] == event.key:
return trigger
return {'action': "key", 'key': event.key}
def update_hover(self, mouse_pos):
"""This method is invoked by a GUI engine on every pure mouse move
and right before the screen's on_mousemotion() method.
Mouse position is checked against screen's trigger list.
If hover is detected (=mouse position is inside the trigger's rectangle)
the trigger is copied and can be returned by get_hover() method
Also if the previously stored value is different than the new one,
the __hover_changed flag is set to True
The idea is to handle mouse hover detection separately,
so other methods could rely on get_hover() and hover_changed() methods.
Probably no screen should require to override this method.
"""
for trigger in self.list_triggers():
if trigger.has_key('hover_id') and trigger['rect'].collidepoint(mouse_pos):
if self.__hover != trigger:
self.__hover_changed = True
self.__hover = trigger
break
def get_hover(self):
"""Returns the current hover trigger"""
return self.__hover
def hover_changed(self):
"""Returns True if screen's hover has changed since last call of this method"""
if self.__hover_changed:
self.__hover_changed = False
return True
else:
return False
def on_mousemotion(self, event):
"""Invoked by a GUI engine on every pure (non-dragging) mouse move.
Currently no screen requires to override this empty implementation.
"""
pass
def get_drag_item(self, mouse_pos):
""""""
for trigger in self.list_triggers():
if trigger.has_key('drag_id') and trigger['rect'].collidepoint(mouse_pos):
return trigger['drag_id']
return None
def on_mousedrag(self, drag_item, pos, rel):
"""Invoked by a GUI engine when left mouse button is being held, drag item is set and mouse moves"""
pass
def on_mousedrop(self, drag_item, (mouse_x, mouse_y)):
"""Invoked by a GUI engine when mouse dragging stops
(drag item was set and left mouse button was released).
"""
pass
def process_trigger(self, trigger):
"""Empty implementation of a trigger handling
If a screen trigger is positively evaluated
(e.g. returned from on_mousebuttonup() or on_keydown() methods)
it's passed as a trigger argument to this method
Every screen should override this method to handle the proper actions.
"""
pass
def enter(self):
""" Called by GUI engine right before gui_client::run_screen() is invoked
Suitable for saving initial state that can be reveresed by the screen's cancel() method
"""
pass
def leave_confirm(self):
""" Called by GUI engine when CONFIRM trigger is activated
Every screen that sends data to the game server should implement this method
| pass
def leave_cancel(self):
""" Called by GUI engine when ESCAPE trigger is activated
This is the right place to implement things like getting the screen to state before any changes were made
"""
pass | """ | random_line_split |
screen.py | import time
from pygame.locals import *
import gui
MOUSE_LEFT_BUTTON = 1
MOUSE_MIDDLE_BUTTON = 2
MOUSE_RIGHT_BUTTON = 3
MOUSE_WHEELUP = 4
MOUSE_WHEELDOWN = 5
class Screen(object):
"""Base gui screen class
every game screen class should inherit from this one
"""
__triggers = []
__old_hover = None
__hover = None
__hover_changed = False
def __init__(self):
pass
def log_info(self, message):
"""Prints an INFO message to standard output"""
ts = int(time.time())
print("# INFO %i ... %s" % (ts, message))
def log_error(self, message):
"""Prints an ERROR message to standard output"""
ts = int(time.time())
print("! ERROR %i ... %s" % (ts, message))
def reset_triggers_list(self):
"""Clears the screen's trigger list"""
self.__triggers = []
def add_trigger(self, trigger):
"""Appends given trigger to the end of screen's trigger list"""
if not trigger.has_key('hover_id'):
trigger['hover_id'] = None
self.__triggers.append(trigger)
def list_triggers(self):
"""Returns the screen's list of triggers"""
return self.__triggers
def get_timestamp(self, zoom = 1):
"""Returns an actual timestamp"""
return int(time.time() * zoom)
def get_image(self, img_key, subkey1 = None, subkey2 = None, subkey3 = None):
"""Returns an image object from GUI engine, identified by its key(s)"""
return gui.GUI.get_image(img_key, subkey1, subkey2, subkey3)
def redraw_flip(self):
"""Redraws the screen, takes care about mouse cursor and flips the graphic buffer to display"""
self.draw()
gui.GUI.highlight_triggers(self.list_triggers())
gui.GUI.flip()
def redraw_noflip(self):
"""Redraws the screen, takes care about mouse cursor but doesn't flip the buffer to display"""
self.draw()
gui.GUI.highlight_triggers(self.list_triggers())
def prepare(self):
"""This method should be implemented by screens that require some
special actions each time before the screen is run.
For example to reset screen to a well known state to prevent unexpected behaviour.
"""
pass
def draw(self):
"""All static graphic output should be implemented in this method.
Unless there is only a dynamic graphic (animations),
every screen should implement this method.
"""
pass
def animate(self):
"""Entry point for Screen animations, e.g. ship trajectory on MainScreen.
GUI engine calls this method periodically
Animations should be time-dependant - such screens have to implement the timing!
"""
pass
def get_escape_trigger(self):
"""Returns standard trigger for sending escape action"""
return {'action': "ESCAPE"}
def on_mousebuttonup(self, event):
"""Default implementation of mouse click event serving.
Checks the mouse wheel events (up and down scrolling) and regular mouse buttons.
If the event's subject is the left mouse button it checks the mouse position against the trigger list and
returns the first trigger where mouse positions is within its rectangle.
There is a good chance that no screen would have to override this method.
"""
if event.button == MOUSE_MIDDLE_BUTTON:
print event
elif event.button == MOUSE_WHEELUP:
return {'action': "SCROLL_UP"}
elif event.button == MOUSE_WHEELDOWN:
return {'action': "SCROLL_DOWN"}
else:
triggers_list = self.list_triggers()
for trigger in triggers_list:
if trigger['rect'].collidepoint(event.pos):
if event.button == MOUSE_LEFT_BUTTON:
trigger['mouse_pos'] = event.pos
return trigger
elif event.button == MOUSE_RIGHT_BUTTON:
return {'action': "help", 'help': trigger['action']}
def on_keydown(self, event):
"""Default implementation of a keyboard event handling.
If keypress is detected by a GUI engine it calls this method.
The pressed key is checked against the trigger list.
Returns the first trigger where the key matches the pressed or
None if no trigger matches the keypress
There is a good chance that no screen would have to override this method.
"""
print("@ screen.Screen::on_keydown()")
print(" scancode = %i" % event.scancode)
print(" key = %i" % event.key)
if event.key == K_ESCAPE:
return {'action': "ESCAPE"}
else:
triggers_list = self.list_triggers()
for trigger in triggers_list:
if trigger.has_key('key') and trigger['key'] == event.key:
return trigger
return {'action': "key", 'key': event.key}
def update_hover(self, mouse_pos):
"""This method is invoked by a GUI engine on every pure mouse move
and right before the screen's on_mousemotion() method.
Mouse position is checked against screen's trigger list.
If hover is detected (=mouse position is inside the trigger's rectangle)
the trigger is copied and can be returned by get_hover() method
Also if the previously stored value is different than the new one,
the __hover_changed flag is set to True
The idea is to handle mouse hover detection separately,
so other methods could rely on get_hover() and hover_changed() methods.
Probably no screen should require to override this method.
"""
for trigger in self.list_triggers():
if trigger.has_key('hover_id') and trigger['rect'].collidepoint(mouse_pos):
if self.__hover != trigger:
self.__hover_changed = True
self.__hover = trigger
break
def get_hover(self):
"""Returns the current hover trigger"""
return self.__hover
def hover_changed(self):
"""Returns True if screen's hover has changed since last call of this method"""
if self.__hover_changed:
self.__hover_changed = False
return True
else:
return False
def on_mousemotion(self, event):
"""Invoked by a GUI engine on every pure (non-dragging) mouse move.
Currently no screen requires to override this empty implementation.
"""
pass
def get_drag_item(self, mouse_pos):
""""""
for trigger in self.list_triggers():
if trigger.has_key('drag_id') and trigger['rect'].collidepoint(mouse_pos):
return trigger['drag_id']
return None
def on_mousedrag(self, drag_item, pos, rel):
"""Invoked by a GUI engine when left mouse button is being held, drag item is set and mouse moves"""
pass
def on_mousedrop(self, drag_item, (mouse_x, mouse_y)):
"""Invoked by a GUI engine when mouse dragging stops
(drag item was set and left mouse button was released).
"""
pass
def process_trigger(self, trigger):
"""Empty implementation of a trigger handling
If a screen trigger is positively evaluated
(e.g. returned from on_mousebuttonup() or on_keydown() methods)
it's passed as a trigger argument to this method
Every screen should override this method to handle the proper actions.
"""
pass
def | (self):
""" Called by GUI engine right before gui_client::run_screen() is invoked
Suitable for saving initial state that can be reveresed by the screen's cancel() method
"""
pass
def leave_confirm(self):
""" Called by GUI engine when CONFIRM trigger is activated
Every screen that sends data to the game server should implement this method
"""
pass
def leave_cancel(self):
""" Called by GUI engine when ESCAPE trigger is activated
This is the right place to implement things like getting the screen to state before any changes were made
"""
pass
| enter | identifier_name |
screen.py | import time
from pygame.locals import *
import gui
MOUSE_LEFT_BUTTON = 1
MOUSE_MIDDLE_BUTTON = 2
MOUSE_RIGHT_BUTTON = 3
MOUSE_WHEELUP = 4
MOUSE_WHEELDOWN = 5
class Screen(object):
"""Base gui screen class
every game screen class should inherit from this one
"""
__triggers = []
__old_hover = None
__hover = None
__hover_changed = False
def __init__(self):
pass
def log_info(self, message):
"""Prints an INFO message to standard output"""
ts = int(time.time())
print("# INFO %i ... %s" % (ts, message))
def log_error(self, message):
"""Prints an ERROR message to standard output"""
ts = int(time.time())
print("! ERROR %i ... %s" % (ts, message))
def reset_triggers_list(self):
"""Clears the screen's trigger list"""
self.__triggers = []
def add_trigger(self, trigger):
"""Appends given trigger to the end of screen's trigger list"""
if not trigger.has_key('hover_id'):
trigger['hover_id'] = None
self.__triggers.append(trigger)
def list_triggers(self):
"""Returns the screen's list of triggers"""
return self.__triggers
def get_timestamp(self, zoom = 1):
|
def get_image(self, img_key, subkey1 = None, subkey2 = None, subkey3 = None):
"""Returns an image object from GUI engine, identified by its key(s)"""
return gui.GUI.get_image(img_key, subkey1, subkey2, subkey3)
def redraw_flip(self):
"""Redraws the screen, takes care about mouse cursor and flips the graphic buffer to display"""
self.draw()
gui.GUI.highlight_triggers(self.list_triggers())
gui.GUI.flip()
def redraw_noflip(self):
"""Redraws the screen, takes care about mouse cursor but doesn't flip the buffer to display"""
self.draw()
gui.GUI.highlight_triggers(self.list_triggers())
def prepare(self):
"""This method should be implemented by screens that require some
special actions each time before the screen is run.
For example to reset screen to a well known state to prevent unexpected behaviour.
"""
pass
def draw(self):
"""All static graphic output should be implemented in this method.
Unless there is only a dynamic graphic (animations),
every screen should implement this method.
"""
pass
def animate(self):
"""Entry point for Screen animations, e.g. ship trajectory on MainScreen.
GUI engine calls this method periodically
Animations should be time-dependant - such screens have to implement the timing!
"""
pass
def get_escape_trigger(self):
"""Returns standard trigger for sending escape action"""
return {'action': "ESCAPE"}
def on_mousebuttonup(self, event):
"""Default implementation of mouse click event serving.
Checks the mouse wheel events (up and down scrolling) and regular mouse buttons.
If the event's subject is the left mouse button it checks the mouse position against the trigger list and
returns the first trigger where mouse positions is within its rectangle.
There is a good chance that no screen would have to override this method.
"""
if event.button == MOUSE_MIDDLE_BUTTON:
print event
elif event.button == MOUSE_WHEELUP:
return {'action': "SCROLL_UP"}
elif event.button == MOUSE_WHEELDOWN:
return {'action': "SCROLL_DOWN"}
else:
triggers_list = self.list_triggers()
for trigger in triggers_list:
if trigger['rect'].collidepoint(event.pos):
if event.button == MOUSE_LEFT_BUTTON:
trigger['mouse_pos'] = event.pos
return trigger
elif event.button == MOUSE_RIGHT_BUTTON:
return {'action': "help", 'help': trigger['action']}
def on_keydown(self, event):
"""Default implementation of a keyboard event handling.
If keypress is detected by a GUI engine it calls this method.
The pressed key is checked against the trigger list.
Returns the first trigger where the key matches the pressed or
None if no trigger matches the keypress
There is a good chance that no screen would have to override this method.
"""
print("@ screen.Screen::on_keydown()")
print(" scancode = %i" % event.scancode)
print(" key = %i" % event.key)
if event.key == K_ESCAPE:
return {'action': "ESCAPE"}
else:
triggers_list = self.list_triggers()
for trigger in triggers_list:
if trigger.has_key('key') and trigger['key'] == event.key:
return trigger
return {'action': "key", 'key': event.key}
def update_hover(self, mouse_pos):
"""This method is invoked by a GUI engine on every pure mouse move
and right before the screen's on_mousemotion() method.
Mouse position is checked against screen's trigger list.
If hover is detected (=mouse position is inside the trigger's rectangle)
the trigger is copied and can be returned by get_hover() method
Also if the previously stored value is different than the new one,
the __hover_changed flag is set to True
The idea is to handle mouse hover detection separately,
so other methods could rely on get_hover() and hover_changed() methods.
Probably no screen should require to override this method.
"""
for trigger in self.list_triggers():
if trigger.has_key('hover_id') and trigger['rect'].collidepoint(mouse_pos):
if self.__hover != trigger:
self.__hover_changed = True
self.__hover = trigger
break
def get_hover(self):
"""Returns the current hover trigger"""
return self.__hover
def hover_changed(self):
"""Returns True if screen's hover has changed since last call of this method"""
if self.__hover_changed:
self.__hover_changed = False
return True
else:
return False
def on_mousemotion(self, event):
"""Invoked by a GUI engine on every pure (non-dragging) mouse move.
Currently no screen requires to override this empty implementation.
"""
pass
def get_drag_item(self, mouse_pos):
""""""
for trigger in self.list_triggers():
if trigger.has_key('drag_id') and trigger['rect'].collidepoint(mouse_pos):
return trigger['drag_id']
return None
def on_mousedrag(self, drag_item, pos, rel):
"""Invoked by a GUI engine when left mouse button is being held, drag item is set and mouse moves"""
pass
def on_mousedrop(self, drag_item, (mouse_x, mouse_y)):
"""Invoked by a GUI engine when mouse dragging stops
(drag item was set and left mouse button was released).
"""
pass
def process_trigger(self, trigger):
"""Empty implementation of a trigger handling
If a screen trigger is positively evaluated
(e.g. returned from on_mousebuttonup() or on_keydown() methods)
it's passed as a trigger argument to this method
Every screen should override this method to handle the proper actions.
"""
pass
def enter(self):
""" Called by GUI engine right before gui_client::run_screen() is invoked
Suitable for saving initial state that can be reveresed by the screen's cancel() method
"""
pass
def leave_confirm(self):
""" Called by GUI engine when CONFIRM trigger is activated
Every screen that sends data to the game server should implement this method
"""
pass
def leave_cancel(self):
""" Called by GUI engine when ESCAPE trigger is activated
This is the right place to implement things like getting the screen to state before any changes were made
"""
pass
| """Returns an actual timestamp"""
return int(time.time() * zoom) | identifier_body |
native.rs | use std::fs::File;
use std::io;
use std::os::unix::fs::MetadataExt;
use std::os::unix::io::AsRawFd;
use nix::errno::Errno;
use crate::util::io::io_err;
mod sys {
use nix::libc::c_int;
#[link(name = "fallocate")]
extern "C" {
pub fn native_fallocate(fd: c_int, len: u64) -> c_int;
}
}
pub fn is_sparse(f: &File) -> io::Result<bool> {
let stat = f.metadata()?;
Ok(stat.blocks() * stat.blksize() < stat.size())
}
pub fn fallocate(f: &File, len: u64) -> io::Result<bool> {
// We ignore the len here, if you actually have a u64 max, then you're kinda fucked either way.
loop {
match unsafe { sys::native_fallocate(f.as_raw_fd(), len) } {
0 => return Ok(true),
-1 => match Errno::last() {
Errno::EOPNOTSUPP | Errno::ENOSYS => {
f.set_len(len)?; | Errno::EINTR => {
continue;
}
e => {
return io_err(e.desc());
}
},
_ => unreachable!(),
}
}
} | return Ok(false);
}
Errno::ENOSPC => {
return io_err("Out of disk space!");
} | random_line_split |
native.rs | use std::fs::File;
use std::io;
use std::os::unix::fs::MetadataExt;
use std::os::unix::io::AsRawFd;
use nix::errno::Errno;
use crate::util::io::io_err;
mod sys {
use nix::libc::c_int;
#[link(name = "fallocate")]
extern "C" {
pub fn native_fallocate(fd: c_int, len: u64) -> c_int;
}
}
pub fn is_sparse(f: &File) -> io::Result<bool> |
pub fn fallocate(f: &File, len: u64) -> io::Result<bool> {
// We ignore the len here, if you actually have a u64 max, then you're kinda fucked either way.
loop {
match unsafe { sys::native_fallocate(f.as_raw_fd(), len) } {
0 => return Ok(true),
-1 => match Errno::last() {
Errno::EOPNOTSUPP | Errno::ENOSYS => {
f.set_len(len)?;
return Ok(false);
}
Errno::ENOSPC => {
return io_err("Out of disk space!");
}
Errno::EINTR => {
continue;
}
e => {
return io_err(e.desc());
}
},
_ => unreachable!(),
}
}
}
| {
let stat = f.metadata()?;
Ok(stat.blocks() * stat.blksize() < stat.size())
} | identifier_body |
native.rs | use std::fs::File;
use std::io;
use std::os::unix::fs::MetadataExt;
use std::os::unix::io::AsRawFd;
use nix::errno::Errno;
use crate::util::io::io_err;
mod sys {
use nix::libc::c_int;
#[link(name = "fallocate")]
extern "C" {
pub fn native_fallocate(fd: c_int, len: u64) -> c_int;
}
}
pub fn is_sparse(f: &File) -> io::Result<bool> {
let stat = f.metadata()?;
Ok(stat.blocks() * stat.blksize() < stat.size())
}
pub fn | (f: &File, len: u64) -> io::Result<bool> {
// We ignore the len here, if you actually have a u64 max, then you're kinda fucked either way.
loop {
match unsafe { sys::native_fallocate(f.as_raw_fd(), len) } {
0 => return Ok(true),
-1 => match Errno::last() {
Errno::EOPNOTSUPP | Errno::ENOSYS => {
f.set_len(len)?;
return Ok(false);
}
Errno::ENOSPC => {
return io_err("Out of disk space!");
}
Errno::EINTR => {
continue;
}
e => {
return io_err(e.desc());
}
},
_ => unreachable!(),
}
}
}
| fallocate | identifier_name |
native.rs | use std::fs::File;
use std::io;
use std::os::unix::fs::MetadataExt;
use std::os::unix::io::AsRawFd;
use nix::errno::Errno;
use crate::util::io::io_err;
mod sys {
use nix::libc::c_int;
#[link(name = "fallocate")]
extern "C" {
pub fn native_fallocate(fd: c_int, len: u64) -> c_int;
}
}
pub fn is_sparse(f: &File) -> io::Result<bool> {
let stat = f.metadata()?;
Ok(stat.blocks() * stat.blksize() < stat.size())
}
pub fn fallocate(f: &File, len: u64) -> io::Result<bool> {
// We ignore the len here, if you actually have a u64 max, then you're kinda fucked either way.
loop {
match unsafe { sys::native_fallocate(f.as_raw_fd(), len) } {
0 => return Ok(true),
-1 => match Errno::last() {
Errno::EOPNOTSUPP | Errno::ENOSYS => {
f.set_len(len)?;
return Ok(false);
}
Errno::ENOSPC => {
return io_err("Out of disk space!");
}
Errno::EINTR => |
e => {
return io_err(e.desc());
}
},
_ => unreachable!(),
}
}
}
| {
continue;
} | conditional_block |
config.rs | use std::io::Read;
use std::fs::File;
use std::path::PathBuf;
use std::env::home_dir;
use serde_json;
#[derive(Debug, Serialize, Deserialize)]
pub struct XyPair {
pub x: u32,
pub y: u32
}
impl XyPair {
#[allow(dead_code)]
pub fn new (x: u32, y: u32) -> Self {
XyPair { x, y }
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Screen {
pub resolution: XyPair,
pub offset: XyPair
}
impl Screen {
#[allow(dead_code)]
pub fn new(x: u32, y: u32, offset_x: u32, offset_y: u32) -> Self {
Screen {
resolution: XyPair::new(x, y),
offset: XyPair::new(offset_x, offset_y)
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub resolution: XyPair,
pub screens: Vec<Screen>
}
impl Config {
#[allow(dead_code)]
pub fn new(x: u32, y: u32, screens: Vec<Screen>) -> Self {
Config {
resolution: XyPair::new(x, y),
screens
}
}
}
fn config_path() -> PathBuf {
home_dir()
.expect("Failed to locate home directory.")
.join(".config")
.join("scrotrim")
.join("config.json")
}
pub fn read_config() -> Config {
let path = config_path();
let mut body = String::new();
let mut file = File::open(&path).expect("Failed to open config.");
file.read_to_string(&mut body).expect("Failed to read config."); | serde_json::from_str(&body).expect("Failed to parse config.")
} | random_line_split |
|
config.rs | use std::io::Read;
use std::fs::File;
use std::path::PathBuf;
use std::env::home_dir;
use serde_json;
#[derive(Debug, Serialize, Deserialize)]
pub struct XyPair {
pub x: u32,
pub y: u32
}
impl XyPair {
#[allow(dead_code)]
pub fn new (x: u32, y: u32) -> Self {
XyPair { x, y }
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Screen {
pub resolution: XyPair,
pub offset: XyPair
}
impl Screen {
#[allow(dead_code)]
pub fn new(x: u32, y: u32, offset_x: u32, offset_y: u32) -> Self {
Screen {
resolution: XyPair::new(x, y),
offset: XyPair::new(offset_x, offset_y)
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub resolution: XyPair,
pub screens: Vec<Screen>
}
impl Config {
#[allow(dead_code)]
pub fn new(x: u32, y: u32, screens: Vec<Screen>) -> Self |
}
fn config_path() -> PathBuf {
home_dir()
.expect("Failed to locate home directory.")
.join(".config")
.join("scrotrim")
.join("config.json")
}
pub fn read_config() -> Config {
let path = config_path();
let mut body = String::new();
let mut file = File::open(&path).expect("Failed to open config.");
file.read_to_string(&mut body).expect("Failed to read config.");
serde_json::from_str(&body).expect("Failed to parse config.")
}
| {
Config {
resolution: XyPair::new(x, y),
screens
}
} | identifier_body |
config.rs | use std::io::Read;
use std::fs::File;
use std::path::PathBuf;
use std::env::home_dir;
use serde_json;
#[derive(Debug, Serialize, Deserialize)]
pub struct XyPair {
pub x: u32,
pub y: u32
}
impl XyPair {
#[allow(dead_code)]
pub fn new (x: u32, y: u32) -> Self {
XyPair { x, y }
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Screen {
pub resolution: XyPair,
pub offset: XyPair
}
impl Screen {
#[allow(dead_code)]
pub fn new(x: u32, y: u32, offset_x: u32, offset_y: u32) -> Self {
Screen {
resolution: XyPair::new(x, y),
offset: XyPair::new(offset_x, offset_y)
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub resolution: XyPair,
pub screens: Vec<Screen>
}
impl Config {
#[allow(dead_code)]
pub fn new(x: u32, y: u32, screens: Vec<Screen>) -> Self {
Config {
resolution: XyPair::new(x, y),
screens
}
}
}
fn | () -> PathBuf {
home_dir()
.expect("Failed to locate home directory.")
.join(".config")
.join("scrotrim")
.join("config.json")
}
pub fn read_config() -> Config {
let path = config_path();
let mut body = String::new();
let mut file = File::open(&path).expect("Failed to open config.");
file.read_to_string(&mut body).expect("Failed to read config.");
serde_json::from_str(&body).expect("Failed to parse config.")
}
| config_path | identifier_name |
mod.rs | use rustc_serialize::json;
use std::fmt;
use std::rc;
use std::collections;
use std::any;
use super::schema;
use super::validators;
pub type KeywordResult = Result<Option<validators::BoxedValidator>, schema::SchemaError>;
pub type KeywordPair = (Vec<&'static str>, Box<Keyword + 'static>);
pub type KeywordPairs = Vec<KeywordPair>;
pub type KeywordMap = collections::HashMap<&'static str, rc::Rc<KeywordConsumer>>;
pub trait Keyword: Sync + any::Any {
fn compile(&self, &json::Json, &schema::WalkContext) -> KeywordResult;
}
impl<T: 'static + Send + Sync + any::Any> Keyword for T where T: Fn(&json::Json, &schema::WalkContext) -> KeywordResult {
fn compile(&self, def: &json::Json, ctx: &schema::WalkContext) -> KeywordResult {
self(def, ctx)
}
}
impl fmt::Debug for Keyword + 'static {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("<keyword>")
}
}
macro_rules! keyword_key_exists {
($val:expr, $key:expr) => {{
let maybe_val = $val.find($key);
if maybe_val.is_none() {
return Ok(None)
} else {
maybe_val.unwrap()
}
}}
}
pub mod multiple_of;
pub mod maxmin;
#[macro_use]
pub mod maxmin_length;
pub mod maxmin_items;
pub mod pattern;
pub mod unique_items;
pub mod items;
pub mod maxmin_properties;
pub mod required;
pub mod properties;
pub mod dependencies;
pub mod enum_;
pub mod type_;
pub mod of;
pub mod ref_;
pub mod not;
pub mod format;
pub fn default() -> KeywordMap {
let mut map = collections::HashMap::new();
decouple_keyword((vec!["multipleOf"], Box::new(multiple_of::MultipleOf)), &mut map);
decouple_keyword((vec!["maximum", "exclusiveMaximum"], Box::new(maxmin::Maximum)), &mut map);
decouple_keyword((vec!["minimum", "exclusiveMinimum"], Box::new(maxmin::Minimum)), &mut map);
decouple_keyword((vec!["maxLength"], Box::new(maxmin_length::MaxLength)), &mut map);
decouple_keyword((vec!["minLength"], Box::new(maxmin_length::MinLength)), &mut map);
decouple_keyword((vec!["pattern"], Box::new(pattern::Pattern)), &mut map);
decouple_keyword((vec!["maxItems"], Box::new(maxmin_items::MaxItems)), &mut map);
decouple_keyword((vec!["minItems"], Box::new(maxmin_items::MinItems)), &mut map);
decouple_keyword((vec!["uniqueItems"], Box::new(unique_items::UniqueItems)), &mut map);
decouple_keyword((vec!["items", "additionalItems"], Box::new(items::Items)), &mut map);
decouple_keyword((vec!["maxProperties"], Box::new(maxmin_properties::MaxProperties)), &mut map);
decouple_keyword((vec!["minProperties"], Box::new(maxmin_properties::MinProperties)), &mut map);
decouple_keyword((vec!["required"], Box::new(required::Required)), &mut map);
decouple_keyword((vec!["properties", "additionalProperties", "patternProperties"], Box::new(properties::Properties)), &mut map);
decouple_keyword((vec!["dependencies"], Box::new(dependencies::Dependencies)), &mut map);
decouple_keyword((vec!["enum"], Box::new(enum_::Enum)), &mut map);
decouple_keyword((vec!["type"], Box::new(type_::Type)), &mut map);
decouple_keyword((vec!["allOf"], Box::new(of::AllOf)), &mut map);
decouple_keyword((vec!["anyOf"], Box::new(of::AnyOf)), &mut map);
decouple_keyword((vec!["oneOf"], Box::new(of::OneOf)), &mut map);
decouple_keyword((vec!["$ref"], Box::new(ref_::Ref)), &mut map);
decouple_keyword((vec!["not"], Box::new(not::Not)), &mut map);
map
}
#[derive(Debug)]
pub struct KeywordConsumer {
pub keys: Vec<&'static str>,
pub keyword: Box<Keyword + 'static>
}
impl KeywordConsumer {
pub fn consume(&self, set: &mut collections::HashSet<&str>) {
for key in self.keys.iter() {
if set.contains(key) {
set.remove(key);
}
}
}
}
pub fn decouple_keyword(keyword_pair: KeywordPair,
map: &mut KeywordMap) | {
let (keys, keyword) = keyword_pair;
let consumer = rc::Rc::new(KeywordConsumer { keys: keys.clone(), keyword: keyword });
for key in keys.iter() {
map.insert(key, consumer.clone());
}
} | identifier_body |
|
mod.rs | use rustc_serialize::json;
use std::fmt;
use std::rc;
use std::collections;
use std::any;
use super::schema;
use super::validators;
pub type KeywordResult = Result<Option<validators::BoxedValidator>, schema::SchemaError>;
pub type KeywordPair = (Vec<&'static str>, Box<Keyword + 'static>);
pub type KeywordPairs = Vec<KeywordPair>;
pub type KeywordMap = collections::HashMap<&'static str, rc::Rc<KeywordConsumer>>;
pub trait Keyword: Sync + any::Any {
fn compile(&self, &json::Json, &schema::WalkContext) -> KeywordResult;
}
impl<T: 'static + Send + Sync + any::Any> Keyword for T where T: Fn(&json::Json, &schema::WalkContext) -> KeywordResult {
fn compile(&self, def: &json::Json, ctx: &schema::WalkContext) -> KeywordResult {
self(def, ctx)
}
}
impl fmt::Debug for Keyword + 'static {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("<keyword>")
}
}
macro_rules! keyword_key_exists {
($val:expr, $key:expr) => {{
let maybe_val = $val.find($key);
if maybe_val.is_none() {
return Ok(None)
} else {
maybe_val.unwrap()
}
}}
}
pub mod multiple_of;
pub mod maxmin;
#[macro_use]
pub mod maxmin_length;
pub mod maxmin_items;
pub mod pattern;
pub mod unique_items;
pub mod items;
pub mod maxmin_properties;
pub mod required;
pub mod properties;
pub mod dependencies;
pub mod enum_;
pub mod type_;
pub mod of;
pub mod ref_;
pub mod not;
pub mod format;
pub fn default() -> KeywordMap {
let mut map = collections::HashMap::new();
decouple_keyword((vec!["multipleOf"], Box::new(multiple_of::MultipleOf)), &mut map);
decouple_keyword((vec!["maximum", "exclusiveMaximum"], Box::new(maxmin::Maximum)), &mut map);
decouple_keyword((vec!["minimum", "exclusiveMinimum"], Box::new(maxmin::Minimum)), &mut map);
decouple_keyword((vec!["maxLength"], Box::new(maxmin_length::MaxLength)), &mut map);
decouple_keyword((vec!["minLength"], Box::new(maxmin_length::MinLength)), &mut map);
decouple_keyword((vec!["pattern"], Box::new(pattern::Pattern)), &mut map);
decouple_keyword((vec!["maxItems"], Box::new(maxmin_items::MaxItems)), &mut map);
decouple_keyword((vec!["minItems"], Box::new(maxmin_items::MinItems)), &mut map);
decouple_keyword((vec!["uniqueItems"], Box::new(unique_items::UniqueItems)), &mut map);
decouple_keyword((vec!["items", "additionalItems"], Box::new(items::Items)), &mut map);
decouple_keyword((vec!["maxProperties"], Box::new(maxmin_properties::MaxProperties)), &mut map);
decouple_keyword((vec!["minProperties"], Box::new(maxmin_properties::MinProperties)), &mut map);
decouple_keyword((vec!["required"], Box::new(required::Required)), &mut map);
decouple_keyword((vec!["properties", "additionalProperties", "patternProperties"], Box::new(properties::Properties)), &mut map);
decouple_keyword((vec!["dependencies"], Box::new(dependencies::Dependencies)), &mut map);
decouple_keyword((vec!["enum"], Box::new(enum_::Enum)), &mut map);
decouple_keyword((vec!["type"], Box::new(type_::Type)), &mut map);
decouple_keyword((vec!["allOf"], Box::new(of::AllOf)), &mut map);
decouple_keyword((vec!["anyOf"], Box::new(of::AnyOf)), &mut map);
decouple_keyword((vec!["oneOf"], Box::new(of::OneOf)), &mut map);
decouple_keyword((vec!["$ref"], Box::new(ref_::Ref)), &mut map);
decouple_keyword((vec!["not"], Box::new(not::Not)), &mut map);
map
}
#[derive(Debug)]
pub struct KeywordConsumer {
pub keys: Vec<&'static str>,
pub keyword: Box<Keyword + 'static>
}
impl KeywordConsumer {
pub fn | (&self, set: &mut collections::HashSet<&str>) {
for key in self.keys.iter() {
if set.contains(key) {
set.remove(key);
}
}
}
}
pub fn decouple_keyword(keyword_pair: KeywordPair,
map: &mut KeywordMap) {
let (keys, keyword) = keyword_pair;
let consumer = rc::Rc::new(KeywordConsumer { keys: keys.clone(), keyword: keyword });
for key in keys.iter() {
map.insert(key, consumer.clone());
}
}
| consume | identifier_name |
mod.rs | use rustc_serialize::json;
use std::fmt;
use std::rc;
use std::collections;
use std::any;
use super::schema;
use super::validators;
pub type KeywordResult = Result<Option<validators::BoxedValidator>, schema::SchemaError>;
pub type KeywordPair = (Vec<&'static str>, Box<Keyword + 'static>);
pub type KeywordPairs = Vec<KeywordPair>;
pub type KeywordMap = collections::HashMap<&'static str, rc::Rc<KeywordConsumer>>;
pub trait Keyword: Sync + any::Any {
fn compile(&self, &json::Json, &schema::WalkContext) -> KeywordResult;
}
impl<T: 'static + Send + Sync + any::Any> Keyword for T where T: Fn(&json::Json, &schema::WalkContext) -> KeywordResult {
fn compile(&self, def: &json::Json, ctx: &schema::WalkContext) -> KeywordResult {
self(def, ctx)
}
}
impl fmt::Debug for Keyword + 'static {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("<keyword>")
}
}
macro_rules! keyword_key_exists {
($val:expr, $key:expr) => {{
let maybe_val = $val.find($key);
if maybe_val.is_none() {
return Ok(None)
} else {
maybe_val.unwrap()
}
}}
}
pub mod multiple_of;
pub mod maxmin;
#[macro_use]
pub mod maxmin_length;
pub mod maxmin_items;
pub mod pattern;
pub mod unique_items;
pub mod items;
pub mod maxmin_properties;
pub mod required;
pub mod properties;
pub mod dependencies;
pub mod enum_;
pub mod type_;
pub mod of;
pub mod ref_;
pub mod not;
pub mod format;
pub fn default() -> KeywordMap {
let mut map = collections::HashMap::new();
decouple_keyword((vec!["multipleOf"], Box::new(multiple_of::MultipleOf)), &mut map);
decouple_keyword((vec!["maximum", "exclusiveMaximum"], Box::new(maxmin::Maximum)), &mut map);
decouple_keyword((vec!["minimum", "exclusiveMinimum"], Box::new(maxmin::Minimum)), &mut map);
decouple_keyword((vec!["maxLength"], Box::new(maxmin_length::MaxLength)), &mut map);
decouple_keyword((vec!["minLength"], Box::new(maxmin_length::MinLength)), &mut map);
decouple_keyword((vec!["pattern"], Box::new(pattern::Pattern)), &mut map);
decouple_keyword((vec!["maxItems"], Box::new(maxmin_items::MaxItems)), &mut map);
decouple_keyword((vec!["minItems"], Box::new(maxmin_items::MinItems)), &mut map);
decouple_keyword((vec!["uniqueItems"], Box::new(unique_items::UniqueItems)), &mut map);
decouple_keyword((vec!["items", "additionalItems"], Box::new(items::Items)), &mut map);
decouple_keyword((vec!["maxProperties"], Box::new(maxmin_properties::MaxProperties)), &mut map);
decouple_keyword((vec!["minProperties"], Box::new(maxmin_properties::MinProperties)), &mut map);
decouple_keyword((vec!["required"], Box::new(required::Required)), &mut map);
decouple_keyword((vec!["properties", "additionalProperties", "patternProperties"], Box::new(properties::Properties)), &mut map);
decouple_keyword((vec!["dependencies"], Box::new(dependencies::Dependencies)), &mut map);
decouple_keyword((vec!["enum"], Box::new(enum_::Enum)), &mut map);
decouple_keyword((vec!["type"], Box::new(type_::Type)), &mut map);
decouple_keyword((vec!["allOf"], Box::new(of::AllOf)), &mut map);
decouple_keyword((vec!["anyOf"], Box::new(of::AnyOf)), &mut map);
decouple_keyword((vec!["oneOf"], Box::new(of::OneOf)), &mut map);
decouple_keyword((vec!["$ref"], Box::new(ref_::Ref)), &mut map);
decouple_keyword((vec!["not"], Box::new(not::Not)), &mut map);
map
}
#[derive(Debug)]
pub struct KeywordConsumer {
pub keys: Vec<&'static str>,
pub keyword: Box<Keyword + 'static>
}
impl KeywordConsumer {
pub fn consume(&self, set: &mut collections::HashSet<&str>) {
for key in self.keys.iter() {
if set.contains(key) |
}
}
}
pub fn decouple_keyword(keyword_pair: KeywordPair,
map: &mut KeywordMap) {
let (keys, keyword) = keyword_pair;
let consumer = rc::Rc::new(KeywordConsumer { keys: keys.clone(), keyword: keyword });
for key in keys.iter() {
map.insert(key, consumer.clone());
}
}
| {
set.remove(key);
} | conditional_block |
mod.rs | use rustc_serialize::json;
use std::fmt;
use std::rc;
use std::collections;
use std::any;
use super::schema;
use super::validators;
pub type KeywordResult = Result<Option<validators::BoxedValidator>, schema::SchemaError>;
pub type KeywordPair = (Vec<&'static str>, Box<Keyword + 'static>);
pub type KeywordPairs = Vec<KeywordPair>;
pub type KeywordMap = collections::HashMap<&'static str, rc::Rc<KeywordConsumer>>;
pub trait Keyword: Sync + any::Any {
fn compile(&self, &json::Json, &schema::WalkContext) -> KeywordResult;
}
impl<T: 'static + Send + Sync + any::Any> Keyword for T where T: Fn(&json::Json, &schema::WalkContext) -> KeywordResult {
fn compile(&self, def: &json::Json, ctx: &schema::WalkContext) -> KeywordResult {
self(def, ctx)
}
}
impl fmt::Debug for Keyword + 'static {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("<keyword>")
}
}
macro_rules! keyword_key_exists {
($val:expr, $key:expr) => {{
let maybe_val = $val.find($key);
if maybe_val.is_none() {
return Ok(None)
} else {
maybe_val.unwrap()
}
}}
}
pub mod multiple_of;
pub mod maxmin;
#[macro_use]
pub mod maxmin_length;
pub mod maxmin_items;
pub mod pattern;
pub mod unique_items;
pub mod items;
pub mod maxmin_properties;
pub mod required;
pub mod properties;
pub mod dependencies;
pub mod enum_;
pub mod type_;
pub mod of;
pub mod ref_;
pub mod not;
pub mod format;
pub fn default() -> KeywordMap {
let mut map = collections::HashMap::new();
decouple_keyword((vec!["multipleOf"], Box::new(multiple_of::MultipleOf)), &mut map);
decouple_keyword((vec!["maximum", "exclusiveMaximum"], Box::new(maxmin::Maximum)), &mut map);
decouple_keyword((vec!["minimum", "exclusiveMinimum"], Box::new(maxmin::Minimum)), &mut map);
decouple_keyword((vec!["maxLength"], Box::new(maxmin_length::MaxLength)), &mut map);
decouple_keyword((vec!["minLength"], Box::new(maxmin_length::MinLength)), &mut map);
decouple_keyword((vec!["pattern"], Box::new(pattern::Pattern)), &mut map);
decouple_keyword((vec!["maxItems"], Box::new(maxmin_items::MaxItems)), &mut map);
decouple_keyword((vec!["minItems"], Box::new(maxmin_items::MinItems)), &mut map);
decouple_keyword((vec!["uniqueItems"], Box::new(unique_items::UniqueItems)), &mut map);
decouple_keyword((vec!["items", "additionalItems"], Box::new(items::Items)), &mut map);
decouple_keyword((vec!["maxProperties"], Box::new(maxmin_properties::MaxProperties)), &mut map);
decouple_keyword((vec!["minProperties"], Box::new(maxmin_properties::MinProperties)), &mut map);
decouple_keyword((vec!["required"], Box::new(required::Required)), &mut map);
decouple_keyword((vec!["properties", "additionalProperties", "patternProperties"], Box::new(properties::Properties)), &mut map);
decouple_keyword((vec!["dependencies"], Box::new(dependencies::Dependencies)), &mut map);
decouple_keyword((vec!["enum"], Box::new(enum_::Enum)), &mut map);
decouple_keyword((vec!["type"], Box::new(type_::Type)), &mut map);
decouple_keyword((vec!["allOf"], Box::new(of::AllOf)), &mut map);
decouple_keyword((vec!["anyOf"], Box::new(of::AnyOf)), &mut map);
decouple_keyword((vec!["oneOf"], Box::new(of::OneOf)), &mut map);
decouple_keyword((vec!["$ref"], Box::new(ref_::Ref)), &mut map);
decouple_keyword((vec!["not"], Box::new(not::Not)), &mut map);
map
}
#[derive(Debug)]
pub struct KeywordConsumer {
pub keys: Vec<&'static str>,
pub keyword: Box<Keyword + 'static>
}
| }
}
}
}
pub fn decouple_keyword(keyword_pair: KeywordPair,
map: &mut KeywordMap) {
let (keys, keyword) = keyword_pair;
let consumer = rc::Rc::new(KeywordConsumer { keys: keys.clone(), keyword: keyword });
for key in keys.iter() {
map.insert(key, consumer.clone());
}
} | impl KeywordConsumer {
pub fn consume(&self, set: &mut collections::HashSet<&str>) {
for key in self.keys.iter() {
if set.contains(key) {
set.remove(key); | random_line_split |
index-tests.tsx | import { Theme } from "@artsy/palette"
import { mount } from "enzyme"
import React from "react"
import { FairEventSection } from "../index"
const data = [
{
name: "TEFAF New York Fall 2019",
id: "RmFpcjp0ZWZhZi1uZXcteW9yay1mYWxsLTIwMTk=",
gravityID: "tefaf-new-york-fall-2019",
image: {
aspect_ratio: 1,
url: "https://d32dm0rphc51dk.cloudfront.net/3cn9Ln3DfEnHxJcjvfBNKA/wide.jpg",
},
end_at: "2001-12-15T12:00:00+00:00",
start_at: "2001-11-12T12:00:00+00:00",
},
] as any[]
describe("FairEventSection", () => {
it("renders properly", () => {
const comp = mount(
<Theme>
<FairEventSection data={data} citySlug="tefaf-new-york-fall-2019" /> | }) | </Theme>
)
expect(comp.text()).toContain("TEFAF New York Fall 2019")
}) | random_line_split |
ReportRaidBuffList.tsx | import React from 'react';
import SPECS from 'game/SPECS';
import SPELLS from 'common/SPELLS';
import { Class, CombatantInfoEvent } from 'parser/core/Events';
import './ReportRaidBuffList.scss';
import ReportRaidBuffListItem from './ReportRaidBuffListItem';
const AVAILABLE_RAID_BUFFS = new Map<number, Array<Class | object>>([
// Buffs
// Stamina
[SPELLS.POWER_WORD_FORTITUDE.id, [Class.Priest]],
// Attack Power
[SPELLS.BATTLE_SHOUT.id, [Class.Warrior]],
// Intellect
[SPELLS.ARCANE_INTELLECT.id, [Class.Mage]],
// Debuffs
// Magic vulnerability
[SPELLS.CHAOS_BRAND.id, [Class.DemonHunter]],
// Physical vulnerability
[SPELLS.MYSTIC_TOUCH.id, [Class.Monk]],
// Raid cooldowns
[SPELLS.BLOODLUST.id, [Class.Shaman, Class.Mage, Class.Hunter]],
// Battle res
[SPELLS.REBIRTH.id, [Class.Druid, Class.DeathKnight, Class.Warlock]],
[SPELLS.RALLYING_CRY.id, [Class.Warrior]],
[SPELLS.ANTI_MAGIC_ZONE.id, [Class.DeathKnight]],
[SPELLS.DARKNESS.id, [SPECS.HAVOC_DEMON_HUNTER]],
[SPELLS.AURA_MASTERY.id, [SPECS.HOLY_PALADIN]],
[SPELLS.SPIRIT_LINK_TOTEM.id, [SPECS.RESTORATION_SHAMAN]],
[SPELLS.HEALING_TIDE_TOTEM_CAST.id, [SPECS.RESTORATION_SHAMAN]],
[SPELLS.REVIVAL.id, [SPECS.MISTWEAVER_MONK]],
[SPELLS.POWER_WORD_BARRIER_CAST.id, [SPECS.DISCIPLINE_PRIEST]],
[SPELLS.DIVINE_HYMN_CAST.id, [SPECS.HOLY_PRIEST]],
[SPELLS.HOLY_WORD_SALVATION_TALENT.id, [SPECS.HOLY_PRIEST]],
[SPELLS.TRANQUILITY_CAST.id, [SPECS.RESTORATION_DRUID]],
]);
const getCompositionBreakdown = (combatants: CombatantInfoEvent[]) => {
const results = new Map<number, number>();
AVAILABLE_RAID_BUFFS.forEach((providedBy, spellId) => {
results.set(spellId, 0);
});
return combatants.reduce((map, combatant) => {
const spec = SPECS[combatant.specID];
if (!spec) {
return map;
}
const className = spec.className;
AVAILABLE_RAID_BUFFS.forEach((providedBy, spellId) => {
if (providedBy.includes(className) || providedBy.includes(spec)) |
});
return map;
}, results);
};
interface Props {
combatants: CombatantInfoEvent[];
}
const ReportRaidBuffList = ({ combatants }: Props) => {
const buffs = getCompositionBreakdown(combatants);
return (
<div className="raidbuffs">
<h1>Raid Buffs</h1>
{Array.from(buffs, ([spellId, count]) => (
<ReportRaidBuffListItem
key={spellId}
spellId={Number(spellId)}
count={count}
/>
))}
</div>
);
};
export default ReportRaidBuffList;
| {
map.set(spellId, map.get(spellId)! + 1);
} | conditional_block |
ReportRaidBuffList.tsx | import React from 'react';
import SPECS from 'game/SPECS';
import SPELLS from 'common/SPELLS';
import { Class, CombatantInfoEvent } from 'parser/core/Events';
import './ReportRaidBuffList.scss';
import ReportRaidBuffListItem from './ReportRaidBuffListItem';
const AVAILABLE_RAID_BUFFS = new Map<number, Array<Class | object>>([
// Buffs
// Stamina
[SPELLS.POWER_WORD_FORTITUDE.id, [Class.Priest]],
// Attack Power
[SPELLS.BATTLE_SHOUT.id, [Class.Warrior]],
// Intellect
[SPELLS.ARCANE_INTELLECT.id, [Class.Mage]],
// Debuffs
// Magic vulnerability
[SPELLS.CHAOS_BRAND.id, [Class.DemonHunter]],
// Physical vulnerability
[SPELLS.MYSTIC_TOUCH.id, [Class.Monk]],
// Raid cooldowns
[SPELLS.BLOODLUST.id, [Class.Shaman, Class.Mage, Class.Hunter]],
// Battle res
[SPELLS.REBIRTH.id, [Class.Druid, Class.DeathKnight, Class.Warlock]],
[SPELLS.RALLYING_CRY.id, [Class.Warrior]],
[SPELLS.ANTI_MAGIC_ZONE.id, [Class.DeathKnight]],
[SPELLS.DARKNESS.id, [SPECS.HAVOC_DEMON_HUNTER]],
[SPELLS.AURA_MASTERY.id, [SPECS.HOLY_PALADIN]],
[SPELLS.SPIRIT_LINK_TOTEM.id, [SPECS.RESTORATION_SHAMAN]],
[SPELLS.HEALING_TIDE_TOTEM_CAST.id, [SPECS.RESTORATION_SHAMAN]],
[SPELLS.REVIVAL.id, [SPECS.MISTWEAVER_MONK]],
[SPELLS.POWER_WORD_BARRIER_CAST.id, [SPECS.DISCIPLINE_PRIEST]],
[SPELLS.DIVINE_HYMN_CAST.id, [SPECS.HOLY_PRIEST]],
[SPELLS.HOLY_WORD_SALVATION_TALENT.id, [SPECS.HOLY_PRIEST]],
[SPELLS.TRANQUILITY_CAST.id, [SPECS.RESTORATION_DRUID]],
]);
| });
return combatants.reduce((map, combatant) => {
const spec = SPECS[combatant.specID];
if (!spec) {
return map;
}
const className = spec.className;
AVAILABLE_RAID_BUFFS.forEach((providedBy, spellId) => {
if (providedBy.includes(className) || providedBy.includes(spec)) {
map.set(spellId, map.get(spellId)! + 1);
}
});
return map;
}, results);
};
interface Props {
combatants: CombatantInfoEvent[];
}
const ReportRaidBuffList = ({ combatants }: Props) => {
const buffs = getCompositionBreakdown(combatants);
return (
<div className="raidbuffs">
<h1>Raid Buffs</h1>
{Array.from(buffs, ([spellId, count]) => (
<ReportRaidBuffListItem
key={spellId}
spellId={Number(spellId)}
count={count}
/>
))}
</div>
);
};
export default ReportRaidBuffList; | const getCompositionBreakdown = (combatants: CombatantInfoEvent[]) => {
const results = new Map<number, number>();
AVAILABLE_RAID_BUFFS.forEach((providedBy, spellId) => {
results.set(spellId, 0); | random_line_split |
a02762.js | var a02762 =
[
[ "AmbigSpec", "a02762.html#aaa3a04113f5db03951771afa6423e7f4", null ],
[ "~AmbigSpec", "a02762.html#a5283933a9e7267b3505f5f18cf289f3e", null ],
[ "correct_fragments", "a02762.html#ad3a4b121b26cf829422700494aed91e4", null ], | [ "wrong_ngram_size", "a02762.html#a4cfb10d18b7c636f3afa5f223afa445e", null ]
]; | [ "correct_ngram_id", "a02762.html#a879c6167dbfc54980bfeb5a15b32bf73", null ],
[ "type", "a02762.html#ae29644f82c6feac4df14b22368fa0873", null ],
[ "wrong_ngram", "a02762.html#a9d7f07e5b038c6d61acc9bb75ba7ef1b", null ], | random_line_split |
__init__.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Pecan Controllers"""
from cdn.transport.pecan.controllers import root
from cdn.transport.pecan.controllers import services
from cdn.transport.pecan.controllers import v1
# Hoist into package namespace
Root = root.RootController
Services = services.ServicesController
V1 = v1.ControllerV1 | # Copyright (c) 2014 Rackspace, Inc.
# | random_line_split |
|
clean_raxml_parsimony_tree.py | #!/usr/bin/env python
# File created on 10 Nov 2011
from __future__ import division
__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Jesse Stombaugh"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Jesse Stombaugh"
__email__ = "[email protected]"
from qiime.util import parse_command_line_parameters, make_option
from cogent.parse.tree import DndParser
from cogent.core.tree import PhyloNode
from qiime.clean_raxml_parsimony_tree import decorate_numtips, decorate_depth,\
get_insert_dict, drop_duplicate_nodes
scoring_methods = ['depth', 'numtips']
script_info = {}
script_info['brief_description'] = "Remove duplicate tips from Raxml Tree"
script_info[
'script_description'] = "This script allows the user to remove specific duplicate tips from a Raxml tree."
script_info['script_usage'] = []
script_info['script_usage'].append(
("Example (depth):",
"For this case the user can pass in input Raxml tree, duplicate tips, and define an output filepath. When using the depth option, only the deepest replicate is kept. ",
" %prog -i raxml_v730_final_placement.tre -t 6 -o raxml_v730_final_placement_depth.tre"))
script_info['script_usage'].append(
("Example (numtips):",
"For this case the user can pass in input Raxml tree, duplicate tips, and define an output filepath. When using the numtips option, the replicate with the fewest siblings is kept. ",
" %prog -i raxml_v730_final_placement.tre -t 6 -o raxml_v730_final_placement_numtips.tre -s numtips"))
script_info['output_description'] = ""
script_info['required_options'] = [
make_option(
'-i',
'--input_tree',
type="existing_filepath",
help='the input raxml parsimony tree'),
make_option(
'-t',
'--tips_to_keep',
type="string",
help='the input tips to score and retain (comma-separated list)'),
make_option(
'-o',
'--output_fp',
type="new_filepath",
help='the output filepath'),
]
script_info['optional_options'] = [
make_option(
'-s',
'--scoring_method',
type="choice",
help='the scoring method either depth or numtips [default: %default]',
default='depth',
choices=scoring_methods),
]
script_info['version'] = __version__
def main():
option_parser, opts, args =\
parse_command_line_parameters(**script_info)
# get options
tree_fp = opts.input_tree
tips_to_keep = opts.tips_to_keep.split(',')
scoring_method = opts.scoring_method
# load tree
tree = DndParser(open(tree_fp, 'U'), constructor=PhyloNode)
# decorate measurements onto tree (either by depth or by number of
# children)
if scoring_method == 'depth':
tree2 = decorate_depth(tree)
elif scoring_method == 'numtips':
|
# get the nodes for the inserted sequences
nodes_dict = get_insert_dict(tree2, set(tips_to_keep))
# remove nodes accordingly
final_tree = drop_duplicate_nodes(tree2, nodes_dict)
# final_tree.nameUnnamedNodes()
# write out the resulting tree
open_outpath = open(opts.output_fp, 'w')
open_outpath.write(final_tree.getNewick(with_distances=True))
open_outpath.close()
if __name__ == "__main__":
main()
| tree2 = decorate_numtips(tree) | conditional_block |
clean_raxml_parsimony_tree.py | #!/usr/bin/env python
# File created on 10 Nov 2011
from __future__ import division
__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Jesse Stombaugh"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Jesse Stombaugh"
__email__ = "[email protected]"
from qiime.util import parse_command_line_parameters, make_option
from cogent.parse.tree import DndParser
from cogent.core.tree import PhyloNode
from qiime.clean_raxml_parsimony_tree import decorate_numtips, decorate_depth,\
get_insert_dict, drop_duplicate_nodes
scoring_methods = ['depth', 'numtips']
script_info = {}
script_info['brief_description'] = "Remove duplicate tips from Raxml Tree" | script_info['script_usage'] = []
script_info['script_usage'].append(
("Example (depth):",
"For this case the user can pass in input Raxml tree, duplicate tips, and define an output filepath. When using the depth option, only the deepest replicate is kept. ",
" %prog -i raxml_v730_final_placement.tre -t 6 -o raxml_v730_final_placement_depth.tre"))
script_info['script_usage'].append(
("Example (numtips):",
"For this case the user can pass in input Raxml tree, duplicate tips, and define an output filepath. When using the numtips option, the replicate with the fewest siblings is kept. ",
" %prog -i raxml_v730_final_placement.tre -t 6 -o raxml_v730_final_placement_numtips.tre -s numtips"))
script_info['output_description'] = ""
script_info['required_options'] = [
make_option(
'-i',
'--input_tree',
type="existing_filepath",
help='the input raxml parsimony tree'),
make_option(
'-t',
'--tips_to_keep',
type="string",
help='the input tips to score and retain (comma-separated list)'),
make_option(
'-o',
'--output_fp',
type="new_filepath",
help='the output filepath'),
]
script_info['optional_options'] = [
make_option(
'-s',
'--scoring_method',
type="choice",
help='the scoring method either depth or numtips [default: %default]',
default='depth',
choices=scoring_methods),
]
script_info['version'] = __version__
def main():
option_parser, opts, args =\
parse_command_line_parameters(**script_info)
# get options
tree_fp = opts.input_tree
tips_to_keep = opts.tips_to_keep.split(',')
scoring_method = opts.scoring_method
# load tree
tree = DndParser(open(tree_fp, 'U'), constructor=PhyloNode)
# decorate measurements onto tree (either by depth or by number of
# children)
if scoring_method == 'depth':
tree2 = decorate_depth(tree)
elif scoring_method == 'numtips':
tree2 = decorate_numtips(tree)
# get the nodes for the inserted sequences
nodes_dict = get_insert_dict(tree2, set(tips_to_keep))
# remove nodes accordingly
final_tree = drop_duplicate_nodes(tree2, nodes_dict)
# final_tree.nameUnnamedNodes()
# write out the resulting tree
open_outpath = open(opts.output_fp, 'w')
open_outpath.write(final_tree.getNewick(with_distances=True))
open_outpath.close()
if __name__ == "__main__":
main() | script_info[
'script_description'] = "This script allows the user to remove specific duplicate tips from a Raxml tree." | random_line_split |
clean_raxml_parsimony_tree.py | #!/usr/bin/env python
# File created on 10 Nov 2011
from __future__ import division
__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Jesse Stombaugh"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Jesse Stombaugh"
__email__ = "[email protected]"
from qiime.util import parse_command_line_parameters, make_option
from cogent.parse.tree import DndParser
from cogent.core.tree import PhyloNode
from qiime.clean_raxml_parsimony_tree import decorate_numtips, decorate_depth,\
get_insert_dict, drop_duplicate_nodes
scoring_methods = ['depth', 'numtips']
script_info = {}
script_info['brief_description'] = "Remove duplicate tips from Raxml Tree"
script_info[
'script_description'] = "This script allows the user to remove specific duplicate tips from a Raxml tree."
script_info['script_usage'] = []
script_info['script_usage'].append(
("Example (depth):",
"For this case the user can pass in input Raxml tree, duplicate tips, and define an output filepath. When using the depth option, only the deepest replicate is kept. ",
" %prog -i raxml_v730_final_placement.tre -t 6 -o raxml_v730_final_placement_depth.tre"))
script_info['script_usage'].append(
("Example (numtips):",
"For this case the user can pass in input Raxml tree, duplicate tips, and define an output filepath. When using the numtips option, the replicate with the fewest siblings is kept. ",
" %prog -i raxml_v730_final_placement.tre -t 6 -o raxml_v730_final_placement_numtips.tre -s numtips"))
script_info['output_description'] = ""
script_info['required_options'] = [
make_option(
'-i',
'--input_tree',
type="existing_filepath",
help='the input raxml parsimony tree'),
make_option(
'-t',
'--tips_to_keep',
type="string",
help='the input tips to score and retain (comma-separated list)'),
make_option(
'-o',
'--output_fp',
type="new_filepath",
help='the output filepath'),
]
script_info['optional_options'] = [
make_option(
'-s',
'--scoring_method',
type="choice",
help='the scoring method either depth or numtips [default: %default]',
default='depth',
choices=scoring_methods),
]
script_info['version'] = __version__
def main():
|
# remove nodes accordingly
final_tree = drop_duplicate_nodes(tree2, nodes_dict)
# final_tree.nameUnnamedNodes()
# write out the resulting tree
open_outpath = open(opts.output_fp, 'w')
open_outpath.write(final_tree.getNewick(with_distances=True))
open_outpath.close()
if __name__ == "__main__":
main()
| option_parser, opts, args =\
parse_command_line_parameters(**script_info)
# get options
tree_fp = opts.input_tree
tips_to_keep = opts.tips_to_keep.split(',')
scoring_method = opts.scoring_method
# load tree
tree = DndParser(open(tree_fp, 'U'), constructor=PhyloNode)
# decorate measurements onto tree (either by depth or by number of
# children)
if scoring_method == 'depth':
tree2 = decorate_depth(tree)
elif scoring_method == 'numtips':
tree2 = decorate_numtips(tree)
# get the nodes for the inserted sequences
nodes_dict = get_insert_dict(tree2, set(tips_to_keep)) | identifier_body |
clean_raxml_parsimony_tree.py | #!/usr/bin/env python
# File created on 10 Nov 2011
from __future__ import division
__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Jesse Stombaugh"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Jesse Stombaugh"
__email__ = "[email protected]"
from qiime.util import parse_command_line_parameters, make_option
from cogent.parse.tree import DndParser
from cogent.core.tree import PhyloNode
from qiime.clean_raxml_parsimony_tree import decorate_numtips, decorate_depth,\
get_insert_dict, drop_duplicate_nodes
scoring_methods = ['depth', 'numtips']
script_info = {}
script_info['brief_description'] = "Remove duplicate tips from Raxml Tree"
script_info[
'script_description'] = "This script allows the user to remove specific duplicate tips from a Raxml tree."
script_info['script_usage'] = []
script_info['script_usage'].append(
("Example (depth):",
"For this case the user can pass in input Raxml tree, duplicate tips, and define an output filepath. When using the depth option, only the deepest replicate is kept. ",
" %prog -i raxml_v730_final_placement.tre -t 6 -o raxml_v730_final_placement_depth.tre"))
script_info['script_usage'].append(
("Example (numtips):",
"For this case the user can pass in input Raxml tree, duplicate tips, and define an output filepath. When using the numtips option, the replicate with the fewest siblings is kept. ",
" %prog -i raxml_v730_final_placement.tre -t 6 -o raxml_v730_final_placement_numtips.tre -s numtips"))
script_info['output_description'] = ""
script_info['required_options'] = [
make_option(
'-i',
'--input_tree',
type="existing_filepath",
help='the input raxml parsimony tree'),
make_option(
'-t',
'--tips_to_keep',
type="string",
help='the input tips to score and retain (comma-separated list)'),
make_option(
'-o',
'--output_fp',
type="new_filepath",
help='the output filepath'),
]
script_info['optional_options'] = [
make_option(
'-s',
'--scoring_method',
type="choice",
help='the scoring method either depth or numtips [default: %default]',
default='depth',
choices=scoring_methods),
]
script_info['version'] = __version__
def | ():
option_parser, opts, args =\
parse_command_line_parameters(**script_info)
# get options
tree_fp = opts.input_tree
tips_to_keep = opts.tips_to_keep.split(',')
scoring_method = opts.scoring_method
# load tree
tree = DndParser(open(tree_fp, 'U'), constructor=PhyloNode)
# decorate measurements onto tree (either by depth or by number of
# children)
if scoring_method == 'depth':
tree2 = decorate_depth(tree)
elif scoring_method == 'numtips':
tree2 = decorate_numtips(tree)
# get the nodes for the inserted sequences
nodes_dict = get_insert_dict(tree2, set(tips_to_keep))
# remove nodes accordingly
final_tree = drop_duplicate_nodes(tree2, nodes_dict)
# final_tree.nameUnnamedNodes()
# write out the resulting tree
open_outpath = open(opts.output_fp, 'w')
open_outpath.write(final_tree.getNewick(with_distances=True))
open_outpath.close()
if __name__ == "__main__":
main()
| main | identifier_name |
Ping.py | '''
@author: [email protected]
A pure python ping implementation using raw socket.
Note that ICMP messages can only be sent from processes running as root.
Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>.
'''
import os
import select
import socket
import struct
import time
class Ping:
''' Power On State Pint Utility (3rdparty)'''
def __init__(self):
self.ICMP_ECHO_REQUEST = 8
def checksum(self, source_string):
summ = 0
count_to = (len(source_string)/2)*2
for count in xrange(0, count_to, 2):
this = ord(source_string[count+1]) * 256 + ord(source_string[count])
summ = summ + this
summ = summ & 0xffffffff
if count_to < len(source_string):
summ = summ + ord(source_string[len(source_string)-1])
summ = summ & 0xffffffff
summ = (summ >> 16) + (summ & 0xffff)
summ = summ + (summ >> 16)
answer = ~summ
answer = answer & 0xffff
# Swap bytes
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receive_one_ping(self, my_socket, idd, timeout):
'''Receive the ping from the socket'''
time_left = timeout
while True:
started_select = time.time()
what_ready = select.select([my_socket], [], [], time_left)
how_long_in_select = (time.time() - started_select)
if what_ready[0] == []: # Timeout
return
time_received = time.time()
received_packet, addr = my_socket.recvfrom(1024)
icmpHeader = received_packet[20:28]
type, code, checksum, packet_id, sequence = struct.unpack("bbHHh", icmpHeader)
if packet_id == idd:
bytess = struct.calcsize("d")
time_sent = struct.unpack("d", received_packet[28:28 + bytess])[0]
return time_received - time_sent
time_left = time_left - how_long_in_select
if time_left <= 0:
return
def send_one_ping(self, my_socket, dest_addr, idd, psize):
'''Send one ping to the given address'''
dest_addr = socket.gethostbyname(dest_addr)
# Remove header size from packet size
psize = psize - 8
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
my_checksum = 0
# Make a dummy header with a 0 checksum
header = struct.pack("bbHHh", self.ICMP_ECHO_REQUEST, 0, my_checksum, idd, 1)
bytess = struct.calcsize("d")
data = (psize - bytess) * "Q"
data = struct.pack("d", time.time()) + data
# Calculate the checksum on the data and the dummy header
my_checksum = self.checksum(header+data)
# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy
header = struct.pack("bbHHh", self.ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), idd, 1)
packet = header + data
my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def do_one(self, dest_addr, timeout, psize):
'''Returns either the delay (in seconds) or none on timeout'''
icmp = socket.getprotobyname("icmp")
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.errno, (errno, msg):
if errno == 1:
# Operation not permitted
msg = msg + (
" - Note that ICMP messages can only be sent from processes"
" running as root."
)
raise socket.error(msg)
my_id = os.getpid() & 0xFFFF |
my_socket.close()
return delay
def verbose_ping(self, dest_addr, timeout = 2, count = 4, psize = 64):
'''
Send 'count' ping with 'psize' size to 'dest_addr' with
the given 'timeout' and display the result
'''
for i in xrange(count):
print 'ping %s with ...' % dest_addr
try:
delay = self.do_one(dest_addr, timeout, psize)
except socket.gaierror, e:
print 'FAILED. (socket error: "%s")' % e[1]
break
if delay == None:
print 'FAILED. (timeout within %ssec.)' % timeout
else:
delay = delay * 1000
print 'get ping in %0.4fms' % delay
print
def quiet_ping(self, dest_addr, timeout = 2, count = 4, psize = 64):
'''
Send 'count' pint with 'psize' size to 'dest_addr' with
the given 'timeout' and display the result.
Returns 'percent' lost packages, 'max' round trip time
and 'avg' round trip time.
'''
mrtt = None
artt = None
plist = []
for i in xrange(count):
try:
delay = self.do_one(dest_addr, timeout, psize)
except socket.gaierror, e:
print 'FAILED. (socket error: "%s")' % e[1]
break
if delay != None:
delay = delay * 1000
plist.append(delay)
# Find lost package percent
percent_lost = 100 - (len(plist)*100/count)
# Find max and avg round trip time
if plist:
mrtt = max(plist)
artt = sum(plist)/len(plist)
return percent_lost, mrtt, artt | self.send_one_ping(my_socket, dest_addr, my_id, psize)
delay = self.receive_one_ping(my_socket, my_id, timeout) | random_line_split |
Ping.py | '''
@author: [email protected]
A pure python ping implementation using raw socket.
Note that ICMP messages can only be sent from processes running as root.
Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>.
'''
import os
import select
import socket
import struct
import time
class Ping:
''' Power On State Pint Utility (3rdparty)'''
def __init__(self):
self.ICMP_ECHO_REQUEST = 8
def checksum(self, source_string):
summ = 0
count_to = (len(source_string)/2)*2
for count in xrange(0, count_to, 2):
this = ord(source_string[count+1]) * 256 + ord(source_string[count])
summ = summ + this
summ = summ & 0xffffffff
if count_to < len(source_string):
summ = summ + ord(source_string[len(source_string)-1])
summ = summ & 0xffffffff
summ = (summ >> 16) + (summ & 0xffff)
summ = summ + (summ >> 16)
answer = ~summ
answer = answer & 0xffff
# Swap bytes
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receive_one_ping(self, my_socket, idd, timeout):
| if time_left <= 0:
return
def send_one_ping(self, my_socket, dest_addr, idd, psize):
'''Send one ping to the given address'''
dest_addr = socket.gethostbyname(dest_addr)
# Remove header size from packet size
psize = psize - 8
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
my_checksum = 0
# Make a dummy header with a 0 checksum
header = struct.pack("bbHHh", self.ICMP_ECHO_REQUEST, 0, my_checksum, idd, 1)
bytess = struct.calcsize("d")
data = (psize - bytess) * "Q"
data = struct.pack("d", time.time()) + data
# Calculate the checksum on the data and the dummy header
my_checksum = self.checksum(header+data)
# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy
header = struct.pack("bbHHh", self.ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), idd, 1)
packet = header + data
my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def do_one(self, dest_addr, timeout, psize):
'''Returns either the delay (in seconds) or none on timeout'''
icmp = socket.getprotobyname("icmp")
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.errno, (errno, msg):
if errno == 1:
# Operation not permitted
msg = msg + (
" - Note that ICMP messages can only be sent from processes"
" running as root."
)
raise socket.error(msg)
my_id = os.getpid() & 0xFFFF
self.send_one_ping(my_socket, dest_addr, my_id, psize)
delay = self.receive_one_ping(my_socket, my_id, timeout)
my_socket.close()
return delay
def verbose_ping(self, dest_addr, timeout = 2, count = 4, psize = 64):
'''
Send 'count' ping with 'psize' size to 'dest_addr' with
the given 'timeout' and display the result
'''
for i in xrange(count):
print 'ping %s with ...' % dest_addr
try:
delay = self.do_one(dest_addr, timeout, psize)
except socket.gaierror, e:
print 'FAILED. (socket error: "%s")' % e[1]
break
if delay == None:
print 'FAILED. (timeout within %ssec.)' % timeout
else:
delay = delay * 1000
print 'get ping in %0.4fms' % delay
print
def quiet_ping(self, dest_addr, timeout = 2, count = 4, psize = 64):
'''
Send 'count' pint with 'psize' size to 'dest_addr' with
the given 'timeout' and display the result.
Returns 'percent' lost packages, 'max' round trip time
and 'avg' round trip time.
'''
mrtt = None
artt = None
plist = []
for i in xrange(count):
try:
delay = self.do_one(dest_addr, timeout, psize)
except socket.gaierror, e:
print 'FAILED. (socket error: "%s")' % e[1]
break
if delay != None:
delay = delay * 1000
plist.append(delay)
# Find lost package percent
percent_lost = 100 - (len(plist)*100/count)
# Find max and avg round trip time
if plist:
mrtt = max(plist)
artt = sum(plist)/len(plist)
return percent_lost, mrtt, artt | '''Receive the ping from the socket'''
time_left = timeout
while True:
started_select = time.time()
what_ready = select.select([my_socket], [], [], time_left)
how_long_in_select = (time.time() - started_select)
if what_ready[0] == []: # Timeout
return
time_received = time.time()
received_packet, addr = my_socket.recvfrom(1024)
icmpHeader = received_packet[20:28]
type, code, checksum, packet_id, sequence = struct.unpack("bbHHh", icmpHeader)
if packet_id == idd:
bytess = struct.calcsize("d")
time_sent = struct.unpack("d", received_packet[28:28 + bytess])[0]
return time_received - time_sent
time_left = time_left - how_long_in_select | identifier_body |
Ping.py | '''
@author: [email protected]
A pure python ping implementation using raw socket.
Note that ICMP messages can only be sent from processes running as root.
Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>.
'''
import os
import select
import socket
import struct
import time
class Ping:
''' Power On State Pint Utility (3rdparty)'''
def __init__(self):
self.ICMP_ECHO_REQUEST = 8
def checksum(self, source_string):
summ = 0
count_to = (len(source_string)/2)*2
for count in xrange(0, count_to, 2):
this = ord(source_string[count+1]) * 256 + ord(source_string[count])
summ = summ + this
summ = summ & 0xffffffff
if count_to < len(source_string):
summ = summ + ord(source_string[len(source_string)-1])
summ = summ & 0xffffffff
summ = (summ >> 16) + (summ & 0xffff)
summ = summ + (summ >> 16)
answer = ~summ
answer = answer & 0xffff
# Swap bytes
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receive_one_ping(self, my_socket, idd, timeout):
'''Receive the ping from the socket'''
time_left = timeout
while True:
started_select = time.time()
what_ready = select.select([my_socket], [], [], time_left)
how_long_in_select = (time.time() - started_select)
if what_ready[0] == []: # Timeout
return
time_received = time.time()
received_packet, addr = my_socket.recvfrom(1024)
icmpHeader = received_packet[20:28]
type, code, checksum, packet_id, sequence = struct.unpack("bbHHh", icmpHeader)
if packet_id == idd:
bytess = struct.calcsize("d")
time_sent = struct.unpack("d", received_packet[28:28 + bytess])[0]
return time_received - time_sent
time_left = time_left - how_long_in_select
if time_left <= 0:
return
def send_one_ping(self, my_socket, dest_addr, idd, psize):
'''Send one ping to the given address'''
dest_addr = socket.gethostbyname(dest_addr)
# Remove header size from packet size
psize = psize - 8
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
my_checksum = 0
# Make a dummy header with a 0 checksum
header = struct.pack("bbHHh", self.ICMP_ECHO_REQUEST, 0, my_checksum, idd, 1)
bytess = struct.calcsize("d")
data = (psize - bytess) * "Q"
data = struct.pack("d", time.time()) + data
# Calculate the checksum on the data and the dummy header
my_checksum = self.checksum(header+data)
# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy
header = struct.pack("bbHHh", self.ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), idd, 1)
packet = header + data
my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def do_one(self, dest_addr, timeout, psize):
'''Returns either the delay (in seconds) or none on timeout'''
icmp = socket.getprotobyname("icmp")
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.errno, (errno, msg):
if errno == 1:
# Operation not permitted
msg = msg + (
" - Note that ICMP messages can only be sent from processes"
" running as root."
)
raise socket.error(msg)
my_id = os.getpid() & 0xFFFF
self.send_one_ping(my_socket, dest_addr, my_id, psize)
delay = self.receive_one_ping(my_socket, my_id, timeout)
my_socket.close()
return delay
def | (self, dest_addr, timeout = 2, count = 4, psize = 64):
'''
Send 'count' ping with 'psize' size to 'dest_addr' with
the given 'timeout' and display the result
'''
for i in xrange(count):
print 'ping %s with ...' % dest_addr
try:
delay = self.do_one(dest_addr, timeout, psize)
except socket.gaierror, e:
print 'FAILED. (socket error: "%s")' % e[1]
break
if delay == None:
print 'FAILED. (timeout within %ssec.)' % timeout
else:
delay = delay * 1000
print 'get ping in %0.4fms' % delay
print
def quiet_ping(self, dest_addr, timeout = 2, count = 4, psize = 64):
'''
Send 'count' pint with 'psize' size to 'dest_addr' with
the given 'timeout' and display the result.
Returns 'percent' lost packages, 'max' round trip time
and 'avg' round trip time.
'''
mrtt = None
artt = None
plist = []
for i in xrange(count):
try:
delay = self.do_one(dest_addr, timeout, psize)
except socket.gaierror, e:
print 'FAILED. (socket error: "%s")' % e[1]
break
if delay != None:
delay = delay * 1000
plist.append(delay)
# Find lost package percent
percent_lost = 100 - (len(plist)*100/count)
# Find max and avg round trip time
if plist:
mrtt = max(plist)
artt = sum(plist)/len(plist)
return percent_lost, mrtt, artt | verbose_ping | identifier_name |
Ping.py | '''
@author: [email protected]
A pure python ping implementation using raw socket.
Note that ICMP messages can only be sent from processes running as root.
Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>.
'''
import os
import select
import socket
import struct
import time
class Ping:
''' Power On State Pint Utility (3rdparty)'''
def __init__(self):
self.ICMP_ECHO_REQUEST = 8
def checksum(self, source_string):
summ = 0
count_to = (len(source_string)/2)*2
for count in xrange(0, count_to, 2):
this = ord(source_string[count+1]) * 256 + ord(source_string[count])
summ = summ + this
summ = summ & 0xffffffff
if count_to < len(source_string):
|
summ = (summ >> 16) + (summ & 0xffff)
summ = summ + (summ >> 16)
answer = ~summ
answer = answer & 0xffff
# Swap bytes
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receive_one_ping(self, my_socket, idd, timeout):
'''Receive the ping from the socket'''
time_left = timeout
while True:
started_select = time.time()
what_ready = select.select([my_socket], [], [], time_left)
how_long_in_select = (time.time() - started_select)
if what_ready[0] == []: # Timeout
return
time_received = time.time()
received_packet, addr = my_socket.recvfrom(1024)
icmpHeader = received_packet[20:28]
type, code, checksum, packet_id, sequence = struct.unpack("bbHHh", icmpHeader)
if packet_id == idd:
bytess = struct.calcsize("d")
time_sent = struct.unpack("d", received_packet[28:28 + bytess])[0]
return time_received - time_sent
time_left = time_left - how_long_in_select
if time_left <= 0:
return
def send_one_ping(self, my_socket, dest_addr, idd, psize):
'''Send one ping to the given address'''
dest_addr = socket.gethostbyname(dest_addr)
# Remove header size from packet size
psize = psize - 8
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
my_checksum = 0
# Make a dummy header with a 0 checksum
header = struct.pack("bbHHh", self.ICMP_ECHO_REQUEST, 0, my_checksum, idd, 1)
bytess = struct.calcsize("d")
data = (psize - bytess) * "Q"
data = struct.pack("d", time.time()) + data
# Calculate the checksum on the data and the dummy header
my_checksum = self.checksum(header+data)
# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy
header = struct.pack("bbHHh", self.ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), idd, 1)
packet = header + data
my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def do_one(self, dest_addr, timeout, psize):
'''Returns either the delay (in seconds) or none on timeout'''
icmp = socket.getprotobyname("icmp")
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.errno, (errno, msg):
if errno == 1:
# Operation not permitted
msg = msg + (
" - Note that ICMP messages can only be sent from processes"
" running as root."
)
raise socket.error(msg)
my_id = os.getpid() & 0xFFFF
self.send_one_ping(my_socket, dest_addr, my_id, psize)
delay = self.receive_one_ping(my_socket, my_id, timeout)
my_socket.close()
return delay
def verbose_ping(self, dest_addr, timeout = 2, count = 4, psize = 64):
'''
Send 'count' ping with 'psize' size to 'dest_addr' with
the given 'timeout' and display the result
'''
for i in xrange(count):
print 'ping %s with ...' % dest_addr
try:
delay = self.do_one(dest_addr, timeout, psize)
except socket.gaierror, e:
print 'FAILED. (socket error: "%s")' % e[1]
break
if delay == None:
print 'FAILED. (timeout within %ssec.)' % timeout
else:
delay = delay * 1000
print 'get ping in %0.4fms' % delay
print
def quiet_ping(self, dest_addr, timeout = 2, count = 4, psize = 64):
'''
Send 'count' pint with 'psize' size to 'dest_addr' with
the given 'timeout' and display the result.
Returns 'percent' lost packages, 'max' round trip time
and 'avg' round trip time.
'''
mrtt = None
artt = None
plist = []
for i in xrange(count):
try:
delay = self.do_one(dest_addr, timeout, psize)
except socket.gaierror, e:
print 'FAILED. (socket error: "%s")' % e[1]
break
if delay != None:
delay = delay * 1000
plist.append(delay)
# Find lost package percent
percent_lost = 100 - (len(plist)*100/count)
# Find max and avg round trip time
if plist:
mrtt = max(plist)
artt = sum(plist)/len(plist)
return percent_lost, mrtt, artt | summ = summ + ord(source_string[len(source_string)-1])
summ = summ & 0xffffffff | conditional_block |
World.ts | import {RNG} from "./RNG";
import {GameObject} from './GameObject';
import {Components} from './Component';
import {EventDispatcher} from './EventDispatcher';
// ###
// 管理所有的 GameObject
// 提供公共方法
// ###
export class World {
eventDispatcher: EventDispatcher;
root: GameObject;
rng: RNG;
constructor(seed = 0) {
this.root = new GameObject();
this.root.world = this;
this.eventDispatcher = new EventDispatcher();
this.rng = new RNG(seed);
}
createGameObject(name = '') {
return this.root.createChild(name);
}
update(dt = 0) {
this.root.update(dt);
}
nextInt() {
return this.rng.nextInt();
}
nextIndex(length) {
| urn this.rng.nextRange(0, length);
}
nextRange(start: number, end: number) {
return this.rng.nextRange(start, end);
}
choice(array) {
return this.rng.choice(array);
}
on(event: string, target, handler?) {
this.eventDispatcher.on(event, target, handler);
}
off(event: string, target, handler?) {
this.eventDispatcher.off(event, target, handler);
}
trigger(event: string, ...params) {
this.eventDispatcher.trigger(event, ...params);
}
/*
* 这个方法可以快速注册多个事件处理函数
* 一般用在单元测试用例里面
*/
onEventMap(eventMap) {
for (let event in eventMap) {
this.on(event, eventMap);
}
}
}
| ret | identifier_name |
World.ts | import {RNG} from "./RNG";
import {GameObject} from './GameObject';
import {Components} from './Component';
import {EventDispatcher} from './EventDispatcher';
// ###
// 管理所有的 GameObject
// 提供公共方法
// ###
export class World {
eventDispatcher: EventDispatcher;
root: GameObject;
rng: RNG;
constructor(seed = 0) {
this.root = new GameObject();
this.root.world = this;
this.eventDispatcher = new EventDispatcher();
this.rng = new RNG(seed);
}
createGameObject(name = '') {
return this.root.createChild(name);
}
update(dt = 0) {
this.root.update(dt);
}
nextInt() {
return this.rng.nextInt();
}
nextIndex(length) {
return this.rng.nextRange(0, length);
}
nextRange(start: number, end: number) {
return this.rng.nextRange(start, end);
}
choice(array) {
return this.rng.choice(array);
}
on(event: string, target, handler?) {
this.eventDispatcher.on(event, target, handler);
}
off(event: string, target, handler?) {
this.eventDispatcher.off(event, target, handler);
}
trigger(event: string, ...params) {
this.eventDispatcher.trigger(event, ...params); | }
/*
* 这个方法可以快速注册多个事件处理函数
* 一般用在单元测试用例里面
*/
onEventMap(eventMap) {
for (let event in eventMap) {
this.on(event, eventMap);
}
}
} | random_line_split |
|
World.ts | import {RNG} from "./RNG";
import {GameObject} from './GameObject';
import {Components} from './Component';
import {EventDispatcher} from './EventDispatcher';
// ###
// 管理所有的 GameObject
// 提供公共方法
// ###
export class World {
eventDispatcher: EventDispatcher;
root: GameObject;
rng: RNG;
constructor(seed = 0) {
this.root = new GameObject();
this.root.world = this;
this.eventDispatcher = new EventDispatcher();
this.rng = new RNG(seed);
}
createGameObject(name = '') {
return this. |
this.root.update(dt);
}
nextInt() {
return this.rng.nextInt();
}
nextIndex(length) {
return this.rng.nextRange(0, length);
}
nextRange(start: number, end: number) {
return this.rng.nextRange(start, end);
}
choice(array) {
return this.rng.choice(array);
}
on(event: string, target, handler?) {
this.eventDispatcher.on(event, target, handler);
}
off(event: string, target, handler?) {
this.eventDispatcher.off(event, target, handler);
}
trigger(event: string, ...params) {
this.eventDispatcher.trigger(event, ...params);
}
/*
* 这个方法可以快速注册多个事件处理函数
* 一般用在单元测试用例里面
*/
onEventMap(eventMap) {
for (let event in eventMap) {
this.on(event, eventMap);
}
}
}
| root.createChild(name);
}
update(dt = 0) { | identifier_body |
object.rs | use libc::c_void;
use ffi::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef};
use cbox::CBox;
use std::fmt;
use std::iter::Iterator;
use std::marker::PhantomData;
use std::mem;
use buffer::MemoryBuffer;
use util;
/// An external object file that has been parsed by LLVLM
pub struct ObjectFile {
obj: LLVMObjectFileRef
}
native_ref!(ObjectFile, obj: LLVMObjectFileRef);
impl ObjectFile {
/// Attempt to parse the object file at the path given
pub fn read(path: &str) -> Result<ObjectFile, CBox<str>> {
let buf = try!(MemoryBuffer::new_from_file(path));
unsafe {
let ptr = object::LLVMCreateObjectFile(buf.as_ptr());
if ptr.is_null() {
Err(CBox::from("unknown error"))
} else {
Ok(ptr.into())
}
}
}
/// Iterate through the symbols in this object fil
pub fn symbols(&self) -> Symbols {
Symbols {
iter: unsafe { object::LLVMGetSymbols(self.obj) },
marker: PhantomData
}
}
}
pub struct Symbols<'a> {
iter: LLVMSymbolIteratorRef,
marker: PhantomData<&'a ()>
}
impl<'a> Iterator for Symbols<'a> {
type Item = Symbol<'a>;
fn next(&mut self) -> Option<Symbol<'a>> {
unsafe {
let name = util::to_str(object::LLVMGetSymbolName(self.iter) as *mut i8);
let size = object::LLVMGetSymbolSize(self.iter) as usize;
let address = object::LLVMGetSymbolAddress(self.iter) as usize;
Some(Symbol {
name: name,
address: mem::transmute(address),
size: size
})
}
}
}
impl<'a> Drop for Symbols<'a> {
fn drop(&mut self) |
}
pub struct Symbol<'a> {
pub name: &'a str,
pub address: *const c_void,
pub size: usize
}
impl<'a> Copy for Symbol<'a> {}
impl<'a> Clone for Symbol<'a> {
fn clone(&self) -> Symbol<'a> {
*self
}
}
impl<'a> fmt::Debug for Symbol<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{} - {}", self.name, self.size)
}
}
impl<'a> Symbol<'a> {
/// Get the pointer for this symbol
pub unsafe fn get<T>(self) -> &'a T {
mem::transmute(self.address)
}
}
| {
unsafe {
object::LLVMDisposeSymbolIterator(self.iter)
}
} | identifier_body |
object.rs | use libc::c_void;
use ffi::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef};
use cbox::CBox;
use std::fmt;
use std::iter::Iterator;
use std::marker::PhantomData;
use std::mem;
use buffer::MemoryBuffer;
use util;
/// An external object file that has been parsed by LLVLM
pub struct ObjectFile {
obj: LLVMObjectFileRef
}
native_ref!(ObjectFile, obj: LLVMObjectFileRef);
impl ObjectFile {
/// Attempt to parse the object file at the path given
pub fn read(path: &str) -> Result<ObjectFile, CBox<str>> {
let buf = try!(MemoryBuffer::new_from_file(path));
unsafe {
let ptr = object::LLVMCreateObjectFile(buf.as_ptr());
if ptr.is_null() {
Err(CBox::from("unknown error"))
} else {
Ok(ptr.into())
}
}
}
/// Iterate through the symbols in this object fil
pub fn symbols(&self) -> Symbols {
Symbols {
iter: unsafe { object::LLVMGetSymbols(self.obj) },
marker: PhantomData
}
}
}
pub struct Symbols<'a> {
iter: LLVMSymbolIteratorRef,
marker: PhantomData<&'a ()>
}
impl<'a> Iterator for Symbols<'a> {
type Item = Symbol<'a>;
fn | (&mut self) -> Option<Symbol<'a>> {
unsafe {
let name = util::to_str(object::LLVMGetSymbolName(self.iter) as *mut i8);
let size = object::LLVMGetSymbolSize(self.iter) as usize;
let address = object::LLVMGetSymbolAddress(self.iter) as usize;
Some(Symbol {
name: name,
address: mem::transmute(address),
size: size
})
}
}
}
impl<'a> Drop for Symbols<'a> {
fn drop(&mut self) {
unsafe {
object::LLVMDisposeSymbolIterator(self.iter)
}
}
}
pub struct Symbol<'a> {
pub name: &'a str,
pub address: *const c_void,
pub size: usize
}
impl<'a> Copy for Symbol<'a> {}
impl<'a> Clone for Symbol<'a> {
fn clone(&self) -> Symbol<'a> {
*self
}
}
impl<'a> fmt::Debug for Symbol<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{} - {}", self.name, self.size)
}
}
impl<'a> Symbol<'a> {
/// Get the pointer for this symbol
pub unsafe fn get<T>(self) -> &'a T {
mem::transmute(self.address)
}
}
| next | identifier_name |
object.rs | use libc::c_void;
use ffi::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef};
use cbox::CBox;
use std::fmt;
use std::iter::Iterator;
use std::marker::PhantomData;
use std::mem;
use buffer::MemoryBuffer;
use util;
/// An external object file that has been parsed by LLVLM
pub struct ObjectFile {
obj: LLVMObjectFileRef
}
native_ref!(ObjectFile, obj: LLVMObjectFileRef);
impl ObjectFile {
/// Attempt to parse the object file at the path given
pub fn read(path: &str) -> Result<ObjectFile, CBox<str>> {
let buf = try!(MemoryBuffer::new_from_file(path));
unsafe {
let ptr = object::LLVMCreateObjectFile(buf.as_ptr());
if ptr.is_null() {
Err(CBox::from("unknown error"))
} else {
Ok(ptr.into())
}
}
}
/// Iterate through the symbols in this object fil
pub fn symbols(&self) -> Symbols {
Symbols {
iter: unsafe { object::LLVMGetSymbols(self.obj) },
marker: PhantomData
}
}
}
pub struct Symbols<'a> {
iter: LLVMSymbolIteratorRef,
marker: PhantomData<&'a ()>
}
impl<'a> Iterator for Symbols<'a> {
type Item = Symbol<'a>;
fn next(&mut self) -> Option<Symbol<'a>> {
unsafe {
let name = util::to_str(object::LLVMGetSymbolName(self.iter) as *mut i8);
let size = object::LLVMGetSymbolSize(self.iter) as usize;
let address = object::LLVMGetSymbolAddress(self.iter) as usize;
Some(Symbol {
name: name,
address: mem::transmute(address),
size: size
})
}
}
}
impl<'a> Drop for Symbols<'a> {
fn drop(&mut self) { | pub struct Symbol<'a> {
pub name: &'a str,
pub address: *const c_void,
pub size: usize
}
impl<'a> Copy for Symbol<'a> {}
impl<'a> Clone for Symbol<'a> {
fn clone(&self) -> Symbol<'a> {
*self
}
}
impl<'a> fmt::Debug for Symbol<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{} - {}", self.name, self.size)
}
}
impl<'a> Symbol<'a> {
/// Get the pointer for this symbol
pub unsafe fn get<T>(self) -> &'a T {
mem::transmute(self.address)
}
} | unsafe {
object::LLVMDisposeSymbolIterator(self.iter)
}
}
} | random_line_split |
object.rs | use libc::c_void;
use ffi::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef};
use cbox::CBox;
use std::fmt;
use std::iter::Iterator;
use std::marker::PhantomData;
use std::mem;
use buffer::MemoryBuffer;
use util;
/// An external object file that has been parsed by LLVLM
pub struct ObjectFile {
obj: LLVMObjectFileRef
}
native_ref!(ObjectFile, obj: LLVMObjectFileRef);
impl ObjectFile {
/// Attempt to parse the object file at the path given
pub fn read(path: &str) -> Result<ObjectFile, CBox<str>> {
let buf = try!(MemoryBuffer::new_from_file(path));
unsafe {
let ptr = object::LLVMCreateObjectFile(buf.as_ptr());
if ptr.is_null() | else {
Ok(ptr.into())
}
}
}
/// Iterate through the symbols in this object fil
pub fn symbols(&self) -> Symbols {
Symbols {
iter: unsafe { object::LLVMGetSymbols(self.obj) },
marker: PhantomData
}
}
}
pub struct Symbols<'a> {
iter: LLVMSymbolIteratorRef,
marker: PhantomData<&'a ()>
}
impl<'a> Iterator for Symbols<'a> {
type Item = Symbol<'a>;
fn next(&mut self) -> Option<Symbol<'a>> {
unsafe {
let name = util::to_str(object::LLVMGetSymbolName(self.iter) as *mut i8);
let size = object::LLVMGetSymbolSize(self.iter) as usize;
let address = object::LLVMGetSymbolAddress(self.iter) as usize;
Some(Symbol {
name: name,
address: mem::transmute(address),
size: size
})
}
}
}
impl<'a> Drop for Symbols<'a> {
fn drop(&mut self) {
unsafe {
object::LLVMDisposeSymbolIterator(self.iter)
}
}
}
pub struct Symbol<'a> {
pub name: &'a str,
pub address: *const c_void,
pub size: usize
}
impl<'a> Copy for Symbol<'a> {}
impl<'a> Clone for Symbol<'a> {
fn clone(&self) -> Symbol<'a> {
*self
}
}
impl<'a> fmt::Debug for Symbol<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{} - {}", self.name, self.size)
}
}
impl<'a> Symbol<'a> {
/// Get the pointer for this symbol
pub unsafe fn get<T>(self) -> &'a T {
mem::transmute(self.address)
}
}
| {
Err(CBox::from("unknown error"))
} | conditional_block |
gcloud_iam_sa.py | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
''' ansible module for gcloud iam servicetaccount'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str',
choices=['present', 'absent', 'list']),
name=dict(default=None, type='str'),
display_name=dict(default=None, type='str'),
),
supports_check_mode=True,
)
gcloud = GcloudIAMServiceAccount(module.params['name'], module.params['display_name'])
state = module.params['state']
api_rval = gcloud.list_service_accounts()
#####
# Get
#####
if state == 'list':
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval, state="list")
module.exit_json(changed=False, results=api_rval['results'], state="list")
########
# Delete
########
if state == 'absent':
if gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a delete.')
api_rval = gcloud.delete_service_account()
module.exit_json(changed=True, results=api_rval, state="absent")
module.exit_json(changed=False, state="absent")
if state == 'present':
########
# Create
########
if not gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a create.')
# Create it here
api_rval = gcloud.create_service_account()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(changed=True, results=api_rval, state="present")
# update
elif gcloud.needs_update():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed an update.')
api_rval = gcloud.update_service_account()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval) | module.exit_json(changed=False, results=api_rval, state="present")
module.exit_json(failed=True,
changed=False,
results='Unknown state passed. %s' % state,
state="unknown")
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
# import module snippets. This are required
from ansible.module_utils.basic import *
main() |
module.exit_json(changed=True, results=api_rval, state="present|update")
| random_line_split |
gcloud_iam_sa.py | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def | ():
''' ansible module for gcloud iam servicetaccount'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str',
choices=['present', 'absent', 'list']),
name=dict(default=None, type='str'),
display_name=dict(default=None, type='str'),
),
supports_check_mode=True,
)
gcloud = GcloudIAMServiceAccount(module.params['name'], module.params['display_name'])
state = module.params['state']
api_rval = gcloud.list_service_accounts()
#####
# Get
#####
if state == 'list':
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval, state="list")
module.exit_json(changed=False, results=api_rval['results'], state="list")
########
# Delete
########
if state == 'absent':
if gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a delete.')
api_rval = gcloud.delete_service_account()
module.exit_json(changed=True, results=api_rval, state="absent")
module.exit_json(changed=False, state="absent")
if state == 'present':
########
# Create
########
if not gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a create.')
# Create it here
api_rval = gcloud.create_service_account()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(changed=True, results=api_rval, state="present")
# update
elif gcloud.needs_update():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed an update.')
api_rval = gcloud.update_service_account()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(changed=True, results=api_rval, state="present|update")
module.exit_json(changed=False, results=api_rval, state="present")
module.exit_json(failed=True,
changed=False,
results='Unknown state passed. %s' % state,
state="unknown")
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
# import module snippets. This are required
from ansible.module_utils.basic import *
main()
| main | identifier_name |
gcloud_iam_sa.py | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
| #####
if state == 'list':
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval, state="list")
module.exit_json(changed=False, results=api_rval['results'], state="list")
########
# Delete
########
if state == 'absent':
if gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a delete.')
api_rval = gcloud.delete_service_account()
module.exit_json(changed=True, results=api_rval, state="absent")
module.exit_json(changed=False, state="absent")
if state == 'present':
########
# Create
########
if not gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a create.')
# Create it here
api_rval = gcloud.create_service_account()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(changed=True, results=api_rval, state="present")
# update
elif gcloud.needs_update():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed an update.')
api_rval = gcloud.update_service_account()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(changed=True, results=api_rval, state="present|update")
module.exit_json(changed=False, results=api_rval, state="present")
module.exit_json(failed=True,
changed=False,
results='Unknown state passed. %s' % state,
state="unknown")
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
# import module snippets. This are required
from ansible.module_utils.basic import *
main()
| ''' ansible module for gcloud iam servicetaccount'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str',
choices=['present', 'absent', 'list']),
name=dict(default=None, type='str'),
display_name=dict(default=None, type='str'),
),
supports_check_mode=True,
)
gcloud = GcloudIAMServiceAccount(module.params['name'], module.params['display_name'])
state = module.params['state']
api_rval = gcloud.list_service_accounts()
#####
# Get | identifier_body |
gcloud_iam_sa.py | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
''' ansible module for gcloud iam servicetaccount'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str',
choices=['present', 'absent', 'list']),
name=dict(default=None, type='str'),
display_name=dict(default=None, type='str'),
),
supports_check_mode=True,
)
gcloud = GcloudIAMServiceAccount(module.params['name'], module.params['display_name'])
state = module.params['state']
api_rval = gcloud.list_service_accounts()
#####
# Get
#####
if state == 'list':
if api_rval['returncode'] != 0:
|
module.exit_json(changed=False, results=api_rval['results'], state="list")
########
# Delete
########
if state == 'absent':
if gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a delete.')
api_rval = gcloud.delete_service_account()
module.exit_json(changed=True, results=api_rval, state="absent")
module.exit_json(changed=False, state="absent")
if state == 'present':
########
# Create
########
if not gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a create.')
# Create it here
api_rval = gcloud.create_service_account()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(changed=True, results=api_rval, state="present")
# update
elif gcloud.needs_update():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed an update.')
api_rval = gcloud.update_service_account()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(changed=True, results=api_rval, state="present|update")
module.exit_json(changed=False, results=api_rval, state="present")
module.exit_json(failed=True,
changed=False,
results='Unknown state passed. %s' % state,
state="unknown")
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
# import module snippets. This are required
from ansible.module_utils.basic import *
main()
| module.fail_json(msg=api_rval, state="list") | conditional_block |
pyunit_benign_glrm.py | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator
def glrm_benign():
print "Importing benign.csv data..."
benignH2O = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/benign.csv"))
benignH2O.describe()
for i in range(8,16,2):
print "H2O GLRM with rank " + str(i) + " decomposition:\n"
glrm_h2o = H2OGeneralizedLowRankEstimator(k=i, init="SVD", recover_svd=True)
glrm_h2o.train(x=benignH2O.names, training_frame=benignH2O)
glrm_h2o.show()
if __name__ == "__main__":
|
else:
glrm_benign()
| pyunit_utils.standalone_test(glrm_benign) | conditional_block |
pyunit_benign_glrm.py | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator
def glrm_benign():
|
if __name__ == "__main__":
pyunit_utils.standalone_test(glrm_benign)
else:
glrm_benign()
| print "Importing benign.csv data..."
benignH2O = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/benign.csv"))
benignH2O.describe()
for i in range(8,16,2):
print "H2O GLRM with rank " + str(i) + " decomposition:\n"
glrm_h2o = H2OGeneralizedLowRankEstimator(k=i, init="SVD", recover_svd=True)
glrm_h2o.train(x=benignH2O.names, training_frame=benignH2O)
glrm_h2o.show() | identifier_body |
pyunit_benign_glrm.py | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator
def glrm_benign():
print "Importing benign.csv data..."
benignH2O = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/benign.csv"))
benignH2O.describe()
for i in range(8,16,2):
print "H2O GLRM with rank " + str(i) + " decomposition:\n" |
if __name__ == "__main__":
pyunit_utils.standalone_test(glrm_benign)
else:
glrm_benign() | glrm_h2o = H2OGeneralizedLowRankEstimator(k=i, init="SVD", recover_svd=True)
glrm_h2o.train(x=benignH2O.names, training_frame=benignH2O)
glrm_h2o.show() | random_line_split |
pyunit_benign_glrm.py | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator
def | ():
print "Importing benign.csv data..."
benignH2O = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/benign.csv"))
benignH2O.describe()
for i in range(8,16,2):
print "H2O GLRM with rank " + str(i) + " decomposition:\n"
glrm_h2o = H2OGeneralizedLowRankEstimator(k=i, init="SVD", recover_svd=True)
glrm_h2o.train(x=benignH2O.names, training_frame=benignH2O)
glrm_h2o.show()
if __name__ == "__main__":
pyunit_utils.standalone_test(glrm_benign)
else:
glrm_benign()
| glrm_benign | identifier_name |
tree.ts | , numParams, handle);
} else {
// Empty tree
this.insertChild(numParams, path, path, handle);
this.type = RouteType.root;
}
}
protected | (tree: this, fullPath: string, path: string, numParams: number, handle: Fn) {
// Find the longest common prefix
// This also implies that the common prefix contains no ':' or '*'
// since the existing key can't contain those chars.
let i = 0;
const min = Math.min(path.length, tree.path.length);
while (i < min && path[i] == tree.path[i]) {
i++;
}
if (i < tree.path.length) {
this.splitAdge(tree, path, i);
}
// Make new node a child of this node
if (i < path.length) {
const newPath = path.slice(i);
if (tree.wildChild) {
this.checkWildcardMatches(tree.children[0], numParams, newPath, fullPath, handle);
return;
}
const firstChar = newPath[0];
// Slash after param
if (tree.type == RouteType.param && firstChar == '/' && tree.children.length == 1) {
const child = tree.children[0];
child.priority++;
this.mergeTree(child, fullPath, newPath, numParams, handle);
return;
}
// Check if a child with the next path char exists
for (let j = 0; j < tree.indices.length; j++) {
if (firstChar == tree.indices[j]) {
j = tree.addPriority(j);
this.mergeTree(tree.children[j], fullPath, newPath, numParams, handle);
return;
}
}
// Otherwise insert it
if (firstChar != ':' && firstChar != '*') {
tree.indices += firstChar;
const treeConfig: TreeConfig = { path: '', wildChild: false, type: RouteType.static };
const child = this.newTree(treeConfig);
tree.children.push(child);
tree.addPriority(tree.indices.length - 1);
child.insertChild(numParams, newPath, fullPath, handle);
} else {
tree.insertChild(numParams, newPath, fullPath, handle);
}
} else if (i == path.length) {
// Make node a (in-path leaf)
if (tree.handle !== null) {
throw new Error(`A handle is already registered for path '${fullPath}'`);
}
tree.handle = handle;
}
}
protected checkWildcardMatches(
tree: this,
numParams: number,
path: string,
fullPath: string,
handle: Fn
) {
tree.priority++;
numParams--;
// Check if the wildcard matches
if (
path.length >= tree.path.length &&
tree.path == path.slice(0, tree.path.length) &&
(tree.path.length >= path.length || path[tree.path.length] == '/')
) {
this.mergeTree(tree, fullPath, path, numParams, handle);
} else {
this.throwWildcardConflict(tree, path, fullPath);
}
}
protected throwWildcardConflict(tree: this, path: string, fullPath: string) {
let pathSeg = '';
if (tree.type == RouteType.catchAll) {
pathSeg = path;
} else {
pathSeg = path.split('/')[0];
}
const prefix = fullPath.slice(0, fullPath.indexOf(pathSeg)) + tree.path;
throw new Error(
`'${pathSeg}' in new path '${fullPath}' conflicts with existing wildcard '${tree.path}' in existing prefix '${prefix}'`
);
}
protected splitAdge(tree: this, path: string, i: number) {
const treeConfig: TreeConfig = {
path: tree.path.slice(i),
wildChild: tree.wildChild,
type: RouteType.static,
indices: tree.indices,
children: tree.children,
handle: tree.handle,
priority: tree.priority - 1,
};
const child = this.newTree(treeConfig);
tree.children = [child];
tree.indices = tree.path[i];
tree.path = path.slice(0, i);
tree.handle = null;
tree.wildChild = false;
}
search(path: string) {
let handle = null;
const params: RouteParam[] = [];
let tree: this = this;
walk: while (true) {
if (path.length > tree.path.length) {
if (path.slice(0, tree.path.length) == tree.path) {
path = path.slice(tree.path.length);
// If this node does not have a wildcard child,
// we can just look up the next child node and continue
// to walk down the tree
if (!tree.wildChild) {
const c = path.charCodeAt(0);
for (let i = 0; i < tree.indices.length; i++) {
if (c == tree.indices.charCodeAt(i)) {
tree = tree.children[i];
continue walk;
}
}
// Nothing found.
return { handle, params };
}
// Handle wildcard child
tree = tree.children[0];
switch (tree.type) {
case RouteType.param:
// Find param end
let end = 0;
while (end < path.length && path.charCodeAt(end) != 47) {
end++;
}
// Save param value
params.push({ key: tree.path.slice(1), value: path.slice(0, end) });
// We need to go deeper!
if (end < path.length) {
if (tree.children.length > 0) {
path = path.slice(end);
tree = tree.children[0];
continue walk;
}
// ... but we can't
return { handle, params };
}
handle = tree.handle;
return { handle, params };
case RouteType.catchAll:
params.push({ key: tree.path.slice(2), value: path });
handle = tree.handle;
return { handle, params };
default:
throw new Error('invalid node type');
}
}
} else if (path == tree.path) {
handle = tree.handle;
}
return { handle, params };
}
}
protected newTree(treeConfig?: TreeConfig) {
return new (this.constructor as typeof Tree)(treeConfig) as this;
}
protected countParams(path: string) {
let n = 0;
for (const char of path) {
if (char != ':' && char != '*') {
continue;
}
n++;
}
return n;
}
protected addPriority(pos: number) {
const children = this.children;
children[pos].priority++;
const prio = children[pos].priority;
// Adjust position (move to fron)
let newPos = pos;
while (newPos > 0 && children[newPos - 1].priority < prio) {
const temp = children[newPos];
children[newPos] = children[newPos - 1];
children[newPos - 1] = temp;
newPos--;
}
// Build new index char string
if (newPos != pos) {
this.indices =
this.indices.slice(0, newPos) +
this.indices[pos] +
this.indices.slice(newPos, pos) +
this.indices.slice(pos + 1);
}
return newPos;
}
protected insertChild(numParams: number, path: string, fullPath: string, handle: Fn) {
let tree: this = this;
let offset = 0; // Already handled chars of the path
// Find prefix until first wildcard
for (let i = 0, max = path.length; numParams > 0; i++) {
const c = path[i];
if (c != ':' && c != '*') {
continue;
}
// Find wildcard end (either '/' or path end)
let end = i + 1;
while (end < max && path[end] != '/') {
if (path[end] == ':' || path[end] == '*') {
throw new Error(
`only one wildcard per path segment is allowed, has: '${path.slice(
i
)}' in path '${fullPath}'`
);
} else {
end++;
}
}
// Check if this Tree existing children which would be unreachable
// if we insert the wildcard here
if (tree.children.length > 0) {
throw new Error(
`wildcard route '${path.slice(
i,
end
)}' conflicts with existing children in path '${fullPath}'`
);
}
// check if the wildcard has a name
if (end - i < 2) {
throw new Error(`wildcards must be named with a non-empty name in path '${fullPath}'`);
}
if (c == ':') {
// Split path at the beginning of the wildcard
if (i > 0) {
tree.path = path.slice(offset, i);
offset = i;
}
const treeConfig1: TreeConfig = { path: '', wildChild: false, type: RouteType.param };
const child = this.newTree(treeConfig1);
tree.children = [child];
tree.wildChild = true;
tree = child;
tree.priority++;
numParams--;
if (end < max) {
tree.path = path.slice(offset, end);
offset = | mergeTree | identifier_name |
tree.ts | , numParams, handle);
} else {
// Empty tree
this.insertChild(numParams, path, path, handle);
this.type = RouteType.root;
}
}
protected mergeTree(tree: this, fullPath: string, path: string, numParams: number, handle: Fn) {
// Find the longest common prefix
// This also implies that the common prefix contains no ':' or '*'
// since the existing key can't contain those chars.
let i = 0;
const min = Math.min(path.length, tree.path.length);
while (i < min && path[i] == tree.path[i]) {
i++;
}
if (i < tree.path.length) {
this.splitAdge(tree, path, i);
}
// Make new node a child of this node
if (i < path.length) {
const newPath = path.slice(i);
if (tree.wildChild) {
this.checkWildcardMatches(tree.children[0], numParams, newPath, fullPath, handle);
return;
}
const firstChar = newPath[0];
// Slash after param
if (tree.type == RouteType.param && firstChar == '/' && tree.children.length == 1) {
const child = tree.children[0];
child.priority++;
this.mergeTree(child, fullPath, newPath, numParams, handle);
return;
}
// Check if a child with the next path char exists
for (let j = 0; j < tree.indices.length; j++) {
if (firstChar == tree.indices[j]) {
j = tree.addPriority(j);
this.mergeTree(tree.children[j], fullPath, newPath, numParams, handle);
return;
}
}
// Otherwise insert it
if (firstChar != ':' && firstChar != '*') {
tree.indices += firstChar;
const treeConfig: TreeConfig = { path: '', wildChild: false, type: RouteType.static };
const child = this.newTree(treeConfig);
tree.children.push(child);
tree.addPriority(tree.indices.length - 1);
child.insertChild(numParams, newPath, fullPath, handle);
} else {
tree.insertChild(numParams, newPath, fullPath, handle);
}
} else if (i == path.length) {
// Make node a (in-path leaf)
if (tree.handle !== null) {
throw new Error(`A handle is already registered for path '${fullPath}'`);
}
tree.handle = handle;
}
}
protected checkWildcardMatches(
tree: this,
numParams: number,
path: string,
fullPath: string,
handle: Fn
) {
tree.priority++;
numParams--;
// Check if the wildcard matches
if (
path.length >= tree.path.length &&
tree.path == path.slice(0, tree.path.length) &&
(tree.path.length >= path.length || path[tree.path.length] == '/')
) {
this.mergeTree(tree, fullPath, path, numParams, handle);
} else {
this.throwWildcardConflict(tree, path, fullPath);
}
}
protected throwWildcardConflict(tree: this, path: string, fullPath: string) {
let pathSeg = '';
if (tree.type == RouteType.catchAll) {
pathSeg = path;
} else {
pathSeg = path.split('/')[0];
}
const prefix = fullPath.slice(0, fullPath.indexOf(pathSeg)) + tree.path;
throw new Error(
`'${pathSeg}' in new path '${fullPath}' conflicts with existing wildcard '${tree.path}' in existing prefix '${prefix}'`
);
}
protected splitAdge(tree: this, path: string, i: number) {
const treeConfig: TreeConfig = {
path: tree.path.slice(i),
wildChild: tree.wildChild,
type: RouteType.static,
indices: tree.indices,
children: tree.children,
handle: tree.handle,
priority: tree.priority - 1,
};
const child = this.newTree(treeConfig);
tree.children = [child];
tree.indices = tree.path[i];
tree.path = path.slice(0, i);
tree.handle = null;
tree.wildChild = false;
}
search(path: string) {
let handle = null;
const params: RouteParam[] = [];
let tree: this = this;
walk: while (true) {
if (path.length > tree.path.length) {
if (path.slice(0, tree.path.length) == tree.path) {
path = path.slice(tree.path.length);
// If this node does not have a wildcard child,
// we can just look up the next child node and continue
// to walk down the tree
if (!tree.wildChild) {
const c = path.charCodeAt(0);
for (let i = 0; i < tree.indices.length; i++) {
if (c == tree.indices.charCodeAt(i)) {
tree = tree.children[i];
continue walk;
}
}
// Nothing found.
return { handle, params };
}
// Handle wildcard child
tree = tree.children[0];
switch (tree.type) {
case RouteType.param:
// Find param end
let end = 0;
while (end < path.length && path.charCodeAt(end) != 47) {
end++;
}
// Save param value
params.push({ key: tree.path.slice(1), value: path.slice(0, end) });
// We need to go deeper!
if (end < path.length) {
if (tree.children.length > 0) {
path = path.slice(end);
tree = tree.children[0];
continue walk;
}
// ... but we can't
return { handle, params };
}
handle = tree.handle;
return { handle, params };
case RouteType.catchAll:
params.push({ key: tree.path.slice(2), value: path });
handle = tree.handle;
return { handle, params };
default:
throw new Error('invalid node type');
}
}
} else if (path == tree.path) |
return { handle, params };
}
}
protected newTree(treeConfig?: TreeConfig) {
return new (this.constructor as typeof Tree)(treeConfig) as this;
}
protected countParams(path: string) {
let n = 0;
for (const char of path) {
if (char != ':' && char != '*') {
continue;
}
n++;
}
return n;
}
protected addPriority(pos: number) {
const children = this.children;
children[pos].priority++;
const prio = children[pos].priority;
// Adjust position (move to fron)
let newPos = pos;
while (newPos > 0 && children[newPos - 1].priority < prio) {
const temp = children[newPos];
children[newPos] = children[newPos - 1];
children[newPos - 1] = temp;
newPos--;
}
// Build new index char string
if (newPos != pos) {
this.indices =
this.indices.slice(0, newPos) +
this.indices[pos] +
this.indices.slice(newPos, pos) +
this.indices.slice(pos + 1);
}
return newPos;
}
protected insertChild(numParams: number, path: string, fullPath: string, handle: Fn) {
let tree: this = this;
let offset = 0; // Already handled chars of the path
// Find prefix until first wildcard
for (let i = 0, max = path.length; numParams > 0; i++) {
const c = path[i];
if (c != ':' && c != '*') {
continue;
}
// Find wildcard end (either '/' or path end)
let end = i + 1;
while (end < max && path[end] != '/') {
if (path[end] == ':' || path[end] == '*') {
throw new Error(
`only one wildcard per path segment is allowed, has: '${path.slice(
i
)}' in path '${fullPath}'`
);
} else {
end++;
}
}
// Check if this Tree existing children which would be unreachable
// if we insert the wildcard here
if (tree.children.length > 0) {
throw new Error(
`wildcard route '${path.slice(
i,
end
)}' conflicts with existing children in path '${fullPath}'`
);
}
// check if the wildcard has a name
if (end - i < 2) {
throw new Error(`wildcards must be named with a non-empty name in path '${fullPath}'`);
}
if (c == ':') {
// Split path at the beginning of the wildcard
if (i > 0) {
tree.path = path.slice(offset, i);
offset = i;
}
const treeConfig1: TreeConfig = { path: '', wildChild: false, type: RouteType.param };
const child = this.newTree(treeConfig1);
tree.children = [child];
tree.wildChild = true;
tree = child;
tree.priority++;
numParams--;
if (end < max) {
tree.path = path.slice(offset, end);
offset | {
handle = tree.handle;
} | conditional_block |
tree.ts | , numParams, handle);
} else {
// Empty tree
this.insertChild(numParams, path, path, handle);
this.type = RouteType.root;
}
}
protected mergeTree(tree: this, fullPath: string, path: string, numParams: number, handle: Fn) {
// Find the longest common prefix
// This also implies that the common prefix contains no ':' or '*'
// since the existing key can't contain those chars.
let i = 0;
const min = Math.min(path.length, tree.path.length);
while (i < min && path[i] == tree.path[i]) {
i++;
}
if (i < tree.path.length) {
this.splitAdge(tree, path, i);
}
// Make new node a child of this node
if (i < path.length) {
const newPath = path.slice(i);
if (tree.wildChild) {
this.checkWildcardMatches(tree.children[0], numParams, newPath, fullPath, handle);
return;
}
const firstChar = newPath[0];
// Slash after param
| const child = tree.children[0];
child.priority++;
this.mergeTree(child, fullPath, newPath, numParams, handle);
return;
}
// Check if a child with the next path char exists
for (let j = 0; j < tree.indices.length; j++) {
if (firstChar == tree.indices[j]) {
j = tree.addPriority(j);
this.mergeTree(tree.children[j], fullPath, newPath, numParams, handle);
return;
}
}
// Otherwise insert it
if (firstChar != ':' && firstChar != '*') {
tree.indices += firstChar;
const treeConfig: TreeConfig = { path: '', wildChild: false, type: RouteType.static };
const child = this.newTree(treeConfig);
tree.children.push(child);
tree.addPriority(tree.indices.length - 1);
child.insertChild(numParams, newPath, fullPath, handle);
} else {
tree.insertChild(numParams, newPath, fullPath, handle);
}
} else if (i == path.length) {
// Make node a (in-path leaf)
if (tree.handle !== null) {
throw new Error(`A handle is already registered for path '${fullPath}'`);
}
tree.handle = handle;
}
}
protected checkWildcardMatches(
tree: this,
numParams: number,
path: string,
fullPath: string,
handle: Fn
) {
tree.priority++;
numParams--;
// Check if the wildcard matches
if (
path.length >= tree.path.length &&
tree.path == path.slice(0, tree.path.length) &&
(tree.path.length >= path.length || path[tree.path.length] == '/')
) {
this.mergeTree(tree, fullPath, path, numParams, handle);
} else {
this.throwWildcardConflict(tree, path, fullPath);
}
}
protected throwWildcardConflict(tree: this, path: string, fullPath: string) {
let pathSeg = '';
if (tree.type == RouteType.catchAll) {
pathSeg = path;
} else {
pathSeg = path.split('/')[0];
}
const prefix = fullPath.slice(0, fullPath.indexOf(pathSeg)) + tree.path;
throw new Error(
`'${pathSeg}' in new path '${fullPath}' conflicts with existing wildcard '${tree.path}' in existing prefix '${prefix}'`
);
}
protected splitAdge(tree: this, path: string, i: number) {
const treeConfig: TreeConfig = {
path: tree.path.slice(i),
wildChild: tree.wildChild,
type: RouteType.static,
indices: tree.indices,
children: tree.children,
handle: tree.handle,
priority: tree.priority - 1,
};
const child = this.newTree(treeConfig);
tree.children = [child];
tree.indices = tree.path[i];
tree.path = path.slice(0, i);
tree.handle = null;
tree.wildChild = false;
}
search(path: string) {
let handle = null;
const params: RouteParam[] = [];
let tree: this = this;
walk: while (true) {
if (path.length > tree.path.length) {
if (path.slice(0, tree.path.length) == tree.path) {
path = path.slice(tree.path.length);
// If this node does not have a wildcard child,
// we can just look up the next child node and continue
// to walk down the tree
if (!tree.wildChild) {
const c = path.charCodeAt(0);
for (let i = 0; i < tree.indices.length; i++) {
if (c == tree.indices.charCodeAt(i)) {
tree = tree.children[i];
continue walk;
}
}
// Nothing found.
return { handle, params };
}
// Handle wildcard child
tree = tree.children[0];
switch (tree.type) {
case RouteType.param:
// Find param end
let end = 0;
while (end < path.length && path.charCodeAt(end) != 47) {
end++;
}
// Save param value
params.push({ key: tree.path.slice(1), value: path.slice(0, end) });
// We need to go deeper!
if (end < path.length) {
if (tree.children.length > 0) {
path = path.slice(end);
tree = tree.children[0];
continue walk;
}
// ... but we can't
return { handle, params };
}
handle = tree.handle;
return { handle, params };
case RouteType.catchAll:
params.push({ key: tree.path.slice(2), value: path });
handle = tree.handle;
return { handle, params };
default:
throw new Error('invalid node type');
}
}
} else if (path == tree.path) {
handle = tree.handle;
}
return { handle, params };
}
}
protected newTree(treeConfig?: TreeConfig) {
return new (this.constructor as typeof Tree)(treeConfig) as this;
}
protected countParams(path: string) {
let n = 0;
for (const char of path) {
if (char != ':' && char != '*') {
continue;
}
n++;
}
return n;
}
protected addPriority(pos: number) {
const children = this.children;
children[pos].priority++;
const prio = children[pos].priority;
// Adjust position (move to fron)
let newPos = pos;
while (newPos > 0 && children[newPos - 1].priority < prio) {
const temp = children[newPos];
children[newPos] = children[newPos - 1];
children[newPos - 1] = temp;
newPos--;
}
// Build new index char string
if (newPos != pos) {
this.indices =
this.indices.slice(0, newPos) +
this.indices[pos] +
this.indices.slice(newPos, pos) +
this.indices.slice(pos + 1);
}
return newPos;
}
protected insertChild(numParams: number, path: string, fullPath: string, handle: Fn) {
let tree: this = this;
let offset = 0; // Already handled chars of the path
// Find prefix until first wildcard
for (let i = 0, max = path.length; numParams > 0; i++) {
const c = path[i];
if (c != ':' && c != '*') {
continue;
}
// Find wildcard end (either '/' or path end)
let end = i + 1;
while (end < max && path[end] != '/') {
if (path[end] == ':' || path[end] == '*') {
throw new Error(
`only one wildcard per path segment is allowed, has: '${path.slice(
i
)}' in path '${fullPath}'`
);
} else {
end++;
}
}
// Check if this Tree existing children which would be unreachable
// if we insert the wildcard here
if (tree.children.length > 0) {
throw new Error(
`wildcard route '${path.slice(
i,
end
)}' conflicts with existing children in path '${fullPath}'`
);
}
// check if the wildcard has a name
if (end - i < 2) {
throw new Error(`wildcards must be named with a non-empty name in path '${fullPath}'`);
}
if (c == ':') {
// Split path at the beginning of the wildcard
if (i > 0) {
tree.path = path.slice(offset, i);
offset = i;
}
const treeConfig1: TreeConfig = { path: '', wildChild: false, type: RouteType.param };
const child = this.newTree(treeConfig1);
tree.children = [child];
tree.wildChild = true;
tree = child;
tree.priority++;
numParams--;
if (end < max) {
tree.path = path.slice(offset, end);
offset = | if (tree.type == RouteType.param && firstChar == '/' && tree.children.length == 1) {
| random_line_split |
trait-cast-generic.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Testing casting of a generic Struct to a Trait with a generic method.
// This is test for issue 10955.
#![allow(unused_variable)]
trait Foo {
fn f<A>(a: A) -> A {
a
}
}
struct | <T> {
x: T,
}
impl<T> Foo for Bar<T> { }
pub fn main() {
let a = Bar { x: 1u };
let b = &a as &Foo;
}
| Bar | identifier_name |
trait-cast-generic.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Testing casting of a generic Struct to a Trait with a generic method.
// This is test for issue 10955.
#![allow(unused_variable)]
trait Foo {
fn f<A>(a: A) -> A {
a
}
}
struct Bar<T> {
x: T,
}
impl<T> Foo for Bar<T> { }
pub fn main() {
let a = Bar { x: 1u }; | let b = &a as &Foo;
} | random_line_split |
|
reduce.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use crate::ir::attrs::BaseAttrsNode;
use crate::ir::PrimExpr;
use crate::runtime::array::Array;
use tvm_macros::Object;
type IndexExpr = PrimExpr;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "ReduceAttrs"]
#[type_key = "relay.attrs.ReduceAttrs"]
pub struct ReduceAttrsNode {
pub base: BaseAttrsNode,
pub axis: Array<IndexExpr>,
pub keepdims: bool,
pub exclude: bool,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "VarianceAttrs"]
#[type_key = "relay.attrs.ReduceAttrs"]
pub struct | {
pub base: BaseAttrsNode,
pub axis: Array<IndexExpr>,
pub keepdims: bool,
pub exclude: bool,
pub unbiased: bool,
}
| VarianceAttrsNode | identifier_name |
reduce.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an | */
use crate::ir::attrs::BaseAttrsNode;
use crate::ir::PrimExpr;
use crate::runtime::array::Array;
use tvm_macros::Object;
type IndexExpr = PrimExpr;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "ReduceAttrs"]
#[type_key = "relay.attrs.ReduceAttrs"]
pub struct ReduceAttrsNode {
pub base: BaseAttrsNode,
pub axis: Array<IndexExpr>,
pub keepdims: bool,
pub exclude: bool,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "VarianceAttrs"]
#[type_key = "relay.attrs.ReduceAttrs"]
pub struct VarianceAttrsNode {
pub base: BaseAttrsNode,
pub axis: Array<IndexExpr>,
pub keepdims: bool,
pub exclude: bool,
pub unbiased: bool,
} | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License. | random_line_split |
net_error_list.rs | {
IO_PENDING = 1,
FAILED = 2,
ABORTED = 3,
INVALID_ARGUMENT = 4,
INVALID_HANDLE = 5,
FILE_NOT_FOUND = 6,
TIMED_OUT = 7,
FILE_TOO_BIG = 8,
UNEXPECTED = 9,
ACCESS_DENIED = 10,
NOT_IMPLEMENTED = 11,
INSUFFICIENT_RESOURCES = 12,
OUT_OF_MEMORY = 13,
UPLOAD_FILE_CHANGED = 14,
SOCKET_NOT_CONNECTED = 15,
FILE_EXISTS = 16,
FILE_PATH_TOO_LONG = 17,
FILE_NO_SPACE = 18,
FILE_VIRUS_INFECTED = 19,
BLOCKED_BY_CLIENT = 20,
NETWORK_CHANGED = 21,
BLOCKED_BY_ADMINISTRATOR = 22,
SOCKET_IS_CONNECTED = 23,
BLOCKED_ENROLLMENT_CHECK_PENDING = 24,
UPLOAD_STREAM_REWIND_NOT_SUPPORTED = 25,
CONNECTION_CLOSED = 100,
CONNECTION_RESET = 101,
CONNECTION_REFUSED = 102,
CONNECTION_ABORTED = 103,
CONNECTION_FAILED = 104,
NAME_NOT_RESOLVED = 105,
INTERNET_DISCONNECTED = 106,
SSL_PROTOCOL_ERROR = 107,
ADDRESS_INVALID = 108,
ADDRESS_UNREACHABLE = 109,
SSL_CLIENT_AUTH_CERT_NEEDED = 110,
TUNNEL_CONNECTION_FAILED = 111,
NO_SSL_VERSIONS_ENABLED = 112,
SSL_VERSION_OR_CIPHER_MISMATCH = 113,
SSL_RENEGOTIATION_REQUESTED = 114,
PROXY_AUTH_UNSUPPORTED = 115,
CERT_ERROR_IN_SSL_RENEGOTIATION = 116,
BAD_SSL_CLIENT_AUTH_CERT = 117,
CONNECTION_TIMED_OUT = 118,
HOST_RESOLVER_QUEUE_TOO_LARGE = 119,
SOCKS_CONNECTION_FAILED = 120,
SOCKS_CONNECTION_HOST_UNREACHABLE = 121,
NPN_NEGOTIATION_FAILED = 122,
SSL_NO_RENEGOTIATION = 123,
WINSOCK_UNEXPECTED_WRITTEN_BYTES = 124,
SSL_DECOMPRESSION_FAILURE_ALERT = 125,
SSL_BAD_RECORD_MAC_ALERT = 126,
PROXY_AUTH_REQUESTED = 127,
SSL_UNSAFE_NEGOTIATION = 128,
SSL_WEAK_SERVER_EPHEMERAL_DH_KEY = 129,
PROXY_CONNECTION_FAILED = 130,
MANDATORY_PROXY_CONFIGURATION_FAILED = 131,
PRECONNECT_MAX_SOCKET_LIMIT = 133,
SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED = 134,
SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY = 135,
PROXY_CERTIFICATE_INVALID = 136,
NAME_RESOLUTION_FAILED = 137,
NETWORK_ACCESS_DENIED = 138,
TEMPORARILY_THROTTLED = 139,
HTTPS_PROXY_TUNNEL_RESPONSE = 140,
SSL_CLIENT_AUTH_SIGNATURE_FAILED = 141,
MSG_TOO_BIG = 142,
SPDY_SESSION_ALREADY_EXISTS = 143,
WS_PROTOCOL_ERROR = 145,
ADDRESS_IN_USE = 147,
SSL_HANDSHAKE_NOT_COMPLETED = 148,
SSL_BAD_PEER_PUBLIC_KEY = 149,
SSL_PINNED_KEY_NOT_IN_CERT_CHAIN = 150,
CLIENT_AUTH_CERT_TYPE_UNSUPPORTED = 151,
ORIGIN_BOUND_CERT_GENERATION_TYPE_MISMATCH = 152,
SSL_DECRYPT_ERROR_ALERT = 153,
WS_THROTTLE_QUEUE_TOO_LARGE = 154,
SSL_SERVER_CERT_CHANGED = 156,
SSL_INAPPROPRIATE_FALLBACK = 157,
CT_NO_SCTS_VERIFIED_OK = 158,
SSL_UNRECOGNIZED_NAME_ALERT = 159,
SOCKET_SET_RECEIVE_BUFFER_SIZE_ERROR = 160,
SOCKET_SET_SEND_BUFFER_SIZE_ERROR = 161,
SOCKET_RECEIVE_BUFFER_SIZE_UNCHANGEABLE = 162,
SOCKET_SEND_BUFFER_SIZE_UNCHANGEABLE = 163,
SSL_CLIENT_AUTH_CERT_BAD_FORMAT = 164,
SSL_FALLBACK_BEYOND_MINIMUM_VERSION = 165,
CERT_COMMON_NAME_INVALID = 200,
CERT_DATE_INVALID = 201,
CERT_AUTHORITY_INVALID = 202,
CERT_CONTAINS_ERRORS = 203,
CERT_NO_REVOCATION_MECHANISM = 204,
CERT_UNABLE_TO_CHECK_REVOCATION = 205,
CERT_REVOKED = 206,
CERT_INVALID = 207,
CERT_WEAK_SIGNATURE_ALGORITHM = 208,
CERT_NON_UNIQUE_NAME = 210,
CERT_WEAK_KEY = 211,
CERT_NAME_CONSTRAINT_VIOLATION = 212,
CERT_VALIDITY_TOO_LONG = 213,
CERT_END = 214,
INVALID_URL = 300,
DISALLOWED_URL_SCHEME = 301,
UNKNOWN_URL_SCHEME = 302,
TOO_MANY_REDIRECTS = 310,
UNSAFE_REDIRECT = 311,
UNSAFE_PORT = 312,
INVALID_RESPONSE = 320,
INVALID_CHUNKED_ENCODING = 321,
METHOD_NOT_SUPPORTED = 322,
UNEXPECTED_PROXY_AUTH = 323,
EMPTY_RESPONSE = 324,
RESPONSE_HEADERS_TOO_BIG = 325,
PAC_STATUS_NOT_OK = 326,
PAC_SCRIPT_FAILED = 327,
REQUEST_RANGE_NOT_SATISFIABLE = 328,
MALFORMED_IDENTITY = 329,
CONTENT_DECODING_FAILED = 330,
NETWORK_IO_SUSPENDED = 331,
SYN_REPLY_NOT_RECEIVED = 332,
ENCODING_CONVERSION_FAILED = 333,
UNRECOGNIZED_FTP_DIRECTORY_LISTING_FORMAT = 334,
INVALID_SPDY_STREAM = 335,
NO_SUPPORTED_PROXIES = 336,
SPDY_PROTOCOL_ERROR = 337,
INVALID_AUTH_CREDENTIALS = 338,
UNSUPPORTED_AUTH_SCHEME = 339,
ENCODING_DETECTION_FAILED = 340,
MISSING_AUTH_CREDENTIALS = 341,
UNEXPECTED_SECURITY_LIBRARY_STATUS = 342,
MISCONFIGURED_AUTH_ENVIRONMENT = 343,
UNDOCUMENTED_SECURITY_LIBRARY_STATUS = 344,
RESPONSE_BODY_TOO_BIG_TO_DRAIN = 345,
RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH = 346,
INCOMPLETE_SPDY_HEADERS = 347,
PAC_NOT_IN_DHCP = 348,
RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION = 349,
RESPONSE_HEADERS_MULTIPLE_LOCATION = 350,
SPDY_SERVER_REFUSED_STREAM = 351,
SPDY_PING_FAILED = 352,
CONTENT_LENGTH_MISMATCH = 354,
INCOMPLETE_CHUNKED_ENCODING = 355,
QUIC_PROTOCOL_ERROR = 356,
RESPONSE_HEADERS_TRUNCATED = 357,
QUIC_HANDSHAKE_FAILED = 358,
REQUEST_FOR_SECURE_RESOURCE_OVER_INSECURE_QUIC = 359,
SPDY_INADEQUATE_TRANSPORT_SECURITY = 360,
SPDY_FLOW_CONTROL_ERROR = 361,
SPDY_FRAME_SIZE_ERROR = 362,
SPDY_COMPRESSION_ERROR = 363,
PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION = 364,
HTTP_1_1_REQUIRED = 365,
PROXY_HTTP_1_1_REQUIRED = 366,
CACHE_MISS = 400,
CACHE_READ_FAILURE = 401,
CACHE_WRITE_FAILURE = 402,
CACHE_OPERATION_NOT_SUPPORTED = 403,
CACHE_OPEN_FAILURE = 404,
CACHE_CREATE_FAILURE = 405,
CACHE_RACE = 406,
CACHE_CHECKSUM_READ_FAILURE = 407,
CACHE_CHECKSUM_MISMATCH = 408,
CACHE_LOCK_TIMEOUT = 409,
INSECURE_RESPONSE = 501,
NO_PRIVATE_KEY_FOR_CERT = 502,
ADD_USER_CERT_FAILED = 503,
FTP_FAILED = 601,
FTP_SERVICE_UNAVAILABLE = 602,
FTP_TRANSFER_ABORTED = 603,
FTP_FILE_BUSY = 604,
FTP_SYNTAX_ERROR = 605,
FTP_COMMAND_NOT_SUPPORTED = 606,
FTP_BAD_COMMAND_SEQUENCE = 607,
PKCS12_IMPORT_BAD_PASSWORD = 701,
PKCS12_IMPORT_FAILED = 702,
IMPORT_CA | NetError | identifier_name |
|
net_error_list.rs | 1,
FAILED = 2,
ABORTED = 3,
INVALID_ARGUMENT = 4,
INVALID_HANDLE = 5,
FILE_NOT_FOUND = 6,
TIMED_OUT = 7,
FILE_TOO_BIG = 8,
UNEXPECTED = 9,
ACCESS_DENIED = 10,
NOT_IMPLEMENTED = 11,
INSUFFICIENT_RESOURCES = 12,
OUT_OF_MEMORY = 13,
UPLOAD_FILE_CHANGED = 14,
SOCKET_NOT_CONNECTED = 15,
FILE_EXISTS = 16,
FILE_PATH_TOO_LONG = 17,
FILE_NO_SPACE = 18,
FILE_VIRUS_INFECTED = 19,
BLOCKED_BY_CLIENT = 20,
NETWORK_CHANGED = 21,
BLOCKED_BY_ADMINISTRATOR = 22,
SOCKET_IS_CONNECTED = 23,
BLOCKED_ENROLLMENT_CHECK_PENDING = 24,
UPLOAD_STREAM_REWIND_NOT_SUPPORTED = 25,
CONNECTION_CLOSED = 100,
CONNECTION_RESET = 101,
CONNECTION_REFUSED = 102,
CONNECTION_ABORTED = 103,
CONNECTION_FAILED = 104,
NAME_NOT_RESOLVED = 105,
INTERNET_DISCONNECTED = 106,
SSL_PROTOCOL_ERROR = 107,
ADDRESS_INVALID = 108,
ADDRESS_UNREACHABLE = 109,
SSL_CLIENT_AUTH_CERT_NEEDED = 110,
TUNNEL_CONNECTION_FAILED = 111,
NO_SSL_VERSIONS_ENABLED = 112,
SSL_VERSION_OR_CIPHER_MISMATCH = 113,
SSL_RENEGOTIATION_REQUESTED = 114,
PROXY_AUTH_UNSUPPORTED = 115,
CERT_ERROR_IN_SSL_RENEGOTIATION = 116,
BAD_SSL_CLIENT_AUTH_CERT = 117,
CONNECTION_TIMED_OUT = 118,
HOST_RESOLVER_QUEUE_TOO_LARGE = 119,
SOCKS_CONNECTION_FAILED = 120,
SOCKS_CONNECTION_HOST_UNREACHABLE = 121,
NPN_NEGOTIATION_FAILED = 122,
SSL_NO_RENEGOTIATION = 123,
WINSOCK_UNEXPECTED_WRITTEN_BYTES = 124,
SSL_DECOMPRESSION_FAILURE_ALERT = 125, | SSL_UNSAFE_NEGOTIATION = 128,
SSL_WEAK_SERVER_EPHEMERAL_DH_KEY = 129,
PROXY_CONNECTION_FAILED = 130,
MANDATORY_PROXY_CONFIGURATION_FAILED = 131,
PRECONNECT_MAX_SOCKET_LIMIT = 133,
SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED = 134,
SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY = 135,
PROXY_CERTIFICATE_INVALID = 136,
NAME_RESOLUTION_FAILED = 137,
NETWORK_ACCESS_DENIED = 138,
TEMPORARILY_THROTTLED = 139,
HTTPS_PROXY_TUNNEL_RESPONSE = 140,
SSL_CLIENT_AUTH_SIGNATURE_FAILED = 141,
MSG_TOO_BIG = 142,
SPDY_SESSION_ALREADY_EXISTS = 143,
WS_PROTOCOL_ERROR = 145,
ADDRESS_IN_USE = 147,
SSL_HANDSHAKE_NOT_COMPLETED = 148,
SSL_BAD_PEER_PUBLIC_KEY = 149,
SSL_PINNED_KEY_NOT_IN_CERT_CHAIN = 150,
CLIENT_AUTH_CERT_TYPE_UNSUPPORTED = 151,
ORIGIN_BOUND_CERT_GENERATION_TYPE_MISMATCH = 152,
SSL_DECRYPT_ERROR_ALERT = 153,
WS_THROTTLE_QUEUE_TOO_LARGE = 154,
SSL_SERVER_CERT_CHANGED = 156,
SSL_INAPPROPRIATE_FALLBACK = 157,
CT_NO_SCTS_VERIFIED_OK = 158,
SSL_UNRECOGNIZED_NAME_ALERT = 159,
SOCKET_SET_RECEIVE_BUFFER_SIZE_ERROR = 160,
SOCKET_SET_SEND_BUFFER_SIZE_ERROR = 161,
SOCKET_RECEIVE_BUFFER_SIZE_UNCHANGEABLE = 162,
SOCKET_SEND_BUFFER_SIZE_UNCHANGEABLE = 163,
SSL_CLIENT_AUTH_CERT_BAD_FORMAT = 164,
SSL_FALLBACK_BEYOND_MINIMUM_VERSION = 165,
CERT_COMMON_NAME_INVALID = 200,
CERT_DATE_INVALID = 201,
CERT_AUTHORITY_INVALID = 202,
CERT_CONTAINS_ERRORS = 203,
CERT_NO_REVOCATION_MECHANISM = 204,
CERT_UNABLE_TO_CHECK_REVOCATION = 205,
CERT_REVOKED = 206,
CERT_INVALID = 207,
CERT_WEAK_SIGNATURE_ALGORITHM = 208,
CERT_NON_UNIQUE_NAME = 210,
CERT_WEAK_KEY = 211,
CERT_NAME_CONSTRAINT_VIOLATION = 212,
CERT_VALIDITY_TOO_LONG = 213,
CERT_END = 214,
INVALID_URL = 300,
DISALLOWED_URL_SCHEME = 301,
UNKNOWN_URL_SCHEME = 302,
TOO_MANY_REDIRECTS = 310,
UNSAFE_REDIRECT = 311,
UNSAFE_PORT = 312,
INVALID_RESPONSE = 320,
INVALID_CHUNKED_ENCODING = 321,
METHOD_NOT_SUPPORTED = 322,
UNEXPECTED_PROXY_AUTH = 323,
EMPTY_RESPONSE = 324,
RESPONSE_HEADERS_TOO_BIG = 325,
PAC_STATUS_NOT_OK = 326,
PAC_SCRIPT_FAILED = 327,
REQUEST_RANGE_NOT_SATISFIABLE = 328,
MALFORMED_IDENTITY = 329,
CONTENT_DECODING_FAILED = 330,
NETWORK_IO_SUSPENDED = 331,
SYN_REPLY_NOT_RECEIVED = 332,
ENCODING_CONVERSION_FAILED = 333,
UNRECOGNIZED_FTP_DIRECTORY_LISTING_FORMAT = 334,
INVALID_SPDY_STREAM = 335,
NO_SUPPORTED_PROXIES = 336,
SPDY_PROTOCOL_ERROR = 337,
INVALID_AUTH_CREDENTIALS = 338,
UNSUPPORTED_AUTH_SCHEME = 339,
ENCODING_DETECTION_FAILED = 340,
MISSING_AUTH_CREDENTIALS = 341,
UNEXPECTED_SECURITY_LIBRARY_STATUS = 342,
MISCONFIGURED_AUTH_ENVIRONMENT = 343,
UNDOCUMENTED_SECURITY_LIBRARY_STATUS = 344,
RESPONSE_BODY_TOO_BIG_TO_DRAIN = 345,
RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH = 346,
INCOMPLETE_SPDY_HEADERS = 347,
PAC_NOT_IN_DHCP = 348,
RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION = 349,
RESPONSE_HEADERS_MULTIPLE_LOCATION = 350,
SPDY_SERVER_REFUSED_STREAM = 351,
SPDY_PING_FAILED = 352,
CONTENT_LENGTH_MISMATCH = 354,
INCOMPLETE_CHUNKED_ENCODING = 355,
QUIC_PROTOCOL_ERROR = 356,
RESPONSE_HEADERS_TRUNCATED = 357,
QUIC_HANDSHAKE_FAILED = 358,
REQUEST_FOR_SECURE_RESOURCE_OVER_INSECURE_QUIC = 359,
SPDY_INADEQUATE_TRANSPORT_SECURITY = 360,
SPDY_FLOW_CONTROL_ERROR = 361,
SPDY_FRAME_SIZE_ERROR = 362,
SPDY_COMPRESSION_ERROR = 363,
PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION = 364,
HTTP_1_1_REQUIRED = 365,
PROXY_HTTP_1_1_REQUIRED = 366,
CACHE_MISS = 400,
CACHE_READ_FAILURE = 401,
CACHE_WRITE_FAILURE = 402,
CACHE_OPERATION_NOT_SUPPORTED = 403,
CACHE_OPEN_FAILURE = 404,
CACHE_CREATE_FAILURE = 405,
CACHE_RACE = 406,
CACHE_CHECKSUM_READ_FAILURE = 407,
CACHE_CHECKSUM_MISMATCH = 408,
CACHE_LOCK_TIMEOUT = 409,
INSECURE_RESPONSE = 501,
NO_PRIVATE_KEY_FOR_CERT = 502,
ADD_USER_CERT_FAILED = 503,
FTP_FAILED = 601,
FTP_SERVICE_UNAVAILABLE = 602,
FTP_TRANSFER_ABORTED = 603,
FTP_FILE_BUSY = 604,
FTP_SYNTAX_ERROR = 605,
FTP_COMMAND_NOT_SUPPORTED = 606,
FTP_BAD_COMMAND_SEQUENCE = 607,
PKCS12_IMPORT_BAD_PASSWORD = 701,
PKCS12_IMPORT_FAILED = 702,
IMPORT_CA_CERT_NOT_CA = 70 | SSL_BAD_RECORD_MAC_ALERT = 126,
PROXY_AUTH_REQUESTED = 127, | random_line_split |
helpers.ts | error']) {
options['error'] = (response: Jolokia.IErrorResponse) => defaultJolokiaErrorHandler(response, options);
}
return options;
}
/**
* The default error handler which logs errors either using debug or log level logging based on the silent setting
* @param response the response from a jolokia request
*/
export function defaultJolokiaErrorHandler(response: Jolokia.IErrorResponse, options: Jolokia.IParams = {}): void {
let operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
let silent = options['silent'];
let stacktrace = response.stacktrace;
if (silent || isIgnorableException(response)) {
log.debug("Operation", operation, "failed due to:", response['error']);
} else {
log.warn("Operation", operation, "failed due to:", response['error']);
}
}
/**
* Checks if it's an error that can happen on timing issues such as its been removed or if we run against older containers
* @param {Object} response the error response from a jolokia request
*/
function isIgnorableException(response: Jolokia.IErrorResponse): boolean {
let isNotFound = (target) =>
target.indexOf("InstanceNotFoundException") >= 0
|| target.indexOf("AttributeNotFoundException") >= 0
|| target.indexOf("IllegalArgumentException: No operation") >= 0;
return (response.stacktrace && isNotFound(response.stacktrace)) || (response.error && isNotFound(response.error));
}
/**
* Logs any failed operation and stack traces
*/
export function logJolokiaStackTrace(response: Jolokia.IErrorResponse) {
let stacktrace = response.stacktrace;
if (stacktrace) {
let operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
log.info("Operation", operation, "failed due to:", response['error']);
}
}
/**
* Applies the Jolokia escaping rules to the mbean name.
* See: http://www.jolokia.org/reference/html/protocol.html#escape-rules
*
* @param {string} mbean the mbean
* @returns {string}
*/
function applyJolokiaEscapeRules(mbean: string): string {
return mbean
.replace(/!/g, '!!')
.replace(/\//g, '!/')
.replace(/"/g, '!"');
}
/**
* Escapes the mbean for Jolokia GET requests.
*
* @param {string} mbean the mbean
* @returns {string}
*/
export function escapeMBean(mbean: string): string {
return encodeURI(applyJolokiaEscapeRules(mbean));
}
/**
* Escapes the mbean as a path for Jolokia POST "list" requests.
* See: https://jolokia.org/reference/html/protocol.html#list
*
* @param {string} mbean the mbean
* @returns {string}
*/
export function escapeMBeanPath(mbean: string): string {
return applyJolokiaEscapeRules(mbean).replace(':', '/');
}
export function parseMBean(mbean) {
let answer: any = {};
let parts: any = mbean.split(":");
if (parts.length > 1) {
answer['domain'] = _.first(parts);
parts = _.without(parts, _.first(parts));
parts = parts.join(":");
answer['attributes'] = {};
let nameValues = parts.split(",");
nameValues.forEach((str) => {
let nameValue = str.split('=');
let name = (<string>_.first(nameValue)).trim();
nameValue = _.without(nameValue, _.first(nameValue));
answer['attributes'][name] = nameValue.join('=').trim();
});
}
return answer;
}
/**
* Register a JMX operation to poll for changes, only
* calls back when a change occurs
*
* @param jolokia
* @param scope
* @param arguments
* @param callback
* @param options
* @returns Object
*/
export function | (jolokia, $scope, arguments, callback: (response: any) => void, options?: any): () => void {
let decorated = {
responseJson: '',
success: (response) => {
let json = angular.toJson(response.value);
if (decorated.responseJson !== json) {
decorated.responseJson = json;
callback(response);
}
}
};
angular.extend(decorated, options);
return Core.register(jolokia, $scope, arguments, onSuccess(undefined, decorated));
}
// Jolokia caching stuff, try and cache responses so we don't always have to wait
// for the server
export interface IResponseHistory {
[name: string]: any;
}
let responseHistory: IResponseHistory = null;
export function getOrInitObjectFromLocalStorage(key: string): any {
let answer: any = undefined;
if (!(key in localStorage)) {
localStorage[key] = angular.toJson({});
}
return angular.fromJson(localStorage[key]);
}
function argumentsToString(arguments: Array<any>) {
return StringHelpers.toString(arguments);
}
function keyForArgument(argument: any) {
if (!('type' in argument)) {
return null;
}
let answer = <string>argument['type'];
switch (answer.toLowerCase()) {
case 'exec':
answer += ':' + argument['mbean'] + ':' + argument['operation'];
let argString = argumentsToString(argument['arguments']);
if (!Core.isBlank(argString)) {
answer += ':' + argString;
}
break;
case 'read':
answer += ':' + argument['mbean'] + ':' + argument['attribute'];
break;
default:
return null;
}
return answer;
}
function createResponseKey(arguments: any) {
let answer = '';
if (angular.isArray(arguments)) {
answer = arguments.map((arg) => { return keyForArgument(arg); }).join(':');
} else {
answer = keyForArgument(arguments);
}
return answer;
}
export function getResponseHistory(): any {
if (responseHistory === null) {
//responseHistory = getOrInitObjectFromLocalStorage('responseHistory');
responseHistory = {};
log.debug("Created response history", responseHistory);
}
return responseHistory;
}
export const MAX_RESPONSE_CACHE_SIZE = 20;
function getOldestKey(responseHistory: IResponseHistory) {
let oldest: number = null;
let oldestKey: string = null;
angular.forEach(responseHistory, (value: any, key: string) => {
//log.debug("Checking entry: ", key);
//log.debug("Oldest timestamp: ", oldest, " key: ", key, " value: ", value);
if (!value || !value.timestamp) {
// null value is an excellent candidate for deletion
oldest = 0;
oldestKey = key;
} else if (oldest === null || value.timestamp < oldest) {
oldest = value.timestamp;
oldestKey = key;
}
});
return oldestKey;
}
function addResponse(arguments: any, value: any) {
let responseHistory = getResponseHistory();
let key = createResponseKey(arguments);
if (key === null) {
log.debug("key for arguments is null, not caching: ", StringHelpers.toString(arguments));
return;
}
//log.debug("Adding response to history, key: ", key, " value: ", value);
// trim the cache if needed
let keys = _.keys(responseHistory);
//log.debug("Number of stored responses: ", keys.length);
if (keys.length >= MAX_RESPONSE_CACHE_SIZE) {
log.debug("Cache limit (", MAX_RESPONSE_CACHE_SIZE, ") met or exceeded (", keys.length, "), trimming oldest response");
let oldestKey = getOldestKey(responseHistory);
if (oldestKey !== null) {
// delete the oldest entry
log.debug("Deleting key: ", oldestKey);
delete responseHistory[oldestKey];
} else {
log.debug("Got null key, could be a cache problem, wiping cache");
keys.forEach((key) => {
log.debug("Deleting key: ", key);
delete responseHistory[key];
});
}
}
responseHistory[key] = value;
//localStorage['responseHistory'] = angular.toJson(responseHistory);
}
function getResponse(jolokia, arguments: any, callback: any) {
let responseHistory = getResponseHistory();
let key = createResponseKey(arguments);
if (key === null) {
jolokia.request(arguments, callback);
return;
}
if (key in responseHistory && 'success' in callback) {
let value = responseHistory[key];
// do this async, the controller might not handle us immediately calling back
setTimeout(() => {
callback['success'](value);
}, 10);
} else {
log.debug("Unable to find existing response for key: ", key);
jolokia.request(arguments, callback);
}
}
// end jolokia caching stuff
/**
* Register a JMX operation to poll for changes
* @method register
* @for Core
* @static
* @ | registerForChanges | identifier_name |
helpers.ts | error']) {
options['error'] = (response: Jolokia.IErrorResponse) => defaultJolokiaErrorHandler(response, options);
}
return options;
}
/**
* The default error handler which logs errors either using debug or log level logging based on the silent setting
* @param response the response from a jolokia request
*/
export function defaultJolokiaErrorHandler(response: Jolokia.IErrorResponse, options: Jolokia.IParams = {}): void {
let operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
let silent = options['silent'];
let stacktrace = response.stacktrace;
if (silent || isIgnorableException(response)) {
log.debug("Operation", operation, "failed due to:", response['error']);
} else {
log.warn("Operation", operation, "failed due to:", response['error']);
}
}
/**
* Checks if it's an error that can happen on timing issues such as its been removed or if we run against older containers
* @param {Object} response the error response from a jolokia request
*/
function isIgnorableException(response: Jolokia.IErrorResponse): boolean {
let isNotFound = (target) =>
target.indexOf("InstanceNotFoundException") >= 0
|| target.indexOf("AttributeNotFoundException") >= 0
|| target.indexOf("IllegalArgumentException: No operation") >= 0;
return (response.stacktrace && isNotFound(response.stacktrace)) || (response.error && isNotFound(response.error));
}
/**
* Logs any failed operation and stack traces
*/
export function logJolokiaStackTrace(response: Jolokia.IErrorResponse) {
let stacktrace = response.stacktrace;
if (stacktrace) {
let operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
log.info("Operation", operation, "failed due to:", response['error']);
}
}
/**
* Applies the Jolokia escaping rules to the mbean name.
* See: http://www.jolokia.org/reference/html/protocol.html#escape-rules
*
* @param {string} mbean the mbean
* @returns {string}
*/
function applyJolokiaEscapeRules(mbean: string): string {
return mbean
.replace(/!/g, '!!')
.replace(/\//g, '!/')
.replace(/"/g, '!"');
}
/**
* Escapes the mbean for Jolokia GET requests.
*
* @param {string} mbean the mbean
* @returns {string}
*/
export function escapeMBean(mbean: string): string |
/**
* Escapes the mbean as a path for Jolokia POST "list" requests.
* See: https://jolokia.org/reference/html/protocol.html#list
*
* @param {string} mbean the mbean
* @returns {string}
*/
export function escapeMBeanPath(mbean: string): string {
return applyJolokiaEscapeRules(mbean).replace(':', '/');
}
export function parseMBean(mbean) {
let answer: any = {};
let parts: any = mbean.split(":");
if (parts.length > 1) {
answer['domain'] = _.first(parts);
parts = _.without(parts, _.first(parts));
parts = parts.join(":");
answer['attributes'] = {};
let nameValues = parts.split(",");
nameValues.forEach((str) => {
let nameValue = str.split('=');
let name = (<string>_.first(nameValue)).trim();
nameValue = _.without(nameValue, _.first(nameValue));
answer['attributes'][name] = nameValue.join('=').trim();
});
}
return answer;
}
/**
* Register a JMX operation to poll for changes, only
* calls back when a change occurs
*
* @param jolokia
* @param scope
* @param arguments
* @param callback
* @param options
* @returns Object
*/
export function registerForChanges(jolokia, $scope, arguments, callback: (response: any) => void, options?: any): () => void {
let decorated = {
responseJson: '',
success: (response) => {
let json = angular.toJson(response.value);
if (decorated.responseJson !== json) {
decorated.responseJson = json;
callback(response);
}
}
};
angular.extend(decorated, options);
return Core.register(jolokia, $scope, arguments, onSuccess(undefined, decorated));
}
// Jolokia caching stuff, try and cache responses so we don't always have to wait
// for the server
export interface IResponseHistory {
[name: string]: any;
}
let responseHistory: IResponseHistory = null;
export function getOrInitObjectFromLocalStorage(key: string): any {
let answer: any = undefined;
if (!(key in localStorage)) {
localStorage[key] = angular.toJson({});
}
return angular.fromJson(localStorage[key]);
}
function argumentsToString(arguments: Array<any>) {
return StringHelpers.toString(arguments);
}
function keyForArgument(argument: any) {
if (!('type' in argument)) {
return null;
}
let answer = <string>argument['type'];
switch (answer.toLowerCase()) {
case 'exec':
answer += ':' + argument['mbean'] + ':' + argument['operation'];
let argString = argumentsToString(argument['arguments']);
if (!Core.isBlank(argString)) {
answer += ':' + argString;
}
break;
case 'read':
answer += ':' + argument['mbean'] + ':' + argument['attribute'];
break;
default:
return null;
}
return answer;
}
function createResponseKey(arguments: any) {
let answer = '';
if (angular.isArray(arguments)) {
answer = arguments.map((arg) => { return keyForArgument(arg); }).join(':');
} else {
answer = keyForArgument(arguments);
}
return answer;
}
export function getResponseHistory(): any {
if (responseHistory === null) {
//responseHistory = getOrInitObjectFromLocalStorage('responseHistory');
responseHistory = {};
log.debug("Created response history", responseHistory);
}
return responseHistory;
}
export const MAX_RESPONSE_CACHE_SIZE = 20;
function getOldestKey(responseHistory: IResponseHistory) {
let oldest: number = null;
let oldestKey: string = null;
angular.forEach(responseHistory, (value: any, key: string) => {
//log.debug("Checking entry: ", key);
//log.debug("Oldest timestamp: ", oldest, " key: ", key, " value: ", value);
if (!value || !value.timestamp) {
// null value is an excellent candidate for deletion
oldest = 0;
oldestKey = key;
} else if (oldest === null || value.timestamp < oldest) {
oldest = value.timestamp;
oldestKey = key;
}
});
return oldestKey;
}
function addResponse(arguments: any, value: any) {
let responseHistory = getResponseHistory();
let key = createResponseKey(arguments);
if (key === null) {
log.debug("key for arguments is null, not caching: ", StringHelpers.toString(arguments));
return;
}
//log.debug("Adding response to history, key: ", key, " value: ", value);
// trim the cache if needed
let keys = _.keys(responseHistory);
//log.debug("Number of stored responses: ", keys.length);
if (keys.length >= MAX_RESPONSE_CACHE_SIZE) {
log.debug("Cache limit (", MAX_RESPONSE_CACHE_SIZE, ") met or exceeded (", keys.length, "), trimming oldest response");
let oldestKey = getOldestKey(responseHistory);
if (oldestKey !== null) {
// delete the oldest entry
log.debug("Deleting key: ", oldestKey);
delete responseHistory[oldestKey];
} else {
log.debug("Got null key, could be a cache problem, wiping cache");
keys.forEach((key) => {
log.debug("Deleting key: ", key);
delete responseHistory[key];
});
}
}
responseHistory[key] = value;
//localStorage['responseHistory'] = angular.toJson(responseHistory);
}
function getResponse(jolokia, arguments: any, callback: any) {
let responseHistory = getResponseHistory();
let key = createResponseKey(arguments);
if (key === null) {
jolokia.request(arguments, callback);
return;
}
if (key in responseHistory && 'success' in callback) {
let value = responseHistory[key];
// do this async, the controller might not handle us immediately calling back
setTimeout(() => {
callback['success'](value);
}, 10);
} else {
log.debug("Unable to find existing response for key: ", key);
jolokia.request(arguments, callback);
}
}
// end jolokia caching stuff
/**
* Register a JMX operation to poll for changes
* @method register
* @for Core
* @static
* | {
return encodeURI(applyJolokiaEscapeRules(mbean));
} | identifier_body |
helpers.ts | ['error']) {
options['error'] = (response: Jolokia.IErrorResponse) => defaultJolokiaErrorHandler(response, options);
}
return options;
}
/**
* The default error handler which logs errors either using debug or log level logging based on the silent setting
* @param response the response from a jolokia request
*/
export function defaultJolokiaErrorHandler(response: Jolokia.IErrorResponse, options: Jolokia.IParams = {}): void {
let operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
let silent = options['silent'];
let stacktrace = response.stacktrace;
if (silent || isIgnorableException(response)) {
log.debug("Operation", operation, "failed due to:", response['error']);
} else {
log.warn("Operation", operation, "failed due to:", response['error']);
}
}
/**
* Checks if it's an error that can happen on timing issues such as its been removed or if we run against older containers
* @param {Object} response the error response from a jolokia request
*/
function isIgnorableException(response: Jolokia.IErrorResponse): boolean {
let isNotFound = (target) =>
target.indexOf("InstanceNotFoundException") >= 0
|| target.indexOf("AttributeNotFoundException") >= 0
|| target.indexOf("IllegalArgumentException: No operation") >= 0;
return (response.stacktrace && isNotFound(response.stacktrace)) || (response.error && isNotFound(response.error));
}
/**
* Logs any failed operation and stack traces
*/
export function logJolokiaStackTrace(response: Jolokia.IErrorResponse) {
let stacktrace = response.stacktrace;
if (stacktrace) {
let operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
log.info("Operation", operation, "failed due to:", response['error']);
}
}
/**
* Applies the Jolokia escaping rules to the mbean name.
* See: http://www.jolokia.org/reference/html/protocol.html#escape-rules
*
* @param {string} mbean the mbean
* @returns {string}
*/
function applyJolokiaEscapeRules(mbean: string): string {
return mbean
.replace(/!/g, '!!')
.replace(/\//g, '!/')
.replace(/"/g, '!"');
}
/**
* Escapes the mbean for Jolokia GET requests.
*
* @param {string} mbean the mbean
* @returns {string}
*/
export function escapeMBean(mbean: string): string {
return encodeURI(applyJolokiaEscapeRules(mbean));
}
/**
* Escapes the mbean as a path for Jolokia POST "list" requests.
* See: https://jolokia.org/reference/html/protocol.html#list
*
* @param {string} mbean the mbean
* @returns {string}
*/
export function escapeMBeanPath(mbean: string): string {
return applyJolokiaEscapeRules(mbean).replace(':', '/');
}
export function parseMBean(mbean) {
let answer: any = {};
let parts: any = mbean.split(":");
if (parts.length > 1) {
answer['domain'] = _.first(parts);
parts = _.without(parts, _.first(parts));
parts = parts.join(":");
answer['attributes'] = {};
let nameValues = parts.split(",");
nameValues.forEach((str) => {
let nameValue = str.split('=');
let name = (<string>_.first(nameValue)).trim();
nameValue = _.without(nameValue, _.first(nameValue));
answer['attributes'][name] = nameValue.join('=').trim();
});
}
return answer;
}
/**
* Register a JMX operation to poll for changes, only | *
* @param jolokia
* @param scope
* @param arguments
* @param callback
* @param options
* @returns Object
*/
export function registerForChanges(jolokia, $scope, arguments, callback: (response: any) => void, options?: any): () => void {
let decorated = {
responseJson: '',
success: (response) => {
let json = angular.toJson(response.value);
if (decorated.responseJson !== json) {
decorated.responseJson = json;
callback(response);
}
}
};
angular.extend(decorated, options);
return Core.register(jolokia, $scope, arguments, onSuccess(undefined, decorated));
}
// Jolokia caching stuff, try and cache responses so we don't always have to wait
// for the server
export interface IResponseHistory {
[name: string]: any;
}
let responseHistory: IResponseHistory = null;
export function getOrInitObjectFromLocalStorage(key: string): any {
let answer: any = undefined;
if (!(key in localStorage)) {
localStorage[key] = angular.toJson({});
}
return angular.fromJson(localStorage[key]);
}
function argumentsToString(arguments: Array<any>) {
return StringHelpers.toString(arguments);
}
function keyForArgument(argument: any) {
if (!('type' in argument)) {
return null;
}
let answer = <string>argument['type'];
switch (answer.toLowerCase()) {
case 'exec':
answer += ':' + argument['mbean'] + ':' + argument['operation'];
let argString = argumentsToString(argument['arguments']);
if (!Core.isBlank(argString)) {
answer += ':' + argString;
}
break;
case 'read':
answer += ':' + argument['mbean'] + ':' + argument['attribute'];
break;
default:
return null;
}
return answer;
}
function createResponseKey(arguments: any) {
let answer = '';
if (angular.isArray(arguments)) {
answer = arguments.map((arg) => { return keyForArgument(arg); }).join(':');
} else {
answer = keyForArgument(arguments);
}
return answer;
}
export function getResponseHistory(): any {
if (responseHistory === null) {
//responseHistory = getOrInitObjectFromLocalStorage('responseHistory');
responseHistory = {};
log.debug("Created response history", responseHistory);
}
return responseHistory;
}
export const MAX_RESPONSE_CACHE_SIZE = 20;
function getOldestKey(responseHistory: IResponseHistory) {
let oldest: number = null;
let oldestKey: string = null;
angular.forEach(responseHistory, (value: any, key: string) => {
//log.debug("Checking entry: ", key);
//log.debug("Oldest timestamp: ", oldest, " key: ", key, " value: ", value);
if (!value || !value.timestamp) {
// null value is an excellent candidate for deletion
oldest = 0;
oldestKey = key;
} else if (oldest === null || value.timestamp < oldest) {
oldest = value.timestamp;
oldestKey = key;
}
});
return oldestKey;
}
function addResponse(arguments: any, value: any) {
let responseHistory = getResponseHistory();
let key = createResponseKey(arguments);
if (key === null) {
log.debug("key for arguments is null, not caching: ", StringHelpers.toString(arguments));
return;
}
//log.debug("Adding response to history, key: ", key, " value: ", value);
// trim the cache if needed
let keys = _.keys(responseHistory);
//log.debug("Number of stored responses: ", keys.length);
if (keys.length >= MAX_RESPONSE_CACHE_SIZE) {
log.debug("Cache limit (", MAX_RESPONSE_CACHE_SIZE, ") met or exceeded (", keys.length, "), trimming oldest response");
let oldestKey = getOldestKey(responseHistory);
if (oldestKey !== null) {
// delete the oldest entry
log.debug("Deleting key: ", oldestKey);
delete responseHistory[oldestKey];
} else {
log.debug("Got null key, could be a cache problem, wiping cache");
keys.forEach((key) => {
log.debug("Deleting key: ", key);
delete responseHistory[key];
});
}
}
responseHistory[key] = value;
//localStorage['responseHistory'] = angular.toJson(responseHistory);
}
function getResponse(jolokia, arguments: any, callback: any) {
let responseHistory = getResponseHistory();
let key = createResponseKey(arguments);
if (key === null) {
jolokia.request(arguments, callback);
return;
}
if (key in responseHistory && 'success' in callback) {
let value = responseHistory[key];
// do this async, the controller might not handle us immediately calling back
setTimeout(() => {
callback['success'](value);
}, 10);
} else {
log.debug("Unable to find existing response for key: ", key);
jolokia.request(arguments, callback);
}
}
// end jolokia caching stuff
/**
* Register a JMX operation to poll for changes
* @method register
* @for Core
* @static
* @return { | * calls back when a change occurs | random_line_split |
helpers.ts | error']) {
options['error'] = (response: Jolokia.IErrorResponse) => defaultJolokiaErrorHandler(response, options);
}
return options;
}
/**
* The default error handler which logs errors either using debug or log level logging based on the silent setting
* @param response the response from a jolokia request
*/
export function defaultJolokiaErrorHandler(response: Jolokia.IErrorResponse, options: Jolokia.IParams = {}): void {
let operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
let silent = options['silent'];
let stacktrace = response.stacktrace;
if (silent || isIgnorableException(response)) {
log.debug("Operation", operation, "failed due to:", response['error']);
} else {
log.warn("Operation", operation, "failed due to:", response['error']);
}
}
/**
* Checks if it's an error that can happen on timing issues such as its been removed or if we run against older containers
* @param {Object} response the error response from a jolokia request
*/
function isIgnorableException(response: Jolokia.IErrorResponse): boolean {
let isNotFound = (target) =>
target.indexOf("InstanceNotFoundException") >= 0
|| target.indexOf("AttributeNotFoundException") >= 0
|| target.indexOf("IllegalArgumentException: No operation") >= 0;
return (response.stacktrace && isNotFound(response.stacktrace)) || (response.error && isNotFound(response.error));
}
/**
* Logs any failed operation and stack traces
*/
export function logJolokiaStackTrace(response: Jolokia.IErrorResponse) {
let stacktrace = response.stacktrace;
if (stacktrace) {
let operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
log.info("Operation", operation, "failed due to:", response['error']);
}
}
/**
* Applies the Jolokia escaping rules to the mbean name.
* See: http://www.jolokia.org/reference/html/protocol.html#escape-rules
*
* @param {string} mbean the mbean
* @returns {string}
*/
function applyJolokiaEscapeRules(mbean: string): string {
return mbean
.replace(/!/g, '!!')
.replace(/\//g, '!/')
.replace(/"/g, '!"');
}
/**
* Escapes the mbean for Jolokia GET requests.
*
* @param {string} mbean the mbean
* @returns {string}
*/
export function escapeMBean(mbean: string): string {
return encodeURI(applyJolokiaEscapeRules(mbean));
}
/**
* Escapes the mbean as a path for Jolokia POST "list" requests.
* See: https://jolokia.org/reference/html/protocol.html#list
*
* @param {string} mbean the mbean
* @returns {string}
*/
export function escapeMBeanPath(mbean: string): string {
return applyJolokiaEscapeRules(mbean).replace(':', '/');
}
export function parseMBean(mbean) {
let answer: any = {};
let parts: any = mbean.split(":");
if (parts.length > 1) {
answer['domain'] = _.first(parts);
parts = _.without(parts, _.first(parts));
parts = parts.join(":");
answer['attributes'] = {};
let nameValues = parts.split(",");
nameValues.forEach((str) => {
let nameValue = str.split('=');
let name = (<string>_.first(nameValue)).trim();
nameValue = _.without(nameValue, _.first(nameValue));
answer['attributes'][name] = nameValue.join('=').trim();
});
}
return answer;
}
/**
* Register a JMX operation to poll for changes, only
* calls back when a change occurs
*
* @param jolokia
* @param scope
* @param arguments
* @param callback
* @param options
* @returns Object
*/
export function registerForChanges(jolokia, $scope, arguments, callback: (response: any) => void, options?: any): () => void {
let decorated = {
responseJson: '',
success: (response) => {
let json = angular.toJson(response.value);
if (decorated.responseJson !== json) {
decorated.responseJson = json;
callback(response);
}
}
};
angular.extend(decorated, options);
return Core.register(jolokia, $scope, arguments, onSuccess(undefined, decorated));
}
// Jolokia caching stuff, try and cache responses so we don't always have to wait
// for the server
export interface IResponseHistory {
[name: string]: any;
}
let responseHistory: IResponseHistory = null;
export function getOrInitObjectFromLocalStorage(key: string): any {
let answer: any = undefined;
if (!(key in localStorage)) {
localStorage[key] = angular.toJson({});
}
return angular.fromJson(localStorage[key]);
}
function argumentsToString(arguments: Array<any>) {
return StringHelpers.toString(arguments);
}
function keyForArgument(argument: any) {
if (!('type' in argument)) {
return null;
}
let answer = <string>argument['type'];
switch (answer.toLowerCase()) {
case 'exec':
answer += ':' + argument['mbean'] + ':' + argument['operation'];
let argString = argumentsToString(argument['arguments']);
if (!Core.isBlank(argString)) {
answer += ':' + argString;
}
break;
case 'read':
answer += ':' + argument['mbean'] + ':' + argument['attribute'];
break;
default:
return null;
}
return answer;
}
function createResponseKey(arguments: any) {
let answer = '';
if (angular.isArray(arguments)) | else {
answer = keyForArgument(arguments);
}
return answer;
}
export function getResponseHistory(): any {
if (responseHistory === null) {
//responseHistory = getOrInitObjectFromLocalStorage('responseHistory');
responseHistory = {};
log.debug("Created response history", responseHistory);
}
return responseHistory;
}
export const MAX_RESPONSE_CACHE_SIZE = 20;
function getOldestKey(responseHistory: IResponseHistory) {
let oldest: number = null;
let oldestKey: string = null;
angular.forEach(responseHistory, (value: any, key: string) => {
//log.debug("Checking entry: ", key);
//log.debug("Oldest timestamp: ", oldest, " key: ", key, " value: ", value);
if (!value || !value.timestamp) {
// null value is an excellent candidate for deletion
oldest = 0;
oldestKey = key;
} else if (oldest === null || value.timestamp < oldest) {
oldest = value.timestamp;
oldestKey = key;
}
});
return oldestKey;
}
function addResponse(arguments: any, value: any) {
let responseHistory = getResponseHistory();
let key = createResponseKey(arguments);
if (key === null) {
log.debug("key for arguments is null, not caching: ", StringHelpers.toString(arguments));
return;
}
//log.debug("Adding response to history, key: ", key, " value: ", value);
// trim the cache if needed
let keys = _.keys(responseHistory);
//log.debug("Number of stored responses: ", keys.length);
if (keys.length >= MAX_RESPONSE_CACHE_SIZE) {
log.debug("Cache limit (", MAX_RESPONSE_CACHE_SIZE, ") met or exceeded (", keys.length, "), trimming oldest response");
let oldestKey = getOldestKey(responseHistory);
if (oldestKey !== null) {
// delete the oldest entry
log.debug("Deleting key: ", oldestKey);
delete responseHistory[oldestKey];
} else {
log.debug("Got null key, could be a cache problem, wiping cache");
keys.forEach((key) => {
log.debug("Deleting key: ", key);
delete responseHistory[key];
});
}
}
responseHistory[key] = value;
//localStorage['responseHistory'] = angular.toJson(responseHistory);
}
function getResponse(jolokia, arguments: any, callback: any) {
let responseHistory = getResponseHistory();
let key = createResponseKey(arguments);
if (key === null) {
jolokia.request(arguments, callback);
return;
}
if (key in responseHistory && 'success' in callback) {
let value = responseHistory[key];
// do this async, the controller might not handle us immediately calling back
setTimeout(() => {
callback['success'](value);
}, 10);
} else {
log.debug("Unable to find existing response for key: ", key);
jolokia.request(arguments, callback);
}
}
// end jolokia caching stuff
/**
* Register a JMX operation to poll for changes
* @method register
* @for Core
* @static
* @ | {
answer = arguments.map((arg) => { return keyForArgument(arg); }).join(':');
} | conditional_block |
font_image_data_generator.js | /**
* Created by gooma on 4/16/2016.
*
* Generate font of same style, with different scale
**/
Dr.Declare('Graphic.FontImageDataGenerator', 'class');
Dr.Require('Graphic.FontImageDataGenerator', 'Graphic.ImageDataExt');
Dr.Require('Graphic.FontImageDataGenerator', 'Graphic.ImageOperation');
Dr.Implement('Graphic.FontImageDataGenerator', function (global, module_get) {
var ImageDataExt = module_get('Graphic.ImageDataExt');
var ImageOperation = module_get('Graphic.ImageOperation');
var FontImageDataGenerator = function () {
this.symbol_image_data_map = {};
this.scaled_symbol_image_data_map = {};
this.setDefaultAttribute(8, 15, 'normal', 'consolas, monaco, monospace', '#000000');
};
FontImageDataGenerator.prototype = {
constructor: FontImageDataGenerator,
setDefaultAttribute: function (font_size, line_height, font_style, font_family, fill_style) {
this._default_font_size = font_size;
this._default_line_height = line_height;
this._default_font_style = font_style; //normal, italic, oblique
this._default_font_family = font_family;
this._default_fill_style = fill_style; //color
this._default_font_config = this.getFontConfig();
},
getFontConfig: function (font_size, line_height, font_style, font_family, fill_style) {
//check CSS font for usage
font_size = font_size || this._default_font_size;
line_height = line_height || this._default_line_height;
font_style = font_style || this._default_font_style;
font_family = font_family || this._default_font_family;
fill_style = fill_style || this._default_fill_style;
return {
font_size: font_size,
line_height: line_height,
font_style: font_style,
font_family: font_family,
fill_style: fill_style,
attribute: font_style + ' ' + font_size + 'px/' + line_height + 'px ' + font_family, //css text
cache_tag: font_style + '|' + font_size + '|' + line_height + '|' + font_family + '|' + fill_style,
}
},
//intended to be used for single character
getSymbolMetricsWidth: function (symbol, font_config) {
var quick_context = ImageOperation.getQuickContext();
quick_context.font = font_config.attribute;
return quick_context.measureText(symbol).width;
},
//with generated cache, intended to be used for single character
generateSymbolImageData: function (symbol, font_config, metrics_width) {
//Dr.log('[generateSymbolImageData]', symbol, font_config.attribute);
//generate
var generated_image_data_ext = ImageDataExt.create( | var context = generated_image_data_ext.data.getContext('2d');
context.font = font_config.attribute;
context.textAlign = "start";
context.textBaseline = "middle"; // better than 'top'
context.fillStyle = font_config.fill_style;
context.fillText(symbol, 0, font_config.line_height * 0.5);
this.symbol_image_data_map[symbol] = this.symbol_image_data_map[symbol] || {};
this.symbol_image_data_map[symbol][font_config.attribute] = generated_image_data_ext;
return generated_image_data_ext;
},
getSymbolImageData: function (symbol, font_config) {
if (this.symbol_image_data_map[symbol] && this.symbol_image_data_map[symbol][font_config.cache_tag]) {
return this.symbol_image_data_map[symbol][font_config.cache_tag];
}
else {
return this.generateSymbolImageData(symbol, font_config, this.getSymbolMetricsWidth(symbol, font_config));
}
},
getScaledSymbolImageData: function (symbol, scale_ratio, font_config) {
font_config = font_config || this._default_font_config;
var cache_key = symbol + '|' + scale_ratio + ':' + font_config.cache_tag;
var scaled_image_data = this.scaled_symbol_image_data_map[cache_key];
if (!scaled_image_data) {
Dr.debug(5, 'cache add', cache_key);
var symbol_image_data = this.getSymbolImageData(symbol, font_config);
scaled_image_data = ImageDataExt.copy(symbol_image_data);
scaled_image_data.toCanvas();
scaled_image_data.scale(scale_ratio);
this.scaled_symbol_image_data_map[cache_key] = scaled_image_data;
}
return scaled_image_data;
},
};
return FontImageDataGenerator;
}); | ImageDataExt.type.CANVAS_ELEMENT,
metrics_width,
font_config.line_height); | random_line_split |
font_image_data_generator.js | /**
* Created by gooma on 4/16/2016.
*
* Generate font of same style, with different scale
**/
Dr.Declare('Graphic.FontImageDataGenerator', 'class');
Dr.Require('Graphic.FontImageDataGenerator', 'Graphic.ImageDataExt');
Dr.Require('Graphic.FontImageDataGenerator', 'Graphic.ImageOperation');
Dr.Implement('Graphic.FontImageDataGenerator', function (global, module_get) {
var ImageDataExt = module_get('Graphic.ImageDataExt');
var ImageOperation = module_get('Graphic.ImageOperation');
var FontImageDataGenerator = function () {
this.symbol_image_data_map = {};
this.scaled_symbol_image_data_map = {};
this.setDefaultAttribute(8, 15, 'normal', 'consolas, monaco, monospace', '#000000');
};
FontImageDataGenerator.prototype = {
constructor: FontImageDataGenerator,
setDefaultAttribute: function (font_size, line_height, font_style, font_family, fill_style) {
this._default_font_size = font_size;
this._default_line_height = line_height;
this._default_font_style = font_style; //normal, italic, oblique
this._default_font_family = font_family;
this._default_fill_style = fill_style; //color
this._default_font_config = this.getFontConfig();
},
getFontConfig: function (font_size, line_height, font_style, font_family, fill_style) {
//check CSS font for usage
font_size = font_size || this._default_font_size;
line_height = line_height || this._default_line_height;
font_style = font_style || this._default_font_style;
font_family = font_family || this._default_font_family;
fill_style = fill_style || this._default_fill_style;
return {
font_size: font_size,
line_height: line_height,
font_style: font_style,
font_family: font_family,
fill_style: fill_style,
attribute: font_style + ' ' + font_size + 'px/' + line_height + 'px ' + font_family, //css text
cache_tag: font_style + '|' + font_size + '|' + line_height + '|' + font_family + '|' + fill_style,
}
},
//intended to be used for single character
getSymbolMetricsWidth: function (symbol, font_config) {
var quick_context = ImageOperation.getQuickContext();
quick_context.font = font_config.attribute;
return quick_context.measureText(symbol).width;
},
//with generated cache, intended to be used for single character
generateSymbolImageData: function (symbol, font_config, metrics_width) {
//Dr.log('[generateSymbolImageData]', symbol, font_config.attribute);
//generate
var generated_image_data_ext = ImageDataExt.create(
ImageDataExt.type.CANVAS_ELEMENT,
metrics_width,
font_config.line_height);
var context = generated_image_data_ext.data.getContext('2d');
context.font = font_config.attribute;
context.textAlign = "start";
context.textBaseline = "middle"; // better than 'top'
context.fillStyle = font_config.fill_style;
context.fillText(symbol, 0, font_config.line_height * 0.5);
this.symbol_image_data_map[symbol] = this.symbol_image_data_map[symbol] || {};
this.symbol_image_data_map[symbol][font_config.attribute] = generated_image_data_ext;
return generated_image_data_ext;
},
getSymbolImageData: function (symbol, font_config) {
if (this.symbol_image_data_map[symbol] && this.symbol_image_data_map[symbol][font_config.cache_tag]) {
return this.symbol_image_data_map[symbol][font_config.cache_tag];
}
else |
},
getScaledSymbolImageData: function (symbol, scale_ratio, font_config) {
font_config = font_config || this._default_font_config;
var cache_key = symbol + '|' + scale_ratio + ':' + font_config.cache_tag;
var scaled_image_data = this.scaled_symbol_image_data_map[cache_key];
if (!scaled_image_data) {
Dr.debug(5, 'cache add', cache_key);
var symbol_image_data = this.getSymbolImageData(symbol, font_config);
scaled_image_data = ImageDataExt.copy(symbol_image_data);
scaled_image_data.toCanvas();
scaled_image_data.scale(scale_ratio);
this.scaled_symbol_image_data_map[cache_key] = scaled_image_data;
}
return scaled_image_data;
},
};
return FontImageDataGenerator;
});
| {
return this.generateSymbolImageData(symbol, font_config, this.getSymbolMetricsWidth(symbol, font_config));
} | conditional_block |
mod.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Terminfo database interface.
use std::collections::HashMap;
use std::io::IoResult;
use std::os;
use attr;
use color;
use Terminal;
use self::searcher::open;
use self::parser::compiled::{parse, msys_terminfo};
use self::parm::{expand, Number, Variables};
/// A parsed terminfo database entry.
#[deriving(Show)]
pub struct TermInfo {
/// Names for the terminal
pub names: Vec<String> ,
/// Map of capability name to boolean value
pub bools: HashMap<String, bool>,
/// Map of capability name to numeric value
pub numbers: HashMap<String, u16>,
/// Map of capability name to raw (unexpanded) string
pub strings: HashMap<String, Vec<u8> >
}
pub mod searcher;
/// TermInfo format parsing.
pub mod parser {
//! ncurses-compatible compiled terminfo format parsing (term(5))
pub mod compiled;
}
pub mod parm;
fn cap_for_attr(attr: attr::Attr) -> &'static str {
match attr {
attr::Bold => "bold",
attr::Dim => "dim",
attr::Italic(true) => "sitm",
attr::Italic(false) => "ritm",
attr::Underline(true) => "smul",
attr::Underline(false) => "rmul",
attr::Blink => "blink",
attr::Standout(true) => "smso",
attr::Standout(false) => "rmso",
attr::Reverse => "rev",
attr::Secure => "invis",
attr::ForegroundColor(_) => "setaf",
attr::BackgroundColor(_) => "setab"
}
}
/// A Terminal that knows how many colors it supports, with a reference to its
/// parsed Terminfo database record.
pub struct TerminfoTerminal<T> {
num_colors: u16,
out: T,
ti: Box<TermInfo>
}
impl<T: Writer> Terminal<T> for TerminfoTerminal<T> {
fn new(out: T) -> Option<TerminfoTerminal<T>> {
let term = match os::getenv("TERM") {
Some(t) => t,
None => {
debug!("TERM environment variable not defined");
return None;
}
};
let entry = open(term.as_slice());
if entry.is_err() {
if os::getenv("MSYSCON").map_or(false, |s| {
"mintty.exe" == s.as_slice()
}) {
// msys terminal
return Some(TerminfoTerminal {out: out, ti: msys_terminfo(), num_colors: 8});
}
debug!("error finding terminfo entry: {}", entry.err().unwrap());
return None;
}
let mut file = entry.unwrap();
let ti = parse(&mut file, false);
if ti.is_err() {
debug!("error parsing terminfo entry: {}", ti.unwrap_err());
return None;
}
let inf = ti.unwrap();
let nc = if inf.strings.find_equiv(&("setaf")).is_some()
&& inf.strings.find_equiv(&("setab")).is_some() {
inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n)
} else { 0 };
return Some(TerminfoTerminal {out: out, ti: inf, num_colors: nc});
}
fn fg(&mut self, color: color::Color) -> IoResult<bool> {
let color = self.dim_if_necessary(color);
if self.num_colors > color {
let s = expand(self.ti
.strings
.find_equiv(&("setaf"))
.unwrap()
.as_slice(),
[Number(color as int)], &mut Variables::new());
if s.is_ok() {
try!(self.out.write(s.unwrap().as_slice()));
return Ok(true)
}
}
Ok(false)
}
fn bg(&mut self, color: color::Color) -> IoResult<bool> {
let color = self.dim_if_necessary(color);
if self.num_colors > color {
let s = expand(self.ti | .as_slice(),
[Number(color as int)], &mut Variables::new());
if s.is_ok() {
try!(self.out.write(s.unwrap().as_slice()));
return Ok(true)
}
}
Ok(false)
}
fn attr(&mut self, attr: attr::Attr) -> IoResult<bool> {
match attr {
attr::ForegroundColor(c) => self.fg(c),
attr::BackgroundColor(c) => self.bg(c),
_ => {
let cap = cap_for_attr(attr);
let parm = self.ti.strings.find_equiv(&cap);
if parm.is_some() {
let s = expand(parm.unwrap().as_slice(),
[],
&mut Variables::new());
if s.is_ok() {
try!(self.out.write(s.unwrap().as_slice()));
return Ok(true)
}
}
Ok(false)
}
}
}
fn supports_attr(&self, attr: attr::Attr) -> bool {
match attr {
attr::ForegroundColor(_) | attr::BackgroundColor(_) => {
self.num_colors > 0
}
_ => {
let cap = cap_for_attr(attr);
self.ti.strings.find_equiv(&cap).is_some()
}
}
}
fn reset(&mut self) -> IoResult<()> {
let mut cap = self.ti.strings.find_equiv(&("sgr0"));
if cap.is_none() {
// are there any terminals that have color/attrs and not sgr0?
// Try falling back to sgr, then op
cap = self.ti.strings.find_equiv(&("sgr"));
if cap.is_none() {
cap = self.ti.strings.find_equiv(&("op"));
}
}
let s = cap.map_or(Err("can't find terminfo capability `sgr0`".to_string()), |op| {
expand(op.as_slice(), [], &mut Variables::new())
});
if s.is_ok() {
return self.out.write(s.unwrap().as_slice())
}
Ok(())
}
fn unwrap(self) -> T { self.out }
fn get_ref<'a>(&'a self) -> &'a T { &self.out }
fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out }
}
impl<T: Writer> TerminfoTerminal<T> {
fn dim_if_necessary(&self, color: color::Color) -> color::Color {
if color >= self.num_colors && color >= 8 && color < 16 {
color-8
} else { color }
}
}
impl<T: Writer> Writer for TerminfoTerminal<T> {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
self.out.write(buf)
}
fn flush(&mut self) -> IoResult<()> {
self.out.flush()
}
} | .strings
.find_equiv(&("setab"))
.unwrap() | random_line_split |
mod.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Terminfo database interface.
use std::collections::HashMap;
use std::io::IoResult;
use std::os;
use attr;
use color;
use Terminal;
use self::searcher::open;
use self::parser::compiled::{parse, msys_terminfo};
use self::parm::{expand, Number, Variables};
/// A parsed terminfo database entry.
#[deriving(Show)]
pub struct TermInfo {
/// Names for the terminal
pub names: Vec<String> ,
/// Map of capability name to boolean value
pub bools: HashMap<String, bool>,
/// Map of capability name to numeric value
pub numbers: HashMap<String, u16>,
/// Map of capability name to raw (unexpanded) string
pub strings: HashMap<String, Vec<u8> >
}
pub mod searcher;
/// TermInfo format parsing.
pub mod parser {
//! ncurses-compatible compiled terminfo format parsing (term(5))
pub mod compiled;
}
pub mod parm;
fn cap_for_attr(attr: attr::Attr) -> &'static str {
match attr {
attr::Bold => "bold",
attr::Dim => "dim",
attr::Italic(true) => "sitm",
attr::Italic(false) => "ritm",
attr::Underline(true) => "smul",
attr::Underline(false) => "rmul",
attr::Blink => "blink",
attr::Standout(true) => "smso",
attr::Standout(false) => "rmso",
attr::Reverse => "rev",
attr::Secure => "invis",
attr::ForegroundColor(_) => "setaf",
attr::BackgroundColor(_) => "setab"
}
}
/// A Terminal that knows how many colors it supports, with a reference to its
/// parsed Terminfo database record.
pub struct TerminfoTerminal<T> {
num_colors: u16,
out: T,
ti: Box<TermInfo>
}
impl<T: Writer> Terminal<T> for TerminfoTerminal<T> {
fn new(out: T) -> Option<TerminfoTerminal<T>> {
let term = match os::getenv("TERM") {
Some(t) => t,
None => {
debug!("TERM environment variable not defined");
return None;
}
};
let entry = open(term.as_slice());
if entry.is_err() {
if os::getenv("MSYSCON").map_or(false, |s| {
"mintty.exe" == s.as_slice()
}) {
// msys terminal
return Some(TerminfoTerminal {out: out, ti: msys_terminfo(), num_colors: 8});
}
debug!("error finding terminfo entry: {}", entry.err().unwrap());
return None;
}
let mut file = entry.unwrap();
let ti = parse(&mut file, false);
if ti.is_err() {
debug!("error parsing terminfo entry: {}", ti.unwrap_err());
return None;
}
let inf = ti.unwrap();
let nc = if inf.strings.find_equiv(&("setaf")).is_some()
&& inf.strings.find_equiv(&("setab")).is_some() {
inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n)
} else { 0 };
return Some(TerminfoTerminal {out: out, ti: inf, num_colors: nc});
}
fn fg(&mut self, color: color::Color) -> IoResult<bool> {
let color = self.dim_if_necessary(color);
if self.num_colors > color {
let s = expand(self.ti
.strings
.find_equiv(&("setaf"))
.unwrap()
.as_slice(),
[Number(color as int)], &mut Variables::new());
if s.is_ok() {
try!(self.out.write(s.unwrap().as_slice()));
return Ok(true)
}
}
Ok(false)
}
fn bg(&mut self, color: color::Color) -> IoResult<bool> {
let color = self.dim_if_necessary(color);
if self.num_colors > color {
let s = expand(self.ti
.strings
.find_equiv(&("setab"))
.unwrap()
.as_slice(),
[Number(color as int)], &mut Variables::new());
if s.is_ok() {
try!(self.out.write(s.unwrap().as_slice()));
return Ok(true)
}
}
Ok(false)
}
fn | (&mut self, attr: attr::Attr) -> IoResult<bool> {
match attr {
attr::ForegroundColor(c) => self.fg(c),
attr::BackgroundColor(c) => self.bg(c),
_ => {
let cap = cap_for_attr(attr);
let parm = self.ti.strings.find_equiv(&cap);
if parm.is_some() {
let s = expand(parm.unwrap().as_slice(),
[],
&mut Variables::new());
if s.is_ok() {
try!(self.out.write(s.unwrap().as_slice()));
return Ok(true)
}
}
Ok(false)
}
}
}
fn supports_attr(&self, attr: attr::Attr) -> bool {
match attr {
attr::ForegroundColor(_) | attr::BackgroundColor(_) => {
self.num_colors > 0
}
_ => {
let cap = cap_for_attr(attr);
self.ti.strings.find_equiv(&cap).is_some()
}
}
}
fn reset(&mut self) -> IoResult<()> {
let mut cap = self.ti.strings.find_equiv(&("sgr0"));
if cap.is_none() {
// are there any terminals that have color/attrs and not sgr0?
// Try falling back to sgr, then op
cap = self.ti.strings.find_equiv(&("sgr"));
if cap.is_none() {
cap = self.ti.strings.find_equiv(&("op"));
}
}
let s = cap.map_or(Err("can't find terminfo capability `sgr0`".to_string()), |op| {
expand(op.as_slice(), [], &mut Variables::new())
});
if s.is_ok() {
return self.out.write(s.unwrap().as_slice())
}
Ok(())
}
fn unwrap(self) -> T { self.out }
fn get_ref<'a>(&'a self) -> &'a T { &self.out }
fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out }
}
impl<T: Writer> TerminfoTerminal<T> {
fn dim_if_necessary(&self, color: color::Color) -> color::Color {
if color >= self.num_colors && color >= 8 && color < 16 {
color-8
} else { color }
}
}
impl<T: Writer> Writer for TerminfoTerminal<T> {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
self.out.write(buf)
}
fn flush(&mut self) -> IoResult<()> {
self.out.flush()
}
}
| attr | identifier_name |
service.py | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import errno
import subprocess
from subprocess import PIPE
import time
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common import utils
class Service(object):
"""
Object that manages the starting and stopping of the ChromeDriver
"""
def __init__(self, executable_path, port=0, service_args=None,
log_path=None, env=None):
"""
Creates a new instance of the Service
:Args:
- executable_path : Path to the ChromeDriver
- port : Port the service is running on
- service_args : List of args to pass to the chromedriver service
- log_path : Path for the chromedriver service to log to"""
self.port = port
self.path = executable_path
self.service_args = service_args or []
if log_path:
self.service_args.append('--log-path=%s' % log_path) | self.env = env
def start(self):
"""
Starts the ChromeDriver Service.
:Exceptions:
- WebDriverException : Raised either when it cannot find the
executable, when it does not have permissions for the
executable, or when it cannot connect to the service.
- Possibly other Exceptions in rare circumstances (OSError, etc).
"""
env = self.env or os.environ
try:
self.process = subprocess.Popen([
self.path,
"--port=%d" % self.port] +
self.service_args, env=env, stdout=PIPE, stderr=PIPE)
except OSError as err:
docs_msg = "Please see " \
"https://sites.google.com/a/chromium.org/chromedriver/home"
if err.errno == errno.ENOENT:
raise WebDriverException(
"'%s' executable needs to be in PATH. %s" % (
os.path.basename(self.path), docs_msg)
)
elif err.errno == errno.EACCES:
raise WebDriverException(
"'%s' executable may have wrong permissions. %s" % (
os.path.basename(self.path), docs_msg)
)
else:
raise
count = 0
while not utils.is_connectable(self.port):
count += 1
time.sleep(1)
if count == 30:
raise WebDriverException("Can not connect to the '" +
os.path.basename(self.path) + "'")
@property
def service_url(self):
"""
Gets the url of the ChromeDriver Service
"""
return "http://localhost:%d" % self.port
def stop(self):
"""
Tells the ChromeDriver to stop and cleans up the process
"""
#If its dead dont worry
if self.process is None:
return
#Tell the Server to die!
try:
from urllib import request as url_request
except ImportError:
import urllib2 as url_request
url_request.urlopen("http://127.0.0.1:%d/shutdown" % self.port)
count = 0
while utils.is_connectable(self.port):
if count == 30:
break
count += 1
time.sleep(1)
#Tell the Server to properly die in case
try:
if self.process:
self.process.stdout.close()
self.process.stderr.close()
self.process.kill()
self.process.wait()
except OSError:
# kill may not be available under windows environment
pass | if self.port == 0:
self.port = utils.free_port() | random_line_split |
service.py | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import errno
import subprocess
from subprocess import PIPE
import time
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common import utils
class Service(object):
"""
Object that manages the starting and stopping of the ChromeDriver
"""
def __init__(self, executable_path, port=0, service_args=None,
log_path=None, env=None):
"""
Creates a new instance of the Service
:Args:
- executable_path : Path to the ChromeDriver
- port : Port the service is running on
- service_args : List of args to pass to the chromedriver service
- log_path : Path for the chromedriver service to log to"""
self.port = port
self.path = executable_path
self.service_args = service_args or []
if log_path:
|
if self.port == 0:
self.port = utils.free_port()
self.env = env
def start(self):
"""
Starts the ChromeDriver Service.
:Exceptions:
- WebDriverException : Raised either when it cannot find the
executable, when it does not have permissions for the
executable, or when it cannot connect to the service.
- Possibly other Exceptions in rare circumstances (OSError, etc).
"""
env = self.env or os.environ
try:
self.process = subprocess.Popen([
self.path,
"--port=%d" % self.port] +
self.service_args, env=env, stdout=PIPE, stderr=PIPE)
except OSError as err:
docs_msg = "Please see " \
"https://sites.google.com/a/chromium.org/chromedriver/home"
if err.errno == errno.ENOENT:
raise WebDriverException(
"'%s' executable needs to be in PATH. %s" % (
os.path.basename(self.path), docs_msg)
)
elif err.errno == errno.EACCES:
raise WebDriverException(
"'%s' executable may have wrong permissions. %s" % (
os.path.basename(self.path), docs_msg)
)
else:
raise
count = 0
while not utils.is_connectable(self.port):
count += 1
time.sleep(1)
if count == 30:
raise WebDriverException("Can not connect to the '" +
os.path.basename(self.path) + "'")
@property
def service_url(self):
"""
Gets the url of the ChromeDriver Service
"""
return "http://localhost:%d" % self.port
def stop(self):
"""
Tells the ChromeDriver to stop and cleans up the process
"""
#If its dead dont worry
if self.process is None:
return
#Tell the Server to die!
try:
from urllib import request as url_request
except ImportError:
import urllib2 as url_request
url_request.urlopen("http://127.0.0.1:%d/shutdown" % self.port)
count = 0
while utils.is_connectable(self.port):
if count == 30:
break
count += 1
time.sleep(1)
#Tell the Server to properly die in case
try:
if self.process:
self.process.stdout.close()
self.process.stderr.close()
self.process.kill()
self.process.wait()
except OSError:
# kill may not be available under windows environment
pass
| self.service_args.append('--log-path=%s' % log_path) | conditional_block |
service.py | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import errno
import subprocess
from subprocess import PIPE
import time
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common import utils
class Service(object):
"""
Object that manages the starting and stopping of the ChromeDriver
"""
def __init__(self, executable_path, port=0, service_args=None,
log_path=None, env=None):
|
def start(self):
"""
Starts the ChromeDriver Service.
:Exceptions:
- WebDriverException : Raised either when it cannot find the
executable, when it does not have permissions for the
executable, or when it cannot connect to the service.
- Possibly other Exceptions in rare circumstances (OSError, etc).
"""
env = self.env or os.environ
try:
self.process = subprocess.Popen([
self.path,
"--port=%d" % self.port] +
self.service_args, env=env, stdout=PIPE, stderr=PIPE)
except OSError as err:
docs_msg = "Please see " \
"https://sites.google.com/a/chromium.org/chromedriver/home"
if err.errno == errno.ENOENT:
raise WebDriverException(
"'%s' executable needs to be in PATH. %s" % (
os.path.basename(self.path), docs_msg)
)
elif err.errno == errno.EACCES:
raise WebDriverException(
"'%s' executable may have wrong permissions. %s" % (
os.path.basename(self.path), docs_msg)
)
else:
raise
count = 0
while not utils.is_connectable(self.port):
count += 1
time.sleep(1)
if count == 30:
raise WebDriverException("Can not connect to the '" +
os.path.basename(self.path) + "'")
@property
def service_url(self):
"""
Gets the url of the ChromeDriver Service
"""
return "http://localhost:%d" % self.port
def stop(self):
"""
Tells the ChromeDriver to stop and cleans up the process
"""
#If its dead dont worry
if self.process is None:
return
#Tell the Server to die!
try:
from urllib import request as url_request
except ImportError:
import urllib2 as url_request
url_request.urlopen("http://127.0.0.1:%d/shutdown" % self.port)
count = 0
while utils.is_connectable(self.port):
if count == 30:
break
count += 1
time.sleep(1)
#Tell the Server to properly die in case
try:
if self.process:
self.process.stdout.close()
self.process.stderr.close()
self.process.kill()
self.process.wait()
except OSError:
# kill may not be available under windows environment
pass
| """
Creates a new instance of the Service
:Args:
- executable_path : Path to the ChromeDriver
- port : Port the service is running on
- service_args : List of args to pass to the chromedriver service
- log_path : Path for the chromedriver service to log to"""
self.port = port
self.path = executable_path
self.service_args = service_args or []
if log_path:
self.service_args.append('--log-path=%s' % log_path)
if self.port == 0:
self.port = utils.free_port()
self.env = env | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.