file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
device_tracker.py
"""Device tracker support for OPNSense routers.""" from homeassistant.components.device_tracker import DeviceScanner from . import CONF_TRACKER_INTERFACE, OPNSENSE_DATA async def async_get_scanner(hass, config, discovery_info=None): """Configure the OPNSense device_tracker.""" interface_client = hass.data[OPNSENSE_DATA]["interfaces"] scanner = OPNSenseDeviceScanner( interface_client, hass.data[OPNSENSE_DATA][CONF_TRACKER_INTERFACE] ) return scanner class
(DeviceScanner): """This class queries a router running OPNsense.""" def __init__(self, client, interfaces): """Initialize the scanner.""" self.last_results = {} self.client = client self.interfaces = interfaces def _get_mac_addrs(self, devices): """Create dict with mac address keys from list of devices.""" out_devices = {} for device in devices: if not self.interfaces: out_devices[device["mac"]] = device elif device["intf_description"] in self.interfaces: out_devices[device["mac"]] = device return out_devices def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self.update_info() return list(self.last_results) def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if device not in self.last_results: return None hostname = self.last_results[device].get("hostname") or None return hostname def update_info(self): """Ensure the information from the OPNSense router is up to date. Return boolean if scanning successful. """ devices = self.client.get_arp() self.last_results = self._get_mac_addrs(devices) def get_extra_attributes(self, device): """Return the extra attrs of the given device.""" if device not in self.last_results: return None if not (mfg := self.last_results[device].get("manufacturer")): return {} return {"manufacturer": mfg}
OPNSenseDeviceScanner
identifier_name
device_tracker.py
"""Device tracker support for OPNSense routers.""" from homeassistant.components.device_tracker import DeviceScanner from . import CONF_TRACKER_INTERFACE, OPNSENSE_DATA async def async_get_scanner(hass, config, discovery_info=None): """Configure the OPNSense device_tracker.""" interface_client = hass.data[OPNSENSE_DATA]["interfaces"] scanner = OPNSenseDeviceScanner( interface_client, hass.data[OPNSENSE_DATA][CONF_TRACKER_INTERFACE] ) return scanner class OPNSenseDeviceScanner(DeviceScanner): """This class queries a router running OPNsense.""" def __init__(self, client, interfaces): """Initialize the scanner.""" self.last_results = {} self.client = client self.interfaces = interfaces def _get_mac_addrs(self, devices): """Create dict with mac address keys from list of devices.""" out_devices = {} for device in devices: if not self.interfaces: out_devices[device["mac"]] = device elif device["intf_description"] in self.interfaces: out_devices[device["mac"]] = device
def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self.update_info() return list(self.last_results) def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if device not in self.last_results: return None hostname = self.last_results[device].get("hostname") or None return hostname def update_info(self): """Ensure the information from the OPNSense router is up to date. Return boolean if scanning successful. """ devices = self.client.get_arp() self.last_results = self._get_mac_addrs(devices) def get_extra_attributes(self, device): """Return the extra attrs of the given device.""" if device not in self.last_results: return None if not (mfg := self.last_results[device].get("manufacturer")): return {} return {"manufacturer": mfg}
return out_devices
random_line_split
devops_borat.py
from random import choice from feedparser import parse from errbot import botcmd, BotPlugin class DevOpsBorat(BotPlugin): """ Quotes from various dev humour related twitter accounts """ @botcmd def borat(self, mess, args): """ Random quotes from the DEVOPS_BORAT twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=DEVOPS_BORAT') items = myfeed['entries'] return choice(items).description @botcmd def jesus(self, mess, args): """ Random quotes from the devops_jesus twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=devops_jesus') items = myfeed['entries']
""" Random quotes from the UXYoda twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=UXYoda') items = myfeed['entries'] return choice(items).description
return choice(items).description @botcmd def yoda(self, mess, args):
random_line_split
devops_borat.py
from random import choice from feedparser import parse from errbot import botcmd, BotPlugin class DevOpsBorat(BotPlugin): """ Quotes from various dev humour related twitter accounts """ @botcmd def borat(self, mess, args): """ Random quotes from the DEVOPS_BORAT twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=DEVOPS_BORAT') items = myfeed['entries'] return choice(items).description @botcmd def jesus(self, mess, args): """ Random quotes from the devops_jesus twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=devops_jesus') items = myfeed['entries'] return choice(items).description @botcmd def
(self, mess, args): """ Random quotes from the UXYoda twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=UXYoda') items = myfeed['entries'] return choice(items).description
yoda
identifier_name
devops_borat.py
from random import choice from feedparser import parse from errbot import botcmd, BotPlugin class DevOpsBorat(BotPlugin): """ Quotes from various dev humour related twitter accounts """ @botcmd def borat(self, mess, args):
@botcmd def jesus(self, mess, args): """ Random quotes from the devops_jesus twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=devops_jesus') items = myfeed['entries'] return choice(items).description @botcmd def yoda(self, mess, args): """ Random quotes from the UXYoda twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=UXYoda') items = myfeed['entries'] return choice(items).description
""" Random quotes from the DEVOPS_BORAT twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=DEVOPS_BORAT') items = myfeed['entries'] return choice(items).description
identifier_body
test_plugins.py
# (c) 2012-2014, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.compat.tests import BUILTINS, unittest from ansible.compat.tests.mock import mock_open, patch, MagicMock from ansible.plugins.loader import MODULE_CACHE, PATH_CACHE, PLUGIN_PATH_CACHE, PluginLoader class TestErrors(unittest.TestCase): def setUp(self): pass def tearDown(self): pass @patch.object(PluginLoader, '_get_paths') def test_print_paths(self, mock_method): mock_method.return_value = ['/path/one', '/path/two', '/path/three'] pl = PluginLoader('foo', 'foo', '', 'test_plugins') paths = pl.print_paths() expected_paths = os.pathsep.join(['/path/one', '/path/two', '/path/three']) self.assertEqual(paths, expected_paths) def test_plugins__get_package_paths_no_package(self): pl = PluginLoader('test', '', 'test', 'test_plugin') self.assertEqual(pl._get_package_paths(), []) def test_plugins__get_package_paths_with_package(self): # the _get_package_paths() call uses __import__ to load a # python library, and then uses the __file__ attribute of # the result for that to get the library path, so we mock # that here and patch the builtin to use our mocked result foo = MagicMock() bar = MagicMock() bam = MagicMock() bam.__file__ = '/path/to/my/foo/bar/bam/__init__.py' bar.bam = bam foo.return_value.bar = bar pl = PluginLoader('test', 'foo.bar.bam', 'test', 'test_plugin') with patch('{0}.__import__'.format(BUILTINS), foo): self.assertEqual(pl._get_package_paths(), ['/path/to/my/foo/bar/bam']) def test_plugins__get_paths(self): pl = PluginLoader('test', '', 'test', 'test_plugin') pl._paths = ['/path/one', '/path/two'] self.assertEqual(pl._get_paths(), ['/path/one', '/path/two']) # NOT YET WORKING # def fake_glob(path): # if path == 'test/*': # return ['test/foo', 'test/bar', 'test/bam'] # elif path == 'test/*/*' # m._paths = None # mock_glob = MagicMock() # mock_glob.return_value = [] # with patch('glob.glob', mock_glob): # pass def assertPluginLoaderConfigBecomes(self, arg, expected): pl = PluginLoader('test', '', arg, 'test_plugin') self.assertEqual(pl.config, expected) def test_plugin__init_config_list(self):
def test_plugin__init_config_str(self): self.assertPluginLoaderConfigBecomes('test', ['test']) def test_plugin__init_config_none(self): self.assertPluginLoaderConfigBecomes(None, [])
config = ['/one', '/two'] self.assertPluginLoaderConfigBecomes(config, config)
identifier_body
test_plugins.py
# (c) 2012-2014, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.compat.tests import BUILTINS, unittest from ansible.compat.tests.mock import mock_open, patch, MagicMock from ansible.plugins.loader import MODULE_CACHE, PATH_CACHE, PLUGIN_PATH_CACHE, PluginLoader class TestErrors(unittest.TestCase): def setUp(self): pass def tearDown(self): pass @patch.object(PluginLoader, '_get_paths') def test_print_paths(self, mock_method): mock_method.return_value = ['/path/one', '/path/two', '/path/three'] pl = PluginLoader('foo', 'foo', '', 'test_plugins') paths = pl.print_paths() expected_paths = os.pathsep.join(['/path/one', '/path/two', '/path/three']) self.assertEqual(paths, expected_paths) def test_plugins__get_package_paths_no_package(self): pl = PluginLoader('test', '', 'test', 'test_plugin') self.assertEqual(pl._get_package_paths(), []) def test_plugins__get_package_paths_with_package(self): # the _get_package_paths() call uses __import__ to load a # python library, and then uses the __file__ attribute of # the result for that to get the library path, so we mock # that here and patch the builtin to use our mocked result foo = MagicMock() bar = MagicMock() bam = MagicMock() bam.__file__ = '/path/to/my/foo/bar/bam/__init__.py' bar.bam = bam foo.return_value.bar = bar pl = PluginLoader('test', 'foo.bar.bam', 'test', 'test_plugin') with patch('{0}.__import__'.format(BUILTINS), foo): self.assertEqual(pl._get_package_paths(), ['/path/to/my/foo/bar/bam'])
pl = PluginLoader('test', '', 'test', 'test_plugin') pl._paths = ['/path/one', '/path/two'] self.assertEqual(pl._get_paths(), ['/path/one', '/path/two']) # NOT YET WORKING # def fake_glob(path): # if path == 'test/*': # return ['test/foo', 'test/bar', 'test/bam'] # elif path == 'test/*/*' # m._paths = None # mock_glob = MagicMock() # mock_glob.return_value = [] # with patch('glob.glob', mock_glob): # pass def assertPluginLoaderConfigBecomes(self, arg, expected): pl = PluginLoader('test', '', arg, 'test_plugin') self.assertEqual(pl.config, expected) def test_plugin__init_config_list(self): config = ['/one', '/two'] self.assertPluginLoaderConfigBecomes(config, config) def test_plugin__init_config_str(self): self.assertPluginLoaderConfigBecomes('test', ['test']) def test_plugin__init_config_none(self): self.assertPluginLoaderConfigBecomes(None, [])
def test_plugins__get_paths(self):
random_line_split
test_plugins.py
# (c) 2012-2014, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.compat.tests import BUILTINS, unittest from ansible.compat.tests.mock import mock_open, patch, MagicMock from ansible.plugins.loader import MODULE_CACHE, PATH_CACHE, PLUGIN_PATH_CACHE, PluginLoader class TestErrors(unittest.TestCase): def setUp(self): pass def tearDown(self): pass @patch.object(PluginLoader, '_get_paths') def test_print_paths(self, mock_method): mock_method.return_value = ['/path/one', '/path/two', '/path/three'] pl = PluginLoader('foo', 'foo', '', 'test_plugins') paths = pl.print_paths() expected_paths = os.pathsep.join(['/path/one', '/path/two', '/path/three']) self.assertEqual(paths, expected_paths) def test_plugins__get_package_paths_no_package(self): pl = PluginLoader('test', '', 'test', 'test_plugin') self.assertEqual(pl._get_package_paths(), []) def test_plugins__get_package_paths_with_package(self): # the _get_package_paths() call uses __import__ to load a # python library, and then uses the __file__ attribute of # the result for that to get the library path, so we mock # that here and patch the builtin to use our mocked result foo = MagicMock() bar = MagicMock() bam = MagicMock() bam.__file__ = '/path/to/my/foo/bar/bam/__init__.py' bar.bam = bam foo.return_value.bar = bar pl = PluginLoader('test', 'foo.bar.bam', 'test', 'test_plugin') with patch('{0}.__import__'.format(BUILTINS), foo): self.assertEqual(pl._get_package_paths(), ['/path/to/my/foo/bar/bam']) def test_plugins__get_paths(self): pl = PluginLoader('test', '', 'test', 'test_plugin') pl._paths = ['/path/one', '/path/two'] self.assertEqual(pl._get_paths(), ['/path/one', '/path/two']) # NOT YET WORKING # def fake_glob(path): # if path == 'test/*': # return ['test/foo', 'test/bar', 'test/bam'] # elif path == 'test/*/*' # m._paths = None # mock_glob = MagicMock() # mock_glob.return_value = [] # with patch('glob.glob', mock_glob): # pass def assertPluginLoaderConfigBecomes(self, arg, expected): pl = PluginLoader('test', '', arg, 'test_plugin') self.assertEqual(pl.config, expected) def test_plugin__init_config_list(self): config = ['/one', '/two'] self.assertPluginLoaderConfigBecomes(config, config) def test_plugin__init_config_str(self): self.assertPluginLoaderConfigBecomes('test', ['test']) def
(self): self.assertPluginLoaderConfigBecomes(None, [])
test_plugin__init_config_none
identifier_name
session.js
var crypto = require('crypto'); var keystone = require('../'); var scmp = require('scmp'); var utils = require('keystone-utils'); /** * Creates a hash of str with Keystone's cookie secret. * Only hashes the first half of the string. */ function hash(str)
/** * Signs in a user using user obejct * * @param {Object} user - user object * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance */ function signinWithUser(user, req, res, onSuccess) { if (arguments.length < 4) { throw new Error('keystone.session.signinWithUser requires user, req and res objects, and an onSuccess callback.'); } if ('object' !== typeof user) { throw new Error('keystone.session.signinWithUser requires user to be an object.'); } if ('object' !== typeof req) { throw new Error('keystone.session.signinWithUser requires req to be an object.'); } if ('object' !== typeof res) { throw new Error('keystone.session.signinWithUser requires res to be an object.'); } if ('function' !== typeof onSuccess) { throw new Error('keystone.session.signinWithUser requires onSuccess to be a function.'); } req.session.regenerate(function() { req.user = user; req.session.userId = user.id; // if the user has a password set, store a persistence cookie to resume sessions if (keystone.get('cookie signin') && user.password) { var userToken = user.id + ':' + hash(user.password); res.cookie('keystone.uid', userToken, { signed: true, httpOnly: true }); } onSuccess(user); }); } exports.signinWithUser = signinWithUser; var postHookedSigninWithUser = function(user, req, res, onSuccess, onFail) { keystone.callHook(user, 'post:signin', function(err) { if (err) { return onFail(err); } exports.signinWithUser(user, req, res, onSuccess, onFail); }); }; /** * Signs in a user user matching the lookup filters * * @param {Object} lookup - must contain email and password * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance * @param {function()} onFail callback */ var doSignin = function(lookup, req, res, onSuccess, onFail) { if (!lookup) { return onFail(new Error('session.signin requires a User ID or Object as the first argument')); } var User = keystone.list(keystone.get('user model')); if ('string' === typeof lookup.email && 'string' === typeof lookup.password) { // create regex for email lookup with special characters escaped var emailRegExp = new RegExp('^' + utils.escapeRegExp(lookup.email) + '$', 'i'); // match email address and password User.model.findOne({ email: emailRegExp }).exec(function(err, user) { if (user) { user._.password.compare(lookup.password, function(err, isMatch) { if (!err && isMatch) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err || new Error('Incorrect email or password')); } }); } else { onFail(err); } }); } else { lookup = '' + lookup; // match the userId, with optional password check var userId = (lookup.indexOf(':') > 0) ? lookup.substr(0, lookup.indexOf(':')) : lookup; var passwordCheck = (lookup.indexOf(':') > 0) ? lookup.substr(lookup.indexOf(':') + 1) : false; User.model.findById(userId).exec(function(err, user) { if (user && (!passwordCheck || scmp(passwordCheck, hash(user.password)))) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err || new Error('Incorrect user or password')); } }); } }; exports.signin = function(lookup, req, res, onSuccess, onFail) { keystone.callHook({}, 'pre:signin', function(err) { if (err) { return onFail(err); } doSignin(lookup, req, res, onSuccess, onFail); }); }; /** * Signs the current user out and resets the session * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.signout = function(req, res, next) { keystone.callHook(req.user, 'pre:signout', function(err) { if (err) { console.log("An error occurred in signout 'pre' middleware", err); } res.clearCookie('keystone.uid'); req.user = null; req.session.regenerate(function(err) { if (err) { return next(err); } keystone.callHook({}, 'post:signout', function(err) { if (err) { console.log("An error occurred in signout 'post' middleware", err); } next(); }); }); }); }; /** * Middleware to ensure session persistence across server restarts * * Looks for a userId cookie, and if present, and there is no user signed in, * automatically signs the user in. * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.persist = function(req, res, next) { var User = keystone.list(keystone.get('user model')); if (!req.session) { console.error('\nKeystoneJS Runtime Error:\n\napp must have session middleware installed. Try adding "express-session" to your express instance.\n'); process.exit(1); } if (keystone.get('cookie signin') && !req.session.userId && req.signedCookies['keystone.uid'] && req.signedCookies['keystone.uid'].indexOf(':') > 0) { exports.signin(req.signedCookies['keystone.uid'], req, res, function() { next(); }, function(err) { next(err); }); } else if (req.session.userId) { User.model.findById(req.session.userId).exec(function(err, user) { if (err) return next(err); req.user = user; next(); }); } else { next(); } }; /** * Middleware to enable access to Keystone * * Bounces the user to the signin screen if they are not signed in or do not have permission. * * req.user is the user returned by the database. It's type is Keystone.List. * * req.user.canAccessKeystone denotes whether the user has access to the admin panel. * If you're having issues double check your user model. Setting `canAccessKeystone` to true in * the database will not be reflected here if it is virtual. * See http://mongoosejs.com/docs/guide.html#virtuals * * @param {Object} req - express request object * @param req.user - The user object Keystone.List * @param req.user.canAccessKeystone {Boolean|Function} * @param {Object} res - express response object * @param {function()} next callback */ exports.keystoneAuth = function(req, res, next) { if (!req.user || !req.user.canAccessKeystone) { var from = new RegExp('^\/keystone\/?$', 'i').test(req.url) ? '' : '?from=' + req.url; return res.redirect(keystone.get('signin url') + from); } next(); };
{ // force type str = '' + str; // get the first half str = str.substr(0, Math.round(str.length / 2)); // hash using sha256 return crypto .createHmac('sha256', keystone.get('cookie secret')) .update(str) .digest('base64') .replace(/\=+$/, ''); }
identifier_body
session.js
var crypto = require('crypto'); var keystone = require('../'); var scmp = require('scmp'); var utils = require('keystone-utils'); /** * Creates a hash of str with Keystone's cookie secret. * Only hashes the first half of the string. */ function
(str) { // force type str = '' + str; // get the first half str = str.substr(0, Math.round(str.length / 2)); // hash using sha256 return crypto .createHmac('sha256', keystone.get('cookie secret')) .update(str) .digest('base64') .replace(/\=+$/, ''); } /** * Signs in a user using user obejct * * @param {Object} user - user object * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance */ function signinWithUser(user, req, res, onSuccess) { if (arguments.length < 4) { throw new Error('keystone.session.signinWithUser requires user, req and res objects, and an onSuccess callback.'); } if ('object' !== typeof user) { throw new Error('keystone.session.signinWithUser requires user to be an object.'); } if ('object' !== typeof req) { throw new Error('keystone.session.signinWithUser requires req to be an object.'); } if ('object' !== typeof res) { throw new Error('keystone.session.signinWithUser requires res to be an object.'); } if ('function' !== typeof onSuccess) { throw new Error('keystone.session.signinWithUser requires onSuccess to be a function.'); } req.session.regenerate(function() { req.user = user; req.session.userId = user.id; // if the user has a password set, store a persistence cookie to resume sessions if (keystone.get('cookie signin') && user.password) { var userToken = user.id + ':' + hash(user.password); res.cookie('keystone.uid', userToken, { signed: true, httpOnly: true }); } onSuccess(user); }); } exports.signinWithUser = signinWithUser; var postHookedSigninWithUser = function(user, req, res, onSuccess, onFail) { keystone.callHook(user, 'post:signin', function(err) { if (err) { return onFail(err); } exports.signinWithUser(user, req, res, onSuccess, onFail); }); }; /** * Signs in a user user matching the lookup filters * * @param {Object} lookup - must contain email and password * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance * @param {function()} onFail callback */ var doSignin = function(lookup, req, res, onSuccess, onFail) { if (!lookup) { return onFail(new Error('session.signin requires a User ID or Object as the first argument')); } var User = keystone.list(keystone.get('user model')); if ('string' === typeof lookup.email && 'string' === typeof lookup.password) { // create regex for email lookup with special characters escaped var emailRegExp = new RegExp('^' + utils.escapeRegExp(lookup.email) + '$', 'i'); // match email address and password User.model.findOne({ email: emailRegExp }).exec(function(err, user) { if (user) { user._.password.compare(lookup.password, function(err, isMatch) { if (!err && isMatch) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err || new Error('Incorrect email or password')); } }); } else { onFail(err); } }); } else { lookup = '' + lookup; // match the userId, with optional password check var userId = (lookup.indexOf(':') > 0) ? lookup.substr(0, lookup.indexOf(':')) : lookup; var passwordCheck = (lookup.indexOf(':') > 0) ? lookup.substr(lookup.indexOf(':') + 1) : false; User.model.findById(userId).exec(function(err, user) { if (user && (!passwordCheck || scmp(passwordCheck, hash(user.password)))) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err || new Error('Incorrect user or password')); } }); } }; exports.signin = function(lookup, req, res, onSuccess, onFail) { keystone.callHook({}, 'pre:signin', function(err) { if (err) { return onFail(err); } doSignin(lookup, req, res, onSuccess, onFail); }); }; /** * Signs the current user out and resets the session * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.signout = function(req, res, next) { keystone.callHook(req.user, 'pre:signout', function(err) { if (err) { console.log("An error occurred in signout 'pre' middleware", err); } res.clearCookie('keystone.uid'); req.user = null; req.session.regenerate(function(err) { if (err) { return next(err); } keystone.callHook({}, 'post:signout', function(err) { if (err) { console.log("An error occurred in signout 'post' middleware", err); } next(); }); }); }); }; /** * Middleware to ensure session persistence across server restarts * * Looks for a userId cookie, and if present, and there is no user signed in, * automatically signs the user in. * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.persist = function(req, res, next) { var User = keystone.list(keystone.get('user model')); if (!req.session) { console.error('\nKeystoneJS Runtime Error:\n\napp must have session middleware installed. Try adding "express-session" to your express instance.\n'); process.exit(1); } if (keystone.get('cookie signin') && !req.session.userId && req.signedCookies['keystone.uid'] && req.signedCookies['keystone.uid'].indexOf(':') > 0) { exports.signin(req.signedCookies['keystone.uid'], req, res, function() { next(); }, function(err) { next(err); }); } else if (req.session.userId) { User.model.findById(req.session.userId).exec(function(err, user) { if (err) return next(err); req.user = user; next(); }); } else { next(); } }; /** * Middleware to enable access to Keystone * * Bounces the user to the signin screen if they are not signed in or do not have permission. * * req.user is the user returned by the database. It's type is Keystone.List. * * req.user.canAccessKeystone denotes whether the user has access to the admin panel. * If you're having issues double check your user model. Setting `canAccessKeystone` to true in * the database will not be reflected here if it is virtual. * See http://mongoosejs.com/docs/guide.html#virtuals * * @param {Object} req - express request object * @param req.user - The user object Keystone.List * @param req.user.canAccessKeystone {Boolean|Function} * @param {Object} res - express response object * @param {function()} next callback */ exports.keystoneAuth = function(req, res, next) { if (!req.user || !req.user.canAccessKeystone) { var from = new RegExp('^\/keystone\/?$', 'i').test(req.url) ? '' : '?from=' + req.url; return res.redirect(keystone.get('signin url') + from); } next(); };
hash
identifier_name
session.js
var crypto = require('crypto'); var keystone = require('../'); var scmp = require('scmp'); var utils = require('keystone-utils'); /** * Creates a hash of str with Keystone's cookie secret. * Only hashes the first half of the string. */ function hash(str) { // force type str = '' + str; // get the first half str = str.substr(0, Math.round(str.length / 2)); // hash using sha256 return crypto .createHmac('sha256', keystone.get('cookie secret')) .update(str) .digest('base64') .replace(/\=+$/, ''); } /** * Signs in a user using user obejct * * @param {Object} user - user object * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance */ function signinWithUser(user, req, res, onSuccess) { if (arguments.length < 4) { throw new Error('keystone.session.signinWithUser requires user, req and res objects, and an onSuccess callback.'); } if ('object' !== typeof user) { throw new Error('keystone.session.signinWithUser requires user to be an object.'); } if ('object' !== typeof req) { throw new Error('keystone.session.signinWithUser requires req to be an object.'); } if ('object' !== typeof res) { throw new Error('keystone.session.signinWithUser requires res to be an object.'); } if ('function' !== typeof onSuccess) { throw new Error('keystone.session.signinWithUser requires onSuccess to be a function.'); } req.session.regenerate(function() { req.user = user; req.session.userId = user.id; // if the user has a password set, store a persistence cookie to resume sessions if (keystone.get('cookie signin') && user.password) { var userToken = user.id + ':' + hash(user.password); res.cookie('keystone.uid', userToken, { signed: true, httpOnly: true }); } onSuccess(user); }); } exports.signinWithUser = signinWithUser; var postHookedSigninWithUser = function(user, req, res, onSuccess, onFail) { keystone.callHook(user, 'post:signin', function(err) { if (err) { return onFail(err); } exports.signinWithUser(user, req, res, onSuccess, onFail); }); }; /** * Signs in a user user matching the lookup filters * * @param {Object} lookup - must contain email and password * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance * @param {function()} onFail callback */ var doSignin = function(lookup, req, res, onSuccess, onFail) { if (!lookup) { return onFail(new Error('session.signin requires a User ID or Object as the first argument')); } var User = keystone.list(keystone.get('user model')); if ('string' === typeof lookup.email && 'string' === typeof lookup.password) { // create regex for email lookup with special characters escaped var emailRegExp = new RegExp('^' + utils.escapeRegExp(lookup.email) + '$', 'i'); // match email address and password User.model.findOne({ email: emailRegExp }).exec(function(err, user) { if (user) { user._.password.compare(lookup.password, function(err, isMatch) { if (!err && isMatch) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err || new Error('Incorrect email or password')); } }); } else { onFail(err); } }); } else { lookup = '' + lookup; // match the userId, with optional password check var userId = (lookup.indexOf(':') > 0) ? lookup.substr(0, lookup.indexOf(':')) : lookup; var passwordCheck = (lookup.indexOf(':') > 0) ? lookup.substr(lookup.indexOf(':') + 1) : false; User.model.findById(userId).exec(function(err, user) { if (user && (!passwordCheck || scmp(passwordCheck, hash(user.password)))) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err || new Error('Incorrect user or password')); } }); } }; exports.signin = function(lookup, req, res, onSuccess, onFail) { keystone.callHook({}, 'pre:signin', function(err) { if (err)
doSignin(lookup, req, res, onSuccess, onFail); }); }; /** * Signs the current user out and resets the session * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.signout = function(req, res, next) { keystone.callHook(req.user, 'pre:signout', function(err) { if (err) { console.log("An error occurred in signout 'pre' middleware", err); } res.clearCookie('keystone.uid'); req.user = null; req.session.regenerate(function(err) { if (err) { return next(err); } keystone.callHook({}, 'post:signout', function(err) { if (err) { console.log("An error occurred in signout 'post' middleware", err); } next(); }); }); }); }; /** * Middleware to ensure session persistence across server restarts * * Looks for a userId cookie, and if present, and there is no user signed in, * automatically signs the user in. * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.persist = function(req, res, next) { var User = keystone.list(keystone.get('user model')); if (!req.session) { console.error('\nKeystoneJS Runtime Error:\n\napp must have session middleware installed. Try adding "express-session" to your express instance.\n'); process.exit(1); } if (keystone.get('cookie signin') && !req.session.userId && req.signedCookies['keystone.uid'] && req.signedCookies['keystone.uid'].indexOf(':') > 0) { exports.signin(req.signedCookies['keystone.uid'], req, res, function() { next(); }, function(err) { next(err); }); } else if (req.session.userId) { User.model.findById(req.session.userId).exec(function(err, user) { if (err) return next(err); req.user = user; next(); }); } else { next(); } }; /** * Middleware to enable access to Keystone * * Bounces the user to the signin screen if they are not signed in or do not have permission. * * req.user is the user returned by the database. It's type is Keystone.List. * * req.user.canAccessKeystone denotes whether the user has access to the admin panel. * If you're having issues double check your user model. Setting `canAccessKeystone` to true in * the database will not be reflected here if it is virtual. * See http://mongoosejs.com/docs/guide.html#virtuals * * @param {Object} req - express request object * @param req.user - The user object Keystone.List * @param req.user.canAccessKeystone {Boolean|Function} * @param {Object} res - express response object * @param {function()} next callback */ exports.keystoneAuth = function(req, res, next) { if (!req.user || !req.user.canAccessKeystone) { var from = new RegExp('^\/keystone\/?$', 'i').test(req.url) ? '' : '?from=' + req.url; return res.redirect(keystone.get('signin url') + from); } next(); };
{ return onFail(err); }
conditional_block
session.js
var crypto = require('crypto'); var keystone = require('../'); var scmp = require('scmp'); var utils = require('keystone-utils'); /** * Creates a hash of str with Keystone's cookie secret. * Only hashes the first half of the string. */ function hash(str) { // force type str = '' + str; // get the first half str = str.substr(0, Math.round(str.length / 2)); // hash using sha256 return crypto .createHmac('sha256', keystone.get('cookie secret')) .update(str) .digest('base64') .replace(/\=+$/, ''); } /** * Signs in a user using user obejct * * @param {Object} user - user object * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance */ function signinWithUser(user, req, res, onSuccess) { if (arguments.length < 4) { throw new Error('keystone.session.signinWithUser requires user, req and res objects, and an onSuccess callback.'); } if ('object' !== typeof user) { throw new Error('keystone.session.signinWithUser requires user to be an object.'); } if ('object' !== typeof req) { throw new Error('keystone.session.signinWithUser requires req to be an object.'); } if ('object' !== typeof res) { throw new Error('keystone.session.signinWithUser requires res to be an object.'); } if ('function' !== typeof onSuccess) { throw new Error('keystone.session.signinWithUser requires onSuccess to be a function.'); } req.session.regenerate(function() { req.user = user; req.session.userId = user.id; // if the user has a password set, store a persistence cookie to resume sessions if (keystone.get('cookie signin') && user.password) {
onSuccess(user); }); } exports.signinWithUser = signinWithUser; var postHookedSigninWithUser = function(user, req, res, onSuccess, onFail) { keystone.callHook(user, 'post:signin', function(err) { if (err) { return onFail(err); } exports.signinWithUser(user, req, res, onSuccess, onFail); }); }; /** * Signs in a user user matching the lookup filters * * @param {Object} lookup - must contain email and password * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance * @param {function()} onFail callback */ var doSignin = function(lookup, req, res, onSuccess, onFail) { if (!lookup) { return onFail(new Error('session.signin requires a User ID or Object as the first argument')); } var User = keystone.list(keystone.get('user model')); if ('string' === typeof lookup.email && 'string' === typeof lookup.password) { // create regex for email lookup with special characters escaped var emailRegExp = new RegExp('^' + utils.escapeRegExp(lookup.email) + '$', 'i'); // match email address and password User.model.findOne({ email: emailRegExp }).exec(function(err, user) { if (user) { user._.password.compare(lookup.password, function(err, isMatch) { if (!err && isMatch) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err || new Error('Incorrect email or password')); } }); } else { onFail(err); } }); } else { lookup = '' + lookup; // match the userId, with optional password check var userId = (lookup.indexOf(':') > 0) ? lookup.substr(0, lookup.indexOf(':')) : lookup; var passwordCheck = (lookup.indexOf(':') > 0) ? lookup.substr(lookup.indexOf(':') + 1) : false; User.model.findById(userId).exec(function(err, user) { if (user && (!passwordCheck || scmp(passwordCheck, hash(user.password)))) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err || new Error('Incorrect user or password')); } }); } }; exports.signin = function(lookup, req, res, onSuccess, onFail) { keystone.callHook({}, 'pre:signin', function(err) { if (err) { return onFail(err); } doSignin(lookup, req, res, onSuccess, onFail); }); }; /** * Signs the current user out and resets the session * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.signout = function(req, res, next) { keystone.callHook(req.user, 'pre:signout', function(err) { if (err) { console.log("An error occurred in signout 'pre' middleware", err); } res.clearCookie('keystone.uid'); req.user = null; req.session.regenerate(function(err) { if (err) { return next(err); } keystone.callHook({}, 'post:signout', function(err) { if (err) { console.log("An error occurred in signout 'post' middleware", err); } next(); }); }); }); }; /** * Middleware to ensure session persistence across server restarts * * Looks for a userId cookie, and if present, and there is no user signed in, * automatically signs the user in. * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.persist = function(req, res, next) { var User = keystone.list(keystone.get('user model')); if (!req.session) { console.error('\nKeystoneJS Runtime Error:\n\napp must have session middleware installed. Try adding "express-session" to your express instance.\n'); process.exit(1); } if (keystone.get('cookie signin') && !req.session.userId && req.signedCookies['keystone.uid'] && req.signedCookies['keystone.uid'].indexOf(':') > 0) { exports.signin(req.signedCookies['keystone.uid'], req, res, function() { next(); }, function(err) { next(err); }); } else if (req.session.userId) { User.model.findById(req.session.userId).exec(function(err, user) { if (err) return next(err); req.user = user; next(); }); } else { next(); } }; /** * Middleware to enable access to Keystone * * Bounces the user to the signin screen if they are not signed in or do not have permission. * * req.user is the user returned by the database. It's type is Keystone.List. * * req.user.canAccessKeystone denotes whether the user has access to the admin panel. * If you're having issues double check your user model. Setting `canAccessKeystone` to true in * the database will not be reflected here if it is virtual. * See http://mongoosejs.com/docs/guide.html#virtuals * * @param {Object} req - express request object * @param req.user - The user object Keystone.List * @param req.user.canAccessKeystone {Boolean|Function} * @param {Object} res - express response object * @param {function()} next callback */ exports.keystoneAuth = function(req, res, next) { if (!req.user || !req.user.canAccessKeystone) { var from = new RegExp('^\/keystone\/?$', 'i').test(req.url) ? '' : '?from=' + req.url; return res.redirect(keystone.get('signin url') + from); } next(); };
var userToken = user.id + ':' + hash(user.password); res.cookie('keystone.uid', userToken, { signed: true, httpOnly: true }); }
random_line_split
widget-picker-filter-view.js
define(function(require) { 'use strict'; var WidgetPickerFilterView; var _ = require('underscore'); var BaseView = require('oroui/js/app/views/base/view'); WidgetPickerFilterView = BaseView.extend({ template: require('tpl!oroui/templates/widget-picker/widget-picker-filter-view.html'), autoRender: true, events: { 'keyup [data-role="widget-picker-search"]': 'onSearch', 'change [data-role="widget-picker-search"]': 'onSearch', 'paste [data-role="widget-picker-search"]': 'onSearch', 'mouseup [data-role="widget-picker-search"]': 'onSearch' }, /** * @inheritDoc */ initialize: function(options) { this.onSearch = _.debounce(this.onSearch, 100); WidgetPickerFilterView.__super__.initialize.apply(this, arguments); },
*/ onSearch: function(e) { this.model.set('search', e.currentTarget.value); } }); return WidgetPickerFilterView; });
/** * * @param {Event} e
random_line_split
app.js
import {Deck, OrthographicView} from '@deck.gl/core'; import {ScatterplotLayer, PathLayer, SolidPolygonLayer} from '@deck.gl/layers'; import GL from '@luma.gl/constants'; import {Buffer} from '@luma.gl/core'; import data from './data'; /** DeckGL **/ const deck = new Deck({ container: 'container', views: new OrthographicView(), controller: true, initialViewState: { target: [6, 6, 0], zoom: 5 }, onWebGLInitialized }); function onWebGLInitialized(gl) { const buffer = new Buffer(gl, data); const positions = {buffer, type: GL.FLOAT, size: 3, offset: 4, stride: 16}; const colors = {buffer, type: GL.UNSIGNED_BYTE, size: 4, offset: 0, stride: 16}; const indices = new Uint16Array([0, 1, 2, 3, 4, 5, 4, 5, 6]); const layers = [ new SolidPolygonLayer({ id: 'polygons', data: { length: 2, startIndices: [0, 3], attributes: { indices, getPolygon: positions, getFillColor: colors } }, pickable: true, autoHighlight: true, _normalize: false, // this instructs SolidPolygonLayer to skip normalization and use the binary as is getWidth: 0.5 }), new PathLayer({ id: 'paths', data: { length: 2, startIndices: [0, 3], attributes: { // PathLayer expects padded positions (1 vertex to the left & 2 vertices to the right) // So it cannot share the same buffer with other layers without padding // TODO - handle in PathTesselator? getPath: {value: data, size: 3, offset: 4, stride: 16}, getColor: colors } }, pickable: true, autoHighlight: true, _pathType: 'open', // this instructs PathLayer to skip normalization and use the binary as is getWidth: 0.5 }), new ScatterplotLayer({ id: 'points', data: { length: 7, attributes: { getPosition: positions, getLineColor: colors } }, pickable: true, autoHighlight: true, stroked: true, filled: false, getRadius: 1, getLineWidth: 0.5 }) ];
deck.setProps({layers}); } /* global document */ document.body.style.margin = '0px';
random_line_split
app.js
import {Deck, OrthographicView} from '@deck.gl/core'; import {ScatterplotLayer, PathLayer, SolidPolygonLayer} from '@deck.gl/layers'; import GL from '@luma.gl/constants'; import {Buffer} from '@luma.gl/core'; import data from './data'; /** DeckGL **/ const deck = new Deck({ container: 'container', views: new OrthographicView(), controller: true, initialViewState: { target: [6, 6, 0], zoom: 5 }, onWebGLInitialized }); function onWebGLInitialized(gl)
/* global document */ document.body.style.margin = '0px';
{ const buffer = new Buffer(gl, data); const positions = {buffer, type: GL.FLOAT, size: 3, offset: 4, stride: 16}; const colors = {buffer, type: GL.UNSIGNED_BYTE, size: 4, offset: 0, stride: 16}; const indices = new Uint16Array([0, 1, 2, 3, 4, 5, 4, 5, 6]); const layers = [ new SolidPolygonLayer({ id: 'polygons', data: { length: 2, startIndices: [0, 3], attributes: { indices, getPolygon: positions, getFillColor: colors } }, pickable: true, autoHighlight: true, _normalize: false, // this instructs SolidPolygonLayer to skip normalization and use the binary as is getWidth: 0.5 }), new PathLayer({ id: 'paths', data: { length: 2, startIndices: [0, 3], attributes: { // PathLayer expects padded positions (1 vertex to the left & 2 vertices to the right) // So it cannot share the same buffer with other layers without padding // TODO - handle in PathTesselator? getPath: {value: data, size: 3, offset: 4, stride: 16}, getColor: colors } }, pickable: true, autoHighlight: true, _pathType: 'open', // this instructs PathLayer to skip normalization and use the binary as is getWidth: 0.5 }), new ScatterplotLayer({ id: 'points', data: { length: 7, attributes: { getPosition: positions, getLineColor: colors } }, pickable: true, autoHighlight: true, stroked: true, filled: false, getRadius: 1, getLineWidth: 0.5 }) ]; deck.setProps({layers}); }
identifier_body
app.js
import {Deck, OrthographicView} from '@deck.gl/core'; import {ScatterplotLayer, PathLayer, SolidPolygonLayer} from '@deck.gl/layers'; import GL from '@luma.gl/constants'; import {Buffer} from '@luma.gl/core'; import data from './data'; /** DeckGL **/ const deck = new Deck({ container: 'container', views: new OrthographicView(), controller: true, initialViewState: { target: [6, 6, 0], zoom: 5 }, onWebGLInitialized }); function
(gl) { const buffer = new Buffer(gl, data); const positions = {buffer, type: GL.FLOAT, size: 3, offset: 4, stride: 16}; const colors = {buffer, type: GL.UNSIGNED_BYTE, size: 4, offset: 0, stride: 16}; const indices = new Uint16Array([0, 1, 2, 3, 4, 5, 4, 5, 6]); const layers = [ new SolidPolygonLayer({ id: 'polygons', data: { length: 2, startIndices: [0, 3], attributes: { indices, getPolygon: positions, getFillColor: colors } }, pickable: true, autoHighlight: true, _normalize: false, // this instructs SolidPolygonLayer to skip normalization and use the binary as is getWidth: 0.5 }), new PathLayer({ id: 'paths', data: { length: 2, startIndices: [0, 3], attributes: { // PathLayer expects padded positions (1 vertex to the left & 2 vertices to the right) // So it cannot share the same buffer with other layers without padding // TODO - handle in PathTesselator? getPath: {value: data, size: 3, offset: 4, stride: 16}, getColor: colors } }, pickable: true, autoHighlight: true, _pathType: 'open', // this instructs PathLayer to skip normalization and use the binary as is getWidth: 0.5 }), new ScatterplotLayer({ id: 'points', data: { length: 7, attributes: { getPosition: positions, getLineColor: colors } }, pickable: true, autoHighlight: true, stroked: true, filled: false, getRadius: 1, getLineWidth: 0.5 }) ]; deck.setProps({layers}); } /* global document */ document.body.style.margin = '0px';
onWebGLInitialized
identifier_name
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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. use super::FractalAnimation; use fractal_lib::color; use fractal_lib::escapetime::EscapeTime; use fractal_lib::geometry; use num::complex::Complex64; use std::cmp; use wasm_bindgen::Clamped; use web_sys::{CanvasRenderingContext2d, ImageData}; pub struct EscapeTimeAnimation { /// The rendering context. ctx: CanvasRenderingContext2d, /// Which EscapeTime system is being animated. Boxed to encapsulate/avoid generics. etsystem: Box<dyn EscapeTime>, /// The current part of the fractal we're viewing. view_area: [geometry::Point; 2], }
ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation { let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } } fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); log::debug!("View area: {:?}", self.view_area); log::debug!("pixel 0,0 maps to {}", vat.map_pixel_to_point([0.0, 0.0])); log::debug!( "pixel {},{} maps to {}", screen_width as u32, screen_height as u32, vat.map_pixel_to_point([screen_width.into(), screen_height.into()]) ); log::debug!("build color range"); let colors = color::color_range_linear( color::BLACK_U8, color::WHITE_U8, cmp::min(self.etsystem.max_iterations(), 50) as usize, ); log::debug!("build image pixels"); let mut image_pixels = (0..screen_height) .map(|y| { (0..screen_width) .map(|x| { let c: Complex64 = vat.map_pixel_to_point([f64::from(x), f64::from(y)]).into(); let (attracted, time) = self.etsystem.test_point(c); if attracted { color::AEBLUE_U8.0.iter() } else { colors[cmp::min(time, 50 - 1) as usize].0.iter() } }) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array = Clamped(image_pixels.as_mut_slice()); // Create an ImageData from the array log::debug!("Create Image Data"); let image = ImageData::new_with_u8_clamped_array_and_sh( clamped_image_array, screen_width, screen_height, ) .unwrap(); log::debug!("Put Image Data"); self.ctx.put_image_data(&image, 0.0, 0.0).unwrap(); } } impl FractalAnimation for EscapeTimeAnimation { fn draw_one_frame(&mut self) -> bool { self.render(); false } fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); let pos_point = vat.map_pixel_to_point([x, y]); pos_point.into() } fn zoom(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); // compute the new view area in the fractal's coordinate system let tlp = vat.map_pixel_to_point([x1, y1]); let brp = vat.map_pixel_to_point([x2, y2]); // update self.view_area = [tlp, brp]; true } }
impl EscapeTimeAnimation { pub fn new(
random_line_split
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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. use super::FractalAnimation; use fractal_lib::color; use fractal_lib::escapetime::EscapeTime; use fractal_lib::geometry; use num::complex::Complex64; use std::cmp; use wasm_bindgen::Clamped; use web_sys::{CanvasRenderingContext2d, ImageData}; pub struct EscapeTimeAnimation { /// The rendering context. ctx: CanvasRenderingContext2d, /// Which EscapeTime system is being animated. Boxed to encapsulate/avoid generics. etsystem: Box<dyn EscapeTime>, /// The current part of the fractal we're viewing. view_area: [geometry::Point; 2], } impl EscapeTimeAnimation { pub fn new( ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation { let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } } fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); log::debug!("View area: {:?}", self.view_area); log::debug!("pixel 0,0 maps to {}", vat.map_pixel_to_point([0.0, 0.0])); log::debug!( "pixel {},{} maps to {}", screen_width as u32, screen_height as u32, vat.map_pixel_to_point([screen_width.into(), screen_height.into()]) ); log::debug!("build color range"); let colors = color::color_range_linear( color::BLACK_U8, color::WHITE_U8, cmp::min(self.etsystem.max_iterations(), 50) as usize, ); log::debug!("build image pixels"); let mut image_pixels = (0..screen_height) .map(|y| { (0..screen_width) .map(|x| { let c: Complex64 = vat.map_pixel_to_point([f64::from(x), f64::from(y)]).into(); let (attracted, time) = self.etsystem.test_point(c); if attracted { color::AEBLUE_U8.0.iter() } else
}) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array = Clamped(image_pixels.as_mut_slice()); // Create an ImageData from the array log::debug!("Create Image Data"); let image = ImageData::new_with_u8_clamped_array_and_sh( clamped_image_array, screen_width, screen_height, ) .unwrap(); log::debug!("Put Image Data"); self.ctx.put_image_data(&image, 0.0, 0.0).unwrap(); } } impl FractalAnimation for EscapeTimeAnimation { fn draw_one_frame(&mut self) -> bool { self.render(); false } fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); let pos_point = vat.map_pixel_to_point([x, y]); pos_point.into() } fn zoom(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); // compute the new view area in the fractal's coordinate system let tlp = vat.map_pixel_to_point([x1, y1]); let brp = vat.map_pixel_to_point([x2, y2]); // update self.view_area = [tlp, brp]; true } }
{ colors[cmp::min(time, 50 - 1) as usize].0.iter() }
conditional_block
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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. use super::FractalAnimation; use fractal_lib::color; use fractal_lib::escapetime::EscapeTime; use fractal_lib::geometry; use num::complex::Complex64; use std::cmp; use wasm_bindgen::Clamped; use web_sys::{CanvasRenderingContext2d, ImageData}; pub struct EscapeTimeAnimation { /// The rendering context. ctx: CanvasRenderingContext2d, /// Which EscapeTime system is being animated. Boxed to encapsulate/avoid generics. etsystem: Box<dyn EscapeTime>, /// The current part of the fractal we're viewing. view_area: [geometry::Point; 2], } impl EscapeTimeAnimation { pub fn new( ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation
fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); log::debug!("View area: {:?}", self.view_area); log::debug!("pixel 0,0 maps to {}", vat.map_pixel_to_point([0.0, 0.0])); log::debug!( "pixel {},{} maps to {}", screen_width as u32, screen_height as u32, vat.map_pixel_to_point([screen_width.into(), screen_height.into()]) ); log::debug!("build color range"); let colors = color::color_range_linear( color::BLACK_U8, color::WHITE_U8, cmp::min(self.etsystem.max_iterations(), 50) as usize, ); log::debug!("build image pixels"); let mut image_pixels = (0..screen_height) .map(|y| { (0..screen_width) .map(|x| { let c: Complex64 = vat.map_pixel_to_point([f64::from(x), f64::from(y)]).into(); let (attracted, time) = self.etsystem.test_point(c); if attracted { color::AEBLUE_U8.0.iter() } else { colors[cmp::min(time, 50 - 1) as usize].0.iter() } }) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array = Clamped(image_pixels.as_mut_slice()); // Create an ImageData from the array log::debug!("Create Image Data"); let image = ImageData::new_with_u8_clamped_array_and_sh( clamped_image_array, screen_width, screen_height, ) .unwrap(); log::debug!("Put Image Data"); self.ctx.put_image_data(&image, 0.0, 0.0).unwrap(); } } impl FractalAnimation for EscapeTimeAnimation { fn draw_one_frame(&mut self) -> bool { self.render(); false } fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); let pos_point = vat.map_pixel_to_point([x, y]); pos_point.into() } fn zoom(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); // compute the new view area in the fractal's coordinate system let tlp = vat.map_pixel_to_point([x1, y1]); let brp = vat.map_pixel_to_point([x2, y2]); // update self.view_area = [tlp, brp]; true } }
{ let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } }
identifier_body
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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. use super::FractalAnimation; use fractal_lib::color; use fractal_lib::escapetime::EscapeTime; use fractal_lib::geometry; use num::complex::Complex64; use std::cmp; use wasm_bindgen::Clamped; use web_sys::{CanvasRenderingContext2d, ImageData}; pub struct EscapeTimeAnimation { /// The rendering context. ctx: CanvasRenderingContext2d, /// Which EscapeTime system is being animated. Boxed to encapsulate/avoid generics. etsystem: Box<dyn EscapeTime>, /// The current part of the fractal we're viewing. view_area: [geometry::Point; 2], } impl EscapeTimeAnimation { pub fn new( ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation { let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } } fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); log::debug!("View area: {:?}", self.view_area); log::debug!("pixel 0,0 maps to {}", vat.map_pixel_to_point([0.0, 0.0])); log::debug!( "pixel {},{} maps to {}", screen_width as u32, screen_height as u32, vat.map_pixel_to_point([screen_width.into(), screen_height.into()]) ); log::debug!("build color range"); let colors = color::color_range_linear( color::BLACK_U8, color::WHITE_U8, cmp::min(self.etsystem.max_iterations(), 50) as usize, ); log::debug!("build image pixels"); let mut image_pixels = (0..screen_height) .map(|y| { (0..screen_width) .map(|x| { let c: Complex64 = vat.map_pixel_to_point([f64::from(x), f64::from(y)]).into(); let (attracted, time) = self.etsystem.test_point(c); if attracted { color::AEBLUE_U8.0.iter() } else { colors[cmp::min(time, 50 - 1) as usize].0.iter() } }) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array = Clamped(image_pixels.as_mut_slice()); // Create an ImageData from the array log::debug!("Create Image Data"); let image = ImageData::new_with_u8_clamped_array_and_sh( clamped_image_array, screen_width, screen_height, ) .unwrap(); log::debug!("Put Image Data"); self.ctx.put_image_data(&image, 0.0, 0.0).unwrap(); } } impl FractalAnimation for EscapeTimeAnimation { fn draw_one_frame(&mut self) -> bool { self.render(); false } fn pixel_to_coordinate(&self, x: f64, y: f64) -> [f64; 2] { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); let pos_point = vat.map_pixel_to_point([x, y]); pos_point.into() } fn
(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_area[1], ); // compute the new view area in the fractal's coordinate system let tlp = vat.map_pixel_to_point([x1, y1]); let brp = vat.map_pixel_to_point([x2, y2]); // update self.view_area = [tlp, brp]; true } }
zoom
identifier_name
columnUtils.d.ts
// Type definitions for ag-grid v15.0.0 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> import { ColumnGroupChild } from "../entities/columnGroupChild"; import { OriginalColumnGroupChild } from "../entities/originalColumnGroupChild"; import { OriginalColumnGroup } from "../entities/originalColumnGroup"; import { Column } from "../entities/column"; export declare class
{ private gridOptionsWrapper; calculateColInitialWidth(colDef: any): number; getOriginalPathForColumn(column: Column, originalBalancedTree: OriginalColumnGroupChild[]): OriginalColumnGroup[]; depthFirstOriginalTreeSearch(tree: OriginalColumnGroupChild[], callback: (treeNode: OriginalColumnGroupChild) => void): void; depthFirstAllColumnTreeSearch(tree: ColumnGroupChild[], callback: (treeNode: ColumnGroupChild) => void): void; depthFirstDisplayedColumnTreeSearch(tree: ColumnGroupChild[], callback: (treeNode: ColumnGroupChild) => void): void; }
ColumnUtils
identifier_name
columnUtils.d.ts
// Type definitions for ag-grid v15.0.0 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> import { ColumnGroupChild } from "../entities/columnGroupChild"; import { OriginalColumnGroupChild } from "../entities/originalColumnGroupChild"; import { OriginalColumnGroup } from "../entities/originalColumnGroup"; import { Column } from "../entities/column"; export declare class ColumnUtils { private gridOptionsWrapper; calculateColInitialWidth(colDef: any): number; getOriginalPathForColumn(column: Column, originalBalancedTree: OriginalColumnGroupChild[]): OriginalColumnGroup[]; depthFirstOriginalTreeSearch(tree: OriginalColumnGroupChild[], callback: (treeNode: OriginalColumnGroupChild) => void): void;
depthFirstAllColumnTreeSearch(tree: ColumnGroupChild[], callback: (treeNode: ColumnGroupChild) => void): void; depthFirstDisplayedColumnTreeSearch(tree: ColumnGroupChild[], callback: (treeNode: ColumnGroupChild) => void): void; }
random_line_split
guildMemberAdd.js
const Log = require("../util/log.js"); const common = require("../util/common.js"); const setting_global = require("../settings.json"); const setting_color = setting_global.commands.user.guilds.color; const setting_mute = setting_global.commands.admin.mute; const setting = setting_global.events.memberAdd; module.exports = (client, member) => { Log.memberAdd(member.user); if (setting.welcomeMessage.enabled) common.getChannel(client, setting.welcomeMessage.channel) .send(setting.welcomeMessage.template[ common.getRandom(0, setting.welcomeMessage.template.length)] .replace("{user}", member.user));
.find("name", role))); if (setting.autoRole.random_color) member.addRole(member.guild.roles .find("name", setting_color.colors[common.getRandom(0, setting_color.colors.length)].role)); if (client.muted && setting.auto_mute) { let time = client.muted[member.id]; if (time) member.addRole(member.guild.find("name", setting_mute.role)); } };
if (setting.autoRole.role) setting.autoRole.role.forEach((role) => member.addRole(member.guild.roles
random_line_split
subjects.server.routes.ts
'use strict'; /** * Module dependencies */ var subjectsPolicy = require('../policies/subjects.server.policy'), subjects = require('../controllers/subjects.server.controller'); module.exports = function(app) { // Subjects collection routes app.route('/api/subjects').all(subjectsPolicy.isAllowed) .get(subjects.list) .post(subjects.create);
// subjects year collection routes app.route('/api/year/:year/semester/:semester').all(subjectsPolicy.isAllowed) .get(subjects.listyearsemester); // subjects year collection routes app.route('/api/year/:year/semester/').all(subjectsPolicy.isAllowed) .get(subjects.listyear); // subjects year collection routes app.route('/api/year/semester/:semester').all(subjectsPolicy.isAllowed) .get(subjects.listsemester); // Single subject routes app.route('/api/subjects/:subjectId').all(subjectsPolicy.isAllowed) .get(subjects.read) .put(subjects.update) .delete(subjects.delete); // Finish by binding the subject middleware app.param('subjectId', subjects.subjectByID); };
random_line_split
data-source-definition-spec.js
describe("DataSourceDefinition", function() { var DATA_SOURCE_NAME = "Lista de Medicamentos"; var ITEM_ID_1 = "item_ID_1"; var ITEM_ID_2 = "item_ID_2"; var dataSourceDefinition; beforeEach(function() { angular.mock.module('otusjs.survey'); inject(function(_$injector_) { dataSourceDefinition = _$injector_.get('otusjs.model.survey.DataSourceDefinitionFactory').create(DATA_SOURCE_NAME); }); }); describe("isBinded method", function() { it("should return false when the DataSourceDefinition has NOT a binded itemID", function() { expect(dataSourceDefinition.isBinded()).toBe(false); }); it("should return true when has a binded itemID", function() { dataSourceDefinition.performBind(ITEM_ID_1);
}); }); describe("getID method", function() { it("should return the DATA_SOURCE_NAME without blank spaces and lower case", function() { expect(dataSourceDefinition.getID()).toBe("listademedicamentos"); }); }); describe("performBind method", function() { beforeEach(function() { dataSourceDefinition.performBind(ITEM_ID_1); }); it("should add an itemID on DataSourceDefinition", function() { expect(dataSourceDefinition.getBindedItems()).toContain(ITEM_ID_1, ITEM_ID_2); }); }); describe("removeBind method", function() { beforeEach(function() { dataSourceDefinition.performBind(ITEM_ID_1); dataSourceDefinition.removeBind(ITEM_ID_1); }); it("should remove a itemID of list of binded items", function() { expect(dataSourceDefinition.getBindedItems()).toEqual([]); }); }); describe("getBindedItems method", function() { beforeEach(function() { dataSourceDefinition.performBind(ITEM_ID_1); }); it("should return a list of binded itemsID", function() { expect(dataSourceDefinition.getBindedItems()).toEqual([ITEM_ID_1]); }); }); describe("toJson method", function () { var json; beforeEach(function () { json = JSON.stringify({ "objectType": "DataSourceDefinition", "id": "listademedicamentos", "name": DATA_SOURCE_NAME, "bindTo": [] }); }); it("should return a Json", function () { expect(JSON.stringify(dataSourceDefinition)).toBe(json); }); }); });
expect(dataSourceDefinition.isBinded()).toBe(true);
random_line_split
link_entity.js
_tmpl.link_entity = function( entity, tagName, returnHTML, count ){ if( !entity ) return false if( tagName && typeof tagName == 'object' ) return _tmpl.link_entity( entity, tagName['tagName'] || null, tagName['returnHTML'] || null, tagName['count'] || null ) tagName = tagName || 'a' returnHTML = returnHTML || false count = typeof count == 'undefined' ? false : count if( typeof entity != 'object' ){ var entityId = parseInt(entity) entity = _g.data.entities[entityId] }else{ var entityId = entity['id'] } return _tmpl.export( '<' + tagName + (tagName == 'a' ? ' href="?infos=entity&id='+entityId+'"' : '') + ' class="link_entity" data-entityid="' + entityId + '" data-infos="[[ENTITY::' + entityId + ']]">' + (entity.picture && entity.picture.avatar ? '<i style="background-image:url(' + entity.picture.avatar + ')"></i>' : '<i></i>' ) + '<span>' + entity._name
+ '</' + tagName + '>', returnHTML ) }
+ ( typeof count == 'undefined' ? '' : ' <small>(' + count + ')</small>' ) + '</span>'
random_line_split
link_entity.js
_tmpl.link_entity = function( entity, tagName, returnHTML, count ){ if( !entity ) return false if( tagName && typeof tagName == 'object' ) return _tmpl.link_entity( entity, tagName['tagName'] || null, tagName['returnHTML'] || null, tagName['count'] || null ) tagName = tagName || 'a' returnHTML = returnHTML || false count = typeof count == 'undefined' ? false : count if( typeof entity != 'object' )
else{ var entityId = entity['id'] } return _tmpl.export( '<' + tagName + (tagName == 'a' ? ' href="?infos=entity&id='+entityId+'"' : '') + ' class="link_entity" data-entityid="' + entityId + '" data-infos="[[ENTITY::' + entityId + ']]">' + (entity.picture && entity.picture.avatar ? '<i style="background-image:url(' + entity.picture.avatar + ')"></i>' : '<i></i>' ) + '<span>' + entity._name + ( typeof count == 'undefined' ? '' : ' <small>(' + count + ')</small>' ) + '</span>' + '</' + tagName + '>', returnHTML ) }
{ var entityId = parseInt(entity) entity = _g.data.entities[entityId] }
conditional_block
RidgeSample.py
#!/usr/bin/env python import arff import numpy as np import sys from sklearn import preprocessing from sklearn.linear_model import RidgeClassifier from sklearn.feature_selection import RFE from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.cross_validation import StratifiedKFold from sklearn import cross_validation from sklearn import metrics #Parameters: filename = sys.argv[1] n_featuresToSelect = [2,3,5,10,20] solvers = ['svd','cholesky','sparse_cg','lsqr','sag'] verboseLevel=10 n_jobs=10 n_crossValidation=10 n_accuracy=10 n_folds=10 # 10% removal of features stepSize=0.1 print "Load dataset" # Load dataset arffDecoder = arff.ArffDecoder() dataset = arffDecoder.decode(open(filename, 'rb'), encode_nominal=True) print "Preprocess dataset" # Get categorical features categoricals = [] # NOTE: skip last (class) 'feature' for feature in range(0,len(dataset['attributes'])-1): if isinstance(dataset['attributes'][feature][1], list): categoricals.append(feature) print "Categorical indices: {0}".format(categoricals) # Apply OneHotEncoder oneHotEncoder = preprocessing.OneHotEncoder(categorical_features=categoricals, sparse=False) print "Number of features: {0}".format(len(dataset['data'][0])) print "Number of samples: {0}".format(len(dataset['data'])) binData = oneHotEncoder.fit_transform(np.array(dataset['data'])) print "n-values: {0}".format(oneHotEncoder.n_values_) print "feature indices: {0}".format(oneHotEncoder.feature_indices_) print "Number of binarised features: {0}".format(len(binData[0])) print "Number of binarised samples: {0}".format(len(binData)) # Setting up input and outputs inputs = binData[:,:-1] output = binData[:,-1] print "Start grid search" # Setup experimental pipeline scaler = preprocessing.RobustScaler() classifier = RidgeClassifier(alpha=1.0, fit_intercept=True, normalize=False, copy_X=True, max_iter=None, tol=0.001, class_weight=None, solver='auto', random_state=None) selector = RFE(classifier,n_features_to_select=n_featuresToSelect[0],step=stepSize)
gridSearch = GridSearchCV(pipeline,param_grid=paramGrid,verbose=verboseLevel,n_jobs=n_jobs,cv=n_crossValidation) gridSearch.fit(inputs,output) estimator = gridSearch.best_estimator_ print "Results: " print "Selected features: {0}".format(estimator.named_steps['RFE'].n_features_to_select) print "Solver: {0}".format(estimator.named_steps['classifier'].solver) # Calculate accuracies print "Calculate accuracies" accuracy = [] for count in range(0,n_accuracy): cv = StratifiedKFold(output,n_folds=n_folds,shuffle=True) predicted = cross_validation.cross_val_predict(estimator,inputs,output,cv=cv,verbose=verboseLevel,n_jobs=n_jobs,) score = metrics.accuracy_score(output,predicted,normalize=True) accuracy.append(score) print "Accuracy array: {0}".format(accuracy) print "Cross-validation accuracy of final model {0}".format(np.mean(accuracy))
pipeline = Pipeline([("scaler",scaler),("RFE",selector),("classifier",classifier)]) paramGrid = dict(RFE__n_features_to_select=n_featuresToSelect, classifier__solver=solvers) # Do grid search
random_line_split
RidgeSample.py
#!/usr/bin/env python import arff import numpy as np import sys from sklearn import preprocessing from sklearn.linear_model import RidgeClassifier from sklearn.feature_selection import RFE from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.cross_validation import StratifiedKFold from sklearn import cross_validation from sklearn import metrics #Parameters: filename = sys.argv[1] n_featuresToSelect = [2,3,5,10,20] solvers = ['svd','cholesky','sparse_cg','lsqr','sag'] verboseLevel=10 n_jobs=10 n_crossValidation=10 n_accuracy=10 n_folds=10 # 10% removal of features stepSize=0.1 print "Load dataset" # Load dataset arffDecoder = arff.ArffDecoder() dataset = arffDecoder.decode(open(filename, 'rb'), encode_nominal=True) print "Preprocess dataset" # Get categorical features categoricals = [] # NOTE: skip last (class) 'feature' for feature in range(0,len(dataset['attributes'])-1):
print "Categorical indices: {0}".format(categoricals) # Apply OneHotEncoder oneHotEncoder = preprocessing.OneHotEncoder(categorical_features=categoricals, sparse=False) print "Number of features: {0}".format(len(dataset['data'][0])) print "Number of samples: {0}".format(len(dataset['data'])) binData = oneHotEncoder.fit_transform(np.array(dataset['data'])) print "n-values: {0}".format(oneHotEncoder.n_values_) print "feature indices: {0}".format(oneHotEncoder.feature_indices_) print "Number of binarised features: {0}".format(len(binData[0])) print "Number of binarised samples: {0}".format(len(binData)) # Setting up input and outputs inputs = binData[:,:-1] output = binData[:,-1] print "Start grid search" # Setup experimental pipeline scaler = preprocessing.RobustScaler() classifier = RidgeClassifier(alpha=1.0, fit_intercept=True, normalize=False, copy_X=True, max_iter=None, tol=0.001, class_weight=None, solver='auto', random_state=None) selector = RFE(classifier,n_features_to_select=n_featuresToSelect[0],step=stepSize) pipeline = Pipeline([("scaler",scaler),("RFE",selector),("classifier",classifier)]) paramGrid = dict(RFE__n_features_to_select=n_featuresToSelect, classifier__solver=solvers) # Do grid search gridSearch = GridSearchCV(pipeline,param_grid=paramGrid,verbose=verboseLevel,n_jobs=n_jobs,cv=n_crossValidation) gridSearch.fit(inputs,output) estimator = gridSearch.best_estimator_ print "Results: " print "Selected features: {0}".format(estimator.named_steps['RFE'].n_features_to_select) print "Solver: {0}".format(estimator.named_steps['classifier'].solver) # Calculate accuracies print "Calculate accuracies" accuracy = [] for count in range(0,n_accuracy): cv = StratifiedKFold(output,n_folds=n_folds,shuffle=True) predicted = cross_validation.cross_val_predict(estimator,inputs,output,cv=cv,verbose=verboseLevel,n_jobs=n_jobs,) score = metrics.accuracy_score(output,predicted,normalize=True) accuracy.append(score) print "Accuracy array: {0}".format(accuracy) print "Cross-validation accuracy of final model {0}".format(np.mean(accuracy))
if isinstance(dataset['attributes'][feature][1], list): categoricals.append(feature)
conditional_block
howcast.py
from __future__ import unicode_literals import re from .common import InfoExtractor class HowcastIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?howcast\.com/videos/(?P<id>\d+)' _TEST = { 'url': 'http://www.howcast.com/videos/390161-How-to-Tie-a-Square-Knot-Properly', 'md5': '8b743df908c42f60cf6496586c7f12c3', 'info_dict': { 'id': '390161', 'ext': 'mp4', 'description': 'The square knot, also known as the reef knot, is one of the oldest, most basic knots to tie, and can be used in many different ways. Here\'s the proper way to tie a square knot.', 'title': 'How to Tie a Square Knot Properly', } } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') webpage = self._download_webpage(url, video_id) self.report_extraction(video_id)
video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'', webpage, 'description', fatal=False) return { 'id': video_id, 'url': video_url, 'title': self._og_search_title(webpage), 'description': video_description, 'thumbnail': self._og_search_thumbnail(webpage), }
video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)', webpage, 'video URL')
random_line_split
howcast.py
from __future__ import unicode_literals import re from .common import InfoExtractor class HowcastIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?howcast\.com/videos/(?P<id>\d+)' _TEST = { 'url': 'http://www.howcast.com/videos/390161-How-to-Tie-a-Square-Knot-Properly', 'md5': '8b743df908c42f60cf6496586c7f12c3', 'info_dict': { 'id': '390161', 'ext': 'mp4', 'description': 'The square knot, also known as the reef knot, is one of the oldest, most basic knots to tie, and can be used in many different ways. Here\'s the proper way to tie a square knot.', 'title': 'How to Tie a Square Knot Properly', } } def
(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') webpage = self._download_webpage(url, video_id) self.report_extraction(video_id) video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)', webpage, 'video URL') video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'', webpage, 'description', fatal=False) return { 'id': video_id, 'url': video_url, 'title': self._og_search_title(webpage), 'description': video_description, 'thumbnail': self._og_search_thumbnail(webpage), }
_real_extract
identifier_name
howcast.py
from __future__ import unicode_literals import re from .common import InfoExtractor class HowcastIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?howcast\.com/videos/(?P<id>\d+)' _TEST = { 'url': 'http://www.howcast.com/videos/390161-How-to-Tie-a-Square-Knot-Properly', 'md5': '8b743df908c42f60cf6496586c7f12c3', 'info_dict': { 'id': '390161', 'ext': 'mp4', 'description': 'The square knot, also known as the reef knot, is one of the oldest, most basic knots to tie, and can be used in many different ways. Here\'s the proper way to tie a square knot.', 'title': 'How to Tie a Square Knot Properly', } } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') webpage = self._download_webpage(url, video_id) self.report_extraction(video_id) video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)', webpage, 'video URL') video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'', webpage, 'description', fatal=False) return { 'id': video_id, 'url': video_url, 'title': self._og_search_title(webpage), 'description': video_description, 'thumbnail': self._og_search_thumbnail(webpage), }
identifier_body
Esx.py
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2009, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 as published by # the Free Software Foundation. # # For complete information please visit: http://www.zenoss.com/oss/ # ########################################################################### __doc__="""Esx Plugin to gather information about virtual machines running under a VMWare ESX server v3.0 """ import Globals from Products.DataCollector.plugins.CollectorPlugin \ import SnmpPlugin, GetTableMap from Products.DataCollector.plugins.DataMaps \ import ObjectMap class Esx(SnmpPlugin): # compname = "os" relname = "guestDevices" modname = 'ZenPacks.zenoss.ZenossVirtualHostMonitor.VirtualMachine' columns = { '.1': 'snmpindex', '.2': 'displayName', '.4': 'osType', '.5': 'memory', '.6': 'adminStatus', '.7': 'vmid', '.8': 'operStatus', } snmpGetTableMaps = ( GetTableMap('vminfo', '.1.3.6.1.4.1.6876.2.1.1', columns), ) def process(self, device, results, log):
log.info('processing %s for device %s', self.name(), device.id) getdata, tabledata = results table = tabledata.get("vminfo") rm = self.relMap() for info in table.values(): info['adminStatus'] = info['adminStatus'] == 'poweredOn' info['operStatus'] = info['operStatus'] == 'running' info['snmpindex'] = info['vmid'] del info['vmid'] om = self.objectMap(info) om.id = self.prepId(om.displayName) rm.append(om) return [rm]
identifier_body
Esx.py
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2009, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 as published by # the Free Software Foundation. # # For complete information please visit: http://www.zenoss.com/oss/ # ########################################################################### __doc__="""Esx Plugin to gather information about virtual machines running under a VMWare ESX server v3.0 """ import Globals from Products.DataCollector.plugins.CollectorPlugin \ import SnmpPlugin, GetTableMap from Products.DataCollector.plugins.DataMaps \ import ObjectMap class Esx(SnmpPlugin): # compname = "os" relname = "guestDevices" modname = 'ZenPacks.zenoss.ZenossVirtualHostMonitor.VirtualMachine' columns = { '.1': 'snmpindex', '.2': 'displayName', '.4': 'osType', '.5': 'memory', '.6': 'adminStatus', '.7': 'vmid', '.8': 'operStatus', } snmpGetTableMaps = ( GetTableMap('vminfo', '.1.3.6.1.4.1.6876.2.1.1', columns), ) def process(self, device, results, log): log.info('processing %s for device %s', self.name(), device.id) getdata, tabledata = results table = tabledata.get("vminfo") rm = self.relMap() for info in table.values():
return [rm]
info['adminStatus'] = info['adminStatus'] == 'poweredOn' info['operStatus'] = info['operStatus'] == 'running' info['snmpindex'] = info['vmid'] del info['vmid'] om = self.objectMap(info) om.id = self.prepId(om.displayName) rm.append(om)
conditional_block
Esx.py
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2009, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 as published by # the Free Software Foundation. # # For complete information please visit: http://www.zenoss.com/oss/ # ########################################################################### __doc__="""Esx Plugin to gather information about virtual machines running under a VMWare ESX server v3.0 """
import ObjectMap class Esx(SnmpPlugin): # compname = "os" relname = "guestDevices" modname = 'ZenPacks.zenoss.ZenossVirtualHostMonitor.VirtualMachine' columns = { '.1': 'snmpindex', '.2': 'displayName', '.4': 'osType', '.5': 'memory', '.6': 'adminStatus', '.7': 'vmid', '.8': 'operStatus', } snmpGetTableMaps = ( GetTableMap('vminfo', '.1.3.6.1.4.1.6876.2.1.1', columns), ) def process(self, device, results, log): log.info('processing %s for device %s', self.name(), device.id) getdata, tabledata = results table = tabledata.get("vminfo") rm = self.relMap() for info in table.values(): info['adminStatus'] = info['adminStatus'] == 'poweredOn' info['operStatus'] = info['operStatus'] == 'running' info['snmpindex'] = info['vmid'] del info['vmid'] om = self.objectMap(info) om.id = self.prepId(om.displayName) rm.append(om) return [rm]
import Globals from Products.DataCollector.plugins.CollectorPlugin \ import SnmpPlugin, GetTableMap from Products.DataCollector.plugins.DataMaps \
random_line_split
Esx.py
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2009, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 as published by # the Free Software Foundation. # # For complete information please visit: http://www.zenoss.com/oss/ # ########################################################################### __doc__="""Esx Plugin to gather information about virtual machines running under a VMWare ESX server v3.0 """ import Globals from Products.DataCollector.plugins.CollectorPlugin \ import SnmpPlugin, GetTableMap from Products.DataCollector.plugins.DataMaps \ import ObjectMap class Esx(SnmpPlugin): # compname = "os" relname = "guestDevices" modname = 'ZenPacks.zenoss.ZenossVirtualHostMonitor.VirtualMachine' columns = { '.1': 'snmpindex', '.2': 'displayName', '.4': 'osType', '.5': 'memory', '.6': 'adminStatus', '.7': 'vmid', '.8': 'operStatus', } snmpGetTableMaps = ( GetTableMap('vminfo', '.1.3.6.1.4.1.6876.2.1.1', columns), ) def
(self, device, results, log): log.info('processing %s for device %s', self.name(), device.id) getdata, tabledata = results table = tabledata.get("vminfo") rm = self.relMap() for info in table.values(): info['adminStatus'] = info['adminStatus'] == 'poweredOn' info['operStatus'] = info['operStatus'] == 'running' info['snmpindex'] = info['vmid'] del info['vmid'] om = self.objectMap(info) om.id = self.prepId(om.displayName) rm.append(om) return [rm]
process
identifier_name
base_spec.py
import os import signal import subprocess import beanstalkc import time import pexpect try: import unittest2 as unittest except ImportError: import unittest from beanstalkctl.util import BeanstalkdMixin class BaseSpec(unittest.TestCase, BeanstalkdMixin): beanstalkd_instance = None beanstalkd_host = '127.0.0.1' beanstalkd_port = 11411 def _beanstalkd_path(self): beanstalkd = os.getenv('BEANSTALKD') if beanstalkd: return os.path.abspath(os.path.join( os.path.dirname(__file__), '..', beanstalkd)) # assume beanstalkd is # installed globally return 'beanstalkd' beanstalkd_path = property(_beanstalkd_path) def _start_beanstalkd(self): print "Using beanstalkd: {0}".format(self.beanstalkd_path) print "Starting up the beanstalkd instance...", self.beanstalkd_instance = subprocess.Popen( [self.beanstalkd_path, '-p', str(self.beanstalkd_port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, ) print 'running as {0}...'.format(self.beanstalkd_instance), print "done." def base_setup(self): self._start_beanstalkd() beanstalkctl = ' '.join([ os.path.join( os.path.dirname(self.call('pwd')), 'bin', 'beanstalkctl'), '--host={0}'.format(self.beanstalkd_host), '--port={0}'.format(self.beanstalkd_port), ]) self.logfh = open( '{0}.log'.format(self.__class__.__name__), 'w', 0) self.beanstalkctl = pexpect.spawn(beanstalkctl, logfile=self.logfh) self.beanstalkctl.setecho(False) self.beanstalkctl.expect('beanstalkctl> ') def base_teardown(self): self.logfh.close() if not self.beanstalkd_instance: return print "Shutting down the beanstalkd instance...", self.beanstalkd_instance.terminate() print "done." def interact(self, cmd, expect='beanstalkctl> '): self.beanstalkctl.sendline(cmd) self.beanstalkctl.expect_exact(expect) return self.get_response() def get_response(self): result = self.beanstalkctl.before if result.endswith('\x1b[K'): return result[:-6] return result def call(self, command, **env): """Run a command on the terminal. Args: command (str): the command to execute Keyword Args: **env (dict): any keyword arguments are collected into a dictionary and passed as environment variables directly to the subprocess call. Returns: tuple. A tuple containing `(stdoutdata, stderrdata)`, or None if unsuccessful. """ p = subprocess.Popen( command, shell=False, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, error = p.communicate() if error: raise Exception(error) return result def clean(self, text): for chunk in ('\r', r'\\x1b[K'): text = text.replace(chunk, '') return text.strip() def
(func): from nose.plugins.skip import SkipTest def wrapper(*args, **kwargs): raise SkipTest("Test %s is skipped" % func.__name__) wrapper.__name__ = func.__name__ return wrapper
skipped
identifier_name
base_spec.py
import os import signal import subprocess import beanstalkc import time import pexpect try: import unittest2 as unittest except ImportError: import unittest from beanstalkctl.util import BeanstalkdMixin class BaseSpec(unittest.TestCase, BeanstalkdMixin): beanstalkd_instance = None beanstalkd_host = '127.0.0.1' beanstalkd_port = 11411 def _beanstalkd_path(self): beanstalkd = os.getenv('BEANSTALKD') if beanstalkd: return os.path.abspath(os.path.join( os.path.dirname(__file__), '..', beanstalkd)) # assume beanstalkd is # installed globally return 'beanstalkd' beanstalkd_path = property(_beanstalkd_path) def _start_beanstalkd(self): print "Using beanstalkd: {0}".format(self.beanstalkd_path) print "Starting up the beanstalkd instance...", self.beanstalkd_instance = subprocess.Popen( [self.beanstalkd_path, '-p', str(self.beanstalkd_port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, ) print 'running as {0}...'.format(self.beanstalkd_instance), print "done." def base_setup(self): self._start_beanstalkd() beanstalkctl = ' '.join([ os.path.join( os.path.dirname(self.call('pwd')), 'bin', 'beanstalkctl'), '--host={0}'.format(self.beanstalkd_host), '--port={0}'.format(self.beanstalkd_port), ]) self.logfh = open( '{0}.log'.format(self.__class__.__name__), 'w', 0) self.beanstalkctl = pexpect.spawn(beanstalkctl, logfile=self.logfh) self.beanstalkctl.setecho(False) self.beanstalkctl.expect('beanstalkctl> ') def base_teardown(self): self.logfh.close() if not self.beanstalkd_instance: return print "Shutting down the beanstalkd instance...", self.beanstalkd_instance.terminate()
def interact(self, cmd, expect='beanstalkctl> '): self.beanstalkctl.sendline(cmd) self.beanstalkctl.expect_exact(expect) return self.get_response() def get_response(self): result = self.beanstalkctl.before if result.endswith('\x1b[K'): return result[:-6] return result def call(self, command, **env): """Run a command on the terminal. Args: command (str): the command to execute Keyword Args: **env (dict): any keyword arguments are collected into a dictionary and passed as environment variables directly to the subprocess call. Returns: tuple. A tuple containing `(stdoutdata, stderrdata)`, or None if unsuccessful. """ p = subprocess.Popen( command, shell=False, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, error = p.communicate() if error: raise Exception(error) return result def clean(self, text): for chunk in ('\r', r'\\x1b[K'): text = text.replace(chunk, '') return text.strip() def skipped(func): from nose.plugins.skip import SkipTest def wrapper(*args, **kwargs): raise SkipTest("Test %s is skipped" % func.__name__) wrapper.__name__ = func.__name__ return wrapper
print "done."
random_line_split
base_spec.py
import os import signal import subprocess import beanstalkc import time import pexpect try: import unittest2 as unittest except ImportError: import unittest from beanstalkctl.util import BeanstalkdMixin class BaseSpec(unittest.TestCase, BeanstalkdMixin): beanstalkd_instance = None beanstalkd_host = '127.0.0.1' beanstalkd_port = 11411 def _beanstalkd_path(self): beanstalkd = os.getenv('BEANSTALKD') if beanstalkd: return os.path.abspath(os.path.join( os.path.dirname(__file__), '..', beanstalkd)) # assume beanstalkd is # installed globally return 'beanstalkd' beanstalkd_path = property(_beanstalkd_path) def _start_beanstalkd(self):
def base_setup(self): self._start_beanstalkd() beanstalkctl = ' '.join([ os.path.join( os.path.dirname(self.call('pwd')), 'bin', 'beanstalkctl'), '--host={0}'.format(self.beanstalkd_host), '--port={0}'.format(self.beanstalkd_port), ]) self.logfh = open( '{0}.log'.format(self.__class__.__name__), 'w', 0) self.beanstalkctl = pexpect.spawn(beanstalkctl, logfile=self.logfh) self.beanstalkctl.setecho(False) self.beanstalkctl.expect('beanstalkctl> ') def base_teardown(self): self.logfh.close() if not self.beanstalkd_instance: return print "Shutting down the beanstalkd instance...", self.beanstalkd_instance.terminate() print "done." def interact(self, cmd, expect='beanstalkctl> '): self.beanstalkctl.sendline(cmd) self.beanstalkctl.expect_exact(expect) return self.get_response() def get_response(self): result = self.beanstalkctl.before if result.endswith('\x1b[K'): return result[:-6] return result def call(self, command, **env): """Run a command on the terminal. Args: command (str): the command to execute Keyword Args: **env (dict): any keyword arguments are collected into a dictionary and passed as environment variables directly to the subprocess call. Returns: tuple. A tuple containing `(stdoutdata, stderrdata)`, or None if unsuccessful. """ p = subprocess.Popen( command, shell=False, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, error = p.communicate() if error: raise Exception(error) return result def clean(self, text): for chunk in ('\r', r'\\x1b[K'): text = text.replace(chunk, '') return text.strip() def skipped(func): from nose.plugins.skip import SkipTest def wrapper(*args, **kwargs): raise SkipTest("Test %s is skipped" % func.__name__) wrapper.__name__ = func.__name__ return wrapper
print "Using beanstalkd: {0}".format(self.beanstalkd_path) print "Starting up the beanstalkd instance...", self.beanstalkd_instance = subprocess.Popen( [self.beanstalkd_path, '-p', str(self.beanstalkd_port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, ) print 'running as {0}...'.format(self.beanstalkd_instance), print "done."
identifier_body
base_spec.py
import os import signal import subprocess import beanstalkc import time import pexpect try: import unittest2 as unittest except ImportError: import unittest from beanstalkctl.util import BeanstalkdMixin class BaseSpec(unittest.TestCase, BeanstalkdMixin): beanstalkd_instance = None beanstalkd_host = '127.0.0.1' beanstalkd_port = 11411 def _beanstalkd_path(self): beanstalkd = os.getenv('BEANSTALKD') if beanstalkd: return os.path.abspath(os.path.join( os.path.dirname(__file__), '..', beanstalkd)) # assume beanstalkd is # installed globally return 'beanstalkd' beanstalkd_path = property(_beanstalkd_path) def _start_beanstalkd(self): print "Using beanstalkd: {0}".format(self.beanstalkd_path) print "Starting up the beanstalkd instance...", self.beanstalkd_instance = subprocess.Popen( [self.beanstalkd_path, '-p', str(self.beanstalkd_port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, ) print 'running as {0}...'.format(self.beanstalkd_instance), print "done." def base_setup(self): self._start_beanstalkd() beanstalkctl = ' '.join([ os.path.join( os.path.dirname(self.call('pwd')), 'bin', 'beanstalkctl'), '--host={0}'.format(self.beanstalkd_host), '--port={0}'.format(self.beanstalkd_port), ]) self.logfh = open( '{0}.log'.format(self.__class__.__name__), 'w', 0) self.beanstalkctl = pexpect.spawn(beanstalkctl, logfile=self.logfh) self.beanstalkctl.setecho(False) self.beanstalkctl.expect('beanstalkctl> ') def base_teardown(self): self.logfh.close() if not self.beanstalkd_instance: return print "Shutting down the beanstalkd instance...", self.beanstalkd_instance.terminate() print "done." def interact(self, cmd, expect='beanstalkctl> '): self.beanstalkctl.sendline(cmd) self.beanstalkctl.expect_exact(expect) return self.get_response() def get_response(self): result = self.beanstalkctl.before if result.endswith('\x1b[K'): return result[:-6] return result def call(self, command, **env): """Run a command on the terminal. Args: command (str): the command to execute Keyword Args: **env (dict): any keyword arguments are collected into a dictionary and passed as environment variables directly to the subprocess call. Returns: tuple. A tuple containing `(stdoutdata, stderrdata)`, or None if unsuccessful. """ p = subprocess.Popen( command, shell=False, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, error = p.communicate() if error: raise Exception(error) return result def clean(self, text): for chunk in ('\r', r'\\x1b[K'):
return text.strip() def skipped(func): from nose.plugins.skip import SkipTest def wrapper(*args, **kwargs): raise SkipTest("Test %s is skipped" % func.__name__) wrapper.__name__ = func.__name__ return wrapper
text = text.replace(chunk, '')
conditional_block
base_filters.py
import re import os import pytz from PIL import Image from dateutil.parser import parse from datetime import datetime from decimal import Decimal from django.template import Library from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils import formats from django.utils.safestring import mark_safe from django.utils.html import conditional_escape, strip_tags, urlize from django.contrib.auth.models import AnonymousUser from django.core.files.storage import default_storage register = Library() @register.filter(name="localize_date") def localize_date(value, to_tz=None): from timezones.utils import adjust_datetime_to_timezone try: if to_tz is None: to_tz = settings.UI_TIME_ZONE from_tz = settings.TIME_ZONE return adjust_datetime_to_timezone(value, from_tz=from_tz, to_tz=to_tz) except AttributeError: return '' localize_date.is_safe = True @register.filter_function def date_short(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format from tendenci.apps.site_settings.utils import get_setting if not value: return u'' if arg is None: s_date_format = get_setting('site', 'global', 'dateformat') if s_date_format: arg = s_date_format else: arg = settings.SHORT_DATETIME_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_short.is_safe = False @register.filter_function def date_long(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format from tendenci.apps.site_settings.utils import get_setting if not value: return u'' if arg is None: s_date_format = get_setting('site', 'global', 'dateformatlong') if s_date_format: arg = s_date_format else: arg = settings.DATETIME_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_long.is_safe = False @register.filter_function def date(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format if not value: return u'' if arg is None: arg = settings.DATETIME_FORMAT else: if arg == 'long': return date_long(value) if arg == 'short': return date_short(value) try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_long.is_safe = False @register.filter_function def order_by(queryset, args): args = [x.strip() for x in args.split(',')]
def str_to_date(string, args=None): """Takes a string and converts it to a datetime object""" date = parse(string) if date: return date return '' @register.filter_function def exif_to_date(s, fmt='%Y:%m:%d %H:%M:%S'): """ The format of datetime in exif is as follows: %Y:%m:%d %H:%M:%S Convert the string with this format to a datetime object. """ if not s: return None try: return datetime.strptime(s, fmt) except ValueError: return None @register.filter_function def in_group(user, group): if group: if isinstance(user, AnonymousUser): return False return group in [dict['pk'] for dict in user.group_set.values('pk')] else: return False @register.filter def domain(link): from urlparse import urlparse link = urlparse(link) return link.hostname @register.filter def strip_template_tags(string): p = re.compile('{[#{%][^#}%]+[%}#]}') return re.sub(p, '', string) @register.filter @stringfilter def stripentities(value): """Strips all [X]HTML tags.""" from django.utils.html import strip_entities return strip_entities(value) stripentities.is_safe = True @register.filter def format_currency(value): """format currency""" from tendenci.apps.base.utils import tcurrency return tcurrency(value) format_currency.is_safe = True @register.filter def get_object(obj): """return obj.object if this obj has the attribute of object""" if hasattr(obj, 'object'): return obj.object else: return obj @register.filter def scope(object): return dir(object) @register.filter def obj_type(object): """ Return object type """ return type(object) @register.filter def is_iterable(object): """ Return boolean Is the object iterable or not """ try: iter(object) return True except TypeError: return False @register.filter @stringfilter def basename(path): from os.path import basename return basename(path) @register.filter def date_diff(value, date_to_compare=None): """Compare two dates and return the difference in days""" import datetime if not isinstance(value, datetime.datetime): return 0 if not isinstance(date_to_compare, datetime.datetime): date_to_compare = datetime.datetime.now() return (date_to_compare - value).days @register.filter def first_chars(string, arg): """ returns the first x characters from a string """ string = str(string) if arg: if not arg.isdigit(): return string return string[:int(arg)] else: return string return string @register.filter def rss_date(value, arg=None): """Formats a date according to the given format.""" from django.utils import formats from django.utils.dateformat import format from datetime import datetime if not value: return u'' else: value = datetime(*value[:-3]) if arg is None: arg = settings.DATE_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' rss_date.is_safe = False @register.filter() def obfuscate_email(email, linktext=None, autoescape=None): """ Given a string representing an email address, returns a mailto link with rot13 JavaScript obfuscation. Accepts an optional argument to use as the link text; otherwise uses the email address itself. """ if autoescape: esc = conditional_escape else: esc = lambda x: x email = re.sub('@', '\\\\100', re.sub('\.', '\\\\056', \ esc(email))).encode('rot13') if linktext: linktext = esc(linktext).encode('rot13') else: linktext = email rotten_link = """<script type="text/javascript">document.write \ ("<n uers=\\\"znvygb:%s\\\">%s<\\057n>".replace(/[a-zA-Z]/g, \ function(c){return String.fromCharCode((c<="Z"?90:122)>=\ (c=c.charCodeAt(0)+13)?c:c-26);}));</script>""" % (email, linktext) return mark_safe(rotten_link) obfuscate_email.needs_autoescape = True @register.filter_function def split_str(s, args): """ Split a string using the python string split method """ if args: if isinstance(s, str): splitter = args[0] return s.split(splitter) return s return s @register.filter_function def str_basename(s): """ Get the basename using the python basename method """ return basename(s) @register.filter @stringfilter def twitterize(value, autoescape=None): value = strip_tags(value) # Link URLs value = urlize(value, nofollow=False, autoescape=autoescape) # Link twitter usernames for the first person value = re.sub(r'(^[^:]+)', r'<a href="http://twitter.com/\1">\1</a>', value) # Link twitter usernames prefixed with @ value = re.sub(r'(\s+|\A)@([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://twitter.com/\2">@\2</a>', value) # Link hash tags value = re.sub(r'(\s+|\A)#([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>', value) return mark_safe(value) twitterize.is_safe = True twitterize.needs_autoescape = True @register.filter @stringfilter def twitterdate(value): from datetime import datetime, timedelta time = value.replace(" +0000", "") dt = datetime.strptime(time, "%a, %d %b %Y %H:%M:%S") return dt + timedelta(hours=-6) @register.filter def thumbnail(file, size='200x200'): # defining the size x, y = [int(x) for x in size.split('x')] # defining the filename and the miniature filename filehead, filetail = os.path.split(file.name) basename, format = os.path.splitext(filetail) miniature = basename + '_' + size + format filename = file.name miniature_filename = os.path.join(filehead, miniature) filehead, filetail = os.path.split(file.url) miniature_url = filehead + '/' + miniature thumbnail_exist = False if default_storage.exists(miniature_filename): mt_filename = default_storage.modified_time(filename) mt_miniature_filename = default_storage.modified_time( miniature_filename) if mt_filename > mt_miniature_filename: # remove the miniature default_storage.delete(miniature_filename) else: thumbnail_exist = True # if the image wasn't already resized, resize it if not thumbnail_exist: if not default_storage.exists(filename): return u'' image = Image.open(default_storage.open(filename)) image.thumbnail([x, y], Image.ANTIALIAS) f = default_storage.open(miniature_filename, 'w') image.save(f, image.format, quality=90, optimize=1) f.close() return miniature_url @register.filter_function def datedelta(dt, range_): from datetime import timedelta range_type = 'add' # parse the range if '+' in range_: range_ = range_[1:len(range_)] if '-' in range_: range_type = 'subtract' range_ = range_[1:len(range_)] k, v = range_.split('=') set_range = { str(k): int(v) } # set the date if range_type == 'add': dt = dt + timedelta(**set_range) if range_type == 'subtract': dt = dt - timedelta(**set_range) return dt @register.filter def split(str, splitter): return str.split(splitter) @register.filter def tag_split(str): str = "".join(str) str = str.replace(", ", ",") return str.split(",") @register.filter def make_range(value): try: value = int(value) if value > 0: return range(int(value)) return [] except: return [] @register.filter def underscore_space(value): return value.replace("_", " ") @register.filter def format_string(value, arg): return arg % value @register.filter def md5_gs(value, arg=None): import hashlib from datetime import datetime, timedelta hashdt = '' if arg and int(arg): timestamp = datetime.now() + timedelta(hours=int(arg)) hashdt = hashlib.md5(timestamp.strftime("%Y;%m;%d;%H;%M").replace(';0', ';')).hexdigest() return ''.join([value, hashdt]) @register.filter def multiply(value, arg): return Decimal(str(value)) * Decimal(str(arg)) @register.filter def add_decimal(value, arg): return Decimal(str(value)) + Decimal(str(arg)) @register.filter def phonenumber(value): if value: # split number from extension or any text x = re.split(r'([a-zA-Z]+)', value) # clean number y = ''.join(i for i in x[0] if i.isdigit()) if len(y) > 10: # has country code code = y[:len(y)-10] number = y[len(y)-10:] if code == '1': number = "(%s) %s-%s" %(number[:3], number[3:6], number[6:]) else: number = "+%s %s %s %s" %(code, number[:3], number[3:6], number[6:]) else: # no country code number = "(%s) %s-%s" %(y[:3], y[3:6], y[6:]) # attach additional text extension ext = '' for i in xrange(1, len(x)): ext = ''.join((ext, x[i])) if ext: return ' '.join((number, ext)) else: return number @register.filter def timezone_label(value): try: now = datetime.now(pytz.timezone(value)) tzinfo = now.strftime("%z") return "(GMT%s) %s" %(tzinfo, value) except: return "" @register.filter def field_to_string(value): if isinstance(value, str) or isinstance(value, unicode): return value if isinstance(value, list): if len(value) == 0: return "" if len(value) == 1: return str(value[0]) if len(value) == 2: return "%s and %s" % (value[0], value[1]) return ", ".join(value) return str(value)
return queryset.order_by(*args) @register.filter_function
random_line_split
base_filters.py
import re import os import pytz from PIL import Image from dateutil.parser import parse from datetime import datetime from decimal import Decimal from django.template import Library from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils import formats from django.utils.safestring import mark_safe from django.utils.html import conditional_escape, strip_tags, urlize from django.contrib.auth.models import AnonymousUser from django.core.files.storage import default_storage register = Library() @register.filter(name="localize_date") def localize_date(value, to_tz=None): from timezones.utils import adjust_datetime_to_timezone try: if to_tz is None: to_tz = settings.UI_TIME_ZONE from_tz = settings.TIME_ZONE return adjust_datetime_to_timezone(value, from_tz=from_tz, to_tz=to_tz) except AttributeError: return '' localize_date.is_safe = True @register.filter_function def date_short(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format from tendenci.apps.site_settings.utils import get_setting if not value: return u'' if arg is None: s_date_format = get_setting('site', 'global', 'dateformat') if s_date_format: arg = s_date_format else: arg = settings.SHORT_DATETIME_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_short.is_safe = False @register.filter_function def date_long(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format from tendenci.apps.site_settings.utils import get_setting if not value: return u'' if arg is None: s_date_format = get_setting('site', 'global', 'dateformatlong') if s_date_format: arg = s_date_format else: arg = settings.DATETIME_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_long.is_safe = False @register.filter_function def date(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format if not value: return u'' if arg is None: arg = settings.DATETIME_FORMAT else: if arg == 'long': return date_long(value) if arg == 'short': return date_short(value) try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_long.is_safe = False @register.filter_function def order_by(queryset, args): args = [x.strip() for x in args.split(',')] return queryset.order_by(*args) @register.filter_function def str_to_date(string, args=None): """Takes a string and converts it to a datetime object""" date = parse(string) if date: return date return '' @register.filter_function def exif_to_date(s, fmt='%Y:%m:%d %H:%M:%S'): """ The format of datetime in exif is as follows: %Y:%m:%d %H:%M:%S Convert the string with this format to a datetime object. """ if not s: return None try: return datetime.strptime(s, fmt) except ValueError: return None @register.filter_function def in_group(user, group): if group: if isinstance(user, AnonymousUser): return False return group in [dict['pk'] for dict in user.group_set.values('pk')] else: return False @register.filter def domain(link): from urlparse import urlparse link = urlparse(link) return link.hostname @register.filter def strip_template_tags(string): p = re.compile('{[#{%][^#}%]+[%}#]}') return re.sub(p, '', string) @register.filter @stringfilter def stripentities(value): """Strips all [X]HTML tags.""" from django.utils.html import strip_entities return strip_entities(value) stripentities.is_safe = True @register.filter def format_currency(value): """format currency""" from tendenci.apps.base.utils import tcurrency return tcurrency(value) format_currency.is_safe = True @register.filter def get_object(obj): """return obj.object if this obj has the attribute of object""" if hasattr(obj, 'object'): return obj.object else: return obj @register.filter def scope(object): return dir(object) @register.filter def obj_type(object): """ Return object type """ return type(object) @register.filter def is_iterable(object): """ Return boolean Is the object iterable or not """ try: iter(object) return True except TypeError: return False @register.filter @stringfilter def basename(path): from os.path import basename return basename(path) @register.filter def date_diff(value, date_to_compare=None): """Compare two dates and return the difference in days""" import datetime if not isinstance(value, datetime.datetime): return 0 if not isinstance(date_to_compare, datetime.datetime): date_to_compare = datetime.datetime.now() return (date_to_compare - value).days @register.filter def first_chars(string, arg): """ returns the first x characters from a string """ string = str(string) if arg: if not arg.isdigit(): return string return string[:int(arg)] else: return string return string @register.filter def rss_date(value, arg=None): """Formats a date according to the given format.""" from django.utils import formats from django.utils.dateformat import format from datetime import datetime if not value: return u'' else: value = datetime(*value[:-3]) if arg is None: arg = settings.DATE_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' rss_date.is_safe = False @register.filter() def obfuscate_email(email, linktext=None, autoescape=None): """ Given a string representing an email address, returns a mailto link with rot13 JavaScript obfuscation. Accepts an optional argument to use as the link text; otherwise uses the email address itself. """ if autoescape: esc = conditional_escape else: esc = lambda x: x email = re.sub('@', '\\\\100', re.sub('\.', '\\\\056', \ esc(email))).encode('rot13') if linktext: linktext = esc(linktext).encode('rot13') else: linktext = email rotten_link = """<script type="text/javascript">document.write \ ("<n uers=\\\"znvygb:%s\\\">%s<\\057n>".replace(/[a-zA-Z]/g, \ function(c){return String.fromCharCode((c<="Z"?90:122)>=\ (c=c.charCodeAt(0)+13)?c:c-26);}));</script>""" % (email, linktext) return mark_safe(rotten_link) obfuscate_email.needs_autoescape = True @register.filter_function def split_str(s, args): """ Split a string using the python string split method """ if args: if isinstance(s, str): splitter = args[0] return s.split(splitter) return s return s @register.filter_function def str_basename(s): """ Get the basename using the python basename method """ return basename(s) @register.filter @stringfilter def twitterize(value, autoescape=None): value = strip_tags(value) # Link URLs value = urlize(value, nofollow=False, autoescape=autoescape) # Link twitter usernames for the first person value = re.sub(r'(^[^:]+)', r'<a href="http://twitter.com/\1">\1</a>', value) # Link twitter usernames prefixed with @ value = re.sub(r'(\s+|\A)@([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://twitter.com/\2">@\2</a>', value) # Link hash tags value = re.sub(r'(\s+|\A)#([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>', value) return mark_safe(value) twitterize.is_safe = True twitterize.needs_autoescape = True @register.filter @stringfilter def twitterdate(value): from datetime import datetime, timedelta time = value.replace(" +0000", "") dt = datetime.strptime(time, "%a, %d %b %Y %H:%M:%S") return dt + timedelta(hours=-6) @register.filter def thumbnail(file, size='200x200'): # defining the size x, y = [int(x) for x in size.split('x')] # defining the filename and the miniature filename filehead, filetail = os.path.split(file.name) basename, format = os.path.splitext(filetail) miniature = basename + '_' + size + format filename = file.name miniature_filename = os.path.join(filehead, miniature) filehead, filetail = os.path.split(file.url) miniature_url = filehead + '/' + miniature thumbnail_exist = False if default_storage.exists(miniature_filename): mt_filename = default_storage.modified_time(filename) mt_miniature_filename = default_storage.modified_time( miniature_filename) if mt_filename > mt_miniature_filename: # remove the miniature default_storage.delete(miniature_filename) else: thumbnail_exist = True # if the image wasn't already resized, resize it if not thumbnail_exist: if not default_storage.exists(filename): return u'' image = Image.open(default_storage.open(filename)) image.thumbnail([x, y], Image.ANTIALIAS) f = default_storage.open(miniature_filename, 'w') image.save(f, image.format, quality=90, optimize=1) f.close() return miniature_url @register.filter_function def datedelta(dt, range_):
@register.filter def split(str, splitter): return str.split(splitter) @register.filter def tag_split(str): str = "".join(str) str = str.replace(", ", ",") return str.split(",") @register.filter def make_range(value): try: value = int(value) if value > 0: return range(int(value)) return [] except: return [] @register.filter def underscore_space(value): return value.replace("_", " ") @register.filter def format_string(value, arg): return arg % value @register.filter def md5_gs(value, arg=None): import hashlib from datetime import datetime, timedelta hashdt = '' if arg and int(arg): timestamp = datetime.now() + timedelta(hours=int(arg)) hashdt = hashlib.md5(timestamp.strftime("%Y;%m;%d;%H;%M").replace(';0', ';')).hexdigest() return ''.join([value, hashdt]) @register.filter def multiply(value, arg): return Decimal(str(value)) * Decimal(str(arg)) @register.filter def add_decimal(value, arg): return Decimal(str(value)) + Decimal(str(arg)) @register.filter def phonenumber(value): if value: # split number from extension or any text x = re.split(r'([a-zA-Z]+)', value) # clean number y = ''.join(i for i in x[0] if i.isdigit()) if len(y) > 10: # has country code code = y[:len(y)-10] number = y[len(y)-10:] if code == '1': number = "(%s) %s-%s" %(number[:3], number[3:6], number[6:]) else: number = "+%s %s %s %s" %(code, number[:3], number[3:6], number[6:]) else: # no country code number = "(%s) %s-%s" %(y[:3], y[3:6], y[6:]) # attach additional text extension ext = '' for i in xrange(1, len(x)): ext = ''.join((ext, x[i])) if ext: return ' '.join((number, ext)) else: return number @register.filter def timezone_label(value): try: now = datetime.now(pytz.timezone(value)) tzinfo = now.strftime("%z") return "(GMT%s) %s" %(tzinfo, value) except: return "" @register.filter def field_to_string(value): if isinstance(value, str) or isinstance(value, unicode): return value if isinstance(value, list): if len(value) == 0: return "" if len(value) == 1: return str(value[0]) if len(value) == 2: return "%s and %s" % (value[0], value[1]) return ", ".join(value) return str(value)
from datetime import timedelta range_type = 'add' # parse the range if '+' in range_: range_ = range_[1:len(range_)] if '-' in range_: range_type = 'subtract' range_ = range_[1:len(range_)] k, v = range_.split('=') set_range = { str(k): int(v) } # set the date if range_type == 'add': dt = dt + timedelta(**set_range) if range_type == 'subtract': dt = dt - timedelta(**set_range) return dt
identifier_body
base_filters.py
import re import os import pytz from PIL import Image from dateutil.parser import parse from datetime import datetime from decimal import Decimal from django.template import Library from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils import formats from django.utils.safestring import mark_safe from django.utils.html import conditional_escape, strip_tags, urlize from django.contrib.auth.models import AnonymousUser from django.core.files.storage import default_storage register = Library() @register.filter(name="localize_date") def localize_date(value, to_tz=None): from timezones.utils import adjust_datetime_to_timezone try: if to_tz is None: to_tz = settings.UI_TIME_ZONE from_tz = settings.TIME_ZONE return adjust_datetime_to_timezone(value, from_tz=from_tz, to_tz=to_tz) except AttributeError: return '' localize_date.is_safe = True @register.filter_function def date_short(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format from tendenci.apps.site_settings.utils import get_setting if not value: return u'' if arg is None: s_date_format = get_setting('site', 'global', 'dateformat') if s_date_format: arg = s_date_format else: arg = settings.SHORT_DATETIME_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_short.is_safe = False @register.filter_function def date_long(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format from tendenci.apps.site_settings.utils import get_setting if not value: return u'' if arg is None: s_date_format = get_setting('site', 'global', 'dateformatlong') if s_date_format: arg = s_date_format else: arg = settings.DATETIME_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_long.is_safe = False @register.filter_function def date(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format if not value: return u'' if arg is None: arg = settings.DATETIME_FORMAT else: if arg == 'long': return date_long(value) if arg == 'short': return date_short(value) try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_long.is_safe = False @register.filter_function def order_by(queryset, args): args = [x.strip() for x in args.split(',')] return queryset.order_by(*args) @register.filter_function def str_to_date(string, args=None): """Takes a string and converts it to a datetime object""" date = parse(string) if date: return date return '' @register.filter_function def exif_to_date(s, fmt='%Y:%m:%d %H:%M:%S'): """ The format of datetime in exif is as follows: %Y:%m:%d %H:%M:%S Convert the string with this format to a datetime object. """ if not s: return None try: return datetime.strptime(s, fmt) except ValueError: return None @register.filter_function def in_group(user, group): if group: if isinstance(user, AnonymousUser): return False return group in [dict['pk'] for dict in user.group_set.values('pk')] else: return False @register.filter def domain(link): from urlparse import urlparse link = urlparse(link) return link.hostname @register.filter def strip_template_tags(string): p = re.compile('{[#{%][^#}%]+[%}#]}') return re.sub(p, '', string) @register.filter @stringfilter def stripentities(value): """Strips all [X]HTML tags.""" from django.utils.html import strip_entities return strip_entities(value) stripentities.is_safe = True @register.filter def format_currency(value): """format currency""" from tendenci.apps.base.utils import tcurrency return tcurrency(value) format_currency.is_safe = True @register.filter def get_object(obj): """return obj.object if this obj has the attribute of object""" if hasattr(obj, 'object'): return obj.object else: return obj @register.filter def scope(object): return dir(object) @register.filter def obj_type(object): """ Return object type """ return type(object) @register.filter def is_iterable(object): """ Return boolean Is the object iterable or not """ try: iter(object) return True except TypeError: return False @register.filter @stringfilter def
(path): from os.path import basename return basename(path) @register.filter def date_diff(value, date_to_compare=None): """Compare two dates and return the difference in days""" import datetime if not isinstance(value, datetime.datetime): return 0 if not isinstance(date_to_compare, datetime.datetime): date_to_compare = datetime.datetime.now() return (date_to_compare - value).days @register.filter def first_chars(string, arg): """ returns the first x characters from a string """ string = str(string) if arg: if not arg.isdigit(): return string return string[:int(arg)] else: return string return string @register.filter def rss_date(value, arg=None): """Formats a date according to the given format.""" from django.utils import formats from django.utils.dateformat import format from datetime import datetime if not value: return u'' else: value = datetime(*value[:-3]) if arg is None: arg = settings.DATE_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' rss_date.is_safe = False @register.filter() def obfuscate_email(email, linktext=None, autoescape=None): """ Given a string representing an email address, returns a mailto link with rot13 JavaScript obfuscation. Accepts an optional argument to use as the link text; otherwise uses the email address itself. """ if autoescape: esc = conditional_escape else: esc = lambda x: x email = re.sub('@', '\\\\100', re.sub('\.', '\\\\056', \ esc(email))).encode('rot13') if linktext: linktext = esc(linktext).encode('rot13') else: linktext = email rotten_link = """<script type="text/javascript">document.write \ ("<n uers=\\\"znvygb:%s\\\">%s<\\057n>".replace(/[a-zA-Z]/g, \ function(c){return String.fromCharCode((c<="Z"?90:122)>=\ (c=c.charCodeAt(0)+13)?c:c-26);}));</script>""" % (email, linktext) return mark_safe(rotten_link) obfuscate_email.needs_autoescape = True @register.filter_function def split_str(s, args): """ Split a string using the python string split method """ if args: if isinstance(s, str): splitter = args[0] return s.split(splitter) return s return s @register.filter_function def str_basename(s): """ Get the basename using the python basename method """ return basename(s) @register.filter @stringfilter def twitterize(value, autoescape=None): value = strip_tags(value) # Link URLs value = urlize(value, nofollow=False, autoescape=autoescape) # Link twitter usernames for the first person value = re.sub(r'(^[^:]+)', r'<a href="http://twitter.com/\1">\1</a>', value) # Link twitter usernames prefixed with @ value = re.sub(r'(\s+|\A)@([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://twitter.com/\2">@\2</a>', value) # Link hash tags value = re.sub(r'(\s+|\A)#([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>', value) return mark_safe(value) twitterize.is_safe = True twitterize.needs_autoescape = True @register.filter @stringfilter def twitterdate(value): from datetime import datetime, timedelta time = value.replace(" +0000", "") dt = datetime.strptime(time, "%a, %d %b %Y %H:%M:%S") return dt + timedelta(hours=-6) @register.filter def thumbnail(file, size='200x200'): # defining the size x, y = [int(x) for x in size.split('x')] # defining the filename and the miniature filename filehead, filetail = os.path.split(file.name) basename, format = os.path.splitext(filetail) miniature = basename + '_' + size + format filename = file.name miniature_filename = os.path.join(filehead, miniature) filehead, filetail = os.path.split(file.url) miniature_url = filehead + '/' + miniature thumbnail_exist = False if default_storage.exists(miniature_filename): mt_filename = default_storage.modified_time(filename) mt_miniature_filename = default_storage.modified_time( miniature_filename) if mt_filename > mt_miniature_filename: # remove the miniature default_storage.delete(miniature_filename) else: thumbnail_exist = True # if the image wasn't already resized, resize it if not thumbnail_exist: if not default_storage.exists(filename): return u'' image = Image.open(default_storage.open(filename)) image.thumbnail([x, y], Image.ANTIALIAS) f = default_storage.open(miniature_filename, 'w') image.save(f, image.format, quality=90, optimize=1) f.close() return miniature_url @register.filter_function def datedelta(dt, range_): from datetime import timedelta range_type = 'add' # parse the range if '+' in range_: range_ = range_[1:len(range_)] if '-' in range_: range_type = 'subtract' range_ = range_[1:len(range_)] k, v = range_.split('=') set_range = { str(k): int(v) } # set the date if range_type == 'add': dt = dt + timedelta(**set_range) if range_type == 'subtract': dt = dt - timedelta(**set_range) return dt @register.filter def split(str, splitter): return str.split(splitter) @register.filter def tag_split(str): str = "".join(str) str = str.replace(", ", ",") return str.split(",") @register.filter def make_range(value): try: value = int(value) if value > 0: return range(int(value)) return [] except: return [] @register.filter def underscore_space(value): return value.replace("_", " ") @register.filter def format_string(value, arg): return arg % value @register.filter def md5_gs(value, arg=None): import hashlib from datetime import datetime, timedelta hashdt = '' if arg and int(arg): timestamp = datetime.now() + timedelta(hours=int(arg)) hashdt = hashlib.md5(timestamp.strftime("%Y;%m;%d;%H;%M").replace(';0', ';')).hexdigest() return ''.join([value, hashdt]) @register.filter def multiply(value, arg): return Decimal(str(value)) * Decimal(str(arg)) @register.filter def add_decimal(value, arg): return Decimal(str(value)) + Decimal(str(arg)) @register.filter def phonenumber(value): if value: # split number from extension or any text x = re.split(r'([a-zA-Z]+)', value) # clean number y = ''.join(i for i in x[0] if i.isdigit()) if len(y) > 10: # has country code code = y[:len(y)-10] number = y[len(y)-10:] if code == '1': number = "(%s) %s-%s" %(number[:3], number[3:6], number[6:]) else: number = "+%s %s %s %s" %(code, number[:3], number[3:6], number[6:]) else: # no country code number = "(%s) %s-%s" %(y[:3], y[3:6], y[6:]) # attach additional text extension ext = '' for i in xrange(1, len(x)): ext = ''.join((ext, x[i])) if ext: return ' '.join((number, ext)) else: return number @register.filter def timezone_label(value): try: now = datetime.now(pytz.timezone(value)) tzinfo = now.strftime("%z") return "(GMT%s) %s" %(tzinfo, value) except: return "" @register.filter def field_to_string(value): if isinstance(value, str) or isinstance(value, unicode): return value if isinstance(value, list): if len(value) == 0: return "" if len(value) == 1: return str(value[0]) if len(value) == 2: return "%s and %s" % (value[0], value[1]) return ", ".join(value) return str(value)
basename
identifier_name
base_filters.py
import re import os import pytz from PIL import Image from dateutil.parser import parse from datetime import datetime from decimal import Decimal from django.template import Library from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils import formats from django.utils.safestring import mark_safe from django.utils.html import conditional_escape, strip_tags, urlize from django.contrib.auth.models import AnonymousUser from django.core.files.storage import default_storage register = Library() @register.filter(name="localize_date") def localize_date(value, to_tz=None): from timezones.utils import adjust_datetime_to_timezone try: if to_tz is None: to_tz = settings.UI_TIME_ZONE from_tz = settings.TIME_ZONE return adjust_datetime_to_timezone(value, from_tz=from_tz, to_tz=to_tz) except AttributeError: return '' localize_date.is_safe = True @register.filter_function def date_short(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format from tendenci.apps.site_settings.utils import get_setting if not value: return u'' if arg is None: s_date_format = get_setting('site', 'global', 'dateformat') if s_date_format: arg = s_date_format else: arg = settings.SHORT_DATETIME_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_short.is_safe = False @register.filter_function def date_long(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format from tendenci.apps.site_settings.utils import get_setting if not value: return u'' if arg is None: s_date_format = get_setting('site', 'global', 'dateformatlong') if s_date_format: arg = s_date_format else: arg = settings.DATETIME_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_long.is_safe = False @register.filter_function def date(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format if not value: return u'' if arg is None: arg = settings.DATETIME_FORMAT else: if arg == 'long': return date_long(value) if arg == 'short': return date_short(value) try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_long.is_safe = False @register.filter_function def order_by(queryset, args): args = [x.strip() for x in args.split(',')] return queryset.order_by(*args) @register.filter_function def str_to_date(string, args=None): """Takes a string and converts it to a datetime object""" date = parse(string) if date: return date return '' @register.filter_function def exif_to_date(s, fmt='%Y:%m:%d %H:%M:%S'): """ The format of datetime in exif is as follows: %Y:%m:%d %H:%M:%S Convert the string with this format to a datetime object. """ if not s: return None try: return datetime.strptime(s, fmt) except ValueError: return None @register.filter_function def in_group(user, group): if group: if isinstance(user, AnonymousUser): return False return group in [dict['pk'] for dict in user.group_set.values('pk')] else: return False @register.filter def domain(link): from urlparse import urlparse link = urlparse(link) return link.hostname @register.filter def strip_template_tags(string): p = re.compile('{[#{%][^#}%]+[%}#]}') return re.sub(p, '', string) @register.filter @stringfilter def stripentities(value): """Strips all [X]HTML tags.""" from django.utils.html import strip_entities return strip_entities(value) stripentities.is_safe = True @register.filter def format_currency(value): """format currency""" from tendenci.apps.base.utils import tcurrency return tcurrency(value) format_currency.is_safe = True @register.filter def get_object(obj): """return obj.object if this obj has the attribute of object""" if hasattr(obj, 'object'): return obj.object else: return obj @register.filter def scope(object): return dir(object) @register.filter def obj_type(object): """ Return object type """ return type(object) @register.filter def is_iterable(object): """ Return boolean Is the object iterable or not """ try: iter(object) return True except TypeError: return False @register.filter @stringfilter def basename(path): from os.path import basename return basename(path) @register.filter def date_diff(value, date_to_compare=None): """Compare two dates and return the difference in days""" import datetime if not isinstance(value, datetime.datetime): return 0 if not isinstance(date_to_compare, datetime.datetime): date_to_compare = datetime.datetime.now() return (date_to_compare - value).days @register.filter def first_chars(string, arg): """ returns the first x characters from a string """ string = str(string) if arg: if not arg.isdigit():
return string[:int(arg)] else: return string return string @register.filter def rss_date(value, arg=None): """Formats a date according to the given format.""" from django.utils import formats from django.utils.dateformat import format from datetime import datetime if not value: return u'' else: value = datetime(*value[:-3]) if arg is None: arg = settings.DATE_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' rss_date.is_safe = False @register.filter() def obfuscate_email(email, linktext=None, autoescape=None): """ Given a string representing an email address, returns a mailto link with rot13 JavaScript obfuscation. Accepts an optional argument to use as the link text; otherwise uses the email address itself. """ if autoescape: esc = conditional_escape else: esc = lambda x: x email = re.sub('@', '\\\\100', re.sub('\.', '\\\\056', \ esc(email))).encode('rot13') if linktext: linktext = esc(linktext).encode('rot13') else: linktext = email rotten_link = """<script type="text/javascript">document.write \ ("<n uers=\\\"znvygb:%s\\\">%s<\\057n>".replace(/[a-zA-Z]/g, \ function(c){return String.fromCharCode((c<="Z"?90:122)>=\ (c=c.charCodeAt(0)+13)?c:c-26);}));</script>""" % (email, linktext) return mark_safe(rotten_link) obfuscate_email.needs_autoescape = True @register.filter_function def split_str(s, args): """ Split a string using the python string split method """ if args: if isinstance(s, str): splitter = args[0] return s.split(splitter) return s return s @register.filter_function def str_basename(s): """ Get the basename using the python basename method """ return basename(s) @register.filter @stringfilter def twitterize(value, autoescape=None): value = strip_tags(value) # Link URLs value = urlize(value, nofollow=False, autoescape=autoescape) # Link twitter usernames for the first person value = re.sub(r'(^[^:]+)', r'<a href="http://twitter.com/\1">\1</a>', value) # Link twitter usernames prefixed with @ value = re.sub(r'(\s+|\A)@([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://twitter.com/\2">@\2</a>', value) # Link hash tags value = re.sub(r'(\s+|\A)#([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>', value) return mark_safe(value) twitterize.is_safe = True twitterize.needs_autoescape = True @register.filter @stringfilter def twitterdate(value): from datetime import datetime, timedelta time = value.replace(" +0000", "") dt = datetime.strptime(time, "%a, %d %b %Y %H:%M:%S") return dt + timedelta(hours=-6) @register.filter def thumbnail(file, size='200x200'): # defining the size x, y = [int(x) for x in size.split('x')] # defining the filename and the miniature filename filehead, filetail = os.path.split(file.name) basename, format = os.path.splitext(filetail) miniature = basename + '_' + size + format filename = file.name miniature_filename = os.path.join(filehead, miniature) filehead, filetail = os.path.split(file.url) miniature_url = filehead + '/' + miniature thumbnail_exist = False if default_storage.exists(miniature_filename): mt_filename = default_storage.modified_time(filename) mt_miniature_filename = default_storage.modified_time( miniature_filename) if mt_filename > mt_miniature_filename: # remove the miniature default_storage.delete(miniature_filename) else: thumbnail_exist = True # if the image wasn't already resized, resize it if not thumbnail_exist: if not default_storage.exists(filename): return u'' image = Image.open(default_storage.open(filename)) image.thumbnail([x, y], Image.ANTIALIAS) f = default_storage.open(miniature_filename, 'w') image.save(f, image.format, quality=90, optimize=1) f.close() return miniature_url @register.filter_function def datedelta(dt, range_): from datetime import timedelta range_type = 'add' # parse the range if '+' in range_: range_ = range_[1:len(range_)] if '-' in range_: range_type = 'subtract' range_ = range_[1:len(range_)] k, v = range_.split('=') set_range = { str(k): int(v) } # set the date if range_type == 'add': dt = dt + timedelta(**set_range) if range_type == 'subtract': dt = dt - timedelta(**set_range) return dt @register.filter def split(str, splitter): return str.split(splitter) @register.filter def tag_split(str): str = "".join(str) str = str.replace(", ", ",") return str.split(",") @register.filter def make_range(value): try: value = int(value) if value > 0: return range(int(value)) return [] except: return [] @register.filter def underscore_space(value): return value.replace("_", " ") @register.filter def format_string(value, arg): return arg % value @register.filter def md5_gs(value, arg=None): import hashlib from datetime import datetime, timedelta hashdt = '' if arg and int(arg): timestamp = datetime.now() + timedelta(hours=int(arg)) hashdt = hashlib.md5(timestamp.strftime("%Y;%m;%d;%H;%M").replace(';0', ';')).hexdigest() return ''.join([value, hashdt]) @register.filter def multiply(value, arg): return Decimal(str(value)) * Decimal(str(arg)) @register.filter def add_decimal(value, arg): return Decimal(str(value)) + Decimal(str(arg)) @register.filter def phonenumber(value): if value: # split number from extension or any text x = re.split(r'([a-zA-Z]+)', value) # clean number y = ''.join(i for i in x[0] if i.isdigit()) if len(y) > 10: # has country code code = y[:len(y)-10] number = y[len(y)-10:] if code == '1': number = "(%s) %s-%s" %(number[:3], number[3:6], number[6:]) else: number = "+%s %s %s %s" %(code, number[:3], number[3:6], number[6:]) else: # no country code number = "(%s) %s-%s" %(y[:3], y[3:6], y[6:]) # attach additional text extension ext = '' for i in xrange(1, len(x)): ext = ''.join((ext, x[i])) if ext: return ' '.join((number, ext)) else: return number @register.filter def timezone_label(value): try: now = datetime.now(pytz.timezone(value)) tzinfo = now.strftime("%z") return "(GMT%s) %s" %(tzinfo, value) except: return "" @register.filter def field_to_string(value): if isinstance(value, str) or isinstance(value, unicode): return value if isinstance(value, list): if len(value) == 0: return "" if len(value) == 1: return str(value[0]) if len(value) == 2: return "%s and %s" % (value[0], value[1]) return ", ".join(value) return str(value)
return string
conditional_block
myform.py
import random import zope.schema import zope.interface from zope.i18nmessageid import MessageFactory from zope.component import getUtility, getMultiAdapter from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile as Zope3PageTemplateFile from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile as FiveViewPageTemplateFile from Products.CMFCore.utils import getToolByName from Products.CMFCore.interfaces import ISiteRoot from Products.CMFPlone.utils import _createObjectByType from Products.CMFPlone.interfaces.controlpanel import IMailSchema from Products.statusmessages.interfaces import IStatusMessage import z3c.form import plone.z3cform.templates from plone.registry.interfaces import IRegistry from smtplib import SMTPException, SMTPRecipientsRefused from vfu.events import MessageFactory as _ from vfu.events.utils import trusted from vfu.events.registration import IBasicForm class MyForm(z3c.form.form.Form): """ Display event with form """ template = Zope3PageTemplateFile("templates/form.pt") fields = z3c.form.field.Fields(IBasicForm) ignoreContext = True enable_unload_protection = False output = None ### ! fieldeset fields['gender'].widgetFactory = z3c.form.browser.radio.RadioFieldWidget fields['pricing'].widgetFactory = z3c.form.browser.radio.RadioFieldWidget def _redirect(self, target=''): if not target: portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state') target = portal_state.portal_url() self.request.response.redirect(target) @z3c.form.button.buttonAndHandler(_(u"Save"), name='submit') def submit(self, action): data, errors = self.extractData() if errors: self.status = _(u"Please correct errors") return folder = self.context id = str(random.randint(0, 99999999)) new_obj = _createObjectByType("vfu.events.registration", folder, id, lastname = data['lastname'], firstname = data['firstname'], gender = data['gender'], job = data['job'], organization = data['organization'], email = data['email'], phone = data['phone'], street = data['street'], number = data['number'], zipcode = data['zipcode'], city = data['city'], country = data['country'], pricing = data['pricing'], comments = data['comments']) portal = getToolByName(self, 'portal_url').getPortalObject() encoding = portal.getProperty('email_charset', 'utf-8') trusted_template = trusted(portal.registration_email) mail_text = trusted_template( self, charset=encoding, reg_data = new_obj, event = self.context) subject = self.context.translate(_(u"New registration")) m_to = data['email'] ## notify admin about new registration if isinstance(mail_text, unicode):
host = getToolByName(self, 'MailHost') registry = getUtility(IRegistry) mail_settings = registry.forInterface(IMailSchema, prefix='plone') m_from = mail_settings.email_from_address try: host.send(mail_text, m_to, m_from, subject=subject, charset=encoding, immediate=True, msg_type="text/html") except SMTPRecipientsRefused: raise SMTPRecipientsRefused( _(u'Recipient address rejected by server.')) except SMTPException as e: raise(e) IStatusMessage(self.request).add(_(u"Submit complete"), type='info') return self._redirect(target=self.context.absolute_url()) form_frame = plone.z3cform.layout.wrap_form(MyForm, index=FiveViewPageTemplateFile("templates/layout.pt"))
mail_text = mail_text.encode(encoding)
conditional_block
myform.py
import random import zope.schema import zope.interface from zope.i18nmessageid import MessageFactory from zope.component import getUtility, getMultiAdapter from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile as Zope3PageTemplateFile from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile as FiveViewPageTemplateFile from Products.CMFCore.utils import getToolByName from Products.CMFCore.interfaces import ISiteRoot from Products.CMFPlone.utils import _createObjectByType from Products.CMFPlone.interfaces.controlpanel import IMailSchema from Products.statusmessages.interfaces import IStatusMessage import z3c.form import plone.z3cform.templates from plone.registry.interfaces import IRegistry from smtplib import SMTPException, SMTPRecipientsRefused from vfu.events import MessageFactory as _ from vfu.events.utils import trusted from vfu.events.registration import IBasicForm class
(z3c.form.form.Form): """ Display event with form """ template = Zope3PageTemplateFile("templates/form.pt") fields = z3c.form.field.Fields(IBasicForm) ignoreContext = True enable_unload_protection = False output = None ### ! fieldeset fields['gender'].widgetFactory = z3c.form.browser.radio.RadioFieldWidget fields['pricing'].widgetFactory = z3c.form.browser.radio.RadioFieldWidget def _redirect(self, target=''): if not target: portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state') target = portal_state.portal_url() self.request.response.redirect(target) @z3c.form.button.buttonAndHandler(_(u"Save"), name='submit') def submit(self, action): data, errors = self.extractData() if errors: self.status = _(u"Please correct errors") return folder = self.context id = str(random.randint(0, 99999999)) new_obj = _createObjectByType("vfu.events.registration", folder, id, lastname = data['lastname'], firstname = data['firstname'], gender = data['gender'], job = data['job'], organization = data['organization'], email = data['email'], phone = data['phone'], street = data['street'], number = data['number'], zipcode = data['zipcode'], city = data['city'], country = data['country'], pricing = data['pricing'], comments = data['comments']) portal = getToolByName(self, 'portal_url').getPortalObject() encoding = portal.getProperty('email_charset', 'utf-8') trusted_template = trusted(portal.registration_email) mail_text = trusted_template( self, charset=encoding, reg_data = new_obj, event = self.context) subject = self.context.translate(_(u"New registration")) m_to = data['email'] ## notify admin about new registration if isinstance(mail_text, unicode): mail_text = mail_text.encode(encoding) host = getToolByName(self, 'MailHost') registry = getUtility(IRegistry) mail_settings = registry.forInterface(IMailSchema, prefix='plone') m_from = mail_settings.email_from_address try: host.send(mail_text, m_to, m_from, subject=subject, charset=encoding, immediate=True, msg_type="text/html") except SMTPRecipientsRefused: raise SMTPRecipientsRefused( _(u'Recipient address rejected by server.')) except SMTPException as e: raise(e) IStatusMessage(self.request).add(_(u"Submit complete"), type='info') return self._redirect(target=self.context.absolute_url()) form_frame = plone.z3cform.layout.wrap_form(MyForm, index=FiveViewPageTemplateFile("templates/layout.pt"))
MyForm
identifier_name
myform.py
import random import zope.schema import zope.interface from zope.i18nmessageid import MessageFactory
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile as FiveViewPageTemplateFile from Products.CMFCore.utils import getToolByName from Products.CMFCore.interfaces import ISiteRoot from Products.CMFPlone.utils import _createObjectByType from Products.CMFPlone.interfaces.controlpanel import IMailSchema from Products.statusmessages.interfaces import IStatusMessage import z3c.form import plone.z3cform.templates from plone.registry.interfaces import IRegistry from smtplib import SMTPException, SMTPRecipientsRefused from vfu.events import MessageFactory as _ from vfu.events.utils import trusted from vfu.events.registration import IBasicForm class MyForm(z3c.form.form.Form): """ Display event with form """ template = Zope3PageTemplateFile("templates/form.pt") fields = z3c.form.field.Fields(IBasicForm) ignoreContext = True enable_unload_protection = False output = None ### ! fieldeset fields['gender'].widgetFactory = z3c.form.browser.radio.RadioFieldWidget fields['pricing'].widgetFactory = z3c.form.browser.radio.RadioFieldWidget def _redirect(self, target=''): if not target: portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state') target = portal_state.portal_url() self.request.response.redirect(target) @z3c.form.button.buttonAndHandler(_(u"Save"), name='submit') def submit(self, action): data, errors = self.extractData() if errors: self.status = _(u"Please correct errors") return folder = self.context id = str(random.randint(0, 99999999)) new_obj = _createObjectByType("vfu.events.registration", folder, id, lastname = data['lastname'], firstname = data['firstname'], gender = data['gender'], job = data['job'], organization = data['organization'], email = data['email'], phone = data['phone'], street = data['street'], number = data['number'], zipcode = data['zipcode'], city = data['city'], country = data['country'], pricing = data['pricing'], comments = data['comments']) portal = getToolByName(self, 'portal_url').getPortalObject() encoding = portal.getProperty('email_charset', 'utf-8') trusted_template = trusted(portal.registration_email) mail_text = trusted_template( self, charset=encoding, reg_data = new_obj, event = self.context) subject = self.context.translate(_(u"New registration")) m_to = data['email'] ## notify admin about new registration if isinstance(mail_text, unicode): mail_text = mail_text.encode(encoding) host = getToolByName(self, 'MailHost') registry = getUtility(IRegistry) mail_settings = registry.forInterface(IMailSchema, prefix='plone') m_from = mail_settings.email_from_address try: host.send(mail_text, m_to, m_from, subject=subject, charset=encoding, immediate=True, msg_type="text/html") except SMTPRecipientsRefused: raise SMTPRecipientsRefused( _(u'Recipient address rejected by server.')) except SMTPException as e: raise(e) IStatusMessage(self.request).add(_(u"Submit complete"), type='info') return self._redirect(target=self.context.absolute_url()) form_frame = plone.z3cform.layout.wrap_form(MyForm, index=FiveViewPageTemplateFile("templates/layout.pt"))
from zope.component import getUtility, getMultiAdapter from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile as Zope3PageTemplateFile
random_line_split
myform.py
import random import zope.schema import zope.interface from zope.i18nmessageid import MessageFactory from zope.component import getUtility, getMultiAdapter from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile as Zope3PageTemplateFile from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile as FiveViewPageTemplateFile from Products.CMFCore.utils import getToolByName from Products.CMFCore.interfaces import ISiteRoot from Products.CMFPlone.utils import _createObjectByType from Products.CMFPlone.interfaces.controlpanel import IMailSchema from Products.statusmessages.interfaces import IStatusMessage import z3c.form import plone.z3cform.templates from plone.registry.interfaces import IRegistry from smtplib import SMTPException, SMTPRecipientsRefused from vfu.events import MessageFactory as _ from vfu.events.utils import trusted from vfu.events.registration import IBasicForm class MyForm(z3c.form.form.Form): """ Display event with form """ template = Zope3PageTemplateFile("templates/form.pt") fields = z3c.form.field.Fields(IBasicForm) ignoreContext = True enable_unload_protection = False output = None ### ! fieldeset fields['gender'].widgetFactory = z3c.form.browser.radio.RadioFieldWidget fields['pricing'].widgetFactory = z3c.form.browser.radio.RadioFieldWidget def _redirect(self, target=''): if not target: portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state') target = portal_state.portal_url() self.request.response.redirect(target) @z3c.form.button.buttonAndHandler(_(u"Save"), name='submit') def submit(self, action):
form_frame = plone.z3cform.layout.wrap_form(MyForm, index=FiveViewPageTemplateFile("templates/layout.pt"))
data, errors = self.extractData() if errors: self.status = _(u"Please correct errors") return folder = self.context id = str(random.randint(0, 99999999)) new_obj = _createObjectByType("vfu.events.registration", folder, id, lastname = data['lastname'], firstname = data['firstname'], gender = data['gender'], job = data['job'], organization = data['organization'], email = data['email'], phone = data['phone'], street = data['street'], number = data['number'], zipcode = data['zipcode'], city = data['city'], country = data['country'], pricing = data['pricing'], comments = data['comments']) portal = getToolByName(self, 'portal_url').getPortalObject() encoding = portal.getProperty('email_charset', 'utf-8') trusted_template = trusted(portal.registration_email) mail_text = trusted_template( self, charset=encoding, reg_data = new_obj, event = self.context) subject = self.context.translate(_(u"New registration")) m_to = data['email'] ## notify admin about new registration if isinstance(mail_text, unicode): mail_text = mail_text.encode(encoding) host = getToolByName(self, 'MailHost') registry = getUtility(IRegistry) mail_settings = registry.forInterface(IMailSchema, prefix='plone') m_from = mail_settings.email_from_address try: host.send(mail_text, m_to, m_from, subject=subject, charset=encoding, immediate=True, msg_type="text/html") except SMTPRecipientsRefused: raise SMTPRecipientsRefused( _(u'Recipient address rejected by server.')) except SMTPException as e: raise(e) IStatusMessage(self.request).add(_(u"Submit complete"), type='info') return self._redirect(target=self.context.absolute_url())
identifier_body
PrintConfig.js
define(["dojo/_base/declare", "dojo/Deferred", "dojo/promise/all", "dojo/_base/lang", "dojo/_base/array", "esri/arcgis/utils", "esri/lang", "esri/tasks/PrintTemplate", "esri/request" ], function( declare, Deferred, all, lang, array, arcgisUtils, esriLang, PrintTemplate, esriRequest) { return declare(null, { constructor: function(parameters) { lang.mixin(this.printConfig, parameters); }, //********* //Variables //************ //defaultFormat: "pdf", printConfig: { templates: null, layouts: false, legendLayers: [], printi18n: null, format: "pdf", printTaskUrl: null, layoutOptions: { "titleText": null, "scalebarUnit": null, "legendLayers": [] } }, templates: [], legendLayers: [], //optional array of additional search layers to configure from the application config process createPrintOptions: function() { var deferred = new Deferred(); all([ this._buildPrintLayouts(), this._createPrintLegend() ]).then(lang.hitch(this, function(results) { deferred.resolve({ templates: this.templates, legendLayers: this.legendLayers }); })); return deferred.promise; }, _createPrintLegend: function() { var deferred = new Deferred(); var layers = arcgisUtils.getLegendLayers(this.printConfig.legendLayers); this.legendLayers = array.map(layers, function(layer) { return { "layerId": layer.layer.id }; }); deferred.resolve(true); return deferred.promise; }, _buildPrintLayouts: function() { var deferred = new Deferred(); if (this.printConfig.templates) { this.templates = this.printConfig.templates; array.forEach(this.templates, lang.hitch(this, function( template) { if (template.layout === "MAP_ONLY") { template.exportOptions = { width: 670, height: 500, dpi: 96 }; } template.layoutOptions = this.printConfig.layoutOptions; })); deferred.resolve(true); } else if (this.printConfig.layouts) { esriRequest({ url: this.printConfig.printTaskUrl, content: { "f": "json" }, callbackParamName: "callback" }).then(lang.hitch(this, function(response) { var layoutTemplate, templateNames, mapOnlyIndex; layoutTemplate = array.filter(response.parameters, function(param, idx) { return param.name === "Layout_Template"; }); if (layoutTemplate.length === 0) { console.log( "print service parameters name for templates must be \"Layout_Template\"" ); return; } templateNames = layoutTemplate[0].choiceList; // remove the MAP_ONLY template then add it to the end of the list of templates mapOnlyIndex = array.indexOf(templateNames, "MAP_ONLY"); if (mapOnlyIndex > -1) { var mapOnly = templateNames.splice(mapOnlyIndex, mapOnlyIndex + 1)[0]; templateNames.push(mapOnly); } // create a print template for each choice this.templates = array.map(templateNames, lang.hitch( this, function(name) { var plate = new PrintTemplate(); plate.layout = plate.label = name; plate.format = this.printConfig.format; plate.layoutOptions = this.printConfig.layoutOptions; return plate; })); deferred.resolve(true); })); } else
return deferred.promise; } }); });
{ //var letterAnsiAPlate = new PrintTemplate(); // letterAnsiAPlate.layout = "Letter ANSI A Landscape"; var landscapeFormat = new PrintTemplate(); landscapeFormat.layout = "Letter ANSI A Landscape"; landscapeFormat.layoutOptions = this.printConfig.layoutOptions; landscapeFormat.format = this.printConfig.format; landscapeFormat.label = this.printConfig.printi18n.layouts.label1 + " ( " + this.printConfig.format + " )"; var portraitFormat = new PrintTemplate(); portraitFormat.layout = "Letter ANSI A Portrait"; portraitFormat.layoutOptions = this.printConfig.layoutOptions; portraitFormat.format = this.printConfig.format; portraitFormat.label = this.printConfig.printi18n.layouts.label2 + " ( " + this.printConfig.format + " )"; var landscapeImage = new PrintTemplate(); landscapeImage.layout = "Letter ANSI A Landscape"; landscapeImage.layoutOptions = this.printConfig.layoutOptions; landscapeImage.format = "png32"; landscapeImage.label = this.printConfig.printi18n.layouts.label3 + " ( image )"; var portraitImage = new PrintTemplate(); portraitImage.layout = "Letter ANSI A Portrait"; portraitImage.layoutOptions = this.printConfig.layoutOptions; portraitImage.format = "png32"; portraitImage.label = this.printConfig.printi18n.layouts.label4 + " ( image )"; this.templates = [landscapeFormat, portraitFormat, landscapeImage, portraitImage ]; deferred.resolve(true); }
conditional_block
PrintConfig.js
define(["dojo/_base/declare", "dojo/Deferred", "dojo/promise/all", "dojo/_base/lang", "dojo/_base/array", "esri/arcgis/utils", "esri/lang", "esri/tasks/PrintTemplate", "esri/request" ], function( declare, Deferred, all, lang, array, arcgisUtils, esriLang, PrintTemplate, esriRequest) { return declare(null, { constructor: function(parameters) { lang.mixin(this.printConfig, parameters); }, //********* //Variables //************ //defaultFormat: "pdf", printConfig: { templates: null, layouts: false, legendLayers: [], printi18n: null, format: "pdf", printTaskUrl: null, layoutOptions: { "titleText": null, "scalebarUnit": null, "legendLayers": [] } }, templates: [], legendLayers: [], //optional array of additional search layers to configure from the application config process createPrintOptions: function() { var deferred = new Deferred(); all([ this._buildPrintLayouts(), this._createPrintLegend() ]).then(lang.hitch(this, function(results) { deferred.resolve({ templates: this.templates, legendLayers: this.legendLayers }); })); return deferred.promise; }, _createPrintLegend: function() { var deferred = new Deferred(); var layers = arcgisUtils.getLegendLayers(this.printConfig.legendLayers); this.legendLayers = array.map(layers, function(layer) { return { "layerId": layer.layer.id
deferred.resolve(true); return deferred.promise; }, _buildPrintLayouts: function() { var deferred = new Deferred(); if (this.printConfig.templates) { this.templates = this.printConfig.templates; array.forEach(this.templates, lang.hitch(this, function( template) { if (template.layout === "MAP_ONLY") { template.exportOptions = { width: 670, height: 500, dpi: 96 }; } template.layoutOptions = this.printConfig.layoutOptions; })); deferred.resolve(true); } else if (this.printConfig.layouts) { esriRequest({ url: this.printConfig.printTaskUrl, content: { "f": "json" }, callbackParamName: "callback" }).then(lang.hitch(this, function(response) { var layoutTemplate, templateNames, mapOnlyIndex; layoutTemplate = array.filter(response.parameters, function(param, idx) { return param.name === "Layout_Template"; }); if (layoutTemplate.length === 0) { console.log( "print service parameters name for templates must be \"Layout_Template\"" ); return; } templateNames = layoutTemplate[0].choiceList; // remove the MAP_ONLY template then add it to the end of the list of templates mapOnlyIndex = array.indexOf(templateNames, "MAP_ONLY"); if (mapOnlyIndex > -1) { var mapOnly = templateNames.splice(mapOnlyIndex, mapOnlyIndex + 1)[0]; templateNames.push(mapOnly); } // create a print template for each choice this.templates = array.map(templateNames, lang.hitch( this, function(name) { var plate = new PrintTemplate(); plate.layout = plate.label = name; plate.format = this.printConfig.format; plate.layoutOptions = this.printConfig.layoutOptions; return plate; })); deferred.resolve(true); })); } else { //var letterAnsiAPlate = new PrintTemplate(); // letterAnsiAPlate.layout = "Letter ANSI A Landscape"; var landscapeFormat = new PrintTemplate(); landscapeFormat.layout = "Letter ANSI A Landscape"; landscapeFormat.layoutOptions = this.printConfig.layoutOptions; landscapeFormat.format = this.printConfig.format; landscapeFormat.label = this.printConfig.printi18n.layouts.label1 + " ( " + this.printConfig.format + " )"; var portraitFormat = new PrintTemplate(); portraitFormat.layout = "Letter ANSI A Portrait"; portraitFormat.layoutOptions = this.printConfig.layoutOptions; portraitFormat.format = this.printConfig.format; portraitFormat.label = this.printConfig.printi18n.layouts.label2 + " ( " + this.printConfig.format + " )"; var landscapeImage = new PrintTemplate(); landscapeImage.layout = "Letter ANSI A Landscape"; landscapeImage.layoutOptions = this.printConfig.layoutOptions; landscapeImage.format = "png32"; landscapeImage.label = this.printConfig.printi18n.layouts.label3 + " ( image )"; var portraitImage = new PrintTemplate(); portraitImage.layout = "Letter ANSI A Portrait"; portraitImage.layoutOptions = this.printConfig.layoutOptions; portraitImage.format = "png32"; portraitImage.label = this.printConfig.printi18n.layouts.label4 + " ( image )"; this.templates = [landscapeFormat, portraitFormat, landscapeImage, portraitImage ]; deferred.resolve(true); } return deferred.promise; } }); });
}; });
random_line_split
lib.rs
// Copyright 2015 Ted Mielczarek. See the COPYRIGHT // file at the top-level directory of this distribution. //! A library for working with [Google Breakpad][breakpad]'s //! text-format [symbol files][symbolfiles]. //! //! The highest-level API provided by this crate is to use the //! [`Symbolizer`][symbolizer] struct. //! //! [breakpad]: https://chromium.googlesource.com/breakpad/breakpad/+/master/ //! [symbolfiles]: https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md //! [symbolizer]: struct.Symbolizer.html //! //! # Examples //! //! ``` //! # std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")); //! use breakpad_symbols::{SimpleSymbolSupplier,Symbolizer,SimpleFrame,SimpleModule}; //! use std::path::PathBuf; //! let paths = vec!(PathBuf::from("../testdata/symbols/")); //! let supplier = SimpleSymbolSupplier::new(paths); //! let symbolizer = Symbolizer::new(supplier); //! //! // Simple function name lookup with debug file, debug id, address. //! assert_eq!(symbolizer.get_symbol_at_address("test_app.pdb", //! "5A9832E5287241C1838ED98914E9B7FF1", //! 0x1010) //! .unwrap(), //! "vswprintf"); //! ``` use failure::Error; use log::{debug, warn}; use reqwest::blocking::Client; use reqwest::Url; use std::borrow::Cow; use std::boxed::Box; use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; pub use minidump_common::traits::Module; pub use crate::sym_file::{CfiRules, SymbolFile}; mod sym_file; /// A `Module` implementation that holds arbitrary data. /// /// This can be useful for getting symbols for a module when you /// have a debug id and filename but not an actual minidump. If you have a /// minidump, you should be using [`MinidumpModule`][minidumpmodule]. /// /// [minidumpmodule]: ../minidump/struct.MinidumpModule.html #[derive(Default)] pub struct SimpleModule { pub base_address: Option<u64>, pub size: Option<u64>, pub code_file: Option<String>, pub code_identifier: Option<String>, pub debug_file: Option<String>, pub debug_id: Option<String>, pub version: Option<String>, } impl SimpleModule { /// Create a `SimpleModule` with the given `debug_file` and `debug_id`. /// /// Uses `default` for the remaining fields. pub fn new(debug_file: &str, debug_id: &str) -> SimpleModule { SimpleModule { debug_file: Some(String::from(debug_file)), debug_id: Some(String::from(debug_id)), ..SimpleModule::default() } } } impl Module for SimpleModule { fn base_address(&self) -> u64 { self.base_address.unwrap_or(0) } fn size(&self) -> u64 { self.size.unwrap_or(0) } fn code_file(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn debug_file(&self) -> Option<Cow<str>> { self.debug_file.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn debug_identifier(&self) -> Option<Cow<str>> { self.debug_id.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn version(&self) -> Option<Cow<str>> { self.version.as_ref().map(|s| Cow::Borrowed(&s[..])) } } /// Like `PathBuf::file_name`, but try to work on Windows or POSIX-style paths. fn leafname(path: &str) -> &str { path.rsplit(|c| c == '/' || c == '\\') .next() .unwrap_or(path) } /// If `filename` ends with `match_extension`, remove it. Append `new_extension` to the result. fn replace_or_add_extension(filename: &str, match_extension: &str, new_extension: &str) -> String { let mut bits = filename.split('.').collect::<Vec<_>>(); if bits.len() > 1 && bits .last() .map_or(false, |e| e.to_lowercase() == match_extension) { bits.pop(); } bits.push(new_extension); bits.join(".") } /// Get a relative symbol path at which to locate symbols for `module`. /// /// Symbols are generally stored in the layout used by Microsoft's symbol /// server and associated tools: /// `<debug filename>/<debug identifier>/<debug filename>.sym`. If /// `debug filename` ends with *.pdb* the leaf filename will have that /// removed. /// `extension` is the expected extension for the symbol filename, generally /// *sym* if Breakpad text format symbols are expected. /// /// The debug filename and debug identifier can be found in the /// [first line][module_line] of the symbol file output by the dump_syms tool. /// You can use [this script][packagesymbols] to run dump_syms and put the /// resulting symbol files in the proper directory structure. /// /// [module_line]: https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md#MODULE-records /// [packagesymbols]: https://gist.github.com/luser/2ad32d290f224782fcfc#file-packagesymbols-py pub fn relative_symbol_path(module: &dyn Module, extension: &str) -> Option<String> { module.debug_file().and_then(|debug_file| { module.debug_identifier().map(|debug_id| { // Can't use PathBuf::file_name here, it doesn't handle // Windows file paths on non-Windows. let leaf = leafname(&debug_file); let filename = replace_or_add_extension(leaf, "pdb", extension); [leaf, &debug_id[..], &filename[..]].join("/") }) }) } /// Possible results of locating symbols. #[derive(Debug)] pub enum SymbolResult { /// Symbols loaded successfully. Ok(SymbolFile), /// Symbol file could not be found. NotFound, /// Error loading symbol file. LoadError(Error), } impl PartialEq for SymbolResult { fn eq(&self, other: &SymbolResult) -> bool
} impl fmt::Display for SymbolResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SymbolResult::Ok(_) => write!(f, "Ok"), SymbolResult::NotFound => write!(f, "Not found"), SymbolResult::LoadError(ref e) => write!(f, "Load error: {}", e), } } } /// A trait for things that can locate symbols for a given module. pub trait SymbolSupplier { /// Locate and load a symbol file for `module`. /// /// Implementations may use any strategy for locating and loading /// symbols. fn locate_symbols(&self, module: &dyn Module) -> SymbolResult; } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from local disk /// paths. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct SimpleSymbolSupplier { /// Local disk paths in which to search for symbols. paths: Vec<PathBuf>, } impl SimpleSymbolSupplier { /// Instantiate a new `SimpleSymbolSupplier` that will search in `paths`. pub fn new(paths: Vec<PathBuf>) -> SimpleSymbolSupplier { SimpleSymbolSupplier { paths } } } impl SymbolSupplier for SimpleSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref path in self.paths.iter() { let test_path = path.join(&rel_path); if fs::metadata(&test_path).ok().map_or(false, |m| m.is_file()) { return SymbolFile::from_file(&test_path) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } /// A SymbolSupplier that maps module names (code_files) to an in-memory string. /// /// Intended for mocking symbol files in tests. #[derive(Default, Debug, Clone)] pub struct StringSymbolSupplier { modules: HashMap<String, String>, } impl StringSymbolSupplier { /// Make a new StringSymbolSupplier with no modules. pub fn new(modules: HashMap<String, String>) -> Self { Self { modules } } } impl SymbolSupplier for StringSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(symbols) = self.modules.get(&*module.code_file()) { return SymbolFile::from_bytes(symbols.as_bytes()) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } SymbolResult::NotFound } } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from HTTP /// URLs. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct HttpSymbolSupplier { /// HTTP Client to use for fetching symbols. client: Client, /// URLs to search for symbols. urls: Vec<Url>, /// A `SimpleSymbolSupplier` to use for local symbol paths. local: SimpleSymbolSupplier, /// A path at which to cache downloaded symbols. cache: PathBuf, } impl HttpSymbolSupplier { /// Create a new `HttpSymbolSupplier`. /// /// Symbols will be searched for in each of `local_paths` and `cache` first, then via HTTP /// at each of `urls`. If a symbol file is found via HTTP it will be saved under `cache`. pub fn new( urls: Vec<String>, cache: PathBuf, mut local_paths: Vec<PathBuf>, ) -> HttpSymbolSupplier { let client = Client::new(); let urls = urls .into_iter() .filter_map(|mut u| { if !u.ends_with('/') { u.push('/'); } Url::parse(&u).ok() }) .collect(); local_paths.push(cache.clone()); let local = SimpleSymbolSupplier::new(local_paths); HttpSymbolSupplier { client, urls, local, cache, } } } /// Save the data in `contents` to `path`. fn save_contents(contents: &[u8], path: &Path) -> io::Result<()> { let base = path.parent().ok_or_else(|| { io::Error::new(io::ErrorKind::Other, format!("Bad cache path: {:?}", path)) })?; fs::create_dir_all(&base)?; let mut f = File::create(path)?; f.write_all(contents)?; Ok(()) } /// Fetch a symbol file from the URL made by combining `base_url` and `rel_path` using `client`, /// save the file contents under `cache` + `rel_path` and also return them. fn fetch_symbol_file( client: &Client, base_url: &Url, rel_path: &str, cache: &Path, ) -> Result<Vec<u8>, Error> { let url = base_url.join(&rel_path)?; debug!("Trying {}", url); let mut res = client.get(url).send()?.error_for_status()?; let mut buf = vec![]; res.read_to_end(&mut buf)?; let local = cache.join(rel_path); match save_contents(&buf, &local) { Ok(_) => {} Err(e) => warn!("Failed to save symbol file in local disk cache: {}", e), } Ok(buf) } impl SymbolSupplier for HttpSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { // Check local paths first. match self.local.locate_symbols(module) { res @ SymbolResult::Ok(_) | res @ SymbolResult::LoadError(_) => res, SymbolResult::NotFound => { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref url in self.urls.iter() { if let Ok(buf) = fetch_symbol_file(&self.client, url, &rel_path, &self.cache) { return SymbolFile::from_bytes(&buf) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } } } /// A trait for setting symbol information on something like a stack frame. pub trait FrameSymbolizer { /// Get the program counter value for this frame. fn get_instruction(&self) -> u64; /// Set the name, base address, and paramter size of the function in // which this frame is executing. fn set_function(&mut self, name: &str, base: u64, parameter_size: u32); /// Set the source file and (1-based) line number this frame represents. fn set_source_file(&mut self, file: &str, line: u32, base: u64); } pub trait FrameWalker { /// Get the instruction address that we're trying to unwind from. fn get_instruction(&self) -> u64; /// Get the number of bytes the callee's callee's parameters take up /// on the stack (or 0 if unknown/invalid). This is needed for /// STACK WIN unwinding. fn get_grand_callee_parameter_size(&self) -> u32; /// Get a register-sized value stored at this address. fn get_register_at_address(&self, address: u64) -> Option<u64>; /// Get the value of a register from the callee's frame. fn get_callee_register(&self, name: &str) -> Option<u64>; /// Set the value of a register for the caller's frame. fn set_caller_register(&mut self, name: &str, val: u64) -> Option<()>; /// Explicitly mark one of the caller's registers as invalid. fn clear_caller_register(&mut self, name: &str); /// Set whatever registers in the caller should be set based on the cfa (e.g. rsp). fn set_cfa(&mut self, val: u64) -> Option<()>; /// Set whatever registers in the caller should be set based on the return address (e.g. rip). fn set_ra(&mut self, val: u64) -> Option<()>; } /// A simple implementation of `FrameSymbolizer` that just holds data. #[derive(Debug, Default)] pub struct SimpleFrame { /// The program counter value for this frame. pub instruction: u64, /// The name of the function in which the current instruction is executing. pub function: Option<String>, /// The offset of the start of `function` from the module base. pub function_base: Option<u64>, /// The size, in bytes, that this function's parameters take up on the stack. pub parameter_size: Option<u32>, /// The name of the source file in which the current instruction is executing. pub source_file: Option<String>, /// The 1-based index of the line number in `source_file` in which the current instruction is /// executing. pub source_line: Option<u32>, /// The offset of the start of `source_line` from the function base. pub source_line_base: Option<u64>, } impl SimpleFrame { /// Instantiate a `SimpleFrame` with instruction pointer `instruction`. pub fn with_instruction(instruction: u64) -> SimpleFrame { SimpleFrame { instruction, ..SimpleFrame::default() } } } impl FrameSymbolizer for SimpleFrame { fn get_instruction(&self) -> u64 { self.instruction } fn set_function(&mut self, name: &str, base: u64, parameter_size: u32) { self.function = Some(String::from(name)); self.function_base = Some(base); self.parameter_size = Some(parameter_size); } fn set_source_file(&mut self, file: &str, line: u32, base: u64) { self.source_file = Some(String::from(file)); self.source_line = Some(line); self.source_line_base = Some(base); } } // Can't make Module derive Hash, since then it can't be used as a trait // object (because the hash method is generic), so this is a hacky workaround. type ModuleKey = (String, String, Option<String>, Option<String>); /// Helper for deriving a hash key from a `Module` for `Symbolizer`. fn key(module: &dyn Module) -> ModuleKey { ( module.code_file().to_string(), module.code_identifier().to_string(), module.debug_file().map(|s| s.to_string()), module.debug_identifier().map(|s| s.to_string()), ) } /// Symbolicate stack frames. /// /// A `Symbolizer` manages loading symbols and looking up symbols in them /// including caching so that symbols for a given module are only loaded once. /// /// Call [`Symbolizer::new`][new] to instantiate a `Symbolizer`. A Symbolizer /// requires a [`SymbolSupplier`][supplier] to locate symbols. If you have /// symbols on disk in the [customary directory layout][dirlayout], a /// [`SimpleSymbolSupplier`][simple] will work. /// /// Use [`get_symbol_at_address`][get_symbol] or [`fill_symbol`][fill_symbol] to /// do symbol lookup. /// /// [new]: struct.Symbolizer.html#method.new /// [supplier]: trait.SymbolSupplier.html /// [dirlayout]: fn.relative_symbol_path.html /// [simple]: struct.SimpleSymbolSupplier.html /// [get_symbol]: struct.Symbolizer.html#method.get_symbol_at_address /// [fill_symbol]: struct.Symbolizer.html#method.fill_symbol pub struct Symbolizer { /// Symbol supplier for locating symbols. supplier: Box<dyn SymbolSupplier + 'static>, /// Cache of symbol locating results. //TODO: use lru-cache: https://crates.io/crates/lru-cache/ symbols: RefCell<HashMap<ModuleKey, SymbolResult>>, } impl Symbolizer { /// Create a `Symbolizer` that uses `supplier` to locate symbols. pub fn new<T: SymbolSupplier + 'static>(supplier: T) -> Symbolizer { Symbolizer { supplier: Box::new(supplier), symbols: RefCell::new(HashMap::new()), } } /// Helper method for non-minidump-using callers. /// /// Pass `debug_file` and `debug_id` describing a specific module, /// and `address`, a module-relative address, and get back /// a symbol in that module that covers that address, or `None`. /// /// See [the module-level documentation][module] for an example. /// /// [module]: index.html pub fn get_symbol_at_address( &self, debug_file: &str, debug_id: &str, address: u64, ) -> Option<String> { let k = (debug_file, debug_id); let mut frame = SimpleFrame::with_instruction(address); self.fill_symbol(&k, &mut frame); frame.function } /// Fill symbol information in `frame` using the instruction address /// from `frame`, and the module information from `module`. If you're not /// using a minidump module, you can use [`SimpleModule`][simplemodule] and /// [`SimpleFrame`][simpleframe]. /// /// # Examples /// /// ``` /// # std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")); /// use breakpad_symbols::{SimpleSymbolSupplier,Symbolizer,SimpleFrame,SimpleModule}; /// use std::path::PathBuf; /// let paths = vec!(PathBuf::from("../testdata/symbols/")); /// let supplier = SimpleSymbolSupplier::new(paths); /// let symbolizer = Symbolizer::new(supplier); /// let m = SimpleModule::new("test_app.pdb", "5A9832E5287241C1838ED98914E9B7FF1"); /// let mut f = SimpleFrame::with_instruction(0x1010); /// symbolizer.fill_symbol(&m, &mut f); /// assert_eq!(f.function.unwrap(), "vswprintf"); /// assert_eq!(f.source_file.unwrap(), r"c:\program files\microsoft visual studio 8\vc\include\swprintf.inl"); /// assert_eq!(f.source_line.unwrap(), 51); /// ``` /// /// [simplemodule]: struct.SimpleModule.html /// [simpleframe]: struct.SimpleFrame.html pub fn fill_symbol(&self, module: &dyn Module, frame: &mut dyn FrameSymbolizer) { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.fill_symbol(module, frame) } } pub fn walk_frame(&self, module: &dyn Module, walker: &mut dyn FrameWalker) -> Option<()> { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.walk_frame(module, walker) } else { None } } fn ensure_module(&self, module: &dyn Module, k: &ModuleKey) { if !self.symbols.borrow().contains_key(&k) { let res = self.supplier.locate_symbols(module); debug!("locate_symbols for {}: {}", module.code_file(), res); self.symbols.borrow_mut().insert(k.clone(), res); } } } #[test] fn test_leafname() { assert_eq!(leafname("c:\\foo\\bar\\test.pdb"), "test.pdb"); assert_eq!(leafname("c:/foo/bar/test.pdb"), "test.pdb"); assert_eq!(leafname("test.pdb"), "test.pdb"); assert_eq!(leafname("test"), "test"); assert_eq!(leafname("/path/to/test"), "test"); } #[test] fn test_replace_or_add_extension() { assert_eq!( replace_or_add_extension("test.pdb", "pdb", "sym"), "test.sym" ); assert_eq!( replace_or_add_extension("TEST.PDB", "pdb", "sym"), "TEST.sym" ); assert_eq!(replace_or_add_extension("test", "pdb", "sym"), "test.sym"); assert_eq!( replace_or_add_extension("test.x", "pdb", "sym"), "test.x.sym" ); assert_eq!(replace_or_add_extension("", "pdb", "sym"), ".sym"); assert_eq!(replace_or_add_extension("test.x", "x", "y"), "test.y"); } #[cfg(test)] mod test { use super::*; use std::fs; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use tempdir::TempDir; #[test] fn test_relative_symbol_path() { let m = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); let m2 = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m2, "bar").unwrap(), "foo.pdb/abcd1234/foo.bar" ); let m3 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m3, "sym").unwrap(), "foo.xyz/abcd1234/foo.xyz.sym" ); let m4 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m4, "bar").unwrap(), "foo.xyz/abcd1234/foo.xyz.bar" ); let bad = SimpleModule::default(); assert!(relative_symbol_path(&bad, "sym").is_none()); let bad2 = SimpleModule { debug_file: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad2, "sym").is_none()); let bad3 = SimpleModule { debug_id: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad3, "sym").is_none()); } #[test] fn test_relative_symbol_path_abs_paths() { { let m = SimpleModule::new("/path/to/foo.bin", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.bin/abcd1234/foo.bin.sym" ); } { let m = SimpleModule::new("c:/path/to/foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); } { let m = SimpleModule::new("c:\\path\\to\\foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); } } fn mksubdirs(path: &Path, dirs: &[&str]) -> Vec<PathBuf> { dirs.iter() .map(|dir| { let new_path = path.join(dir); fs::create_dir(&new_path).unwrap(); new_path }) .collect() } fn write_symbol_file(path: &Path, contents: &[u8]) { let dir = path.parent().unwrap(); if !fs::metadata(&dir).ok().map_or(false, |m| m.is_dir()) { fs::create_dir_all(&dir).unwrap(); } let mut f = File::create(path).unwrap(); f.write_all(contents).unwrap(); } fn write_good_symbol_file(path: &Path) { write_symbol_file(path, b"MODULE Linux x86 abcd1234 foo\n"); } fn write_bad_symbol_file(path: &Path) { write_symbol_file(path, b"this is not a symbol file\n"); } #[test] fn test_simple_symbol_supplier() { let t = TempDir::new("symtest").unwrap(); let paths = mksubdirs(t.path(), &["one", "two"]); let supplier = SimpleSymbolSupplier::new(paths.clone()); let bad = SimpleModule::default(); assert_eq!(supplier.locate_symbols(&bad), SymbolResult::NotFound); // Try loading symbols for each of two modules in each of the two // search paths. for &(path, file, id, sym) in [ (&paths[0], "foo.pdb", "abcd1234", "foo.pdb/abcd1234/foo.sym"), (&paths[1], "bar.xyz", "ff9900", "bar.xyz/ff9900/bar.xyz.sym"), ] .iter() { let m = SimpleModule::new(file, id); // No symbols present yet. assert_eq!(supplier.locate_symbols(&m), SymbolResult::NotFound); write_good_symbol_file(&path.join(sym)); // Should load OK now that it exists. assert!( matches!(supplier.locate_symbols(&m), SymbolResult::Ok(_)), "{}", format!("Located symbols for {}", sym) ); } // Write a malformed symbol file, verify that it's found but fails to load. let mal = SimpleModule::new("baz.pdb", "ffff0000"); let sym = "baz.pdb/ffff0000/baz.sym"; assert_eq!(supplier.locate_symbols(&mal), SymbolResult::NotFound); write_bad_symbol_file(&paths[0].join(sym)); let res = supplier.locate_symbols(&mal); assert!( matches!(res, SymbolResult::LoadError(_)), "{}", format!("Correctly failed to parse {}, result: {:?}", sym, res) ); } #[test] fn test_symbolizer() { let t = TempDir::new("symtest").unwrap(); let path = t.path(); // TODO: This could really use a MockSupplier let supplier = SimpleSymbolSupplier::new(vec![PathBuf::from(path)]); let symbolizer = Symbolizer::new(supplier); let m1 = SimpleModule::new("foo.pdb", "abcd1234"); write_symbol_file( &path.join("foo.pdb/abcd1234/foo.sym"), b"MODULE Linux x86 abcd1234 foo FILE 1 foo.c FUNC 1000 30 10 some func 1000 30 100 1 ", ); let mut f1 = SimpleFrame::with_instruction(0x1010); symbolizer.fill_symbol(&m1, &mut f1); assert_eq!(f1.function.unwrap(), "some func"); assert_eq!(f1.function_base.unwrap(), 0x1000); assert_eq!(f1.source_file.unwrap(), "foo.c"); assert_eq!(f1.source_line.unwrap(), 100); assert_eq!(f1.source_line_base.unwrap(), 0x1000); assert_eq!( symbolizer .get_symbol_at_address("foo.pdb", "abcd1234", 0x1010) .unwrap(), "some func" ); let m2 = SimpleModule::new("bar.pdb", "ffff0000"); let mut f2 = SimpleFrame::with_instruction(0x1010); // No symbols present, should not find anything. symbolizer.fill_symbol(&m2, &mut f2); assert!(f2.function.is_none()); assert!(f2.function_base.is_none()); assert!(f2.source_file.is_none()); assert!(f2.source_line.is_none()); // Results should be cached. write_symbol_file( &path.join("bar.pdb/ffff0000/bar.sym"), b"MODULE Linux x86 ffff0000 bar FILE 53 bar.c FUNC 1000 30 10 another func 1000 30 7 53 ", ); symbolizer.fill_symbol(&m2, &mut f2); assert!(f2.function.is_none()); assert!(f2.function_base.is_none()); assert!(f2.source_file.is_none()); assert!(f2.source_line.is_none()); // This should also use cached results. assert!(symbolizer .get_symbol_at_address("bar.pdb", "ffff0000", 0x1010) .is_none()); } }
{ match (self, other) { (&SymbolResult::Ok(ref a), &SymbolResult::Ok(ref b)) => a == b, (&SymbolResult::NotFound, &SymbolResult::NotFound) => true, (&SymbolResult::LoadError(_), &SymbolResult::LoadError(_)) => true, _ => false, } }
identifier_body
lib.rs
// Copyright 2015 Ted Mielczarek. See the COPYRIGHT // file at the top-level directory of this distribution. //! A library for working with [Google Breakpad][breakpad]'s //! text-format [symbol files][symbolfiles]. //! //! The highest-level API provided by this crate is to use the //! [`Symbolizer`][symbolizer] struct. //! //! [breakpad]: https://chromium.googlesource.com/breakpad/breakpad/+/master/ //! [symbolfiles]: https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md //! [symbolizer]: struct.Symbolizer.html //! //! # Examples //! //! ``` //! # std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")); //! use breakpad_symbols::{SimpleSymbolSupplier,Symbolizer,SimpleFrame,SimpleModule}; //! use std::path::PathBuf; //! let paths = vec!(PathBuf::from("../testdata/symbols/")); //! let supplier = SimpleSymbolSupplier::new(paths); //! let symbolizer = Symbolizer::new(supplier); //! //! // Simple function name lookup with debug file, debug id, address. //! assert_eq!(symbolizer.get_symbol_at_address("test_app.pdb", //! "5A9832E5287241C1838ED98914E9B7FF1", //! 0x1010) //! .unwrap(), //! "vswprintf"); //! ``` use failure::Error; use log::{debug, warn}; use reqwest::blocking::Client; use reqwest::Url; use std::borrow::Cow; use std::boxed::Box; use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; pub use minidump_common::traits::Module; pub use crate::sym_file::{CfiRules, SymbolFile}; mod sym_file; /// A `Module` implementation that holds arbitrary data. /// /// This can be useful for getting symbols for a module when you /// have a debug id and filename but not an actual minidump. If you have a /// minidump, you should be using [`MinidumpModule`][minidumpmodule]. /// /// [minidumpmodule]: ../minidump/struct.MinidumpModule.html #[derive(Default)] pub struct SimpleModule { pub base_address: Option<u64>, pub size: Option<u64>, pub code_file: Option<String>, pub code_identifier: Option<String>, pub debug_file: Option<String>, pub debug_id: Option<String>, pub version: Option<String>, } impl SimpleModule { /// Create a `SimpleModule` with the given `debug_file` and `debug_id`. /// /// Uses `default` for the remaining fields. pub fn new(debug_file: &str, debug_id: &str) -> SimpleModule { SimpleModule { debug_file: Some(String::from(debug_file)), debug_id: Some(String::from(debug_id)), ..SimpleModule::default() } } } impl Module for SimpleModule { fn base_address(&self) -> u64 { self.base_address.unwrap_or(0) } fn size(&self) -> u64 { self.size.unwrap_or(0) } fn code_file(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn debug_file(&self) -> Option<Cow<str>> { self.debug_file.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn debug_identifier(&self) -> Option<Cow<str>> { self.debug_id.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn version(&self) -> Option<Cow<str>> { self.version.as_ref().map(|s| Cow::Borrowed(&s[..])) } } /// Like `PathBuf::file_name`, but try to work on Windows or POSIX-style paths. fn leafname(path: &str) -> &str { path.rsplit(|c| c == '/' || c == '\\') .next() .unwrap_or(path) } /// If `filename` ends with `match_extension`, remove it. Append `new_extension` to the result. fn replace_or_add_extension(filename: &str, match_extension: &str, new_extension: &str) -> String { let mut bits = filename.split('.').collect::<Vec<_>>(); if bits.len() > 1 && bits .last() .map_or(false, |e| e.to_lowercase() == match_extension) { bits.pop(); } bits.push(new_extension); bits.join(".") } /// Get a relative symbol path at which to locate symbols for `module`. /// /// Symbols are generally stored in the layout used by Microsoft's symbol /// server and associated tools: /// `<debug filename>/<debug identifier>/<debug filename>.sym`. If /// `debug filename` ends with *.pdb* the leaf filename will have that /// removed. /// `extension` is the expected extension for the symbol filename, generally /// *sym* if Breakpad text format symbols are expected. /// /// The debug filename and debug identifier can be found in the /// [first line][module_line] of the symbol file output by the dump_syms tool. /// You can use [this script][packagesymbols] to run dump_syms and put the /// resulting symbol files in the proper directory structure. /// /// [module_line]: https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md#MODULE-records /// [packagesymbols]: https://gist.github.com/luser/2ad32d290f224782fcfc#file-packagesymbols-py pub fn relative_symbol_path(module: &dyn Module, extension: &str) -> Option<String> { module.debug_file().and_then(|debug_file| { module.debug_identifier().map(|debug_id| { // Can't use PathBuf::file_name here, it doesn't handle // Windows file paths on non-Windows. let leaf = leafname(&debug_file); let filename = replace_or_add_extension(leaf, "pdb", extension); [leaf, &debug_id[..], &filename[..]].join("/") }) }) } /// Possible results of locating symbols. #[derive(Debug)] pub enum SymbolResult { /// Symbols loaded successfully. Ok(SymbolFile), /// Symbol file could not be found. NotFound, /// Error loading symbol file. LoadError(Error), } impl PartialEq for SymbolResult { fn eq(&self, other: &SymbolResult) -> bool { match (self, other) { (&SymbolResult::Ok(ref a), &SymbolResult::Ok(ref b)) => a == b, (&SymbolResult::NotFound, &SymbolResult::NotFound) => true, (&SymbolResult::LoadError(_), &SymbolResult::LoadError(_)) => true, _ => false, } } } impl fmt::Display for SymbolResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SymbolResult::Ok(_) => write!(f, "Ok"), SymbolResult::NotFound => write!(f, "Not found"), SymbolResult::LoadError(ref e) => write!(f, "Load error: {}", e), } } } /// A trait for things that can locate symbols for a given module. pub trait SymbolSupplier { /// Locate and load a symbol file for `module`. /// /// Implementations may use any strategy for locating and loading /// symbols. fn locate_symbols(&self, module: &dyn Module) -> SymbolResult; } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from local disk /// paths. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct SimpleSymbolSupplier { /// Local disk paths in which to search for symbols. paths: Vec<PathBuf>, } impl SimpleSymbolSupplier { /// Instantiate a new `SimpleSymbolSupplier` that will search in `paths`. pub fn new(paths: Vec<PathBuf>) -> SimpleSymbolSupplier { SimpleSymbolSupplier { paths } } } impl SymbolSupplier for SimpleSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref path in self.paths.iter() { let test_path = path.join(&rel_path); if fs::metadata(&test_path).ok().map_or(false, |m| m.is_file()) { return SymbolFile::from_file(&test_path) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } /// A SymbolSupplier that maps module names (code_files) to an in-memory string. /// /// Intended for mocking symbol files in tests. #[derive(Default, Debug, Clone)] pub struct StringSymbolSupplier { modules: HashMap<String, String>, } impl StringSymbolSupplier { /// Make a new StringSymbolSupplier with no modules. pub fn new(modules: HashMap<String, String>) -> Self { Self { modules } } } impl SymbolSupplier for StringSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(symbols) = self.modules.get(&*module.code_file()) { return SymbolFile::from_bytes(symbols.as_bytes()) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } SymbolResult::NotFound } } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from HTTP /// URLs. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct HttpSymbolSupplier { /// HTTP Client to use for fetching symbols. client: Client, /// URLs to search for symbols. urls: Vec<Url>, /// A `SimpleSymbolSupplier` to use for local symbol paths. local: SimpleSymbolSupplier, /// A path at which to cache downloaded symbols. cache: PathBuf, } impl HttpSymbolSupplier { /// Create a new `HttpSymbolSupplier`. /// /// Symbols will be searched for in each of `local_paths` and `cache` first, then via HTTP /// at each of `urls`. If a symbol file is found via HTTP it will be saved under `cache`. pub fn new( urls: Vec<String>, cache: PathBuf, mut local_paths: Vec<PathBuf>, ) -> HttpSymbolSupplier { let client = Client::new(); let urls = urls .into_iter() .filter_map(|mut u| { if !u.ends_with('/') { u.push('/'); } Url::parse(&u).ok() }) .collect(); local_paths.push(cache.clone()); let local = SimpleSymbolSupplier::new(local_paths); HttpSymbolSupplier { client, urls, local, cache, } } } /// Save the data in `contents` to `path`. fn save_contents(contents: &[u8], path: &Path) -> io::Result<()> { let base = path.parent().ok_or_else(|| { io::Error::new(io::ErrorKind::Other, format!("Bad cache path: {:?}", path)) })?; fs::create_dir_all(&base)?; let mut f = File::create(path)?; f.write_all(contents)?; Ok(()) } /// Fetch a symbol file from the URL made by combining `base_url` and `rel_path` using `client`, /// save the file contents under `cache` + `rel_path` and also return them. fn fetch_symbol_file( client: &Client, base_url: &Url, rel_path: &str, cache: &Path, ) -> Result<Vec<u8>, Error> { let url = base_url.join(&rel_path)?; debug!("Trying {}", url); let mut res = client.get(url).send()?.error_for_status()?; let mut buf = vec![]; res.read_to_end(&mut buf)?; let local = cache.join(rel_path); match save_contents(&buf, &local) { Ok(_) => {} Err(e) => warn!("Failed to save symbol file in local disk cache: {}", e), } Ok(buf) } impl SymbolSupplier for HttpSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { // Check local paths first. match self.local.locate_symbols(module) { res @ SymbolResult::Ok(_) | res @ SymbolResult::LoadError(_) => res, SymbolResult::NotFound => { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref url in self.urls.iter() { if let Ok(buf) = fetch_symbol_file(&self.client, url, &rel_path, &self.cache) { return SymbolFile::from_bytes(&buf) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } } } /// A trait for setting symbol information on something like a stack frame. pub trait FrameSymbolizer { /// Get the program counter value for this frame. fn get_instruction(&self) -> u64; /// Set the name, base address, and paramter size of the function in // which this frame is executing. fn set_function(&mut self, name: &str, base: u64, parameter_size: u32); /// Set the source file and (1-based) line number this frame represents. fn set_source_file(&mut self, file: &str, line: u32, base: u64); } pub trait FrameWalker { /// Get the instruction address that we're trying to unwind from. fn get_instruction(&self) -> u64; /// Get the number of bytes the callee's callee's parameters take up /// on the stack (or 0 if unknown/invalid). This is needed for /// STACK WIN unwinding. fn get_grand_callee_parameter_size(&self) -> u32; /// Get a register-sized value stored at this address. fn get_register_at_address(&self, address: u64) -> Option<u64>; /// Get the value of a register from the callee's frame. fn get_callee_register(&self, name: &str) -> Option<u64>; /// Set the value of a register for the caller's frame. fn set_caller_register(&mut self, name: &str, val: u64) -> Option<()>; /// Explicitly mark one of the caller's registers as invalid. fn clear_caller_register(&mut self, name: &str); /// Set whatever registers in the caller should be set based on the cfa (e.g. rsp). fn set_cfa(&mut self, val: u64) -> Option<()>; /// Set whatever registers in the caller should be set based on the return address (e.g. rip). fn set_ra(&mut self, val: u64) -> Option<()>; } /// A simple implementation of `FrameSymbolizer` that just holds data. #[derive(Debug, Default)] pub struct SimpleFrame { /// The program counter value for this frame. pub instruction: u64, /// The name of the function in which the current instruction is executing. pub function: Option<String>, /// The offset of the start of `function` from the module base. pub function_base: Option<u64>, /// The size, in bytes, that this function's parameters take up on the stack. pub parameter_size: Option<u32>, /// The name of the source file in which the current instruction is executing. pub source_file: Option<String>, /// The 1-based index of the line number in `source_file` in which the current instruction is /// executing. pub source_line: Option<u32>, /// The offset of the start of `source_line` from the function base. pub source_line_base: Option<u64>, } impl SimpleFrame { /// Instantiate a `SimpleFrame` with instruction pointer `instruction`. pub fn with_instruction(instruction: u64) -> SimpleFrame { SimpleFrame { instruction, ..SimpleFrame::default() } } } impl FrameSymbolizer for SimpleFrame { fn get_instruction(&self) -> u64 { self.instruction } fn set_function(&mut self, name: &str, base: u64, parameter_size: u32) { self.function = Some(String::from(name)); self.function_base = Some(base); self.parameter_size = Some(parameter_size); } fn set_source_file(&mut self, file: &str, line: u32, base: u64) { self.source_file = Some(String::from(file)); self.source_line = Some(line); self.source_line_base = Some(base); } } // Can't make Module derive Hash, since then it can't be used as a trait // object (because the hash method is generic), so this is a hacky workaround. type ModuleKey = (String, String, Option<String>, Option<String>); /// Helper for deriving a hash key from a `Module` for `Symbolizer`. fn key(module: &dyn Module) -> ModuleKey { ( module.code_file().to_string(), module.code_identifier().to_string(), module.debug_file().map(|s| s.to_string()), module.debug_identifier().map(|s| s.to_string()), ) } /// Symbolicate stack frames. /// /// A `Symbolizer` manages loading symbols and looking up symbols in them /// including caching so that symbols for a given module are only loaded once. /// /// Call [`Symbolizer::new`][new] to instantiate a `Symbolizer`. A Symbolizer /// requires a [`SymbolSupplier`][supplier] to locate symbols. If you have /// symbols on disk in the [customary directory layout][dirlayout], a /// [`SimpleSymbolSupplier`][simple] will work. /// /// Use [`get_symbol_at_address`][get_symbol] or [`fill_symbol`][fill_symbol] to /// do symbol lookup. /// /// [new]: struct.Symbolizer.html#method.new /// [supplier]: trait.SymbolSupplier.html /// [dirlayout]: fn.relative_symbol_path.html /// [simple]: struct.SimpleSymbolSupplier.html /// [get_symbol]: struct.Symbolizer.html#method.get_symbol_at_address /// [fill_symbol]: struct.Symbolizer.html#method.fill_symbol pub struct Symbolizer { /// Symbol supplier for locating symbols. supplier: Box<dyn SymbolSupplier + 'static>, /// Cache of symbol locating results. //TODO: use lru-cache: https://crates.io/crates/lru-cache/ symbols: RefCell<HashMap<ModuleKey, SymbolResult>>, } impl Symbolizer { /// Create a `Symbolizer` that uses `supplier` to locate symbols. pub fn new<T: SymbolSupplier + 'static>(supplier: T) -> Symbolizer { Symbolizer { supplier: Box::new(supplier), symbols: RefCell::new(HashMap::new()), } } /// Helper method for non-minidump-using callers. /// /// Pass `debug_file` and `debug_id` describing a specific module, /// and `address`, a module-relative address, and get back /// a symbol in that module that covers that address, or `None`. /// /// See [the module-level documentation][module] for an example. /// /// [module]: index.html pub fn get_symbol_at_address( &self, debug_file: &str, debug_id: &str, address: u64, ) -> Option<String> { let k = (debug_file, debug_id); let mut frame = SimpleFrame::with_instruction(address); self.fill_symbol(&k, &mut frame); frame.function } /// Fill symbol information in `frame` using the instruction address /// from `frame`, and the module information from `module`. If you're not /// using a minidump module, you can use [`SimpleModule`][simplemodule] and /// [`SimpleFrame`][simpleframe]. /// /// # Examples /// /// ``` /// # std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")); /// use breakpad_symbols::{SimpleSymbolSupplier,Symbolizer,SimpleFrame,SimpleModule}; /// use std::path::PathBuf; /// let paths = vec!(PathBuf::from("../testdata/symbols/")); /// let supplier = SimpleSymbolSupplier::new(paths); /// let symbolizer = Symbolizer::new(supplier); /// let m = SimpleModule::new("test_app.pdb", "5A9832E5287241C1838ED98914E9B7FF1"); /// let mut f = SimpleFrame::with_instruction(0x1010); /// symbolizer.fill_symbol(&m, &mut f); /// assert_eq!(f.function.unwrap(), "vswprintf");
/// /// [simplemodule]: struct.SimpleModule.html /// [simpleframe]: struct.SimpleFrame.html pub fn fill_symbol(&self, module: &dyn Module, frame: &mut dyn FrameSymbolizer) { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.fill_symbol(module, frame) } } pub fn walk_frame(&self, module: &dyn Module, walker: &mut dyn FrameWalker) -> Option<()> { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.walk_frame(module, walker) } else { None } } fn ensure_module(&self, module: &dyn Module, k: &ModuleKey) { if !self.symbols.borrow().contains_key(&k) { let res = self.supplier.locate_symbols(module); debug!("locate_symbols for {}: {}", module.code_file(), res); self.symbols.borrow_mut().insert(k.clone(), res); } } } #[test] fn test_leafname() { assert_eq!(leafname("c:\\foo\\bar\\test.pdb"), "test.pdb"); assert_eq!(leafname("c:/foo/bar/test.pdb"), "test.pdb"); assert_eq!(leafname("test.pdb"), "test.pdb"); assert_eq!(leafname("test"), "test"); assert_eq!(leafname("/path/to/test"), "test"); } #[test] fn test_replace_or_add_extension() { assert_eq!( replace_or_add_extension("test.pdb", "pdb", "sym"), "test.sym" ); assert_eq!( replace_or_add_extension("TEST.PDB", "pdb", "sym"), "TEST.sym" ); assert_eq!(replace_or_add_extension("test", "pdb", "sym"), "test.sym"); assert_eq!( replace_or_add_extension("test.x", "pdb", "sym"), "test.x.sym" ); assert_eq!(replace_or_add_extension("", "pdb", "sym"), ".sym"); assert_eq!(replace_or_add_extension("test.x", "x", "y"), "test.y"); } #[cfg(test)] mod test { use super::*; use std::fs; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use tempdir::TempDir; #[test] fn test_relative_symbol_path() { let m = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); let m2 = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m2, "bar").unwrap(), "foo.pdb/abcd1234/foo.bar" ); let m3 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m3, "sym").unwrap(), "foo.xyz/abcd1234/foo.xyz.sym" ); let m4 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m4, "bar").unwrap(), "foo.xyz/abcd1234/foo.xyz.bar" ); let bad = SimpleModule::default(); assert!(relative_symbol_path(&bad, "sym").is_none()); let bad2 = SimpleModule { debug_file: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad2, "sym").is_none()); let bad3 = SimpleModule { debug_id: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad3, "sym").is_none()); } #[test] fn test_relative_symbol_path_abs_paths() { { let m = SimpleModule::new("/path/to/foo.bin", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.bin/abcd1234/foo.bin.sym" ); } { let m = SimpleModule::new("c:/path/to/foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); } { let m = SimpleModule::new("c:\\path\\to\\foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); } } fn mksubdirs(path: &Path, dirs: &[&str]) -> Vec<PathBuf> { dirs.iter() .map(|dir| { let new_path = path.join(dir); fs::create_dir(&new_path).unwrap(); new_path }) .collect() } fn write_symbol_file(path: &Path, contents: &[u8]) { let dir = path.parent().unwrap(); if !fs::metadata(&dir).ok().map_or(false, |m| m.is_dir()) { fs::create_dir_all(&dir).unwrap(); } let mut f = File::create(path).unwrap(); f.write_all(contents).unwrap(); } fn write_good_symbol_file(path: &Path) { write_symbol_file(path, b"MODULE Linux x86 abcd1234 foo\n"); } fn write_bad_symbol_file(path: &Path) { write_symbol_file(path, b"this is not a symbol file\n"); } #[test] fn test_simple_symbol_supplier() { let t = TempDir::new("symtest").unwrap(); let paths = mksubdirs(t.path(), &["one", "two"]); let supplier = SimpleSymbolSupplier::new(paths.clone()); let bad = SimpleModule::default(); assert_eq!(supplier.locate_symbols(&bad), SymbolResult::NotFound); // Try loading symbols for each of two modules in each of the two // search paths. for &(path, file, id, sym) in [ (&paths[0], "foo.pdb", "abcd1234", "foo.pdb/abcd1234/foo.sym"), (&paths[1], "bar.xyz", "ff9900", "bar.xyz/ff9900/bar.xyz.sym"), ] .iter() { let m = SimpleModule::new(file, id); // No symbols present yet. assert_eq!(supplier.locate_symbols(&m), SymbolResult::NotFound); write_good_symbol_file(&path.join(sym)); // Should load OK now that it exists. assert!( matches!(supplier.locate_symbols(&m), SymbolResult::Ok(_)), "{}", format!("Located symbols for {}", sym) ); } // Write a malformed symbol file, verify that it's found but fails to load. let mal = SimpleModule::new("baz.pdb", "ffff0000"); let sym = "baz.pdb/ffff0000/baz.sym"; assert_eq!(supplier.locate_symbols(&mal), SymbolResult::NotFound); write_bad_symbol_file(&paths[0].join(sym)); let res = supplier.locate_symbols(&mal); assert!( matches!(res, SymbolResult::LoadError(_)), "{}", format!("Correctly failed to parse {}, result: {:?}", sym, res) ); } #[test] fn test_symbolizer() { let t = TempDir::new("symtest").unwrap(); let path = t.path(); // TODO: This could really use a MockSupplier let supplier = SimpleSymbolSupplier::new(vec![PathBuf::from(path)]); let symbolizer = Symbolizer::new(supplier); let m1 = SimpleModule::new("foo.pdb", "abcd1234"); write_symbol_file( &path.join("foo.pdb/abcd1234/foo.sym"), b"MODULE Linux x86 abcd1234 foo FILE 1 foo.c FUNC 1000 30 10 some func 1000 30 100 1 ", ); let mut f1 = SimpleFrame::with_instruction(0x1010); symbolizer.fill_symbol(&m1, &mut f1); assert_eq!(f1.function.unwrap(), "some func"); assert_eq!(f1.function_base.unwrap(), 0x1000); assert_eq!(f1.source_file.unwrap(), "foo.c"); assert_eq!(f1.source_line.unwrap(), 100); assert_eq!(f1.source_line_base.unwrap(), 0x1000); assert_eq!( symbolizer .get_symbol_at_address("foo.pdb", "abcd1234", 0x1010) .unwrap(), "some func" ); let m2 = SimpleModule::new("bar.pdb", "ffff0000"); let mut f2 = SimpleFrame::with_instruction(0x1010); // No symbols present, should not find anything. symbolizer.fill_symbol(&m2, &mut f2); assert!(f2.function.is_none()); assert!(f2.function_base.is_none()); assert!(f2.source_file.is_none()); assert!(f2.source_line.is_none()); // Results should be cached. write_symbol_file( &path.join("bar.pdb/ffff0000/bar.sym"), b"MODULE Linux x86 ffff0000 bar FILE 53 bar.c FUNC 1000 30 10 another func 1000 30 7 53 ", ); symbolizer.fill_symbol(&m2, &mut f2); assert!(f2.function.is_none()); assert!(f2.function_base.is_none()); assert!(f2.source_file.is_none()); assert!(f2.source_line.is_none()); // This should also use cached results. assert!(symbolizer .get_symbol_at_address("bar.pdb", "ffff0000", 0x1010) .is_none()); } }
/// assert_eq!(f.source_file.unwrap(), r"c:\program files\microsoft visual studio 8\vc\include\swprintf.inl"); /// assert_eq!(f.source_line.unwrap(), 51); /// ```
random_line_split
lib.rs
// Copyright 2015 Ted Mielczarek. See the COPYRIGHT // file at the top-level directory of this distribution. //! A library for working with [Google Breakpad][breakpad]'s //! text-format [symbol files][symbolfiles]. //! //! The highest-level API provided by this crate is to use the //! [`Symbolizer`][symbolizer] struct. //! //! [breakpad]: https://chromium.googlesource.com/breakpad/breakpad/+/master/ //! [symbolfiles]: https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md //! [symbolizer]: struct.Symbolizer.html //! //! # Examples //! //! ``` //! # std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")); //! use breakpad_symbols::{SimpleSymbolSupplier,Symbolizer,SimpleFrame,SimpleModule}; //! use std::path::PathBuf; //! let paths = vec!(PathBuf::from("../testdata/symbols/")); //! let supplier = SimpleSymbolSupplier::new(paths); //! let symbolizer = Symbolizer::new(supplier); //! //! // Simple function name lookup with debug file, debug id, address. //! assert_eq!(symbolizer.get_symbol_at_address("test_app.pdb", //! "5A9832E5287241C1838ED98914E9B7FF1", //! 0x1010) //! .unwrap(), //! "vswprintf"); //! ``` use failure::Error; use log::{debug, warn}; use reqwest::blocking::Client; use reqwest::Url; use std::borrow::Cow; use std::boxed::Box; use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; pub use minidump_common::traits::Module; pub use crate::sym_file::{CfiRules, SymbolFile}; mod sym_file; /// A `Module` implementation that holds arbitrary data. /// /// This can be useful for getting symbols for a module when you /// have a debug id and filename but not an actual minidump. If you have a /// minidump, you should be using [`MinidumpModule`][minidumpmodule]. /// /// [minidumpmodule]: ../minidump/struct.MinidumpModule.html #[derive(Default)] pub struct SimpleModule { pub base_address: Option<u64>, pub size: Option<u64>, pub code_file: Option<String>, pub code_identifier: Option<String>, pub debug_file: Option<String>, pub debug_id: Option<String>, pub version: Option<String>, } impl SimpleModule { /// Create a `SimpleModule` with the given `debug_file` and `debug_id`. /// /// Uses `default` for the remaining fields. pub fn new(debug_file: &str, debug_id: &str) -> SimpleModule { SimpleModule { debug_file: Some(String::from(debug_file)), debug_id: Some(String::from(debug_id)), ..SimpleModule::default() } } } impl Module for SimpleModule { fn base_address(&self) -> u64 { self.base_address.unwrap_or(0) } fn size(&self) -> u64 { self.size.unwrap_or(0) } fn
(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn debug_file(&self) -> Option<Cow<str>> { self.debug_file.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn debug_identifier(&self) -> Option<Cow<str>> { self.debug_id.as_ref().map(|s| Cow::Borrowed(&s[..])) } fn version(&self) -> Option<Cow<str>> { self.version.as_ref().map(|s| Cow::Borrowed(&s[..])) } } /// Like `PathBuf::file_name`, but try to work on Windows or POSIX-style paths. fn leafname(path: &str) -> &str { path.rsplit(|c| c == '/' || c == '\\') .next() .unwrap_or(path) } /// If `filename` ends with `match_extension`, remove it. Append `new_extension` to the result. fn replace_or_add_extension(filename: &str, match_extension: &str, new_extension: &str) -> String { let mut bits = filename.split('.').collect::<Vec<_>>(); if bits.len() > 1 && bits .last() .map_or(false, |e| e.to_lowercase() == match_extension) { bits.pop(); } bits.push(new_extension); bits.join(".") } /// Get a relative symbol path at which to locate symbols for `module`. /// /// Symbols are generally stored in the layout used by Microsoft's symbol /// server and associated tools: /// `<debug filename>/<debug identifier>/<debug filename>.sym`. If /// `debug filename` ends with *.pdb* the leaf filename will have that /// removed. /// `extension` is the expected extension for the symbol filename, generally /// *sym* if Breakpad text format symbols are expected. /// /// The debug filename and debug identifier can be found in the /// [first line][module_line] of the symbol file output by the dump_syms tool. /// You can use [this script][packagesymbols] to run dump_syms and put the /// resulting symbol files in the proper directory structure. /// /// [module_line]: https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md#MODULE-records /// [packagesymbols]: https://gist.github.com/luser/2ad32d290f224782fcfc#file-packagesymbols-py pub fn relative_symbol_path(module: &dyn Module, extension: &str) -> Option<String> { module.debug_file().and_then(|debug_file| { module.debug_identifier().map(|debug_id| { // Can't use PathBuf::file_name here, it doesn't handle // Windows file paths on non-Windows. let leaf = leafname(&debug_file); let filename = replace_or_add_extension(leaf, "pdb", extension); [leaf, &debug_id[..], &filename[..]].join("/") }) }) } /// Possible results of locating symbols. #[derive(Debug)] pub enum SymbolResult { /// Symbols loaded successfully. Ok(SymbolFile), /// Symbol file could not be found. NotFound, /// Error loading symbol file. LoadError(Error), } impl PartialEq for SymbolResult { fn eq(&self, other: &SymbolResult) -> bool { match (self, other) { (&SymbolResult::Ok(ref a), &SymbolResult::Ok(ref b)) => a == b, (&SymbolResult::NotFound, &SymbolResult::NotFound) => true, (&SymbolResult::LoadError(_), &SymbolResult::LoadError(_)) => true, _ => false, } } } impl fmt::Display for SymbolResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SymbolResult::Ok(_) => write!(f, "Ok"), SymbolResult::NotFound => write!(f, "Not found"), SymbolResult::LoadError(ref e) => write!(f, "Load error: {}", e), } } } /// A trait for things that can locate symbols for a given module. pub trait SymbolSupplier { /// Locate and load a symbol file for `module`. /// /// Implementations may use any strategy for locating and loading /// symbols. fn locate_symbols(&self, module: &dyn Module) -> SymbolResult; } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from local disk /// paths. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct SimpleSymbolSupplier { /// Local disk paths in which to search for symbols. paths: Vec<PathBuf>, } impl SimpleSymbolSupplier { /// Instantiate a new `SimpleSymbolSupplier` that will search in `paths`. pub fn new(paths: Vec<PathBuf>) -> SimpleSymbolSupplier { SimpleSymbolSupplier { paths } } } impl SymbolSupplier for SimpleSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref path in self.paths.iter() { let test_path = path.join(&rel_path); if fs::metadata(&test_path).ok().map_or(false, |m| m.is_file()) { return SymbolFile::from_file(&test_path) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } /// A SymbolSupplier that maps module names (code_files) to an in-memory string. /// /// Intended for mocking symbol files in tests. #[derive(Default, Debug, Clone)] pub struct StringSymbolSupplier { modules: HashMap<String, String>, } impl StringSymbolSupplier { /// Make a new StringSymbolSupplier with no modules. pub fn new(modules: HashMap<String, String>) -> Self { Self { modules } } } impl SymbolSupplier for StringSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { if let Some(symbols) = self.modules.get(&*module.code_file()) { return SymbolFile::from_bytes(symbols.as_bytes()) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } SymbolResult::NotFound } } /// An implementation of `SymbolSupplier` that loads Breakpad text-format symbols from HTTP /// URLs. /// /// See [`relative_symbol_path`] for details on how paths are searched. /// /// [`relative_symbol_path`]: fn.relative_symbol_path.html pub struct HttpSymbolSupplier { /// HTTP Client to use for fetching symbols. client: Client, /// URLs to search for symbols. urls: Vec<Url>, /// A `SimpleSymbolSupplier` to use for local symbol paths. local: SimpleSymbolSupplier, /// A path at which to cache downloaded symbols. cache: PathBuf, } impl HttpSymbolSupplier { /// Create a new `HttpSymbolSupplier`. /// /// Symbols will be searched for in each of `local_paths` and `cache` first, then via HTTP /// at each of `urls`. If a symbol file is found via HTTP it will be saved under `cache`. pub fn new( urls: Vec<String>, cache: PathBuf, mut local_paths: Vec<PathBuf>, ) -> HttpSymbolSupplier { let client = Client::new(); let urls = urls .into_iter() .filter_map(|mut u| { if !u.ends_with('/') { u.push('/'); } Url::parse(&u).ok() }) .collect(); local_paths.push(cache.clone()); let local = SimpleSymbolSupplier::new(local_paths); HttpSymbolSupplier { client, urls, local, cache, } } } /// Save the data in `contents` to `path`. fn save_contents(contents: &[u8], path: &Path) -> io::Result<()> { let base = path.parent().ok_or_else(|| { io::Error::new(io::ErrorKind::Other, format!("Bad cache path: {:?}", path)) })?; fs::create_dir_all(&base)?; let mut f = File::create(path)?; f.write_all(contents)?; Ok(()) } /// Fetch a symbol file from the URL made by combining `base_url` and `rel_path` using `client`, /// save the file contents under `cache` + `rel_path` and also return them. fn fetch_symbol_file( client: &Client, base_url: &Url, rel_path: &str, cache: &Path, ) -> Result<Vec<u8>, Error> { let url = base_url.join(&rel_path)?; debug!("Trying {}", url); let mut res = client.get(url).send()?.error_for_status()?; let mut buf = vec![]; res.read_to_end(&mut buf)?; let local = cache.join(rel_path); match save_contents(&buf, &local) { Ok(_) => {} Err(e) => warn!("Failed to save symbol file in local disk cache: {}", e), } Ok(buf) } impl SymbolSupplier for HttpSymbolSupplier { fn locate_symbols(&self, module: &dyn Module) -> SymbolResult { // Check local paths first. match self.local.locate_symbols(module) { res @ SymbolResult::Ok(_) | res @ SymbolResult::LoadError(_) => res, SymbolResult::NotFound => { if let Some(rel_path) = relative_symbol_path(module, "sym") { for ref url in self.urls.iter() { if let Ok(buf) = fetch_symbol_file(&self.client, url, &rel_path, &self.cache) { return SymbolFile::from_bytes(&buf) .map(SymbolResult::Ok) .unwrap_or_else(SymbolResult::LoadError); } } } SymbolResult::NotFound } } } } /// A trait for setting symbol information on something like a stack frame. pub trait FrameSymbolizer { /// Get the program counter value for this frame. fn get_instruction(&self) -> u64; /// Set the name, base address, and paramter size of the function in // which this frame is executing. fn set_function(&mut self, name: &str, base: u64, parameter_size: u32); /// Set the source file and (1-based) line number this frame represents. fn set_source_file(&mut self, file: &str, line: u32, base: u64); } pub trait FrameWalker { /// Get the instruction address that we're trying to unwind from. fn get_instruction(&self) -> u64; /// Get the number of bytes the callee's callee's parameters take up /// on the stack (or 0 if unknown/invalid). This is needed for /// STACK WIN unwinding. fn get_grand_callee_parameter_size(&self) -> u32; /// Get a register-sized value stored at this address. fn get_register_at_address(&self, address: u64) -> Option<u64>; /// Get the value of a register from the callee's frame. fn get_callee_register(&self, name: &str) -> Option<u64>; /// Set the value of a register for the caller's frame. fn set_caller_register(&mut self, name: &str, val: u64) -> Option<()>; /// Explicitly mark one of the caller's registers as invalid. fn clear_caller_register(&mut self, name: &str); /// Set whatever registers in the caller should be set based on the cfa (e.g. rsp). fn set_cfa(&mut self, val: u64) -> Option<()>; /// Set whatever registers in the caller should be set based on the return address (e.g. rip). fn set_ra(&mut self, val: u64) -> Option<()>; } /// A simple implementation of `FrameSymbolizer` that just holds data. #[derive(Debug, Default)] pub struct SimpleFrame { /// The program counter value for this frame. pub instruction: u64, /// The name of the function in which the current instruction is executing. pub function: Option<String>, /// The offset of the start of `function` from the module base. pub function_base: Option<u64>, /// The size, in bytes, that this function's parameters take up on the stack. pub parameter_size: Option<u32>, /// The name of the source file in which the current instruction is executing. pub source_file: Option<String>, /// The 1-based index of the line number in `source_file` in which the current instruction is /// executing. pub source_line: Option<u32>, /// The offset of the start of `source_line` from the function base. pub source_line_base: Option<u64>, } impl SimpleFrame { /// Instantiate a `SimpleFrame` with instruction pointer `instruction`. pub fn with_instruction(instruction: u64) -> SimpleFrame { SimpleFrame { instruction, ..SimpleFrame::default() } } } impl FrameSymbolizer for SimpleFrame { fn get_instruction(&self) -> u64 { self.instruction } fn set_function(&mut self, name: &str, base: u64, parameter_size: u32) { self.function = Some(String::from(name)); self.function_base = Some(base); self.parameter_size = Some(parameter_size); } fn set_source_file(&mut self, file: &str, line: u32, base: u64) { self.source_file = Some(String::from(file)); self.source_line = Some(line); self.source_line_base = Some(base); } } // Can't make Module derive Hash, since then it can't be used as a trait // object (because the hash method is generic), so this is a hacky workaround. type ModuleKey = (String, String, Option<String>, Option<String>); /// Helper for deriving a hash key from a `Module` for `Symbolizer`. fn key(module: &dyn Module) -> ModuleKey { ( module.code_file().to_string(), module.code_identifier().to_string(), module.debug_file().map(|s| s.to_string()), module.debug_identifier().map(|s| s.to_string()), ) } /// Symbolicate stack frames. /// /// A `Symbolizer` manages loading symbols and looking up symbols in them /// including caching so that symbols for a given module are only loaded once. /// /// Call [`Symbolizer::new`][new] to instantiate a `Symbolizer`. A Symbolizer /// requires a [`SymbolSupplier`][supplier] to locate symbols. If you have /// symbols on disk in the [customary directory layout][dirlayout], a /// [`SimpleSymbolSupplier`][simple] will work. /// /// Use [`get_symbol_at_address`][get_symbol] or [`fill_symbol`][fill_symbol] to /// do symbol lookup. /// /// [new]: struct.Symbolizer.html#method.new /// [supplier]: trait.SymbolSupplier.html /// [dirlayout]: fn.relative_symbol_path.html /// [simple]: struct.SimpleSymbolSupplier.html /// [get_symbol]: struct.Symbolizer.html#method.get_symbol_at_address /// [fill_symbol]: struct.Symbolizer.html#method.fill_symbol pub struct Symbolizer { /// Symbol supplier for locating symbols. supplier: Box<dyn SymbolSupplier + 'static>, /// Cache of symbol locating results. //TODO: use lru-cache: https://crates.io/crates/lru-cache/ symbols: RefCell<HashMap<ModuleKey, SymbolResult>>, } impl Symbolizer { /// Create a `Symbolizer` that uses `supplier` to locate symbols. pub fn new<T: SymbolSupplier + 'static>(supplier: T) -> Symbolizer { Symbolizer { supplier: Box::new(supplier), symbols: RefCell::new(HashMap::new()), } } /// Helper method for non-minidump-using callers. /// /// Pass `debug_file` and `debug_id` describing a specific module, /// and `address`, a module-relative address, and get back /// a symbol in that module that covers that address, or `None`. /// /// See [the module-level documentation][module] for an example. /// /// [module]: index.html pub fn get_symbol_at_address( &self, debug_file: &str, debug_id: &str, address: u64, ) -> Option<String> { let k = (debug_file, debug_id); let mut frame = SimpleFrame::with_instruction(address); self.fill_symbol(&k, &mut frame); frame.function } /// Fill symbol information in `frame` using the instruction address /// from `frame`, and the module information from `module`. If you're not /// using a minidump module, you can use [`SimpleModule`][simplemodule] and /// [`SimpleFrame`][simpleframe]. /// /// # Examples /// /// ``` /// # std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")); /// use breakpad_symbols::{SimpleSymbolSupplier,Symbolizer,SimpleFrame,SimpleModule}; /// use std::path::PathBuf; /// let paths = vec!(PathBuf::from("../testdata/symbols/")); /// let supplier = SimpleSymbolSupplier::new(paths); /// let symbolizer = Symbolizer::new(supplier); /// let m = SimpleModule::new("test_app.pdb", "5A9832E5287241C1838ED98914E9B7FF1"); /// let mut f = SimpleFrame::with_instruction(0x1010); /// symbolizer.fill_symbol(&m, &mut f); /// assert_eq!(f.function.unwrap(), "vswprintf"); /// assert_eq!(f.source_file.unwrap(), r"c:\program files\microsoft visual studio 8\vc\include\swprintf.inl"); /// assert_eq!(f.source_line.unwrap(), 51); /// ``` /// /// [simplemodule]: struct.SimpleModule.html /// [simpleframe]: struct.SimpleFrame.html pub fn fill_symbol(&self, module: &dyn Module, frame: &mut dyn FrameSymbolizer) { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.fill_symbol(module, frame) } } pub fn walk_frame(&self, module: &dyn Module, walker: &mut dyn FrameWalker) -> Option<()> { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols.borrow().get(&k) { sym.walk_frame(module, walker) } else { None } } fn ensure_module(&self, module: &dyn Module, k: &ModuleKey) { if !self.symbols.borrow().contains_key(&k) { let res = self.supplier.locate_symbols(module); debug!("locate_symbols for {}: {}", module.code_file(), res); self.symbols.borrow_mut().insert(k.clone(), res); } } } #[test] fn test_leafname() { assert_eq!(leafname("c:\\foo\\bar\\test.pdb"), "test.pdb"); assert_eq!(leafname("c:/foo/bar/test.pdb"), "test.pdb"); assert_eq!(leafname("test.pdb"), "test.pdb"); assert_eq!(leafname("test"), "test"); assert_eq!(leafname("/path/to/test"), "test"); } #[test] fn test_replace_or_add_extension() { assert_eq!( replace_or_add_extension("test.pdb", "pdb", "sym"), "test.sym" ); assert_eq!( replace_or_add_extension("TEST.PDB", "pdb", "sym"), "TEST.sym" ); assert_eq!(replace_or_add_extension("test", "pdb", "sym"), "test.sym"); assert_eq!( replace_or_add_extension("test.x", "pdb", "sym"), "test.x.sym" ); assert_eq!(replace_or_add_extension("", "pdb", "sym"), ".sym"); assert_eq!(replace_or_add_extension("test.x", "x", "y"), "test.y"); } #[cfg(test)] mod test { use super::*; use std::fs; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use tempdir::TempDir; #[test] fn test_relative_symbol_path() { let m = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); let m2 = SimpleModule::new("foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m2, "bar").unwrap(), "foo.pdb/abcd1234/foo.bar" ); let m3 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m3, "sym").unwrap(), "foo.xyz/abcd1234/foo.xyz.sym" ); let m4 = SimpleModule::new("foo.xyz", "abcd1234"); assert_eq!( &relative_symbol_path(&m4, "bar").unwrap(), "foo.xyz/abcd1234/foo.xyz.bar" ); let bad = SimpleModule::default(); assert!(relative_symbol_path(&bad, "sym").is_none()); let bad2 = SimpleModule { debug_file: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad2, "sym").is_none()); let bad3 = SimpleModule { debug_id: Some("foo".to_string()), ..SimpleModule::default() }; assert!(relative_symbol_path(&bad3, "sym").is_none()); } #[test] fn test_relative_symbol_path_abs_paths() { { let m = SimpleModule::new("/path/to/foo.bin", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.bin/abcd1234/foo.bin.sym" ); } { let m = SimpleModule::new("c:/path/to/foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); } { let m = SimpleModule::new("c:\\path\\to\\foo.pdb", "abcd1234"); assert_eq!( &relative_symbol_path(&m, "sym").unwrap(), "foo.pdb/abcd1234/foo.sym" ); } } fn mksubdirs(path: &Path, dirs: &[&str]) -> Vec<PathBuf> { dirs.iter() .map(|dir| { let new_path = path.join(dir); fs::create_dir(&new_path).unwrap(); new_path }) .collect() } fn write_symbol_file(path: &Path, contents: &[u8]) { let dir = path.parent().unwrap(); if !fs::metadata(&dir).ok().map_or(false, |m| m.is_dir()) { fs::create_dir_all(&dir).unwrap(); } let mut f = File::create(path).unwrap(); f.write_all(contents).unwrap(); } fn write_good_symbol_file(path: &Path) { write_symbol_file(path, b"MODULE Linux x86 abcd1234 foo\n"); } fn write_bad_symbol_file(path: &Path) { write_symbol_file(path, b"this is not a symbol file\n"); } #[test] fn test_simple_symbol_supplier() { let t = TempDir::new("symtest").unwrap(); let paths = mksubdirs(t.path(), &["one", "two"]); let supplier = SimpleSymbolSupplier::new(paths.clone()); let bad = SimpleModule::default(); assert_eq!(supplier.locate_symbols(&bad), SymbolResult::NotFound); // Try loading symbols for each of two modules in each of the two // search paths. for &(path, file, id, sym) in [ (&paths[0], "foo.pdb", "abcd1234", "foo.pdb/abcd1234/foo.sym"), (&paths[1], "bar.xyz", "ff9900", "bar.xyz/ff9900/bar.xyz.sym"), ] .iter() { let m = SimpleModule::new(file, id); // No symbols present yet. assert_eq!(supplier.locate_symbols(&m), SymbolResult::NotFound); write_good_symbol_file(&path.join(sym)); // Should load OK now that it exists. assert!( matches!(supplier.locate_symbols(&m), SymbolResult::Ok(_)), "{}", format!("Located symbols for {}", sym) ); } // Write a malformed symbol file, verify that it's found but fails to load. let mal = SimpleModule::new("baz.pdb", "ffff0000"); let sym = "baz.pdb/ffff0000/baz.sym"; assert_eq!(supplier.locate_symbols(&mal), SymbolResult::NotFound); write_bad_symbol_file(&paths[0].join(sym)); let res = supplier.locate_symbols(&mal); assert!( matches!(res, SymbolResult::LoadError(_)), "{}", format!("Correctly failed to parse {}, result: {:?}", sym, res) ); } #[test] fn test_symbolizer() { let t = TempDir::new("symtest").unwrap(); let path = t.path(); // TODO: This could really use a MockSupplier let supplier = SimpleSymbolSupplier::new(vec![PathBuf::from(path)]); let symbolizer = Symbolizer::new(supplier); let m1 = SimpleModule::new("foo.pdb", "abcd1234"); write_symbol_file( &path.join("foo.pdb/abcd1234/foo.sym"), b"MODULE Linux x86 abcd1234 foo FILE 1 foo.c FUNC 1000 30 10 some func 1000 30 100 1 ", ); let mut f1 = SimpleFrame::with_instruction(0x1010); symbolizer.fill_symbol(&m1, &mut f1); assert_eq!(f1.function.unwrap(), "some func"); assert_eq!(f1.function_base.unwrap(), 0x1000); assert_eq!(f1.source_file.unwrap(), "foo.c"); assert_eq!(f1.source_line.unwrap(), 100); assert_eq!(f1.source_line_base.unwrap(), 0x1000); assert_eq!( symbolizer .get_symbol_at_address("foo.pdb", "abcd1234", 0x1010) .unwrap(), "some func" ); let m2 = SimpleModule::new("bar.pdb", "ffff0000"); let mut f2 = SimpleFrame::with_instruction(0x1010); // No symbols present, should not find anything. symbolizer.fill_symbol(&m2, &mut f2); assert!(f2.function.is_none()); assert!(f2.function_base.is_none()); assert!(f2.source_file.is_none()); assert!(f2.source_line.is_none()); // Results should be cached. write_symbol_file( &path.join("bar.pdb/ffff0000/bar.sym"), b"MODULE Linux x86 ffff0000 bar FILE 53 bar.c FUNC 1000 30 10 another func 1000 30 7 53 ", ); symbolizer.fill_symbol(&m2, &mut f2); assert!(f2.function.is_none()); assert!(f2.function_base.is_none()); assert!(f2.source_file.is_none()); assert!(f2.source_line.is_none()); // This should also use cached results. assert!(symbolizer .get_symbol_at_address("bar.pdb", "ffff0000", 0x1010) .is_none()); } }
code_file
identifier_name
issue-182.ts
import {Connection} from "../../../src/connection/Connection"; import {Post} from "./entity/Post"; import {expect} from "chai"; import {PostStatus} from "./model/PostStatus"; describe("github issues > #182 enums are not saved properly", () => { let connections: Connection[]; before(async () => connections = await createTestingConnections({ entities: [__dirname + "/entity/*{.js,.ts}"], schemaCreate: true, dropSchemaOnConnection: true, enabledDrivers: ["mysql"] // we can properly test lazy-relations only on one platform })); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); it("should persist successfully with enum values", () => Promise.all(connections.map(async connection => { const post1 = new Post(); post1.status = PostStatus.NEW; post1.title = "Hello Post #1"; // persist await connection.entityManager.persist(post1); const loadedPosts1 = await connection.entityManager.findOne(Post, { title: "Hello Post #1" }); expect(loadedPosts1!).not.to.be.empty; loadedPosts1!.should.be.eql({ id: 1, title: "Hello Post #1", status: PostStatus.NEW }); // remove persisted await connection.entityManager.remove(post1); const post2 = new Post(); post2.status = PostStatus.ACTIVE; post2.title = "Hello Post #1"; // persist await connection.entityManager.persist(post2); const loadedPosts2 = await connection.entityManager.findOne(Post, { title: "Hello Post #1" }); expect(loadedPosts2!).not.to.be.empty; loadedPosts2!.should.be.eql({ id: 2, title: "Hello Post #1", status: PostStatus.ACTIVE }); // remove persisted await connection.entityManager.remove(post2); const post3 = new Post(); post3.status = PostStatus.ACHIEVED; post3.title = "Hello Post #1"; // persist await connection.entityManager.persist(post3); const loadedPosts3 = await connection.entityManager.findOne(Post, { title: "Hello Post #1" }); expect(loadedPosts3!).not.to.be.empty; loadedPosts3!.should.be.eql({ id: 3, title: "Hello Post #1", status: PostStatus.ACHIEVED }); // remove persisted await connection.entityManager.remove(post3); }))); });
import "reflect-metadata"; import {createTestingConnections, closeTestingConnections, reloadTestingDatabases} from "../../utils/test-utils";
random_line_split
context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The context within which style is calculated. #![deny(missing_docs)] use animation::{Animation, PropertyAnimation}; use app_units::Au; use bloom::StyleBloom; use data::ElementData; use dom::{OpaqueNode, TNode, TElement, SendElement}; use error_reporting::ParseErrorReporter; use euclid::Size2D; #[cfg(feature = "gecko")] use gecko_bindings::structs; use matching::StyleSharingCandidateCache; use parking_lot::RwLock; #[cfg(feature = "gecko")] use selector_parser::PseudoElement; use selectors::matching::ElementSelectorFlags; use servo_config::opts; use shared_lock::StylesheetGuards; use std::collections::HashMap; use std::env; use std::fmt; use std::ops::Add; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Sender; use stylist::Stylist; use thread_state; use time; use timer::Timer; use traversal::DomTraversal; /// This structure is used to create a local style context from a shared one. pub struct ThreadLocalStyleContextCreationInfo { new_animations_sender: Sender<Animation>, } impl ThreadLocalStyleContextCreationInfo { /// Trivially constructs a `ThreadLocalStyleContextCreationInfo`. pub fn new(animations_sender: Sender<Animation>) -> Self { ThreadLocalStyleContextCreationInfo { new_animations_sender: animations_sender, } } } /// Which quirks mode is this document in. /// /// See: https://quirks.spec.whatwg.org/ #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum QuirksMode { /// Quirks mode. Quirks, /// Limited quirks mode. LimitedQuirks, /// No quirks mode. NoQuirks, } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: Arc<Stylist>, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The animations that are currently running. pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, ///The CSS error reporter for all CSS loaded in this layout thread pub error_reporter: Box<ParseErrorReporter>, /// Data needed to create the thread-local style context from the shared one. pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// The QuirksMode state which the document needs to be rendered with pub quirks_mode: QuirksMode, /// True if the traversal is processing only animation restyles. pub animation_only_restyle: bool, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device.au_viewport_size() } } /// Information about the current element being processed. We group this together /// into a single struct within ThreadLocalStyleContext so that we can instantiate /// and destroy it easily at the beginning and end of element processing. pub struct CurrentElementInfo { /// The element being processed. Currently we use an OpaqueNode since we only /// use this for identity checks, but we could use SendElement if there were /// a good reason to. element: OpaqueNode, /// Whether the element is being styled for the first time. is_initial_style: bool, /// A Vec of possibly expired animations. Used only by Servo. #[allow(dead_code)] pub possibly_expired_animations: Vec<PropertyAnimation>, } /// Statistics gathered during the traversal. We gather statistics on each thread /// and then combine them after the threads join via the Add implementation below. #[derive(Default)] pub struct TraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: Option<bool>, } /// Implementation of Add to aggregate statistics across different threads. impl<'a> Add for &'a TraversalStatistics { type Output = TraversalStatistics; fn add(self, other: Self) -> TraversalStatistics { debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0, "traversal_time_ms should be set at the end by the caller"); TraversalStatistics { elements_traversed: self.elements_traversed + other.elements_traversed, elements_styled: self.elements_styled + other.elements_styled, elements_matched: self.elements_matched + other.elements_matched, styles_shared: self.styles_shared + other.styles_shared, traversal_time_ms: 0.0, is_parallel: None, } } } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!(self.traversal_time_ms != 0.0, "should have set traversal time"); try!(writeln!(f, "[PERF] perf block start")); try!(writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() { "parallel" } else { "sequential" })); try!(writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)); try!(writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)); try!(writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)); try!(writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)); try!(writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)); writeln!(f, "[PERF] perf block end") } } lazy_static! { /// Whether to dump style statistics, computed statically. We use an environmental /// variable so that this is easy to set for Gecko builds, and matches the /// mechanism we use to dump statistics on the Gecko style system. static ref DUMP_STYLE_STATISTICS: bool = { match env::var("DUMP_STYLE_STATISTICS") { Ok(s) => !s.is_empty(), Err(_) => false, } }; } impl TraversalStatistics { /// Returns whether statistics dumping is enabled. pub fn should_dump() -> bool { *DUMP_STYLE_STATISTICS || opts::get().style_sharing_stats } /// Computes the traversal time given the start time in seconds. pub fn finish<E, D>(&mut self, traversal: &D, start: f64) where E: TElement, D: DomTraversal<E>, { self.is_parallel = Some(traversal.is_parallel()); self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of UpdateAnimations. pub flags UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations, /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions, /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties, /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults, } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Sets selector flags. This is used when we need to set flags on an /// element that we don't have exclusive access to (i.e. the parent). SetSelectorFlags(SendElement<E>, ElementSelectorFlags), #[cfg(feature = "gecko")] /// Marks that we need to update CSS animations, update effect properties of /// any type of animations after the normal traversal. UpdateAnimations(SendElement<E>, Option<PseudoElement>, UpdateAnimationsTasks), } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert!(thread_state::get() == thread_state::LAYOUT); match self { SetSelectorFlags(el, flags) => { unsafe { el.set_selector_flags(flags) }; } #[cfg(feature = "gecko")] UpdateAnimations(el, pseudo, tasks) => { unsafe { el.update_animations(pseudo.as_ref(), tasks) }; } } } /// Creates a task to set the selector flags on an element. pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self { use self::SequentialTask::*; SetSelectorFlags(unsafe { SendElement::new(el) }, flags) } #[cfg(feature = "gecko")] /// Creates a task to update various animation state on a given (pseudo-)element. pub fn update_animations(el: E, pseudo: Option<PseudoElement>, tasks: UpdateAnimationsTasks) -> Self { use self::SequentialTask::*; UpdateAnimations(unsafe { SendElement::new(el) }, pseudo, tasks) } } /// A thread-local style context. /// /// This context contains data that needs to be used during restyling, but is /// not required to be unique among worker threads, so we create one per worker /// thread in order to be able to mutate it without locking. pub struct ThreadLocalStyleContext<E: TElement> { /// A cache to share style among siblings. pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>, /// The bloom filter used to fast-reject selector-matching. pub bloom_filter: StyleBloom<E>, /// A channel on which new animations that have been triggered by style /// recalculation can be sent. pub new_animations_sender: Sender<Animation>, /// A set of tasks to be run (on the parent thread) in sequential mode after /// the rest of the styling is complete. This is useful for infrequently-needed /// non-threadsafe operations. pub tasks: Vec<SequentialTask<E>>, /// Statistics about the traversal. pub statistics: TraversalStatistics, /// Information related to the current element, non-None during processing. pub current_element_info: Option<CurrentElementInfo>, } impl<E: TElement> ThreadLocalStyleContext<E> { /// Creates a new `ThreadLocalStyleContext` from a shared one. pub fn
(shared: &SharedStyleContext) -> Self { ThreadLocalStyleContext { style_sharing_candidate_cache: StyleSharingCandidateCache::new(), bloom_filter: StyleBloom::new(), new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(), tasks: Vec::new(), statistics: TraversalStatistics::default(), current_element_info: None, } } /// Notes when the style system starts traversing an element. pub fn begin_element(&mut self, element: E, data: &ElementData) { debug_assert!(self.current_element_info.is_none()); self.current_element_info = Some(CurrentElementInfo { element: element.as_node().opaque(), is_initial_style: !data.has_styles(), possibly_expired_animations: Vec::new(), }); } /// Notes when the style system finishes traversing an element. pub fn end_element(&mut self, element: E) { debug_assert!(self.current_element_info.is_some()); debug_assert!(self.current_element_info.as_ref().unwrap().element == element.as_node().opaque()); self.current_element_info = None; } /// Returns true if the current element being traversed is being styled for /// the first time. /// /// Panics if called while no element is being traversed. pub fn is_initial_style(&self) -> bool { self.current_element_info.as_ref().unwrap().is_initial_style } } impl<E: TElement> Drop for ThreadLocalStyleContext<E> { fn drop(&mut self) { debug_assert!(self.current_element_info.is_none()); // Execute any enqueued sequential tasks. debug_assert!(thread_state::get() == thread_state::LAYOUT); for task in self.tasks.drain(..) { task.execute(); } } } /// A `StyleContext` is just a simple container for a immutable reference to a /// shared style context, and a mutable reference to a local one. pub struct StyleContext<'a, E: TElement + 'a> { /// The shared style context reference. pub shared: &'a SharedStyleContext<'a>, /// The thread-local style context (mutable) reference. pub thread_local: &'a mut ThreadLocalStyleContext<E>, } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, }
new
identifier_name
context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The context within which style is calculated. #![deny(missing_docs)] use animation::{Animation, PropertyAnimation}; use app_units::Au; use bloom::StyleBloom; use data::ElementData; use dom::{OpaqueNode, TNode, TElement, SendElement}; use error_reporting::ParseErrorReporter; use euclid::Size2D; #[cfg(feature = "gecko")] use gecko_bindings::structs; use matching::StyleSharingCandidateCache; use parking_lot::RwLock; #[cfg(feature = "gecko")] use selector_parser::PseudoElement; use selectors::matching::ElementSelectorFlags; use servo_config::opts; use shared_lock::StylesheetGuards; use std::collections::HashMap; use std::env; use std::fmt; use std::ops::Add; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Sender; use stylist::Stylist; use thread_state; use time; use timer::Timer; use traversal::DomTraversal; /// This structure is used to create a local style context from a shared one. pub struct ThreadLocalStyleContextCreationInfo { new_animations_sender: Sender<Animation>, } impl ThreadLocalStyleContextCreationInfo { /// Trivially constructs a `ThreadLocalStyleContextCreationInfo`. pub fn new(animations_sender: Sender<Animation>) -> Self { ThreadLocalStyleContextCreationInfo { new_animations_sender: animations_sender, } } } /// Which quirks mode is this document in. /// /// See: https://quirks.spec.whatwg.org/ #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum QuirksMode { /// Quirks mode. Quirks, /// Limited quirks mode. LimitedQuirks, /// No quirks mode. NoQuirks, } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext<'a> { /// The CSS selector stylist. pub stylist: Arc<Stylist>, /// Guards for pre-acquired locks pub guards: StylesheetGuards<'a>, /// The animations that are currently running. pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired since the last style recalculation. pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>, ///The CSS error reporter for all CSS loaded in this layout thread pub error_reporter: Box<ParseErrorReporter>, /// Data needed to create the thread-local style context from the shared one. pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>, /// The current timer for transitions and animations. This is needed to test /// them. pub timer: Timer, /// The QuirksMode state which the document needs to be rendered with pub quirks_mode: QuirksMode, /// True if the traversal is processing only animation restyles. pub animation_only_restyle: bool, } impl<'a> SharedStyleContext<'a> { /// Return a suitable viewport size in order to be used for viewport units. pub fn viewport_size(&self) -> Size2D<Au> { self.stylist.device.au_viewport_size() } } /// Information about the current element being processed. We group this together /// into a single struct within ThreadLocalStyleContext so that we can instantiate /// and destroy it easily at the beginning and end of element processing. pub struct CurrentElementInfo { /// The element being processed. Currently we use an OpaqueNode since we only /// use this for identity checks, but we could use SendElement if there were /// a good reason to. element: OpaqueNode, /// Whether the element is being styled for the first time. is_initial_style: bool, /// A Vec of possibly expired animations. Used only by Servo. #[allow(dead_code)] pub possibly_expired_animations: Vec<PropertyAnimation>, } /// Statistics gathered during the traversal. We gather statistics on each thread /// and then combine them after the threads join via the Add implementation below. #[derive(Default)] pub struct TraversalStatistics { /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache hits from the StyleSharingCache. pub styles_shared: u32, /// Time spent in the traversal, in milliseconds. pub traversal_time_ms: f64, /// Whether this was a parallel traversal. pub is_parallel: Option<bool>, } /// Implementation of Add to aggregate statistics across different threads. impl<'a> Add for &'a TraversalStatistics { type Output = TraversalStatistics; fn add(self, other: Self) -> TraversalStatistics { debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0, "traversal_time_ms should be set at the end by the caller"); TraversalStatistics { elements_traversed: self.elements_traversed + other.elements_traversed, elements_styled: self.elements_styled + other.elements_styled, elements_matched: self.elements_matched + other.elements_matched, styles_shared: self.styles_shared + other.styles_shared, traversal_time_ms: 0.0, is_parallel: None, } } } /// Format the statistics in a way that the performance test harness understands. /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2 impl fmt::Display for TraversalStatistics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_assert!(self.traversal_time_ms != 0.0, "should have set traversal time"); try!(writeln!(f, "[PERF] perf block start")); try!(writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() { "parallel" } else { "sequential" })); try!(writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)); try!(writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)); try!(writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)); try!(writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)); try!(writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)); writeln!(f, "[PERF] perf block end") } } lazy_static! { /// Whether to dump style statistics, computed statically. We use an environmental /// variable so that this is easy to set for Gecko builds, and matches the /// mechanism we use to dump statistics on the Gecko style system. static ref DUMP_STYLE_STATISTICS: bool = { match env::var("DUMP_STYLE_STATISTICS") { Ok(s) => !s.is_empty(), Err(_) => false, } }; } impl TraversalStatistics { /// Returns whether statistics dumping is enabled. pub fn should_dump() -> bool { *DUMP_STYLE_STATISTICS || opts::get().style_sharing_stats } /// Computes the traversal time given the start time in seconds. pub fn finish<E, D>(&mut self, traversal: &D, start: f64) where E: TElement, D: DomTraversal<E>, { self.is_parallel = Some(traversal.is_parallel()); self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0; } } #[cfg(feature = "gecko")] bitflags! { /// Represents which tasks are performed in a SequentialTask of UpdateAnimations. pub flags UpdateAnimationsTasks: u8 { /// Update CSS Animations. const CSS_ANIMATIONS = structs::UpdateAnimationsTasks_CSSAnimations, /// Update CSS Transitions. const CSS_TRANSITIONS = structs::UpdateAnimationsTasks_CSSTransitions, /// Update effect properties. const EFFECT_PROPERTIES = structs::UpdateAnimationsTasks_EffectProperties, /// Update animation cacade results for animations running on the compositor. const CASCADE_RESULTS = structs::UpdateAnimationsTasks_CascadeResults, } } /// A task to be run in sequential mode on the parent (non-worker) thread. This /// is used by the style system to queue up work which is not safe to do during /// the parallel traversal. pub enum SequentialTask<E: TElement> { /// Sets selector flags. This is used when we need to set flags on an /// element that we don't have exclusive access to (i.e. the parent). SetSelectorFlags(SendElement<E>, ElementSelectorFlags), #[cfg(feature = "gecko")] /// Marks that we need to update CSS animations, update effect properties of /// any type of animations after the normal traversal. UpdateAnimations(SendElement<E>, Option<PseudoElement>, UpdateAnimationsTasks), } impl<E: TElement> SequentialTask<E> { /// Executes this task. pub fn execute(self) { use self::SequentialTask::*; debug_assert!(thread_state::get() == thread_state::LAYOUT); match self { SetSelectorFlags(el, flags) => { unsafe { el.set_selector_flags(flags) }; } #[cfg(feature = "gecko")] UpdateAnimations(el, pseudo, tasks) => { unsafe { el.update_animations(pseudo.as_ref(), tasks) }; } } } /// Creates a task to set the selector flags on an element. pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self { use self::SequentialTask::*; SetSelectorFlags(unsafe { SendElement::new(el) }, flags) } #[cfg(feature = "gecko")] /// Creates a task to update various animation state on a given (pseudo-)element. pub fn update_animations(el: E, pseudo: Option<PseudoElement>, tasks: UpdateAnimationsTasks) -> Self { use self::SequentialTask::*; UpdateAnimations(unsafe { SendElement::new(el) }, pseudo, tasks) } } /// A thread-local style context. /// /// This context contains data that needs to be used during restyling, but is /// not required to be unique among worker threads, so we create one per worker /// thread in order to be able to mutate it without locking. pub struct ThreadLocalStyleContext<E: TElement> { /// A cache to share style among siblings.
/// recalculation can be sent. pub new_animations_sender: Sender<Animation>, /// A set of tasks to be run (on the parent thread) in sequential mode after /// the rest of the styling is complete. This is useful for infrequently-needed /// non-threadsafe operations. pub tasks: Vec<SequentialTask<E>>, /// Statistics about the traversal. pub statistics: TraversalStatistics, /// Information related to the current element, non-None during processing. pub current_element_info: Option<CurrentElementInfo>, } impl<E: TElement> ThreadLocalStyleContext<E> { /// Creates a new `ThreadLocalStyleContext` from a shared one. pub fn new(shared: &SharedStyleContext) -> Self { ThreadLocalStyleContext { style_sharing_candidate_cache: StyleSharingCandidateCache::new(), bloom_filter: StyleBloom::new(), new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(), tasks: Vec::new(), statistics: TraversalStatistics::default(), current_element_info: None, } } /// Notes when the style system starts traversing an element. pub fn begin_element(&mut self, element: E, data: &ElementData) { debug_assert!(self.current_element_info.is_none()); self.current_element_info = Some(CurrentElementInfo { element: element.as_node().opaque(), is_initial_style: !data.has_styles(), possibly_expired_animations: Vec::new(), }); } /// Notes when the style system finishes traversing an element. pub fn end_element(&mut self, element: E) { debug_assert!(self.current_element_info.is_some()); debug_assert!(self.current_element_info.as_ref().unwrap().element == element.as_node().opaque()); self.current_element_info = None; } /// Returns true if the current element being traversed is being styled for /// the first time. /// /// Panics if called while no element is being traversed. pub fn is_initial_style(&self) -> bool { self.current_element_info.as_ref().unwrap().is_initial_style } } impl<E: TElement> Drop for ThreadLocalStyleContext<E> { fn drop(&mut self) { debug_assert!(self.current_element_info.is_none()); // Execute any enqueued sequential tasks. debug_assert!(thread_state::get() == thread_state::LAYOUT); for task in self.tasks.drain(..) { task.execute(); } } } /// A `StyleContext` is just a simple container for a immutable reference to a /// shared style context, and a mutable reference to a local one. pub struct StyleContext<'a, E: TElement + 'a> { /// The shared style context reference. pub shared: &'a SharedStyleContext<'a>, /// The thread-local style context (mutable) reference. pub thread_local: &'a mut ThreadLocalStyleContext<E>, } /// Why we're doing reflow. #[derive(PartialEq, Copy, Clone, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, /// We're reflowing in order to satisfy a script query. No display list will be created. ForScriptQuery, }
pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>, /// The bloom filter used to fast-reject selector-matching. pub bloom_filter: StyleBloom<E>, /// A channel on which new animations that have been triggered by style
random_line_split
markup.ts
/** * A custom Quill highlighting module for markup modes/styles. It manages * multiple mode instances that are used to apply text formatting to the * contents of the control. * * The module is added to the component per the API instructions: * https://quilljs.com/guides/building-a-custom-module/ * * Once the module is initialized the highlighting mode can be changed with * the `set` functions. This just changes what the reference internally to * another class that handles the formatting. * * See the README.md file for an example. * * Note that initial *content* cannot be set in the contructor to the module. * it is overwritten with the contents of the `#editor` div as Quill is * instantiated. It can be set after creation of the Quill instance using * the `.setContent('')` function. * * @module Markup */ const debug = require("debug")("quill-markup.markup"); import {union} from "lodash"; import {getFontList} from "util.fontlist"; import {line as getLine, Section} from "util.section"; import {Quill} from "./helpers"; import {cssHighlights} from "./highlights"; import { Asciidoc, BaseMarkupMode, Markdown, RestructuredText, Text } from "./modes"; export type EventCallback = (val: any) => void; const nilEvent: EventCallback = (val: any): void => { val = val; }; export enum MarkupMode { asciidoc, markdown, restructuredtext, text } export interface MarkupOptions { content?: string; custom?: any; dirtyLimit?: number; fontName?: string; fontSize?: number; followLinks?: boolean; highlight?: string; idleDelay?: number; mode?: MarkupMode; onChange?: EventCallback; onClick?: EventCallback; onClickLink?: EventCallback; } const defaultOptions: MarkupOptions = { content: "", custom: {}, dirtyLimit: 20, fontName: "Fira Code", fontSize: 12, followLinks: false, highlight: "solarized-light", idleDelay: 2000, mode: MarkupMode.text, onChange: nilEvent, onClick: nilEvent, onClickLink: nilEvent }; require("./styles.css"); export class Markup { // As the document is modified the number of characters that are changed // is counted. When a "dirty" limit is reached and the user is idle then // a full rescan of the document block elements will occur. The smaller // the limit, the sooner this will occur when idle. private _dirtyIdle: boolean = false; private _dirtyInline: boolean = false; private _dirtyCount: number = 10; private _dirtyLimit: number; // The time between each incremental section scan private _delay: number = 250; private _changing: boolean = false; // The time before idle detection private _idle: boolean = true; private _idleDelay: number = 2000; private _idleTimer: any; // A reference to the DOM editor node private _editor: HTMLElement; private _fonts: string[] = ["Fira Code", "Inconsolata", "Source Code Pro"]; private _line: Section = { start: 0, end: 0, text: "", multiLine: false }; private _modes: any = {}; private _opts: MarkupOptions; private _paste: boolean = false; private _processor: BaseMarkupMode; private _quill: any; constructor(quill: any, opts: MarkupOptions = {}) { debug("Initializing markup module"); this._quill = quill; this._opts = Object.assign({}, defaultOptions, opts); this._editor = quill.container; debug("quill (local): %o", quill); debug("Quill (global): %o", Quill); debug("Editor id: %s", this.editorKey); this._modes[MarkupMode.asciidoc] = new Asciidoc(quill); this._modes[MarkupMode.markdown] = new Markdown(quill); this._modes[MarkupMode.restructuredtext] = new RestructuredText(quill); this._modes[MarkupMode.text] = new Text(quill); debug("modes: %O", this._modes); this._fonts = union(this._fonts, getFontList()); debug("available fonts: %O", this.fonts); // bind all potential callbacks to the class. [ "handleClick", "handleEditorChange", "handlePaste", "handleTextChange", "resetInactivityTimer", "markIdle", "redo", "refresh", "set", "setBold", "setContent", "setItalic", "setFont", "setFontSize", "setHeader", "setMode", "setMono", "setStrikeThrough", "setUnderline", "undo" ].forEach((fn: string) => { this[fn] = this[fn].bind(this); }); quill.on("editor-change", this.handleEditorChange); quill.on("text-change", this.handleTextChange); this._editor.addEventListener("paste", this.handlePaste); this._editor.addEventListener("click", this.handleClick); window.addEventListener("load", this.resetInactivityTimer); document.addEventListener("mousemove", this.resetInactivityTimer); document.addEventListener("click", this.resetInactivityTimer); document.addEventListener("keydown", this.resetInactivityTimer); this.set(opts); } get editor() { return this._editor; } get editorKey() { return this.quill.container.id; } get fonts() { return this._fonts; } get highlights() { return Object.keys(cssHighlights); } get idle() { return this._idle; } get modes() { return Object.keys(MarkupMode) .map((key) => MarkupMode[key]) .filter((it) => typeof it === "string"); } get opts() { return this._opts; } get quill() { return this._quill; } /** * Resets the idle timer when the user does something in the app. */ private resetInactivityTimer() { this._idle = false; clearTimeout(this._idleTimer); this._idleTimer = setTimeout(this.markIdle, this._idleDelay); } /** * When the user is idle for N seconds this function is called by a global * timer to set a flag and rescan the full document. This can be an * expensive operation and we need to find the tradeoff limit */ private markIdle() { this._idle = true; if (this._dirtyIdle)
if (this._dirtyInline) { this._processor.refreshInline(); this._dirtyInline = false; } } /** * Calls the quill history redo function */ public redo() { if (this._quill.history) { this._quill.history.redo(); } } /** * Rescans the entire document for highlighting. This is a wrapper around * the processor's full refresh function. */ public refresh() { this._processor.refreshFull(); this._dirtyIdle = false; this._dirtyCount = 0; this._dirtyInline = false; } /** * Changes the current highlighting mode and display style. It also sets * the content within control. * @param opts {HighlightOptions} configuration options. `mode` sets the * editing mode. `styling` sets the current display theme. `custom` is * an object that contains custom format colors (for highlights). The * `content` resets the content within the control. If this is null it * is ignored. */ public set(opts: MarkupOptions) { this._opts = Object.assign({}, defaultOptions, this._opts, opts); debug("options: %o", this._opts); this._processor = this._modes[this._opts.mode]; debug("using processor: %o", this._processor); this._dirtyLimit = this._opts.dirtyLimit; this._idleDelay = this._opts.idleDelay; this._processor.style = Object.assign( { foreground: "black", background: "white" }, this._opts.mode === MarkupMode.text ? {} : require("./highlighting.json"), this._opts.custom ); debug("current highlighting colors: %o", this._processor.style); this.setContent(this._opts.content); this.setFont(this._opts.fontName); this.setFontSize(this._opts.fontSize); this.setHighlight(this._opts.highlight); this._editor.style["color"] = this._processor.style.foreground; this._editor.style[ "background-color" ] = this._processor.style.background; this._line = getLine(this._opts.content, 0); this._processor.refreshFull(); } /** * Will call the current processor's bold function to make the current * highlight or word bold. */ public setBold() { this._processor.handleBold(); } /** * Will update the current content of the control with the given * @param content {string} the new content settting for the editor. */ public setContent(content: string) { this._opts.content = content; this._processor.text = content; } /** * Changes the current overall font for the editor. This control works with * mono fonts, so this will set it for all text. The fonts are all defined * in `./lib/fonts`. * @param fontName {string} the name of the font to set. */ public setFont(fontName: string) { if (!this._fonts.includes(fontName)) { fontName = this._fonts[0]; } debug("setting font: %s", fontName); this._opts.fontName = fontName; this._editor.style.fontFamily = fontName; } /** * Changes the current overall size of the fonts within the editor. * @param fontSize {number} the number of pixels in the font sizing. This * will resolve to `##px`. */ public setFontSize(fontSize: number) { debug("setting font size: %spx", fontSize); this._opts.fontSize = fontSize; this._editor.style["font-size"] = `${fontSize}px`; } /** * Calls the processor's current header creation function * @param level {string} the level selected by the user */ public setHeader(level: string) { this._processor.handleHeader(Number(level)); } public setHighlight(name: string) { debug("setting highlight: %s", name); if (name in cssHighlights) { const oldlink = document.getElementById("highlights"); const newlink = document.createElement("link"); newlink.setAttribute("id", "highlights"); newlink.setAttribute("rel", "stylesheet"); newlink.setAttribute("type", "text/css"); newlink.setAttribute("href", cssHighlights[name]); const head = document.getElementsByTagName("head").item(0); if (oldlink) { head.replaceChild(newlink, oldlink); } else { head.appendChild(newlink); } } } /** * Calls the current processor's italic function to make the current * highlight or word italic. */ public setItalic() { this._processor.handleItalic(); } /** * Changes the current display mode for the markup processor * @param mode {string} the name of the mode to set */ public setMode(mode: string) { debug("setting mode: %s", mode); if (!(mode in MarkupMode)) { mode = "text"; } this.set({ content: this._processor.text, mode: MarkupMode[mode] }); } /** * Calls the current processor's mono function to hihglight the current * word/selection. */ public setMono() { this._processor.handleMono(); } /** * Calls the current processor's strikthrough function to highlight the * current word/selection. */ public setStrikeThrough() { this._processor.handleStrikeThrough(); } /** * Calls the current processor's underline function to highlight the * current word/selection. */ public setUnderline() { this._processor.handleUnderline(); } /** * Calls the quill history undo function */ public undo() { if (this._quill.history) { this._quill.history.undo(); } } /** * This event is invoked whenever the mouse is clicked within the editor. * It will call the user give onClick handler and pass the position within * the editor that was clicked. * * If the `followLinks` configuration option is given, then another handler * is called that will check if the clicked position is a link. If it is, * then the regex match object that found this link is returned to the * callback (giving the full text, start/end offsets, and groups). */ private handleClick() { this._opts.onClick(this._processor.pos); if (this._opts.followLinks) { const pos: number = this._processor.pos; for (const it of this._processor.links) { if (pos >= it.link.start && pos <= it.link.end) { this._opts.onClickLink(it.link); break; } } } } /** * This event is invoked whenever a change occurs in the editor (any type). * @param eventName {string} the name of the event that occurred. * @param args {any[]} the dyanamic parameter list passed to this event. */ private handleEditorChange(eventName: string, ...args: any[]) { // debug('handleEditorChange: %s, %o', eventName, args); if (eventName === "selection-change") { const range = args[0]; if (range) { this._processor.range = range; this._processor.pos = range.index; } // Compute the line that will be involved in highlighting this._line = getLine(this._processor.text, this._processor.pos); } } /** * When the user pastes information into the editor, this event is fired */ private handlePaste() { this._paste = true; } /** * Invoked with each change of the content text. * * This will also hold a timer to peform a full scan after N seconds. * Using "sections" to format has a trade off where a block format on * a boundary of a section can lose formatting where the bottom of the * block is seen by the section, but the top is not, so the regex string * will not match within the section. This timer will send a full * range of the document to the processor after N seconds (5 seconds by * default). The timer will only occur when changes occur (so it is * idle if the keyboard is idle) */ private handleTextChange(delta?: any, old?: any, source?: string) { delta = old = delta; // stupid but satifies the linter if (source === "user" && this._dirtyCount++ > this._dirtyLimit) { this._dirtyIdle = true; } this._dirtyInline = true; if (!this._changing || this._paste) { this._changing = true; setTimeout(() => { if (this._paste) { this._processor.refreshFull(); this._paste = false; } else { this._processor.handleChange( this._line.start, this._line.end ); } this._opts.onChange(this._processor.text); this._changing = false; }, this._delay); } } }
{ this._dirtyIdle = false; this._dirtyCount = 0; this._processor.refreshBlock(); }
conditional_block
markup.ts
/** * A custom Quill highlighting module for markup modes/styles. It manages * multiple mode instances that are used to apply text formatting to the * contents of the control. * * The module is added to the component per the API instructions: * https://quilljs.com/guides/building-a-custom-module/ * * Once the module is initialized the highlighting mode can be changed with * the `set` functions. This just changes what the reference internally to * another class that handles the formatting. * * See the README.md file for an example. * * Note that initial *content* cannot be set in the contructor to the module. * it is overwritten with the contents of the `#editor` div as Quill is * instantiated. It can be set after creation of the Quill instance using * the `.setContent('')` function. * * @module Markup */ const debug = require("debug")("quill-markup.markup"); import {union} from "lodash"; import {getFontList} from "util.fontlist"; import {line as getLine, Section} from "util.section"; import {Quill} from "./helpers"; import {cssHighlights} from "./highlights"; import { Asciidoc, BaseMarkupMode, Markdown, RestructuredText, Text } from "./modes"; export type EventCallback = (val: any) => void; const nilEvent: EventCallback = (val: any): void => { val = val; }; export enum MarkupMode { asciidoc, markdown, restructuredtext, text } export interface MarkupOptions { content?: string; custom?: any; dirtyLimit?: number; fontName?: string; fontSize?: number; followLinks?: boolean; highlight?: string; idleDelay?: number; mode?: MarkupMode; onChange?: EventCallback; onClick?: EventCallback; onClickLink?: EventCallback; } const defaultOptions: MarkupOptions = { content: "", custom: {}, dirtyLimit: 20, fontName: "Fira Code", fontSize: 12, followLinks: false, highlight: "solarized-light", idleDelay: 2000, mode: MarkupMode.text, onChange: nilEvent, onClick: nilEvent, onClickLink: nilEvent }; require("./styles.css"); export class Markup { // As the document is modified the number of characters that are changed // is counted. When a "dirty" limit is reached and the user is idle then // a full rescan of the document block elements will occur. The smaller // the limit, the sooner this will occur when idle. private _dirtyIdle: boolean = false; private _dirtyInline: boolean = false; private _dirtyCount: number = 10; private _dirtyLimit: number; // The time between each incremental section scan private _delay: number = 250; private _changing: boolean = false; // The time before idle detection private _idle: boolean = true; private _idleDelay: number = 2000; private _idleTimer: any; // A reference to the DOM editor node private _editor: HTMLElement; private _fonts: string[] = ["Fira Code", "Inconsolata", "Source Code Pro"]; private _line: Section = { start: 0, end: 0, text: "", multiLine: false }; private _modes: any = {}; private _opts: MarkupOptions; private _paste: boolean = false; private _processor: BaseMarkupMode; private _quill: any; constructor(quill: any, opts: MarkupOptions = {}) { debug("Initializing markup module"); this._quill = quill; this._opts = Object.assign({}, defaultOptions, opts); this._editor = quill.container; debug("quill (local): %o", quill); debug("Quill (global): %o", Quill); debug("Editor id: %s", this.editorKey); this._modes[MarkupMode.asciidoc] = new Asciidoc(quill); this._modes[MarkupMode.markdown] = new Markdown(quill); this._modes[MarkupMode.restructuredtext] = new RestructuredText(quill); this._modes[MarkupMode.text] = new Text(quill); debug("modes: %O", this._modes); this._fonts = union(this._fonts, getFontList()); debug("available fonts: %O", this.fonts); // bind all potential callbacks to the class. [ "handleClick", "handleEditorChange", "handlePaste", "handleTextChange", "resetInactivityTimer", "markIdle", "redo", "refresh", "set", "setBold", "setContent", "setItalic", "setFont", "setFontSize", "setHeader", "setMode", "setMono", "setStrikeThrough", "setUnderline", "undo" ].forEach((fn: string) => { this[fn] = this[fn].bind(this); }); quill.on("editor-change", this.handleEditorChange); quill.on("text-change", this.handleTextChange); this._editor.addEventListener("paste", this.handlePaste); this._editor.addEventListener("click", this.handleClick); window.addEventListener("load", this.resetInactivityTimer); document.addEventListener("mousemove", this.resetInactivityTimer); document.addEventListener("click", this.resetInactivityTimer); document.addEventListener("keydown", this.resetInactivityTimer); this.set(opts); } get editor() { return this._editor; } get editorKey() { return this.quill.container.id; } get fonts() { return this._fonts; } get highlights() { return Object.keys(cssHighlights); } get idle() { return this._idle; } get modes() { return Object.keys(MarkupMode) .map((key) => MarkupMode[key]) .filter((it) => typeof it === "string"); } get opts() { return this._opts; } get quill() { return this._quill; } /** * Resets the idle timer when the user does something in the app. */ private resetInactivityTimer() { this._idle = false; clearTimeout(this._idleTimer); this._idleTimer = setTimeout(this.markIdle, this._idleDelay); } /** * When the user is idle for N seconds this function is called by a global * timer to set a flag and rescan the full document. This can be an * expensive operation and we need to find the tradeoff limit */ private markIdle() { this._idle = true; if (this._dirtyIdle) { this._dirtyIdle = false; this._dirtyCount = 0; this._processor.refreshBlock(); } if (this._dirtyInline) { this._processor.refreshInline(); this._dirtyInline = false; } } /** * Calls the quill history redo function */ public redo() { if (this._quill.history) { this._quill.history.redo(); } } /** * Rescans the entire document for highlighting. This is a wrapper around * the processor's full refresh function. */ public refresh() { this._processor.refreshFull(); this._dirtyIdle = false; this._dirtyCount = 0; this._dirtyInline = false; } /** * Changes the current highlighting mode and display style. It also sets * the content within control. * @param opts {HighlightOptions} configuration options. `mode` sets the * editing mode. `styling` sets the current display theme. `custom` is * an object that contains custom format colors (for highlights). The * `content` resets the content within the control. If this is null it * is ignored. */ public set(opts: MarkupOptions) { this._opts = Object.assign({}, defaultOptions, this._opts, opts); debug("options: %o", this._opts); this._processor = this._modes[this._opts.mode]; debug("using processor: %o", this._processor); this._dirtyLimit = this._opts.dirtyLimit; this._idleDelay = this._opts.idleDelay; this._processor.style = Object.assign( { foreground: "black", background: "white" }, this._opts.mode === MarkupMode.text ? {} : require("./highlighting.json"), this._opts.custom ); debug("current highlighting colors: %o", this._processor.style); this.setContent(this._opts.content); this.setFont(this._opts.fontName); this.setFontSize(this._opts.fontSize); this.setHighlight(this._opts.highlight); this._editor.style["color"] = this._processor.style.foreground; this._editor.style[ "background-color" ] = this._processor.style.background; this._line = getLine(this._opts.content, 0); this._processor.refreshFull(); } /** * Will call the current processor's bold function to make the current * highlight or word bold. */ public setBold() { this._processor.handleBold(); } /** * Will update the current content of the control with the given * @param content {string} the new content settting for the editor. */ public setContent(content: string) { this._opts.content = content; this._processor.text = content; } /** * Changes the current overall font for the editor. This control works with * mono fonts, so this will set it for all text. The fonts are all defined * in `./lib/fonts`. * @param fontName {string} the name of the font to set. */ public setFont(fontName: string) { if (!this._fonts.includes(fontName)) { fontName = this._fonts[0]; } debug("setting font: %s", fontName); this._opts.fontName = fontName; this._editor.style.fontFamily = fontName; } /** * Changes the current overall size of the fonts within the editor. * @param fontSize {number} the number of pixels in the font sizing. This * will resolve to `##px`. */ public setFontSize(fontSize: number)
/** * Calls the processor's current header creation function * @param level {string} the level selected by the user */ public setHeader(level: string) { this._processor.handleHeader(Number(level)); } public setHighlight(name: string) { debug("setting highlight: %s", name); if (name in cssHighlights) { const oldlink = document.getElementById("highlights"); const newlink = document.createElement("link"); newlink.setAttribute("id", "highlights"); newlink.setAttribute("rel", "stylesheet"); newlink.setAttribute("type", "text/css"); newlink.setAttribute("href", cssHighlights[name]); const head = document.getElementsByTagName("head").item(0); if (oldlink) { head.replaceChild(newlink, oldlink); } else { head.appendChild(newlink); } } } /** * Calls the current processor's italic function to make the current * highlight or word italic. */ public setItalic() { this._processor.handleItalic(); } /** * Changes the current display mode for the markup processor * @param mode {string} the name of the mode to set */ public setMode(mode: string) { debug("setting mode: %s", mode); if (!(mode in MarkupMode)) { mode = "text"; } this.set({ content: this._processor.text, mode: MarkupMode[mode] }); } /** * Calls the current processor's mono function to hihglight the current * word/selection. */ public setMono() { this._processor.handleMono(); } /** * Calls the current processor's strikthrough function to highlight the * current word/selection. */ public setStrikeThrough() { this._processor.handleStrikeThrough(); } /** * Calls the current processor's underline function to highlight the * current word/selection. */ public setUnderline() { this._processor.handleUnderline(); } /** * Calls the quill history undo function */ public undo() { if (this._quill.history) { this._quill.history.undo(); } } /** * This event is invoked whenever the mouse is clicked within the editor. * It will call the user give onClick handler and pass the position within * the editor that was clicked. * * If the `followLinks` configuration option is given, then another handler * is called that will check if the clicked position is a link. If it is, * then the regex match object that found this link is returned to the * callback (giving the full text, start/end offsets, and groups). */ private handleClick() { this._opts.onClick(this._processor.pos); if (this._opts.followLinks) { const pos: number = this._processor.pos; for (const it of this._processor.links) { if (pos >= it.link.start && pos <= it.link.end) { this._opts.onClickLink(it.link); break; } } } } /** * This event is invoked whenever a change occurs in the editor (any type). * @param eventName {string} the name of the event that occurred. * @param args {any[]} the dyanamic parameter list passed to this event. */ private handleEditorChange(eventName: string, ...args: any[]) { // debug('handleEditorChange: %s, %o', eventName, args); if (eventName === "selection-change") { const range = args[0]; if (range) { this._processor.range = range; this._processor.pos = range.index; } // Compute the line that will be involved in highlighting this._line = getLine(this._processor.text, this._processor.pos); } } /** * When the user pastes information into the editor, this event is fired */ private handlePaste() { this._paste = true; } /** * Invoked with each change of the content text. * * This will also hold a timer to peform a full scan after N seconds. * Using "sections" to format has a trade off where a block format on * a boundary of a section can lose formatting where the bottom of the * block is seen by the section, but the top is not, so the regex string * will not match within the section. This timer will send a full * range of the document to the processor after N seconds (5 seconds by * default). The timer will only occur when changes occur (so it is * idle if the keyboard is idle) */ private handleTextChange(delta?: any, old?: any, source?: string) { delta = old = delta; // stupid but satifies the linter if (source === "user" && this._dirtyCount++ > this._dirtyLimit) { this._dirtyIdle = true; } this._dirtyInline = true; if (!this._changing || this._paste) { this._changing = true; setTimeout(() => { if (this._paste) { this._processor.refreshFull(); this._paste = false; } else { this._processor.handleChange( this._line.start, this._line.end ); } this._opts.onChange(this._processor.text); this._changing = false; }, this._delay); } } }
{ debug("setting font size: %spx", fontSize); this._opts.fontSize = fontSize; this._editor.style["font-size"] = `${fontSize}px`; }
identifier_body
markup.ts
/** * A custom Quill highlighting module for markup modes/styles. It manages * multiple mode instances that are used to apply text formatting to the * contents of the control. * * The module is added to the component per the API instructions: * https://quilljs.com/guides/building-a-custom-module/ * * Once the module is initialized the highlighting mode can be changed with * the `set` functions. This just changes what the reference internally to * another class that handles the formatting. * * See the README.md file for an example. * * Note that initial *content* cannot be set in the contructor to the module. * it is overwritten with the contents of the `#editor` div as Quill is * instantiated. It can be set after creation of the Quill instance using * the `.setContent('')` function. * * @module Markup */ const debug = require("debug")("quill-markup.markup"); import {union} from "lodash"; import {getFontList} from "util.fontlist"; import {line as getLine, Section} from "util.section"; import {Quill} from "./helpers"; import {cssHighlights} from "./highlights"; import { Asciidoc, BaseMarkupMode, Markdown, RestructuredText, Text } from "./modes"; export type EventCallback = (val: any) => void; const nilEvent: EventCallback = (val: any): void => { val = val; }; export enum MarkupMode { asciidoc, markdown, restructuredtext, text } export interface MarkupOptions { content?: string; custom?: any; dirtyLimit?: number; fontName?: string; fontSize?: number; followLinks?: boolean; highlight?: string; idleDelay?: number; mode?: MarkupMode; onChange?: EventCallback; onClick?: EventCallback; onClickLink?: EventCallback; } const defaultOptions: MarkupOptions = { content: "", custom: {}, dirtyLimit: 20, fontName: "Fira Code", fontSize: 12, followLinks: false, highlight: "solarized-light", idleDelay: 2000, mode: MarkupMode.text, onChange: nilEvent, onClick: nilEvent, onClickLink: nilEvent }; require("./styles.css"); export class Markup { // As the document is modified the number of characters that are changed // is counted. When a "dirty" limit is reached and the user is idle then // a full rescan of the document block elements will occur. The smaller // the limit, the sooner this will occur when idle. private _dirtyIdle: boolean = false; private _dirtyInline: boolean = false; private _dirtyCount: number = 10; private _dirtyLimit: number; // The time between each incremental section scan private _delay: number = 250; private _changing: boolean = false; // The time before idle detection private _idle: boolean = true; private _idleDelay: number = 2000; private _idleTimer: any; // A reference to the DOM editor node private _editor: HTMLElement; private _fonts: string[] = ["Fira Code", "Inconsolata", "Source Code Pro"]; private _line: Section = { start: 0, end: 0, text: "", multiLine: false }; private _modes: any = {}; private _opts: MarkupOptions; private _paste: boolean = false; private _processor: BaseMarkupMode; private _quill: any; constructor(quill: any, opts: MarkupOptions = {}) { debug("Initializing markup module"); this._quill = quill; this._opts = Object.assign({}, defaultOptions, opts); this._editor = quill.container; debug("quill (local): %o", quill); debug("Quill (global): %o", Quill); debug("Editor id: %s", this.editorKey); this._modes[MarkupMode.asciidoc] = new Asciidoc(quill); this._modes[MarkupMode.markdown] = new Markdown(quill); this._modes[MarkupMode.restructuredtext] = new RestructuredText(quill); this._modes[MarkupMode.text] = new Text(quill); debug("modes: %O", this._modes); this._fonts = union(this._fonts, getFontList()); debug("available fonts: %O", this.fonts); // bind all potential callbacks to the class. [ "handleClick", "handleEditorChange", "handlePaste", "handleTextChange", "resetInactivityTimer", "markIdle", "redo", "refresh", "set", "setBold", "setContent", "setItalic", "setFont", "setFontSize", "setHeader", "setMode", "setMono", "setStrikeThrough", "setUnderline", "undo" ].forEach((fn: string) => { this[fn] = this[fn].bind(this); }); quill.on("editor-change", this.handleEditorChange); quill.on("text-change", this.handleTextChange); this._editor.addEventListener("paste", this.handlePaste); this._editor.addEventListener("click", this.handleClick); window.addEventListener("load", this.resetInactivityTimer); document.addEventListener("mousemove", this.resetInactivityTimer); document.addEventListener("click", this.resetInactivityTimer); document.addEventListener("keydown", this.resetInactivityTimer); this.set(opts); } get editor() { return this._editor; } get editorKey() { return this.quill.container.id; } get fonts() { return this._fonts; } get highlights() { return Object.keys(cssHighlights); } get idle() { return this._idle; } get modes() { return Object.keys(MarkupMode) .map((key) => MarkupMode[key]) .filter((it) => typeof it === "string"); } get opts() { return this._opts; } get quill() { return this._quill; } /** * Resets the idle timer when the user does something in the app. */ private resetInactivityTimer() { this._idle = false; clearTimeout(this._idleTimer); this._idleTimer = setTimeout(this.markIdle, this._idleDelay); } /** * When the user is idle for N seconds this function is called by a global * timer to set a flag and rescan the full document. This can be an * expensive operation and we need to find the tradeoff limit */ private markIdle() { this._idle = true; if (this._dirtyIdle) { this._dirtyIdle = false; this._dirtyCount = 0; this._processor.refreshBlock(); } if (this._dirtyInline) { this._processor.refreshInline(); this._dirtyInline = false; } } /** * Calls the quill history redo function */ public redo() { if (this._quill.history) { this._quill.history.redo(); } } /** * Rescans the entire document for highlighting. This is a wrapper around * the processor's full refresh function. */ public refresh() { this._processor.refreshFull(); this._dirtyIdle = false; this._dirtyCount = 0; this._dirtyInline = false; } /** * Changes the current highlighting mode and display style. It also sets * the content within control. * @param opts {HighlightOptions} configuration options. `mode` sets the * editing mode. `styling` sets the current display theme. `custom` is * an object that contains custom format colors (for highlights). The * `content` resets the content within the control. If this is null it * is ignored. */ public set(opts: MarkupOptions) { this._opts = Object.assign({}, defaultOptions, this._opts, opts); debug("options: %o", this._opts); this._processor = this._modes[this._opts.mode]; debug("using processor: %o", this._processor); this._dirtyLimit = this._opts.dirtyLimit; this._idleDelay = this._opts.idleDelay; this._processor.style = Object.assign( { foreground: "black", background: "white" }, this._opts.mode === MarkupMode.text ? {} : require("./highlighting.json"), this._opts.custom ); debug("current highlighting colors: %o", this._processor.style); this.setContent(this._opts.content); this.setFont(this._opts.fontName); this.setFontSize(this._opts.fontSize); this.setHighlight(this._opts.highlight); this._editor.style["color"] = this._processor.style.foreground; this._editor.style[ "background-color" ] = this._processor.style.background; this._line = getLine(this._opts.content, 0); this._processor.refreshFull(); } /** * Will call the current processor's bold function to make the current * highlight or word bold. */ public setBold() { this._processor.handleBold(); } /** * Will update the current content of the control with the given * @param content {string} the new content settting for the editor. */ public setContent(content: string) { this._opts.content = content; this._processor.text = content; } /** * Changes the current overall font for the editor. This control works with * mono fonts, so this will set it for all text. The fonts are all defined * in `./lib/fonts`. * @param fontName {string} the name of the font to set. */ public setFont(fontName: string) { if (!this._fonts.includes(fontName)) { fontName = this._fonts[0]; } debug("setting font: %s", fontName); this._opts.fontName = fontName; this._editor.style.fontFamily = fontName; } /** * Changes the current overall size of the fonts within the editor. * @param fontSize {number} the number of pixels in the font sizing. This * will resolve to `##px`. */ public setFontSize(fontSize: number) { debug("setting font size: %spx", fontSize); this._opts.fontSize = fontSize; this._editor.style["font-size"] = `${fontSize}px`; } /** * Calls the processor's current header creation function * @param level {string} the level selected by the user */ public setHeader(level: string) { this._processor.handleHeader(Number(level)); }
const oldlink = document.getElementById("highlights"); const newlink = document.createElement("link"); newlink.setAttribute("id", "highlights"); newlink.setAttribute("rel", "stylesheet"); newlink.setAttribute("type", "text/css"); newlink.setAttribute("href", cssHighlights[name]); const head = document.getElementsByTagName("head").item(0); if (oldlink) { head.replaceChild(newlink, oldlink); } else { head.appendChild(newlink); } } } /** * Calls the current processor's italic function to make the current * highlight or word italic. */ public setItalic() { this._processor.handleItalic(); } /** * Changes the current display mode for the markup processor * @param mode {string} the name of the mode to set */ public setMode(mode: string) { debug("setting mode: %s", mode); if (!(mode in MarkupMode)) { mode = "text"; } this.set({ content: this._processor.text, mode: MarkupMode[mode] }); } /** * Calls the current processor's mono function to hihglight the current * word/selection. */ public setMono() { this._processor.handleMono(); } /** * Calls the current processor's strikthrough function to highlight the * current word/selection. */ public setStrikeThrough() { this._processor.handleStrikeThrough(); } /** * Calls the current processor's underline function to highlight the * current word/selection. */ public setUnderline() { this._processor.handleUnderline(); } /** * Calls the quill history undo function */ public undo() { if (this._quill.history) { this._quill.history.undo(); } } /** * This event is invoked whenever the mouse is clicked within the editor. * It will call the user give onClick handler and pass the position within * the editor that was clicked. * * If the `followLinks` configuration option is given, then another handler * is called that will check if the clicked position is a link. If it is, * then the regex match object that found this link is returned to the * callback (giving the full text, start/end offsets, and groups). */ private handleClick() { this._opts.onClick(this._processor.pos); if (this._opts.followLinks) { const pos: number = this._processor.pos; for (const it of this._processor.links) { if (pos >= it.link.start && pos <= it.link.end) { this._opts.onClickLink(it.link); break; } } } } /** * This event is invoked whenever a change occurs in the editor (any type). * @param eventName {string} the name of the event that occurred. * @param args {any[]} the dyanamic parameter list passed to this event. */ private handleEditorChange(eventName: string, ...args: any[]) { // debug('handleEditorChange: %s, %o', eventName, args); if (eventName === "selection-change") { const range = args[0]; if (range) { this._processor.range = range; this._processor.pos = range.index; } // Compute the line that will be involved in highlighting this._line = getLine(this._processor.text, this._processor.pos); } } /** * When the user pastes information into the editor, this event is fired */ private handlePaste() { this._paste = true; } /** * Invoked with each change of the content text. * * This will also hold a timer to peform a full scan after N seconds. * Using "sections" to format has a trade off where a block format on * a boundary of a section can lose formatting where the bottom of the * block is seen by the section, but the top is not, so the regex string * will not match within the section. This timer will send a full * range of the document to the processor after N seconds (5 seconds by * default). The timer will only occur when changes occur (so it is * idle if the keyboard is idle) */ private handleTextChange(delta?: any, old?: any, source?: string) { delta = old = delta; // stupid but satifies the linter if (source === "user" && this._dirtyCount++ > this._dirtyLimit) { this._dirtyIdle = true; } this._dirtyInline = true; if (!this._changing || this._paste) { this._changing = true; setTimeout(() => { if (this._paste) { this._processor.refreshFull(); this._paste = false; } else { this._processor.handleChange( this._line.start, this._line.end ); } this._opts.onChange(this._processor.text); this._changing = false; }, this._delay); } } }
public setHighlight(name: string) { debug("setting highlight: %s", name); if (name in cssHighlights) {
random_line_split
markup.ts
/** * A custom Quill highlighting module for markup modes/styles. It manages * multiple mode instances that are used to apply text formatting to the * contents of the control. * * The module is added to the component per the API instructions: * https://quilljs.com/guides/building-a-custom-module/ * * Once the module is initialized the highlighting mode can be changed with * the `set` functions. This just changes what the reference internally to * another class that handles the formatting. * * See the README.md file for an example. * * Note that initial *content* cannot be set in the contructor to the module. * it is overwritten with the contents of the `#editor` div as Quill is * instantiated. It can be set after creation of the Quill instance using * the `.setContent('')` function. * * @module Markup */ const debug = require("debug")("quill-markup.markup"); import {union} from "lodash"; import {getFontList} from "util.fontlist"; import {line as getLine, Section} from "util.section"; import {Quill} from "./helpers"; import {cssHighlights} from "./highlights"; import { Asciidoc, BaseMarkupMode, Markdown, RestructuredText, Text } from "./modes"; export type EventCallback = (val: any) => void; const nilEvent: EventCallback = (val: any): void => { val = val; }; export enum MarkupMode { asciidoc, markdown, restructuredtext, text } export interface MarkupOptions { content?: string; custom?: any; dirtyLimit?: number; fontName?: string; fontSize?: number; followLinks?: boolean; highlight?: string; idleDelay?: number; mode?: MarkupMode; onChange?: EventCallback; onClick?: EventCallback; onClickLink?: EventCallback; } const defaultOptions: MarkupOptions = { content: "", custom: {}, dirtyLimit: 20, fontName: "Fira Code", fontSize: 12, followLinks: false, highlight: "solarized-light", idleDelay: 2000, mode: MarkupMode.text, onChange: nilEvent, onClick: nilEvent, onClickLink: nilEvent }; require("./styles.css"); export class Markup { // As the document is modified the number of characters that are changed // is counted. When a "dirty" limit is reached and the user is idle then // a full rescan of the document block elements will occur. The smaller // the limit, the sooner this will occur when idle. private _dirtyIdle: boolean = false; private _dirtyInline: boolean = false; private _dirtyCount: number = 10; private _dirtyLimit: number; // The time between each incremental section scan private _delay: number = 250; private _changing: boolean = false; // The time before idle detection private _idle: boolean = true; private _idleDelay: number = 2000; private _idleTimer: any; // A reference to the DOM editor node private _editor: HTMLElement; private _fonts: string[] = ["Fira Code", "Inconsolata", "Source Code Pro"]; private _line: Section = { start: 0, end: 0, text: "", multiLine: false }; private _modes: any = {}; private _opts: MarkupOptions; private _paste: boolean = false; private _processor: BaseMarkupMode; private _quill: any; constructor(quill: any, opts: MarkupOptions = {}) { debug("Initializing markup module"); this._quill = quill; this._opts = Object.assign({}, defaultOptions, opts); this._editor = quill.container; debug("quill (local): %o", quill); debug("Quill (global): %o", Quill); debug("Editor id: %s", this.editorKey); this._modes[MarkupMode.asciidoc] = new Asciidoc(quill); this._modes[MarkupMode.markdown] = new Markdown(quill); this._modes[MarkupMode.restructuredtext] = new RestructuredText(quill); this._modes[MarkupMode.text] = new Text(quill); debug("modes: %O", this._modes); this._fonts = union(this._fonts, getFontList()); debug("available fonts: %O", this.fonts); // bind all potential callbacks to the class. [ "handleClick", "handleEditorChange", "handlePaste", "handleTextChange", "resetInactivityTimer", "markIdle", "redo", "refresh", "set", "setBold", "setContent", "setItalic", "setFont", "setFontSize", "setHeader", "setMode", "setMono", "setStrikeThrough", "setUnderline", "undo" ].forEach((fn: string) => { this[fn] = this[fn].bind(this); }); quill.on("editor-change", this.handleEditorChange); quill.on("text-change", this.handleTextChange); this._editor.addEventListener("paste", this.handlePaste); this._editor.addEventListener("click", this.handleClick); window.addEventListener("load", this.resetInactivityTimer); document.addEventListener("mousemove", this.resetInactivityTimer); document.addEventListener("click", this.resetInactivityTimer); document.addEventListener("keydown", this.resetInactivityTimer); this.set(opts); } get editor() { return this._editor; } get editorKey() { return this.quill.container.id; } get fonts() { return this._fonts; } get highlights() { return Object.keys(cssHighlights); } get idle() { return this._idle; } get modes() { return Object.keys(MarkupMode) .map((key) => MarkupMode[key]) .filter((it) => typeof it === "string"); } get opts() { return this._opts; } get quill() { return this._quill; } /** * Resets the idle timer when the user does something in the app. */ private resetInactivityTimer() { this._idle = false; clearTimeout(this._idleTimer); this._idleTimer = setTimeout(this.markIdle, this._idleDelay); } /** * When the user is idle for N seconds this function is called by a global * timer to set a flag and rescan the full document. This can be an * expensive operation and we need to find the tradeoff limit */ private markIdle() { this._idle = true; if (this._dirtyIdle) { this._dirtyIdle = false; this._dirtyCount = 0; this._processor.refreshBlock(); } if (this._dirtyInline) { this._processor.refreshInline(); this._dirtyInline = false; } } /** * Calls the quill history redo function */ public redo() { if (this._quill.history) { this._quill.history.redo(); } } /** * Rescans the entire document for highlighting. This is a wrapper around * the processor's full refresh function. */ public
() { this._processor.refreshFull(); this._dirtyIdle = false; this._dirtyCount = 0; this._dirtyInline = false; } /** * Changes the current highlighting mode and display style. It also sets * the content within control. * @param opts {HighlightOptions} configuration options. `mode` sets the * editing mode. `styling` sets the current display theme. `custom` is * an object that contains custom format colors (for highlights). The * `content` resets the content within the control. If this is null it * is ignored. */ public set(opts: MarkupOptions) { this._opts = Object.assign({}, defaultOptions, this._opts, opts); debug("options: %o", this._opts); this._processor = this._modes[this._opts.mode]; debug("using processor: %o", this._processor); this._dirtyLimit = this._opts.dirtyLimit; this._idleDelay = this._opts.idleDelay; this._processor.style = Object.assign( { foreground: "black", background: "white" }, this._opts.mode === MarkupMode.text ? {} : require("./highlighting.json"), this._opts.custom ); debug("current highlighting colors: %o", this._processor.style); this.setContent(this._opts.content); this.setFont(this._opts.fontName); this.setFontSize(this._opts.fontSize); this.setHighlight(this._opts.highlight); this._editor.style["color"] = this._processor.style.foreground; this._editor.style[ "background-color" ] = this._processor.style.background; this._line = getLine(this._opts.content, 0); this._processor.refreshFull(); } /** * Will call the current processor's bold function to make the current * highlight or word bold. */ public setBold() { this._processor.handleBold(); } /** * Will update the current content of the control with the given * @param content {string} the new content settting for the editor. */ public setContent(content: string) { this._opts.content = content; this._processor.text = content; } /** * Changes the current overall font for the editor. This control works with * mono fonts, so this will set it for all text. The fonts are all defined * in `./lib/fonts`. * @param fontName {string} the name of the font to set. */ public setFont(fontName: string) { if (!this._fonts.includes(fontName)) { fontName = this._fonts[0]; } debug("setting font: %s", fontName); this._opts.fontName = fontName; this._editor.style.fontFamily = fontName; } /** * Changes the current overall size of the fonts within the editor. * @param fontSize {number} the number of pixels in the font sizing. This * will resolve to `##px`. */ public setFontSize(fontSize: number) { debug("setting font size: %spx", fontSize); this._opts.fontSize = fontSize; this._editor.style["font-size"] = `${fontSize}px`; } /** * Calls the processor's current header creation function * @param level {string} the level selected by the user */ public setHeader(level: string) { this._processor.handleHeader(Number(level)); } public setHighlight(name: string) { debug("setting highlight: %s", name); if (name in cssHighlights) { const oldlink = document.getElementById("highlights"); const newlink = document.createElement("link"); newlink.setAttribute("id", "highlights"); newlink.setAttribute("rel", "stylesheet"); newlink.setAttribute("type", "text/css"); newlink.setAttribute("href", cssHighlights[name]); const head = document.getElementsByTagName("head").item(0); if (oldlink) { head.replaceChild(newlink, oldlink); } else { head.appendChild(newlink); } } } /** * Calls the current processor's italic function to make the current * highlight or word italic. */ public setItalic() { this._processor.handleItalic(); } /** * Changes the current display mode for the markup processor * @param mode {string} the name of the mode to set */ public setMode(mode: string) { debug("setting mode: %s", mode); if (!(mode in MarkupMode)) { mode = "text"; } this.set({ content: this._processor.text, mode: MarkupMode[mode] }); } /** * Calls the current processor's mono function to hihglight the current * word/selection. */ public setMono() { this._processor.handleMono(); } /** * Calls the current processor's strikthrough function to highlight the * current word/selection. */ public setStrikeThrough() { this._processor.handleStrikeThrough(); } /** * Calls the current processor's underline function to highlight the * current word/selection. */ public setUnderline() { this._processor.handleUnderline(); } /** * Calls the quill history undo function */ public undo() { if (this._quill.history) { this._quill.history.undo(); } } /** * This event is invoked whenever the mouse is clicked within the editor. * It will call the user give onClick handler and pass the position within * the editor that was clicked. * * If the `followLinks` configuration option is given, then another handler * is called that will check if the clicked position is a link. If it is, * then the regex match object that found this link is returned to the * callback (giving the full text, start/end offsets, and groups). */ private handleClick() { this._opts.onClick(this._processor.pos); if (this._opts.followLinks) { const pos: number = this._processor.pos; for (const it of this._processor.links) { if (pos >= it.link.start && pos <= it.link.end) { this._opts.onClickLink(it.link); break; } } } } /** * This event is invoked whenever a change occurs in the editor (any type). * @param eventName {string} the name of the event that occurred. * @param args {any[]} the dyanamic parameter list passed to this event. */ private handleEditorChange(eventName: string, ...args: any[]) { // debug('handleEditorChange: %s, %o', eventName, args); if (eventName === "selection-change") { const range = args[0]; if (range) { this._processor.range = range; this._processor.pos = range.index; } // Compute the line that will be involved in highlighting this._line = getLine(this._processor.text, this._processor.pos); } } /** * When the user pastes information into the editor, this event is fired */ private handlePaste() { this._paste = true; } /** * Invoked with each change of the content text. * * This will also hold a timer to peform a full scan after N seconds. * Using "sections" to format has a trade off where a block format on * a boundary of a section can lose formatting where the bottom of the * block is seen by the section, but the top is not, so the regex string * will not match within the section. This timer will send a full * range of the document to the processor after N seconds (5 seconds by * default). The timer will only occur when changes occur (so it is * idle if the keyboard is idle) */ private handleTextChange(delta?: any, old?: any, source?: string) { delta = old = delta; // stupid but satifies the linter if (source === "user" && this._dirtyCount++ > this._dirtyLimit) { this._dirtyIdle = true; } this._dirtyInline = true; if (!this._changing || this._paste) { this._changing = true; setTimeout(() => { if (this._paste) { this._processor.refreshFull(); this._paste = false; } else { this._processor.handleChange( this._line.start, this._line.end ); } this._opts.onChange(this._processor.text); this._changing = false; }, this._delay); } } }
refresh
identifier_name
module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {NglInternalOutletModule} from '../util/outlet.module'; import {NglFormElement} from './elements/element'; import {NglFormInput, NglFormTextarea, NglFormSelect, NglFormCheckbox} from './elements/input'; import {NglFormElementRequired} from './elements/required'; import {NglFormGroup} from './groups/group'; import {NglFormGroupAlternate} from './groups/group-alt'; import {NglFormGroupElement} from './groups/element'; import {NglFormGroupCheckbox, NglFormGroupRadio} from './groups/input'; import {NglFormLabelTemplate} from './form-label'; const NGL_FORM_DIRECTIVES = [ NglFormElement, NglFormInput, NglFormTextarea, NglFormSelect, NglFormCheckbox, NglFormElementRequired, NglFormGroup, NglFormGroupAlternate, NglFormGroupElement, NglFormGroupCheckbox, NglFormGroupRadio, NglFormLabelTemplate, ]; @NgModule({ declarations: NGL_FORM_DIRECTIVES, exports: NGL_FORM_DIRECTIVES, imports: [CommonModule, NglInternalOutletModule], }) export class
{}
NglFormsModule
identifier_name
module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {NglInternalOutletModule} from '../util/outlet.module'; import {NglFormElement} from './elements/element'; import {NglFormInput, NglFormTextarea, NglFormSelect, NglFormCheckbox} from './elements/input'; import {NglFormElementRequired} from './elements/required'; import {NglFormGroup} from './groups/group'; import {NglFormGroupAlternate} from './groups/group-alt'; import {NglFormGroupElement} from './groups/element'; import {NglFormGroupCheckbox, NglFormGroupRadio} from './groups/input'; import {NglFormLabelTemplate} from './form-label'; const NGL_FORM_DIRECTIVES = [ NglFormElement, NglFormInput, NglFormTextarea, NglFormSelect, NglFormCheckbox, NglFormElementRequired, NglFormGroup, NglFormGroupAlternate, NglFormGroupElement, NglFormGroupCheckbox, NglFormGroupRadio, NglFormLabelTemplate, ]; @NgModule({ declarations: NGL_FORM_DIRECTIVES, exports: NGL_FORM_DIRECTIVES, imports: [CommonModule, NglInternalOutletModule],
}) export class NglFormsModule {}
random_line_split
template.py
""" sentry.interfaces.template ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Template',) from sentry.interfaces.base import Interface, InterfaceValidationError from sentry.interfaces.stacktrace import get_context from sentry.utils.safe import trim class Template(Interface): """ A rendered template (generally used like a single frame in a stacktrace). The attributes ``filename``, ``context_line``, and ``lineno`` are required. >>> { >>> "abs_path": "/real/file/name.html" >>> "filename": "file/name.html", >>> "pre_context": [ >>> "line1", >>> "line2" >>> ], >>> "context_line": "line3", >>> "lineno": 3, >>> "post_context": [ >>> "line4", >>> "line5"
""" score = 1100 @classmethod def to_python(cls, data): if not data.get('filename'): raise InterfaceValidationError("Missing 'filename'") if not data.get('context_line'): raise InterfaceValidationError("Missing 'context_line'") if not data.get('lineno'): raise InterfaceValidationError("Missing 'lineno'") kwargs = { 'abs_path': trim(data.get('abs_path', None), 256), 'filename': trim(data['filename'], 256), 'context_line': trim(data.get('context_line', None), 256), 'lineno': int(data['lineno']), # TODO(dcramer): trim pre/post_context 'pre_context': data.get('pre_context'), 'post_context': data.get('post_context'), } return cls(**kwargs) def get_alias(self): return 'template' def get_path(self): return 'sentry.interfaces.Template' def get_hash(self): return [self.filename, self.context_line] def to_string(self, event, is_public=False, **kwargs): context = get_context( lineno=self.lineno, context_line=self.context_line, pre_context=self.pre_context, post_context=self.post_context, filename=self.filename, ) result = [ 'Stacktrace (most recent call last):', '', self.get_traceback(event, context) ] return '\n'.join(result) def get_traceback(self, event, context): result = [ event.message, '', 'File "%s", line %s' % (self.filename, self.lineno), '', ] result.extend([n[1].strip('\n') for n in context]) return '\n'.join(result) def get_api_context(self, is_public=False): return { 'lineNo': self.lineno, 'filename': self.filename, 'context': get_context( lineno=self.lineno, context_line=self.context_line, pre_context=self.pre_context, post_context=self.post_context, filename=self.filename, ), }
>>> ], >>> } .. note:: This interface can be passed as the 'template' key in addition to the full interface path.
random_line_split
template.py
""" sentry.interfaces.template ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Template',) from sentry.interfaces.base import Interface, InterfaceValidationError from sentry.interfaces.stacktrace import get_context from sentry.utils.safe import trim class
(Interface): """ A rendered template (generally used like a single frame in a stacktrace). The attributes ``filename``, ``context_line``, and ``lineno`` are required. >>> { >>> "abs_path": "/real/file/name.html" >>> "filename": "file/name.html", >>> "pre_context": [ >>> "line1", >>> "line2" >>> ], >>> "context_line": "line3", >>> "lineno": 3, >>> "post_context": [ >>> "line4", >>> "line5" >>> ], >>> } .. note:: This interface can be passed as the 'template' key in addition to the full interface path. """ score = 1100 @classmethod def to_python(cls, data): if not data.get('filename'): raise InterfaceValidationError("Missing 'filename'") if not data.get('context_line'): raise InterfaceValidationError("Missing 'context_line'") if not data.get('lineno'): raise InterfaceValidationError("Missing 'lineno'") kwargs = { 'abs_path': trim(data.get('abs_path', None), 256), 'filename': trim(data['filename'], 256), 'context_line': trim(data.get('context_line', None), 256), 'lineno': int(data['lineno']), # TODO(dcramer): trim pre/post_context 'pre_context': data.get('pre_context'), 'post_context': data.get('post_context'), } return cls(**kwargs) def get_alias(self): return 'template' def get_path(self): return 'sentry.interfaces.Template' def get_hash(self): return [self.filename, self.context_line] def to_string(self, event, is_public=False, **kwargs): context = get_context( lineno=self.lineno, context_line=self.context_line, pre_context=self.pre_context, post_context=self.post_context, filename=self.filename, ) result = [ 'Stacktrace (most recent call last):', '', self.get_traceback(event, context) ] return '\n'.join(result) def get_traceback(self, event, context): result = [ event.message, '', 'File "%s", line %s' % (self.filename, self.lineno), '', ] result.extend([n[1].strip('\n') for n in context]) return '\n'.join(result) def get_api_context(self, is_public=False): return { 'lineNo': self.lineno, 'filename': self.filename, 'context': get_context( lineno=self.lineno, context_line=self.context_line, pre_context=self.pre_context, post_context=self.post_context, filename=self.filename, ), }
Template
identifier_name
template.py
""" sentry.interfaces.template ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Template',) from sentry.interfaces.base import Interface, InterfaceValidationError from sentry.interfaces.stacktrace import get_context from sentry.utils.safe import trim class Template(Interface): """ A rendered template (generally used like a single frame in a stacktrace). The attributes ``filename``, ``context_line``, and ``lineno`` are required. >>> { >>> "abs_path": "/real/file/name.html" >>> "filename": "file/name.html", >>> "pre_context": [ >>> "line1", >>> "line2" >>> ], >>> "context_line": "line3", >>> "lineno": 3, >>> "post_context": [ >>> "line4", >>> "line5" >>> ], >>> } .. note:: This interface can be passed as the 'template' key in addition to the full interface path. """ score = 1100 @classmethod def to_python(cls, data): if not data.get('filename'): raise InterfaceValidationError("Missing 'filename'") if not data.get('context_line'): raise InterfaceValidationError("Missing 'context_line'") if not data.get('lineno'): raise InterfaceValidationError("Missing 'lineno'") kwargs = { 'abs_path': trim(data.get('abs_path', None), 256), 'filename': trim(data['filename'], 256), 'context_line': trim(data.get('context_line', None), 256), 'lineno': int(data['lineno']), # TODO(dcramer): trim pre/post_context 'pre_context': data.get('pre_context'), 'post_context': data.get('post_context'), } return cls(**kwargs) def get_alias(self): return 'template' def get_path(self): return 'sentry.interfaces.Template' def get_hash(self): return [self.filename, self.context_line] def to_string(self, event, is_public=False, **kwargs): context = get_context( lineno=self.lineno, context_line=self.context_line, pre_context=self.pre_context, post_context=self.post_context, filename=self.filename, ) result = [ 'Stacktrace (most recent call last):', '', self.get_traceback(event, context) ] return '\n'.join(result) def get_traceback(self, event, context):
def get_api_context(self, is_public=False): return { 'lineNo': self.lineno, 'filename': self.filename, 'context': get_context( lineno=self.lineno, context_line=self.context_line, pre_context=self.pre_context, post_context=self.post_context, filename=self.filename, ), }
result = [ event.message, '', 'File "%s", line %s' % (self.filename, self.lineno), '', ] result.extend([n[1].strip('\n') for n in context]) return '\n'.join(result)
identifier_body
template.py
""" sentry.interfaces.template ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Template',) from sentry.interfaces.base import Interface, InterfaceValidationError from sentry.interfaces.stacktrace import get_context from sentry.utils.safe import trim class Template(Interface): """ A rendered template (generally used like a single frame in a stacktrace). The attributes ``filename``, ``context_line``, and ``lineno`` are required. >>> { >>> "abs_path": "/real/file/name.html" >>> "filename": "file/name.html", >>> "pre_context": [ >>> "line1", >>> "line2" >>> ], >>> "context_line": "line3", >>> "lineno": 3, >>> "post_context": [ >>> "line4", >>> "line5" >>> ], >>> } .. note:: This interface can be passed as the 'template' key in addition to the full interface path. """ score = 1100 @classmethod def to_python(cls, data): if not data.get('filename'): raise InterfaceValidationError("Missing 'filename'") if not data.get('context_line'): raise InterfaceValidationError("Missing 'context_line'") if not data.get('lineno'):
kwargs = { 'abs_path': trim(data.get('abs_path', None), 256), 'filename': trim(data['filename'], 256), 'context_line': trim(data.get('context_line', None), 256), 'lineno': int(data['lineno']), # TODO(dcramer): trim pre/post_context 'pre_context': data.get('pre_context'), 'post_context': data.get('post_context'), } return cls(**kwargs) def get_alias(self): return 'template' def get_path(self): return 'sentry.interfaces.Template' def get_hash(self): return [self.filename, self.context_line] def to_string(self, event, is_public=False, **kwargs): context = get_context( lineno=self.lineno, context_line=self.context_line, pre_context=self.pre_context, post_context=self.post_context, filename=self.filename, ) result = [ 'Stacktrace (most recent call last):', '', self.get_traceback(event, context) ] return '\n'.join(result) def get_traceback(self, event, context): result = [ event.message, '', 'File "%s", line %s' % (self.filename, self.lineno), '', ] result.extend([n[1].strip('\n') for n in context]) return '\n'.join(result) def get_api_context(self, is_public=False): return { 'lineNo': self.lineno, 'filename': self.filename, 'context': get_context( lineno=self.lineno, context_line=self.context_line, pre_context=self.pre_context, post_context=self.post_context, filename=self.filename, ), }
raise InterfaceValidationError("Missing 'lineno'")
conditional_block
nodeSession.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { IRequestProps, ITransport, sdkError, HttpMethod, encodeParams, } from './transport' import { AuthToken } from './authToken' import { NodeTransport } from './nodeTransport' import { IApiSettings } from './apiSettings' import { AuthSession, IAccessToken, IError } from './authSession' const strPost: HttpMethod = 'POST' const strDelete: HttpMethod = 'DELETE' export class NodeSession extends AuthSession { private readonly apiPath: string = '/api/3.1' _authToken: AuthToken = new AuthToken() _sudoToken: AuthToken = new AuthToken() constructor(public settings: IApiSettings, transport?: ITransport) { super(settings, transport || new NodeTransport(settings)) } /** * Abstraction of AuthToken retrieval to support sudo mode */ get activeToken() { if (this._sudoToken.access_token) { return this._sudoToken } return this._authToken } /** * Is there an active authentication token? */ isAuthenticated() { // TODO I think this can be simplified const token = this.activeToken if (!(token && token.access_token)) return false return token.isActive() } /** * Add authentication data to the pending API request * @param props initialized API request properties * * @returns the updated request properties */ async authenticate(props: IRequestProps)
isSudo() { return !!this.sudoId && this._sudoToken.isActive() } /** * retrieve the current authentication token. If there is no active token, performs default * login to retrieve the token */ async getToken() { if (!this.isAuthenticated()) { await this.login() } return this.activeToken } /** * Reset the authentication session */ reset() { this.sudoId = '' this._authToken.reset() this._sudoToken.reset() } /** * Activate the authentication token for the API3 or sudo user * @param sudoId {string | number}: optional. If provided, impersonates the user specified * */ async login(sudoId?: string | number) { if (sudoId || sudoId !== this.sudoId || !this.isAuthenticated()) { if (sudoId) { await this._login(sudoId.toString()) } else { await this._login() } } return this.activeToken } /** * Logout the active user. If the active user is sudo, the session reverts to the API3 user */ async logout() { let result = false if (this.isAuthenticated()) { result = await this._logout() } return result } private async sudoLogout() { let result = false if (this.isSudo()) { result = await this.logout() // Logout the current sudo this._sudoToken.reset() } return result } // internal login method that manages default auth token and sudo workflow private async _login(newId?: string) { // for linty freshness, always logout sudo if set await this.sudoLogout() if (newId !== this.sudoId) { // Assign new requested sudo id this.sudoId = newId || '' } if (!this._authToken.isActive()) { this.reset() // only retain client API3 credentials for the lifetime of the login request const section = this.settings.readConfig() const clientId = section.client_id const clientSecret = section.client_secret if (!clientId || !clientSecret) { throw sdkError({ message: 'API credentials client_id and/or client_secret are not set', }) } const body = encodeParams({ client_id: clientId, client_secret: clientSecret, }) // authenticate client const token = await this.ok( this.transport.request<IAccessToken, IError>( strPost, `${this.apiPath}/login`, undefined, body ) ) this._authToken.setToken(token) } if (this.sudoId) { // Use the API user auth to sudo const token = this.activeToken const promise = this.transport.request<IAccessToken, IError>( strPost, encodeURI(`${this.apiPath}/login/${newId}`), null, null, // ensure the auth token is included in the sudo request (init: IRequestProps) => { if (token.access_token) { init.headers.Authorization = `Bearer ${token.access_token}` } return init }, this.settings // TODO this may not be needed here ) const accessToken = await this.ok(promise) this._sudoToken.setToken(accessToken) } return this.activeToken } private async _logout() { const token = this.activeToken const promise = this.transport.request<string, IError>( strDelete, `${this.apiPath}/logout`, null, null, // ensure the auth token is included in the logout promise (init: IRequestProps) => { if (token.access_token) { init.headers.Authorization = `Bearer ${token.access_token}` } return init }, this.settings ) await this.ok(promise) // If no error was thrown, logout was successful if (this.sudoId) { // User was logged out, so set auth back to default this.sudoId = '' this._sudoToken.reset() if (!this._authToken.isActive()) { await this.login() } } else { // completely logged out this.reset() } return true } }
{ const token = await this.getToken() if (token && token.access_token) { props.headers.Authorization = `Bearer ${token.access_token}` } return props }
identifier_body
nodeSession.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { IRequestProps, ITransport, sdkError, HttpMethod, encodeParams, } from './transport' import { AuthToken } from './authToken' import { NodeTransport } from './nodeTransport' import { IApiSettings } from './apiSettings' import { AuthSession, IAccessToken, IError } from './authSession' const strPost: HttpMethod = 'POST' const strDelete: HttpMethod = 'DELETE' export class NodeSession extends AuthSession { private readonly apiPath: string = '/api/3.1' _authToken: AuthToken = new AuthToken() _sudoToken: AuthToken = new AuthToken() constructor(public settings: IApiSettings, transport?: ITransport) { super(settings, transport || new NodeTransport(settings)) } /** * Abstraction of AuthToken retrieval to support sudo mode */ get activeToken() { if (this._sudoToken.access_token) { return this._sudoToken } return this._authToken } /** * Is there an active authentication token? */ isAuthenticated() { // TODO I think this can be simplified const token = this.activeToken if (!(token && token.access_token)) return false return token.isActive() } /** * Add authentication data to the pending API request * @param props initialized API request properties * * @returns the updated request properties */ async authenticate(props: IRequestProps) { const token = await this.getToken() if (token && token.access_token) { props.headers.Authorization = `Bearer ${token.access_token}` } return props } isSudo() { return !!this.sudoId && this._sudoToken.isActive() } /** * retrieve the current authentication token. If there is no active token, performs default * login to retrieve the token */ async getToken() { if (!this.isAuthenticated()) { await this.login() } return this.activeToken } /** * Reset the authentication session */ reset() { this.sudoId = '' this._authToken.reset() this._sudoToken.reset() } /** * Activate the authentication token for the API3 or sudo user * @param sudoId {string | number}: optional. If provided, impersonates the user specified * */ async login(sudoId?: string | number) { if (sudoId || sudoId !== this.sudoId || !this.isAuthenticated()) { if (sudoId) { await this._login(sudoId.toString()) } else { await this._login() } } return this.activeToken } /** * Logout the active user. If the active user is sudo, the session reverts to the API3 user */ async logout() { let result = false if (this.isAuthenticated()) { result = await this._logout() } return result } private async sudoLogout() { let result = false if (this.isSudo()) { result = await this.logout() // Logout the current sudo this._sudoToken.reset() } return result } // internal login method that manages default auth token and sudo workflow private async _login(newId?: string) { // for linty freshness, always logout sudo if set await this.sudoLogout() if (newId !== this.sudoId)
if (!this._authToken.isActive()) { this.reset() // only retain client API3 credentials for the lifetime of the login request const section = this.settings.readConfig() const clientId = section.client_id const clientSecret = section.client_secret if (!clientId || !clientSecret) { throw sdkError({ message: 'API credentials client_id and/or client_secret are not set', }) } const body = encodeParams({ client_id: clientId, client_secret: clientSecret, }) // authenticate client const token = await this.ok( this.transport.request<IAccessToken, IError>( strPost, `${this.apiPath}/login`, undefined, body ) ) this._authToken.setToken(token) } if (this.sudoId) { // Use the API user auth to sudo const token = this.activeToken const promise = this.transport.request<IAccessToken, IError>( strPost, encodeURI(`${this.apiPath}/login/${newId}`), null, null, // ensure the auth token is included in the sudo request (init: IRequestProps) => { if (token.access_token) { init.headers.Authorization = `Bearer ${token.access_token}` } return init }, this.settings // TODO this may not be needed here ) const accessToken = await this.ok(promise) this._sudoToken.setToken(accessToken) } return this.activeToken } private async _logout() { const token = this.activeToken const promise = this.transport.request<string, IError>( strDelete, `${this.apiPath}/logout`, null, null, // ensure the auth token is included in the logout promise (init: IRequestProps) => { if (token.access_token) { init.headers.Authorization = `Bearer ${token.access_token}` } return init }, this.settings ) await this.ok(promise) // If no error was thrown, logout was successful if (this.sudoId) { // User was logged out, so set auth back to default this.sudoId = '' this._sudoToken.reset() if (!this._authToken.isActive()) { await this.login() } } else { // completely logged out this.reset() } return true } }
{ // Assign new requested sudo id this.sudoId = newId || '' }
conditional_block
nodeSession.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { IRequestProps, ITransport, sdkError, HttpMethod, encodeParams, } from './transport' import { AuthToken } from './authToken' import { NodeTransport } from './nodeTransport' import { IApiSettings } from './apiSettings' import { AuthSession, IAccessToken, IError } from './authSession' const strPost: HttpMethod = 'POST' const strDelete: HttpMethod = 'DELETE' export class NodeSession extends AuthSession { private readonly apiPath: string = '/api/3.1' _authToken: AuthToken = new AuthToken() _sudoToken: AuthToken = new AuthToken() constructor(public settings: IApiSettings, transport?: ITransport) { super(settings, transport || new NodeTransport(settings)) } /** * Abstraction of AuthToken retrieval to support sudo mode */ get activeToken() { if (this._sudoToken.access_token) { return this._sudoToken } return this._authToken } /** * Is there an active authentication token? */ isAuthenticated() { // TODO I think this can be simplified const token = this.activeToken if (!(token && token.access_token)) return false return token.isActive() } /** * Add authentication data to the pending API request * @param props initialized API request properties * * @returns the updated request properties */ async authenticate(props: IRequestProps) { const token = await this.getToken() if (token && token.access_token) { props.headers.Authorization = `Bearer ${token.access_token}` } return props }
() { return !!this.sudoId && this._sudoToken.isActive() } /** * retrieve the current authentication token. If there is no active token, performs default * login to retrieve the token */ async getToken() { if (!this.isAuthenticated()) { await this.login() } return this.activeToken } /** * Reset the authentication session */ reset() { this.sudoId = '' this._authToken.reset() this._sudoToken.reset() } /** * Activate the authentication token for the API3 or sudo user * @param sudoId {string | number}: optional. If provided, impersonates the user specified * */ async login(sudoId?: string | number) { if (sudoId || sudoId !== this.sudoId || !this.isAuthenticated()) { if (sudoId) { await this._login(sudoId.toString()) } else { await this._login() } } return this.activeToken } /** * Logout the active user. If the active user is sudo, the session reverts to the API3 user */ async logout() { let result = false if (this.isAuthenticated()) { result = await this._logout() } return result } private async sudoLogout() { let result = false if (this.isSudo()) { result = await this.logout() // Logout the current sudo this._sudoToken.reset() } return result } // internal login method that manages default auth token and sudo workflow private async _login(newId?: string) { // for linty freshness, always logout sudo if set await this.sudoLogout() if (newId !== this.sudoId) { // Assign new requested sudo id this.sudoId = newId || '' } if (!this._authToken.isActive()) { this.reset() // only retain client API3 credentials for the lifetime of the login request const section = this.settings.readConfig() const clientId = section.client_id const clientSecret = section.client_secret if (!clientId || !clientSecret) { throw sdkError({ message: 'API credentials client_id and/or client_secret are not set', }) } const body = encodeParams({ client_id: clientId, client_secret: clientSecret, }) // authenticate client const token = await this.ok( this.transport.request<IAccessToken, IError>( strPost, `${this.apiPath}/login`, undefined, body ) ) this._authToken.setToken(token) } if (this.sudoId) { // Use the API user auth to sudo const token = this.activeToken const promise = this.transport.request<IAccessToken, IError>( strPost, encodeURI(`${this.apiPath}/login/${newId}`), null, null, // ensure the auth token is included in the sudo request (init: IRequestProps) => { if (token.access_token) { init.headers.Authorization = `Bearer ${token.access_token}` } return init }, this.settings // TODO this may not be needed here ) const accessToken = await this.ok(promise) this._sudoToken.setToken(accessToken) } return this.activeToken } private async _logout() { const token = this.activeToken const promise = this.transport.request<string, IError>( strDelete, `${this.apiPath}/logout`, null, null, // ensure the auth token is included in the logout promise (init: IRequestProps) => { if (token.access_token) { init.headers.Authorization = `Bearer ${token.access_token}` } return init }, this.settings ) await this.ok(promise) // If no error was thrown, logout was successful if (this.sudoId) { // User was logged out, so set auth back to default this.sudoId = '' this._sudoToken.reset() if (!this._authToken.isActive()) { await this.login() } } else { // completely logged out this.reset() } return true } }
isSudo
identifier_name
nodeSession.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { IRequestProps, ITransport, sdkError, HttpMethod, encodeParams, } from './transport' import { AuthToken } from './authToken' import { NodeTransport } from './nodeTransport' import { IApiSettings } from './apiSettings' import { AuthSession, IAccessToken, IError } from './authSession' const strPost: HttpMethod = 'POST' const strDelete: HttpMethod = 'DELETE' export class NodeSession extends AuthSession { private readonly apiPath: string = '/api/3.1' _authToken: AuthToken = new AuthToken() _sudoToken: AuthToken = new AuthToken() constructor(public settings: IApiSettings, transport?: ITransport) { super(settings, transport || new NodeTransport(settings)) } /** * Abstraction of AuthToken retrieval to support sudo mode */ get activeToken() { if (this._sudoToken.access_token) { return this._sudoToken } return this._authToken } /** * Is there an active authentication token? */ isAuthenticated() { // TODO I think this can be simplified const token = this.activeToken if (!(token && token.access_token)) return false return token.isActive() } /** * Add authentication data to the pending API request * @param props initialized API request properties * * @returns the updated request properties */ async authenticate(props: IRequestProps) { const token = await this.getToken() if (token && token.access_token) { props.headers.Authorization = `Bearer ${token.access_token}` } return props } isSudo() { return !!this.sudoId && this._sudoToken.isActive() } /** * retrieve the current authentication token. If there is no active token, performs default * login to retrieve the token */ async getToken() { if (!this.isAuthenticated()) { await this.login() }
/** * Reset the authentication session */ reset() { this.sudoId = '' this._authToken.reset() this._sudoToken.reset() } /** * Activate the authentication token for the API3 or sudo user * @param sudoId {string | number}: optional. If provided, impersonates the user specified * */ async login(sudoId?: string | number) { if (sudoId || sudoId !== this.sudoId || !this.isAuthenticated()) { if (sudoId) { await this._login(sudoId.toString()) } else { await this._login() } } return this.activeToken } /** * Logout the active user. If the active user is sudo, the session reverts to the API3 user */ async logout() { let result = false if (this.isAuthenticated()) { result = await this._logout() } return result } private async sudoLogout() { let result = false if (this.isSudo()) { result = await this.logout() // Logout the current sudo this._sudoToken.reset() } return result } // internal login method that manages default auth token and sudo workflow private async _login(newId?: string) { // for linty freshness, always logout sudo if set await this.sudoLogout() if (newId !== this.sudoId) { // Assign new requested sudo id this.sudoId = newId || '' } if (!this._authToken.isActive()) { this.reset() // only retain client API3 credentials for the lifetime of the login request const section = this.settings.readConfig() const clientId = section.client_id const clientSecret = section.client_secret if (!clientId || !clientSecret) { throw sdkError({ message: 'API credentials client_id and/or client_secret are not set', }) } const body = encodeParams({ client_id: clientId, client_secret: clientSecret, }) // authenticate client const token = await this.ok( this.transport.request<IAccessToken, IError>( strPost, `${this.apiPath}/login`, undefined, body ) ) this._authToken.setToken(token) } if (this.sudoId) { // Use the API user auth to sudo const token = this.activeToken const promise = this.transport.request<IAccessToken, IError>( strPost, encodeURI(`${this.apiPath}/login/${newId}`), null, null, // ensure the auth token is included in the sudo request (init: IRequestProps) => { if (token.access_token) { init.headers.Authorization = `Bearer ${token.access_token}` } return init }, this.settings // TODO this may not be needed here ) const accessToken = await this.ok(promise) this._sudoToken.setToken(accessToken) } return this.activeToken } private async _logout() { const token = this.activeToken const promise = this.transport.request<string, IError>( strDelete, `${this.apiPath}/logout`, null, null, // ensure the auth token is included in the logout promise (init: IRequestProps) => { if (token.access_token) { init.headers.Authorization = `Bearer ${token.access_token}` } return init }, this.settings ) await this.ok(promise) // If no error was thrown, logout was successful if (this.sudoId) { // User was logged out, so set auth back to default this.sudoId = '' this._sudoToken.reset() if (!this._authToken.isActive()) { await this.login() } } else { // completely logged out this.reset() } return true } }
return this.activeToken }
random_line_split
orbitcam.js
function OrbitCamera(basecam) { this._cam = basecam; this._viewpos = new THREE.Vector3(0.0,0.0,0.0); this._theta = 0; this._phi = 0; this._rate = 0.05; this._minradius = 0.1; this._maxradius = 20.0; this._radius = 5.0; this._tarphi = 0.0; this._tartheta = 0.0; this._reftheta = 0.0; this._tracked = false; this._trackslope = 0.6; this._tracktheta = 0.0; } function sphericalToCartesian(phi, theta, rad, offset) { var y = Math.sin(phi) * rad; var r2 = Math.cos(phi) * rad; var x = Math.cos(theta) * r2; var z = Math.sin(theta) * r2; var ret = new THREE.Vector3(x, y, z); if(offset) { ret.add(offset); } return ret; } OrbitCamera.prototype.setTracking = function(trackstate) { if(trackstate == true) { this._tracked = true; this._tracktheta = this._reftheta; } else { this._tracked = false; this._viewpos.set(0,0,0); } }; OrbitCamera.prototype.updateTrack = function() { var trackdist = -this._trackslope * this._radius;
this._viewpos.set(viewx, 0.0, viewz); }; OrbitCamera.prototype.updateCam = function() { if(this._tracked) { this.updateTrack(); } this._theta += ( this._tartheta + this._reftheta - this._theta ) * this._rate; this._phi += ( this._tarphi - this._phi ) * this._rate; this._cam.position.copy(sphericalToCartesian(this._phi, this._theta, this._radius, this._viewpos)); this._cam.lookAt( this._viewpos ); }; OrbitCamera.prototype.updateSpherical = function(targettheta, targetphi) { this._tarphi = targetphi; this._tartheta = targettheta; this.updateCam(); }; OrbitCamera.prototype.updateScreen = function(sx, sy, sw, sh) { var phi = ((sy / sh) * 2.0 - 1.0) * Math.PI; var theta = ((sx / sw) * 2.0 - 1.0) * Math.PI * 2.0; this.updateSpherical(theta, phi); }; OrbitCamera.prototype.updateZoomDelta = function(dzoom) { this._radius = Math.max(this._minradius, Math.min(this._maxradius, this._radius + dzoom)); this.updateCam(); }; OrbitCamera.prototype.setRefTheta = function(reftheta) { this._reftheta = reftheta; }; OrbitCamera.prototype.updateScreenDelta = function(dx, dy, sw, sh) { var dphi = ((dy / sh) * 1.0) * Math.PI; var dtheta = ((dx / sw) * 1.0) * Math.PI * 2.0; //console.log("sw: " + sw + ", sh: " + sh); //console.log("dphi: " + dphi + ", dtheta: " + dtheta); this._tartheta += dtheta; this._tarphi = Math.max(-Math.PI/2.0, Math.min(Math.PI/2.0, this._tarphi + dphi)); //console.log("tphi: " + this._tarphi + ", ttheta: " + this._tartheta); this.updateCam(); }; OrbitCamera.prototype.panScreenDelta = function(dx, dy, sw, sh) { var du = (dx / sw) * 100.0; var dv = (dy / sh) * 100.0; var ct = Math.cos(this._theta); var st = Math.sin(this._theta); var dz = du * ct - dv * st; var dx = -du * st - dv * ct; this._viewpos.x += dx; this._viewpos.z += dz; this.updateCam(); }; OrbitCamera.prototype.resetViewPos = function() { this._viewpos.set(0,0,0); }; var ocam; var mouseDownState = false; var mouseX = 0, mouseY = 0; var prevMouseX = 0, prevMouseY = 0; var mouseDX = 0, mouseDY = 0; var zoomButtonDown = false; var zoomButtonKeycode = 16; // shift var panButtonDown = false; var panButtonKeycode = 17; // ctrl function initOrbitCamera(rawcamera) { ocam = new OrbitCamera(rawcamera); document.addEventListener( 'mousedown', onCamMouseDown, false ); document.addEventListener( 'mouseup', onCamMouseUp, false ); document.addEventListener( 'mousemove', onCamDocumentMouseMove, false ); document.addEventListener( 'keydown', onCamDocumentKeyDown, false ); document.addEventListener( 'keyup', onCamDocumentKeyUp, false ); } function updateCamera() { mouseDX = mouseX - prevMouseX; mouseDY = mouseY - prevMouseY; prevMouseX = mouseX; prevMouseY = mouseY; if(mouseDownState == true) { //console.log("Dx: " + mouseDX + ", Dy: " + mouseDY) ocam.updateScreenDelta(mouseDX, mouseDY, windowX, windowY); } else if(zoomButtonDown) { ocam.updateZoomDelta(mouseDY / 10.0); } else if(panButtonDown) { ocam.panScreenDelta(mouseDX, mouseDY, windowX, windowY); } else { ocam.updateCam(); } } function onCamMouseDown() { mouseDownState = true; } function onCamMouseUp() { mouseDownState = false; } function onWindowResize() { getSize(); camera.aspect = windowX / windowY; camera.updateProjectionMatrix(); renderer.setSize( windowX, windowY ); } function onCamDocumentKeyDown(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = true; } if(event.keyCode == panButtonKeycode) { panButtonDown = true; } } function onCamDocumentKeyUp(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = false; } if(event.keyCode == panButtonKeycode) { panButtonDown = false; } } function onCamDocumentMouseMove( event ) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; }
this._tracktheta += ( this._reftheta - this._tracktheta ) * this._rate; var viewx = Math.cos(this._tracktheta) * trackdist; var viewz = Math.sin(this._tracktheta) * trackdist;
random_line_split
orbitcam.js
function OrbitCamera(basecam) { this._cam = basecam; this._viewpos = new THREE.Vector3(0.0,0.0,0.0); this._theta = 0; this._phi = 0; this._rate = 0.05; this._minradius = 0.1; this._maxradius = 20.0; this._radius = 5.0; this._tarphi = 0.0; this._tartheta = 0.0; this._reftheta = 0.0; this._tracked = false; this._trackslope = 0.6; this._tracktheta = 0.0; } function sphericalToCartesian(phi, theta, rad, offset)
OrbitCamera.prototype.setTracking = function(trackstate) { if(trackstate == true) { this._tracked = true; this._tracktheta = this._reftheta; } else { this._tracked = false; this._viewpos.set(0,0,0); } }; OrbitCamera.prototype.updateTrack = function() { var trackdist = -this._trackslope * this._radius; this._tracktheta += ( this._reftheta - this._tracktheta ) * this._rate; var viewx = Math.cos(this._tracktheta) * trackdist; var viewz = Math.sin(this._tracktheta) * trackdist; this._viewpos.set(viewx, 0.0, viewz); }; OrbitCamera.prototype.updateCam = function() { if(this._tracked) { this.updateTrack(); } this._theta += ( this._tartheta + this._reftheta - this._theta ) * this._rate; this._phi += ( this._tarphi - this._phi ) * this._rate; this._cam.position.copy(sphericalToCartesian(this._phi, this._theta, this._radius, this._viewpos)); this._cam.lookAt( this._viewpos ); }; OrbitCamera.prototype.updateSpherical = function(targettheta, targetphi) { this._tarphi = targetphi; this._tartheta = targettheta; this.updateCam(); }; OrbitCamera.prototype.updateScreen = function(sx, sy, sw, sh) { var phi = ((sy / sh) * 2.0 - 1.0) * Math.PI; var theta = ((sx / sw) * 2.0 - 1.0) * Math.PI * 2.0; this.updateSpherical(theta, phi); }; OrbitCamera.prototype.updateZoomDelta = function(dzoom) { this._radius = Math.max(this._minradius, Math.min(this._maxradius, this._radius + dzoom)); this.updateCam(); }; OrbitCamera.prototype.setRefTheta = function(reftheta) { this._reftheta = reftheta; }; OrbitCamera.prototype.updateScreenDelta = function(dx, dy, sw, sh) { var dphi = ((dy / sh) * 1.0) * Math.PI; var dtheta = ((dx / sw) * 1.0) * Math.PI * 2.0; //console.log("sw: " + sw + ", sh: " + sh); //console.log("dphi: " + dphi + ", dtheta: " + dtheta); this._tartheta += dtheta; this._tarphi = Math.max(-Math.PI/2.0, Math.min(Math.PI/2.0, this._tarphi + dphi)); //console.log("tphi: " + this._tarphi + ", ttheta: " + this._tartheta); this.updateCam(); }; OrbitCamera.prototype.panScreenDelta = function(dx, dy, sw, sh) { var du = (dx / sw) * 100.0; var dv = (dy / sh) * 100.0; var ct = Math.cos(this._theta); var st = Math.sin(this._theta); var dz = du * ct - dv * st; var dx = -du * st - dv * ct; this._viewpos.x += dx; this._viewpos.z += dz; this.updateCam(); }; OrbitCamera.prototype.resetViewPos = function() { this._viewpos.set(0,0,0); }; var ocam; var mouseDownState = false; var mouseX = 0, mouseY = 0; var prevMouseX = 0, prevMouseY = 0; var mouseDX = 0, mouseDY = 0; var zoomButtonDown = false; var zoomButtonKeycode = 16; // shift var panButtonDown = false; var panButtonKeycode = 17; // ctrl function initOrbitCamera(rawcamera) { ocam = new OrbitCamera(rawcamera); document.addEventListener( 'mousedown', onCamMouseDown, false ); document.addEventListener( 'mouseup', onCamMouseUp, false ); document.addEventListener( 'mousemove', onCamDocumentMouseMove, false ); document.addEventListener( 'keydown', onCamDocumentKeyDown, false ); document.addEventListener( 'keyup', onCamDocumentKeyUp, false ); } function updateCamera() { mouseDX = mouseX - prevMouseX; mouseDY = mouseY - prevMouseY; prevMouseX = mouseX; prevMouseY = mouseY; if(mouseDownState == true) { //console.log("Dx: " + mouseDX + ", Dy: " + mouseDY) ocam.updateScreenDelta(mouseDX, mouseDY, windowX, windowY); } else if(zoomButtonDown) { ocam.updateZoomDelta(mouseDY / 10.0); } else if(panButtonDown) { ocam.panScreenDelta(mouseDX, mouseDY, windowX, windowY); } else { ocam.updateCam(); } } function onCamMouseDown() { mouseDownState = true; } function onCamMouseUp() { mouseDownState = false; } function onWindowResize() { getSize(); camera.aspect = windowX / windowY; camera.updateProjectionMatrix(); renderer.setSize( windowX, windowY ); } function onCamDocumentKeyDown(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = true; } if(event.keyCode == panButtonKeycode) { panButtonDown = true; } } function onCamDocumentKeyUp(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = false; } if(event.keyCode == panButtonKeycode) { panButtonDown = false; } } function onCamDocumentMouseMove( event ) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; }
{ var y = Math.sin(phi) * rad; var r2 = Math.cos(phi) * rad; var x = Math.cos(theta) * r2; var z = Math.sin(theta) * r2; var ret = new THREE.Vector3(x, y, z); if(offset) { ret.add(offset); } return ret; }
identifier_body
orbitcam.js
function OrbitCamera(basecam) { this._cam = basecam; this._viewpos = new THREE.Vector3(0.0,0.0,0.0); this._theta = 0; this._phi = 0; this._rate = 0.05; this._minradius = 0.1; this._maxradius = 20.0; this._radius = 5.0; this._tarphi = 0.0; this._tartheta = 0.0; this._reftheta = 0.0; this._tracked = false; this._trackslope = 0.6; this._tracktheta = 0.0; } function sphericalToCartesian(phi, theta, rad, offset) { var y = Math.sin(phi) * rad; var r2 = Math.cos(phi) * rad; var x = Math.cos(theta) * r2; var z = Math.sin(theta) * r2; var ret = new THREE.Vector3(x, y, z); if(offset)
return ret; } OrbitCamera.prototype.setTracking = function(trackstate) { if(trackstate == true) { this._tracked = true; this._tracktheta = this._reftheta; } else { this._tracked = false; this._viewpos.set(0,0,0); } }; OrbitCamera.prototype.updateTrack = function() { var trackdist = -this._trackslope * this._radius; this._tracktheta += ( this._reftheta - this._tracktheta ) * this._rate; var viewx = Math.cos(this._tracktheta) * trackdist; var viewz = Math.sin(this._tracktheta) * trackdist; this._viewpos.set(viewx, 0.0, viewz); }; OrbitCamera.prototype.updateCam = function() { if(this._tracked) { this.updateTrack(); } this._theta += ( this._tartheta + this._reftheta - this._theta ) * this._rate; this._phi += ( this._tarphi - this._phi ) * this._rate; this._cam.position.copy(sphericalToCartesian(this._phi, this._theta, this._radius, this._viewpos)); this._cam.lookAt( this._viewpos ); }; OrbitCamera.prototype.updateSpherical = function(targettheta, targetphi) { this._tarphi = targetphi; this._tartheta = targettheta; this.updateCam(); }; OrbitCamera.prototype.updateScreen = function(sx, sy, sw, sh) { var phi = ((sy / sh) * 2.0 - 1.0) * Math.PI; var theta = ((sx / sw) * 2.0 - 1.0) * Math.PI * 2.0; this.updateSpherical(theta, phi); }; OrbitCamera.prototype.updateZoomDelta = function(dzoom) { this._radius = Math.max(this._minradius, Math.min(this._maxradius, this._radius + dzoom)); this.updateCam(); }; OrbitCamera.prototype.setRefTheta = function(reftheta) { this._reftheta = reftheta; }; OrbitCamera.prototype.updateScreenDelta = function(dx, dy, sw, sh) { var dphi = ((dy / sh) * 1.0) * Math.PI; var dtheta = ((dx / sw) * 1.0) * Math.PI * 2.0; //console.log("sw: " + sw + ", sh: " + sh); //console.log("dphi: " + dphi + ", dtheta: " + dtheta); this._tartheta += dtheta; this._tarphi = Math.max(-Math.PI/2.0, Math.min(Math.PI/2.0, this._tarphi + dphi)); //console.log("tphi: " + this._tarphi + ", ttheta: " + this._tartheta); this.updateCam(); }; OrbitCamera.prototype.panScreenDelta = function(dx, dy, sw, sh) { var du = (dx / sw) * 100.0; var dv = (dy / sh) * 100.0; var ct = Math.cos(this._theta); var st = Math.sin(this._theta); var dz = du * ct - dv * st; var dx = -du * st - dv * ct; this._viewpos.x += dx; this._viewpos.z += dz; this.updateCam(); }; OrbitCamera.prototype.resetViewPos = function() { this._viewpos.set(0,0,0); }; var ocam; var mouseDownState = false; var mouseX = 0, mouseY = 0; var prevMouseX = 0, prevMouseY = 0; var mouseDX = 0, mouseDY = 0; var zoomButtonDown = false; var zoomButtonKeycode = 16; // shift var panButtonDown = false; var panButtonKeycode = 17; // ctrl function initOrbitCamera(rawcamera) { ocam = new OrbitCamera(rawcamera); document.addEventListener( 'mousedown', onCamMouseDown, false ); document.addEventListener( 'mouseup', onCamMouseUp, false ); document.addEventListener( 'mousemove', onCamDocumentMouseMove, false ); document.addEventListener( 'keydown', onCamDocumentKeyDown, false ); document.addEventListener( 'keyup', onCamDocumentKeyUp, false ); } function updateCamera() { mouseDX = mouseX - prevMouseX; mouseDY = mouseY - prevMouseY; prevMouseX = mouseX; prevMouseY = mouseY; if(mouseDownState == true) { //console.log("Dx: " + mouseDX + ", Dy: " + mouseDY) ocam.updateScreenDelta(mouseDX, mouseDY, windowX, windowY); } else if(zoomButtonDown) { ocam.updateZoomDelta(mouseDY / 10.0); } else if(panButtonDown) { ocam.panScreenDelta(mouseDX, mouseDY, windowX, windowY); } else { ocam.updateCam(); } } function onCamMouseDown() { mouseDownState = true; } function onCamMouseUp() { mouseDownState = false; } function onWindowResize() { getSize(); camera.aspect = windowX / windowY; camera.updateProjectionMatrix(); renderer.setSize( windowX, windowY ); } function onCamDocumentKeyDown(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = true; } if(event.keyCode == panButtonKeycode) { panButtonDown = true; } } function onCamDocumentKeyUp(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = false; } if(event.keyCode == panButtonKeycode) { panButtonDown = false; } } function onCamDocumentMouseMove( event ) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; }
{ ret.add(offset); }
conditional_block
orbitcam.js
function OrbitCamera(basecam) { this._cam = basecam; this._viewpos = new THREE.Vector3(0.0,0.0,0.0); this._theta = 0; this._phi = 0; this._rate = 0.05; this._minradius = 0.1; this._maxradius = 20.0; this._radius = 5.0; this._tarphi = 0.0; this._tartheta = 0.0; this._reftheta = 0.0; this._tracked = false; this._trackslope = 0.6; this._tracktheta = 0.0; } function sphericalToCartesian(phi, theta, rad, offset) { var y = Math.sin(phi) * rad; var r2 = Math.cos(phi) * rad; var x = Math.cos(theta) * r2; var z = Math.sin(theta) * r2; var ret = new THREE.Vector3(x, y, z); if(offset) { ret.add(offset); } return ret; } OrbitCamera.prototype.setTracking = function(trackstate) { if(trackstate == true) { this._tracked = true; this._tracktheta = this._reftheta; } else { this._tracked = false; this._viewpos.set(0,0,0); } }; OrbitCamera.prototype.updateTrack = function() { var trackdist = -this._trackslope * this._radius; this._tracktheta += ( this._reftheta - this._tracktheta ) * this._rate; var viewx = Math.cos(this._tracktheta) * trackdist; var viewz = Math.sin(this._tracktheta) * trackdist; this._viewpos.set(viewx, 0.0, viewz); }; OrbitCamera.prototype.updateCam = function() { if(this._tracked) { this.updateTrack(); } this._theta += ( this._tartheta + this._reftheta - this._theta ) * this._rate; this._phi += ( this._tarphi - this._phi ) * this._rate; this._cam.position.copy(sphericalToCartesian(this._phi, this._theta, this._radius, this._viewpos)); this._cam.lookAt( this._viewpos ); }; OrbitCamera.prototype.updateSpherical = function(targettheta, targetphi) { this._tarphi = targetphi; this._tartheta = targettheta; this.updateCam(); }; OrbitCamera.prototype.updateScreen = function(sx, sy, sw, sh) { var phi = ((sy / sh) * 2.0 - 1.0) * Math.PI; var theta = ((sx / sw) * 2.0 - 1.0) * Math.PI * 2.0; this.updateSpherical(theta, phi); }; OrbitCamera.prototype.updateZoomDelta = function(dzoom) { this._radius = Math.max(this._minradius, Math.min(this._maxradius, this._radius + dzoom)); this.updateCam(); }; OrbitCamera.prototype.setRefTheta = function(reftheta) { this._reftheta = reftheta; }; OrbitCamera.prototype.updateScreenDelta = function(dx, dy, sw, sh) { var dphi = ((dy / sh) * 1.0) * Math.PI; var dtheta = ((dx / sw) * 1.0) * Math.PI * 2.0; //console.log("sw: " + sw + ", sh: " + sh); //console.log("dphi: " + dphi + ", dtheta: " + dtheta); this._tartheta += dtheta; this._tarphi = Math.max(-Math.PI/2.0, Math.min(Math.PI/2.0, this._tarphi + dphi)); //console.log("tphi: " + this._tarphi + ", ttheta: " + this._tartheta); this.updateCam(); }; OrbitCamera.prototype.panScreenDelta = function(dx, dy, sw, sh) { var du = (dx / sw) * 100.0; var dv = (dy / sh) * 100.0; var ct = Math.cos(this._theta); var st = Math.sin(this._theta); var dz = du * ct - dv * st; var dx = -du * st - dv * ct; this._viewpos.x += dx; this._viewpos.z += dz; this.updateCam(); }; OrbitCamera.prototype.resetViewPos = function() { this._viewpos.set(0,0,0); }; var ocam; var mouseDownState = false; var mouseX = 0, mouseY = 0; var prevMouseX = 0, prevMouseY = 0; var mouseDX = 0, mouseDY = 0; var zoomButtonDown = false; var zoomButtonKeycode = 16; // shift var panButtonDown = false; var panButtonKeycode = 17; // ctrl function initOrbitCamera(rawcamera) { ocam = new OrbitCamera(rawcamera); document.addEventListener( 'mousedown', onCamMouseDown, false ); document.addEventListener( 'mouseup', onCamMouseUp, false ); document.addEventListener( 'mousemove', onCamDocumentMouseMove, false ); document.addEventListener( 'keydown', onCamDocumentKeyDown, false ); document.addEventListener( 'keyup', onCamDocumentKeyUp, false ); } function updateCamera() { mouseDX = mouseX - prevMouseX; mouseDY = mouseY - prevMouseY; prevMouseX = mouseX; prevMouseY = mouseY; if(mouseDownState == true) { //console.log("Dx: " + mouseDX + ", Dy: " + mouseDY) ocam.updateScreenDelta(mouseDX, mouseDY, windowX, windowY); } else if(zoomButtonDown) { ocam.updateZoomDelta(mouseDY / 10.0); } else if(panButtonDown) { ocam.panScreenDelta(mouseDX, mouseDY, windowX, windowY); } else { ocam.updateCam(); } } function onCamMouseDown() { mouseDownState = true; } function
() { mouseDownState = false; } function onWindowResize() { getSize(); camera.aspect = windowX / windowY; camera.updateProjectionMatrix(); renderer.setSize( windowX, windowY ); } function onCamDocumentKeyDown(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = true; } if(event.keyCode == panButtonKeycode) { panButtonDown = true; } } function onCamDocumentKeyUp(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = false; } if(event.keyCode == panButtonKeycode) { panButtonDown = false; } } function onCamDocumentMouseMove( event ) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; }
onCamMouseUp
identifier_name
models.py
""" Data models used for Blockstore API Client """ from datetime import datetime from uuid import UUID import attr import six def _convert_to_uuid(value): if not isinstance(value, UUID): return UUID(value) return value @attr.s(frozen=True) class Collection(object): """ Metadata about a blockstore collection """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) title = attr.ib(type=six.text_type) @attr.s(frozen=True) class Bundle(object): """ Metadata about a blockstore bundle """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) title = attr.ib(type=six.text_type) description = attr.ib(type=six.text_type) slug = attr.ib(type=six.text_type) drafts = attr.ib(type=dict) # Dict of drafts, where keys are the draft names and values are draft UUIDs # Note that if latest_version is 0, it means that no versions yet exist latest_version = attr.ib(type=int, validator=attr.validators.instance_of(int)) @attr.s(frozen=True) class Draft(object): """ Metadata about a blockstore draft """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) name = attr.ib(type=six.text_type) updated_at = attr.ib(type=datetime, validator=attr.validators.instance_of(datetime)) files = attr.ib(type=dict) links = attr.ib(type=dict) @attr.s(frozen=True) class BundleFile(object): """ Metadata about a file in a blockstore bundle or draft. """ path = attr.ib(type=six.text_type) size = attr.ib(type=int) url = attr.ib(type=six.text_type) hash_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class DraftFile(BundleFile): """ Metadata about a file in a blockstore draft. """ modified = attr.ib(type=bool) # Was this file modified in the draft? @attr.s(frozen=True) class
(object): """ A pointer to a specific BundleVersion """ bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) version = attr.ib(type=int) snapshot_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class LinkDetails(object): """ Details about a specific link in a BundleVersion or Draft """ name = attr.ib(type=str) direct = attr.ib(type=LinkReference) indirect = attr.ib(type=list) # List of LinkReference objects @attr.s(frozen=True) class DraftLinkDetails(LinkDetails): """ Details about a specific link in a Draft """ modified = attr.ib(type=bool)
LinkReference
identifier_name
models.py
""" Data models used for Blockstore API Client """ from datetime import datetime from uuid import UUID import attr import six def _convert_to_uuid(value): if not isinstance(value, UUID):
return value @attr.s(frozen=True) class Collection(object): """ Metadata about a blockstore collection """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) title = attr.ib(type=six.text_type) @attr.s(frozen=True) class Bundle(object): """ Metadata about a blockstore bundle """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) title = attr.ib(type=six.text_type) description = attr.ib(type=six.text_type) slug = attr.ib(type=six.text_type) drafts = attr.ib(type=dict) # Dict of drafts, where keys are the draft names and values are draft UUIDs # Note that if latest_version is 0, it means that no versions yet exist latest_version = attr.ib(type=int, validator=attr.validators.instance_of(int)) @attr.s(frozen=True) class Draft(object): """ Metadata about a blockstore draft """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) name = attr.ib(type=six.text_type) updated_at = attr.ib(type=datetime, validator=attr.validators.instance_of(datetime)) files = attr.ib(type=dict) links = attr.ib(type=dict) @attr.s(frozen=True) class BundleFile(object): """ Metadata about a file in a blockstore bundle or draft. """ path = attr.ib(type=six.text_type) size = attr.ib(type=int) url = attr.ib(type=six.text_type) hash_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class DraftFile(BundleFile): """ Metadata about a file in a blockstore draft. """ modified = attr.ib(type=bool) # Was this file modified in the draft? @attr.s(frozen=True) class LinkReference(object): """ A pointer to a specific BundleVersion """ bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) version = attr.ib(type=int) snapshot_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class LinkDetails(object): """ Details about a specific link in a BundleVersion or Draft """ name = attr.ib(type=str) direct = attr.ib(type=LinkReference) indirect = attr.ib(type=list) # List of LinkReference objects @attr.s(frozen=True) class DraftLinkDetails(LinkDetails): """ Details about a specific link in a Draft """ modified = attr.ib(type=bool)
return UUID(value)
conditional_block
models.py
""" Data models used for Blockstore API Client """ from datetime import datetime from uuid import UUID import attr import six def _convert_to_uuid(value): if not isinstance(value, UUID): return UUID(value) return value @attr.s(frozen=True) class Collection(object): """ Metadata about a blockstore collection """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) title = attr.ib(type=six.text_type) @attr.s(frozen=True) class Bundle(object): """ Metadata about a blockstore bundle """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) title = attr.ib(type=six.text_type) description = attr.ib(type=six.text_type) slug = attr.ib(type=six.text_type) drafts = attr.ib(type=dict) # Dict of drafts, where keys are the draft names and values are draft UUIDs # Note that if latest_version is 0, it means that no versions yet exist latest_version = attr.ib(type=int, validator=attr.validators.instance_of(int)) @attr.s(frozen=True) class Draft(object): """ Metadata about a blockstore draft """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) name = attr.ib(type=six.text_type) updated_at = attr.ib(type=datetime, validator=attr.validators.instance_of(datetime)) files = attr.ib(type=dict) links = attr.ib(type=dict) @attr.s(frozen=True) class BundleFile(object): """ Metadata about a file in a blockstore bundle or draft.
url = attr.ib(type=six.text_type) hash_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class DraftFile(BundleFile): """ Metadata about a file in a blockstore draft. """ modified = attr.ib(type=bool) # Was this file modified in the draft? @attr.s(frozen=True) class LinkReference(object): """ A pointer to a specific BundleVersion """ bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) version = attr.ib(type=int) snapshot_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class LinkDetails(object): """ Details about a specific link in a BundleVersion or Draft """ name = attr.ib(type=str) direct = attr.ib(type=LinkReference) indirect = attr.ib(type=list) # List of LinkReference objects @attr.s(frozen=True) class DraftLinkDetails(LinkDetails): """ Details about a specific link in a Draft """ modified = attr.ib(type=bool)
""" path = attr.ib(type=six.text_type) size = attr.ib(type=int)
random_line_split
models.py
""" Data models used for Blockstore API Client """ from datetime import datetime from uuid import UUID import attr import six def _convert_to_uuid(value): if not isinstance(value, UUID): return UUID(value) return value @attr.s(frozen=True) class Collection(object): """ Metadata about a blockstore collection """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) title = attr.ib(type=six.text_type) @attr.s(frozen=True) class Bundle(object): """ Metadata about a blockstore bundle """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) title = attr.ib(type=six.text_type) description = attr.ib(type=six.text_type) slug = attr.ib(type=six.text_type) drafts = attr.ib(type=dict) # Dict of drafts, where keys are the draft names and values are draft UUIDs # Note that if latest_version is 0, it means that no versions yet exist latest_version = attr.ib(type=int, validator=attr.validators.instance_of(int)) @attr.s(frozen=True) class Draft(object): """ Metadata about a blockstore draft """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) name = attr.ib(type=six.text_type) updated_at = attr.ib(type=datetime, validator=attr.validators.instance_of(datetime)) files = attr.ib(type=dict) links = attr.ib(type=dict) @attr.s(frozen=True) class BundleFile(object): """ Metadata about a file in a blockstore bundle or draft. """ path = attr.ib(type=six.text_type) size = attr.ib(type=int) url = attr.ib(type=six.text_type) hash_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class DraftFile(BundleFile): """ Metadata about a file in a blockstore draft. """ modified = attr.ib(type=bool) # Was this file modified in the draft? @attr.s(frozen=True) class LinkReference(object): """ A pointer to a specific BundleVersion """ bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) version = attr.ib(type=int) snapshot_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class LinkDetails(object): """ Details about a specific link in a BundleVersion or Draft """ name = attr.ib(type=str) direct = attr.ib(type=LinkReference) indirect = attr.ib(type=list) # List of LinkReference objects @attr.s(frozen=True) class DraftLinkDetails(LinkDetails):
""" Details about a specific link in a Draft """ modified = attr.ib(type=bool)
identifier_body
MuiColorChit.js
import React from 'react'; import { withTheme } from '@material-ui/core'; const MuiColorChit = (props) => { let { theme } = props; let chitStyle = { flexGrow: 0, flexShrink: 0, width: props.size === "small" ? '16px' : '24px', height: props.size === "small" ? '16px' : '24px', borderRadius: '50%', background: props.color } let containerStyle = { flexGrow: 0, flexShrink: 0, display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', margin: props.isSelected ? '0px' : '8px', width: props.isSelected ? '32px' : '24px',
height: props.isSelected ? '32px' : '24px', borderRadius: '50%', background: theme.palette.action.selected, transition: theme.transitions.create(['width', 'height', 'margin']), } containerStyle.width = props.size === "small" ? '16px' : containerStyle.width; containerStyle.height = props.size === "small" ? '16px' : containerStyle.height; return ( <div style={containerStyle} onClick={props.onClick} > <div style={chitStyle}/> </div> ) }; export default withTheme()(MuiColorChit);
random_line_split
Link.js
'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Broadcasts = require('./Broadcasts'); var _PropTypes = require('./PropTypes'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call)
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Link = function (_React$Component) { _inherits(Link, _React$Component); function Link() { var _temp, _this, _ret; _classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.handleClick = function (event) { if (_this.props.onClick) _this.props.onClick(event); if (!event.defaultPrevented && // onClick prevented default !_this.props.target && // let browser handle "target=_blank" etc. !isModifiedEvent(event) && isLeftClickEvent(event)) { event.preventDefault(); _this.handleTransition(); } }, _this.handleTransition = function () { var router = _this.context.router; var _this$props = _this.props, to = _this$props.to, replace = _this$props.replace; var navigate = replace ? router.replaceWith : router.transitionTo; navigate(to); }, _temp), _possibleConstructorReturn(_this, _ret); } Link.prototype.render = function render() { var _this2 = this; var router = this.context.router; var _props = this.props, to = _props.to, style = _props.style, activeStyle = _props.activeStyle, className = _props.className, activeClassName = _props.activeClassName, getIsActive = _props.isActive, activeOnlyWhenExact = _props.activeOnlyWhenExact, replace = _props.replace, children = _props.children, rest = _objectWithoutProperties(_props, ['to', 'style', 'activeStyle', 'className', 'activeClassName', 'isActive', 'activeOnlyWhenExact', 'replace', 'children']); return _react2.default.createElement( _Broadcasts.LocationSubscriber, null, function (location) { var isActive = getIsActive(location, createLocationDescriptor(to), _this2.props); // If children is a function, we are using a Function as Children Component // so useful values will be passed down to the children function. if (typeof children == 'function') { return children({ isActive: isActive, location: location, href: router ? router.createHref(to) : to, onClick: _this2.handleClick, transition: _this2.handleTransition }); } // Maybe we should use <Match> here? Not sure how the custom `isActive` // prop would shake out, also, this check happens a LOT so maybe its good // to optimize here w/ a faster isActive check, so we'd need to benchmark // any attempt at changing to use <Match> return _react2.default.createElement('a', _extends({}, rest, { href: router ? router.createHref(to) : to, onClick: _this2.handleClick, style: isActive ? _extends({}, style, activeStyle) : style, className: isActive ? [className, activeClassName].join(' ').trim() : className, children: children })); } ); }; return Link; }(_react2.default.Component); Link.defaultProps = { replace: false, activeOnlyWhenExact: false, className: '', activeClassName: '', style: {}, activeStyle: {}, isActive: function isActive(location, to, props) { return pathIsActive(to.pathname, location.pathname, props.activeOnlyWhenExact) && queryIsActive(to.query, location.query); } }; Link.contextTypes = { router: _PropTypes.routerContext.isRequired }; if (process.env.NODE_ENV !== 'production') { Link.propTypes = { to: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]).isRequired, replace: _react.PropTypes.bool, activeStyle: _react.PropTypes.object, activeClassName: _react.PropTypes.string, activeOnlyWhenExact: _react.PropTypes.bool, isActive: _react.PropTypes.func, children: _react.PropTypes.oneOfType([_react.PropTypes.node, _react.PropTypes.func]), // props we have to deal with but aren't necessarily // part of the Link API style: _react.PropTypes.object, className: _react.PropTypes.string, target: _react.PropTypes.string, onClick: _react.PropTypes.func }; } // we should probably use LocationUtils.createLocationDescriptor var createLocationDescriptor = function createLocationDescriptor(to) { return (typeof to === 'undefined' ? 'undefined' : _typeof(to)) === 'object' ? to : { pathname: to }; }; var pathIsActive = function pathIsActive(to, pathname, activeOnlyWhenExact) { return activeOnlyWhenExact ? pathname === to : pathname.indexOf(to) === 0; }; var queryIsActive = function queryIsActive(query, activeQuery) { if (activeQuery == null) return query == null; if (query == null) return true; return deepEqual(query, activeQuery); }; var isLeftClickEvent = function isLeftClickEvent(event) { return event.button === 0; }; var isModifiedEvent = function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); }; var deepEqual = function deepEqual(a, b) { if (a == b) return true; if (a == null || b == null) return false; if (Array.isArray(a)) { return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return deepEqual(item, b[index]); }); } if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object') { for (var p in a) { if (!Object.prototype.hasOwnProperty.call(a, p)) { continue; } if (a[p] === undefined) { if (b[p] !== undefined) { return false; } } else if (!Object.prototype.hasOwnProperty.call(b, p)) { return false; } else if (!deepEqual(a[p], b[p])) { return false; } } return true; } return String(a) === String(b); }; exports.default = Link;
{ if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
identifier_body
Link.js
'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Broadcasts = require('./Broadcasts'); var _PropTypes = require('./PropTypes'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Link = function (_React$Component) { _inherits(Link, _React$Component); function Link() { var _temp, _this, _ret; _classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.handleClick = function (event) { if (_this.props.onClick) _this.props.onClick(event); if (!event.defaultPrevented && // onClick prevented default !_this.props.target && // let browser handle "target=_blank" etc. !isModifiedEvent(event) && isLeftClickEvent(event)) { event.preventDefault(); _this.handleTransition(); } }, _this.handleTransition = function () { var router = _this.context.router; var _this$props = _this.props, to = _this$props.to, replace = _this$props.replace; var navigate = replace ? router.replaceWith : router.transitionTo; navigate(to); }, _temp), _possibleConstructorReturn(_this, _ret); } Link.prototype.render = function render() { var _this2 = this; var router = this.context.router; var _props = this.props, to = _props.to, style = _props.style, activeStyle = _props.activeStyle, className = _props.className, activeClassName = _props.activeClassName, getIsActive = _props.isActive, activeOnlyWhenExact = _props.activeOnlyWhenExact, replace = _props.replace, children = _props.children, rest = _objectWithoutProperties(_props, ['to', 'style', 'activeStyle', 'className', 'activeClassName', 'isActive', 'activeOnlyWhenExact', 'replace', 'children']); return _react2.default.createElement( _Broadcasts.LocationSubscriber, null, function (location) { var isActive = getIsActive(location, createLocationDescriptor(to), _this2.props); // If children is a function, we are using a Function as Children Component // so useful values will be passed down to the children function. if (typeof children == 'function') { return children({ isActive: isActive, location: location, href: router ? router.createHref(to) : to, onClick: _this2.handleClick, transition: _this2.handleTransition }); } // Maybe we should use <Match> here? Not sure how the custom `isActive` // prop would shake out, also, this check happens a LOT so maybe its good // to optimize here w/ a faster isActive check, so we'd need to benchmark // any attempt at changing to use <Match> return _react2.default.createElement('a', _extends({}, rest, { href: router ? router.createHref(to) : to, onClick: _this2.handleClick, style: isActive ? _extends({}, style, activeStyle) : style, className: isActive ? [className, activeClassName].join(' ').trim() : className, children: children })); } ); }; return Link; }(_react2.default.Component); Link.defaultProps = { replace: false, activeOnlyWhenExact: false, className: '', activeClassName: '', style: {}, activeStyle: {}, isActive: function isActive(location, to, props) { return pathIsActive(to.pathname, location.pathname, props.activeOnlyWhenExact) && queryIsActive(to.query, location.query); } }; Link.contextTypes = { router: _PropTypes.routerContext.isRequired }; if (process.env.NODE_ENV !== 'production') { Link.propTypes = { to: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]).isRequired, replace: _react.PropTypes.bool, activeStyle: _react.PropTypes.object, activeClassName: _react.PropTypes.string, activeOnlyWhenExact: _react.PropTypes.bool, isActive: _react.PropTypes.func, children: _react.PropTypes.oneOfType([_react.PropTypes.node, _react.PropTypes.func]), // props we have to deal with but aren't necessarily // part of the Link API style: _react.PropTypes.object, className: _react.PropTypes.string, target: _react.PropTypes.string, onClick: _react.PropTypes.func }; } // we should probably use LocationUtils.createLocationDescriptor var createLocationDescriptor = function createLocationDescriptor(to) { return (typeof to === 'undefined' ? 'undefined' : _typeof(to)) === 'object' ? to : { pathname: to }; }; var pathIsActive = function pathIsActive(to, pathname, activeOnlyWhenExact) { return activeOnlyWhenExact ? pathname === to : pathname.indexOf(to) === 0; }; var queryIsActive = function queryIsActive(query, activeQuery) { if (activeQuery == null) return query == null; if (query == null) return true; return deepEqual(query, activeQuery); }; var isLeftClickEvent = function isLeftClickEvent(event) { return event.button === 0; }; var isModifiedEvent = function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); }; var deepEqual = function deepEqual(a, b) { if (a == b) return true; if (a == null || b == null) return false; if (Array.isArray(a)) { return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return deepEqual(item, b[index]); }); } if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object') { for (var p in a) { if (!Object.prototype.hasOwnProperty.call(a, p))
if (a[p] === undefined) { if (b[p] !== undefined) { return false; } } else if (!Object.prototype.hasOwnProperty.call(b, p)) { return false; } else if (!deepEqual(a[p], b[p])) { return false; } } return true; } return String(a) === String(b); }; exports.default = Link;
{ continue; }
conditional_block
Link.js
'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Broadcasts = require('./Broadcasts'); var _PropTypes = require('./PropTypes'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function
(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Link = function (_React$Component) { _inherits(Link, _React$Component); function Link() { var _temp, _this, _ret; _classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.handleClick = function (event) { if (_this.props.onClick) _this.props.onClick(event); if (!event.defaultPrevented && // onClick prevented default !_this.props.target && // let browser handle "target=_blank" etc. !isModifiedEvent(event) && isLeftClickEvent(event)) { event.preventDefault(); _this.handleTransition(); } }, _this.handleTransition = function () { var router = _this.context.router; var _this$props = _this.props, to = _this$props.to, replace = _this$props.replace; var navigate = replace ? router.replaceWith : router.transitionTo; navigate(to); }, _temp), _possibleConstructorReturn(_this, _ret); } Link.prototype.render = function render() { var _this2 = this; var router = this.context.router; var _props = this.props, to = _props.to, style = _props.style, activeStyle = _props.activeStyle, className = _props.className, activeClassName = _props.activeClassName, getIsActive = _props.isActive, activeOnlyWhenExact = _props.activeOnlyWhenExact, replace = _props.replace, children = _props.children, rest = _objectWithoutProperties(_props, ['to', 'style', 'activeStyle', 'className', 'activeClassName', 'isActive', 'activeOnlyWhenExact', 'replace', 'children']); return _react2.default.createElement( _Broadcasts.LocationSubscriber, null, function (location) { var isActive = getIsActive(location, createLocationDescriptor(to), _this2.props); // If children is a function, we are using a Function as Children Component // so useful values will be passed down to the children function. if (typeof children == 'function') { return children({ isActive: isActive, location: location, href: router ? router.createHref(to) : to, onClick: _this2.handleClick, transition: _this2.handleTransition }); } // Maybe we should use <Match> here? Not sure how the custom `isActive` // prop would shake out, also, this check happens a LOT so maybe its good // to optimize here w/ a faster isActive check, so we'd need to benchmark // any attempt at changing to use <Match> return _react2.default.createElement('a', _extends({}, rest, { href: router ? router.createHref(to) : to, onClick: _this2.handleClick, style: isActive ? _extends({}, style, activeStyle) : style, className: isActive ? [className, activeClassName].join(' ').trim() : className, children: children })); } ); }; return Link; }(_react2.default.Component); Link.defaultProps = { replace: false, activeOnlyWhenExact: false, className: '', activeClassName: '', style: {}, activeStyle: {}, isActive: function isActive(location, to, props) { return pathIsActive(to.pathname, location.pathname, props.activeOnlyWhenExact) && queryIsActive(to.query, location.query); } }; Link.contextTypes = { router: _PropTypes.routerContext.isRequired }; if (process.env.NODE_ENV !== 'production') { Link.propTypes = { to: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]).isRequired, replace: _react.PropTypes.bool, activeStyle: _react.PropTypes.object, activeClassName: _react.PropTypes.string, activeOnlyWhenExact: _react.PropTypes.bool, isActive: _react.PropTypes.func, children: _react.PropTypes.oneOfType([_react.PropTypes.node, _react.PropTypes.func]), // props we have to deal with but aren't necessarily // part of the Link API style: _react.PropTypes.object, className: _react.PropTypes.string, target: _react.PropTypes.string, onClick: _react.PropTypes.func }; } // we should probably use LocationUtils.createLocationDescriptor var createLocationDescriptor = function createLocationDescriptor(to) { return (typeof to === 'undefined' ? 'undefined' : _typeof(to)) === 'object' ? to : { pathname: to }; }; var pathIsActive = function pathIsActive(to, pathname, activeOnlyWhenExact) { return activeOnlyWhenExact ? pathname === to : pathname.indexOf(to) === 0; }; var queryIsActive = function queryIsActive(query, activeQuery) { if (activeQuery == null) return query == null; if (query == null) return true; return deepEqual(query, activeQuery); }; var isLeftClickEvent = function isLeftClickEvent(event) { return event.button === 0; }; var isModifiedEvent = function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); }; var deepEqual = function deepEqual(a, b) { if (a == b) return true; if (a == null || b == null) return false; if (Array.isArray(a)) { return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return deepEqual(item, b[index]); }); } if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object') { for (var p in a) { if (!Object.prototype.hasOwnProperty.call(a, p)) { continue; } if (a[p] === undefined) { if (b[p] !== undefined) { return false; } } else if (!Object.prototype.hasOwnProperty.call(b, p)) { return false; } else if (!deepEqual(a[p], b[p])) { return false; } } return true; } return String(a) === String(b); }; exports.default = Link;
_classCallCheck
identifier_name
Link.js
'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Broadcasts = require('./Broadcasts'); var _PropTypes = require('./PropTypes'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Link = function (_React$Component) { _inherits(Link, _React$Component); function Link() { var _temp, _this, _ret; _classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.handleClick = function (event) { if (_this.props.onClick) _this.props.onClick(event); if (!event.defaultPrevented && // onClick prevented default !_this.props.target && // let browser handle "target=_blank" etc. !isModifiedEvent(event) && isLeftClickEvent(event)) { event.preventDefault(); _this.handleTransition(); } }, _this.handleTransition = function () { var router = _this.context.router; var _this$props = _this.props, to = _this$props.to, replace = _this$props.replace; var navigate = replace ? router.replaceWith : router.transitionTo; navigate(to); }, _temp), _possibleConstructorReturn(_this, _ret); } Link.prototype.render = function render() { var _this2 = this; var router = this.context.router; var _props = this.props, to = _props.to, style = _props.style, activeStyle = _props.activeStyle, className = _props.className, activeClassName = _props.activeClassName, getIsActive = _props.isActive, activeOnlyWhenExact = _props.activeOnlyWhenExact, replace = _props.replace, children = _props.children, rest = _objectWithoutProperties(_props, ['to', 'style', 'activeStyle', 'className', 'activeClassName', 'isActive', 'activeOnlyWhenExact', 'replace', 'children']); return _react2.default.createElement( _Broadcasts.LocationSubscriber, null, function (location) { var isActive = getIsActive(location, createLocationDescriptor(to), _this2.props); // If children is a function, we are using a Function as Children Component // so useful values will be passed down to the children function. if (typeof children == 'function') { return children({ isActive: isActive, location: location, href: router ? router.createHref(to) : to, onClick: _this2.handleClick, transition: _this2.handleTransition }); } // Maybe we should use <Match> here? Not sure how the custom `isActive` // prop would shake out, also, this check happens a LOT so maybe its good // to optimize here w/ a faster isActive check, so we'd need to benchmark // any attempt at changing to use <Match> return _react2.default.createElement('a', _extends({}, rest, { href: router ? router.createHref(to) : to, onClick: _this2.handleClick, style: isActive ? _extends({}, style, activeStyle) : style, className: isActive ? [className, activeClassName].join(' ').trim() : className, children: children })); } ); }; return Link; }(_react2.default.Component); Link.defaultProps = { replace: false, activeOnlyWhenExact: false, className: '', activeClassName: '', style: {}, activeStyle: {}, isActive: function isActive(location, to, props) { return pathIsActive(to.pathname, location.pathname, props.activeOnlyWhenExact) && queryIsActive(to.query, location.query); } }; Link.contextTypes = { router: _PropTypes.routerContext.isRequired }; if (process.env.NODE_ENV !== 'production') { Link.propTypes = { to: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]).isRequired, replace: _react.PropTypes.bool, activeStyle: _react.PropTypes.object, activeClassName: _react.PropTypes.string, activeOnlyWhenExact: _react.PropTypes.bool, isActive: _react.PropTypes.func, children: _react.PropTypes.oneOfType([_react.PropTypes.node, _react.PropTypes.func]), // props we have to deal with but aren't necessarily // part of the Link API style: _react.PropTypes.object, className: _react.PropTypes.string, target: _react.PropTypes.string, onClick: _react.PropTypes.func }; } // we should probably use LocationUtils.createLocationDescriptor var createLocationDescriptor = function createLocationDescriptor(to) { return (typeof to === 'undefined' ? 'undefined' : _typeof(to)) === 'object' ? to : { pathname: to }; }; var pathIsActive = function pathIsActive(to, pathname, activeOnlyWhenExact) { return activeOnlyWhenExact ? pathname === to : pathname.indexOf(to) === 0; }; var queryIsActive = function queryIsActive(query, activeQuery) { if (activeQuery == null) return query == null; if (query == null) return true; return deepEqual(query, activeQuery); }; var isLeftClickEvent = function isLeftClickEvent(event) { return event.button === 0; };
var deepEqual = function deepEqual(a, b) { if (a == b) return true; if (a == null || b == null) return false; if (Array.isArray(a)) { return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return deepEqual(item, b[index]); }); } if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object') { for (var p in a) { if (!Object.prototype.hasOwnProperty.call(a, p)) { continue; } if (a[p] === undefined) { if (b[p] !== undefined) { return false; } } else if (!Object.prototype.hasOwnProperty.call(b, p)) { return false; } else if (!deepEqual(a[p], b[p])) { return false; } } return true; } return String(a) === String(b); }; exports.default = Link;
var isModifiedEvent = function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); };
random_line_split
volume_cubic_inches_to_metric_test.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import unittest from .volume_cubic_inches_to_metric import cubic_inches_to_metric class VolumeTestCase(unittest.TestCase): def test(self): text = ( "Total volume is 100.50 cubic inches for this land. "
"Total volume is 1-16 cb. in for this land. " "Total volume is 16.7-Cubic-in for this land. " "Total volume is 16,500-cu. in. for this land. " ) item = {"body_html": text} res, diff = cubic_inches_to_metric(item) self.assertEqual(diff["100.50 cubic inches"], "100.50 cubic inches (1,647 cubic centimeter)") self.assertEqual(diff["15.7 cubic in"], "15.7 cubic in (257.3 cubic centimeter)") self.assertEqual(diff["1 Cubic Inch"], "1 Cubic Inch (16 cubic centimeter)") self.assertEqual(diff["1-16 cu-in"], "1-16 cu-in (16-262 cubic centimeter)") self.assertEqual(diff["1-16 cb. in"], "1-16 cb. in (16-262 cubic centimeter)") self.assertEqual(diff["16.7-Cubic-in"], "16.7-Cubic-in (273.7 cubic centimeter)") self.assertEqual(diff["16,500-cu. in"], "16,500-cu. in (0.3 cubic meter)") self.assertEqual(res["body_html"], item["body_html"])
"Total volume is 15.7 cubic in for this land. " "Total volume is 1 Cubic Inch for this land. " "Total volume is 1-16 cu-in for this land. "
random_line_split
volume_cubic_inches_to_metric_test.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import unittest from .volume_cubic_inches_to_metric import cubic_inches_to_metric class VolumeTestCase(unittest.TestCase): def test(self):
text = ( "Total volume is 100.50 cubic inches for this land. " "Total volume is 15.7 cubic in for this land. " "Total volume is 1 Cubic Inch for this land. " "Total volume is 1-16 cu-in for this land. " "Total volume is 1-16 cb. in for this land. " "Total volume is 16.7-Cubic-in for this land. " "Total volume is 16,500-cu. in. for this land. " ) item = {"body_html": text} res, diff = cubic_inches_to_metric(item) self.assertEqual(diff["100.50 cubic inches"], "100.50 cubic inches (1,647 cubic centimeter)") self.assertEqual(diff["15.7 cubic in"], "15.7 cubic in (257.3 cubic centimeter)") self.assertEqual(diff["1 Cubic Inch"], "1 Cubic Inch (16 cubic centimeter)") self.assertEqual(diff["1-16 cu-in"], "1-16 cu-in (16-262 cubic centimeter)") self.assertEqual(diff["1-16 cb. in"], "1-16 cb. in (16-262 cubic centimeter)") self.assertEqual(diff["16.7-Cubic-in"], "16.7-Cubic-in (273.7 cubic centimeter)") self.assertEqual(diff["16,500-cu. in"], "16,500-cu. in (0.3 cubic meter)") self.assertEqual(res["body_html"], item["body_html"])
identifier_body
volume_cubic_inches_to_metric_test.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import unittest from .volume_cubic_inches_to_metric import cubic_inches_to_metric class
(unittest.TestCase): def test(self): text = ( "Total volume is 100.50 cubic inches for this land. " "Total volume is 15.7 cubic in for this land. " "Total volume is 1 Cubic Inch for this land. " "Total volume is 1-16 cu-in for this land. " "Total volume is 1-16 cb. in for this land. " "Total volume is 16.7-Cubic-in for this land. " "Total volume is 16,500-cu. in. for this land. " ) item = {"body_html": text} res, diff = cubic_inches_to_metric(item) self.assertEqual(diff["100.50 cubic inches"], "100.50 cubic inches (1,647 cubic centimeter)") self.assertEqual(diff["15.7 cubic in"], "15.7 cubic in (257.3 cubic centimeter)") self.assertEqual(diff["1 Cubic Inch"], "1 Cubic Inch (16 cubic centimeter)") self.assertEqual(diff["1-16 cu-in"], "1-16 cu-in (16-262 cubic centimeter)") self.assertEqual(diff["1-16 cb. in"], "1-16 cb. in (16-262 cubic centimeter)") self.assertEqual(diff["16.7-Cubic-in"], "16.7-Cubic-in (273.7 cubic centimeter)") self.assertEqual(diff["16,500-cu. in"], "16,500-cu. in (0.3 cubic meter)") self.assertEqual(res["body_html"], item["body_html"])
VolumeTestCase
identifier_name
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, Debug)] pub struct CartesianJoint<N: RealField> { position: Vector<N>, } impl<N: RealField> CartesianJoint<N> { /// Create a cartesian joint with an initial position given by `position`. pub fn new(position: Vector<N>) -> Self { CartesianJoint { position } } } impl<N: RealField> Joint<N> for CartesianJoint<N> { #[inline] fn ndofs(&self) -> usize { DIM } fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N> { let t = Translation::from(parent_shift - body_shift + self.position); Isometry::from_parts(t, na::one()) } fn update_jacobians(&mut self, _: &Vector<N>, _: &[N]) {} fn jacobian(&self, _: &Isometry<N>, out: &mut JacobianSliceMut<N>) { out.fill_diagonal(N::one()) } fn jacobian_dot(&self, _: &Isometry<N>, _: &mut JacobianSliceMut<N>) {} fn jacobian_dot_veldiff_mul_coordinates( &self, _: &Isometry<N>, _: &[N], _: &mut JacobianSliceMut<N>, ) { } fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { Velocity::from_vectors(Vector::from_row_slice(&vels[..DIM]), na::zero()) } fn jacobian_dot_mul_coordinates(&self, _: &[N]) -> Velocity<N> { Velocity::zero() } fn
(&self, _: &mut DVectorSliceMut<N>) {} fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]) { self.position += Vector::from_row_slice(&vels[..DIM]) * parameters.dt(); } fn apply_displacement(&mut self, disp: &[N]) { self.position += Vector::from_row_slice(&disp[..DIM]); } #[inline] fn clone(&self) -> Box<dyn Joint<N>> { Box::new(*self) } }
default_damping
identifier_name
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, Debug)] pub struct CartesianJoint<N: RealField> { position: Vector<N>, }
CartesianJoint { position } } } impl<N: RealField> Joint<N> for CartesianJoint<N> { #[inline] fn ndofs(&self) -> usize { DIM } fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N> { let t = Translation::from(parent_shift - body_shift + self.position); Isometry::from_parts(t, na::one()) } fn update_jacobians(&mut self, _: &Vector<N>, _: &[N]) {} fn jacobian(&self, _: &Isometry<N>, out: &mut JacobianSliceMut<N>) { out.fill_diagonal(N::one()) } fn jacobian_dot(&self, _: &Isometry<N>, _: &mut JacobianSliceMut<N>) {} fn jacobian_dot_veldiff_mul_coordinates( &self, _: &Isometry<N>, _: &[N], _: &mut JacobianSliceMut<N>, ) { } fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { Velocity::from_vectors(Vector::from_row_slice(&vels[..DIM]), na::zero()) } fn jacobian_dot_mul_coordinates(&self, _: &[N]) -> Velocity<N> { Velocity::zero() } fn default_damping(&self, _: &mut DVectorSliceMut<N>) {} fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]) { self.position += Vector::from_row_slice(&vels[..DIM]) * parameters.dt(); } fn apply_displacement(&mut self, disp: &[N]) { self.position += Vector::from_row_slice(&disp[..DIM]); } #[inline] fn clone(&self) -> Box<dyn Joint<N>> { Box::new(*self) } }
impl<N: RealField> CartesianJoint<N> { /// Create a cartesian joint with an initial position given by `position`. pub fn new(position: Vector<N>) -> Self {
random_line_split
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, Debug)] pub struct CartesianJoint<N: RealField> { position: Vector<N>, } impl<N: RealField> CartesianJoint<N> { /// Create a cartesian joint with an initial position given by `position`. pub fn new(position: Vector<N>) -> Self { CartesianJoint { position } } } impl<N: RealField> Joint<N> for CartesianJoint<N> { #[inline] fn ndofs(&self) -> usize { DIM } fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N> { let t = Translation::from(parent_shift - body_shift + self.position); Isometry::from_parts(t, na::one()) } fn update_jacobians(&mut self, _: &Vector<N>, _: &[N]) {} fn jacobian(&self, _: &Isometry<N>, out: &mut JacobianSliceMut<N>) { out.fill_diagonal(N::one()) } fn jacobian_dot(&self, _: &Isometry<N>, _: &mut JacobianSliceMut<N>)
fn jacobian_dot_veldiff_mul_coordinates( &self, _: &Isometry<N>, _: &[N], _: &mut JacobianSliceMut<N>, ) { } fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { Velocity::from_vectors(Vector::from_row_slice(&vels[..DIM]), na::zero()) } fn jacobian_dot_mul_coordinates(&self, _: &[N]) -> Velocity<N> { Velocity::zero() } fn default_damping(&self, _: &mut DVectorSliceMut<N>) {} fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]) { self.position += Vector::from_row_slice(&vels[..DIM]) * parameters.dt(); } fn apply_displacement(&mut self, disp: &[N]) { self.position += Vector::from_row_slice(&disp[..DIM]); } #[inline] fn clone(&self) -> Box<dyn Joint<N>> { Box::new(*self) } }
{}
identifier_body
tokens.py
# Copyright (C) 2014-2016 Andrey Antukh <[email protected]> # Copyright (C) 2014-2016 Jesús Espino <[email protected]> # Copyright (C) 2014-2016 David Barragán <[email protected]> # Copyright (C) 2014-2016 Alejandro Alonso <[email protected]> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from taiga.base import exceptions as exc from django.apps import apps from django.core import signing from django.utils.translation import ugettext as _ def ge
ser, scope): """ Generate a new signed token containing a specified user limited for a scope (identified as a string). """ data = {"user_%s_id" % (scope): user.id} return signing.dumps(data) def get_user_for_token(token, scope, max_age=None): """ Given a selfcontained token and a scope try to parse and unsign it. If max_age is specified it checks token expiration. If token passes a validation, returns a user instance corresponding with user_id stored in the incoming token. """ try: data = signing.loads(token, max_age=max_age) except signing.BadSignature: raise exc.NotAuthenticated(_("Invalid token")) model_cls = apps.get_model("users", "User") try: user = model_cls.objects.get(pk=data["user_%s_id" % (scope)]) except (model_cls.DoesNotExist, KeyError): raise exc.NotAuthenticated(_("Invalid token")) else: return user
t_token_for_user(u
identifier_name
tokens.py
# Copyright (C) 2014-2016 Andrey Antukh <[email protected]> # Copyright (C) 2014-2016 Jesús Espino <[email protected]> # Copyright (C) 2014-2016 David Barragán <[email protected]> # Copyright (C) 2014-2016 Alejandro Alonso <[email protected]> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from taiga.base import exceptions as exc from django.apps import apps from django.core import signing from django.utils.translation import ugettext as _ def get_token_for_user(user, scope): """ Generate a new signed token containing a specified user limited for a scope (identified as a string). """ data = {"user_%s_id" % (scope): user.id} return signing.dumps(data) def get_user_for_token(token, scope, max_age=None): """ Given a selfcontained token and a scope try to parse and unsign it. If max_age is specified it checks token expiration. If token passes a validation, returns a user instance corresponding with user_id stored in the incoming token. """ try: data = signing.loads(token, max_age=max_age) except signing.BadSignature: raise exc.NotAuthenticated(_("Invalid token"))
model_cls = apps.get_model("users", "User") try: user = model_cls.objects.get(pk=data["user_%s_id" % (scope)]) except (model_cls.DoesNotExist, KeyError): raise exc.NotAuthenticated(_("Invalid token")) else: return user
random_line_split
tokens.py
# Copyright (C) 2014-2016 Andrey Antukh <[email protected]> # Copyright (C) 2014-2016 Jesús Espino <[email protected]> # Copyright (C) 2014-2016 David Barragán <[email protected]> # Copyright (C) 2014-2016 Alejandro Alonso <[email protected]> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from taiga.base import exceptions as exc from django.apps import apps from django.core import signing from django.utils.translation import ugettext as _ def get_token_for_user(user, scope): """ Generate a new signed token containing a specified user limited for a scope (identified as a string). """ data = {"user_%s_id" % (scope): user.id} return signing.dumps(data) def get_user_for_token(token, scope, max_age=None): """ Given a selfcontained token and a scope try to parse and unsign it. If max_age is specified it checks token expiration. If token passes a validation, returns a user instance corresponding with user_id stored in the incoming token. """ try: data = signing.loads(token, max_age=max_age) except signing.BadSignature: raise exc.NotAuthenticated(_("Invalid token")) model_cls = apps.get_model("users", "User") try: user = model_cls.objects.get(pk=data["user_%s_id" % (scope)]) except (model_cls.DoesNotExist, KeyError): raise exc.NotAuthenticated(_("Invalid token")) else: re
turn user
conditional_block
tokens.py
# Copyright (C) 2014-2016 Andrey Antukh <[email protected]> # Copyright (C) 2014-2016 Jesús Espino <[email protected]> # Copyright (C) 2014-2016 David Barragán <[email protected]> # Copyright (C) 2014-2016 Alejandro Alonso <[email protected]> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from taiga.base import exceptions as exc from django.apps import apps from django.core import signing from django.utils.translation import ugettext as _ def get_token_for_user(user, scope): ""
def get_user_for_token(token, scope, max_age=None): """ Given a selfcontained token and a scope try to parse and unsign it. If max_age is specified it checks token expiration. If token passes a validation, returns a user instance corresponding with user_id stored in the incoming token. """ try: data = signing.loads(token, max_age=max_age) except signing.BadSignature: raise exc.NotAuthenticated(_("Invalid token")) model_cls = apps.get_model("users", "User") try: user = model_cls.objects.get(pk=data["user_%s_id" % (scope)]) except (model_cls.DoesNotExist, KeyError): raise exc.NotAuthenticated(_("Invalid token")) else: return user
" Generate a new signed token containing a specified user limited for a scope (identified as a string). """ data = {"user_%s_id" % (scope): user.id} return signing.dumps(data)
identifier_body
pa-in.js
//! moment.js locale configuration //! locale : Punjabi (India) [pa-in] //! author : Harpreet Singh : https://github.com/harpreetkhalsagtbit ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var symbolMap = { '1': '੧', '2': '੨', '3': '੩', '4': '੪', '5': '੫', '6': '੬', '7': '੭', '8': '੮', '9': '੯', '0': '੦' }, numberMap = { '੧': '1', '੨': '2', '੩': '3', '੪': '4', '੫': '5', '੬': '6', '੭': '7', '੮': '8', '੯': '9', '੦': '0' }; var pa_in = moment.defineLocale('pa-in', { // There are months name as per Nanakshahi Calender but they are not used as rigidly in modern Punjabi. months : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), monthsShort : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), weekdays : 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'), weekdaysShort : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), weekdaysMin : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), longDateFormat : { LT : 'A h:mm ਵਜੇ', LTS : 'A h:mm:ss ਵਜੇ', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm ਵਜੇ', LLLL : 'dddd, D MMMM YYYY, A h:mm ਵਜੇ' }, calendar : { sameDay : '[ਅਜ] LT', nextDay : '[ਕਲ] LT', nextWeek : 'dddd, LT', lastDay : '[ਕਲ] LT', lastWeek : '[ਪਿਛਲੇ] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s ਵਿੱਚ', past : '%s ਪਿਛਲੇ', s : 'ਕੁਝ ਸਕਿੰਟ', m : 'ਇਕ ਮਿੰਟ', mm : '%d ਮਿੰਟ', h : 'ਇੱਕ ਘੰਟਾ', hh : '%d ਘੰਟੇ', d : 'ਇੱਕ ਦਿਨ', dd : '%d ਦਿਨ', M : 'ਇੱਕ ਮਹੀਨਾ', MM : '%d ਮਹੀਨੇ', y : 'ਇੱਕ ਸਾਲ', yy : '%d ਸਾਲ' }, preparse: function (string) { return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, // Punjabi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi. meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'ਰਾਤ') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'ਸਵੇਰ') { return hour; } else if (meridiem === 'ਦੁਪਹਿਰ') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'ਸ਼ਾਮ') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ਰਾਤ'; } else if (hour < 10) { return 'ਸਵੇਰ'; } else if (hour < 17) { return 'ਦੁਪਹਿਰ'; } else if (hour < 20) { return 'ਸ਼ਾਮ'; } else { return 'ਰਾਤ'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); return pa_in; }));
conditional_block
pa-in.js
//! moment.js locale configuration //! locale : Punjabi (India) [pa-in] //! author : Harpreet Singh : https://github.com/harpreetkhalsagtbit ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var symbolMap = { '1': '੧', '2': '੨', '3': '੩', '4': '੪', '5': '੫', '6': '੬', '7': '੭', '8': '੮', '9': '੯', '0': '੦' }, numberMap = { '੧': '1', '੨': '2', '੩': '3', '੪': '4', '੫': '5', '੬': '6', '੭': '7', '੮': '8', '੯': '9', '੦': '0' }; var pa_in = moment.defineLocale('pa-in', { // There are months name as per Nanakshahi Calender but they are not used as rigidly in modern Punjabi. months : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), monthsShort : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), weekdays : 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'), weekdaysShort : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), weekdaysMin : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), longDateFormat : { LT : 'A h:mm ਵਜੇ', LTS : 'A h:mm:ss ਵਜੇ', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm ਵਜੇ', LLLL : 'dddd, D MMMM YYYY, A h:mm ਵਜੇ' }, calendar : { sameDay : '[ਅਜ] LT', nextDay : '[ਕਲ] LT', nextWeek : 'dddd, LT', lastDay : '[ਕਲ] LT', lastWeek : '[ਪਿਛਲੇ] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s ਵਿੱਚ', past : '%s ਪਿਛਲੇ', s : 'ਕੁਝ ਸਕਿੰਟ', m : 'ਇਕ ਮਿੰਟ', mm : '%d ਮਿੰਟ', h : 'ਇੱਕ ਘੰਟਾ', hh : '%d ਘੰਟੇ', d : 'ਇੱਕ ਦਿਨ', dd : '%d ਦਿਨ', M : 'ਇੱਕ ਮਹੀਨਾ', MM : '%d ਮਹੀਨੇ', y : 'ਇੱਕ ਸਾਲ', yy : '%d ਸਾਲ' }, preparse: function (string) { return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, // Punjabi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi. meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'ਰਾਤ') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'ਸਵੇਰ') { return hour; } else if (meridiem === 'ਦੁਪਹਿਰ') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'ਸ਼ਾਮ') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ਰਾਤ'; } else if (hour < 10) { return 'ਸਵੇਰ'; } else if (hour < 17) { return 'ਦੁਪਹਿਰ'; } else if (hour < 20) { return 'ਸ਼ਾਮ'; } else { return 'ਰਾਤ'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }
return pa_in; }));
});
random_line_split
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A multiplexed cita protocol use byteorder::{ByteOrder, NetworkEndian}; use bytes::{BufMut, Bytes, BytesMut}; use cita_types::Address; use logger::{error, warn}; use std::str; /// Implementation of the multiplexed line-based protocol. /// /// Frames begin with a 4 byte header, consisting of the numeric request ID /// encoded in network order, followed by the frame payload encoded as a UTF-8 /// string and terminated with a '\n' character: /// /// # An example frame: /// /// +------------------------+--------------------------+ /// | Type | Content | /// +------------------------+--------------------------+ /// | Symbol for Start | \xDEADBEEF | /// | Length of Full Payload | u32 | /// | Version | u64 | /// | Address | u8;20 | /// | Length of Key | u8 | /// | TTL | u8 | /// | Reserved | u8;2 | /// +------------------------+--------------------------+ /// | Key | bytes of a str | /// +------------------------+--------------------------+ /// | Message | a serialize data | /// +------------------------+--------------------------+ /// // Start of network messages. const NETMSG_START: u64 = 0xDEAD_BEEF_0000_0000; /// According to CITA frame, defines its frame header length as: /// "Symbol for Start" + "Length of Full Payload" + "Version"+ /// "Address"+ "Length of Key"+"TTL"+"Reserved", /// And this will consume "4 + 4 + 8 + 20 + 1 + 1+ 2" fixed-lengths of the frame. pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 8 + 20 + 1 + 1 + 2;
pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMessageUnit { pub key: String, pub data: Vec<u8>, pub addr: Address, pub version: u64, pub ttl: u8, } impl NetMessageUnit { pub fn new(key: String, data: Vec<u8>, addr: Address, version: u64, ttl: u8) -> Self { NetMessageUnit { key, data, addr, version, ttl, } } } impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn pubsub_message_to_network_message(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); return None; } let length_full = length_key + info.data.len(); // Use 1 bytes to store the length for key, then store key, the last part is body. if length_full > u32::max_value() as usize { error!( "[CitaProtocol] The MQ message with key {} is too long {}.", info.key, info.data.len() ); return None; } let mut buf = BytesMut::with_capacity(length_full + CITA_FRAME_HEADER_LEN); let request_id = NETMSG_START + length_full as u64; buf.put_u64_be(request_id); buf.put_u64_be(info.version); buf.put(info.addr.to_vec()); buf.put_u8(length_key as u8); buf.put_u8(info.ttl); buf.put_u16_be(0); buf.put(info.key.as_bytes()); buf.put_slice(&info.data); Some(buf.into()) } pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<NetMessageUnit> { if buf.len() < CITA_FRAME_HEADER_LEN { return None; } let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN); let request_id = NetworkEndian::read_u64(&head_buf); let netmsg_start = request_id & 0xffff_ffff_0000_0000; let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize; if netmsg_start != NETMSG_START { return None; } if length_full > buf.len() || length_full == 0 { return None; } let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]); let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]); let length_key = head_buf[HEAD_KEY_LEN_OFFSET] as usize; let ttl = head_buf[HEAD_TTL_OFFSET]; if length_key == 0 { error!("[CitaProtocol] Network message key is empty."); return None; } if length_key > buf.len() { error!( "[CitaProtocol] Buffer is not enough for key {} > {}.", length_key, buf.len() ); return None; } let key_buf = buf.split_to(length_key); let key_str_result = str::from_utf8(&key_buf); if key_str_result.is_err() { error!( "[CitaProtocol] Network message parse key error {:?}.", key_buf ); return None; } let key = key_str_result.unwrap().to_string(); if length_full == length_key { warn!("[CitaProtocol] Network message is empty."); } Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_empty_message() { let buf = pubsub_message_to_network_message(&NetMessageUnit::default()); let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::new()); assert!(pub_msg_opt.is_none()); assert!(buf.is_none()); } #[test] fn convert_messages() { let mut msg = NetMessageUnit::default(); let key = "this-is-the-key".to_string(); let data = vec![1, 3, 5, 7, 9]; msg.key = key.clone(); msg.data = data.clone(); let buf = pubsub_message_to_network_message(&msg).unwrap(); let pub_msg_opt = network_message_to_pubsub_message(&mut buf.try_mut().unwrap()); assert!(pub_msg_opt.is_some()); let info = pub_msg_opt.unwrap(); assert_eq!(key, info.key); assert_eq!(data, info.data); } }
pub const HEAD_VERSION_OFFSET: usize = 4 + 4;
random_line_split
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A multiplexed cita protocol use byteorder::{ByteOrder, NetworkEndian}; use bytes::{BufMut, Bytes, BytesMut}; use cita_types::Address; use logger::{error, warn}; use std::str; /// Implementation of the multiplexed line-based protocol. /// /// Frames begin with a 4 byte header, consisting of the numeric request ID /// encoded in network order, followed by the frame payload encoded as a UTF-8 /// string and terminated with a '\n' character: /// /// # An example frame: /// /// +------------------------+--------------------------+ /// | Type | Content | /// +------------------------+--------------------------+ /// | Symbol for Start | \xDEADBEEF | /// | Length of Full Payload | u32 | /// | Version | u64 | /// | Address | u8;20 | /// | Length of Key | u8 | /// | TTL | u8 | /// | Reserved | u8;2 | /// +------------------------+--------------------------+ /// | Key | bytes of a str | /// +------------------------+--------------------------+ /// | Message | a serialize data | /// +------------------------+--------------------------+ /// // Start of network messages. const NETMSG_START: u64 = 0xDEAD_BEEF_0000_0000; /// According to CITA frame, defines its frame header length as: /// "Symbol for Start" + "Length of Full Payload" + "Version"+ /// "Address"+ "Length of Key"+"TTL"+"Reserved", /// And this will consume "4 + 4 + 8 + 20 + 1 + 1+ 2" fixed-lengths of the frame. pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 8 + 20 + 1 + 1 + 2; pub const HEAD_VERSION_OFFSET: usize = 4 + 4; pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMessageUnit { pub key: String, pub data: Vec<u8>, pub addr: Address, pub version: u64, pub ttl: u8, } impl NetMessageUnit { pub fn new(key: String, data: Vec<u8>, addr: Address, version: u64, ttl: u8) -> Self
} impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn pubsub_message_to_network_message(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); return None; } let length_full = length_key + info.data.len(); // Use 1 bytes to store the length for key, then store key, the last part is body. if length_full > u32::max_value() as usize { error!( "[CitaProtocol] The MQ message with key {} is too long {}.", info.key, info.data.len() ); return None; } let mut buf = BytesMut::with_capacity(length_full + CITA_FRAME_HEADER_LEN); let request_id = NETMSG_START + length_full as u64; buf.put_u64_be(request_id); buf.put_u64_be(info.version); buf.put(info.addr.to_vec()); buf.put_u8(length_key as u8); buf.put_u8(info.ttl); buf.put_u16_be(0); buf.put(info.key.as_bytes()); buf.put_slice(&info.data); Some(buf.into()) } pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<NetMessageUnit> { if buf.len() < CITA_FRAME_HEADER_LEN { return None; } let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN); let request_id = NetworkEndian::read_u64(&head_buf); let netmsg_start = request_id & 0xffff_ffff_0000_0000; let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize; if netmsg_start != NETMSG_START { return None; } if length_full > buf.len() || length_full == 0 { return None; } let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]); let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]); let length_key = head_buf[HEAD_KEY_LEN_OFFSET] as usize; let ttl = head_buf[HEAD_TTL_OFFSET]; if length_key == 0 { error!("[CitaProtocol] Network message key is empty."); return None; } if length_key > buf.len() { error!( "[CitaProtocol] Buffer is not enough for key {} > {}.", length_key, buf.len() ); return None; } let key_buf = buf.split_to(length_key); let key_str_result = str::from_utf8(&key_buf); if key_str_result.is_err() { error!( "[CitaProtocol] Network message parse key error {:?}.", key_buf ); return None; } let key = key_str_result.unwrap().to_string(); if length_full == length_key { warn!("[CitaProtocol] Network message is empty."); } Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_empty_message() { let buf = pubsub_message_to_network_message(&NetMessageUnit::default()); let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::new()); assert!(pub_msg_opt.is_none()); assert!(buf.is_none()); } #[test] fn convert_messages() { let mut msg = NetMessageUnit::default(); let key = "this-is-the-key".to_string(); let data = vec![1, 3, 5, 7, 9]; msg.key = key.clone(); msg.data = data.clone(); let buf = pubsub_message_to_network_message(&msg).unwrap(); let pub_msg_opt = network_message_to_pubsub_message(&mut buf.try_mut().unwrap()); assert!(pub_msg_opt.is_some()); let info = pub_msg_opt.unwrap(); assert_eq!(key, info.key); assert_eq!(data, info.data); } }
{ NetMessageUnit { key, data, addr, version, ttl, } }
identifier_body
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A multiplexed cita protocol use byteorder::{ByteOrder, NetworkEndian}; use bytes::{BufMut, Bytes, BytesMut}; use cita_types::Address; use logger::{error, warn}; use std::str; /// Implementation of the multiplexed line-based protocol. /// /// Frames begin with a 4 byte header, consisting of the numeric request ID /// encoded in network order, followed by the frame payload encoded as a UTF-8 /// string and terminated with a '\n' character: /// /// # An example frame: /// /// +------------------------+--------------------------+ /// | Type | Content | /// +------------------------+--------------------------+ /// | Symbol for Start | \xDEADBEEF | /// | Length of Full Payload | u32 | /// | Version | u64 | /// | Address | u8;20 | /// | Length of Key | u8 | /// | TTL | u8 | /// | Reserved | u8;2 | /// +------------------------+--------------------------+ /// | Key | bytes of a str | /// +------------------------+--------------------------+ /// | Message | a serialize data | /// +------------------------+--------------------------+ /// // Start of network messages. const NETMSG_START: u64 = 0xDEAD_BEEF_0000_0000; /// According to CITA frame, defines its frame header length as: /// "Symbol for Start" + "Length of Full Payload" + "Version"+ /// "Address"+ "Length of Key"+"TTL"+"Reserved", /// And this will consume "4 + 4 + 8 + 20 + 1 + 1+ 2" fixed-lengths of the frame. pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 8 + 20 + 1 + 1 + 2; pub const HEAD_VERSION_OFFSET: usize = 4 + 4; pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMessageUnit { pub key: String, pub data: Vec<u8>, pub addr: Address, pub version: u64, pub ttl: u8, } impl NetMessageUnit { pub fn new(key: String, data: Vec<u8>, addr: Address, version: u64, ttl: u8) -> Self { NetMessageUnit { key, data, addr, version, ttl, } } } impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn
(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); return None; } let length_full = length_key + info.data.len(); // Use 1 bytes to store the length for key, then store key, the last part is body. if length_full > u32::max_value() as usize { error!( "[CitaProtocol] The MQ message with key {} is too long {}.", info.key, info.data.len() ); return None; } let mut buf = BytesMut::with_capacity(length_full + CITA_FRAME_HEADER_LEN); let request_id = NETMSG_START + length_full as u64; buf.put_u64_be(request_id); buf.put_u64_be(info.version); buf.put(info.addr.to_vec()); buf.put_u8(length_key as u8); buf.put_u8(info.ttl); buf.put_u16_be(0); buf.put(info.key.as_bytes()); buf.put_slice(&info.data); Some(buf.into()) } pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<NetMessageUnit> { if buf.len() < CITA_FRAME_HEADER_LEN { return None; } let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN); let request_id = NetworkEndian::read_u64(&head_buf); let netmsg_start = request_id & 0xffff_ffff_0000_0000; let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize; if netmsg_start != NETMSG_START { return None; } if length_full > buf.len() || length_full == 0 { return None; } let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]); let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]); let length_key = head_buf[HEAD_KEY_LEN_OFFSET] as usize; let ttl = head_buf[HEAD_TTL_OFFSET]; if length_key == 0 { error!("[CitaProtocol] Network message key is empty."); return None; } if length_key > buf.len() { error!( "[CitaProtocol] Buffer is not enough for key {} > {}.", length_key, buf.len() ); return None; } let key_buf = buf.split_to(length_key); let key_str_result = str::from_utf8(&key_buf); if key_str_result.is_err() { error!( "[CitaProtocol] Network message parse key error {:?}.", key_buf ); return None; } let key = key_str_result.unwrap().to_string(); if length_full == length_key { warn!("[CitaProtocol] Network message is empty."); } Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_empty_message() { let buf = pubsub_message_to_network_message(&NetMessageUnit::default()); let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::new()); assert!(pub_msg_opt.is_none()); assert!(buf.is_none()); } #[test] fn convert_messages() { let mut msg = NetMessageUnit::default(); let key = "this-is-the-key".to_string(); let data = vec![1, 3, 5, 7, 9]; msg.key = key.clone(); msg.data = data.clone(); let buf = pubsub_message_to_network_message(&msg).unwrap(); let pub_msg_opt = network_message_to_pubsub_message(&mut buf.try_mut().unwrap()); assert!(pub_msg_opt.is_some()); let info = pub_msg_opt.unwrap(); assert_eq!(key, info.key); assert_eq!(data, info.data); } }
pubsub_message_to_network_message
identifier_name
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A multiplexed cita protocol use byteorder::{ByteOrder, NetworkEndian}; use bytes::{BufMut, Bytes, BytesMut}; use cita_types::Address; use logger::{error, warn}; use std::str; /// Implementation of the multiplexed line-based protocol. /// /// Frames begin with a 4 byte header, consisting of the numeric request ID /// encoded in network order, followed by the frame payload encoded as a UTF-8 /// string and terminated with a '\n' character: /// /// # An example frame: /// /// +------------------------+--------------------------+ /// | Type | Content | /// +------------------------+--------------------------+ /// | Symbol for Start | \xDEADBEEF | /// | Length of Full Payload | u32 | /// | Version | u64 | /// | Address | u8;20 | /// | Length of Key | u8 | /// | TTL | u8 | /// | Reserved | u8;2 | /// +------------------------+--------------------------+ /// | Key | bytes of a str | /// +------------------------+--------------------------+ /// | Message | a serialize data | /// +------------------------+--------------------------+ /// // Start of network messages. const NETMSG_START: u64 = 0xDEAD_BEEF_0000_0000; /// According to CITA frame, defines its frame header length as: /// "Symbol for Start" + "Length of Full Payload" + "Version"+ /// "Address"+ "Length of Key"+"TTL"+"Reserved", /// And this will consume "4 + 4 + 8 + 20 + 1 + 1+ 2" fixed-lengths of the frame. pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 8 + 20 + 1 + 1 + 2; pub const HEAD_VERSION_OFFSET: usize = 4 + 4; pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMessageUnit { pub key: String, pub data: Vec<u8>, pub addr: Address, pub version: u64, pub ttl: u8, } impl NetMessageUnit { pub fn new(key: String, data: Vec<u8>, addr: Address, version: u64, ttl: u8) -> Self { NetMessageUnit { key, data, addr, version, ttl, } } } impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn pubsub_message_to_network_message(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); return None; } let length_full = length_key + info.data.len(); // Use 1 bytes to store the length for key, then store key, the last part is body. if length_full > u32::max_value() as usize { error!( "[CitaProtocol] The MQ message with key {} is too long {}.", info.key, info.data.len() ); return None; } let mut buf = BytesMut::with_capacity(length_full + CITA_FRAME_HEADER_LEN); let request_id = NETMSG_START + length_full as u64; buf.put_u64_be(request_id); buf.put_u64_be(info.version); buf.put(info.addr.to_vec()); buf.put_u8(length_key as u8); buf.put_u8(info.ttl); buf.put_u16_be(0); buf.put(info.key.as_bytes()); buf.put_slice(&info.data); Some(buf.into()) } pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<NetMessageUnit> { if buf.len() < CITA_FRAME_HEADER_LEN { return None; } let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN); let request_id = NetworkEndian::read_u64(&head_buf); let netmsg_start = request_id & 0xffff_ffff_0000_0000; let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize; if netmsg_start != NETMSG_START { return None; } if length_full > buf.len() || length_full == 0 { return None; } let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]); let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]); let length_key = head_buf[HEAD_KEY_LEN_OFFSET] as usize; let ttl = head_buf[HEAD_TTL_OFFSET]; if length_key == 0 { error!("[CitaProtocol] Network message key is empty."); return None; } if length_key > buf.len() { error!( "[CitaProtocol] Buffer is not enough for key {} > {}.", length_key, buf.len() ); return None; } let key_buf = buf.split_to(length_key); let key_str_result = str::from_utf8(&key_buf); if key_str_result.is_err() { error!( "[CitaProtocol] Network message parse key error {:?}.", key_buf ); return None; } let key = key_str_result.unwrap().to_string(); if length_full == length_key
Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_empty_message() { let buf = pubsub_message_to_network_message(&NetMessageUnit::default()); let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::new()); assert!(pub_msg_opt.is_none()); assert!(buf.is_none()); } #[test] fn convert_messages() { let mut msg = NetMessageUnit::default(); let key = "this-is-the-key".to_string(); let data = vec![1, 3, 5, 7, 9]; msg.key = key.clone(); msg.data = data.clone(); let buf = pubsub_message_to_network_message(&msg).unwrap(); let pub_msg_opt = network_message_to_pubsub_message(&mut buf.try_mut().unwrap()); assert!(pub_msg_opt.is_some()); let info = pub_msg_opt.unwrap(); assert_eq!(key, info.key); assert_eq!(data, info.data); } }
{ warn!("[CitaProtocol] Network message is empty."); }
conditional_block
worker.js
// Generated by CoffeeScript 1.8.0 var BITSTR, DERNULL, INTERGER, OID, PRTSTR, SEQUENCE, SET, TAG, UTF8STR, asn1Util, cryptoUtil, generateCSR, generateKeyPair, j, keyUtil, onmessage; postMessage({ type: 'status', message: 'Importing JSRSASign library ...' }); importScripts('jsrsasign-4.7.0-all-min.js'); j = KJUR; keyUtil = KEYUTIL; asn1Util = j.asn1.ASN1Util; cryptoUtil = j.crypto.Util; SEQUENCE = function(arr) { return new j.asn1.DERSequence({ 'array': arr }); };
SET = function(arr) { return new j.asn1.DERSet({ 'array': arr }); }; INTERGER = function(num) { return new j.asn1.DERInteger({ 'int': num }); }; PRTSTR = function(str) { return new j.asn1.DERPrintableString({ 'str': str }); }; UTF8STR = function(str) { return new j.asn1.DERUTF8String({ 'str': str }); }; BITSTR = function(hex) { return new j.asn1.DERBitString({ 'hex': hex }); }; OID = function(oid) { return j.asn1.x509.OID.name2obj(oid); }; TAG = function(tag) { return new j.asn1.DERTaggedObject({ 'tag': tag || 'a0' }); }; DERNULL = function() { return new j.asn1.DERNull(); }; generateKeyPair = function(len) { var keyPair, privateKeyHex, privateKeyObj, privateKeyPEM, publicKeyHex, publicKeyObj, publicKeyPEM, ret, tbl; ret = {}; tbl = [324, 588]; keyPair = keyUtil.generateKeypair("RSA", len); privateKeyObj = ret.privateKeyObj = keyPair.prvKeyObj; publicKeyObj = ret.publicKeyObj = keyPair.pubKeyObj; privateKeyObj.isPrivate = true; privateKeyPEM = ret.privateKeyPEM = keyUtil.getPEM(privateKeyObj, "PKCS8PRV"); privateKeyHex = ret.privateKeyHex = keyUtil.getHexFromPEM(privateKeyPEM, "PRIVATE KEY"); publicKeyPEM = ret.publicKeyPEM = keyUtil.getPEM(publicKeyObj); publicKeyHex = ret.publicKeyHex = keyUtil.getHexFromPEM(publicKeyPEM, "PUBLIC KEY"); if (tbl.indexOf(ret.publicKeyHex.length) === -1) { return false; } return ret; }; generateCSR = function(data, keyPair, alg) { var certificateRequestInfo, sig; alg = alg || 'SHA256withRSA'; certificateRequestInfo = SEQUENCE([INTERGER(0), SEQUENCE([SET([SEQUENCE([OID("countryName"), PRTSTR(data.countryName)])]), SET([SEQUENCE([OID("stateOrProvinceName"), UTF8STR(data.stateOrProvinceName)])]), SET([SEQUENCE([OID("locality"), UTF8STR(data.locality)])]), SET([SEQUENCE([OID("organization"), UTF8STR(data.organization)])]), SET([SEQUENCE([OID("commonName"), UTF8STR(data.commonName)])])]), new j.asn1.x509.SubjectPublicKeyInfo(keyPair.publicKeyObj), TAG()]); sig = new j.crypto.Signature({ alg: alg }); sig.init(keyPair.privateKeyPEM); sig.updateHex(certificateRequestInfo.getEncodedHex()); return SEQUENCE([certificateRequestInfo, SEQUENCE([OID(alg), DERNULL()]), BITSTR('00' + sig.sign())]); }; onmessage = function(e) { var CSR, CSRPEM, data, keyPair; data = e.data.workload; postMessage({ type: 'status', message: 'Generating private key ...' }); keyPair = false; while (1) { keyPair = generateKeyPair(parseInt(data.keySize)); if (keyPair === false) { postMessage({ type: 'status', message: 'Regenerating private key ...' }); } else { break; } } postMessage({ type: 'status', message: 'Generating CSR ...' }); CSR = generateCSR(data, keyPair, "SHA256withRSA"); postMessage({ type: 'status', message: 'Converting CSR to PEM format ...' }); CSRPEM = asn1Util.getPEMStringFromHex(CSR.getEncodedHex(), "CERTIFICATE REQUEST"); postMessage({ type: 'private', pem: keyPair.privateKeyPEM }); postMessage({ type: 'csr', pem: CSRPEM }); return postMessage({ type: 'done' }); };
random_line_split