repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
CodeKittey/lycheeJS
libraries/lychee/source/platform/node/Viewport.js
2921
lychee.define('Viewport').tags({ platform: 'node' }).includes([ 'lychee.event.Emitter' ]).supports(function(lychee, global) { if (typeof process !== 'undefined') { if (typeof process.stdout === 'object' && typeof process.stdout.on === 'function') { return true; } } return false; }).exports(function(lychee, global) { /* * EVENTS */ var _instances = []; var _listeners = { resize: function() { for (var i = 0, l = _instances.length; i < l; i++) { _process_reshape.call(_instances[i], process.stdout.columns, process.stdout.rows); } } }; /* * FEATURE DETECTION */ (function() { var resize = true; if (resize === true) { process.stdout.on('resize', _listeners.resize); } if (lychee.debug === true) { var methods = []; if (resize) methods.push('Resize'); if (methods.length === 0) { console.error('lychee.Viewport: Supported methods are NONE'); } else { console.info('lychee.Viewport: Supported methods are ' + methods.join(', ')); } } })(); /* * HELPERS */ var _process_reshape = function(width, height) { if (width === this.width && height === this.height) { return false; } this.width = width; this.height = height; var orientation = null; var rotation = null; if (width > height) { orientation = 'landscape'; rotation = 'landscape'; } else { orientation = 'landscape'; rotation = 'landscape'; } return this.trigger('reshape', [ orientation, rotation, width, height ]); }; /* * IMPLEMENTATION */ var Class = function(data) { var settings = lychee.extend({}, data); this.fullscreen = false; this.width = process.stdout.columns; this.height = process.stdout.rows; this.__orientation = 0; // Unsupported lychee.event.Emitter.call(this); _instances.push(this); this.setFullscreen(settings.fullscreen); /* * INITIALIZATION */ setTimeout(function() { this.width = 0; this.height = 0; _process_reshape.call(this, process.stdout.columns, process.stdout.rows); }.bind(this), 100); settings = null; }; Class.prototype = { destroy: function() { var found = false; for (var i = 0, il = _instances.length; i < il; i++) { if (_instances[i] === this) { _instances.splice(i, 1); found = true; il--; i--; } } this.unbind(); return found; }, /* * ENTITY API */ // deserialize: function(blob) {}, serialize: function() { var data = lychee.event.Emitter.prototype.serialize.call(this); data['constructor'] = 'lychee.Viewport'; var settings = {}; if (this.fullscreen !== false) settings.fullscreen = this.fullscreen; data['arguments'][0] = settings; return data; }, /* * CUSTOM API */ setFullscreen: function(fullscreen) { return false; } }; return Class; });
mit
anaviltripathi/pgmpy
pgmpy/tests/test_models/test_BayesianModel.py
23605
import unittest import networkx as nx import pandas as pd import numpy as np import numpy.testing as np_test from pgmpy.models import BayesianModel import pgmpy.tests.help_functions as hf from pgmpy.factors import TabularCPD, JointProbabilityDistribution, Factor from pgmpy.independencies import Independencies from pgmpy.extern import six class TestBaseModelCreation(unittest.TestCase): def setUp(self): self.G = BayesianModel() def test_class_init_without_data(self): self.assertIsInstance(self.G, nx.DiGraph) def test_class_init_with_data_string(self): self.g = BayesianModel([('a', 'b'), ('b', 'c')]) self.assertListEqual(sorted(self.g.nodes()), ['a', 'b', 'c']) self.assertListEqual(hf.recursive_sorted(self.g.edges()), [['a', 'b'], ['b', 'c']]) def test_class_init_with_data_nonstring(self): BayesianModel([(1, 2), (2, 3)]) def test_add_node_string(self): self.G.add_node('a') self.assertListEqual(self.G.nodes(), ['a']) def test_add_node_nonstring(self): self.G.add_node(1) def test_add_nodes_from_string(self): self.G.add_nodes_from(['a', 'b', 'c', 'd']) self.assertListEqual(sorted(self.G.nodes()), ['a', 'b', 'c', 'd']) def test_add_nodes_from_non_string(self): self.G.add_nodes_from([1, 2, 3, 4]) def test_add_edge_string(self): self.G.add_edge('d', 'e') self.assertListEqual(sorted(self.G.nodes()), ['d', 'e']) self.assertListEqual(self.G.edges(), [('d', 'e')]) self.G.add_nodes_from(['a', 'b', 'c']) self.G.add_edge('a', 'b') self.assertListEqual(hf.recursive_sorted(self.G.edges()), [['a', 'b'], ['d', 'e']]) def test_add_edge_nonstring(self): self.G.add_edge(1, 2) def test_add_edge_selfloop(self): self.assertRaises(ValueError, self.G.add_edge, 'a', 'a') def test_add_edge_result_cycle(self): self.G.add_edges_from([('a', 'b'), ('a', 'c')]) self.assertRaises(ValueError, self.G.add_edge, 'c', 'a') def test_add_edges_from_string(self): self.G.add_edges_from([('a', 'b'), ('b', 'c')]) self.assertListEqual(sorted(self.G.nodes()), ['a', 'b', 'c']) self.assertListEqual(hf.recursive_sorted(self.G.edges()), [['a', 'b'], ['b', 'c']]) self.G.add_nodes_from(['d', 'e', 'f']) self.G.add_edges_from([('d', 'e'), ('e', 'f')]) self.assertListEqual(sorted(self.G.nodes()), ['a', 'b', 'c', 'd', 'e', 'f']) self.assertListEqual(hf.recursive_sorted(self.G.edges()), hf.recursive_sorted([('a', 'b'), ('b', 'c'), ('d', 'e'), ('e', 'f')])) def test_add_edges_from_nonstring(self): self.G.add_edges_from([(1, 2), (2, 3)]) def test_add_edges_from_self_loop(self): self.assertRaises(ValueError, self.G.add_edges_from, [('a', 'a')]) def test_add_edges_from_result_cycle(self): self.assertRaises(ValueError, self.G.add_edges_from, [('a', 'b'), ('b', 'c'), ('c', 'a')]) def test_update_node_parents_bm_constructor(self): self.g = BayesianModel([('a', 'b'), ('b', 'c')]) self.assertListEqual(self.g.predecessors('a'), []) self.assertListEqual(self.g.predecessors('b'), ['a']) self.assertListEqual(self.g.predecessors('c'), ['b']) def test_update_node_parents(self): self.G.add_nodes_from(['a', 'b', 'c']) self.G.add_edges_from([('a', 'b'), ('b', 'c')]) self.assertListEqual(self.G.predecessors('a'), []) self.assertListEqual(self.G.predecessors('b'), ['a']) self.assertListEqual(self.G.predecessors('c'), ['b']) def tearDown(self): del self.G class TestBayesianModelMethods(unittest.TestCase): def setUp(self): self.G = BayesianModel([('a', 'd'), ('b', 'd'), ('d', 'e'), ('b', 'c')]) self.G1 = BayesianModel([('diff', 'grade'), ('intel', 'grade')]) diff_cpd = TabularCPD('diff', 2, values=[[0.2], [0.8]]) intel_cpd = TabularCPD('intel', 3, values=[[0.5], [0.3], [0.2]]) grade_cpd = TabularCPD('grade', 3, values=[[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]], evidence=['diff', 'intel'], evidence_card=[2, 3]) self.G1.add_cpds(diff_cpd, intel_cpd, grade_cpd) def test_moral_graph(self): moral_graph = self.G.moralize() self.assertListEqual(sorted(moral_graph.nodes()), ['a', 'b', 'c', 'd', 'e']) for edge in moral_graph.edges(): self.assertTrue(edge in [('a', 'b'), ('a', 'd'), ('b', 'c'), ('d', 'b'), ('e', 'd')] or (edge[1], edge[0]) in [('a', 'b'), ('a', 'd'), ('b', 'c'), ('d', 'b'), ('e', 'd')]) def test_moral_graph_with_edge_present_over_parents(self): G = BayesianModel([('a', 'd'), ('d', 'e'), ('b', 'd'), ('b', 'c'), ('a', 'b')]) moral_graph = G.moralize() self.assertListEqual(sorted(moral_graph.nodes()), ['a', 'b', 'c', 'd', 'e']) for edge in moral_graph.edges(): self.assertTrue(edge in [('a', 'b'), ('c', 'b'), ('d', 'a'), ('d', 'b'), ('d', 'e')] or (edge[1], edge[0]) in [('a', 'b'), ('c', 'b'), ('d', 'a'), ('d', 'b'), ('d', 'e')]) def test_local_independencies(self): self.assertEqual(self.G.local_independencies('a'), Independencies(['a', ['b', 'c']])) self.assertEqual(self.G.local_independencies('c'), Independencies(['c', ['a', 'd', 'e'], 'b'])) self.assertEqual(self.G.local_independencies('d'), Independencies(['d', 'c', ['b', 'a']])) self.assertEqual(self.G.local_independencies('e'), Independencies(['e', ['c', 'b', 'a'], 'd'])) self.assertEqual(self.G.local_independencies('b'), Independencies(['b', 'a'])) self.assertEqual(self.G1.local_independencies('grade'), Independencies()) def test_get_independencies(self): chain = BayesianModel([('X', 'Y'), ('Y', 'Z')]) self.assertEqual(chain.get_independencies(), Independencies(('X', 'Z', 'Y'), ('Z', 'X', 'Y'))) fork = BayesianModel([('Y', 'X'), ('Y', 'Z')]) self.assertEqual(fork.get_independencies(), Independencies(('X', 'Z', 'Y'), ('Z', 'X', 'Y'))) collider = BayesianModel([('X', 'Y'), ('Z', 'Y')]) self.assertEqual(collider.get_independencies(), Independencies(('X', 'Z'), ('Z', 'X'))) def test_is_imap(self): val = [0.01, 0.01, 0.08, 0.006, 0.006, 0.048, 0.004, 0.004, 0.032, 0.04, 0.04, 0.32, 0.024, 0.024, 0.192, 0.016, 0.016, 0.128] JPD = JointProbabilityDistribution(['diff', 'intel', 'grade'], [2, 3, 3], val) fac = Factor(['diff', 'intel', 'grade'], [2, 3, 3], val) self.assertTrue(self.G1.is_imap(JPD)) self.assertRaises(TypeError, self.G1.is_imap, fac) def test_get_immoralities(self): G = BayesianModel([('x', 'y'), ('z', 'y'), ('x', 'z'), ('w', 'y')]) self.assertEqual(G.get_immoralities(), {('w', 'x'), ('w', 'z')}) G1 = BayesianModel([('x', 'y'), ('z', 'y'), ('z', 'x'), ('w', 'y')]) self.assertEqual(G1.get_immoralities(), {('w', 'x'), ('w', 'z')}) G2 = BayesianModel([('x', 'y'), ('z', 'y'), ('x', 'z'), ('w', 'y'), ('w', 'x')]) self.assertEqual(G2.get_immoralities(), {('w', 'z')}) def test_is_iequivalent(self): from pgmpy.models import MarkovModel G = BayesianModel([('x', 'y'), ('z', 'y'), ('x', 'z'), ('w', 'y')]) self.assertRaises(TypeError, G.is_iequivalent, MarkovModel()) G1 = BayesianModel([('V', 'W'), ('W', 'X'), ('X', 'Y'), ('Z', 'Y')]) G2 = BayesianModel([('W', 'V'), ('X', 'W'), ('X', 'Y'), ('Z', 'Y')]) self.assertTrue(G1.is_iequivalent(G2)) G3 = BayesianModel([('W', 'V'), ('W', 'X'), ('Y', 'X'), ('Z', 'Y')]) self.assertFalse(G3.is_iequivalent(G2)) def tearDown(self): del self.G del self.G1 class TestBayesianModelCPD(unittest.TestCase): def setUp(self): self.G = BayesianModel([('d', 'g'), ('i', 'g'), ('g', 'l'), ('i', 's')]) def test_active_trail_nodes(self): self.assertEqual(sorted(self.G.active_trail_nodes('d')), ['d', 'g', 'l']) self.assertEqual(sorted(self.G.active_trail_nodes('i')), ['g', 'i', 'l', 's']) def test_active_trail_nodes_args(self): self.assertEqual(sorted(self.G.active_trail_nodes('d', observed='g')), ['d', 'i', 's']) self.assertEqual(sorted(self.G.active_trail_nodes('l', observed='g')), ['l']) self.assertEqual(sorted(self.G.active_trail_nodes('s', observed=['i', 'l'])), ['s']) self.assertEqual(sorted(self.G.active_trail_nodes('s', observed=['d', 'l'])), ['g', 'i', 's']) def test_is_active_trail_triplets(self): self.assertTrue(self.G.is_active_trail('d', 'l')) self.assertTrue(self.G.is_active_trail('g', 's')) self.assertFalse(self.G.is_active_trail('d', 'i')) self.assertTrue(self.G.is_active_trail('d', 'i', observed='g')) self.assertFalse(self.G.is_active_trail('d', 'l', observed='g')) self.assertFalse(self.G.is_active_trail('i', 'l', observed='g')) self.assertTrue(self.G.is_active_trail('d', 'i', observed='l')) self.assertFalse(self.G.is_active_trail('g', 's', observed='i')) def test_is_active_trail(self): self.assertFalse(self.G.is_active_trail('d', 's')) self.assertTrue(self.G.is_active_trail('s', 'l')) self.assertTrue(self.G.is_active_trail('d', 's', observed='g')) self.assertFalse(self.G.is_active_trail('s', 'l', observed='g')) def test_is_active_trail_args(self): self.assertFalse(self.G.is_active_trail('s', 'l', 'i')) self.assertFalse(self.G.is_active_trail('s', 'l', 'g')) self.assertTrue(self.G.is_active_trail('d', 's', 'l')) self.assertFalse(self.G.is_active_trail('d', 's', ['i', 'l'])) def test_get_cpds(self): cpd_d = TabularCPD('d', 2, values=np.random.rand(2, 1)) cpd_i = TabularCPD('i', 2, values=np.random.rand(2, 1)) cpd_g = TabularCPD('g', 2, values=np.random.rand(2, 4), evidence=['d', 'i'], evidence_card=[2, 2]) cpd_l = TabularCPD('l', 2, values=np.random.rand(2, 2), evidence=['g'], evidence_card=[2]) cpd_s = TabularCPD('s', 2, values=np.random.rand(2, 2), evidence=['i'], evidence_card=[2]) self.G.add_cpds(cpd_d, cpd_i, cpd_g, cpd_l, cpd_s) self.assertEqual(self.G.get_cpds('d').variable, 'd') def test_get_cpds1(self): self.model = BayesianModel([('A', 'AB')]) cpd_a = TabularCPD('A', 2, values=np.random.rand(2, 1)) cpd_ab = TabularCPD('AB', 2, values=np.random.rand(2, 2), evidence=['A'], evidence_card=[2]) self.model.add_cpds(cpd_a, cpd_ab) self.assertEqual(self.model.get_cpds('A').variable, 'A') self.assertEqual(self.model.get_cpds('AB').variable, 'AB') def test_add_single_cpd(self): cpd_s = TabularCPD('s', 2, np.random.rand(2, 2), ['i'], 2) self.G.add_cpds(cpd_s) self.assertListEqual(self.G.get_cpds(), [cpd_s]) def test_add_multiple_cpds(self): cpd_d = TabularCPD('d', 2, values=np.random.rand(2, 1)) cpd_i = TabularCPD('i', 2, values=np.random.rand(2, 1)) cpd_g = TabularCPD('g', 2, values=np.random.rand(2, 4), evidence=['d', 'i'], evidence_card=[2, 2]) cpd_l = TabularCPD('l', 2, values=np.random.rand(2, 2), evidence=['g'], evidence_card=[2]) cpd_s = TabularCPD('s', 2, values=np.random.rand(2, 2), evidence=['i'], evidence_card=[2]) self.G.add_cpds(cpd_d, cpd_i, cpd_g, cpd_l, cpd_s) self.assertEqual(self.G.get_cpds('d'), cpd_d) self.assertEqual(self.G.get_cpds('i'), cpd_i) self.assertEqual(self.G.get_cpds('g'), cpd_g) self.assertEqual(self.G.get_cpds('l'), cpd_l) self.assertEqual(self.G.get_cpds('s'), cpd_s) def test_check_model(self): cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3, 0.4, 0.6], [0.8, 0.7, 0.6, 0.4]]), evidence=['d', 'i'], evidence_card=[2, 2]) cpd_s = TabularCPD('s', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['i'], evidence_card=[2]) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['g'], evidence_card=[2]) self.G.add_cpds(cpd_g, cpd_s, cpd_l) self.assertTrue(self.G.check_model()) def test_check_model1(self): cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['i'], evidence_card=[2]) self.G.add_cpds(cpd_g) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_g) cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3, 0.4, 0.6], [0.8, 0.7, 0.6, 0.4]]), evidence=['d', 's'], evidence_card=[2, 2]) self.G.add_cpds(cpd_g) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_g) cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['l'], evidence_card=[2]) self.G.add_cpds(cpd_g) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_g) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3], [0.8, 0.7]]), evidence=['d'], evidence_card=[2]) self.G.add_cpds(cpd_l) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_l) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3, 0.4, 0.6], [0.8, 0.7, 0.6, 0.4]]), evidence=['d', 'i'], evidence_card=[2, 2]) self.G.add_cpds(cpd_l) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_l) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3, 0.4, 0.6, 0.2, 0.3, 0.4, 0.6], [0.8, 0.7, 0.6, 0.4, 0.8, 0.7, 0.6, 0.4]]), evidence=['g', 'd', 'i'], evidence_card=[2, 2, 2]) self.G.add_cpds(cpd_l) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_l) def test_check_model2(self): cpd_s = TabularCPD('s', 2, values=np.array([[0.5, 0.3], [0.8, 0.7]]), evidence=['i'], evidence_card=2) self.G.add_cpds(cpd_s) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_s) cpd_g = TabularCPD('g', 2, values=np.array([[0.2, 0.3, 0.4, 0.6], [0.3, 0.7, 0.6, 0.4]]), evidence=['d', 'i'], evidence_card=[2, 2]) self.G.add_cpds(cpd_g) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_g) cpd_l = TabularCPD('l', 2, values=np.array([[0.2, 0.3], [0.1, 0.7]]), evidence=['g'], evidence_card=[2]) self.G.add_cpds(cpd_l) self.assertRaises(ValueError, self.G.check_model) self.G.remove_cpds(cpd_l) def tearDown(self): del self.G class TestBayesianModelFitPredict(unittest.TestCase): def setUp(self): self.model_disconnected = BayesianModel() self.model_disconnected.add_nodes_from(['A', 'B', 'C', 'D', 'E']) self.model_connected = BayesianModel([('A', 'B'), ('C', 'B'), ('C', 'D'), ('B', 'E')]) def test_disconnected_fit(self): values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)), columns=['A', 'B', 'C', 'D', 'E']) self.model_disconnected.fit(values) for node in ['A', 'B', 'C', 'D', 'E']: cpd = self.model_disconnected.get_cpds(node) self.assertEqual(cpd.variable, node) np_test.assert_array_equal(cpd.cardinality, np.array([2])) value = (values.ix[:, node].value_counts() / values.ix[:, node].value_counts().sum()) value = value.reindex(sorted(value.index)).values np_test.assert_array_equal(cpd.values, value) def test_connected_predict(self): np.random.seed(42) values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)), columns=['A', 'B', 'C', 'D', 'E']) fit_data = values[:800] predict_data = values[800:].copy() self.model_connected.fit(fit_data) self.assertRaises(ValueError, self.model_connected.predict, predict_data) predict_data.drop('E', axis=1, inplace=True) e_predict = self.model_connected.predict(predict_data) np_test.assert_array_equal(e_predict.values.ravel(), np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0])) def tearDown(self): del self.model_connected del self.model_disconnected class TestDirectedGraphCPDOperations(unittest.TestCase): def setUp(self): self.graph = BayesianModel() def test_add_single_cpd(self): cpd = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd) self.assertListEqual(self.graph.get_cpds(), [cpd]) def test_add_multiple_cpds(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.assertListEqual(self.graph.get_cpds(), [cpd1, cpd2, cpd3]) def test_remove_single_cpd(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.graph.remove_cpds(cpd1) self.assertListEqual(self.graph.get_cpds(), [cpd2, cpd3]) def test_remove_multiple_cpds(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.graph.remove_cpds(cpd1, cpd3) self.assertListEqual(self.graph.get_cpds(), [cpd2]) def test_remove_single_cpd_string(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.graph.remove_cpds('diff') self.assertListEqual(self.graph.get_cpds(), [cpd2, cpd3]) def test_remove_multiple_cpds_string(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.graph.remove_cpds('diff', 'grade') self.assertListEqual(self.graph.get_cpds(), [cpd2]) def test_get_cpd_for_node(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.assertEqual(self.graph.get_cpds('diff'), cpd1) self.assertEqual(self.graph.get_cpds('intel'), cpd2) self.assertEqual(self.graph.get_cpds('grade'), cpd3) def test_get_cpd_raises_error(self): cpd1 = TabularCPD('diff', 2, values=np.random.rand(2, 1)) cpd2 = TabularCPD('intel', 2, values=np.random.rand(2, 1)) cpd3 = TabularCPD('grade', 2, values=np.random.rand(2, 4), evidence=['diff', 'intel'], evidence_card=[2, 2]) self.graph.add_edges_from([('diff', 'grade'), ('intel', 'grade')]) self.graph.add_cpds(cpd1, cpd2, cpd3) self.assertRaises(ValueError, self.graph.get_cpds, 'sat') def tearDown(self): del self.graph
mit
D3A7H13/4HeadRankingSystem
src/FourHeadRankingSystem/Models/AccountViewModels/RegisterViewModel.cs
875
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace FourHeadRankingSystem.Models.AccountViewModels { public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
mit
bankonme/MUE-Src
src/qt/paymentrequestplus.cpp
7409
// Copyright (c) 2009-2015 Bitcoin Developers // Copyright (c) 2014-2015 MonetaryUnit Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Wraps dumb protocol buffer paymentRequest // with some extra methods // #include "paymentrequestplus.h" #include <stdexcept> #include <openssl/x509.h> #include <openssl/x509_vfy.h> #include <QDateTime> #include <QDebug> #include <QSslCertificate> class SSLVerifyError : public std::runtime_error { public: SSLVerifyError(std::string err) : std::runtime_error(err) { } }; bool PaymentRequestPlus::parse(const QByteArray& data) { bool parseOK = paymentRequest.ParseFromArray(data.data(), data.size()); if (!parseOK) { qDebug() << "PaymentRequestPlus::parse : Error parsing payment request"; return false; } if (paymentRequest.payment_details_version() > 1) { qDebug() << "PaymentRequestPlus::parse : Received up-version payment details, version=" << paymentRequest.payment_details_version(); return false; } parseOK = details.ParseFromString(paymentRequest.serialized_payment_details()); if (!parseOK) { qDebug() << "PaymentRequestPlus::parse : Error parsing payment details"; paymentRequest.Clear(); return false; } return true; } bool PaymentRequestPlus::SerializeToString(string* output) const { return paymentRequest.SerializeToString(output); } bool PaymentRequestPlus::IsInitialized() const { return paymentRequest.IsInitialized(); } QString PaymentRequestPlus::getPKIType() const { if (!IsInitialized()) return QString("none"); return QString::fromStdString(paymentRequest.pki_type()); } bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) const { merchant.clear(); if (!IsInitialized()) return false; // One day we'll support more PKI types, but just // x509 for now: const EVP_MD* digestAlgorithm = NULL; if (paymentRequest.pki_type() == "x509+sha256") { digestAlgorithm = EVP_sha256(); } else if (paymentRequest.pki_type() == "x509+sha1") { digestAlgorithm = EVP_sha1(); } else if (paymentRequest.pki_type() == "none") { qDebug() << "PaymentRequestPlus::getMerchant : Payment request: pki_type == none"; return false; } else { qDebug() << "PaymentRequestPlus::getMerchant : Payment request: unknown pki_type " << QString::fromStdString(paymentRequest.pki_type()); return false; } payments::X509Certificates certChain; if (!certChain.ParseFromString(paymentRequest.pki_data())) { qDebug() << "PaymentRequestPlus::getMerchant : Payment request: error parsing pki_data"; return false; } std::vector<X509*> certs; const QDateTime currentTime = QDateTime::currentDateTime(); for (int i = 0; i < certChain.certificate_size(); i++) { QByteArray certData(certChain.certificate(i).data(), certChain.certificate(i).size()); QSslCertificate qCert(certData, QSsl::Der); if (currentTime < qCert.effectiveDate() || currentTime > qCert.expiryDate()) { qDebug() << "PaymentRequestPlus::getMerchant : Payment request: certificate expired or not yet active: " << qCert; return false; } #if QT_VERSION >= 0x050000 if (qCert.isBlacklisted()) { qDebug() << "PaymentRequestPlus::getMerchant : Payment request: certificate blacklisted: " << qCert; return false; } #endif const unsigned char *data = (const unsigned char *)certChain.certificate(i).data(); X509 *cert = d2i_X509(NULL, &data, certChain.certificate(i).size()); if (cert) certs.push_back(cert); } if (certs.empty()) { qDebug() << "PaymentRequestPlus::getMerchant : Payment request: empty certificate chain"; return false; } // The first cert is the signing cert, the rest are untrusted certs that chain // to a valid root authority. OpenSSL needs them separately. STACK_OF(X509) *chain = sk_X509_new_null(); for (int i = certs.size()-1; i > 0; i--) { sk_X509_push(chain, certs[i]); } X509 *signing_cert = certs[0]; // Now create a "store context", which is a single use object for checking, // load the signing cert into it and verify. X509_STORE_CTX *store_ctx = X509_STORE_CTX_new(); if (!store_ctx) { qDebug() << "PaymentRequestPlus::getMerchant : Payment request: error creating X509_STORE_CTX"; return false; } char *website = NULL; bool fResult = true; try { if (!X509_STORE_CTX_init(store_ctx, certStore, signing_cert, chain)) { int error = X509_STORE_CTX_get_error(store_ctx); throw SSLVerifyError(X509_verify_cert_error_string(error)); } // Now do the verification! int result = X509_verify_cert(store_ctx); if (result != 1) { int error = X509_STORE_CTX_get_error(store_ctx); throw SSLVerifyError(X509_verify_cert_error_string(error)); } X509_NAME *certname = X509_get_subject_name(signing_cert); // Valid cert; check signature: payments::PaymentRequest rcopy(paymentRequest); // Copy rcopy.set_signature(std::string("")); std::string data_to_verify; // Everything but the signature rcopy.SerializeToString(&data_to_verify); EVP_MD_CTX ctx; EVP_PKEY *pubkey = X509_get_pubkey(signing_cert); EVP_MD_CTX_init(&ctx); if (!EVP_VerifyInit_ex(&ctx, digestAlgorithm, NULL) || !EVP_VerifyUpdate(&ctx, data_to_verify.data(), data_to_verify.size()) || !EVP_VerifyFinal(&ctx, (const unsigned char*)paymentRequest.signature().data(), paymentRequest.signature().size(), pubkey)) { throw SSLVerifyError("Bad signature, invalid PaymentRequest."); } // OpenSSL API for getting human printable strings from certs is baroque. int textlen = X509_NAME_get_text_by_NID(certname, NID_commonName, NULL, 0); website = new char[textlen + 1]; if (X509_NAME_get_text_by_NID(certname, NID_commonName, website, textlen + 1) == textlen && textlen > 0) { merchant = website; } else { throw SSLVerifyError("Bad certificate, missing common name."); } // TODO: detect EV certificates and set merchant = business name instead of unfriendly NID_commonName ? } catch (SSLVerifyError& err) { fResult = false; qDebug() << "PaymentRequestPlus::getMerchant : SSL error: " << err.what(); } if (website) delete[] website; X509_STORE_CTX_free(store_ctx); for (unsigned int i = 0; i < certs.size(); i++) X509_free(certs[i]); return fResult; } QList<std::pair<CScript,qint64> > PaymentRequestPlus::getPayTo() const { QList<std::pair<CScript,qint64> > result; for (int i = 0; i < details.outputs_size(); i++) { const unsigned char* scriptStr = (const unsigned char*)details.outputs(i).script().data(); CScript s(scriptStr, scriptStr+details.outputs(i).script().size()); result.append(make_pair(s, details.outputs(i).amount())); } return result; }
mit
peteratseneca/dps907fall2015
Week_06/ErrorHandling/ErrorHandling/Controllers/Links_vm.cs
6621
using System; using System.Collections.Generic; using System.Linq; using System.Web; // new... using Newtonsoft.Json; namespace ErrorHandling.Controllers { // This source code file has classes for link relations // There is a 'Link' class that models a hypermedia link // There are two abstract classes // One is for a single linked item // The other is for a linked collection // A resource model class can inherit from one of these classes // The biggest benefit is the reduction in code-writing // For example, the LinkedItem<T> abstract class can be used as the // base class for a 'Product' linked item, or for a 'Supplier' linked item // Study the source code for a resource model class cluster to see how it's used /// <summary> /// A hypermedia link /// </summary> public class Link { /// <summary> /// Rel - relation /// </summary> public string Rel { get; set; } /// <summary> /// Href - hypermedia reference /// </summary> public string Href { get; set; } // New added properties... // The null value handling issue is controversial // Attributes were used here to make the result look nicer (without null-valued properties) // However, read these... // StackOverflow - http://stackoverflow.com/questions/10150312/removing-null-properties-from-json-in-mvc-web-api-4-beta // CodePlex - http://aspnetwebstack.codeplex.com/workitem/243 /// <summary> /// ContentType - internet media type, for content negotiation /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string ContentType { get; set; } /// <summary> /// Method - HTTP method(s) which can be used /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string Method { get; set; } /// <summary> /// Title - human-readable title label /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string Title { get; set; } } // Factory // The abstract base classes for "linked" objects have been refactored // Each is a "factory" - it constructs an object that includes all the links // The benefit is code reduction - the resource model classes are smaller /// <summary> /// Encloses an 'item' in a media type that has a 'Links' collection /// Abstract base class, which must be inherited /// </summary> /// <typeparam name="T">View model object</typeparam> public abstract class LinkedItem<T> { public LinkedItem(T item) { Links = new List<Link>(); Item = item; // Get the current request URL var absolutePath = HttpContext.Current.Request.Url.AbsolutePath; // Link relation for 'self' in the item // Use "dynamic" to avoid having to create an interface // Using "dynamic" forces the programmer to ensure that the // passed-in object does indeed include a property named "Link" dynamic i = Item; i.Link = new Link() { Rel = "self", Href = absolutePath }; // Link relation for 'self' this.Links.Add(new Link() { Rel = "self", Href = absolutePath }); // Link relation for 'collection' string[] u = absolutePath.Split(new char[] { '/' }); this.Links.Add(new Link() { Rel = "collection", Href = string.Format("/{0}/{1}", u[1], u[2]) }); } public LinkedItem(T item, int id) { // This constructor handles the "add new" use case // In an "add new" situation, the AbsolutePath is the collection // We need to add the new unique identifier on to the end Links = new List<Link>(); Item = item; // Get the current request URL var absolutePath = HttpContext.Current.Request.Url.AbsolutePath; // Use "dynamic" to avoid having to create an interface // Using "dynamic" forces the programmer to ensure that the // passed-in object does indeed include a property named "Link" dynamic i = Item; // Link relation for 'self' in the item // Add the unique identifier to the end of the absolutePath absolutePath += string.Format("/{0}", i.Id); i.Link = new Link() { Rel = "self", Href = absolutePath }; // Link relation for 'self' this.Links.Add(new Link() { Rel = "self", Href = absolutePath }); // Link relation for 'collection' string[] u = absolutePath.Split(new char[] { '/' }); this.Links.Add(new Link() { Rel = "collection", Href = string.Format("/{0}/{1}", u[1], u[2]) }); } /// <summary> /// Links for this item /// </summary> public List<Link> Links { get; set; } /// <summary> /// Data item /// </summary> public T Item { get; set; } } // Factory /// <summary> /// Encloses a 'collection' in a media type that has a 'Links' collection /// Abstract base class, which must be inherited /// </summary> /// <typeparam name="T">View model collection</typeparam> public abstract class LinkedCollection<T> { public LinkedCollection(IEnumerable<T> collection) { this.Links = new List<Link>(); Collection = collection; // Get the current request URL var absolutePath = HttpContext.Current.Request.Url.AbsolutePath; // Link relation for 'self' this.Links.Add(new Link() { Rel = "self", Href = absolutePath }); // Add 'item' links for each item in the collection // Use "dynamic" to avoid having to create an interface // Using "dynamic" forces the programmer to ensure that the // object does indeed include a property named "Link" foreach (dynamic item in this.Collection) { item.Link = new Link() { Rel = "item", Href = string.Format("{0}/{1}", absolutePath, item.Id) }; } } /// <summary> /// Links for this collection /// </summary> public List<Link> Links { get; set; } /// <summary> /// Data collection /// </summary> public IEnumerable<T> Collection { get; set; } } }
mit
boztalay/OldProjects
C++/Win32 Projects/Minecraft Watcher/main.cpp
3209
#include <windows.h> LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { HWND hwnd; WNDCLASSEX wndclass = {0}; wndclass.cbSize = sizeof(wndclass); wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProc; wndclass.hInstance = hInstance; wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.lpszClassName = "GameTutorials"; RegisterClassEx(&wndclass); hwnd = CreateWindowEx(NULL, "GameTutorials", "My First Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 320, 200, NULL, NULL, hInstance, NULL); for (;;) { Sleep(10); if ( FindWindow(NULL, "MySpace - Mozilla Firefox")) { DWORD pid; HANDLE hand1 = NULL; HWND hwndWindow1; hwndWindow1 = FindWindow(NULL, "MySpace - Mozilla Firefox"); GetWindowThreadProcessId(hwndWindow1, &pid); hand1 = OpenProcess(PROCESS_ALL_ACCESS,0,pid); TerminateProcess(hand1, 0); MessageBox(hwnd, "LOL OWNED!!", "OWNED!", MB_OK | MB_ICONEXCLAMATION); } else if ( FindWindow(NULL, "MySpace - Windows Internet Explorer")) { DWORD pid; HANDLE hand2 = NULL; HWND hwndWindow2; hwndWindow2 = FindWindow(NULL, "MySpace - Windows Internet Explorer"); GetWindowThreadProcessId(hwndWindow2, &pid); hand2 = OpenProcess(PROCESS_ALL_ACCESS,0,pid); TerminateProcess(hand2, 0); MessageBox(hwnd, "LOL OWNED!!", "OWNED!", MB_OK | MB_ICONEXCLAMATION); } else if ( FindWindow(NULL, "Play Games, Free Online Games at AddictingGames - Mozilla Firefox")) { DWORD pid; HANDLE hand3 = NULL; HWND hwndWindow3; hwndWindow3 = FindWindow(NULL, "Play Games, Free Online Games at AddictingGames - Mozilla Firefox"); GetWindowThreadProcessId(hwndWindow3, &pid); hand3 = OpenProcess(PROCESS_ALL_ACCESS,0,pid); TerminateProcess(hand3, 0); MessageBox(hwnd, "LOL OWNED!!", "OWNED!", MB_OK | MB_ICONEXCLAMATION); } else if ( FindWindow(NULL, "Play Games, Free Online Games at AddictingGames - Windows Internet Explorer")) { DWORD pid; HANDLE hand4 = NULL; HWND hwndWindow4; hwndWindow4 = FindWindow(NULL, "Play Games, Free Online Games at AddictingGames - Windows Internet Explorer"); GetWindowThreadProcessId(hwndWindow4, &pid); hand4 = OpenProcess(PROCESS_ALL_ACCESS,0,pid); TerminateProcess(hand4, 0); MessageBox(hwnd, "LOL OWNED!!", "OWNED!", MB_OK | MB_ICONEXCLAMATION); } } UnregisterClass("GameTutorials",hInstance); return 0; } LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { return 0; }
mit
ayline94/Diplomarbeit-Zeitboerse
angebot.js
1645
$(document).ready(function(){ //------------- Angebotsliste -------------------------// // Angebote anzeigen function displayAngebotListe() { $.ajax({ url:"api/angebot/show-list.php", method:"POST", success:function(data){ $('#angebotsliste').html(data); } }); } displayAngebotListe(); // Angebot suchen $('#search_angebot').keyup(function(){ var txt = $(this).val(); if(txt != '') { $.ajax({ url:"api/angebot/search.php", method:"post", data:{search:txt}, dataType:"text", success:function(data) { $('#angebotsliste').html(data); } }); } else { displayAngebotListe(); } }); //-------- Angebot Detailansicht -----------------// // Einzelansicht Angebot anzeigen function showAngebotDetail(id) { $.ajax({ url:"api/angebot/show-detail.php", method:"GET", data: { id:id }, success:function(data){ $('#showAngebotDetail').html(data); } }); } showAngebotDetail(getParam('id')); //----------- Facebook Sharing ------------// $(document).on('click', '#facebookShare', function(){ var sharer = "https://www.facebook.com/sharer/sharer.php?u="; window.open(sharer + location.href,'sharer', 'width=226,height=236'); }); });
mit
magic-cli/magic
src/Commands/NewCommand.php
10469
<?php namespace Magic\Commands; use Exception; use GuzzleHttp\Exception\ClientException; use League\Flysystem\Adapter\Local; use Magic\Commands\Command; use Magic\Contracts\MagicTemplate as MagicTemplateContract; use Magic\CustomTemplate\CustomTemplateBuilder; use Magic\Filesystem\Filesystem; use Magic\Http\MagicHttp; use Magic\Parser\TemplateParser; use RuntimeException; use Symfony\Component\Console\Command\LockableTrait; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use ZipArchive; class NewCommand extends Command { /** @var String */ protected $template; /** @var Magic\Filesystem\Filesystem */ public static $filesystem; /** * Configure the "new" command options. * * @return void */ protected function configure() { $this ->setName('new') ->addArgument('template', InputArgument::REQUIRED) ->addArgument('name', InputArgument::REQUIRED) ->setDescription('Create new PHP project'); } /** * Execute the command. * * @return void */ protected function fire(InputInterface $input, OutputInterface $output) { if (! class_exists('ZipArchive')) { throw new RuntimeException('The Zip PHP extension is not installed. Please install it and try again.'); } $targetName = $input->getArgument('name'); $targetDirectory = $this->getTargetDirectory($targetName); $this->template = $template = $input->getArgument('template'); // If this is a local template, extract the local template into // target directory and run the template build command if ($this->isLocalTemplate($template)) { $this->title('Local template'); $this->extractLocalTemplate($template, $targetDirectory) ->askRequiredQuestions() ->runCustomTemplateCommands($template, $targetDirectory) ->buildTemplate($targetDirectory); } // If template is not a local directory, download remote template // extract into temporary path and build template else { $this->title('Downloading template...'); $this->progressStart(100); // Get temporary directory // Directory will be used to store zip file and process template $tempDirectory = $this->temporaryDirectory($targetName, $template); $zipFile = $this->downloadTemplate($template, $tempDirectory); $this->progressFinish(); $templateDirectoryDestination = $tempDirectory . '/' . ltrim($template,'/'); $remoteTemplateDirectory = $templateDirectoryDestination . '-master'; $this->extract($zipFile, $tempDirectory) ->extractLocalTemplate( $remoteTemplateDirectory, $targetDirectory ) ->askRequiredQuestions() ->runCustomTemplateCommands($remoteTemplateDirectory, $targetDirectory) ->buildTemplate($targetDirectory) ->clean($tempDirectory); } $this->listing([ '> All done!... like magic!', '', "cd {$targetDirectory}", "composer start", ]); } /** * Get temporary directory * * @param String $targetName * @param String $template * @return String */ protected function temporaryDirectory($targetName, $template) { $temporaryDirectoryName = '.' . md5($targetName . $template); $directory = $this->workingDirectory($temporaryDirectoryName); $this->filesystem()->makeDirectory($directory, 0755, true, true); return $directory; } /** * Initial questions * * @return Magic\Commands\NewCommand */ protected function askRequiredQuestions() { $projectName = $this->ask( "Project name", $this->defaultProjectName(), function($answer) { if (!preg_match('/([a-z-._\/0-9]+)\/([a-z-._\/0-9]+)/x', $answer)) { throw new RuntimeException("Invalid project name. It should be lowercase and have a vendor name, a forward slash, and a package name. Example: my-vendor-name/my-project-name"); } return $answer; } ); $projectDescription = $this->ask( "Project description:", "My new project" ); $author = $this->ask( "Author:", $this->defaultAuthor() ); $this->data = [ 'name' => $projectName, 'description' => $projectDescription, 'author' => $author ]; return $this; } /** * Get default project name * @return String */ protected function defaultProjectName() { $project = slugify($this->template); if(empty($project)) { $project = 'my-project'; } return slugify($this->gitUser('name'), '') . '/' . $project; } /** * Get default author * * @return String */ protected function defaultAuthor() { return sprintf("%s <%s>", ucfirst($this->gitUser('name')), $this->gitUser('email') ); } /** * Get default author * @return String */ protected function gitUser($key = null) { $data = [ 'name' => exec('git config --get user.name'), 'email' => exec('git config --get user.email'), ]; return isset($data[$key]) ? $data[$key] : $data; } /** * Call template parser and build template * * @param String $targetDirectory * @return Magic\Commands\NewCommand */ protected function buildTemplate($targetDirectory) { TemplateParser::directory($targetDirectory) ->with($this->data) ->build(); return $this; } /** * Handle custom template commands * * @param String $templatePath * @return void */ protected function runCustomTemplateCommands($templatePath, $targetDirectory) { if (($template = $this->getCustomTemplate($templatePath)) === false) { return $this; } $data = (new CustomTemplateBuilder($this))->handle($template, $targetDirectory); $this->data = array_replace_recursive($this->data, $data); return $this; } /** * Get custom template if exists * * @param String $templatePath * @return \TemplateGenerator|false */ protected function getCustomTemplate($templatePath) { $customTemplateFile = rtrim($templatePath,'/') . '/template.php'; if (! $this->filesystem()->exists($customTemplateFile)) { return false; } $template = require $customTemplateFile; if ($template instanceof MagicTemplateContract) { return $template; } return false; } /** * setup local template * * @param String $template * @param String $destination * @return Magic\Commands\NewCommand */ protected function extractLocalTemplate($template, $destination) { if (!$this->filesystem()->isDirectory($dir = "{$template}/template")) { throw new RuntimeException("Invalid template [{$dir}]"); } $this->filesystem()->copyDirectory($dir, $destination); return $this; } /** * Remove file or path * * @param String $path * @return Magic\Commands\NewCommand */ protected function clean($path) { $this->filesystem()->removeDirectory($path); return $this; } /** * Get the new project target directory * * @param String $name * @return String */ protected function getTargetDirectory($name) { return $this->workingDirectory($name); } /** * Check if is a local template * @param String $template * @return boolean */ protected function isLocalTemplate($template) { return $this->filesystem()->isDirectory($template); } /** * Extract the Zip file into the given directory. * * @param string $zipFile * @param string $directory * @return $this */ protected function extract($zipFile, $destination) { if (($archive = new ZipArchive)->open($zipFile) !== true) { throw new RuntimeException("Could not open template zip file"); } $archive->extractTo($destination); $archive->close(); return $this; } /** * Get template zip filename * * @param String $template * @return String */ protected function getTemplateFilename($template) { $hash = md5($template); return "magic_{$hash}.zip"; } /** * Current working directory * * @return string */ protected function workingDirectory($suffix = null) { $directory = getcwd(); if (!is_null($suffix)) { return $directory . '/' . ltrim($suffix, '/'); } return $directory; } /** * Download template * * @param String $template * @return String */ protected function downloadTemplate($template, $destination) { $response = MagicHttp::get("https://github.com/magic-cli-templates/{$template}/archive/master.zip"); if ($response->getStatusCode() !== 200) { throw new RuntimeException("Error while trying to download template {$template}"); } $zipFile = rtrim($destination,'/') . '/' . $this->getTemplateFilename($template); file_put_contents($zipFile, $response->getBody()); return $zipFile; } /** * Get filesystem instance * * @return Magic\Filesystem\Filesystem */ public function filesystem() { if (is_null(self::$filesystem)) { self::$filesystem = new Filesystem; } return self::$filesystem; } }
mit
maltewintner/photoduels
app/views/photoduels/part/head.blade.php
289
<head> <title>@lang('photoduels.head_title')</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {{ HTML::style('css/bootstrap.min.css') }} {{ HTML::style('css/photoduels.css') }} {{ HTML::style('css/fam-icons.css') }} </head>
mit
DojoSamurai/Dojo
app/cache/dev/twig/65/97/2aeb0230e08c7baf3eb1b98b652cfc143ef7a8f43769ba38b2edb1743606.php
2068
<?php /* TwigBundle:Exception:logs.html.twig */ class __TwigTemplate_65972aeb0230e08c7baf3eb1b98b652cfc143ef7a8f43769ba38b2edb1743606 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<ol class=\"traces logs\"> "; // line 2 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable((isset($context["logs"]) ? $context["logs"] : $this->getContext($context, "logs"))); foreach ($context['_seq'] as $context["_key"] => $context["log"]) { // line 3 echo " <li"; if (($this->getAttribute($context["log"], "priority", array()) >= 400)) { echo " class=\"error\""; } elseif (($this->getAttribute($context["log"], "priority", array()) >= 300)) { echo " class=\"warning\""; } echo "> "; // line 4 echo twig_escape_filter($this->env, $this->getAttribute($context["log"], "priorityName", array()), "html", null, true); echo " - "; echo twig_escape_filter($this->env, $this->getAttribute($context["log"], "message", array()), "html", null, true); echo " </li> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['log'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 7 echo "</ol> "; } public function getTemplateName() { return "TwigBundle:Exception:logs.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 46 => 7, 35 => 4, 26 => 3, 22 => 2, 19 => 1,); } }
mit
WonchulYang/angularyang
app/scripts/controllers/mapContoller.js
1024
'use strict'; /** * @ngdoc function * @name sbAdminApp.controller:MainCtrl * @description * # MainCtrl * Controller of the sbAdminApp */ angular.module('sbAdminApp') .controller('MapCtrl', ['$scope', function ($scope) { var myLatLng = {lat: -12.566535, lng: 126.97796919000007}; // Create a map object and specify the DOM element for display. var map = new google.maps.Map(document.getElementById('map'), { //center: myLatLng, scrollwheel: true, zoom: 16 }); // Create a marker and set its position. var marker = new google.maps.Marker({ map: map, //position: myLatLng, title: 'Hello World!' }); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(pos) { myLatLng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude); map.setCenter(myLatLng); marker.setPosition(myLatLng); }); } else { map.setCenter(myLatLng); marker.setPosition(myLatLng); } }]);
mit
cuckata23/wurfl-data
data/sagem_myx_4_ver1.php
1860
<?php return array ( 'id' => 'sagem_myx_4_ver1', 'fallback' => 'opwv_v62_generic', 'capabilities' => array ( 'uaprof' => 'http://extranet.sagem.com/UAProfile/835509.xml', 'model_name' => 'myX-4', 'brand_name' => 'Sagem', 'max_image_width' => '121', 'resolution_height' => '160', 'resolution_width' => '128', 'max_image_height' => '120', 'bmp' => 'true', 'colors' => '65536', 'max_deck_size' => '100000', 'nokia_voice_call' => 'true', 'j2me_midp_2_0' => 'true', 'j2me_cldc_1_0' => 'true', 'j2me_screen_height' => '160', 'j2me_screen_width' => '128', 'j2me_midp_1_0' => 'true', 'mms_3gpp' => 'true', 'mms_png' => 'true', 'mms_max_size' => '102400', 'mms_max_width' => '640', 'sender' => 'true', 'mms_max_height' => '640', 'mms_gif_static' => 'true', 'mms_video' => 'true', 'mms_wav' => 'true', 'mms_vcard' => 'true', 'mms_midi_monophonic' => 'true', 'mms_vcalendar' => 'true', 'receiver' => 'true', 'mms_wbmp' => 'true', 'mms_amr' => 'true', 'mms_jpeg_baseline' => 'true', 'wav' => 'true', 'amr' => 'true', 'midi_monophonic' => 'true', 'imelody' => 'true', 'directdownload_support' => 'true', 'ringtone_voices' => '16', 'wallpaper_png' => 'true', 'wallpaper_colors' => '16', 'ringtone_amr' => 'true', 'ringtone_midi_monophonic' => 'true', 'wallpaper_preferred_width' => '128', 'wallpaper_jpg' => 'true', 'wallpaper_preferred_height' => '128', 'ringtone_imelody' => 'true', 'ringtone' => 'true', 'wallpaper_gif' => 'true', 'ringtone_midi_polyphonic' => 'true', 'ringtone_wav' => 'true', 'video' => 'true', 'playback_3gpp' => 'true', 'playback_acodec_amr' => 'nb', 'streaming_real_media' => 'none', 'streaming_3gpp' => 'true', ), );
mit
innogames/gitlabhq
app/services/ci/job_artifacts/destroy_batch_service.rb
3072
# frozen_string_literal: true module Ci module JobArtifacts class DestroyBatchService include BaseServiceUtility include ::Gitlab::Utils::StrongMemoize # Danger: Private - Should only be called in Ci Services that pass a batch of job artifacts # Not for use outside of the Ci:: namespace # Adds the passed batch of job artifacts to the `ci_deleted_objects` table # for asyncronous destruction of the objects in Object Storage via the `Ci::DeleteObjectsService` # and then deletes the batch of related `ci_job_artifacts` records. # Params: # +job_artifacts+:: A relation of job artifacts to destroy (fewer than MAX_JOB_ARTIFACT_BATCH_SIZE) # +pick_up_at+:: When to pick up for deletion of files # Returns: # +Hash+:: A hash with status and destroyed_artifacts_count keys def initialize(job_artifacts, pick_up_at: nil) @job_artifacts = job_artifacts.with_destroy_preloads.to_a @pick_up_at = pick_up_at end # rubocop: disable CodeReuse/ActiveRecord def execute(update_stats: true) return success(destroyed_artifacts_count: 0, statistics_updates: {}) if @job_artifacts.empty? Ci::DeletedObject.transaction do Ci::DeletedObject.bulk_import(@job_artifacts, @pick_up_at) Ci::JobArtifact.id_in(@job_artifacts.map(&:id)).delete_all destroy_related_records(@job_artifacts) end # This is executed outside of the transaction because it depends on Redis update_project_statistics! if update_stats increment_monitoring_statistics(artifacts_count) success(destroyed_artifacts_count: artifacts_count, statistics_updates: affected_project_statistics) end # rubocop: enable CodeReuse/ActiveRecord private # This method is implemented in EE and it must do only database work def destroy_related_records(artifacts); end # using ! here since this can't be called inside a transaction def update_project_statistics! affected_project_statistics.each do |project, delta| project.increment_statistic_value(Ci::JobArtifact.project_statistics_name, delta) end end def affected_project_statistics strong_memoize(:affected_project_statistics) do artifacts_by_project = @job_artifacts.group_by(&:project) artifacts_by_project.each.with_object({}) do |(project, artifacts), accumulator| delta = -artifacts.sum { |artifact| artifact.size.to_i } accumulator[project] = delta end end end def increment_monitoring_statistics(size) metrics.increment_destroyed_artifacts(size) end def metrics @metrics ||= ::Gitlab::Ci::Artifacts::Metrics.new end def artifacts_count strong_memoize(:artifacts_count) do @job_artifacts.count end end end end end Ci::JobArtifacts::DestroyBatchService.prepend_mod_with('Ci::JobArtifacts::DestroyBatchService')
mit
de-wiring/containerspec
tests/serverspec-tests/test_spec.rb
156
require 'spec_helper.rb' describe docker_image('nginx:latest') do it { should exist } its(:inspection) { should include 'Architecture' => 'amd64' } end
mit
BeYkeRYkt/Bulls-and-Cows
Eclipse/src/ru/beykerykt/bullsandcows/base/gui/PrintStreamInterface.java
1721
/** * MIT License * * Copyright (c) 2017 Vladimir Mikhaylov * * 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. **/ package ru.beykerykt.bullsandcows.base.gui; import java.io.PrintStream; import java.util.Scanner; public class PrintStreamInterface implements IUserInterface { protected PrintStream stream; protected Scanner input; public PrintStreamInterface(PrintStream stream) { this.stream = stream; } @Override public void showText(String text) { stream.println(text); } @Override public String getInput() { return "1111"; // input.next(); } @Override public void onPlayerJoin() { input = new Scanner(System.in); } @Override public void onPlayerLeave() { input.close(); } }
mit
daryllabar/XrmUnitTest
NMemory.Base/Execution/Optimization/JoinGroup`2.cs
2083
// ---------------------------------------------------------------------------------- // <copyright file="JoinGroup`2.cs" company="NMemory Team"> // Copyright (C) 2012-2014 NMemory Team // // 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. // </copyright> // ---------------------------------------------------------------------------------- namespace NMemory.Execution.Optimization { using System.Collections.Generic; internal class JoinGroup<TOuter, TInner> { private readonly TOuter outer; private readonly IEnumerable<TInner> inner; public JoinGroup(TOuter outer, IEnumerable<TInner> inner) { this.outer = outer; this.inner = inner; } public TOuter Outer { get { return this.outer; } } public IEnumerable<TInner> Inner { get { return this.inner; } } } }
mit
akosszasz/akosszasz.github.io
fishing2021/media/admin/filemanager/scripts/languages/pl.js
2414
{ "AUTHORIZATION_REQUIRED": "Nie jesteś upoważniony do używania menadżera plików.", "INVALID_ACTION": "Niewłaściwa akcja.", "MODE_ERROR": "Tryb wyświetlania błędów.", "DIRECTORY_ALREADY_EXISTS": "Lokalizacja '%s' już istnieje.", "UNABLE_TO_CREATE_DIRECTORY": "Brak możliwości utworzenia lokalizacji %s.", "INVALID_VAR": "Niewłaściwa zmienna %s.", "DIRECTORY_NOT_EXIST": "Lokalizacja %s nie istnieje.", "UNABLE_TO_OPEN_DIRECTORY": "Brak możliwości otwarcia lokalizacji %s.", "ERROR_RENAMING_DIRECTORY": "Nie udało się zmienić lokalizacji z %s na %s.", "ERROR_RENAMING_FILE": "Nie udało się zmienić nazwy pliku z %s na %s.", "INVALID_DIRECTORY_OR_FILE": "Niewłaściwa lokalizacja lub plik.", "INVALID_FILE_UPLOAD": "Niewłaściwy plik.", "UPLOAD_FILES_SMALLER_THAN": "Proszę użyć pliku mniejszego niż %s.", "UPLOAD_IMAGES_ONLY": "Użyj pliku obrazkowego, inne typy plików nie są wspierane.", "UPLOAD_IMAGES_TYPE_JPEG_GIF_PNG": "Proszę użyj plików obrazkowych w formacie JPEG, GIF lub PNG.", "FILE_DOES_NOT_EXIST": "Plik %s nie istnieje.", "LANGUAGE_FILE_NOT_FOUND": "Plik językowy nie znaleziony.", "default_foldername": "Mój folder", "prompt_foldername": "Wpisz nazwę nowego folderu (nie używaj polskich znaków)", "no_foldername": "Nie podano nazwy folderu.", "create_folder": "Utwórz folder", "cancel": "Anuluj", "select_from_left": "Wybierz plik z lewej strony.", "fck_select_integration": "Funkcja wybierz ('Select') jest używana tylko z FCKEditor.", "new_filename": "Wpisz nową nazwę. Nie używaj polskich znaków.", "successful_rename": "Nazwa pliku została zmieniona.", "rename": "Zmień nazwę", "confirmation_delete": "Czy na pewno chcesz usunąć wybrany plik?", "successful_delete": "Usunięto plik.", "successful_added_file": "Dodano nowy plik.", "successful_added_folder": "Dodano nowy folder.", "select": "Wybierz", "download": "Pobierz", "del": "Usuń", "parentfolder": "Parent folder", "dimensions": "Wymiary", "created": "Utworzono", "modified": "Zmodyfikowano", "size": "Rozmiar", "name": "Nazwa", "could_not_retrieve_folder": "Nie udało się otworzyć folderu.", "yes": "Tak", "no": "Nie", "upload": "Dodaj", "new_folder": "Nowy folder", "grid_view": "Widok siatki.", "list_view": "Widok listy.", "current_folder": "Aktualny folder: ", "bytes": " bytes", "kb": "kb", "mb": "mb", "gb": "gb" }
mit
salsify/ember-cli-pact
tests/helpers/ajax.js
432
// Quick'n'dirty AJAX without using `fetch` (needs Pretender support) // or `jQuery` (don't want to assume it's around) export default function ajax(url, { method = 'GET' } = {}) { return new Promise((resolve, reject) => { let request = new XMLHttpRequest(); request.onload = () => resolve(JSON.parse(request.responseText)); request.onerror = () => reject(); request.open(method, url); request.send(); }); }
mit
abactel/smhw
smhw_cli.py
12191
#!/usr/bin/env python3 """showmyhomework from your terminal""" import argparse # allows command line argument parsing import curses # provides interface import datetime # display relative dates import sys # parse command line arguments, exit program import webbrowser # open URL in browser import yaml # parse config import smhw_core # gets new entries import markdown_strings as md # allows markdown generation BOLD = "\n\033[1m" def get_command_line_arguments(config, args): """Parses command line arguments and adds them to config""" # parser initiation parser = argparse.ArgumentParser( description="Showmyhomework command line interface.") parser.add_argument("--config", metavar="FILENAME", default="./config.yml", help="use custom configuration file location") parser.add_argument("--no_curses", default=False, action="store_true", help="print plain markdown to terminal") parser.add_argument("--no_download", default=True, action="store_false", help="prevent download of new icalendar on load") parser.add_argument("--num_of_entries", default=-1, metavar="N", type=int, help="specifies number of markdown entries to save") args = parser.parse_args() # saves options to arguments config["config_file"] = args.config config["no_curses"] = args.no_curses config["number_of_entries"] = args.num_of_entries config["download_on_load"] = not args.no_download return config def get_config(config): """Adds details from config file to config""" config_file_error_main = BOLD + "ERROR: Please set up your config file" config_file_error_setup = BOLD + "Try running `setup.py` \n" # open config file try: config_file = yaml.safe_load(open(config["config_file"])) except FileNotFoundError: print(config_file_error_main + ", config file not found", end="") print(config_file_error_setup) sys.exit(1) # load required entries try: config["iCalendar_URL"] = config_file["iCalendar URL"] except: print(config_file_error_main + ", iCalendar URL missing", end="") print(config_file_error_setup) sys.exit(1) # load optional entries try: arguments = config_file["arguments"] if "no_curses" in arguments: config["no_curses"] = True except: pass return config def convert_to_markdown(entries, config, file_name): """Converts entries to markdown""" num = config["number_of_entries"] # create main homework table full_file = [] entries = sorted(entries, key=lambda k: k['due_date'])[::-1] ## create columns subject_list = [entry["subject"][:-1] for entry in entries][:num] title_list = [entry["short_title"] for entry in entries][:num] due_list = [entry["relative_date"] for entry in entries][:num] ## add titles to columns subject_list.insert(0, "Subject") title_list.insert(0, "Title") due_list.insert(0, "Due") ## add table to full_file full_file.append(md.table([subject_list, title_list, due_list])) full_file.append("\n\nLast updated: " + str(datetime.datetime.now()) + "\n") # display or save file if config["no_curses"]: print("\n" + "".join(full_file)) else: with open(file_name, "w") as file: file.write("".join(full_file)) def mark_homework_state(state, uid): """Mark completion state of homework items in storage""" storage_file = yaml.safe_load(open("./storage.yml")) completed_homework = storage_file["completed"] if state == "complete": if uid not in str(completed_homework): with open("./storage.yml", "a") as file: file.write(" - " + uid + "\n") elif state == "incomplete": with open("./storage.yml", "r") as file: saved_file = file.readlines() with open("./storage.yml", "w") as file: for line in saved_file: if str(uid) not in line: file.write(line) def no_curses_display(config): entries, successful_download = smhw_core.get_new_entries(config) if not successful_download: print("No internet connection, using already downloaded file") convert_to_markdown(entries, config, "calendar.md") def curses_interface(config): """Creates curses interface for the user to interact with""" def status_bar(text): pad = 5 window.addstr(window_height - 2, pad, " " * (window_width - pad + 1)) window.addstr(window_height - 2, pad, text, curses.color_pair(1)) def open_URL(url): webbrowser.get().open_new_tab(url) status_bar("URL opened") def show_details(): # prepare curses window window.border(0) curses.noecho() window.addstr(0, 2, " showmyhomework ") # create variables containing details current_title = entries[user_chosen_entry]["title"] current_due_date_datetime = entries[user_chosen_entry]["due_date"] current_due_date = current_due_date_datetime.strftime("%Y-%m-%d") current_subject = entries[user_chosen_entry]["subject"] current_link = entries[user_chosen_entry]["link"] current_teacher = entries[user_chosen_entry]["teacher"] # prepare variables padlevel = 78 maximium_title_length = window_width - padlevel - len(current_subject) current_title = smhw_core.shorten_text(current_title, maximium_title_length) current_tile_position = len(current_title) + padlevel # display homework details window.addstr(2, padlevel - 2, current_title, curses.A_BOLD) window.addstr(3, padlevel, "Due: " + current_due_date, curses.A_DIM) window.addstr(2, current_tile_position, current_subject, curses.A_DIM) if window_width > 135: window.addstr(4, padlevel, "Link: " + current_link, curses.A_DIM) window.addstr(5, padlevel, "Set by: " + current_teacher, curses.A_DIM) def show_description(): window.border(0) curses.noecho() window.addstr(0, 2, " showmyhomework ") window.addstr(10, 78, "see https://github.com/abactel/smhw/issues/24") def get_user_input(text_to_display): status_bar("") curses.echo() text_to_display = text_to_display.rstrip() + " " window.addstr(text_to_display, curses.color_pair(1)) text = window.getstr(window_height - 2, 5 + len(text_to_display), 15) return str(text.strip())[2:-1] def filter_entries(entries): selected_filter = get_user_input("Filter:").split() for entry in entries: if selected_filter[0] == "date": if selected_filter[1] == "future" and entry["due_distance"] > 0: config["dimmed_ids"].append(entry["id"]) elif selected_filter[1] == "past" and entry["due_distance"] < 0: config["dimmed_ids"].append(entry["id"]) elif selected_filter[0] == "reset": config["dimmed_ids"] = [] elif selected_filter[0] == "quit": window.clear() else: status_bar("Not a valid filter.") return entries # prepare curses window window = curses.initscr() window.border(0) curses.noecho() curses.curs_set(0) window.keypad(1) ## create colors curses.start_color() curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK) # create constants CONNECTION_ERROR = "No internet connection, using already downloaded file" # create variables config["dimmed_ids"] = [] user_chosen_entry = 0 # initial download of homework if config["download_on_load"]: entries, successful_download = smhw_core.get_new_entries(config) if successful_download: key = ord("&") else: key = ord("$") else: entries, successful_download = smhw_core.get_new_entries( config, download_file=False) key = ord("£") # main loop while key != ord("q"): # get current screen size, allows resizing window_height, window_width = window.getmaxyx() maximum_number_of_entries_shown = window_height - 5 # parse keypress if key == ord("&"): status_bar("Started succesfully") elif key == ord("$"): status_bar(CONNECTION_ERROR) elif key == ord("£"): status_bar("Started succesfully, loaded file") elif key == ord("k") or key == curses.KEY_UP: if 0 < user_chosen_entry: user_chosen_entry -= 1 elif key == ord("j") or key == curses.KEY_DOWN: if (user_chosen_entry < maximum_number_of_entries_shown - 1): user_chosen_entry += 1 elif key == ord("s"): ## get information save_location = get_user_input("Save location (q to cancel): ") try: config["number_of_entries"] = int(get_user_input( "Number of entries (-1 for all):")) except ValueError: config["number_of_entries"] = -1 ## save if save_location != "q": convert_to_markdown(entries, config, save_location) status_bar("Wrote to " + save_location) else: status_bar("Cancelled") elif key == ord("r"): entries, successful_download = smhw_core.get_new_entries(config) if successful_download: status_bar("Homework feed refreshed") else: status_bar(CONNECTION_ERROR) elif key == ord("o"): open_URL(entries[user_chosen_entry]["link"]) elif key == ord("c"): status_bar("") elif key == ord("h") or key == curses.KEY_LEFT: try: entry_to_mark = entries[user_chosen_entry]["uid"] if entries[user_chosen_entry]["completed"]: mark_homework_state("incomplete", entry_to_mark) window.erase() window.border(0) else: mark_homework_state("complete", entry_to_mark) except: status_bar("Couldn't mark homework") smhw_core.get_completed_homework(entries) elif key == ord("f"): entries = filter_entries(entries) # display homework for entry in entries: if entry["id"] < maximum_number_of_entries_shown: # add modifications modifier = False if entry["id"] in config["dimmed_ids"]: modifier = curses.A_DIM if entry["id"] == user_chosen_entry: # `if` as it overrides dimming modifier = curses.A_BOLD pad_level = int(entry["id"]) + 2 # display all homeowkr window.addstr(pad_level, 4, entry["subject"], modifier) window.addstr(pad_level, 16, entry["short_title"], modifier) window.addstr(pad_level, 65, entry["relative_date"], modifier) if entry["completed"]: window.addstr(int(entry["id"]) + 2, 2, "✔️", modifier) if window_width > 75: # hides details if screen is too small show_details() if key == ord("l") or key == curses.KEY_RIGHT: show_description() # preperation for next loop event = window.getch() key = event window.border(0) window.refresh() curses.endwin() def main(argv): # initialize variable config = {} get_command_line_arguments(config, argv) get_config(config) # begin interface if config["no_curses"]: no_curses_display(config) else: curses_interface(config) if __name__ == "__main__": main(sys.argv[1:])
mit
Hexeption/Youtube-Hacked-Client-1.8
minecraft/net/minecraft/network/Packet.java
483
package net.minecraft.network; import java.io.IOException; public interface Packet { /** * Reads the raw packet data from the data stream. */ void readPacketData(PacketBuffer data) throws IOException; /** * Writes the raw packet data to the data stream. */ void writePacketData(PacketBuffer data) throws IOException; /** * Passes this Packet on to the NetHandler for processing. */ void processPacket(INetHandler handler); }
mit
InseeFr/DDI-Access-Services
src/main/java/fr/insee/rmes/config/ElasticContext.java
869
package fr.insee.rmes.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ElasticContext { @Value("${fr.insee.rmes.elasticsearch.cluster.name}") private String clusterName; @Value("${fr.insee.rmes.elasticsearch.host}") private String host; @Value("${fr.insee.rmes.elasticsearch.port}") private int port; @Bean public RestHighLevelClient client() throws Exception { RestClient lowLevelClient = RestClient.builder( new HttpHost(host, port, "http")).build(); return new RestHighLevelClient(lowLevelClient); } }
mit
ahmadnurhidayat/Cook-It-Android-XML-Template
app/src/test/java/com/uiresource/cookit/ExampleUnitTest.java
399
package com.uiresource.cookit; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
KodamaSakuno/ProjectDentan
Dentan.Game/Data/EnemyFleet.cs
3512
using System.Linq; namespace Moen.KanColle.Dentan.Data { public class EnemyFleet : ModelBase, IID { public int ID { get; set; } public bool IsPracticeFleet { get; internal set; } string r_Name; public string Name { get { return r_Name; } set { if (r_Name != value) { r_Name = value; OnPropertyChanged(); } } } Formation r_Formation; public Formation Formation { get { return r_Formation; } set { if (r_Formation != value) { r_Formation = value; OnPropertyChanged(); } } } public int[] ShipIDs { get; set; } EnemyShip[] r_Ships; public EnemyShip[] Ships { get { if (r_Ships == null && ShipIDs != null) UpdateShips(); return r_Ships; } set { r_Ships = value; OnPropertyChanged(); } } public bool HasEquipments { get; set; } int r_AA; public int AA { get { return r_AA; } set { if (r_AA != value) { r_AA = value; OnPropertyChanged(); } } } int? r_PracticeExperience; public int? PracticeExperience { get { return r_PracticeExperience; } set { if (r_PracticeExperience != value) { r_PracticeExperience = value; OnPropertyChanged(); } } } public AbyssalFleet AbyssalFleet { get; set; } public void UpdateShips() { Ships = ShipIDs.Select(r => { var rInfo = KanColleGame.Current.Base.Ships[r]; Slot[] rSlots; if (IsPracticeFleet) rSlots = rInfo.PlaneCount.Take(rInfo.EquipmentCount).Select(rpCount => new Slot(null, rpCount, rpCount)).ToArray(); else { var rData = AbyssalShip.FromID(r); if (rData == null || rData.Equipments == null) rSlots = rInfo.PlaneCount.Take(rInfo.EquipmentCount).Select(rpCount => new Slot(null, rpCount, rpCount)).ToArray(); else rSlots = rData.Equipments.Zip(rInfo.PlaneCount, (rpEquipment, rpCount) => new Slot(rpEquipment, rpCount, rpCount)).ToArray(); } string rCustomName = null; if (rInfo.AbyssalShipClass.HasValue && rInfo.AbyssalShipClass.Value == AbyssalShipClass.LateModel) rCustomName = rInfo.Name.Replace("後期型", string.Empty); return new EnemyShip(rInfo, 1, rSlots) { CustomName = rCustomName }; }).ToArray(); UpdateAA(); if (!IsPracticeFleet) HasEquipments = Ships.All(r => r.Slots.All(rpSlot => rpSlot.Equipment != null)); } public void UpdateAA() { AA = Ships.Sum(r => r.Slots.Sum(rpSlot => rpSlot.PlaneAA)); } } }
mit
betrakiss/MovieRegistry
models/record.rb
124
require 'active_record' class Record < ActiveRecord::Base belongs_to :user belongs_to :movie belongs_to :episode end
mit
JanHalozan/SonosStream
src/js/search.js
843
const youtubeApiKey = 'AIzaSyAGyDq2bPgXD2uvwfx_kCEAC-sE9jk-KJE'; var YouTube = require('youtube-node'); var youtube = new YouTube(); youtube.setKey(youtubeApiKey); $('.search-button').click(function() { var needle = $('.search-field').val(); var resultsList = $('.search-results'); resultsList.empty(); youtube.search(needle, 10, function(error, result) { if (error) { //TODO: Print error output resultsList.append('<li>Error</li>'); return; } var items = result.items; $(items).each(function(index, obj) { var videoId = obj.id.videoId; var title = obj.snippet.title; var item = '<li class="item" id="' + videoId + '"><img src="' + obj.snippet.thumbnails.default.url + '">' + title + '</li>'; resultsList.append(item); }); }); });
mit
dominics/predisque
src/Profile/Factory.php
1894
<?php namespace Predisque\Profile; use Predis\ClientException; /** * Factory class for creating profile instances from strings. */ class Factory { private static $profiles = array( '1.0' => DisqueVersion100::class, 'dev' => DisqueUnstable::class, 'default' => DisqueVersion100::class, ); private function __construct() { // NOOP } /** * Returns the default server profile. * * @return ProfileInterface * @throws ClientException */ public static function getDefault() { return self::get('default'); } /** * Returns the development server profile. * * @return ProfileInterface * @throws ClientException */ public static function getDevelopment() { return self::get('dev'); } /** * Registers a new server profile. * * @param string $alias Profile version or alias. * @param string $class FQN of a class implementing Predis\Profile\ProfileInterface. * * @throws \InvalidArgumentException */ public static function define($alias, $class) { $reflection = new \ReflectionClass($class); if (!$reflection->isSubclassOf(ProfileInterface::class)) { throw new \InvalidArgumentException("The class '$class' is not a valid profile class."); } self::$profiles[$alias] = $class; } /** * Returns the specified server profile. * * @param string $version Profile version or alias. * * @throws ClientException * * @return ProfileInterface */ public static function get($version) { if (!isset(self::$profiles[$version])) { throw new ClientException("Unknown server profile: '$version'."); } $profile = self::$profiles[$version]; return new $profile(); } }
mit
gugcz/devfest-gamification
android/CDH-Master/src/main/java/cz/destil/cdhmaster/service/ConnectivityReceiver.java
741
package cz.destil.cdhmaster.service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import cz.destil.cdhmaster.util.DebugLog; import cz.destil.cdhmaster.util.Util; /** * Created by Destil on 4.11.13. */ public class ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Util.isNetworkAvailable()) { DebugLog.i("Connectivity up"); UnlockService unlockService = UnlockService.get(); if (unlockService != null && !unlockService.isStackEmpty() && !unlockService.isUnlockingInProgress()) { unlockService.unlockNext(); } } } }
mit
abhinaykrupa/1s
application/views/jobsView.php
10095
<form id="search" name="<?= $pageId ?>" class="form-horizontal" action="<?= $canonicalURL ?>" method="get"> <div class="form-group"> <label class="control-label col-sm-5" for="keyword">Job Title:</label> <div class="col-sm-3"> <input type="text" class="form-control" id="keyword" name="keyword" value="<?= $selectedKeyword ?>" placeholder="Job Title,Skills, or Company" /> </div> </div> <br/> <div class="form-group"> <label class="control-label col-sm-5" for="location">Location:</label> <div class="col-sm-3"> <input type="text" class="form-control zipautofill" id="location" name="location" value="<?= $selectedLocation ?>" placeholder="Zipcode, City or State" /> </div> </div> <div class="geo-details"> <input type="hidden" data-geo="country" value="" id="setting_country" name="setting_country" class="location" /> <input type="hidden" data-geo="country_short" value="" id="setting_country_short" name="setting_country_short" class="location" /> <input type="hidden" data-geo="administrative_area_level_1" value="" id="setting_state" name="setting_state" class="location" /> <input type="hidden" data-geo="administrative_area_level_1_short" value="" id="setting_state_short" name="setting_state_short" class="location" /> <input type="hidden" data-geo="administrative_area_level_2" value="" id="setting_city" name="setting_city" class="location" /> <input type="hidden" data-geo="postal_code" value="" id="setting_postal_code" name="postal_code" class="location" /> </div> <br/> <div class="form-group"> <label class="control-label col-sm-5" for="jobType">Job Type:</label> <div class="col-sm-3"> <select class="form-control" id="jobType" name="jobType"> <?php foreach ($jobTypes as $jobTypeId => $jobType) { $selected = ($selectedJobTypeId == $jobTypeId) ? 'selected' : ''; echo "<option value='$jobTypeId' $selected>$jobType</option>"; } ?> </select> </div> </div> <br/> <div class="form-group"> <label class="control-label col-sm-5" for="distance">Distance:</label> <div class="col-sm-3"> <select class="form-control" id="distance" name="distance"> <?php foreach ($distances as $distance_id => $distance) { $selected = ($selectedDistanceId == $distance_id) ? 'selected' : ''; echo "<option value='$distance_id' $selected>$distance Miles</option>"; } ?> </select> </div> </div> <br/> <div class="control-group" data-toggle="buttons"> <?php foreach ($websites as $websiteId => $website) { $checked = in_array($websiteId, $selectedWebsiteIds) ? 'checked' : ''; ?> <label class="btn btn-primary websiteLabel <?= ($checked) ? 'active' : '' ?>"> <input type="checkbox" name="selectedWebsiteIds[<?= $websiteId ?>]" class="websiteCheckbox" value="<?= $websiteId ?>" <?= $checked ?> autocomplete="off" /> <?= $website['name'] ?> <span class="glyphicon <?= ($checked) ? 'glyphicon-check' : 'glyphicon-unchecked' ?>"></span> <!--<a href="<?= $website['url'] ?>" id="<?= $websiteId ?>" class="btn-link btn-lg" rel="nofollow" target="_blank"><?= $website['name'] ?></a>--> </label> <?php } ?> </div> <div class="form-group"> <div class="col-sm-offset-5 col-sm-2"> <a href="" id="checkAll" rel="nofollow" class="btn-link">Check All</a> | <a href="" id="unCheckAll" rel="nofollow" class="btn-link">Uncheck All</a> </div> </div> <div id="checkBoxError" class="alert alert-danger fade in hide"> <a href="" class="close" aria-label="close">&times;</a> <strong>Sorry!</strong> Please select at least one website from the above list to search. </div> <div id="popupBlockError" class="alert alert-danger fade in hide"> <a href="" class="close" aria-label="close">&times;</a> <strong>Sorry! Your browser popup blocker is enabled. Please disable it for <?= APP_NAME ?> and re-submit.</strong> </div> <div class="form-group"> <div class="col-sm-offset-5 col-sm-1"> <button type="submit" id="submit" name="submit" class="btn btn-success btn-lg" data-toggle="modal" data-target=".signUpAlerts" > <span class="glyphicon glyphicon-search"></span> Search </button> </div> </div> </form> <br/><br/> <?php if(!empty($selectedJobId)) { ?> <div class="row" style="margin-bottom:30px;"> <div class="col-lg-12 col-sm-12" id="scrollid"> <div class="row"> <?php if(in_array($selectedJobId,$apiJobIds)) { for($i=0; $i<=count($selectedJobData->jobs)-1;$i++) { if($selectedJobId === $selectedJobData->jobs[$i]->id) { ?> <h3 class="text-center">Job Summary</h3> <div class="col-lg-12 col-sm-12"> <div class="col-lg-12 col-sm-12 zr_job_title" style="margin-bottom: 10px;"> <h3 > <a rel="nofollow" style="margin-top: 20px;" href="<?php echo $selectedJobData->jobs[$i]->url; ?>" target="_blank" class="zr_job_link"> <?php echo $selectedJobData->jobs[$i]->name; ?> </a> </h3> </div> <div class="col-lg-4 col-sm-6 textleft" style="margin-top: 7px;"> <span class="job_company"><strong>Employment Type:</strong> <?php echo $selectedJobData->jobs[$i]->salary_interval; ?> </span> </div> <div class="col-lg-4 col-sm-6" style="margin-top: 7px;"> <span class="zr_job_company"><strong>Salary Max:</strong> <?php echo $selectedJobData->jobs[$i]->salary_max; ?> </span> </div> <div class="col-lg-4 col-sm-6" style="margin-top: 7px;"> <span class="zr_job_company"><strong>Hiring Company:</strong> <?php echo $selectedJobData->jobs[$i]->hiring_company->name; ?> </span> </div> <div class="col-lg-4 col-sm-6 textleft" style="margin-top: 7px;"> <span class="zr_job_location"><strong>Location:</strong> <?php echo $selectedJobData->jobs[$i]->location; ?> </span> </div> <div class="col-lg-12 zr_job_title" style="margin-bottom: 30px; margin-top: 7px;"> <span class="zr_job_company"><strong>Job Description: </strong> <?php echo $selectedJobData->jobs[$i]->snippet; ?> </span> <span class="text-left"> <a href="<?php echo $selectedJobData->jobs[$i]->url; ?>" style="color:#00ADD8; font-size: 14px;" target="_blank">Read More</a> </span> </div> </div> <br/><br/> <a href="<?php echo $selectedJobData->jobs[$i]->url;?>" target="_blank"><button type="button" class="btn btn-primary">Apply Now</button></a> <?php } } } else { ?> <div class="col-lg-12 col-sm-12" style="margin-top: 20px; margin-bottom: -20px;"> <h3 class="text-center">Sorry, this job is no longer available. Please find few related jobs below.</h3> </div> <?php } ?> </div> </div> <br/><br/> <div class="col-lg-12 col-sm-12" style="margin-top: 20px; margin-bottom: -20px;"> <h3 class="text-center">Related Jobs</h3> </div> </div> <?php } ?> <!-- zipsearch affiliate program --> <div id="searchResults" align="center"></div>
mit
millwrightjs/millwright
src/plugins/minify.js
1044
const _ = require('lodash'); const postcss = require('postcss'); const cssnano = require('cssnano'); const uglifyjs = require('uglify-js'); module.exports = function minify(file) { const minified = minifiers[file.typeDest](file); return minified.then(result => _.assign(file, result)); } const minifiers = {css, js}; function css(file) { const opts = { from: file.src, to: file.src, map: { prev: file.map, inline: false, sourcesContent: false, annotation: false } }; return postcss([cssnano()]) .process(file.content, opts) .then(result => ({ content: result.css, map: result.map.toString() })); } function js(file) { const opts = { fromString: true, sourceMapUrl: false }; if (file.map) { opts.inSourceMap = _.isObject(file.map) ? file.map : JSON.parse(file.map); opts.outSourceMap = file.destFilename + '.map'; } const result = uglifyjs.minify(file.content, opts); return Promise.resolve({content: result.code, map: result.map}); }
mit
kgryte/npmignore
test/test.async.js
5214
/* global require, describe, it */ 'use strict'; // MODULES // var chai = require( 'chai' ), mkdirp = require( 'mkdirp' ), path = require( 'path' ), fs = require( 'fs' ), cp = require( './../lib/async.js' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'async', function tests() { it( 'should export a function', function test() { expect( cp ).to.be.a( 'function' ); }); it( 'should throw an error if not provided a destination', function test() { expect( foo ).to.throw( Error ); function foo() { cp(); } }); it( 'should throw an error if not provided a valid destination directory', function test() { var values = [ 5, null, true, undefined, NaN, [], {}, function(){} ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( TypeError ); } function badValue( value ) { return function() { cp( value ); }; } }); it( 'should throw an error if not provided a valid options argument', function test() { var values = [ 'beep', 5, null, true, undefined, NaN, [], // function(){} // allowed as fcn is variadic ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue1( values[i] ) ).to.throw( TypeError ); expect( badValue2( values[i] ) ).to.throw( TypeError ); } function badValue1( value ) { return function() { cp( './beep/boop', value ); }; } function badValue2( value ) { return function() { cp( './beep/boop', value, function(){} ); }; } }); it( 'should throw an error if provided a callback argument which is not a function', function test() { var values = [ 'beep', 5, null, true, undefined, NaN, [], {} ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( TypeError ); } function badValue( value ) { return function() { cp( './beep/boop', {}, value ); }; } }); it( 'should throw an error if provided a template option which is not a string primitive', function test() { var values = [ 5, null, true, undefined, NaN, [], {}, function(){} ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( TypeError ); } function badValue( value ) { return function() { cp( './beep/boop', { 'template': value }); }; } }); it( 'should throw an error if provided an unrecognized template option', function test() { var values = [ 'beep', 'boop', 'woot' ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( Error ); } function badValue( value ) { return function() { cp( './beep/boop', { 'template': value }); }; } }); it( 'should create a .npmignore file in a specified directory', function test( done ) { var dirpath; dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() ); mkdirp.sync( dirpath ); cp( dirpath, onFinish ); function onFinish( error ) { var bool; if ( error ) { assert.ok( false ); } else { bool = fs.existsSync( path.join( dirpath, '.npmignore' ) ); assert.isTrue( bool ); } done(); } }); it( 'should pass any write errors to a provided callback', function test( done ) { var dirpath; dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() ); cp( dirpath, onFinish ); function onFinish( error ) { if ( error ) { assert.ok( true ); } else { assert.ok( false ); } done(); } }); it( 'should create a .npmignore file in a specified directory without requiring a callback', function test( done ) { var dirpath; dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() ); mkdirp.sync( dirpath ); cp( dirpath ); setTimeout( onTimeout, 500 ); function onTimeout() { var bool = fs.existsSync( path.join( dirpath, '.npmignore' ) ); assert.isTrue( bool ); done(); } }); it( 'should create a .npmignore file using a specified template', function test( done ) { var dirpath; dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() ); mkdirp.sync( dirpath ); cp( dirpath, { 'template': 'default' }, onFinish ); function onFinish( error ) { var fpath1, fpath2, f1, f2; if ( error ) { assert.ok( false ); done(); return; } fpath1 = path.join( dirpath, '.npmignore' ); f1 = fs.readFileSync( fpath1, { 'encoding': 'utf8' }); fpath2 = path.join( path.resolve( __dirname, '../lib/default' ), 'npmignore' ); f2 = fs.readFileSync( fpath2, { 'encoding': 'utf8' }); assert.strictEqual( f1, f2 ); done(); } }); it( 'should ignore any unrecognized options', function test( done ) { var dirpath; dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() ); mkdirp.sync( dirpath ); cp( dirpath, { 'beep': 'boop' }, onFinish ); function onFinish( error ) { var bool; if ( error ) { assert.ok( false ); } else { bool = fs.existsSync( path.join( dirpath, '.npmignore' ) ); assert.isTrue( bool ); } done(); } }); });
mit
kenzierocks/AutoErgel
src/main/java/me/kenzierocks/autoergel/util/ServiceProvider.java
1488
/* * This file is part of Autoergel, licensed under the MIT License (MIT). * * Copyright (c) kenzierocks (Kenzie Togami) <http://kenzierocks.me> * Copyright (c) contributors * * 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. */ package me.kenzierocks.autoergel.util; public interface ServiceProvider<T> { T provide(); Class<? extends T> getProvidedType(); default int voteFor(ServiceProvider<? extends T> provider) { return 0; } }
mit
incentivetoken/offspring
com.dgex.offspring.ui/src/com/dgex/offspring/ui/messaging/MessageNodeImpl.java
791
package com.dgex.offspring.ui.messaging; import java.util.ArrayList; import java.util.List; public class MessageNodeImpl implements IMessageNode { private final IMessageNode parent; private final MessageWrapper message; private List<IMessageNode> children = null; public MessageNodeImpl(IMessageNode parent, MessageWrapper message) { this.parent = parent; this.message = message; } @Override public IMessageNode getParent() { return parent; } @Override public List<IMessageNode> getChildren() { if (children == null) children = new ArrayList<IMessageNode>(); return children; } @Override public MessageWrapper getMessage() { return message; } @Override public boolean hasChildren() { return children != null; } }
mit
jarrett/buscar
lib/buscar/index.rb
4687
module Buscar class Index include Enumerable # Views can call this method to iterate over the current page's records. Uses # the value returned by #page, which in turn uses the value of @params[:page] def each collection = paginate? ? records_on_page(page) : records collection.each do |record| yield record end end def empty? records.empty? end # Returns one of the following in descending order of preference: # - params[:filter] # - default_filter_option # - 'none' def filter_param @params[:filter] || (respond_to?(:default_filter_option, true) ? default_filter_option : 'none') end def filter_param_options filter_options.collect do |opt| arr = [opt[0]] arr << opt[2] if opt.length == 3 arr end end def self.generate(*args) index = new(*args) index.generate! index end def generate! unless respond_to?(:finder, true) raise 'Subclasses of Index must define #finder, which must return something that responds to #find. For example, #finder may return an ActiveRecord::Base subclass.' end raise "Buscar::Index#conditions is deprecated. Name your method where_clause instead." if respond_to?(:conditions, true) raise "Buscar::Index#order is deprecated. Name your method order_clause instead." if respond_to?(:order, true) raise "Buscar::Index#include_clause is deprecated. Name your method includes_clause instead." if respond_to?(:include, true) @records = finder.scoped # Get the bare relation object in case none of the modifiers are used # Use each AR query modifier other than #where and #order if applicable %w(having select group limit offset joins includes lock readonly from).each do |meth| @records = @records.send(meth, send("#{meth}_clause".to_sym)) if respond_to?("#{meth}_clause".to_sym, true) end chained_filters = filter chained_filters = chain(chained_filters) unless chained_filters.is_a?(Chain) # filter might return a Chain or a single filtering rule. If it's a single one, we'll put it in an array. @filter_procs = chained_filters.select { |f| f.is_a?(Proc) } # Procs will be triggered by the first call to #records so as not to defeat lazy loading where_filters = chained_filters.select { |f| !f.is_a?(Proc) } # SQL filters can be used right away where_filters.each do |filt| @records = @records.where(filt) end sort_rule = sort # If sorting by a proc, do it on the first call to #records so as not to defeat lazy loading if sort_rule.is_a?(Proc) @sort_proc = sort_rule else @records = @records.order(sort_rule) end end def initialize(params = {}) @params = params end def length records.length end def optional_params(*keys) keys.inject({}) do |hash, key| unless @params[key].blank? hash[key] = @params[key] end hash end end # The current page, as determined by @params[:page]. Since we want the user to see the page array as one-based, # but we use zero-based indices internally, we subtract one from the page number. # # Thus, the return value is a zero-based offset. def page (@params[:page] || @params['page'] || 1).to_i - 1 end def page_count (records.length.to_f / records_per_page).ceil end attr_reader :params # page_num is zero-based for this method. def records_on_page(page_num) if paginate? records.slice((page_num) * records_per_page, records_per_page) else records end end # Returns one of the following in descending order of preference: # - params[:sort] # - default_sort_option # - 'none' def sort_param @params[:sort] || (respond_to?(:default_sort_option, true) ? default_sort_option : 'none') end def sort_param_options sort_options.collect do |opt| arr = [opt[0]] arr << opt[2] if opt.length == 3 arr end end def records unless @procs_called @filter_procs.each do |proc| @records = @records.select(&proc) end @records = @records.sort_by(&@sort_proc) if @sort_proc @procs_called = true end @records end private class Chain < Array; end def chain(*elements) Chain.new(elements) end # Return something for #where, a Proc, or an array def filter if respond_to?(:filter_options, true) and (option = filter_options.assoc(filter_param)) option[1] else nil end end def paginate? true end def records_per_page @params[:records_per_page] || 50 end def sort if respond_to?(:sort_options, true) and (option = sort_options.assoc(sort_param)) option[1] else nil end end end end
mit
npruehs/ggj2016
Unity/Rituals/Assets/Game/Scripts/Menu/FadeOutImage.cs
1054
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FadeOutImage.cs" company="Slash Games"> // Copyright (c) Slash Games. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Rituals.Menu { using UnityEngine; using UnityEngine.UI; public class FadeOutImage : MonoBehaviour { #region Fields public float AlphaPerSecond; public Image Image; #endregion #region Methods private void Update() { this.Image.color = new Color( this.Image.color.r, this.Image.color.g, this.Image.color.b, this.Image.color.a - this.AlphaPerSecond * Time.deltaTime); if (this.Image.color.a <= 0.0f) { Destroy(this.gameObject); } } #endregion } }
mit
landonepps/vscode
extensions/markdown-language-features/src/markdownEngine.ts
9351
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as crypto from 'crypto'; import { MarkdownIt, Token } from 'markdown-it'; import * as path from 'path'; import * as vscode from 'vscode'; import { MarkdownContributions } from './markdownExtensions'; import { Slugifier } from './slugify'; import { SkinnyTextDocument } from './tableOfContentsProvider'; import { getUriForLinkWithKnownExternalScheme } from './util/links'; const UNICODE_NEWLINE_REGEX = /\u2028|\u2029/g; interface MarkdownItConfig { readonly breaks: boolean; readonly linkify: boolean; } class TokenCache { private cachedDocument?: { readonly uri: vscode.Uri; readonly version: number; readonly config: MarkdownItConfig; }; private tokens?: Token[]; public tryGetCached(document: SkinnyTextDocument, config: MarkdownItConfig): Token[] | undefined { if (this.cachedDocument && this.cachedDocument.uri.toString() === document.uri.toString() && this.cachedDocument.version === document.version && this.cachedDocument.config.breaks === config.breaks && this.cachedDocument.config.linkify === config.linkify ) { return this.tokens; } return undefined; } public update(document: SkinnyTextDocument, config: MarkdownItConfig, tokens: Token[]) { this.cachedDocument = { uri: document.uri, version: document.version, config, }; this.tokens = tokens; } } export class MarkdownEngine { private md?: Promise<MarkdownIt>; private currentDocument?: vscode.Uri; private _slugCount = new Map<string, number>(); private _tokenCache = new TokenCache(); public constructor( private readonly extensionPreviewResourceProvider: MarkdownContributions, private readonly slugifier: Slugifier, ) { } private async getEngine(config: MarkdownItConfig): Promise<MarkdownIt> { if (!this.md) { this.md = import('markdown-it').then(async markdownIt => { let md: MarkdownIt = markdownIt(await getMarkdownOptions(() => md)); for (const plugin of this.extensionPreviewResourceProvider.markdownItPlugins) { try { md = (await plugin)(md); } catch { // noop } } const frontMatterPlugin = require('markdown-it-front-matter'); // Extract rules from front matter plugin and apply at a lower precedence let fontMatterRule: any; frontMatterPlugin({ block: { ruler: { before: (_id: any, _id2: any, rule: any) => { fontMatterRule = rule; } } } }, () => { /* noop */ }); md.block.ruler.before('fence', 'front_matter', fontMatterRule, { alt: ['paragraph', 'reference', 'blockquote', 'list'] }); for (const renderName of ['paragraph_open', 'heading_open', 'image', 'code_block', 'fence', 'blockquote_open', 'list_item_open']) { this.addLineNumberRenderer(md, renderName); } this.addImageStabilizer(md); this.addFencedRenderer(md); this.addLinkNormalizer(md); this.addLinkValidator(md); this.addNamedHeaders(md); return md; }); } const md = await this.md!; md.set(config); return md; } private tokenize( document: SkinnyTextDocument, config: MarkdownItConfig, engine: MarkdownIt ): Token[] { const cached = this._tokenCache.tryGetCached(document, config); if (cached) { return cached; } this.currentDocument = document.uri; this._slugCount = new Map<string, number>(); const text = document.getText(); const tokens = engine.parse(text.replace(UNICODE_NEWLINE_REGEX, ''), {}); this._tokenCache.update(document, config, tokens); return tokens; } public async render(document: SkinnyTextDocument): Promise<string> { const config = this.getConfig(document.uri); const engine = await this.getEngine(config); return engine.renderer.render(this.tokenize(document, config, engine), { ...(engine as any).options, ...config }, {}); } public async parse(document: SkinnyTextDocument): Promise<Token[]> { const config = this.getConfig(document.uri); const engine = await this.getEngine(config); return this.tokenize(document, config, engine); } private getConfig(resource: vscode.Uri): MarkdownItConfig { const config = vscode.workspace.getConfiguration('markdown', resource); return { breaks: config.get<boolean>('preview.breaks', false), linkify: config.get<boolean>('preview.linkify', true) }; } private addLineNumberRenderer(md: any, ruleName: string): void { const original = md.renderer.rules[ruleName]; md.renderer.rules[ruleName] = (tokens: any, idx: number, options: any, env: any, self: any) => { const token = tokens[idx]; if (token.map && token.map.length) { token.attrSet('data-line', token.map[0]); token.attrJoin('class', 'code-line'); } if (original) { return original(tokens, idx, options, env, self); } else { return self.renderToken(tokens, idx, options, env, self); } }; } private addImageStabilizer(md: any): void { const original = md.renderer.rules.image; md.renderer.rules.image = (tokens: any, idx: number, options: any, env: any, self: any) => { const token = tokens[idx]; token.attrJoin('class', 'loading'); const src = token.attrGet('src'); if (src) { const hash = crypto.createHash('sha256'); hash.update(src); const imgHash = hash.digest('hex'); token.attrSet('id', `image-hash-${imgHash}`); } if (original) { return original(tokens, idx, options, env, self); } else { return self.renderToken(tokens, idx, options, env, self); } }; } private addFencedRenderer(md: any): void { const original = md.renderer.rules['fenced']; md.renderer.rules['fenced'] = (tokens: any, idx: number, options: any, env: any, self: any) => { const token = tokens[idx]; if (token.map && token.map.length) { token.attrJoin('class', 'hljs'); } return original(tokens, idx, options, env, self); }; } private addLinkNormalizer(md: any): void { const normalizeLink = md.normalizeLink; md.normalizeLink = (link: string) => { try { const externalSchemeUri = getUriForLinkWithKnownExternalScheme(link); if (externalSchemeUri) { // set true to skip encoding return normalizeLink(externalSchemeUri.toString(true)); } // Assume it must be an relative or absolute file path // Use a fake scheme to avoid parse warnings let uri = vscode.Uri.parse(`vscode-resource:${link}`); if (uri.path) { // Assume it must be a file const fragment = uri.fragment; if (uri.path[0] === '/') { const root = vscode.workspace.getWorkspaceFolder(this.currentDocument!); if (root) { uri = vscode.Uri.file(path.join(root.uri.fsPath, uri.path)); } } else { uri = vscode.Uri.file(path.join(path.dirname(this.currentDocument!.path), uri.path)); } if (fragment) { uri = uri.with({ fragment: this.slugifier.fromHeading(fragment).value }); } return normalizeLink(uri.with({ scheme: 'vscode-resource' }).toString(true)); } else if (!uri.path && uri.fragment) { return `#${this.slugifier.fromHeading(uri.fragment).value}`; } } catch (e) { // noop } return normalizeLink(link); }; } private addLinkValidator(md: any): void { const validateLink = md.validateLink; md.validateLink = (link: string) => { // support file:// links return validateLink(link) || link.indexOf('file:') === 0; }; } private addNamedHeaders(md: any): void { const original = md.renderer.rules.heading_open; md.renderer.rules.heading_open = (tokens: any, idx: number, options: any, env: any, self: any) => { const title = tokens[idx + 1].children.reduce((acc: string, t: any) => acc + t.content, ''); let slug = this.slugifier.fromHeading(title); if (this._slugCount.has(slug.value)) { const count = this._slugCount.get(slug.value)!; this._slugCount.set(slug.value, count + 1); slug = this.slugifier.fromHeading(slug.value + '-' + (count + 1)); } else { this._slugCount.set(slug.value, 0); } tokens[idx].attrs = tokens[idx].attrs || []; tokens[idx].attrs.push(['id', slug.value]); if (original) { return original(tokens, idx, options, env, self); } else { return self.renderToken(tokens, idx, options, env, self); } }; } } async function getMarkdownOptions(md: () => MarkdownIt) { const hljs = await import('highlight.js'); return { html: true, highlight: (str: string, lang?: string) => { console.log(123); // Workaround for highlight not supporting tsx: https://github.com/isagalaev/highlight.js/issues/1155 if (lang && ['tsx', 'typescriptreact'].indexOf(lang.toLocaleLowerCase()) >= 0) { lang = 'jsx'; } if (lang && lang.toLocaleLowerCase() === 'json5') { lang = 'json'; } if (lang && lang.toLocaleLowerCase() === 'c#') { lang = 'cs'; } if (lang && hljs.getLanguage(lang)) { try { return `<div>${hljs.highlight(lang, str, true).value}</div>`; } catch (error) { } } return `<code><div>${md().utils.escapeHtml(str)}</div></code>`; } }; }
mit
pipedrive/client-nodejs
src/model/BaseNote.js
7961
/** * Pipedrive API v1 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; import BaseNoteDealTitle from './BaseNoteDealTitle'; import BaseNoteOrganization from './BaseNoteOrganization'; import BaseNotePerson from './BaseNotePerson'; import NoteCreatorUser from './NoteCreatorUser'; /** * The BaseNote model module. * @module model/BaseNote * @version 1.0.0 */ class BaseNote { /** * Constructs a new <code>BaseNote</code>. * @alias module:model/BaseNote */ constructor() { BaseNote.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>BaseNote</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/BaseNote} obj Optional instance to populate. * @return {module:model/BaseNote} The populated <code>BaseNote</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new BaseNote(); if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'Number'); delete data['id']; } if (data.hasOwnProperty('active_flag')) { obj['active_flag'] = ApiClient.convertToType(data['active_flag'], 'Boolean'); delete data['active_flag']; } if (data.hasOwnProperty('add_time')) { obj['add_time'] = ApiClient.convertToType(data['add_time'], 'String'); delete data['add_time']; } if (data.hasOwnProperty('content')) { obj['content'] = ApiClient.convertToType(data['content'], 'String'); delete data['content']; } if (data.hasOwnProperty('deal')) { obj['deal'] = BaseNoteDealTitle.constructFromObject(data['deal']); delete data['deal']; } if (data.hasOwnProperty('lead_id')) { obj['lead_id'] = ApiClient.convertToType(data['lead_id'], 'String'); delete data['lead_id']; } if (data.hasOwnProperty('deal_id')) { obj['deal_id'] = ApiClient.convertToType(data['deal_id'], 'Number'); delete data['deal_id']; } if (data.hasOwnProperty('last_update_user_id')) { obj['last_update_user_id'] = ApiClient.convertToType(data['last_update_user_id'], 'Number'); delete data['last_update_user_id']; } if (data.hasOwnProperty('org_id')) { obj['org_id'] = ApiClient.convertToType(data['org_id'], 'Number'); delete data['org_id']; } if (data.hasOwnProperty('organization')) { obj['organization'] = BaseNoteOrganization.constructFromObject(data['organization']); delete data['organization']; } if (data.hasOwnProperty('person')) { obj['person'] = BaseNotePerson.constructFromObject(data['person']); delete data['person']; } if (data.hasOwnProperty('person_id')) { obj['person_id'] = ApiClient.convertToType(data['person_id'], 'Number'); delete data['person_id']; } if (data.hasOwnProperty('pinned_to_deal_flag')) { obj['pinned_to_deal_flag'] = ApiClient.convertToType(data['pinned_to_deal_flag'], 'Boolean'); delete data['pinned_to_deal_flag']; } if (data.hasOwnProperty('pinned_to_organization_flag')) { obj['pinned_to_organization_flag'] = ApiClient.convertToType(data['pinned_to_organization_flag'], 'Boolean'); delete data['pinned_to_organization_flag']; } if (data.hasOwnProperty('pinned_to_person_flag')) { obj['pinned_to_person_flag'] = ApiClient.convertToType(data['pinned_to_person_flag'], 'Boolean'); delete data['pinned_to_person_flag']; } if (data.hasOwnProperty('update_time')) { obj['update_time'] = ApiClient.convertToType(data['update_time'], 'String'); delete data['update_time']; } if (data.hasOwnProperty('user')) { obj['user'] = NoteCreatorUser.constructFromObject(data['user']); delete data['user']; } if (data.hasOwnProperty('user_id')) { obj['user_id'] = ApiClient.convertToType(data['user_id'], 'Number'); delete data['user_id']; } if (Object.keys(data).length > 0) { Object.assign(obj, data); } } return obj; } } /** * The ID of the note * @member {Number} id */ BaseNote.prototype['id'] = undefined; /** * Whether the note is active or deleted * @member {Boolean} active_flag */ BaseNote.prototype['active_flag'] = undefined; /** * The creation date and time of the note * @member {String} add_time */ BaseNote.prototype['add_time'] = undefined; /** * The content of the note in HTML format. Subject to sanitization on the back-end. * @member {String} content */ BaseNote.prototype['content'] = undefined; /** * @member {module:model/BaseNoteDealTitle} deal */ BaseNote.prototype['deal'] = undefined; /** * The ID of the lead the note is attached to * @member {String} lead_id */ BaseNote.prototype['lead_id'] = undefined; /** * The ID of the deal the note is attached to * @member {Number} deal_id */ BaseNote.prototype['deal_id'] = undefined; /** * The ID of the user who last updated the note * @member {Number} last_update_user_id */ BaseNote.prototype['last_update_user_id'] = undefined; /** * The ID of the organization the note is attached to * @member {Number} org_id */ BaseNote.prototype['org_id'] = undefined; /** * @member {module:model/BaseNoteOrganization} organization */ BaseNote.prototype['organization'] = undefined; /** * @member {module:model/BaseNotePerson} person */ BaseNote.prototype['person'] = undefined; /** * The ID of the person the note is attached to * @member {Number} person_id */ BaseNote.prototype['person_id'] = undefined; /** * If true, the results are filtered by note to deal pinning state * @member {Boolean} pinned_to_deal_flag */ BaseNote.prototype['pinned_to_deal_flag'] = undefined; /** * If true, the results are filtered by note to organization pinning state * @member {Boolean} pinned_to_organization_flag */ BaseNote.prototype['pinned_to_organization_flag'] = undefined; /** * If true, the results are filtered by note to person pinning state * @member {Boolean} pinned_to_person_flag */ BaseNote.prototype['pinned_to_person_flag'] = undefined; /** * The last updated date and time of the note * @member {String} update_time */ BaseNote.prototype['update_time'] = undefined; /** * @member {module:model/NoteCreatorUser} user */ BaseNote.prototype['user'] = undefined; /** * The ID of the note creator * @member {Number} user_id */ BaseNote.prototype['user_id'] = undefined; export default BaseNote;
mit
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.5.0/autocomplete-sources/autocomplete-sources-min.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:d3df9a2a67f24419c07867ad96beff2cd199871b493ca98cb92445e021adbbb7 size 3407
mit
platanus/platanus-rails
lib/platanus/enum.rb
2575
# enum.rb : ActiveRecord Enumerated Attributes. # # Copyright August 2012, Ignacio Baixas +mailto:[email protected]+. module Platanus ## Adds +attr_enum+ property generator to a module. # # When attr_enum is called on one of the model properties name: # * A getter and setter for the <name>_str property are added, this allows the property to be accessed as a string, # the string representations are obtained from the enumeration module's constants ::downcased:: names. # * An inclusion validation is added for the property, only values included in the enumeration module's constants are allowed # # Given the following configuration: # # module Test # ONE = 1 # TWO = 2 # THREE = 3 # end # # class Model # include Platanus::Enum # # attr_enum :target, Test # end # # One could do: # # t = Model.new # t.target = Test.ONE # t.target_str = 'one' # Same as above # t.target = 5 # Generates a validation error # t.target_str = # Raises an InvalidEnumName exception # module Enum # Exception risen when an invalid value is passed to one of the _str= setters. class InvalidEnumName < Exception; end def self.included(base) base.extend ClassMethods end module ClassMethods def attr_enum(_target, _module, _options={}) map = {} pname = _options.has_key?(:property_name) ? _options[:property_name] : (_target.to_s + '_str') # Extract module constants _module.constants.each { |cname| map[_module.const_get(cname)] = cname.to_s.downcase } # Add string getter self.send(:define_method, pname) do map.fetch(self.send(_target), '') end # Add string setter self.send(:define_method, pname + '=') do |value| map.each_pair do |k,v| if v == value self.send(_target.to_s + '=', k) return end end raise InvalidEnumName end # Retrieve singleton class to define new class methods klass = class << self; self; end # Add parse function klass.send(:define_method, 'parse_' + _target.to_s) do |value| value = value.to_s map.each_pair do |k,v| return k if v == value end return nil end # Add value validator (unless validation is disabled) self.validates _target, inclusion: { :in => map.keys } if _options.fetch(:validate, true) end end end end
mit
kiyokura/SSDTHelper
src/SampleDbProjectTest/spCalculateMonthlySalesTest.cs
1311
using NUnit.Framework; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using Dapper; namespace SampleDbProjectTest { [TestFixture] public class spCalculateMonthlySalesTest { [Test] public void spCalculateMonthlySales_Execute() { var excelFile = Util.GetLocalFileFullPath("spCalculateMonthlySalesTest.xlsx"); // init data var dt = SSDTHelper.ExcelReader.Read(excelFile, "DailySales"); var loader = new SSDTHelper.DataLoader(); loader.ConnectionString = Config.ConnectionString; loader.Load(dt); using (var cn = new SqlConnection(Config.ConnectionString)) { cn.Open(); // execute var param = new { year = 2017, month = 1 }; cn.Execute("spCalculateMonthlySales", param: param, commandType: System.Data.CommandType.StoredProcedure); // read result var resultset = cn.Query("SELECT * FROM MonthlySales ORDER BY ShopID, SalesMonth"); // check result set var message = ""; var ismatch = SSDTHelper.ResultChecker.IsMatch(resultset, excelFile, "ResultCheckSheet", out message); Assert.AreEqual(true, ismatch, message); } } } }
mit
Polynominal/Lucy3D
Dependencies/sol2/single/sol/sol.hpp
405093
// The MIT License (MIT) // Copyright (c) 2013-2016 Rapptz, ThePhD and contributors // 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. // This file was generated with a script. // Generated 2016-10-15 22:53:00.289259 UTC // This header was generated with sol v2.14.10 (revision 8f7433f) // https://github.com/ThePhD/sol2 #ifndef SOL_SINGLE_INCLUDE_HPP #define SOL_SINGLE_INCLUDE_HPP // beginning of sol/state.hpp // beginning of sol/state_view.hpp // beginning of sol/error.hpp #include <stdexcept> #include <string> namespace sol { namespace detail { struct direct_error_tag {}; const auto direct_error = direct_error_tag{}; } // detail class error : public std::runtime_error { private: // Because VC++ is a fuccboi std::string w; public: error(const std::string& str) : error(detail::direct_error, "lua: error: " + str) {} error(detail::direct_error_tag, const std::string& str) : std::runtime_error(""), w(str) {} error(detail::direct_error_tag, std::string&& str) : std::runtime_error(""), w(std::move(str)) {} error(const error& e) = default; error(error&& e) = default; error& operator=(const error& e) = default; error& operator=(error&& e) = default; virtual const char* what() const noexcept override { return w.c_str(); } }; } // sol // end of sol/error.hpp // beginning of sol/table.hpp // beginning of sol/table_core.hpp // beginning of sol/proxy.hpp // beginning of sol/traits.hpp // beginning of sol/tuple.hpp #include <tuple> #include <cstddef> namespace sol { namespace detail { using swallow = std::initializer_list<int>; } // detail template<typename... Args> struct types { typedef std::make_index_sequence<sizeof...(Args)> indices; static constexpr std::size_t size() { return sizeof...(Args); } }; namespace meta { namespace detail { template<typename... Args> struct tuple_types_ { typedef types<Args...> type; }; template<typename... Args> struct tuple_types_<std::tuple<Args...>> { typedef types<Args...> type; }; } // detail template<typename T> using unqualified = std::remove_cv<std::remove_reference_t<T>>; template<typename T> using unqualified_t = typename unqualified<T>::type; template<typename... Args> using tuple_types = typename detail::tuple_types_<Args...>::type; template<typename Arg> struct pop_front_type; template<typename Arg> using pop_front_type_t = typename pop_front_type<Arg>::type; template<typename... Args> struct pop_front_type<types<Args...>> { typedef void front_type; typedef types<Args...> type; }; template<typename Arg, typename... Args> struct pop_front_type<types<Arg, Args...>> { typedef Arg front_type; typedef types<Args...> type; }; template <std::size_t N, typename Tuple> using tuple_element = std::tuple_element<N, unqualified_t<Tuple>>; template <std::size_t N, typename Tuple> using tuple_element_t = std::tuple_element_t<N, unqualified_t<Tuple>>; template <std::size_t N, typename Tuple> using unqualified_tuple_element = unqualified<tuple_element_t<N, Tuple>>; template <std::size_t N, typename Tuple> using unqualified_tuple_element_t = unqualified_t<tuple_element_t<N, Tuple>>; } // meta } // sol // end of sol/tuple.hpp // beginning of sol/bind_traits.hpp namespace sol { namespace meta { namespace meta_detail { template<class F> struct check_deducible_signature { struct nat {}; template<class G> static auto test(int) -> decltype(&G::operator(), void()); template<class> static auto test(...)->nat; using type = std::is_void<decltype(test<F>(0))>; }; } // meta_detail template<class F> struct has_deducible_signature : meta_detail::check_deducible_signature<F>::type { }; namespace meta_detail { template <std::size_t I, typename T> struct void_tuple_element : meta::tuple_element<I, T> {}; template <std::size_t I> struct void_tuple_element<I, std::tuple<>> { typedef void type; }; template <std::size_t I, typename T> using void_tuple_element_t = typename void_tuple_element<I, T>::type; template <bool has_c_variadic, typename T, typename R, typename... Args> struct basic_traits { private: typedef std::conditional_t<std::is_void<T>::value, int, T>& first_type; public: static const bool is_member_function = std::is_void<T>::value; static const bool has_c_var_arg = has_c_variadic; static const std::size_t arity = sizeof...(Args); static const std::size_t free_arity = sizeof...(Args)+static_cast<std::size_t>(!std::is_void<T>::value); typedef types<Args...> args_list; typedef std::tuple<Args...> args_tuple; typedef T object_type; typedef R return_type; typedef tuple_types<R> returns_list; typedef R(function_type)(Args...); typedef std::conditional_t<std::is_void<T>::value, args_list, types<first_type, Args...>> free_args_list; typedef std::conditional_t<std::is_void<T>::value, R(Args...), R(first_type, Args...)> free_function_type; typedef std::conditional_t<std::is_void<T>::value, R(*)(Args...), R(*)(first_type, Args...)> free_function_pointer_type; typedef std::remove_pointer_t<free_function_pointer_type> signature_type; template<std::size_t i> using arg_at = void_tuple_element_t<i, args_tuple>; }; template<typename Signature, bool b = has_deducible_signature<Signature>::value> struct fx_traits : basic_traits<false, void, void> {}; // Free Functions template<typename R, typename... Args> struct fx_traits<R(Args...), false> : basic_traits<false, void, R, Args...> { typedef R(*function_pointer_type)(Args...); }; template<typename R, typename... Args> struct fx_traits<R(*)(Args...), false> : basic_traits<false, void, R, Args...> { typedef R(*function_pointer_type)(Args...); }; template<typename R, typename... Args> struct fx_traits<R(Args..., ...), false> : basic_traits<true, void, R, Args...> { typedef R(*function_pointer_type)(Args..., ...); }; template<typename R, typename... Args> struct fx_traits<R(*)(Args..., ...), false> : basic_traits<true, void, R, Args...> { typedef R(*function_pointer_type)(Args..., ...); }; // Member Functions /* C-Style Variadics */ template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args...), false> : basic_traits<false, T, R, Args...> { typedef R(T::* function_pointer_type)(Args...); }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args..., ...), false> : basic_traits<true, T, R, Args...> { typedef R(T::* function_pointer_type)(Args..., ...); }; /* Const Volatile */ template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args...) const, false> : basic_traits<false, T, R, Args...> { typedef R(T::* function_pointer_type)(Args...) const; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args..., ...) const, false> : basic_traits<true, T, R, Args...> { typedef R(T::* function_pointer_type)(Args..., ...) const; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args...) const volatile, false> : basic_traits<false, T, R, Args...> { typedef R(T::* function_pointer_type)(Args...) const volatile; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args..., ...) const volatile, false> : basic_traits<true, T, R, Args...> { typedef R(T::* function_pointer_type)(Args..., ...) const volatile; }; /* Member Function Qualifiers */ template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args...) &, false> : basic_traits<false, T, R, Args...> { typedef R(T::* function_pointer_type)(Args...) &; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args..., ...) &, false> : basic_traits<true, T, R, Args...> { typedef R(T::* function_pointer_type)(Args..., ...) &; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args...) const &, false> : basic_traits<false, T, R, Args...> { typedef R(T::* function_pointer_type)(Args...) const &; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args..., ...) const &, false> : basic_traits<true, T, R, Args...> { typedef R(T::* function_pointer_type)(Args..., ...) const &; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args...) const volatile &, false> : basic_traits<false, T, R, Args...> { typedef R(T::* function_pointer_type)(Args...) const volatile &; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args..., ...) const volatile &, false> : basic_traits<true, T, R, Args...> { typedef R(T::* function_pointer_type)(Args..., ...) const volatile &; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args...) && , false> : basic_traits<false, T, R, Args...> { typedef R(T::* function_pointer_type)(Args...) && ; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args..., ...) && , false> : basic_traits<true, T, R, Args...> { typedef R(T::* function_pointer_type)(Args..., ...) && ; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args...) const &&, false> : basic_traits<false, T, R, Args...> { typedef R(T::* function_pointer_type)(Args...) const &&; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args..., ...) const &&, false> : basic_traits<true, T, R, Args...> { typedef R(T::* function_pointer_type)(Args..., ...) const &&; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args...) const volatile &&, false> : basic_traits<false, T, R, Args...> { typedef R(T::* function_pointer_type)(Args...) const volatile &&; }; template<typename T, typename R, typename... Args> struct fx_traits<R(T::*)(Args..., ...) const volatile &&, false> : basic_traits<true, T, R, Args...> { typedef R(T::* function_pointer_type)(Args..., ...) const volatile &&; }; template<typename Signature> struct fx_traits<Signature, true> : fx_traits<typename fx_traits<decltype(&Signature::operator())>::function_type, false> {}; template<typename Signature, bool b = std::is_member_object_pointer<Signature>::value> struct callable_traits : fx_traits<std::decay_t<Signature>> { }; template<typename R, typename T> struct callable_traits<R(T::*), true> { typedef R Arg; typedef T object_type; using signature_type = R(T::*); static const bool is_member_function = false; static const std::size_t arity = 1; static const std::size_t free_arity = 2; typedef std::tuple<Arg> args_tuple; typedef R return_type; typedef types<Arg> args_list; typedef types<T, Arg> free_args_list; typedef meta::tuple_types<R> returns_list; typedef R(function_type)(T&, R); typedef R(*function_pointer_type)(T&, R); typedef R(*free_function_pointer_type)(T&, R); template<std::size_t i> using arg_at = void_tuple_element_t<i, args_tuple>; }; } // meta_detail template<typename Signature> struct bind_traits : meta_detail::callable_traits<Signature> {}; template<typename Signature> using function_args_t = typename bind_traits<Signature>::args_list; template<typename Signature> using function_signature_t = typename bind_traits<Signature>::signature_type; template<typename Signature> using function_return_t = typename bind_traits<Signature>::return_type; } // meta } // sol // end of sol/bind_traits.hpp #include <type_traits> #include <memory> #include <functional> namespace sol { template<std::size_t I> using index_value = std::integral_constant<std::size_t, I>; namespace meta { template<typename T> struct identity { typedef T type; }; template<typename T> using identity_t = typename identity<T>::type; template<typename... Args> struct is_tuple : std::false_type { }; template<typename... Args> struct is_tuple<std::tuple<Args...>> : std::true_type { }; template<typename T> struct unwrapped { typedef T type; }; template<typename T> struct unwrapped<std::reference_wrapper<T>> { typedef T type; }; template<typename T> using unwrapped_t = typename unwrapped<T>::type; template <typename T> struct unwrap_unqualified : unwrapped<unqualified_t<T>> {}; template <typename T> using unwrap_unqualified_t = typename unwrap_unqualified<T>::type; template<typename T> struct remove_member_pointer; template<typename R, typename T> struct remove_member_pointer<R T::*> { typedef R type; }; template<typename R, typename T> struct remove_member_pointer<R T::* const> { typedef R type; }; template<typename T> using remove_member_pointer_t = remove_member_pointer<T>; template<template<typename...> class Templ, typename T> struct is_specialization_of : std::false_type { }; template<typename... T, template<typename...> class Templ> struct is_specialization_of<Templ, Templ<T...>> : std::true_type { }; template<class T, class...> struct all_same : std::true_type { }; template<class T, class U, class... Args> struct all_same<T, U, Args...> : std::integral_constant <bool, std::is_same<T, U>::value && all_same<T, Args...>::value> { }; template<class T, class...> struct any_same : std::false_type { }; template<class T, class U, class... Args> struct any_same<T, U, Args...> : std::integral_constant <bool, std::is_same<T, U>::value || any_same<T, Args...>::value> { }; template<typename T> using invoke_t = typename T::type; template<bool B> using boolean = std::integral_constant<bool, B>; template<typename T> using neg = boolean<!T::value>; template<typename Condition, typename Then, typename Else> using condition = std::conditional_t<Condition::value, Then, Else>; template<typename... Args> struct all : boolean<true> {}; template<typename T, typename... Args> struct all<T, Args...> : condition<T, all<Args...>, boolean<false>> {}; template<typename... Args> struct any : boolean<false> {}; template<typename T, typename... Args> struct any<T, Args...> : condition<T, boolean<true>, any<Args...>> {}; enum class enable_t { _ }; constexpr const auto enabler = enable_t::_; template<bool value, typename T = void> using disable_if_t = std::enable_if_t<!value, T>; template<typename... Args> using enable = std::enable_if_t<all<Args...>::value, enable_t>; template<typename... Args> using disable = std::enable_if_t<neg<all<Args...>>::value, enable_t>; template<typename... Args> using disable_any = std::enable_if_t<neg<any<Args...>>::value, enable_t>; template<typename V, typename... Vs> struct find_in_pack_v : boolean<false> { }; template<typename V, typename Vs1, typename... Vs> struct find_in_pack_v<V, Vs1, Vs...> : any<boolean<(V::value == Vs1::value)>, find_in_pack_v<V, Vs...>> { }; namespace meta_detail { template<std::size_t I, typename T, typename... Args> struct index_in_pack : std::integral_constant<std::size_t, SIZE_MAX> { }; template<std::size_t I, typename T, typename T1, typename... Args> struct index_in_pack<I, T, T1, Args...> : std::conditional_t<std::is_same<T, T1>::value, std::integral_constant<std::ptrdiff_t, I>, index_in_pack<I + 1, T, Args...>> { }; } template<typename T, typename... Args> struct index_in_pack : meta_detail::index_in_pack<0, T, Args...> { }; template<typename T, typename List> struct index_in : meta_detail::index_in_pack<0, T, List> { }; template<typename T, typename... Args> struct index_in<T, types<Args...>> : meta_detail::index_in_pack<0, T, Args...> { }; template<std::size_t I, typename... Args> struct at_in_pack {}; template<std::size_t I, typename... Args> using at_in_pack_t = typename at_in_pack<I, Args...>::type; template<std::size_t I, typename Arg, typename... Args> struct at_in_pack<I, Arg, Args...> : std::conditional<I == 0, Arg, at_in_pack_t<I - 1, Args...>> {}; template<typename Arg, typename... Args> struct at_in_pack<0, Arg, Args...> { typedef Arg type; }; namespace meta_detail { template<std::size_t Limit, std::size_t I, template<typename...> class Pred, typename... Ts> struct count_for_pack : std::integral_constant<std::size_t, 0> {}; template<std::size_t Limit, std::size_t I, template<typename...> class Pred, typename T, typename... Ts> struct count_for_pack<Limit, I, Pred, T, Ts...> : std::conditional_t < sizeof...(Ts) == 0 || Limit < 2, std::integral_constant<std::size_t, I + static_cast<std::size_t>(Limit != 0 && Pred<T>::value)>, count_for_pack<Limit - 1, I + static_cast<std::size_t>(Pred<T>::value), Pred, Ts...> > { }; template<std::size_t I, template<typename...> class Pred, typename... Ts> struct count_2_for_pack : std::integral_constant<std::size_t, 0> {}; template<std::size_t I, template<typename...> class Pred, typename T, typename U, typename... Ts> struct count_2_for_pack<I, Pred, T, U, Ts...> : std::conditional_t<sizeof...(Ts) == 0, std::integral_constant<std::size_t, I + static_cast<std::size_t>(Pred<T>::value)>, count_2_for_pack<I + static_cast<std::size_t>(Pred<T>::value), Pred, Ts...> > { }; } // meta_detail template<template<typename...> class Pred, typename... Ts> struct count_for_pack : meta_detail::count_for_pack<sizeof...(Ts), 0, Pred, Ts...> { }; template<template<typename...> class Pred, typename List> struct count_for; template<template<typename...> class Pred, typename... Args> struct count_for<Pred, types<Args...>> : count_for_pack<Pred, Args...> {}; template<std::size_t Limit, template<typename...> class Pred, typename... Ts> struct count_for_to_pack : meta_detail::count_for_pack<Limit, 0, Pred, Ts...> { }; template<template<typename...> class Pred, typename... Ts> struct count_2_for_pack : meta_detail::count_2_for_pack<0, Pred, Ts...> { }; template<typename... Args> struct return_type { typedef std::tuple<Args...> type; }; template<typename T> struct return_type<T> { typedef T type; }; template<> struct return_type<> { typedef void type; }; template <typename... Args> using return_type_t = typename return_type<Args...>::type; namespace meta_detail { template <typename> struct always_true : std::true_type {}; struct is_invokable_tester { template <typename Fun, typename... Args> always_true<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int); template <typename...> std::false_type static test(...); }; } // meta_detail template <typename T> struct is_invokable; template <typename Fun, typename... Args> struct is_invokable<Fun(Args...)> : decltype(meta_detail::is_invokable_tester::test<Fun, Args...>(0)) {}; namespace meta_detail { template<typename T, bool isclass = std::is_class<unqualified_t<T>>::value> struct is_callable : std::is_function<std::remove_pointer_t<T>> {}; template<typename T> struct is_callable<T, true> { using yes = char; using no = struct { char s[2]; }; struct F { void operator()(); }; struct Derived : T, F {}; template<typename U, U> struct Check; template<typename V> static no test(Check<void (F::*)(), &V::operator()>*); template<typename> static yes test(...); static const bool value = sizeof(test<Derived>(0)) == sizeof(yes); }; struct has_begin_end_impl { template<typename T, typename U = unqualified_t<T>, typename B = decltype(std::declval<U&>().begin()), typename E = decltype(std::declval<U&>().end())> static std::true_type test(int); template<typename...> static std::false_type test(...); }; struct has_key_value_pair_impl { template<typename T, typename U = unqualified_t<T>, typename V = typename U::value_type, typename F = decltype(std::declval<V&>().first), typename S = decltype(std::declval<V&>().second)> static std::true_type test(int); template<typename...> static std::false_type test(...); }; template <typename T, typename U = T, typename = decltype(std::declval<T&>() < std::declval<U&>())> std::true_type supports_op_less_test(const T&); std::false_type supports_op_less_test(...); template <typename T, typename U = T, typename = decltype(std::declval<T&>() == std::declval<U&>())> std::true_type supports_op_equal_test(const T&); std::false_type supports_op_equal_test(...); template <typename T, typename U = T, typename = decltype(std::declval<T&>() <= std::declval<U&>())> std::true_type supports_op_less_equal_test(const T&); std::false_type supports_op_less_equal_test(...); } // meta_detail template <typename T> using supports_op_less = decltype(meta_detail::supports_op_less_test(std::declval<T&>())); template <typename T> using supports_op_equal = decltype(meta_detail::supports_op_equal_test(std::declval<T&>())); template <typename T> using supports_op_less_equal = decltype(meta_detail::supports_op_less_equal_test(std::declval<T&>())); template<typename T> struct is_callable : boolean<meta_detail::is_callable<T>::value> {}; template<typename T> struct has_begin_end : decltype(meta_detail::has_begin_end_impl::test<T>(0)) {}; template<typename T> struct has_key_value_pair : decltype(meta_detail::has_key_value_pair_impl::test<T>(0)) {}; template <typename T> using is_string_constructible = any<std::is_same<unqualified_t<T>, const char*>, std::is_same<unqualified_t<T>, char>, std::is_same<unqualified_t<T>, std::string>, std::is_same<unqualified_t<T>, std::initializer_list<char>>>; template <typename T> using is_c_str = any< std::is_same<std::decay_t<unqualified_t<T>>, const char*>, std::is_same<std::decay_t<unqualified_t<T>>, char*>, std::is_same<unqualified_t<T>, std::string> >; template <typename T> struct is_move_only : all< neg<std::is_reference<T>>, neg<std::is_copy_constructible<unqualified_t<T>>>, std::is_move_constructible<unqualified_t<T>> > {}; template <typename T> using is_not_move_only = neg<is_move_only<T>>; namespace meta_detail { template <typename T, meta::disable<meta::is_specialization_of<std::tuple, meta::unqualified_t<T>>> = meta::enabler> decltype(auto) force_tuple(T&& x) { return std::forward_as_tuple(std::forward<T>(x)); } template <typename T, meta::enable<meta::is_specialization_of<std::tuple, meta::unqualified_t<T>>> = meta::enabler> decltype(auto) force_tuple(T&& x) { return std::forward<T>(x); } } // meta_detail template <typename... X> decltype(auto) tuplefy(X&&... x) { return std::tuple_cat(meta_detail::force_tuple(std::forward<X>(x))...); } } // meta namespace detail { template <std::size_t I, typename Tuple> decltype(auto) forward_get(Tuple&& tuple) { return std::forward<meta::tuple_element_t<I, Tuple>>(std::get<I>(tuple)); } template <std::size_t... I, typename Tuple> auto forward_tuple_impl(std::index_sequence<I...>, Tuple&& tuple) -> decltype(std::tuple<decltype(forward_get<I>(tuple))...>(forward_get<I>(tuple)...)) { return std::tuple<decltype(forward_get<I>(tuple))...>(std::move(std::get<I>(tuple))...); } template <typename Tuple> auto forward_tuple(Tuple&& tuple) { auto x = forward_tuple_impl(std::make_index_sequence<std::tuple_size<meta::unqualified_t<Tuple>>::value>(), std::forward<Tuple>(tuple)); return x; } template<typename T> auto unwrap(T&& item) -> decltype(std::forward<T>(item)) { return std::forward<T>(item); } template<typename T> T& unwrap(std::reference_wrapper<T> arg) { return arg.get(); } template<typename T> auto deref(T&& item) -> decltype(std::forward<T>(item)) { return std::forward<T>(item); } template<typename T> inline T& deref(T* item) { return *item; } template<typename T, typename Dx> inline std::add_lvalue_reference_t<T> deref(std::unique_ptr<T, Dx>& item) { return *item; } template<typename T> inline std::add_lvalue_reference_t<T> deref(std::shared_ptr<T>& item) { return *item; } template<typename T, typename Dx> inline std::add_lvalue_reference_t<T> deref(const std::unique_ptr<T, Dx>& item) { return *item; } template<typename T> inline std::add_lvalue_reference_t<T> deref(const std::shared_ptr<T>& item) { return *item; } template<typename T> inline T* ptr(T& val) { return std::addressof(val); } template<typename T> inline T* ptr(std::reference_wrapper<T> val) { return std::addressof(val.get()); } template<typename T> inline T* ptr(T* val) { return val; } } // detail } // sol // end of sol/traits.hpp // beginning of sol/object.hpp // beginning of sol/optional.hpp // beginning of sol/in_place.hpp namespace sol { namespace detail { struct in_place_of {}; template <std::size_t I> struct in_place_of_i {}; template <typename T> struct in_place_of_t {}; } // detail struct in_place_tag { struct init {}; constexpr in_place_tag(init) {} in_place_tag() = delete; }; constexpr inline in_place_tag in_place(detail::in_place_of) { return in_place_tag(in_place_tag::init()); } template <typename T> constexpr inline in_place_tag in_place(detail::in_place_of_t<T>) { return in_place_tag(in_place_tag::init()); } template <std::size_t I> constexpr inline in_place_tag in_place(detail::in_place_of_i<I>) { return in_place_tag(in_place_tag::init()); } using in_place_t = in_place_tag(&)(detail::in_place_of); template <typename T> using in_place_type_t = in_place_tag(&)(detail::in_place_of_t<T>); template <std::size_t I> using in_place_index_t = in_place_tag(&)(detail::in_place_of_i<I>); } // sol // end of sol/in_place.hpp #if defined(SOL_USE_BOOST) #include <boost/optional.hpp> #else // beginning of Optional/optional.hpp # ifndef ___SOL_OPTIONAL_HPP___ # define ___SOL_OPTIONAL_HPP___ # include <utility> # include <type_traits> # include <initializer_list> # include <cassert> # include <functional> # include <string> # include <stdexcept> # define TR2_OPTIONAL_REQUIRES(...) typename ::std::enable_if<__VA_ARGS__::value, bool>::type = false # if defined __GNUC__ // NOTE: GNUC is also defined for Clang # if (__GNUC__ >= 5) # define TR2_OPTIONAL_GCC_5_0_AND_HIGHER___ # define TR2_OPTIONAL_GCC_4_8_AND_HIGHER___ # elif (__GNUC__ == 4) && (__GNUC_MINOR__ >= 8) # define TR2_OPTIONAL_GCC_4_8_AND_HIGHER___ # elif (__GNUC__ > 4) # define TR2_OPTIONAL_GCC_4_8_AND_HIGHER___ # endif # # if (__GNUC__ == 4) && (__GNUC_MINOR__ >= 7) # define TR2_OPTIONAL_GCC_4_7_AND_HIGHER___ # elif (__GNUC__ > 4) # define TR2_OPTIONAL_GCC_4_7_AND_HIGHER___ # endif # # if (__GNUC__ == 4) && (__GNUC_MINOR__ == 8) && (__GNUC_PATCHLEVEL__ >= 1) # define TR2_OPTIONAL_GCC_4_8_1_AND_HIGHER___ # elif (__GNUC__ == 4) && (__GNUC_MINOR__ >= 9) # define TR2_OPTIONAL_GCC_4_8_1_AND_HIGHER___ # elif (__GNUC__ > 4) # define TR2_OPTIONAL_GCC_4_8_1_AND_HIGHER___ # endif # endif # # if defined __clang_major__ # if (__clang_major__ == 3 && __clang_minor__ >= 5) # define TR2_OPTIONAL_CLANG_3_5_AND_HIGHTER_ # elif (__clang_major__ > 3) # define TR2_OPTIONAL_CLANG_3_5_AND_HIGHTER_ # endif # if defined TR2_OPTIONAL_CLANG_3_5_AND_HIGHTER_ # define TR2_OPTIONAL_CLANG_3_4_2_AND_HIGHER_ # elif (__clang_major__ == 3 && __clang_minor__ == 4 && __clang_patchlevel__ >= 2) # define TR2_OPTIONAL_CLANG_3_4_2_AND_HIGHER_ # endif # endif # # if defined _MSC_VER # if (_MSC_VER >= 1900) # define TR2_OPTIONAL_MSVC_2015_AND_HIGHER___ # endif # endif # if defined __clang__ # if (__clang_major__ > 2) || (__clang_major__ == 2) && (__clang_minor__ >= 9) # define OPTIONAL_HAS_THIS_RVALUE_REFS 1 # else # define OPTIONAL_HAS_THIS_RVALUE_REFS 0 # endif # elif defined TR2_OPTIONAL_GCC_4_8_1_AND_HIGHER___ # define OPTIONAL_HAS_THIS_RVALUE_REFS 1 # elif defined TR2_OPTIONAL_MSVC_2015_AND_HIGHER___ # define OPTIONAL_HAS_THIS_RVALUE_REFS 1 # else # define OPTIONAL_HAS_THIS_RVALUE_REFS 0 # endif # if defined TR2_OPTIONAL_GCC_4_8_1_AND_HIGHER___ # define OPTIONAL_HAS_CONSTEXPR_INIT_LIST 1 # define OPTIONAL_CONSTEXPR_INIT_LIST constexpr # else # define OPTIONAL_HAS_CONSTEXPR_INIT_LIST 0 # define OPTIONAL_CONSTEXPR_INIT_LIST # endif # if defined TR2_OPTIONAL_CLANG_3_5_AND_HIGHTER_ && (defined __cplusplus) && (__cplusplus != 201103L) # define OPTIONAL_HAS_MOVE_ACCESSORS 1 # else # define OPTIONAL_HAS_MOVE_ACCESSORS 0 # endif # // In C++11 constexpr implies const, so we need to make non-const members also non-constexpr # if (defined __cplusplus) && (__cplusplus == 201103L) # define OPTIONAL_MUTABLE_CONSTEXPR # else # define OPTIONAL_MUTABLE_CONSTEXPR constexpr # endif namespace sol{ # if defined TR2_OPTIONAL_GCC_4_8_AND_HIGHER___ // leave it: it is already there # elif defined TR2_OPTIONAL_CLANG_3_4_2_AND_HIGHER_ // leave it: it is already there # elif defined TR2_OPTIONAL_MSVC_2015_AND_HIGHER___ // leave it: it is already there # elif defined TR2_OPTIONAL_DISABLE_EMULATION_OF_TYPE_TRAITS // leave it: the user doesn't want it # else template <typename T> using is_trivially_destructible = ::std::has_trivial_destructor<T>; # endif # if (defined TR2_OPTIONAL_GCC_4_7_AND_HIGHER___) // leave it; our metafunctions are already defined. # elif defined TR2_OPTIONAL_CLANG_3_4_2_AND_HIGHER_ // leave it; our metafunctions are already defined. # elif defined TR2_OPTIONAL_MSVC_2015_AND_HIGHER___ // leave it: it is already there # elif defined TR2_OPTIONAL_DISABLE_EMULATION_OF_TYPE_TRAITS // leave it: the user doesn't want it # else template <class T> struct is_nothrow_move_constructible { constexpr static bool value = ::std::is_nothrow_constructible<T, T&&>::value; }; template <class T, class U> struct is_assignable { template <class X, class Y> constexpr static bool has_assign(...) { return false; } template <class X, class Y, size_t S = sizeof((::std::declval<X>() = ::std::declval<Y>(), true)) > // the comma operator is necessary for the cases where operator= returns void constexpr static bool has_assign(bool) { return true; } constexpr static bool value = has_assign<T, U>(true); }; template <class T> struct is_nothrow_move_assignable { template <class X, bool has_any_move_assign> struct has_nothrow_move_assign { constexpr static bool value = false; }; template <class X> struct has_nothrow_move_assign<X, true> { constexpr static bool value = noexcept( ::std::declval<X&>() = ::std::declval<X&&>() ); }; constexpr static bool value = has_nothrow_move_assign<T, is_assignable<T&, T&&>::value>::value; }; # endif template <class T> class optional; template <class T> class optional<T&>; template <class T> inline constexpr T&& constexpr_forward(typename ::std::remove_reference<T>::type& t) noexcept { return static_cast<T&&>(t); } template <class T> inline constexpr T&& constexpr_forward(typename ::std::remove_reference<T>::type&& t) noexcept { static_assert(!::std::is_lvalue_reference<T>::value, "!!"); return static_cast<T&&>(t); } template <class T> inline constexpr typename ::std::remove_reference<T>::type&& constexpr_move(T&& t) noexcept { return static_cast<typename ::std::remove_reference<T>::type&&>(t); } #if defined NDEBUG # define TR2_OPTIONAL_ASSERTED_EXPRESSION(CHECK, EXPR) (EXPR) #else # define TR2_OPTIONAL_ASSERTED_EXPRESSION(CHECK, EXPR) ((CHECK) ? (EXPR) : ([]{assert(!#CHECK);}(), (EXPR))) #endif namespace detail_ { template <typename T> struct has_overloaded_addressof { template <class X> constexpr static bool has_overload(...) { return false; } template <class X, size_t S = sizeof(::std::declval<X&>().operator&()) > constexpr static bool has_overload(bool) { return true; } constexpr static bool value = has_overload<T>(true); }; template <typename T, TR2_OPTIONAL_REQUIRES(!has_overloaded_addressof<T>)> constexpr T* static_addressof(T& ref) { return &ref; } template <typename T, TR2_OPTIONAL_REQUIRES(has_overloaded_addressof<T>)> T* static_addressof(T& ref) { return ::std::addressof(ref); } template <class U> constexpr U convert(U v) { return v; } } // namespace detail_ constexpr struct trivial_init_t {} trivial_init{}; struct nullopt_t { struct init{}; constexpr explicit nullopt_t(init){} }; constexpr nullopt_t nullopt{nullopt_t::init()}; class bad_optional_access : public ::std::logic_error { public: explicit bad_optional_access(const ::std::string& what_arg) : ::std::logic_error{what_arg} {} explicit bad_optional_access(const char* what_arg) : ::std::logic_error{what_arg} {} }; template <class T> struct optional_base { bool init_; char storage_[sizeof(T)]; constexpr optional_base() noexcept : init_(false), storage_() {}; explicit optional_base(const T& v) : init_(true), storage_() { new (&storage())T(v); } explicit optional_base(T&& v) : init_(true), storage_() { new (&storage())T(constexpr_move(v)); } template <class... Args> explicit optional_base(in_place_t, Args&&... args) : init_(true), storage_() { new (&storage())T(constexpr_forward<Args>(args)...); } template <class U, class... Args, TR2_OPTIONAL_REQUIRES(::std::is_constructible<T, ::std::initializer_list<U>>)> explicit optional_base(in_place_t, ::std::initializer_list<U> il, Args&&... args) : init_(true), storage_() { new (&storage())T(il, constexpr_forward<Args>(args)...); } #if defined __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif T& storage() { return *reinterpret_cast<T*>(&storage_[0]); } constexpr const T& storage() const { return *reinterpret_cast<T const*>(&storage_[0]); } #if defined __GNUC__ #pragma GCC diagnostic pop #endif ~optional_base() { if (init_) { storage().T::~T(); } } }; #if defined __GNUC__ && !defined TR2_OPTIONAL_GCC_5_0_AND_HIGHER___ template <typename T> using constexpr_optional_base = optional_base<T>; #else template <class T> struct constexpr_optional_base { bool init_; char storage_[sizeof(T)]; constexpr constexpr_optional_base() noexcept : init_(false), storage_() {} explicit constexpr constexpr_optional_base(const T& v) : init_(true), storage_() { new (&storage())T(v); } explicit constexpr constexpr_optional_base(T&& v) : init_(true), storage_() { new (&storage())T(constexpr_move(v)); } template <class... Args> explicit constexpr constexpr_optional_base(in_place_t, Args&&... args) : init_(true), storage_() { new (&storage())T(constexpr_forward<Args>(args)...); } template <class U, class... Args, TR2_OPTIONAL_REQUIRES(::std::is_constructible<T, ::std::initializer_list<U>>)> OPTIONAL_CONSTEXPR_INIT_LIST explicit constexpr_optional_base(in_place_t, ::std::initializer_list<U> il, Args&&... args) : init_(true), storage_() { new (&storage())T(il, constexpr_forward<Args>(args)...); } #if defined __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif T& storage() { return (*reinterpret_cast<T*>(&storage_[0])); } constexpr const T& storage() const { return (*reinterpret_cast<T const*>(&storage_[0])); } #if defined __GNUC__ #pragma GCC diagnostic pop #endif ~constexpr_optional_base() = default; }; #endif template <class T> using OptionalBase = typename ::std::conditional< ::std::is_trivially_destructible<T>::value, constexpr_optional_base<typename ::std::remove_const<T>::type>, optional_base<typename ::std::remove_const<T>::type> >::type; template <class T> class optional : private OptionalBase<T> { static_assert( !::std::is_same<typename ::std::decay<T>::type, nullopt_t>::value, "bad T" ); static_assert( !::std::is_same<typename ::std::decay<T>::type, in_place_t>::value, "bad T" ); constexpr bool initialized() const noexcept { return OptionalBase<T>::init_; } typename ::std::remove_const<T>::type* dataptr() { return ::std::addressof(OptionalBase<T>::storage()); } constexpr const T* dataptr() const { return detail_::static_addressof(OptionalBase<T>::storage()); } # if OPTIONAL_HAS_THIS_RVALUE_REFS == 1 constexpr const T& contained_val() const& { return OptionalBase<T>::storage(); } # if OPTIONAL_HAS_MOVE_ACCESSORS == 1 OPTIONAL_MUTABLE_CONSTEXPR T&& contained_val() && { return ::std::move(OptionalBase<T>::storage()); } OPTIONAL_MUTABLE_CONSTEXPR T& contained_val() & { return OptionalBase<T>::storage(); } # else T& contained_val() & { return OptionalBase<T>::storage(); } T&& contained_val() && { return ::std::move(OptionalBase<T>::storage()); } # endif # else constexpr const T& contained_val() const { return OptionalBase<T>::storage(); } T& contained_val() { return OptionalBase<T>::storage(); } # endif void clear() noexcept { if (initialized()) dataptr()->T::~T(); OptionalBase<T>::init_ = false; } template <class... Args> void initialize(Args&&... args) noexcept(noexcept(T(::std::forward<Args>(args)...))) { assert(!OptionalBase<T>::init_); ::new (static_cast<void*>(dataptr())) T(::std::forward<Args>(args)...); OptionalBase<T>::init_ = true; } template <class U, class... Args> void initialize(::std::initializer_list<U> il, Args&&... args) noexcept(noexcept(T(il, ::std::forward<Args>(args)...))) { assert(!OptionalBase<T>::init_); ::new (static_cast<void*>(dataptr())) T(il, ::std::forward<Args>(args)...); OptionalBase<T>::init_ = true; } public: typedef T value_type; // 20.5.5.1, constructors constexpr optional() noexcept : OptionalBase<T>() {}; constexpr optional(nullopt_t) noexcept : OptionalBase<T>() {}; optional(const optional& rhs) : OptionalBase<T>() { if (rhs.initialized()) { ::new (static_cast<void*>(dataptr())) T(*rhs); OptionalBase<T>::init_ = true; } } optional(const optional<T&>& rhs) : optional() { if (rhs) { ::new (static_cast<void*>(dataptr())) T(*rhs); OptionalBase<T>::init_ = true; } } optional(optional&& rhs) noexcept(::std::is_nothrow_move_constructible<T>::value) : OptionalBase<T>() { if (rhs.initialized()) { ::new (static_cast<void*>(dataptr())) T(::std::move(*rhs)); OptionalBase<T>::init_ = true; } } constexpr optional(const T& v) : OptionalBase<T>(v) {} constexpr optional(T&& v) : OptionalBase<T>(constexpr_move(v)) {} template <class... Args> explicit constexpr optional(in_place_t, Args&&... args) : OptionalBase<T>(in_place, constexpr_forward<Args>(args)...) {} template <class U, class... Args, TR2_OPTIONAL_REQUIRES(::std::is_constructible<T, ::std::initializer_list<U>>)> OPTIONAL_CONSTEXPR_INIT_LIST explicit optional(in_place_t, ::std::initializer_list<U> il, Args&&... args) : OptionalBase<T>(in_place, il, constexpr_forward<Args>(args)...) {} // 20.5.4.2, Destructor ~optional() = default; // 20.5.4.3, assignment optional& operator=(nullopt_t) noexcept { clear(); return *this; } optional& operator=(const optional& rhs) { if (initialized() == true && rhs.initialized() == false) clear(); else if (initialized() == false && rhs.initialized() == true) initialize(*rhs); else if (initialized() == true && rhs.initialized() == true) contained_val() = *rhs; return *this; } optional& operator=(optional&& rhs) noexcept(::std::is_nothrow_move_assignable<T>::value && ::std::is_nothrow_move_constructible<T>::value) { if (initialized() == true && rhs.initialized() == false) clear(); else if (initialized() == false && rhs.initialized() == true) initialize(::std::move(*rhs)); else if (initialized() == true && rhs.initialized() == true) contained_val() = ::std::move(*rhs); return *this; } template <class U> auto operator=(U&& v) -> typename ::std::enable_if < ::std::is_same<typename ::std::decay<U>::type, T>::value, optional& >::type { if (initialized()) { contained_val() = ::std::forward<U>(v); } else { initialize(::std::forward<U>(v)); } return *this; } template <class... Args> void emplace(Args&&... args) { clear(); initialize(::std::forward<Args>(args)...); } template <class U, class... Args> void emplace(::std::initializer_list<U> il, Args&&... args) { clear(); initialize<U, Args...>(il, ::std::forward<Args>(args)...); } // 20.5.4.4, Swap void swap(optional<T>& rhs) noexcept(::std::is_nothrow_move_constructible<T>::value && noexcept(swap(::std::declval<T&>(), ::std::declval<T&>()))) { if (initialized() == true && rhs.initialized() == false) { rhs.initialize(::std::move(**this)); clear(); } else if (initialized() == false && rhs.initialized() == true) { initialize(::std::move(*rhs)); rhs.clear(); } else if (initialized() == true && rhs.initialized() == true) { using ::std::swap; swap(**this, *rhs); } } // 20.5.4.5, Observers explicit constexpr operator bool() const noexcept { return initialized(); } constexpr T const* operator ->() const { return TR2_OPTIONAL_ASSERTED_EXPRESSION(initialized(), dataptr()); } # if OPTIONAL_HAS_MOVE_ACCESSORS == 1 OPTIONAL_MUTABLE_CONSTEXPR T* operator ->() { assert (initialized()); return dataptr(); } constexpr T const& operator *() const& { return TR2_OPTIONAL_ASSERTED_EXPRESSION(initialized(), contained_val()); } OPTIONAL_MUTABLE_CONSTEXPR T& operator *() & { assert (initialized()); return contained_val(); } OPTIONAL_MUTABLE_CONSTEXPR T&& operator *() && { assert (initialized()); return constexpr_move(contained_val()); } constexpr T const& value() const& { return initialized() ? contained_val() : (throw bad_optional_access("bad optional access"), contained_val()); } OPTIONAL_MUTABLE_CONSTEXPR T& value() & { return initialized() ? contained_val() : (throw bad_optional_access("bad optional access"), contained_val()); } OPTIONAL_MUTABLE_CONSTEXPR T&& value() && { if (!initialized()) throw bad_optional_access("bad optional access"); return ::std::move(contained_val()); } # else T* operator ->() { assert (initialized()); return dataptr(); } constexpr T const& operator *() const { return TR2_OPTIONAL_ASSERTED_EXPRESSION(initialized(), contained_val()); } T& operator *() { assert (initialized()); return contained_val(); } constexpr T const& value() const { return initialized() ? contained_val() : (throw bad_optional_access("bad optional access"), contained_val()); } T& value() { return initialized() ? contained_val() : (throw bad_optional_access("bad optional access"), contained_val()); } # endif # if OPTIONAL_HAS_THIS_RVALUE_REFS == 1 template <class V> constexpr T value_or(V&& v) const& { return *this ? **this : detail_::convert<T>(constexpr_forward<V>(v)); } # if OPTIONAL_HAS_MOVE_ACCESSORS == 1 template <class V> OPTIONAL_MUTABLE_CONSTEXPR T value_or(V&& v) && { return *this ? constexpr_move(const_cast<optional<T>&>(*this).contained_val()) : detail_::convert<T>(constexpr_forward<V>(v)); } # else template <class V> T value_or(V&& v) && { return *this ? constexpr_move(const_cast<optional<T>&>(*this).contained_val()) : detail_::convert<T>(constexpr_forward<V>(v)); } # endif # else template <class V> constexpr T value_or(V&& v) const { return *this ? **this : detail_::convert<T>(constexpr_forward<V>(v)); } # endif }; template <class T> class optional<T&> { static_assert( !::std::is_same<T, nullopt_t>::value, "bad T" ); static_assert( !::std::is_same<T, in_place_t>::value, "bad T" ); T* ref; public: // 20.5.5.1, construction/destruction constexpr optional() noexcept : ref(nullptr) {} constexpr optional(nullopt_t) noexcept : ref(nullptr) {} constexpr optional(T& v) noexcept : ref(detail_::static_addressof(v)) {} optional(T&&) = delete; constexpr optional(const optional& rhs) noexcept : ref(rhs.ref) {} explicit constexpr optional(in_place_t, T& v) noexcept : ref(detail_::static_addressof(v)) {} explicit optional(in_place_t, T&&) = delete; ~optional() = default; // 20.5.5.2, mutation optional& operator=(nullopt_t) noexcept { ref = nullptr; return *this; } // optional& operator=(const optional& rhs) noexcept { // ref = rhs.ref; // return *this; // } // optional& operator=(optional&& rhs) noexcept { // ref = rhs.ref; // return *this; // } template <typename U> auto operator=(U&& rhs) noexcept -> typename ::std::enable_if < ::std::is_same<typename ::std::decay<U>::type, optional<T&>>::value, optional& >::type { ref = rhs.ref; return *this; } template <typename U> auto operator=(U&& rhs) noexcept -> typename ::std::enable_if < !::std::is_same<typename ::std::decay<U>::type, optional<T&>>::value, optional& >::type = delete; void emplace(T& v) noexcept { ref = detail_::static_addressof(v); } void emplace(T&&) = delete; void swap(optional<T&>& rhs) noexcept { ::std::swap(ref, rhs.ref); } // 20.5.5.3, observers constexpr T* operator->() const { return TR2_OPTIONAL_ASSERTED_EXPRESSION(ref, ref); } constexpr T& operator*() const { return TR2_OPTIONAL_ASSERTED_EXPRESSION(ref, *ref); } constexpr T& value() const { return ref ? *ref : (throw bad_optional_access("bad optional access"), *ref); } explicit constexpr operator bool() const noexcept { return ref != nullptr; } template <typename V> constexpr T& value_or(V&& v) const { return *this ? **this : detail_::convert<T&>(constexpr_forward<V>(v)); } }; template <class T> class optional<T&&> { static_assert( sizeof(T) == 0, "optional rvalue references disallowed" ); }; template <class T> constexpr bool operator==(const optional<T>& x, const optional<T>& y) { return bool(x) != bool(y) ? false : bool(x) == false ? true : *x == *y; } template <class T> constexpr bool operator!=(const optional<T>& x, const optional<T>& y) { return !(x == y); } template <class T> constexpr bool operator<(const optional<T>& x, const optional<T>& y) { return (!y) ? false : (!x) ? true : *x < *y; } template <class T> constexpr bool operator>(const optional<T>& x, const optional<T>& y) { return (y < x); } template <class T> constexpr bool operator<=(const optional<T>& x, const optional<T>& y) { return !(y < x); } template <class T> constexpr bool operator>=(const optional<T>& x, const optional<T>& y) { return !(x < y); } template <class T> constexpr bool operator==(const optional<T>& x, nullopt_t) noexcept { return (!x); } template <class T> constexpr bool operator==(nullopt_t, const optional<T>& x) noexcept { return (!x); } template <class T> constexpr bool operator!=(const optional<T>& x, nullopt_t) noexcept { return bool(x); } template <class T> constexpr bool operator!=(nullopt_t, const optional<T>& x) noexcept { return bool(x); } template <class T> constexpr bool operator<(const optional<T>&, nullopt_t) noexcept { return false; } template <class T> constexpr bool operator<(nullopt_t, const optional<T>& x) noexcept { return bool(x); } template <class T> constexpr bool operator<=(const optional<T>& x, nullopt_t) noexcept { return (!x); } template <class T> constexpr bool operator<=(nullopt_t, const optional<T>&) noexcept { return true; } template <class T> constexpr bool operator>(const optional<T>& x, nullopt_t) noexcept { return bool(x); } template <class T> constexpr bool operator>(nullopt_t, const optional<T>&) noexcept { return false; } template <class T> constexpr bool operator>=(const optional<T>&, nullopt_t) noexcept { return true; } template <class T> constexpr bool operator>=(nullopt_t, const optional<T>& x) noexcept { return (!x); } template <class T> constexpr bool operator==(const optional<T>& x, const T& v) { return bool(x) ? *x == v : false; } template <class T> constexpr bool operator==(const T& v, const optional<T>& x) { return bool(x) ? v == *x : false; } template <class T> constexpr bool operator!=(const optional<T>& x, const T& v) { return bool(x) ? *x != v : true; } template <class T> constexpr bool operator!=(const T& v, const optional<T>& x) { return bool(x) ? v != *x : true; } template <class T> constexpr bool operator<(const optional<T>& x, const T& v) { return bool(x) ? *x < v : true; } template <class T> constexpr bool operator>(const T& v, const optional<T>& x) { return bool(x) ? v > *x : true; } template <class T> constexpr bool operator>(const optional<T>& x, const T& v) { return bool(x) ? *x > v : false; } template <class T> constexpr bool operator<(const T& v, const optional<T>& x) { return bool(x) ? v < *x : false; } template <class T> constexpr bool operator>=(const optional<T>& x, const T& v) { return bool(x) ? *x >= v : false; } template <class T> constexpr bool operator<=(const T& v, const optional<T>& x) { return bool(x) ? v <= *x : false; } template <class T> constexpr bool operator<=(const optional<T>& x, const T& v) { return bool(x) ? *x <= v : true; } template <class T> constexpr bool operator>=(const T& v, const optional<T>& x) { return bool(x) ? v >= *x : true; } template <class T> constexpr bool operator==(const optional<T&>& x, const T& v) { return bool(x) ? *x == v : false; } template <class T> constexpr bool operator==(const T& v, const optional<T&>& x) { return bool(x) ? v == *x : false; } template <class T> constexpr bool operator!=(const optional<T&>& x, const T& v) { return bool(x) ? *x != v : true; } template <class T> constexpr bool operator!=(const T& v, const optional<T&>& x) { return bool(x) ? v != *x : true; } template <class T> constexpr bool operator<(const optional<T&>& x, const T& v) { return bool(x) ? *x < v : true; } template <class T> constexpr bool operator>(const T& v, const optional<T&>& x) { return bool(x) ? v > *x : true; } template <class T> constexpr bool operator>(const optional<T&>& x, const T& v) { return bool(x) ? *x > v : false; } template <class T> constexpr bool operator<(const T& v, const optional<T&>& x) { return bool(x) ? v < *x : false; } template <class T> constexpr bool operator>=(const optional<T&>& x, const T& v) { return bool(x) ? *x >= v : false; } template <class T> constexpr bool operator<=(const T& v, const optional<T&>& x) { return bool(x) ? v <= *x : false; } template <class T> constexpr bool operator<=(const optional<T&>& x, const T& v) { return bool(x) ? *x <= v : true; } template <class T> constexpr bool operator>=(const T& v, const optional<T&>& x) { return bool(x) ? v >= *x : true; } template <class T> constexpr bool operator==(const optional<const T&>& x, const T& v) { return bool(x) ? *x == v : false; } template <class T> constexpr bool operator==(const T& v, const optional<const T&>& x) { return bool(x) ? v == *x : false; } template <class T> constexpr bool operator!=(const optional<const T&>& x, const T& v) { return bool(x) ? *x != v : true; } template <class T> constexpr bool operator!=(const T& v, const optional<const T&>& x) { return bool(x) ? v != *x : true; } template <class T> constexpr bool operator<(const optional<const T&>& x, const T& v) { return bool(x) ? *x < v : true; } template <class T> constexpr bool operator>(const T& v, const optional<const T&>& x) { return bool(x) ? v > *x : true; } template <class T> constexpr bool operator>(const optional<const T&>& x, const T& v) { return bool(x) ? *x > v : false; } template <class T> constexpr bool operator<(const T& v, const optional<const T&>& x) { return bool(x) ? v < *x : false; } template <class T> constexpr bool operator>=(const optional<const T&>& x, const T& v) { return bool(x) ? *x >= v : false; } template <class T> constexpr bool operator<=(const T& v, const optional<const T&>& x) { return bool(x) ? v <= *x : false; } template <class T> constexpr bool operator<=(const optional<const T&>& x, const T& v) { return bool(x) ? *x <= v : true; } template <class T> constexpr bool operator>=(const T& v, const optional<const T&>& x) { return bool(x) ? v >= *x : true; } template <class T> void swap(optional<T>& x, optional<T>& y) noexcept(noexcept(x.swap(y))) { x.swap(y); } template <class T> constexpr optional<typename ::std::decay<T>::type> make_optional(T&& v) { return optional<typename ::std::decay<T>::type>(constexpr_forward<T>(v)); } template <class X> constexpr optional<X&> make_optional(::std::reference_wrapper<X> v) { return optional<X&>(v.get()); } } // namespace namespace std { template <typename T> struct hash<sol::optional<T>> { typedef typename hash<T>::result_type result_type; typedef sol::optional<T> argument_type; constexpr result_type operator()(argument_type const& arg) const { return arg ? ::std::hash<T>{}(*arg) : result_type{}; } }; template <typename T> struct hash<sol::optional<T&>> { typedef typename hash<T>::result_type result_type; typedef sol::optional<T&> argument_type; constexpr result_type operator()(argument_type const& arg) const { return arg ? ::std::hash<T>{}(*arg) : result_type{}; } }; } # undef TR2_OPTIONAL_REQUIRES # undef TR2_OPTIONAL_ASSERTED_EXPRESSION # endif //___SOL_OPTIONAL_HPP___ // end of Optional/optional.hpp #endif // Boost vs. Better optional namespace sol { #if defined(SOL_USE_BOOST) template <typename T> using optional = boost::optional<T>; using nullopt_t = boost::none_t; const nullopt_t nullopt = boost::none; #endif // Boost vs. Better optional } // sol // end of sol/optional.hpp // beginning of sol/reference.hpp // beginning of sol/types.hpp // beginning of sol/compatibility.hpp // beginning of sol/compatibility/version.hpp #include <lua.hpp> #if defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) #ifndef SOL_CODECVT_SUPPORT #define SOL_CODECVT_SUPPORT 1 #endif // sol codecvt support #elif defined(__GNUC__) #if __GNUC__ >= 5 #ifndef SOL_CODECVT_SUPPORT #define SOL_CODECVT_SUPPORT 1 #endif // codecvt support #endif // g++ 5.x.x #else #endif // Windows/VC++ vs. g++ vs Others #ifdef LUAJIT_VERSION #ifndef SOL_LUAJIT #define SOL_LUAJIT #define SOL_LUAJIT_VERSION LUAJIT_VERSION_NUM #endif // sol luajit #endif // luajit #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 502 #define SOL_LUA_VERSION LUA_VERSION_NUM #elif defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 501 #define SOL_LUA_VERSION LUA_VERSION_NUM #elif !defined(LUA_VERSION_NUM) #define SOL_LUA_VERSION 500 #else #define SOL_LUA_VERSION 502 #endif // Lua Version 502, 501 || luajit, 500 #ifdef _MSC_VER #ifdef _DEBUG #ifndef NDEBUG #ifndef SOL_CHECK_ARGUMENTS #endif // Check Arguments #ifndef SOL_SAFE_USERTYPE #define SOL_SAFE_USERTYPE #endif // Safe Usertypes #endif // NDEBUG #endif // Debug #ifndef _CPPUNWIND #ifndef SOL_NO_EXCEPTIONS #define SOL_NO_EXCEPTIONS 1 #endif #endif // Automatic Exceptions #ifndef _CPPRTTI #ifndef SOL_NO_RTTI #define SOL_NO_RTTI 1 #endif #endif // Automatic RTTI #elif defined(__GNUC__) || defined(__clang__) #ifndef NDEBUG #ifndef __OPTIMIZE__ #ifndef SOL_CHECK_ARGUMENTS #endif // Check Arguments #ifndef SOL_SAFE_USERTYPE #define SOL_SAFE_USERTYPE #endif // Safe Usertypes #endif // g++ optimizer flag #endif // Not Debug #ifndef __EXCEPTIONS #ifndef SOL_NO_EXCEPTIONS #define SOL_NO_EXCEPTIONS 1 #endif #endif // No Exceptions #ifndef __GXX_RTTI #ifndef SOL_NO_RTII #define SOL_NO_RTTI 1 #endif #endif // No RTTI #endif // vc++ || clang++/g++ #ifndef SOL_SAFE_USERTYPE #ifdef SOL_CHECK_ARGUMENTS #define SOL_SAFE_USERTYPE #endif // Turn on Safety for all #endif // Safe Usertypes // end of sol/compatibility/version.hpp #ifndef SOL_NO_COMPAT #ifdef __cplusplus extern "C" { #endif // beginning of sol/compatibility/5.1.0.h #ifndef SOL_5_1_0_H #define SOL_5_1_0_H #if SOL_LUA_VERSION == 501 /* Lua 5.1 */ #include <stddef.h> #include <string.h> #include <stdio.h> /* LuaJIT doesn't define these unofficial macros ... */ #if !defined(LUAI_INT32) #include <limits.h> #if INT_MAX-20 < 32760 #define LUAI_INT32 long #define LUAI_UINT32 unsigned long #elif INT_MAX > 2147483640L #define LUAI_INT32 int #define LUAI_UINT32 unsigned int #else #error "could not detect suitable lua_Unsigned datatype" #endif #endif /* LuaJIT does not have the updated error codes for thread status/function returns */ #ifndef LUA_ERRGCMM #define LUA_ERRGCMM (LUA_ERRERR + 1) #endif // LUA_ERRGCMM /* LuaJIT does not support continuation contexts / return error codes? */ #ifndef LUA_KCONTEXT #define LUA_KCONTEXT std::ptrdiff_t typedef LUA_KCONTEXT lua_KContext; typedef int(*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); #endif // LUA_KCONTEXT #define LUA_OPADD 0 #define LUA_OPSUB 1 #define LUA_OPMUL 2 #define LUA_OPDIV 3 #define LUA_OPMOD 4 #define LUA_OPPOW 5 #define LUA_OPUNM 6 #define LUA_OPEQ 0 #define LUA_OPLT 1 #define LUA_OPLE 2 typedef LUAI_UINT32 lua_Unsigned; typedef struct luaL_Buffer_52 { luaL_Buffer b; /* make incorrect code crash! */ char *ptr; size_t nelems; size_t capacity; lua_State *L2; } luaL_Buffer_52; #define luaL_Buffer luaL_Buffer_52 #define lua_tounsigned(L, i) lua_tounsignedx(L, i, NULL) #define lua_rawlen(L, i) lua_objlen(L, i) inline void lua_callk(lua_State *L, int nargs, int nresults, lua_KContext, lua_KFunction) { // should probably warn the user of Lua 5.1 that continuation isn't supported... lua_call(L, nargs, nresults); } inline int lua_pcallk(lua_State *L, int nargs, int nresults, int errfunc, lua_KContext, lua_KFunction) { // should probably warn the user of Lua 5.1 that continuation isn't supported... return lua_pcall(L, nargs, nresults, errfunc); } void lua_arith(lua_State *L, int op); int lua_compare(lua_State *L, int idx1, int idx2, int op); void lua_pushunsigned(lua_State *L, lua_Unsigned n); lua_Unsigned luaL_checkunsigned(lua_State *L, int i); lua_Unsigned lua_tounsignedx(lua_State *L, int i, int *isnum); lua_Unsigned luaL_optunsigned(lua_State *L, int i, lua_Unsigned def); lua_Integer lua_tointegerx(lua_State *L, int i, int *isnum); void lua_len(lua_State *L, int i); int luaL_len(lua_State *L, int i); const char *luaL_tolstring(lua_State *L, int idx, size_t *len); void luaL_requiref(lua_State *L, char const* modname, lua_CFunction openf, int glb); #define luaL_buffinit luaL_buffinit_52 void luaL_buffinit(lua_State *L, luaL_Buffer_52 *B); #define luaL_prepbuffsize luaL_prepbuffsize_52 char *luaL_prepbuffsize(luaL_Buffer_52 *B, size_t s); #define luaL_addlstring luaL_addlstring_52 void luaL_addlstring(luaL_Buffer_52 *B, const char *s, size_t l); #define luaL_addvalue luaL_addvalue_52 void luaL_addvalue(luaL_Buffer_52 *B); #define luaL_pushresult luaL_pushresult_52 void luaL_pushresult(luaL_Buffer_52 *B); #undef luaL_buffinitsize #define luaL_buffinitsize(L, B, s) \ (luaL_buffinit(L, B), luaL_prepbuffsize(B, s)) #undef luaL_prepbuffer #define luaL_prepbuffer(B) \ luaL_prepbuffsize(B, LUAL_BUFFERSIZE) #undef luaL_addchar #define luaL_addchar(B, c) \ ((void)((B)->nelems < (B)->capacity || luaL_prepbuffsize(B, 1)), \ ((B)->ptr[(B)->nelems++] = (c))) #undef luaL_addsize #define luaL_addsize(B, s) \ ((B)->nelems += (s)) #undef luaL_addstring #define luaL_addstring(B, s) \ luaL_addlstring(B, s, strlen(s)) #undef luaL_pushresultsize #define luaL_pushresultsize(B, s) \ (luaL_addsize(B, s), luaL_pushresult(B)) typedef struct kepler_lua_compat_get_string_view { const char *s; size_t size; } kepler_lua_compat_get_string_view; inline const char* kepler_lua_compat_get_string(lua_State* L, void* ud, size_t* size) { kepler_lua_compat_get_string_view* ls = (kepler_lua_compat_get_string_view*) ud; (void)L; if (ls->size == 0) return NULL; *size = ls->size; ls->size = 0; return ls->s; } #if !defined(SOL_LUAJIT) || ((SOL_LUAJIT_VERSION - 020100) <= 0) inline int luaL_loadbufferx(lua_State* L, const char* buff, size_t size, const char* name, const char*) { kepler_lua_compat_get_string_view ls; ls.s = buff; ls.size = size; return lua_load(L, kepler_lua_compat_get_string, &ls, name/*, mode*/); } #endif // LuaJIT 2.1.x beta and beyond #endif /* Lua 5.1 */ #endif // SOL_5_1_0_H// end of sol/compatibility/5.1.0.h // beginning of sol/compatibility/5.0.0.h #ifndef SOL_5_0_0_H #define SOL_5_0_0_H #if SOL_LUA_VERSION < 501 /* Lua 5.0 */ #define LUA_QL(x) "'" x "'" #define LUA_QS LUA_QL("%s") #define luaL_Reg luaL_reg #define luaL_opt(L, f, n, d) \ (lua_isnoneornil(L, n) ? (d) : f(L, n)) #define luaL_addchar(B,c) \ ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \ (*(B)->p++ = (char)(c))) #endif // Lua 5.0 #endif // SOL_5_0_0_H // end of sol/compatibility/5.0.0.h // beginning of sol/compatibility/5.x.x.h #ifndef SOL_5_X_X_H #define SOL_5_X_X_H #if SOL_LUA_VERSION < 502 #define LUA_RIDX_GLOBALS LUA_GLOBALSINDEX #define LUA_OK 0 #define lua_pushglobaltable(L) \ lua_pushvalue(L, LUA_GLOBALSINDEX) #define luaL_newlib(L, l) \ (lua_newtable((L)),luaL_setfuncs((L), (l), 0)) void luaL_checkversion(lua_State *L); int lua_absindex(lua_State *L, int i); void lua_copy(lua_State *L, int from, int to); void lua_rawgetp(lua_State *L, int i, const void *p); void lua_rawsetp(lua_State *L, int i, const void *p); void *luaL_testudata(lua_State *L, int i, const char *tname); lua_Number lua_tonumberx(lua_State *L, int i, int *isnum); void lua_getuservalue(lua_State *L, int i); void lua_setuservalue(lua_State *L, int i); void luaL_setfuncs(lua_State *L, const luaL_Reg *l, int nup); void luaL_setmetatable(lua_State *L, const char *tname); int luaL_getsubtable(lua_State *L, int i, const char *name); void luaL_traceback(lua_State *L, lua_State *L1, const char *msg, int level); int luaL_fileresult(lua_State *L, int stat, const char *fname); #endif // Lua 5.1 and below #endif // SOL_5_X_X_H // end of sol/compatibility/5.x.x.h // beginning of sol/compatibility/5.x.x.inl #ifndef SOL_5_X_X_INL #define SOL_5_X_X_INL // beginning of sol/compatibility/5.2.0.h #ifndef SOL_5_2_0_H #define SOL_5_2_0_H #if SOL_LUA_VERSION < 503 inline int lua_isinteger(lua_State* L, int idx) { if (lua_type(L, idx) != LUA_TNUMBER) return 0; // This is a very slipshod way to do the testing // but lua_totingerx doesn't play ball nicely // on older versions... lua_Number n = lua_tonumber(L, idx); lua_Integer i = lua_tointeger(L, idx); if (i != n) return 0; // it's DEFINITELY an integer return 1; } #endif // SOL_LUA_VERSION == 502 #endif // SOL_5_2_0_H // end of sol/compatibility/5.2.0.h #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM == 501 #include <errno.h> #define PACKAGE_KEY "_sol.package" inline int lua_absindex(lua_State *L, int i) { if (i < 0 && i > LUA_REGISTRYINDEX) i += lua_gettop(L) + 1; return i; } inline void lua_copy(lua_State *L, int from, int to) { int abs_to = lua_absindex(L, to); luaL_checkstack(L, 1, "not enough stack slots"); lua_pushvalue(L, from); lua_replace(L, abs_to); } inline void lua_rawgetp(lua_State *L, int i, const void *p) { int abs_i = lua_absindex(L, i); lua_pushlightuserdata(L, (void*)p); lua_rawget(L, abs_i); } inline void lua_rawsetp(lua_State *L, int i, const void *p) { int abs_i = lua_absindex(L, i); luaL_checkstack(L, 1, "not enough stack slots"); lua_pushlightuserdata(L, (void*)p); lua_insert(L, -2); lua_rawset(L, abs_i); } inline void *luaL_testudata(lua_State *L, int i, const char *tname) { void *p = lua_touserdata(L, i); luaL_checkstack(L, 2, "not enough stack slots"); if (p == NULL || !lua_getmetatable(L, i)) return NULL; else { int res = 0; luaL_getmetatable(L, tname); res = lua_rawequal(L, -1, -2); lua_pop(L, 2); if (!res) p = NULL; } return p; } inline lua_Number lua_tonumberx(lua_State *L, int i, int *isnum) { lua_Number n = lua_tonumber(L, i); if (isnum != NULL) { *isnum = (n != 0 || lua_isnumber(L, i)); } return n; } inline static void push_package_table(lua_State *L) { lua_pushliteral(L, PACKAGE_KEY); lua_rawget(L, LUA_REGISTRYINDEX); if (!lua_istable(L, -1)) { lua_pop(L, 1); /* try to get package table from globals */ lua_pushliteral(L, "package"); lua_rawget(L, LUA_GLOBALSINDEX); if (lua_istable(L, -1)) { lua_pushliteral(L, PACKAGE_KEY); lua_pushvalue(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); } } } inline void lua_getuservalue(lua_State *L, int i) { luaL_checktype(L, i, LUA_TUSERDATA); luaL_checkstack(L, 2, "not enough stack slots"); lua_getfenv(L, i); lua_pushvalue(L, LUA_GLOBALSINDEX); if (lua_rawequal(L, -1, -2)) { lua_pop(L, 1); lua_pushnil(L); lua_replace(L, -2); } else { lua_pop(L, 1); push_package_table(L); if (lua_rawequal(L, -1, -2)) { lua_pop(L, 1); lua_pushnil(L); lua_replace(L, -2); } else lua_pop(L, 1); } } inline void lua_setuservalue(lua_State *L, int i) { luaL_checktype(L, i, LUA_TUSERDATA); if (lua_isnil(L, -1)) { luaL_checkstack(L, 1, "not enough stack slots"); lua_pushvalue(L, LUA_GLOBALSINDEX); lua_replace(L, -2); } lua_setfenv(L, i); } /* ** Adapted from Lua 5.2.0 */ inline void luaL_setfuncs(lua_State *L, const luaL_Reg *l, int nup) { luaL_checkstack(L, nup + 1, "too many upvalues"); for (; l->name != NULL; l++) { /* fill the table with given functions */ int i; lua_pushstring(L, l->name); for (i = 0; i < nup; i++) /* copy upvalues to the top */ lua_pushvalue(L, -(nup + 1)); lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ lua_settable(L, -(nup + 3)); /* table must be below the upvalues, the name and the closure */ } lua_pop(L, nup); /* remove upvalues */ } inline void luaL_setmetatable(lua_State *L, const char *tname) { luaL_checkstack(L, 1, "not enough stack slots"); luaL_getmetatable(L, tname); lua_setmetatable(L, -2); } inline int luaL_getsubtable(lua_State *L, int i, const char *name) { int abs_i = lua_absindex(L, i); luaL_checkstack(L, 3, "not enough stack slots"); lua_pushstring(L, name); lua_gettable(L, abs_i); if (lua_istable(L, -1)) return 1; lua_pop(L, 1); lua_newtable(L); lua_pushstring(L, name); lua_pushvalue(L, -2); lua_settable(L, abs_i); return 0; } #ifndef SOL_LUAJIT inline static int countlevels(lua_State *L) { lua_Debug ar; int li = 1, le = 1; /* find an upper bound */ while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } /* do a binary search */ while (li < le) { int m = (li + le) / 2; if (lua_getstack(L, m, &ar)) li = m + 1; else le = m; } return le - 1; } inline static int findfield(lua_State *L, int objidx, int level) { if (level == 0 || !lua_istable(L, -1)) return 0; /* not found */ lua_pushnil(L); /* start 'next' loop */ while (lua_next(L, -2)) { /* for each pair in table */ if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ if (lua_rawequal(L, objidx, -1)) { /* found object? */ lua_pop(L, 1); /* remove value (but keep name) */ return 1; } else if (findfield(L, objidx, level - 1)) { /* try recursively */ lua_remove(L, -2); /* remove table (but keep name) */ lua_pushliteral(L, "."); lua_insert(L, -2); /* place '.' between the two names */ lua_concat(L, 3); return 1; } } lua_pop(L, 1); /* remove value */ } return 0; /* not found */ } inline static int pushglobalfuncname(lua_State *L, lua_Debug *ar) { int top = lua_gettop(L); lua_getinfo(L, "f", ar); /* push function */ lua_pushvalue(L, LUA_GLOBALSINDEX); if (findfield(L, top + 1, 2)) { lua_copy(L, -1, top + 1); /* move name to proper place */ lua_pop(L, 2); /* remove pushed values */ return 1; } else { lua_settop(L, top); /* remove function and global table */ return 0; } } inline static void pushfuncname(lua_State *L, lua_Debug *ar) { if (*ar->namewhat != '\0') /* is there a name? */ lua_pushfstring(L, "function " LUA_QS, ar->name); else if (*ar->what == 'm') /* main? */ lua_pushliteral(L, "main chunk"); else if (*ar->what == 'C') { if (pushglobalfuncname(L, ar)) { lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1)); lua_remove(L, -2); /* remove name */ } else lua_pushliteral(L, "?"); } else lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); } #define LEVELS1 12 /* size of the first part of the stack */ #define LEVELS2 10 /* size of the second part of the stack */ inline void luaL_traceback(lua_State *L, lua_State *L1, const char *msg, int level) { lua_Debug ar; int top = lua_gettop(L); int numlevels = countlevels(L1); int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0; if (msg) lua_pushfstring(L, "%s\n", msg); lua_pushliteral(L, "stack traceback:"); while (lua_getstack(L1, level++, &ar)) { if (level == mark) { /* too many levels? */ lua_pushliteral(L, "\n\t..."); /* add a '...' */ level = numlevels - LEVELS2; /* and skip to last ones */ } else { lua_getinfo(L1, "Slnt", &ar); lua_pushfstring(L, "\n\t%s:", ar.short_src); if (ar.currentline > 0) lua_pushfstring(L, "%d:", ar.currentline); lua_pushliteral(L, " in "); pushfuncname(L, &ar); lua_concat(L, lua_gettop(L) - top); } } lua_concat(L, lua_gettop(L) - top); } #endif inline const lua_Number *lua_version(lua_State *L) { static const lua_Number version = LUA_VERSION_NUM; if (L == NULL) return &version; // TODO: wonky hacks to get at the inside of the incomplete type lua_State? //else return L->l_G->version; else return &version; } inline static void luaL_checkversion_(lua_State *L, lua_Number ver) { const lua_Number* v = lua_version(L); if (v != lua_version(NULL)) luaL_error(L, "multiple Lua VMs detected"); else if (*v != ver) luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", ver, *v); /* check conversions number -> integer types */ lua_pushnumber(L, -(lua_Number)0x1234); if (lua_tointeger(L, -1) != -0x1234 || lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234) luaL_error(L, "bad conversion number->int;" " must recompile Lua with proper settings"); lua_pop(L, 1); } inline void luaL_checkversion(lua_State* L) { luaL_checkversion_(L, LUA_VERSION_NUM); } #ifndef SOL_LUAJIT inline int luaL_fileresult(lua_State *L, int stat, const char *fname) { int en = errno; /* calls to Lua API may change this value */ if (stat) { lua_pushboolean(L, 1); return 1; } else { char buf[1024]; #ifdef __GLIBC__ strerror_r(en, buf, 1024); #else strerror_s(buf, 1024, en); #endif lua_pushnil(L); if (fname) lua_pushfstring(L, "%s: %s", fname, buf); else lua_pushstring(L, buf); lua_pushnumber(L, (lua_Number)en); return 3; } } #endif // luajit #endif // Lua 5.0 or Lua 5.1 #if SOL_LUA_VERSION == 501 typedef LUAI_INT32 LUA_INT32; /********************************************************************/ /* extract of 5.2's luaconf.h */ /* detects proper defines for faster unsigned<->number conversion */ /* see copyright notice at the end of this file */ /********************************************************************/ #if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE) #define LUA_WIN /* enable goodies for regular Windows platforms */ #endif #if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) /* { */ /* Microsoft compiler on a Pentium (32 bit) ? */ #if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86) /* { */ #define LUA_MSASMTRICK #define LUA_IEEEENDIAN 0 #define LUA_NANTRICK /* pentium 32 bits? */ #elif defined(__i386__) || defined(__i386) || defined(__X86__) /* }{ */ #define LUA_IEEE754TRICK #define LUA_IEEELL #define LUA_IEEEENDIAN 0 #define LUA_NANTRICK /* pentium 64 bits? */ #elif defined(__x86_64) /* }{ */ #define LUA_IEEE754TRICK #define LUA_IEEEENDIAN 0 #elif defined(__POWERPC__) || defined(__ppc__) /* }{ */ #define LUA_IEEE754TRICK #define LUA_IEEEENDIAN 1 #else /* }{ */ /* assume IEEE754 and a 32-bit integer type */ #define LUA_IEEE754TRICK #endif /* } */ #endif /* } */ /********************************************************************/ /* extract of 5.2's llimits.h */ /* gives us lua_number2unsigned and lua_unsigned2number */ /* see copyright notice just below this one here */ /********************************************************************/ /********************************************************************* * This file contains parts of Lua 5.2's source code: * * Copyright (C) 1994-2013 Lua.org, PUC-Rio. * * 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. *********************************************************************/ #if defined(MS_ASMTRICK) || defined(LUA_MSASMTRICK) /* { */ /* trick with Microsoft assembler for X86 */ #define lua_number2unsigned(i,n) \ {__int64 l; __asm {__asm fld n __asm fistp l} i = (unsigned int)l;} #elif defined(LUA_IEEE754TRICK) /* }{ */ /* the next trick should work on any machine using IEEE754 with a 32-bit int type */ union compat52_luai_Cast { double l_d; LUA_INT32 l_p[2]; }; #if !defined(LUA_IEEEENDIAN) /* { */ #define LUAI_EXTRAIEEE \ static const union compat52_luai_Cast ieeeendian = {-(33.0 + 6755399441055744.0)}; #define LUA_IEEEENDIANLOC (ieeeendian.l_p[1] == 33) #else #define LUA_IEEEENDIANLOC LUA_IEEEENDIAN #define LUAI_EXTRAIEEE /* empty */ #endif /* } */ #define lua_number2int32(i,n,t) \ { LUAI_EXTRAIEEE \ volatile union compat52_luai_Cast u; u.l_d = (n) + 6755399441055744.0; \ (i) = (t)u.l_p[LUA_IEEEENDIANLOC]; } #define lua_number2unsigned(i,n) lua_number2int32(i, n, lua_Unsigned) #endif /* } */ /* the following definitions always work, but may be slow */ #if !defined(lua_number2unsigned) /* { */ /* the following definition assures proper modulo behavior */ #if defined(LUA_NUMBER_DOUBLE) || defined(LUA_NUMBER_FLOAT) #include <math.h> #define SUPUNSIGNED ((lua_Number)(~(lua_Unsigned)0) + 1) #define lua_number2unsigned(i,n) \ ((i)=(lua_Unsigned)((n) - floor((n)/SUPUNSIGNED)*SUPUNSIGNED)) #else #define lua_number2unsigned(i,n) ((i)=(lua_Unsigned)(n)) #endif #endif /* } */ #if !defined(lua_unsigned2number) /* on several machines, coercion from unsigned to double is slow, so it may be worth to avoid */ #define lua_unsigned2number(u) \ (((u) <= (lua_Unsigned)INT_MAX) ? (lua_Number)(int)(u) : (lua_Number)(u)) #endif /********************************************************************/ inline static void compat52_call_lua(lua_State *L, char const code[], size_t len, int nargs, int nret) { lua_rawgetp(L, LUA_REGISTRYINDEX, (void*)code); if (lua_type(L, -1) != LUA_TFUNCTION) { lua_pop(L, 1); if (luaL_loadbuffer(L, code, len, "=none")) lua_error(L); lua_pushvalue(L, -1); lua_rawsetp(L, LUA_REGISTRYINDEX, (void*)code); } lua_insert(L, -nargs - 1); lua_call(L, nargs, nret); } static const char compat52_arith_code[] = { "local op,a,b=...\n" "if op==0 then return a+b\n" "elseif op==1 then return a-b\n" "elseif op==2 then return a*b\n" "elseif op==3 then return a/b\n" "elseif op==4 then return a%b\n" "elseif op==5 then return a^b\n" "elseif op==6 then return -a\n" "end\n" }; inline void lua_arith(lua_State *L, int op) { if (op < LUA_OPADD || op > LUA_OPUNM) luaL_error(L, "invalid 'op' argument for lua_arith"); luaL_checkstack(L, 5, "not enough stack slots"); if (op == LUA_OPUNM) lua_pushvalue(L, -1); lua_pushnumber(L, op); lua_insert(L, -3); compat52_call_lua(L, compat52_arith_code, sizeof(compat52_arith_code) - 1, 3, 1); } static const char compat52_compare_code[] = { "local a,b=...\n" "return a<=b\n" }; inline int lua_compare(lua_State *L, int idx1, int idx2, int op) { int result = 0; switch (op) { case LUA_OPEQ: return lua_equal(L, idx1, idx2); case LUA_OPLT: return lua_lessthan(L, idx1, idx2); case LUA_OPLE: luaL_checkstack(L, 5, "not enough stack slots"); idx1 = lua_absindex(L, idx1); idx2 = lua_absindex(L, idx2); lua_pushvalue(L, idx1); lua_pushvalue(L, idx2); compat52_call_lua(L, compat52_compare_code, sizeof(compat52_compare_code) - 1, 2, 1); result = lua_toboolean(L, -1); lua_pop(L, 1); return result; default: luaL_error(L, "invalid 'op' argument for lua_compare"); } return 0; } inline void lua_pushunsigned(lua_State *L, lua_Unsigned n) { lua_pushnumber(L, lua_unsigned2number(n)); } inline lua_Unsigned luaL_checkunsigned(lua_State *L, int i) { lua_Unsigned result; lua_Number n = lua_tonumber(L, i); if (n == 0 && !lua_isnumber(L, i)) luaL_checktype(L, i, LUA_TNUMBER); lua_number2unsigned(result, n); return result; } inline lua_Unsigned lua_tounsignedx(lua_State *L, int i, int *isnum) { lua_Unsigned result; lua_Number n = lua_tonumberx(L, i, isnum); lua_number2unsigned(result, n); return result; } inline lua_Unsigned luaL_optunsigned(lua_State *L, int i, lua_Unsigned def) { return luaL_opt(L, luaL_checkunsigned, i, def); } inline lua_Integer lua_tointegerx(lua_State *L, int i, int *isnum) { lua_Integer n = lua_tointeger(L, i); if (isnum != NULL) { *isnum = (n != 0 || lua_isnumber(L, i)); } return n; } inline void lua_len(lua_State *L, int i) { switch (lua_type(L, i)) { case LUA_TSTRING: /* fall through */ case LUA_TTABLE: if (!luaL_callmeta(L, i, "__len")) lua_pushnumber(L, (int)lua_objlen(L, i)); break; case LUA_TUSERDATA: if (luaL_callmeta(L, i, "__len")) break; /* maybe fall through */ default: luaL_error(L, "attempt to get length of a %s value", lua_typename(L, lua_type(L, i))); } } inline int luaL_len(lua_State *L, int i) { int res = 0, isnum = 0; luaL_checkstack(L, 1, "not enough stack slots"); lua_len(L, i); res = (int)lua_tointegerx(L, -1, &isnum); lua_pop(L, 1); if (!isnum) luaL_error(L, "object length is not a number"); return res; } inline const char *luaL_tolstring(lua_State *L, int idx, size_t *len) { if (!luaL_callmeta(L, idx, "__tostring")) { int t = lua_type(L, idx); switch (t) { case LUA_TNIL: lua_pushliteral(L, "nil"); break; case LUA_TSTRING: case LUA_TNUMBER: lua_pushvalue(L, idx); break; case LUA_TBOOLEAN: if (lua_toboolean(L, idx)) lua_pushliteral(L, "true"); else lua_pushliteral(L, "false"); break; default: lua_pushfstring(L, "%s: %p", lua_typename(L, t), lua_topointer(L, idx)); break; } } return lua_tolstring(L, -1, len); } inline void luaL_requiref(lua_State *L, char const* modname, lua_CFunction openf, int glb) { luaL_checkstack(L, 3, "not enough stack slots"); lua_pushcfunction(L, openf); lua_pushstring(L, modname); lua_call(L, 1, 1); lua_getglobal(L, "package"); if (lua_istable(L, -1) == 0) { lua_pop(L, 1); lua_createtable(L, 0, 16); lua_setglobal(L, "package"); lua_getglobal(L, "package"); } lua_getfield(L, -1, "loaded"); if (lua_istable(L, -1) == 0) { lua_pop(L, 1); lua_createtable(L, 0, 1); lua_setfield(L, -2, "loaded"); lua_getfield(L, -1, "loaded"); } lua_replace(L, -2); lua_pushvalue(L, -2); lua_setfield(L, -2, modname); lua_pop(L, 1); if (glb) { lua_pushvalue(L, -1); lua_setglobal(L, modname); } } inline void luaL_buffinit(lua_State *L, luaL_Buffer_52 *B) { /* make it crash if used via pointer to a 5.1-style luaL_Buffer */ B->b.p = NULL; B->b.L = NULL; B->b.lvl = 0; /* reuse the buffer from the 5.1-style luaL_Buffer though! */ B->ptr = B->b.buffer; B->capacity = LUAL_BUFFERSIZE; B->nelems = 0; B->L2 = L; } inline char *luaL_prepbuffsize(luaL_Buffer_52 *B, size_t s) { if (B->capacity - B->nelems < s) { /* needs to grow */ char* newptr = NULL; size_t newcap = B->capacity * 2; if (newcap - B->nelems < s) newcap = B->nelems + s; if (newcap < B->capacity) /* overflow */ luaL_error(B->L2, "buffer too large"); newptr = (char*)lua_newuserdata(B->L2, newcap); memcpy(newptr, B->ptr, B->nelems); if (B->ptr != B->b.buffer) lua_replace(B->L2, -2); /* remove old buffer */ B->ptr = newptr; B->capacity = newcap; } return B->ptr + B->nelems; } inline void luaL_addlstring(luaL_Buffer_52 *B, const char *s, size_t l) { memcpy(luaL_prepbuffsize(B, l), s, l); luaL_addsize(B, l); } inline void luaL_addvalue(luaL_Buffer_52 *B) { size_t len = 0; const char *s = lua_tolstring(B->L2, -1, &len); if (!s) luaL_error(B->L2, "cannot convert value to string"); if (B->ptr != B->b.buffer) lua_insert(B->L2, -2); /* userdata buffer must be at stack top */ luaL_addlstring(B, s, len); lua_remove(B->L2, B->ptr != B->b.buffer ? -2 : -1); } inline void luaL_pushresult(luaL_Buffer_52 *B) { lua_pushlstring(B->L2, B->ptr, B->nelems); if (B->ptr != B->b.buffer) lua_replace(B->L2, -2); /* remove userdata buffer */ } #endif /* SOL_LUA_VERSION == 501 */ #endif // SOL_5_X_X_INL // end of sol/compatibility/5.x.x.inl #ifdef __cplusplus } #endif #endif // SOL_NO_COMPAT // end of sol/compatibility.hpp // beginning of sol/string_shim.hpp #pragma once namespace sol { namespace string_detail { struct string_shim { std::size_t s; const char* p; string_shim(const std::string& r) : string_shim(r.data(), r.size()) {} string_shim(const char* p) : string_shim(p, std::char_traits<char>::length(p)) {} string_shim(const char* p, std::size_t s) : s(s), p(p) {} static int compare(const char* lhs_p, std::size_t lhs_sz, const char* rhs_p, std::size_t rhs_sz) { int result = std::char_traits<char>::compare(lhs_p, rhs_p, lhs_sz < rhs_sz ? lhs_sz : rhs_sz); if (result != 0) return result; if (lhs_sz < rhs_sz) return -1; if (lhs_sz > rhs_sz) return 1; return 0; } const char* c_str() const { return p; } const char* data() const { return p; } std::size_t size() const { return s; } bool operator==(const string_shim& r) const { return compare(p, s, r.data(), r.size()) == 0; } bool operator==(const char* r) const { return compare(r, std::char_traits<char>::length(r), p, s) == 0; } bool operator==(const std::string& r) const { return compare(r.data(), r.size(), p, s) == 0; } bool operator!=(const string_shim& r) const { return !(*this == r); } bool operator!=(const char* r) const { return !(*this == r); } bool operator!=(const std::string& r) const { return !(*this == r); } }; } }// end of sol/string_shim.hpp #include <array> namespace sol { namespace detail { #ifdef SOL_NO_EXCEPTIONS template <lua_CFunction f> int static_trampoline(lua_State* L) { return f(L); } template <typename Fx, typename... Args> int trampoline(lua_State* L, Fx&& f, Args&&... args) { return f(L, std::forward<Args>(args)...); } inline int c_trampoline(lua_State* L, lua_CFunction f) { return trampoline(L, f); } #else template <lua_CFunction f> int static_trampoline(lua_State* L) { try { return f(L); } catch (const char *s) { lua_pushstring(L, s); } catch (const std::exception& e) { lua_pushstring(L, e.what()); } catch (...) { lua_pushstring(L, "caught (...) exception"); } return lua_error(L); } template <typename Fx, typename... Args> int trampoline(lua_State* L, Fx&& f, Args&&... args) { try { return f(L, std::forward<Args>(args)...); } catch (const char *s) { lua_pushstring(L, s); } catch (const std::exception& e) { lua_pushstring(L, e.what()); } catch (...) { lua_pushstring(L, "caught (...) exception"); } return lua_error(L); } inline int c_trampoline(lua_State* L, lua_CFunction f) { return trampoline(L, f); } #endif // Exceptions vs. No Exceptions template <typename T> struct unique_usertype {}; template <typename T> struct implicit_wrapper { T& item; implicit_wrapper(T* item) : item(*item) {} implicit_wrapper(T& item) : item(item) {} operator T& () { return item; } operator T* () { return std::addressof(item); } }; } // detail struct nil_t {}; const nil_t nil{}; inline bool operator==(nil_t, nil_t) { return true; } inline bool operator!=(nil_t, nil_t) { return false; } struct metatable_key_t {}; const metatable_key_t metatable_key = {}; struct no_metatable_t {}; const no_metatable_t no_metatable = {}; typedef std::remove_pointer_t<lua_CFunction> lua_r_CFunction; template <typename T> struct unique_usertype_traits { typedef T type; typedef T actual_type; static const bool value = false; template <typename U> static bool is_null(U&&) { return false; } template <typename U> static auto get(U&& value) { return std::addressof(detail::deref(value)); } }; template <typename T> struct unique_usertype_traits<std::shared_ptr<T>> { typedef T type; typedef std::shared_ptr<T> actual_type; static const bool value = true; static bool is_null(const actual_type& p) { return p == nullptr; } static type* get(const actual_type& p) { return p.get(); } }; template <typename T, typename D> struct unique_usertype_traits<std::unique_ptr<T, D>> { typedef T type; typedef std::unique_ptr<T, D> actual_type; static const bool value = true; static bool is_null(const actual_type& p) { return p == nullptr; } static type* get(const actual_type& p) { return p.get(); } }; template <typename T> struct non_null {}; template <typename... Args> struct function_sig {}; struct upvalue_index { int index; upvalue_index(int idx) : index(lua_upvalueindex(idx)) {} operator int() const { return index; } }; struct raw_index { int index; raw_index(int i) : index(i) {} operator int() const { return index; } }; struct absolute_index { int index; absolute_index(lua_State* L, int idx) : index(lua_absindex(L, idx)) {} operator int() const { return index; } }; struct lightuserdata_value { void* value; lightuserdata_value(void* data) : value(data) {} operator void*() const { return value; } }; struct userdata_value { void* value; userdata_value(void* data) : value(data) {} operator void*() const { return value; } }; template <typename L> struct light { L* value; light(L& x) : value(std::addressof(x)) {} light(L* x) : value(x) {} light(void* x) : value(static_cast<L*>(x)) {} operator L* () const { return value; } operator L& () const { return *value; } }; template <typename T> auto make_light(T& l) { typedef meta::unwrapped_t<std::remove_pointer_t<std::remove_pointer_t<T>>> L; return light<L>(l); } template <typename U> struct user { U value; user(U x) : value(std::move(x)) {} operator U* () { return std::addressof(value); } operator U& () { return value; } operator const U& () const { return value; } }; template <typename T> auto make_user(T&& u) { typedef meta::unwrapped_t<meta::unqualified_t<T>> U; return user<U>(std::forward<T>(u)); } template <typename T> struct metatable_registry_key { T key; metatable_registry_key(T key) : key(std::forward<T>(key)) {} }; template <typename T> auto meta_registry_key(T&& key) { typedef meta::unqualified_t<T> K; return metatable_registry_key<K>(std::forward<T>(key)); } template <typename... Upvalues> struct closure { lua_CFunction c_function; std::tuple<Upvalues...> upvalues; closure(lua_CFunction f, Upvalues... upvalues) : c_function(f), upvalues(std::forward<Upvalues>(upvalues)...) {} }; template <> struct closure<> { lua_CFunction c_function; int upvalues; closure(lua_CFunction f, int upvalues = 0) : c_function(f), upvalues(upvalues) {} }; typedef closure<> c_closure; template <typename... Args> closure<Args...> make_closure(lua_CFunction f, Args&&... args) { return closure<Args...>(f, std::forward<Args>(args)...); } template <typename Sig, typename... Ps> struct function_arguments { std::tuple<Ps...> arguments; template <typename Arg, typename... Args, meta::disable<std::is_same<meta::unqualified_t<Arg>, function_arguments>> = meta::enabler> function_arguments(Arg&& arg, Args&&... args) : arguments(std::forward<Arg>(arg), std::forward<Args>(args)...) {} }; template <typename Sig = function_sig<>, typename... Args> auto as_function(Args&&... args) { return function_arguments<Sig, std::decay_t<Args>...>(std::forward<Args>(args)...); } template <typename Sig = function_sig<>, typename... Args> auto as_function_reference(Args&&... args) { return function_arguments<Sig, Args...>(std::forward<Args>(args)...); } template <typename T> struct as_table_t { T source; template <typename... Args> as_table_t(Args&&... args) : source(std::forward<Args>(args)...) {} operator std::add_lvalue_reference_t<T> () { return source; } }; template <typename T> as_table_t<T> as_table(T&& container) { return as_table_t<T>(std::forward<T>(container)); } struct this_state { lua_State* L; operator lua_State* () const { return L; } lua_State* operator-> () const { return L; } }; enum class call_syntax { dot = 0, colon = 1 }; enum class call_status : int { ok = LUA_OK, yielded = LUA_YIELD, runtime = LUA_ERRRUN, memory = LUA_ERRMEM, handler = LUA_ERRERR, gc = LUA_ERRGCMM }; enum class thread_status : int { ok = LUA_OK, yielded = LUA_YIELD, runtime = LUA_ERRRUN, memory = LUA_ERRMEM, gc = LUA_ERRGCMM, handler = LUA_ERRERR, dead, }; enum class load_status : int { ok = LUA_OK, syntax = LUA_ERRSYNTAX, memory = LUA_ERRMEM, gc = LUA_ERRGCMM, file = LUA_ERRFILE, }; enum class type : int { none = LUA_TNONE, nil = LUA_TNIL, string = LUA_TSTRING, number = LUA_TNUMBER, thread = LUA_TTHREAD, boolean = LUA_TBOOLEAN, function = LUA_TFUNCTION, userdata = LUA_TUSERDATA, lightuserdata = LUA_TLIGHTUSERDATA, table = LUA_TTABLE, poly = none | nil | string | number | thread | table | boolean | function | userdata | lightuserdata }; enum class meta_function { construct, index, new_index, mode, call, metatable, to_string, length, unary_minus, addition, subtraction, multiplication, division, modulus, power_of, involution = power_of, concatenation, equal_to, less_than, less_than_or_equal_to, garbage_collect, call_function = call, }; typedef meta_function meta_method; const std::array<std::string, 2> meta_variable_names = { { "__index", "__newindex", } }; const std::array<std::string, 21> meta_function_names = { { "new", "__index", "__newindex", "__mode", "__call", "__metatable", "__tostring", "__len", "__unm", "__add", "__sub", "__mul", "__div", "__mod", "__pow", "__concat", "__eq", "__lt", "__le", "__gc", } }; inline const std::string& name_of(meta_function mf) { return meta_function_names[static_cast<int>(mf)]; } inline type type_of(lua_State* L, int index) { return static_cast<type>(lua_type(L, index)); } inline int type_panic(lua_State* L, int index, type expected, type actual) { return luaL_error(L, "stack index %d, expected %s, received %s", index, expected == type::poly ? "anything" : lua_typename(L, static_cast<int>(expected)), expected == type::poly ? "anything" : lua_typename(L, static_cast<int>(actual)) ); } // Specify this function as the handler for lua::check if you know there's nothing wrong inline int no_panic(lua_State*, int, type, type) noexcept { return 0; } inline void type_error(lua_State* L, int expected, int actual) { luaL_error(L, "expected %s, received %s", lua_typename(L, expected), lua_typename(L, actual)); } inline void type_error(lua_State* L, type expected, type actual) { type_error(L, static_cast<int>(expected), static_cast<int>(actual)); } inline void type_assert(lua_State* L, int index, type expected, type actual) { if (expected != type::poly && expected != actual) { type_panic(L, index, expected, actual); } } inline void type_assert(lua_State* L, int index, type expected) { type actual = type_of(L, index); type_assert(L, index, expected, actual); } inline std::string type_name(lua_State* L, type t) { return lua_typename(L, static_cast<int>(t)); } class reference; class stack_reference; template <typename Table, typename Key> struct proxy; template<typename T> class usertype; template <bool, typename T> class basic_table_core; template <bool b> using table_core = basic_table_core<b, reference>; template <bool b> using stack_table_core = basic_table_core<b, stack_reference>; typedef table_core<false> table; typedef table_core<true> global_table; typedef stack_table_core<false> stack_table; typedef stack_table_core<true> stack_global_table; template <typename T> class basic_function; template <typename T> class basic_protected_function; using function = basic_function<reference>; using protected_function = basic_protected_function<reference>; using stack_function = basic_function<stack_reference>; using stack_protected_function = basic_protected_function<stack_reference>; template <typename base_t> class basic_object; template <typename base_t> class basic_userdata; template <typename base_t> class basic_lightuserdata; struct variadic_args; using object = basic_object<reference>; using stack_object = basic_object<stack_reference>; using userdata = basic_userdata<reference>; using stack_userdata = basic_userdata<stack_reference>; using lightuserdata = basic_lightuserdata<reference>; using stack_lightuserdata = basic_lightuserdata<stack_reference>; class coroutine; class thread; struct variadic_args; struct this_state; namespace detail { template <typename T, typename = void> struct lua_type_of : std::integral_constant<type, type::userdata> {}; template <> struct lua_type_of<std::string> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<std::wstring> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<std::u16string> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<std::u32string> : std::integral_constant<type, type::string> {}; template <std::size_t N> struct lua_type_of<char[N]> : std::integral_constant<type, type::string> {}; template <std::size_t N> struct lua_type_of<wchar_t[N]> : std::integral_constant<type, type::string> {}; template <std::size_t N> struct lua_type_of<char16_t[N]> : std::integral_constant<type, type::string> {}; template <std::size_t N> struct lua_type_of<char32_t[N]> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<char> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<wchar_t> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<char16_t> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<char32_t> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<const char*> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<const char16_t*> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<const char32_t*> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<string_detail::string_shim> : std::integral_constant<type, type::string> {}; template <> struct lua_type_of<bool> : std::integral_constant<type, type::boolean> {}; template <> struct lua_type_of<nil_t> : std::integral_constant<type, type::nil> { }; template <> struct lua_type_of<nullopt_t> : std::integral_constant<type, type::nil> { }; template <> struct lua_type_of<std::nullptr_t> : std::integral_constant<type, type::nil> { }; template <> struct lua_type_of<sol::error> : std::integral_constant<type, type::string> { }; template <bool b, typename Base> struct lua_type_of<basic_table_core<b, Base>> : std::integral_constant<type, type::table> { }; template <> struct lua_type_of<reference> : std::integral_constant<type, type::poly> {}; template <> struct lua_type_of<stack_reference> : std::integral_constant<type, type::poly> {}; template <typename Base> struct lua_type_of<basic_object<Base>> : std::integral_constant<type, type::poly> {}; template <typename... Args> struct lua_type_of<std::tuple<Args...>> : std::integral_constant<type, type::poly> {}; template <typename A, typename B> struct lua_type_of<std::pair<A, B>> : std::integral_constant<type, type::poly> {}; template <> struct lua_type_of<void*> : std::integral_constant<type, type::lightuserdata> {}; template <> struct lua_type_of<lightuserdata_value> : std::integral_constant<type, type::lightuserdata> {}; template <> struct lua_type_of<userdata_value> : std::integral_constant<type, type::userdata> {}; template <typename T> struct lua_type_of<light<T>> : std::integral_constant<type, type::lightuserdata> {}; template <typename T> struct lua_type_of<user<T>> : std::integral_constant<type, type::userdata> {}; template <typename Base> struct lua_type_of<basic_lightuserdata<Base>> : std::integral_constant<type, type::lightuserdata> {}; template <typename Base> struct lua_type_of<basic_userdata<Base>> : std::integral_constant<type, type::userdata> {}; template <> struct lua_type_of<lua_CFunction> : std::integral_constant<type, type::function> {}; template <> struct lua_type_of<std::remove_pointer_t<lua_CFunction>> : std::integral_constant<type, type::function> {}; template <typename Base> struct lua_type_of<basic_function<Base>> : std::integral_constant<type, type::function> {}; template <typename Base> struct lua_type_of<basic_protected_function<Base>> : std::integral_constant<type, type::function> {}; template <> struct lua_type_of<coroutine> : std::integral_constant<type, type::function> {}; template <> struct lua_type_of<thread> : std::integral_constant<type, type::thread> {}; template <typename Signature> struct lua_type_of<std::function<Signature>> : std::integral_constant<type, type::function> {}; template <typename T> struct lua_type_of<optional<T>> : std::integral_constant<type, type::poly> {}; template <> struct lua_type_of<variadic_args> : std::integral_constant<type, type::poly> {}; template <> struct lua_type_of<this_state> : std::integral_constant<type, type::poly> {}; template <> struct lua_type_of<type> : std::integral_constant<type, type::poly> {}; template <typename T> struct lua_type_of<T*> : std::integral_constant<type, type::userdata> {}; template <typename T> struct lua_type_of<T, std::enable_if_t<std::is_arithmetic<T>::value>> : std::integral_constant<type, type::number> {}; template <typename T> struct lua_type_of<T, std::enable_if_t<std::is_enum<T>::value>> : std::integral_constant<type, type::number> {}; template <> struct lua_type_of<meta_function> : std::integral_constant<type, type::string> {}; template <typename C, C v, template <typename...> class V, typename... Args> struct accumulate : std::integral_constant<C, v> {}; template <typename C, C v, template <typename...> class V, typename T, typename... Args> struct accumulate<C, v, V, T, Args...> : accumulate<C, v + V<T>::value, V, Args...> {}; } // detail template <typename T> struct is_unique_usertype : std::integral_constant<bool, unique_usertype_traits<T>::value> {}; template <typename T> struct lua_type_of : detail::lua_type_of<T> {}; template <typename T> struct lua_size : std::integral_constant<int, 1> { }; template <typename A, typename B> struct lua_size<std::pair<A, B>> : std::integral_constant<int, lua_size<A>::value + lua_size<B>::value> { }; template <typename... Args> struct lua_size<std::tuple<Args...>> : std::integral_constant<int, detail::accumulate<int, 0, lua_size, Args...>::value> { }; template <typename T> struct is_lua_primitive : std::integral_constant<bool, type::userdata != lua_type_of<meta::unqualified_t<T>>::value || (lua_size<T>::value > 1) || std::is_base_of<reference, meta::unqualified_t<T>>::value || std::is_base_of<stack_reference, meta::unqualified_t<T>>::value || meta::is_specialization_of<std::tuple, meta::unqualified_t<T>>::value || meta::is_specialization_of<std::pair, meta::unqualified_t<T>>::value > { }; template <typename T> struct is_lua_reference : std::integral_constant<bool, std::is_base_of<reference, meta::unqualified_t<T>>::value || std::is_base_of<stack_reference, meta::unqualified_t<T>>::value || meta::is_specialization_of<proxy, meta::unqualified_t<T>>::value > { }; template <typename T> struct is_lua_primitive<T*> : std::true_type {}; template <typename T> struct is_lua_primitive<std::reference_wrapper<T>> : std::true_type { }; template <typename T> struct is_lua_primitive<user<T>> : std::true_type { }; template <typename T> struct is_lua_primitive<light<T>> : is_lua_primitive<T*> { }; template <typename T> struct is_lua_primitive<optional<T>> : std::true_type {}; template <> struct is_lua_primitive<userdata_value> : std::true_type {}; template <> struct is_lua_primitive<lightuserdata_value> : std::true_type {}; template <typename T> struct is_lua_primitive<non_null<T>> : is_lua_primitive<T*> {}; template <typename T> struct is_proxy_primitive : is_lua_primitive<T> { }; template <typename T> struct is_transparent_argument : std::false_type {}; template <> struct is_transparent_argument<this_state> : std::true_type {}; template <> struct is_transparent_argument<variadic_args> : std::true_type {}; template <typename Signature> struct lua_bind_traits : meta::bind_traits<Signature> { private: typedef meta::bind_traits<Signature> base_t; public: static const std::size_t true_arity = base_t::arity; static const std::size_t arity = base_t::arity - meta::count_for<is_transparent_argument, typename base_t::args_list>::value; static const std::size_t true_free_arity = base_t::free_arity; static const std::size_t free_arity = base_t::free_arity - meta::count_for<is_transparent_argument, typename base_t::args_list>::value; }; template <typename T> struct is_table : std::false_type {}; template <bool x, typename T> struct is_table<basic_table_core<x, T>> : std::true_type {}; template <typename T> struct is_function : std::false_type {}; template <typename T> struct is_function<basic_function<T>> : std::true_type {}; template <typename T> struct is_function<basic_protected_function<T>> : std::true_type {}; template <typename T> struct is_lightuserdata : std::false_type {}; template <typename T> struct is_lightuserdata<basic_lightuserdata<T>> : std::true_type {}; template <typename T> struct is_userdata : std::false_type {}; template <typename T> struct is_userdata<basic_userdata<T>> : std::true_type {}; template<typename T> inline type type_of() { return lua_type_of<meta::unqualified_t<T>>::value; } } // sol // end of sol/types.hpp // beginning of sol/stack_reference.hpp namespace sol { class stack_reference { private: lua_State* L = nullptr; int index = 0; protected: int registry_index() const noexcept { return LUA_NOREF; } public: stack_reference() noexcept = default; stack_reference(nil_t) noexcept : stack_reference() {}; stack_reference(lua_State* L, int i) noexcept : L(L), index(lua_absindex(L, i)) {} stack_reference(lua_State* L, absolute_index i) noexcept : L(L), index(i) {} stack_reference(lua_State* L, raw_index i) noexcept : L(L), index(i) {} stack_reference(stack_reference&& o) noexcept = default; stack_reference& operator=(stack_reference&&) noexcept = default; stack_reference(const stack_reference&) noexcept = default; stack_reference& operator=(const stack_reference&) noexcept = default; int push() const noexcept { lua_pushvalue(L, index); return 1; } void pop(int n = 1) const noexcept { lua_pop(lua_state(), n); } int stack_index() const noexcept { return index; } type get_type() const noexcept { int result = lua_type(L, index); return static_cast<type>(result); } lua_State* lua_state() const noexcept { return L; } bool valid() const noexcept { type t = get_type(); return t != type::nil && t != type::none; } }; inline bool operator== (const stack_reference& l, const stack_reference& r) { return lua_compare(l.lua_state(), l.stack_index(), r.stack_index(), LUA_OPEQ) == 0; } inline bool operator!= (const stack_reference& l, const stack_reference& r) { return !operator==(l, r); } } // sol // end of sol/stack_reference.hpp namespace sol { namespace stack { template <bool top_level> struct push_popper_n { lua_State* L; int t; push_popper_n(lua_State* L, int x) : L(L), t(x) { } ~push_popper_n() { lua_pop(L, t); } }; template <> struct push_popper_n<true> { push_popper_n(lua_State*, int) { } }; template <bool top_level, typename T> struct push_popper { T t; push_popper(T x) : t(x) { t.push(); } ~push_popper() { t.pop(); } }; template <typename T> struct push_popper<true, T> { push_popper(T) {} ~push_popper() {} }; template <bool top_level = false, typename T> push_popper<top_level, T> push_pop(T&& x) { return push_popper<top_level, T>(std::forward<T>(x)); } template <bool top_level = false> push_popper_n<top_level> pop_n(lua_State* L, int x) { return push_popper_n<top_level>(L, x); } } // stack namespace detail { struct global_tag { } const global_{}; } // detail class reference { private: lua_State* L = nullptr; // non-owning int ref = LUA_NOREF; int copy() const noexcept { if (ref == LUA_NOREF) return LUA_NOREF; push(); return luaL_ref(L, LUA_REGISTRYINDEX); } protected: reference(lua_State* L, detail::global_tag) noexcept : L(L) { lua_pushglobaltable(L); ref = luaL_ref(L, LUA_REGISTRYINDEX); } int stack_index() const noexcept { return -1; } public: reference() noexcept = default; reference(nil_t) noexcept : reference() {} reference(const stack_reference& r) noexcept : reference(r.lua_state(), r.stack_index()) {} reference(stack_reference&& r) noexcept : reference(r.lua_state(), r.stack_index()) {} reference(lua_State* L, int index = -1) noexcept : L(L) { lua_pushvalue(L, index); ref = luaL_ref(L, LUA_REGISTRYINDEX); } virtual ~reference() noexcept { luaL_unref(L, LUA_REGISTRYINDEX, ref); } reference(reference&& o) noexcept { L = o.L; ref = o.ref; o.L = nullptr; o.ref = LUA_NOREF; } reference& operator=(reference&& o) noexcept { L = o.L; ref = o.ref; o.L = nullptr; o.ref = LUA_NOREF; return *this; } reference(const reference& o) noexcept { L = o.L; ref = o.copy(); } reference& operator=(const reference& o) noexcept { L = o.L; ref = o.copy(); return *this; } int push() const noexcept { lua_rawgeti(L, LUA_REGISTRYINDEX, ref); return 1; } void pop(int n = 1) const noexcept { lua_pop(lua_state(), n); } int registry_index() const noexcept { return ref; } bool valid() const noexcept { return !(ref == LUA_NOREF || ref == LUA_REFNIL); } explicit operator bool() const noexcept { return valid(); } type get_type() const noexcept { auto pp = stack::push_pop(*this); int result = lua_type(L, -1); return static_cast<type>(result); } lua_State* lua_state() const noexcept { return L; } }; inline bool operator== (const reference& l, const reference& r) { auto ppl = stack::push_pop(l); auto ppr = stack::push_pop(r); return lua_compare(l.lua_state(), -1, -2, LUA_OPEQ) == 1; } inline bool operator!= (const reference& l, const reference& r) { return !operator==(l, r); } } // sol // end of sol/reference.hpp // beginning of sol/stack.hpp // beginning of sol/stack_core.hpp // beginning of sol/userdata.hpp namespace sol { template <typename base_t> class basic_userdata : public base_t { public: basic_userdata() noexcept = default; template <typename T, meta::enable<meta::neg<std::is_same<meta::unqualified_t<T>, basic_userdata>>, meta::neg<std::is_same<base_t, stack_reference>>, std::is_base_of<base_t, meta::unqualified_t<T>>> = meta::enabler> basic_userdata(T&& r) noexcept : base_t(std::forward<T>(r)) { #ifdef SOL_CHECK_ARGUMENTS if (!is_userdata<meta::unqualified_t<T>>::value) { auto pp = stack::push_pop(*this); type_assert(base_t::lua_state(), -1, type::userdata); } #endif // Safety } basic_userdata(const basic_userdata&) = default; basic_userdata(basic_userdata&&) = default; basic_userdata& operator=(const basic_userdata&) = default; basic_userdata& operator=(basic_userdata&&) = default; basic_userdata(const stack_reference& r) : basic_userdata(r.lua_state(), r.stack_index()) {} basic_userdata(stack_reference&& r) : basic_userdata(r.lua_state(), r.stack_index()) {} basic_userdata(lua_State* L, int index = -1) : base_t(L, index) { #ifdef SOL_CHECK_ARGUMENTS type_assert(L, index, type::userdata); #endif // Safety } }; template <typename base_t> class basic_lightuserdata : public base_t { public: basic_lightuserdata() noexcept = default; template <typename T, meta::enable<meta::neg<std::is_same<meta::unqualified_t<T>, basic_lightuserdata>>, meta::neg<std::is_same<base_t, stack_reference>>, std::is_base_of<base_t, meta::unqualified_t<T>>> = meta::enabler> basic_lightuserdata(T&& r) noexcept : base_t(std::forward<T>(r)) { #ifdef SOL_CHECK_ARGUMENTS if (!is_userdata<meta::unqualified_t<T>>::value) { auto pp = stack::push_pop(*this); type_assert(base_t::lua_state(), -1, type::lightuserdata); } #endif // Safety } basic_lightuserdata(const basic_lightuserdata&) = default; basic_lightuserdata(basic_lightuserdata&&) = default; basic_lightuserdata& operator=(const basic_lightuserdata&) = default; basic_lightuserdata& operator=(basic_lightuserdata&&) = default; basic_lightuserdata(const stack_reference& r) : basic_lightuserdata(r.lua_state(), r.stack_index()) {} basic_lightuserdata(stack_reference&& r) : basic_lightuserdata(r.lua_state(), r.stack_index()) {} basic_lightuserdata(lua_State* L, int index = -1) : base_t(L, index) { #ifdef SOL_CHECK_ARGUMENTS type_assert(L, index, type::lightuserdata); #endif // Safety } }; } // sol // end of sol/userdata.hpp // beginning of sol/tie.hpp namespace sol { namespace detail { template <typename T> struct is_speshul : std::false_type {}; } template <typename T> struct tie_size : std::tuple_size<T> {}; template <typename T> struct is_tieable : std::integral_constant<bool, (::sol::tie_size<T>::value > 0)> {}; template <typename... Tn> struct tie_t : public std::tuple<std::add_lvalue_reference_t<Tn>...> { private: typedef std::tuple<std::add_lvalue_reference_t<Tn>...> base_t; template <typename T> void set(std::false_type, T&& target) { std::get<0>(*this) = std::forward<T>(target); } template <typename T> void set(std::true_type, T&& target) { typedef tie_size<meta::unqualified_t<T>> value_size; typedef tie_size<std::tuple<Tn...>> tie_size; typedef std::conditional_t<(value_size::value < tie_size::value), value_size, tie_size> indices_size; typedef std::make_index_sequence<indices_size::value> indices; set_extra(detail::is_speshul<meta::unqualified_t<T>>(), indices(), std::forward<T>(target)); } template <std::size_t... I, typename T> void set_extra(std::true_type, std::index_sequence<I...>, T&& target) { using std::get; (void)detail::swallow{ 0, (get<I>(*this) = get<I>(types<Tn...>(), target), 0)... , 0 }; } template <std::size_t... I, typename T> void set_extra(std::false_type, std::index_sequence<I...>, T&& target) { using std::get; (void)detail::swallow{ 0, (get<I>(*this) = get<I>(target), 0)... , 0 }; } public: using base_t::base_t; template <typename T> tie_t& operator= (T&& value) { typedef is_tieable<meta::unqualified_t<T>> tieable; set(tieable(), std::forward<T>(value)); return *this; } }; template <typename... Tn> struct tie_size< tie_t<Tn...> > : std::tuple_size< std::tuple<Tn...> > { }; namespace adl_barrier_detail { template <typename... Tn> inline tie_t<std::remove_reference_t<Tn>...> tie(Tn&&... argn) { return tie_t<std::remove_reference_t<Tn>...>(std::forward<Tn>(argn)...); } } using namespace adl_barrier_detail; } // sol // end of sol/tie.hpp // beginning of sol/stack_guard.hpp namespace sol { namespace detail { inline void stack_fail(int, int) { #ifndef SOL_NO_EXCEPTIONS throw error(detail::direct_error, "imbalanced stack after operation finish"); #else // Lol, what do you want, an error printout? :3c // There's no sane default here. The right way would be C-style abort(), and that's not acceptable, so // hopefully someone will register their own stack_fail thing for the `fx` parameter of stack_guard. #endif // No Exceptions } } // detail struct stack_guard { lua_State* L; int top; std::function<void(int, int)> on_mismatch; stack_guard(lua_State* L) : stack_guard(L, lua_gettop(L)) {} stack_guard(lua_State* L, int top, std::function<void(int, int)> fx = detail::stack_fail) : L(L), top(top), on_mismatch(std::move(fx)) {} bool check_stack(int modification = 0) const { int bottom = lua_gettop(L) + modification; if (top == bottom) { return true; } on_mismatch(top, bottom); return false; } ~stack_guard() { check_stack(); } }; } // sol // end of sol/stack_guard.hpp #include <vector> namespace sol { namespace detail { struct as_reference_tag {}; template <typename T> struct as_pointer_tag {}; template <typename T> struct as_value_tag {}; using special_destruct_func = void(*)(void*); template <typename T, typename Real> inline void special_destruct(void* memory) { T** pointerpointer = static_cast<T**>(memory); special_destruct_func* dx = static_cast<special_destruct_func*>(static_cast<void*>(pointerpointer + 1)); Real* target = static_cast<Real*>(static_cast<void*>(dx + 1)); target->~Real(); } template <typename T> inline int unique_destruct(lua_State* L) { void* memory = lua_touserdata(L, 1); T** pointerpointer = static_cast<T**>(memory); special_destruct_func& dx = *static_cast<special_destruct_func*>(static_cast<void*>(pointerpointer + 1)); (dx)(memory); return 0; } template <typename T> inline int user_alloc_destroy(lua_State* L) { void* rawdata = lua_touserdata(L, upvalue_index(1)); T* data = static_cast<T*>(rawdata); std::allocator<T> alloc; alloc.destroy(data); return 0; } template <typename T> inline int usertype_alloc_destroy(lua_State* L) { void* rawdata = lua_touserdata(L, 1); T** pdata = static_cast<T**>(rawdata); T* data = *pdata; std::allocator<T> alloc{}; alloc.destroy(data); return 0; } template <typename T> void reserve(T&, std::size_t) {} template <typename T, typename Al> void reserve(std::vector<T, Al>& arr, std::size_t hint) { arr.reserve(hint); } template <typename T, typename Tr, typename Al> void reserve(std::basic_string<T, Tr, Al>& arr, std::size_t hint) { arr.reserve(hint); } } // detail namespace stack { template<typename T, bool global = false, bool raw = false, typename = void> struct field_getter; template <typename T, bool global = false, bool raw = false, typename = void> struct probe_field_getter; template<typename T, bool global = false, bool raw = false, typename = void> struct field_setter; template<typename T, typename = void> struct getter; template<typename T, typename = void> struct popper; template<typename T, typename = void> struct pusher; template<typename T, type = lua_type_of<T>::value, typename = void> struct checker; template<typename T, typename = void> struct check_getter; struct probe { bool success; int levels; probe(bool s, int l) : success(s), levels(l) {} operator bool() const { return success; }; }; struct record { int last; int used; record() : last(), used() {} void use(int count) { last = count; used += count; } }; namespace stack_detail { template <typename T> struct strip { typedef T type; }; template <typename T> struct strip<std::reference_wrapper<T>> { typedef T& type; }; template <typename T> struct strip<user<T>> { typedef T& type; }; template <typename T> struct strip<non_null<T>> { typedef T type; }; template <typename T> using strip_t = typename strip<T>::type; const bool default_check_arguments = #ifdef SOL_CHECK_ARGUMENTS true; #else false; #endif template<typename T> inline decltype(auto) unchecked_get(lua_State* L, int index, record& tracking) { return getter<meta::unqualified_t<T>>{}.get(L, index, tracking); } } // stack_detail inline bool maybe_indexable(lua_State* L, int index = -1) { type t = type_of(L, index); return t == type::userdata || t == type::table; } template<typename T, typename... Args> inline int push(lua_State* L, T&& t, Args&&... args) { return pusher<meta::unqualified_t<T>>{}.push(L, std::forward<T>(t), std::forward<Args>(args)...); } // overload allows to use a pusher of a specific type, but pass in any kind of args template<typename T, typename Arg, typename... Args, typename = std::enable_if_t<!std::is_same<T, Arg>::value>> inline int push(lua_State* L, Arg&& arg, Args&&... args) { return pusher<meta::unqualified_t<T>>{}.push(L, std::forward<Arg>(arg), std::forward<Args>(args)...); } template<typename T, typename... Args> inline int push_reference(lua_State* L, T&& t, Args&&... args) { typedef meta::all< std::is_lvalue_reference<T>, meta::neg<std::is_const<T>>, meta::neg<is_lua_primitive<meta::unqualified_t<T>>>, meta::neg<is_unique_usertype<meta::unqualified_t<T>>> > use_reference_tag; return pusher<std::conditional_t<use_reference_tag::value, detail::as_reference_tag, meta::unqualified_t<T>>>{}.push(L, std::forward<T>(t), std::forward<Args>(args)...); } inline int multi_push(lua_State*) { // do nothing return 0; } template<typename T, typename... Args> inline int multi_push(lua_State* L, T&& t, Args&&... args) { int pushcount = push(L, std::forward<T>(t)); void(sol::detail::swallow{ (pushcount += sol::stack::push(L, std::forward<Args>(args)), 0)... }); return pushcount; } inline int multi_push_reference(lua_State*) { // do nothing return 0; } template<typename T, typename... Args> inline int multi_push_reference(lua_State* L, T&& t, Args&&... args) { int pushcount = push_reference(L, std::forward<T>(t)); void(sol::detail::swallow{ (pushcount += sol::stack::push_reference(L, std::forward<Args>(args)), 0)... }); return pushcount; } template <typename T, typename Handler> bool check(lua_State* L, int index, Handler&& handler, record& tracking) { typedef meta::unqualified_t<T> Tu; checker<Tu> c; // VC++ has a bad warning here: shut it up (void)c; return c.check(L, index, std::forward<Handler>(handler), tracking); } template <typename T, typename Handler> bool check(lua_State* L, int index, Handler&& handler) { record tracking{}; return check<T>(L, index, std::forward<Handler>(handler), tracking); } template <typename T> bool check(lua_State* L, int index = -lua_size<meta::unqualified_t<T>>::value) { auto handler = no_panic; return check<T>(L, index, handler); } template<typename T, typename Handler> inline decltype(auto) check_get(lua_State* L, int index, Handler&& handler, record& tracking) { return check_getter<meta::unqualified_t<T>>{}.get(L, index, std::forward<Handler>(handler), tracking); } template<typename T, typename Handler> inline decltype(auto) check_get(lua_State* L, int index, Handler&& handler) { record tracking{}; return check_get<T>(L, index, handler, tracking); } template<typename T> inline decltype(auto) check_get(lua_State* L, int index = -lua_size<meta::unqualified_t<T>>::value) { auto handler = no_panic; return check_get<T>(L, index, handler); } namespace stack_detail { #ifdef SOL_CHECK_ARGUMENTS template <typename T> inline auto tagged_get(types<T>, lua_State* L, int index, record& tracking) -> decltype(stack_detail::unchecked_get<T>(L, index, tracking)) { auto op = check_get<T>(L, index, type_panic, tracking); return *op; } #else template <typename T> inline decltype(auto) tagged_get(types<T>, lua_State* L, int index, record& tracking) { return stack_detail::unchecked_get<T>(L, index, tracking); } #endif template <typename T> inline decltype(auto) tagged_get(types<optional<T>>, lua_State* L, int index, record& tracking) { return stack_detail::unchecked_get<optional<T>>(L, index, tracking); } template <bool b> struct check_types { template <typename T, typename... Args, typename Handler> static bool check(types<T, Args...>, lua_State* L, int firstargument, Handler&& handler, record& tracking) { if (!stack::check<T>(L, firstargument + tracking.used, handler, tracking)) return false; return check(types<Args...>(), L, firstargument, std::forward<Handler>(handler), tracking); } template <typename Handler> static bool check(types<>, lua_State*, int, Handler&&, record&) { return true; } }; template <> struct check_types<false> { template <typename... Args, typename Handler> static bool check(types<Args...>, lua_State*, int, Handler&&, record&) { return true; } }; } // stack_detail template <bool b, typename... Args, typename Handler> bool multi_check(lua_State* L, int index, Handler&& handler, record& tracking) { return stack_detail::check_types<b>{}.check(types<meta::unqualified_t<Args>...>(), L, index, std::forward<Handler>(handler), tracking); } template <bool b, typename... Args, typename Handler> bool multi_check(lua_State* L, int index, Handler&& handler) { record tracking{}; return multi_check<b, Args...>(L, index, std::forward<Handler>(handler), tracking); } template <bool b, typename... Args> bool multi_check(lua_State* L, int index) { auto handler = no_panic; return multi_check<b, Args...>(L, index, handler); } template <typename... Args, typename Handler> bool multi_check(lua_State* L, int index, Handler&& handler, record& tracking) { return multi_check<true, Args...>(L, index, std::forward<Handler>(handler), tracking); } template <typename... Args, typename Handler> bool multi_check(lua_State* L, int index, Handler&& handler) { return multi_check<true, Args...>(L, index, std::forward<Handler>(handler)); } template <typename... Args> bool multi_check(lua_State* L, int index) { return multi_check<true, Args...>(L, index); } template<typename T> inline decltype(auto) get(lua_State* L, int index, record& tracking) { return stack_detail::tagged_get(types<T>(), L, index, tracking); } template<typename T> inline decltype(auto) get(lua_State* L, int index = -lua_size<meta::unqualified_t<T>>::value) { record tracking{}; return get<T>(L, index, tracking); } template<typename T> inline decltype(auto) pop(lua_State* L) { return popper<meta::unqualified_t<T>>{}.pop(L); } template <bool global = false, bool raw = false, typename Key> void get_field(lua_State* L, Key&& key) { field_getter<meta::unqualified_t<Key>, global, raw>{}.get(L, std::forward<Key>(key)); } template <bool global = false, bool raw = false, typename Key> void get_field(lua_State* L, Key&& key, int tableindex) { field_getter<meta::unqualified_t<Key>, global, raw>{}.get(L, std::forward<Key>(key), tableindex); } template <bool global = false, typename Key> void raw_get_field(lua_State* L, Key&& key) { get_field<global, true>(L, std::forward<Key>(key)); } template <bool global = false, typename Key> void raw_get_field(lua_State* L, Key&& key, int tableindex) { get_field<global, true>(L, std::forward<Key>(key), tableindex); } template <bool global = false, bool raw = false, typename Key> probe probe_get_field(lua_State* L, Key&& key) { return probe_field_getter<meta::unqualified_t<Key>, global, raw>{}.get(L, std::forward<Key>(key)); } template <bool global = false, bool raw = false, typename Key> probe probe_get_field(lua_State* L, Key&& key, int tableindex) { return probe_field_getter<meta::unqualified_t<Key>, global, raw>{}.get(L, std::forward<Key>(key), tableindex); } template <bool global = false, typename Key> probe probe_raw_get_field(lua_State* L, Key&& key) { return probe_get_field<global, true>(L, std::forward<Key>(key)); } template <bool global = false, typename Key> probe probe_raw_get_field(lua_State* L, Key&& key, int tableindex) { return probe_get_field<global, true>(L, std::forward<Key>(key), tableindex); } template <bool global = false, bool raw = false, typename Key, typename Value> void set_field(lua_State* L, Key&& key, Value&& value) { field_setter<meta::unqualified_t<Key>, global, raw>{}.set(L, std::forward<Key>(key), std::forward<Value>(value)); } template <bool global = false, bool raw = false, typename Key, typename Value> void set_field(lua_State* L, Key&& key, Value&& value, int tableindex) { field_setter<meta::unqualified_t<Key>, global, raw>{}.set(L, std::forward<Key>(key), std::forward<Value>(value), tableindex); } template <bool global = false, typename Key, typename Value> void raw_set_field(lua_State* L, Key&& key, Value&& value) { set_field<global, true>(L, std::forward<Key>(key), std::forward<Value>(value)); } template <bool global = false, typename Key, typename Value> void raw_set_field(lua_State* L, Key&& key, Value&& value, int tableindex) { set_field<global, true>(L, std::forward<Key>(key), std::forward<Value>(value), tableindex); } } // stack } // sol // end of sol/stack_core.hpp // beginning of sol/stack_check.hpp // beginning of sol/usertype_traits.hpp // beginning of sol/demangle.hpp #include <cctype> namespace sol { namespace detail { #ifdef _MSC_VER template <typename T> inline std::string ctti_get_type_name() { const static std::array<std::string, 7> removals = { { "public:", "private:", "protected:", "struct ", "class ", "`anonymous-namespace'", "`anonymous namespace'" } }; std::string name = __FUNCSIG__; std::size_t start = name.find("get_type_name"); if (start == std::string::npos) start = 0; else start += 13; if (start < name.size() - 1) start += 1; std::size_t end = name.find_last_of('>'); if (end == std::string::npos) end = name.size(); name = name.substr(start, end - start); if (name.find("struct", 0) == 0) name.replace(0, 6, "", 0); if (name.find("class", 0) == 0) name.replace(0, 5, "", 0); while (!name.empty() && std::isblank(name.front())) name.erase(name.begin()); while (!name.empty() && std::isblank(name.back())) name.pop_back(); for (std::size_t r = 0; r < removals.size(); ++r) { auto found = name.find(removals[r]); while (found != std::string::npos) { name.erase(found, removals[r].size()); found = name.find(removals[r]); } } return name; } #elif defined(__GNUC__) || defined(__clang__) template <typename T, class seperator_mark = int> inline std::string ctti_get_type_name() { const static std::array<std::string, 2> removals = { { "{anonymous}", "(anonymous namespace)" } }; std::string name = __PRETTY_FUNCTION__; std::size_t start = name.find_first_of('['); start = name.find_first_of('=', start); std::size_t end = name.find_last_of(']'); if (end == std::string::npos) end = name.size(); if (start == std::string::npos) start = 0; if (start < name.size() - 1) start += 1; name = name.substr(start, end - start); start = name.rfind("seperator_mark"); if (start != std::string::npos) { name.erase(start - 2, name.length()); } while (!name.empty() && std::isblank(name.front())) name.erase(name.begin()); while (!name.empty() && std::isblank(name.back())) name.pop_back(); for (std::size_t r = 0; r < removals.size(); ++r) { auto found = name.find(removals[r]); while (found != std::string::npos) { name.erase(found, removals[r].size()); found = name.find(removals[r]); } } return name; } #else #error Compiler not supported for demangling #endif // compilers template <typename T> inline std::string demangle_once() { std::string realname = ctti_get_type_name<T>(); return realname; } template <typename T> inline std::string short_demangle_once() { std::string realname = ctti_get_type_name<T>(); // This isn't the most complete but it'll do for now...? static const std::array<std::string, 10> ops = { { "operator<", "operator<<", "operator<<=", "operator<=", "operator>", "operator>>", "operator>>=", "operator>=", "operator->", "operator->*" } }; int level = 0; std::ptrdiff_t idx = 0; for (idx = static_cast<std::ptrdiff_t>(realname.empty() ? 0 : realname.size() - 1); idx > 0; --idx) { if (level == 0 && realname[idx] == ':') { break; } bool isleft = realname[idx] == '<'; bool isright = realname[idx] == '>'; if (!isleft && !isright) continue; bool earlybreak = false; for (const auto& op : ops) { std::size_t nisop = realname.rfind(op, idx); if (nisop == std::string::npos) continue; std::size_t nisopidx = idx - op.size() + 1; if (nisop == nisopidx) { idx = static_cast<std::ptrdiff_t>(nisopidx); earlybreak = true; } break; } if (earlybreak) { continue; } level += isleft ? -1 : 1; } if (idx > 0) { realname.erase(0, realname.length() < static_cast<std::size_t>(idx) ? realname.length() : idx + 1); } return realname; } template <typename T> inline std::string demangle() { static const std::string d = demangle_once<T>(); return d; } template <typename T> inline std::string short_demangle() { static const std::string d = short_demangle_once<T>(); return d; } } // detail } // sol // end of sol/demangle.hpp namespace sol { template<typename T> struct usertype_traits { static const std::string name; static const std::string qualified_name; static const std::string metatable; static const std::string user_metatable; static const std::string user_gc_metatable; static const std::string gc_table; }; template<typename T> const std::string usertype_traits<T>::name = detail::short_demangle<T>(); template<typename T> const std::string usertype_traits<T>::qualified_name = detail::demangle<T>(); template<typename T> const std::string usertype_traits<T>::metatable = std::string("sol.").append(detail::demangle<T>()); template<typename T> const std::string usertype_traits<T>::user_metatable = std::string("sol.").append(detail::demangle<T>()).append(".user"); template<typename T> const std::string usertype_traits<T>::user_gc_metatable = std::string("sol.").append(detail::demangle<T>()).append(".user\xE2\x99\xBB"); template<typename T> const std::string usertype_traits<T>::gc_table = std::string("sol.").append(detail::demangle<T>().append(".\xE2\x99\xBB")); } // end of sol/usertype_traits.hpp // beginning of sol/inheritance.hpp #include <atomic> namespace sol { template <typename... Args> struct base_list { }; template <typename... Args> using bases = base_list<Args...>; typedef bases<> base_classes_tag; const auto base_classes = base_classes_tag(); namespace detail { template <typename T> struct has_derived { static bool value; }; template <typename T> bool has_derived<T>::value = false; inline std::size_t unique_id() { static std::atomic<std::size_t> x(0); return ++x; } template <typename T> struct id_for { static const std::size_t value; }; template <typename T> const std::size_t id_for<T>::value = unique_id(); inline decltype(auto) base_class_check_key() { static const auto& key = "class_check"; return key; } inline decltype(auto) base_class_cast_key() { static const auto& key = "class_cast"; return key; } inline decltype(auto) base_class_index_propogation_key() { static const auto& key = u8"\xF0\x9F\x8C\xB2.index"; return key; } inline decltype(auto) base_class_new_index_propogation_key() { static const auto& key = u8"\xF0\x9F\x8C\xB2.new_index"; return key; } template <typename T, typename... Bases> struct inheritance { static bool type_check_bases(types<>, std::size_t) { return false; } template <typename Base, typename... Args> static bool type_check_bases(types<Base, Args...>, std::size_t ti) { return ti == id_for<Base>::value || type_check_bases(types<Args...>(), ti); } static bool type_check(std::size_t ti) { return ti == id_for<T>::value || type_check_bases(types<Bases...>(), ti); } static void* type_cast_bases(types<>, T*, std::size_t) { return nullptr; } template <typename Base, typename... Args> static void* type_cast_bases(types<Base, Args...>, T* data, std::size_t ti) { // Make sure to convert to T first, and then dynamic cast to the proper type return ti != id_for<Base>::value ? type_cast_bases(types<Args...>(), data, ti) : static_cast<void*>(static_cast<Base*>(data)); } static void* type_cast(void* voiddata, std::size_t ti) { T* data = static_cast<T*>(voiddata); return static_cast<void*>(ti != id_for<T>::value ? type_cast_bases(types<Bases...>(), data, ti) : data); } }; using inheritance_check_function = decltype(&inheritance<void>::type_check); using inheritance_cast_function = decltype(&inheritance<void>::type_cast); } // detail } // sol // end of sol/inheritance.hpp #include <utility> namespace sol { namespace stack { namespace stack_detail { template <typename T, bool poptable = true> inline bool check_metatable(lua_State* L, int index = -2) { const auto& metakey = usertype_traits<T>::metatable; luaL_getmetatable(L, &metakey[0]); const type expectedmetatabletype = static_cast<type>(lua_type(L, -1)); if (expectedmetatabletype != type::nil) { if (lua_rawequal(L, -1, index) == 1) { lua_pop(L, 1 + static_cast<int>(poptable)); return true; } } lua_pop(L, 1); return false; } template <type expected, int(*check_func)(lua_State*, int)> struct basic_check { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { tracking.use(1); bool success = check_func(L, index) == 1; if (!success) { // expected type, actual type handler(L, index, expected, type_of(L, index)); } return success; } }; } // stack_detail template <typename T, type expected, typename> struct checker { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { tracking.use(1); const type indextype = type_of(L, index); bool success = expected == indextype; if (!success) { // expected type, actual type handler(L, index, expected, indextype); } return success; } }; template<typename T> struct checker<T, type::number, std::enable_if_t<std::is_integral<T>::value>> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { tracking.use(1); bool success = lua_isinteger(L, index) == 1; if (!success) { // expected type, actual type handler(L, index, type::number, type_of(L, index)); } return success; } }; template<typename T> struct checker<T, type::number, std::enable_if_t<std::is_floating_point<T>::value>> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { tracking.use(1); bool success = lua_isnumber(L, index) == 1; if (!success) { // expected type, actual type handler(L, index, type::number, type_of(L, index)); } return success; } }; template <type expected, typename C> struct checker<nil_t, expected, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { bool success = lua_isnil(L, index); if (success) { tracking.use(1); return success; } tracking.use(0); success = lua_isnone(L, index); if (!success) { // expected type, actual type handler(L, index, expected, type_of(L, index)); } return success; } }; template <type expected, typename C> struct checker<nullopt_t, expected, C> : checker<nil_t> {}; template <typename C> struct checker<this_state, type::poly, C> { template <typename Handler> static bool check(lua_State*, int, Handler&&, record& tracking) { tracking.use(0); return true; } }; template <typename C> struct checker<variadic_args, type::poly, C> { template <typename Handler> static bool check(lua_State*, int, Handler&&, record& tracking) { tracking.use(0); return true; } }; template <typename C> struct checker<type, type::poly, C> { template <typename Handler> static bool check(lua_State*, int, Handler&&, record& tracking) { tracking.use(0); return true; } }; template <typename T, typename C> struct checker<T, type::poly, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { tracking.use(1); bool success = !lua_isnone(L, index); if (!success) { // expected type, actual type handler(L, index, type::none, type_of(L, index)); } return success; } }; template <typename T, typename C> struct checker<T, type::lightuserdata, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { tracking.use(1); type t = type_of(L, index); bool success = t == type::userdata || t == type::lightuserdata; if (!success) { // expected type, actual type handler(L, index, type::lightuserdata, t); } return success; } }; template <typename C> struct checker<userdata_value, type::userdata, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { tracking.use(1); type t = type_of(L, index); bool success = t == type::userdata; if (!success) { // expected type, actual type handler(L, index, type::userdata, t); } return success; } }; template <typename T, typename C> struct checker<user<T>, type::userdata, C> : checker<user<T>, type::lightuserdata, C> {}; template <typename T, typename C> struct checker<non_null<T>, type::userdata, C> : checker<T, lua_type_of<T>::value, C> {}; template <typename C> struct checker<lua_CFunction, type::function, C> : stack_detail::basic_check<type::function, lua_iscfunction> {}; template <typename C> struct checker<std::remove_pointer_t<lua_CFunction>, type::function, C> : checker<lua_CFunction, type::function, C> {}; template <typename C> struct checker<c_closure, type::function, C> : checker<lua_CFunction, type::function, C> {}; template <typename T, typename C> struct checker<T, type::function, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { tracking.use(1); type t = type_of(L, index); if (t == type::nil || t == type::none || t == type::function) { // allow for nil to be returned return true; } if (t != type::userdata && t != type::table) { handler(L, index, type::function, t); return false; } // Do advanced check for call-style userdata? static const auto& callkey = name_of(meta_function::call); if (lua_getmetatable(L, index) == 0) { // No metatable, no __call key possible handler(L, index, type::function, t); return false; } if (lua_isnoneornil(L, -1)) { lua_pop(L, 1); handler(L, index, type::function, t); return false; } lua_getfield(L, -1, &callkey[0]); if (lua_isnoneornil(L, -1)) { lua_pop(L, 2); handler(L, index, type::function, t); return false; } // has call, is definitely a function lua_pop(L, 2); return true; } }; template <typename T, typename C> struct checker<T, type::table, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { tracking.use(1); type t = type_of(L, index); if (t == type::table) { return true; } if (t != type::userdata) { handler(L, index, type::function, t); return false; } return true; } }; template <typename T, typename C> struct checker<T*, type::userdata, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { const type indextype = type_of(L, index); // Allow nil to be transformed to nullptr if (indextype == type::nil) { tracking.use(1); return true; } return checker<meta::unqualified_t<T>, type::userdata, C>{}.check(types<meta::unqualified_t<T>>(), L, indextype, index, std::forward<Handler>(handler), tracking); } }; template <typename T, typename C> struct checker<T, type::userdata, C> { template <typename U, typename Handler> static bool check(types<U>, lua_State* L, type indextype, int index, Handler&& handler, record& tracking) { tracking.use(1); if (indextype != type::userdata) { handler(L, index, type::userdata, indextype); return false; } if (meta::any<std::is_same<T, lightuserdata_value>, std::is_same<T, userdata_value>, std::is_same<T, userdata>, std::is_same<T, lightuserdata>>::value) return true; if (lua_getmetatable(L, index) == 0) { return true; } int metatableindex = lua_gettop(L); if (stack_detail::check_metatable<U>(L, metatableindex)) return true; if (stack_detail::check_metatable<U*>(L, metatableindex)) return true; if (stack_detail::check_metatable<detail::unique_usertype<U>>(L, metatableindex)) return true; bool success = false; if (detail::has_derived<T>::value) { auto pn = stack::pop_n(L, 1); lua_pushstring(L, &detail::base_class_check_key()[0]); lua_rawget(L, metatableindex); if (type_of(L, -1) != type::nil) { void* basecastdata = lua_touserdata(L, -1); detail::inheritance_check_function ic = (detail::inheritance_check_function)basecastdata; success = ic(detail::id_for<T>::value); } } if (!success) { lua_pop(L, 1); handler(L, index, type::userdata, indextype); return false; } lua_pop(L, 1); return true; } template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { const type indextype = type_of(L, index); return check(types<T>(), L, indextype, index, std::forward<Handler>(handler), tracking); } }; template<typename T> struct checker<T, type::userdata, std::enable_if_t<is_unique_usertype<T>::value>> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { return checker<typename unique_usertype_traits<T>::type, type::userdata>{}.check(L, index, std::forward<Handler>(handler), tracking); } }; template<typename T, typename C> struct checker<std::reference_wrapper<T>, type::userdata, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { return checker<T, type::userdata, C>{}.check(L, index, std::forward<Handler>(handler), tracking); } }; template<typename... Args, typename C> struct checker<std::tuple<Args...>, type::poly, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { return stack::multi_check<Args...>(L, index, std::forward<Handler>(handler), tracking); } }; template<typename A, typename B, typename C> struct checker<std::pair<A, B>, type::poly, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { return stack::multi_check<A, B>(L, index, std::forward<Handler>(handler), tracking); } }; template<typename T, typename C> struct checker<optional<T>, type::poly, C> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { type t = type_of(L, index); if (t == type::none) { tracking.use(0); return true; } return t == type::nil || stack::check<T>(L, index, std::forward<Handler>(handler), tracking); } }; } // stack } // sol // end of sol/stack_check.hpp // beginning of sol/stack_get.hpp // beginning of sol/overload.hpp namespace sol { template <typename... Functions> struct overload_set { std::tuple<Functions...> functions; template <typename Arg, typename... Args, meta::disable<std::is_same<overload_set, meta::unqualified_t<Arg>>> = meta::enabler> overload_set (Arg&& arg, Args&&... args) : functions(std::forward<Arg>(arg), std::forward<Args>(args)...) {} overload_set(const overload_set&) = default; overload_set(overload_set&&) = default; overload_set& operator=(const overload_set&) = default; overload_set& operator=(overload_set&&) = default; }; template <typename... Args> decltype(auto) overload(Args&&... args) { return overload_set<std::decay_t<Args>...>(std::forward<Args>(args)...); } } // end of sol/overload.hpp #ifdef SOL_CODECVT_SUPPORT #include <codecvt> #include <locale> #endif namespace sol { namespace stack { template<typename T, typename> struct getter { static T& get(lua_State* L, int index, record& tracking) { return getter<T&>{}.get(L, index, tracking); } }; template<typename T> struct getter<T, std::enable_if_t<std::is_floating_point<T>::value>> { static T get(lua_State* L, int index, record& tracking) { tracking.use(1); return static_cast<T>(lua_tonumber(L, index)); } }; template<typename T> struct getter<T, std::enable_if_t<meta::all<std::is_integral<T>, std::is_signed<T>>::value>> { static T get(lua_State* L, int index, record& tracking) { tracking.use(1); return static_cast<T>(lua_tointeger(L, index)); } }; template<typename T> struct getter<T, std::enable_if_t<meta::all<std::is_integral<T>, std::is_unsigned<T>>::value>> { static T get(lua_State* L, int index, record& tracking) { tracking.use(1); return static_cast<T>(lua_tointeger(L, index)); } }; template<typename T> struct getter<T, std::enable_if_t<std::is_enum<T>::value>> { static T get(lua_State* L, int index, record& tracking) { tracking.use(1); return static_cast<T>(lua_tointegerx(L, index, nullptr)); } }; template<typename T> struct getter<as_table_t<T>, std::enable_if_t<!meta::has_key_value_pair<meta::unqualified_t<T>>::value>> { static T get(lua_State* L, int index, record& tracking) { typedef typename T::value_type V; tracking.use(1); index = lua_absindex(L, index); T arr; get_field<false, true>(L, static_cast<lua_Integer>(-1), index); int isnum; std::size_t sizehint = static_cast<std::size_t>(lua_tointegerx(L, -1, &isnum)); if (isnum != 0) { detail::reserve(arr, sizehint); } lua_pop(L, 1); #if SOL_LUA_VERSION >= 503 // This method is HIGHLY performant over regular table iteration thanks to the Lua API changes in 5.3 for (lua_Integer i = 0; ; i += lua_size<V>::value, lua_pop(L, lua_size<V>::value)) { for (int vi = 0; vi < lua_size<V>::value; ++vi) { type t = static_cast<type>(lua_geti(L, index, i + vi)); if (t == type::nil) { if (i == 0) { continue; } else { lua_pop(L, (vi + 1)); return arr; } } } arr.push_back(stack::get<V>(L, -lua_size<V>::value)); } #else // Zzzz slower but necessary thanks to the lower version API and missing functions qq for (lua_Integer i = 0; ; i += lua_size<V>::value, lua_pop(L, lua_size<V>::value)) { for (int vi = 0; vi < lua_size<V>::value; ++vi) { lua_pushinteger(L, i); lua_gettable(L, index); type t = type_of(L, -1); if (t == type::nil) { if (i == 0) { continue; } else { lua_pop(L, (vi + 1)); return arr; } } } arr.push_back(stack::get<V>(L, -1)); } #endif return arr; } }; template<typename T> struct getter<as_table_t<T>, std::enable_if_t<meta::has_key_value_pair<meta::unqualified_t<T>>::value>> { static T get(lua_State* L, int index, record& tracking) { typedef typename T::value_type P; typedef typename P::first_type K; typedef typename P::second_type V; tracking.use(1); T associative; index = lua_absindex(L, index); lua_pushnil(L); while (lua_next(L, index) != 0) { decltype(auto) key = stack::check_get<K>(L, -2); if (!key) { lua_pop(L, 1); continue; } associative.emplace(std::forward<decltype(*key)>(*key), stack::get<V>(L, -1)); lua_pop(L, 1); } return associative; } }; template<typename T> struct getter<T, std::enable_if_t<std::is_base_of<reference, T>::value || std::is_base_of<stack_reference, T>::value>> { static T get(lua_State* L, int index, record& tracking) { tracking.use(1); return T(L, index); } }; template<> struct getter<userdata_value> { static userdata_value get(lua_State* L, int index, record& tracking) { tracking.use(1); return userdata_value(lua_touserdata(L, index)); } }; template<> struct getter<lightuserdata_value> { static lightuserdata_value get(lua_State* L, int index, record& tracking) { tracking.use(1); return lightuserdata_value(lua_touserdata(L, index)); } }; template<typename T> struct getter<light<T>> { static light<T> get(lua_State* L, int index, record& tracking) { tracking.use(1); return light<T>(static_cast<T*>(lua_touserdata(L, index))); } }; template<typename T> struct getter<user<T>> { static T& get(lua_State* L, int index, record& tracking) { tracking.use(1); return *static_cast<T*>(lua_touserdata(L, index)); } }; template<typename T> struct getter<user<T*>> { static T* get(lua_State* L, int index, record& tracking) { tracking.use(1); return static_cast<T*>(lua_touserdata(L, index)); } }; template<> struct getter<type> { static type get(lua_State *L, int index, record& tracking) { tracking.use(1); return static_cast<type>(lua_type(L, index)); } }; template<> struct getter<bool> { static bool get(lua_State* L, int index, record& tracking) { tracking.use(1); return lua_toboolean(L, index) != 0; } }; template<> struct getter<std::string> { static std::string get(lua_State* L, int index, record& tracking) { tracking.use(1); std::size_t len; auto str = lua_tolstring(L, index, &len); return std::string( str, len ); } }; template <> struct getter<string_detail::string_shim> { string_detail::string_shim get(lua_State* L, int index, record& tracking) { tracking.use(1); size_t len; const char* p = lua_tolstring(L, index, &len); return string_detail::string_shim(p, len); } }; template<> struct getter<const char*> { static const char* get(lua_State* L, int index, record& tracking) { tracking.use(1); return lua_tostring(L, index); } }; template<> struct getter<char> { static char get(lua_State* L, int index, record& tracking) { tracking.use(1); size_t len; auto str = lua_tolstring(L, index, &len); return len > 0 ? str[0] : '\0'; } }; #ifdef SOL_CODECVT_SUPPORT template<> struct getter<std::wstring> { static std::wstring get(lua_State* L, int index, record& tracking) { tracking.use(1); size_t len; auto str = lua_tolstring(L, index, &len); if (len < 1) return std::wstring(); if (sizeof(wchar_t) == 2) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert; std::wstring r = convert.from_bytes(str, str + len); #ifdef __MINGW32__ // Fuck you, MinGW, and fuck you libstdc++ for introducing this absolutely asinine bug // https://sourceforge.net/p/mingw-w64/bugs/538/ // http://chat.stackoverflow.com/transcript/message/32271369#32271369 for (auto& c : r) { uint8_t* b = reinterpret_cast<uint8_t*>(&c); std::swap(b[0], b[1]); } #endif return r; } std::wstring_convert<std::codecvt_utf8<wchar_t>> convert; std::wstring r = convert.from_bytes(str, str + len); return r; } }; template<> struct getter<std::u16string> { static std::u16string get(lua_State* L, int index, record& tracking) { tracking.use(1); size_t len; auto str = lua_tolstring(L, index, &len); if (len < 1) return std::u16string(); #ifdef _MSC_VER std::wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t> convert; auto intd = convert.from_bytes(str, str + len); std::u16string r(intd.size(), '\0'); std::memcpy(&r[0], intd.data(), intd.size() * sizeof(char16_t)); #else std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert; std::u16string r = convert.from_bytes(str, str + len); #endif // VC++ is a shit return r; } }; template<> struct getter<std::u32string> { static std::u32string get(lua_State* L, int index, record& tracking) { tracking.use(1); size_t len; auto str = lua_tolstring(L, index, &len); if (len < 1) return std::u32string(); #ifdef _MSC_VER std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> convert; auto intd = convert.from_bytes(str, str + len); std::u32string r(intd.size(), '\0'); std::memcpy(&r[0], intd.data(), r.size() * sizeof(char32_t)); #else std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; std::u32string r = convert.from_bytes(str, str + len); #endif // VC++ is a shit return r; } }; template<> struct getter<wchar_t> { static wchar_t get(lua_State* L, int index, record& tracking) { auto str = getter<std::wstring>{}.get(L, index, tracking); return str.size() > 0 ? str[0] : wchar_t(0); } }; template<> struct getter<char16_t> { static char16_t get(lua_State* L, int index, record& tracking) { auto str = getter<std::u16string>{}.get(L, index, tracking); return str.size() > 0 ? str[0] : char16_t(0); } }; template<> struct getter<char32_t> { static char32_t get(lua_State* L, int index, record& tracking) { auto str = getter<std::u32string>{}.get(L, index, tracking); return str.size() > 0 ? str[0] : char32_t(0); } }; #endif // codecvt header support template<> struct getter<meta_function> { static meta_function get(lua_State *L, int index, record& tracking) { tracking.use(1); const char* name = getter<const char*>{}.get(L, index, tracking); for (std::size_t i = 0; i < meta_function_names.size(); ++i) if (meta_function_names[i] == name) return static_cast<meta_function>(i); return meta_function::construct; } }; template<> struct getter<nil_t> { static nil_t get(lua_State*, int, record& tracking) { tracking.use(1); return nil; } }; template<> struct getter<std::nullptr_t> { static std::nullptr_t get(lua_State*, int, record& tracking) { tracking.use(1); return nullptr; } }; template<> struct getter<nullopt_t> { static nullopt_t get(lua_State*, int, record& tracking) { tracking.use(1); return nullopt; } }; template<> struct getter<this_state> { static this_state get(lua_State* L, int, record& tracking) { tracking.use(0); return this_state{ L }; } }; template<> struct getter<lua_CFunction> { static lua_CFunction get(lua_State* L, int index, record& tracking) { tracking.use(1); return lua_tocfunction(L, index); } }; template<> struct getter<c_closure> { static c_closure get(lua_State* L, int index, record& tracking) { tracking.use(1); return c_closure(lua_tocfunction(L, index), -1); } }; template<> struct getter<error> { static error get(lua_State* L, int index, record& tracking) { tracking.use(1); size_t sz = 0; const char* err = lua_tolstring(L, index, &sz); if (err == nullptr) { return error(detail::direct_error, ""); } return error(detail::direct_error, std::string(err, sz)); } }; template<> struct getter<void*> { static void* get(lua_State* L, int index, record& tracking) { tracking.use(1); return lua_touserdata(L, index); } }; template<typename T> struct getter<T*> { static T* get_no_nil(lua_State* L, int index, record& tracking) { tracking.use(1); void** pudata = static_cast<void**>(lua_touserdata(L, index)); void* udata = *pudata; return get_no_nil_from(L, udata, index, tracking); } static T* get_no_nil_from(lua_State* L, void* udata, int index, record&) { if (detail::has_derived<T>::value && luaL_getmetafield(L, index, &detail::base_class_cast_key()[0]) != 0) { void* basecastdata = lua_touserdata(L, -1); detail::inheritance_cast_function ic = (detail::inheritance_cast_function)basecastdata; // use the casting function to properly adjust the pointer for the desired T udata = ic(udata, detail::id_for<T>::value); lua_pop(L, 1); } T* obj = static_cast<T*>(udata); return obj; } static T* get(lua_State* L, int index, record& tracking) { type t = type_of(L, index); if (t == type::nil) { tracking.use(1); return nullptr; } return get_no_nil(L, index, tracking); } }; template<typename T> struct getter<non_null<T*>> { static T* get(lua_State* L, int index, record& tracking) { return getter<T*>::get_no_nil(L, index, tracking); } }; template<typename T> struct getter<T&> { static T& get(lua_State* L, int index, record& tracking) { return *getter<T*>::get_no_nil(L, index, tracking); } }; template<typename T> struct getter<T, std::enable_if_t<is_unique_usertype<T>::value>> { typedef typename unique_usertype_traits<T>::type P; typedef typename unique_usertype_traits<T>::actual_type Real; static Real& get(lua_State* L, int index, record& tracking) { tracking.use(1); P** pref = static_cast<P**>(lua_touserdata(L, index)); detail::special_destruct_func* fx = static_cast<detail::special_destruct_func*>(static_cast<void*>(pref + 1)); Real* mem = static_cast<Real*>(static_cast<void*>(fx + 1)); return *mem; } }; template<typename T> struct getter<std::reference_wrapper<T>> { static T& get(lua_State* L, int index, record& tracking) { return getter<T&>{}.get(L, index, tracking); } }; template<typename... Args> struct getter<std::tuple<Args...>> { typedef std::tuple<decltype(stack::get<Args>(nullptr, 0))...> R; template <typename... TArgs> static R apply(std::index_sequence<>, lua_State*, int, record&, TArgs&&... args) { // Fuck you too, VC++ return R{std::forward<TArgs>(args)...}; } template <std::size_t I, std::size_t... Ix, typename... TArgs> static R apply(std::index_sequence<I, Ix...>, lua_State* L, int index, record& tracking, TArgs&&... args) { // Fuck you too, VC++ typedef std::tuple_element_t<I, std::tuple<Args...>> T; return apply(std::index_sequence<Ix...>(), L, index, tracking, std::forward<TArgs>(args)..., stack::get<T>(L, index + tracking.used, tracking)); } static R get(lua_State* L, int index, record& tracking) { return apply(std::make_index_sequence<sizeof...(Args)>(), L, index, tracking); } }; template<typename A, typename B> struct getter<std::pair<A, B>> { static decltype(auto) get(lua_State* L, int index, record& tracking) { return std::pair<decltype(stack::get<A>(L, index)), decltype(stack::get<B>(L, index))>{stack::get<A>(L, index, tracking), stack::get<B>(L, index + tracking.used, tracking)}; } }; } // stack } // sol // end of sol/stack_get.hpp // beginning of sol/stack_check_get.hpp namespace sol { namespace stack { template <typename T, typename> struct check_getter { typedef decltype(stack_detail::unchecked_get<T>(nullptr, 0, std::declval<record&>())) R; template <typename Handler> static optional<R> get(lua_State* L, int index, Handler&& handler, record& tracking) { if (!check<T>(L, index, std::forward<Handler>(handler))) { tracking.use(static_cast<int>(!lua_isnone(L, index))); return nullopt; } return stack_detail::unchecked_get<T>(L, index, tracking); } }; template <typename T> struct check_getter<optional<T>> { template <typename Handler> static decltype(auto) get(lua_State* L, int index, Handler&&, record& tracking) { return check_get<T>(L, index, no_panic, tracking); } }; template <typename T> struct check_getter<T, std::enable_if_t<std::is_integral<T>::value && lua_type_of<T>::value == type::number>> { template <typename Handler> static optional<T> get(lua_State* L, int index, Handler&& handler, record& tracking) { int isnum = 0; lua_Integer value = lua_tointegerx(L, index, &isnum); if (isnum == 0) { type t = type_of(L, index); tracking.use(static_cast<int>(t != type::none)); handler(L, index, type::number, t); return nullopt; } tracking.use(1); return static_cast<T>(value); } }; template <typename T> struct check_getter<T, std::enable_if_t<std::is_enum<T>::value && !meta::any_same<T, meta_function, type>::value>> { template <typename Handler> static optional<T> get(lua_State* L, int index, Handler&& handler, record& tracking) { int isnum = 0; lua_Integer value = lua_tointegerx(L, index, &isnum); if (isnum == 0) { type t = type_of(L, index); tracking.use(static_cast<int>(t != type::none)); handler(L, index, type::number, t); return nullopt; } tracking.use(1); return static_cast<T>(value); } }; template <typename T> struct check_getter<T, std::enable_if_t<std::is_floating_point<T>::value>> { template <typename Handler> static optional<T> get(lua_State* L, int index, Handler&& handler, record& tracking) { int isnum = 0; lua_Number value = lua_tonumberx(L, index, &isnum); if (isnum == 0) { type t = type_of(L, index); tracking.use(static_cast<int>(t != type::none)); handler(L, index, type::number, t); return nullopt; } tracking.use(1); return static_cast<T>(value); } }; template <typename T> struct getter<optional<T>> { static decltype(auto) get(lua_State* L, int index, record& tracking) { return check_get<T>(L, index, no_panic, tracking); } }; } // stack } // sol // end of sol/stack_check_get.hpp // beginning of sol/stack_push.hpp // beginning of sol/raii.hpp namespace sol { namespace detail { struct default_construct { template<typename T, typename... Args> static void construct(T&& obj, Args&&... args) { std::allocator<meta::unqualified_t<T>> alloc{}; alloc.construct(obj, std::forward<Args>(args)...); } template<typename T, typename... Args> void operator()(T&& obj, Args&&... args) const { construct(std::forward<T>(obj), std::forward<Args>(args)...); } }; struct default_destruct { template<typename T> static void destroy(T&& obj) { std::allocator<meta::unqualified_t<T>> alloc{}; alloc.destroy(obj); } template<typename T> void operator()(T&& obj) const { destroy(std::forward<T>(obj)); } }; struct deleter { template <typename T> void operator()(T* p) const { delete p; } }; template <typename T, typename Dx, typename... Args> inline std::unique_ptr<T, Dx> make_unique_deleter(Args&&... args) { return std::unique_ptr<T, Dx>(new T(std::forward<Args>(args)...)); } template <typename Tag, typename T> struct tagged { T value; template <typename Arg, typename... Args, meta::disable<std::is_same<meta::unqualified_t<Arg>, tagged>> = meta::enabler> tagged(Arg&& arg, Args&&... args) : value(std::forward<Arg>(arg), std::forward<Args>(args)...) {} }; } // detail template <typename... Args> struct constructor_list {}; template<typename... Args> using constructors = constructor_list<Args...>; const auto default_constructor = constructors<types<>>{}; struct no_construction {}; const auto no_constructor = no_construction{}; struct call_construction {}; const auto call_constructor = call_construction{}; template <typename... Functions> struct constructor_wrapper { std::tuple<Functions...> functions; template <typename Arg, typename... Args, meta::disable<std::is_same<meta::unqualified_t<Arg>, constructor_wrapper>> = meta::enabler> constructor_wrapper(Arg&& arg, Args&&... args) : functions(std::forward<Arg>(arg), std::forward<Args>(args)...) {} }; template <typename... Functions> inline auto initializers(Functions&&... functions) { return constructor_wrapper<std::decay_t<Functions>...>(std::forward<Functions>(functions)...); } template <typename... Functions> struct factory_wrapper { std::tuple<Functions...> functions; template <typename Arg, typename... Args, meta::disable<std::is_same<meta::unqualified_t<Arg>, factory_wrapper>> = meta::enabler> factory_wrapper(Arg&& arg, Args&&... args) : functions(std::forward<Arg>(arg), std::forward<Args>(args)...) {} }; template <typename... Functions> inline auto factories(Functions&&... functions) { return factory_wrapper<std::decay_t<Functions>...>(std::forward<Functions>(functions)...); } template <typename Function> struct destructor_wrapper { Function fx; destructor_wrapper(Function f) : fx(std::move(f)) {} }; template <> struct destructor_wrapper<void> {}; const destructor_wrapper<void> default_destructor{}; template <typename Fx> inline auto destructor(Fx&& fx) { return destructor_wrapper<std::decay_t<Fx>>(std::forward<Fx>(fx)); } } // sol // end of sol/raii.hpp #ifdef SOL_CODECVT_SUPPORT #endif namespace sol { namespace stack { template <typename T> struct pusher<detail::as_value_tag<T>> { template <typename F, typename... Args> static int push_fx(lua_State* L, F&& f, Args&&... args) { // Basically, we store all user-data like this: // If it's a movable/copyable value (no std::ref(x)), then we store the pointer to the new // data in the first sizeof(T*) bytes, and then however many bytes it takes to // do the actual object. Things that are std::ref or plain T* are stored as // just the sizeof(T*), and nothing else. T** pointerpointer = static_cast<T**>(lua_newuserdata(L, sizeof(T*) + sizeof(T))); T*& referencereference = *pointerpointer; T* allocationtarget = reinterpret_cast<T*>(pointerpointer + 1); referencereference = allocationtarget; std::allocator<T> alloc{}; alloc.construct(allocationtarget, std::forward<Args>(args)...); f(); return 1; } template <typename K, typename... Args> static int push_keyed(lua_State* L, K&& k, Args&&... args) { return push_fx(L, [&L, &k]() { luaL_newmetatable(L, &k[0]); lua_setmetatable(L, -2); }, std::forward<Args>(args)...); } template <typename... Args> static int push(lua_State* L, Args&&... args) { return push_keyed(L, usertype_traits<T>::metatable, std::forward<Args>(args)...); } }; template <typename T> struct pusher<detail::as_pointer_tag<T>> { template <typename F> static int push_fx(lua_State* L, F&& f, T* obj) { if (obj == nullptr) return stack::push(L, nil); T** pref = static_cast<T**>(lua_newuserdata(L, sizeof(T*))); *pref = obj; f(); return 1; } template <typename K> static int push_keyed(lua_State* L, K&& k, T* obj) { return push_fx(L, [&L, &k]() { luaL_newmetatable(L, &k[0]); lua_setmetatable(L, -2); }, obj); } static int push(lua_State* L, T* obj) { return push_keyed(L, usertype_traits<meta::unqualified_t<T>*>::metatable, obj); } }; template <> struct pusher<detail::as_reference_tag> { template <typename T> static int push(lua_State* L, T&& obj) { return stack::push(L, detail::ptr(obj)); } }; template<typename T, typename> struct pusher { template <typename... Args> static int push(lua_State* L, Args&&... args) { return pusher<detail::as_value_tag<T>>{}.push(L, std::forward<Args>(args)...); } }; template<typename T> struct pusher<T*, meta::disable_if_t<meta::all<meta::has_begin_end<meta::unqualified_t<T>>, meta::neg<meta::any<std::is_base_of<reference, meta::unqualified_t<T>>, std::is_base_of<stack_reference, meta::unqualified_t<T>>>>>::value>> { template <typename... Args> static int push(lua_State* L, Args&&... args) { return pusher<detail::as_pointer_tag<T>>{}.push(L, std::forward<Args>(args)...); } }; template<typename T> struct pusher<T, std::enable_if_t<is_unique_usertype<T>::value>> { typedef typename unique_usertype_traits<T>::type P; typedef typename unique_usertype_traits<T>::actual_type Real; template <typename Arg, meta::enable<std::is_base_of<Real, meta::unqualified_t<Arg>>> = meta::enabler> static int push(lua_State* L, Arg&& arg) { if (unique_usertype_traits<T>::is_null(arg)) return stack::push(L, nil); return push_deep(L, std::forward<Arg>(arg)); } template <typename Arg0, typename Arg1, typename... Args> static int push(lua_State* L, Arg0&& arg0, Arg0&& arg1, Args&&... args) { return push_deep(L, std::forward<Arg0>(arg0), std::forward<Arg1>(arg1), std::forward<Args>(args)...); } template <typename... Args> static int push_deep(lua_State* L, Args&&... args) { P** pref = static_cast<P**>(lua_newuserdata(L, sizeof(P*) + sizeof(detail::special_destruct_func) + sizeof(Real))); detail::special_destruct_func* fx = static_cast<detail::special_destruct_func*>(static_cast<void*>(pref + 1)); Real* mem = static_cast<Real*>(static_cast<void*>(fx + 1)); *fx = detail::special_destruct<P, Real>; detail::default_construct::construct(mem, std::forward<Args>(args)...); *pref = unique_usertype_traits<T>::get(*mem); if (luaL_newmetatable(L, &usertype_traits<detail::unique_usertype<P>>::metatable[0]) == 1) { set_field(L, "__gc", detail::unique_destruct<P>); } lua_setmetatable(L, -2); return 1; } }; template<typename T> struct pusher<std::reference_wrapper<T>> { static int push(lua_State* L, const std::reference_wrapper<T>& t) { return stack::push(L, std::addressof(detail::deref(t.get()))); } }; template<typename T> struct pusher<T, std::enable_if_t<std::is_floating_point<T>::value>> { static int push(lua_State* L, const T& value) { lua_pushnumber(L, value); return 1; } }; template<typename T> struct pusher<T, std::enable_if_t<meta::all<std::is_integral<T>, std::is_signed<T>>::value>> { static int push(lua_State* L, const T& value) { lua_pushinteger(L, static_cast<lua_Integer>(value)); return 1; } }; template<typename T> struct pusher<T, std::enable_if_t<std::is_enum<T>::value>> { static int push(lua_State* L, const T& value) { if (std::is_same<char, T>::value) { return stack::push(L, static_cast<int>(value)); } return stack::push(L, static_cast<std::underlying_type_t<T>>(value)); } }; template<typename T> struct pusher<T, std::enable_if_t<meta::all<std::is_integral<T>, std::is_unsigned<T>>::value>> { static int push(lua_State* L, const T& value) { lua_pushinteger(L, static_cast<lua_Integer>(value)); return 1; } }; template<typename T> struct pusher<as_table_t<T>, std::enable_if_t<!meta::has_key_value_pair<meta::unqualified_t<std::remove_pointer_t<T>>>::value>> { static int push(lua_State* L, const as_table_t<T>& tablecont) { auto& cont = detail::deref(detail::unwrap(tablecont.source)); lua_createtable(L, static_cast<int>(cont.size()), 0); int tableindex = lua_gettop(L); std::size_t index = 1; for (const auto& i : cont) { #if SOL_LUA_VERSION >= 503 int p = stack::push(L, i); for (int pi = 0; pi < p; ++pi) { lua_seti(L, tableindex, static_cast<lua_Integer>(index++)); } #else lua_pushinteger(L, static_cast<lua_Integer>(index)); int p = stack::push(L, i); if (p == 1) { ++index; lua_settable(L, tableindex); } else { int firstindex = tableindex + 1 + 1; for (int pi = 0; pi < p; ++pi) { stack::push(L, index); lua_pushvalue(L, firstindex); lua_settable(L, tableindex); ++index; ++firstindex; } lua_pop(L, 1 + p); } #endif } // TODO: figure out a better way to do this...? //set_field(L, -1, cont.size()); return 1; } }; template<typename T> struct pusher<as_table_t<T>, std::enable_if_t<meta::has_key_value_pair<meta::unqualified_t<std::remove_pointer_t<T>>>::value>> { static int push(lua_State* L, const as_table_t<T>& tablecont) { auto& cont = detail::deref(detail::unwrap(tablecont.source)); lua_createtable(L, static_cast<int>(cont.size()), 0); int tableindex = lua_gettop(L); for (const auto& pair : cont) { set_field(L, pair.first, pair.second, tableindex); } return 1; } }; template<typename T> struct pusher<T, std::enable_if_t<std::is_base_of<reference, T>::value || std::is_base_of<stack_reference, T>::value>> { static int push(lua_State*, const T& ref) { return ref.push(); } static int push(lua_State*, T&& ref) { return ref.push(); } }; template<> struct pusher<bool> { static int push(lua_State* L, bool b) { lua_pushboolean(L, b); return 1; } }; template<> struct pusher<nil_t> { static int push(lua_State* L, nil_t) { lua_pushnil(L); return 1; } }; template<> struct pusher<metatable_key_t> { static int push(lua_State* L, metatable_key_t) { lua_pushlstring(L, "__mt", 4); return 1; } }; template<> struct pusher<std::remove_pointer_t<lua_CFunction>> { static int push(lua_State* L, lua_CFunction func, int n = 0) { lua_pushcclosure(L, func, n); return 1; } }; template<> struct pusher<lua_CFunction> { static int push(lua_State* L, lua_CFunction func, int n = 0) { lua_pushcclosure(L, func, n); return 1; } }; template<> struct pusher<c_closure> { static int push(lua_State* L, c_closure cc) { lua_pushcclosure(L, cc.c_function, cc.upvalues); return 1; } }; template<typename Arg, typename... Args> struct pusher<closure<Arg, Args...>> { template <std::size_t... I, typename T> static int push(std::index_sequence<I...>, lua_State* L, T&& c) { int pushcount = multi_push(L, detail::forward_get<I>(c.upvalues)...); return stack::push(L, c_closure(c.c_function, pushcount)); } template <typename T> static int push(lua_State* L, T&& c) { return push(std::make_index_sequence<1 + sizeof...(Args)>(), L, std::forward<T>(c)); } }; template<> struct pusher<void*> { static int push(lua_State* L, void* userdata) { lua_pushlightuserdata(L, userdata); return 1; } }; template<> struct pusher<lightuserdata_value> { static int push(lua_State* L, lightuserdata_value userdata) { lua_pushlightuserdata(L, userdata); return 1; } }; template<typename T> struct pusher<light<T>> { static int push(lua_State* L, light<T> l) { lua_pushlightuserdata(L, static_cast<void*>(l.value)); return 1; } }; template<typename T> struct pusher<user<T>> { template <bool with_meta = true, typename Key, typename... Args> static int push_with(lua_State* L, Key&& name, Args&&... args) { // A dumb pusher void* rawdata = lua_newuserdata(L, sizeof(T)); T* data = static_cast<T*>(rawdata); std::allocator<T> alloc; alloc.construct(data, std::forward<Args>(args)...); if (with_meta) { lua_CFunction cdel = detail::user_alloc_destroy<T>; // Make sure we have a plain GC set for this data if (luaL_newmetatable(L, name) != 0) { lua_pushlightuserdata(L, rawdata); lua_pushcclosure(L, cdel, 1); lua_setfield(L, -2, "__gc"); } lua_setmetatable(L, -2); } return 1; } template <typename Arg, typename... Args, meta::disable<meta::any_same<meta::unqualified_t<Arg>, no_metatable_t, metatable_key_t>> = meta::enabler> static int push(lua_State* L, Arg&& arg, Args&&... args) { const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable[0]; return push_with(L, name, std::forward<Arg>(arg), std::forward<Args>(args)...); } template <typename... Args> static int push(lua_State* L, no_metatable_t, Args&&... args) { const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable[0]; return push_with<false>(L, name, std::forward<Args>(args)...); } template <typename Key, typename... Args> static int push(lua_State* L, metatable_key_t, Key&& key, Args&&... args) { const auto name = &key[0]; return push_with<true>(L, name, std::forward<Args>(args)...); } static int push(lua_State* L, const user<T>& u) { const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable[0]; return push_with(L, name, u.value); } static int push(lua_State* L, user<T>&& u) { const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable[0]; return push_with(L, name, std::move(u.value)); } static int push(lua_State* L, no_metatable_t, const user<T>& u) { const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable[0]; return push_with<false>(L, name, u.value); } static int push(lua_State* L, no_metatable_t, user<T>&& u) { const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable[0]; return push_with<false>(L, name, std::move(u.value)); } }; template<> struct pusher<userdata_value> { static int push(lua_State* L, userdata_value data) { void** ud = static_cast<void**>(lua_newuserdata(L, sizeof(void*))); *ud = data.value; return 1; } }; template<> struct pusher<const char*> { static int push_sized(lua_State* L, const char* str, std::size_t len) { lua_pushlstring(L, str, len); return 1; } static int push(lua_State* L, const char* str) { return push_sized(L, str, std::char_traits<char>::length(str)); } static int push(lua_State* L, const char* strb, const char* stre) { return push_sized(L, strb, stre - strb); } static int push(lua_State* L, const char* str, std::size_t len) { return push_sized(L, str, len); } }; template<size_t N> struct pusher<char[N]> { static int push(lua_State* L, const char(&str)[N]) { lua_pushlstring(L, str, N - 1); return 1; } static int push(lua_State* L, const char(&str)[N], std::size_t sz) { lua_pushlstring(L, str, sz); return 1; } }; template <> struct pusher<char> { static int push(lua_State* L, char c) { const char str[2] = { c, '\0' }; return stack::push(L, str, 1); } }; template<> struct pusher<std::string> { static int push(lua_State* L, const std::string& str) { lua_pushlstring(L, str.c_str(), str.size()); return 1; } static int push(lua_State* L, const std::string& str, std::size_t sz) { lua_pushlstring(L, str.c_str(), sz); return 1; } }; template<> struct pusher<meta_function> { static int push(lua_State* L, meta_function m) { const std::string& str = name_of(m); lua_pushlstring(L, str.c_str(), str.size()); return 1; } }; #ifdef SOL_CODECVT_SUPPORT template<> struct pusher<const wchar_t*> { static int push(lua_State* L, const wchar_t* wstr) { return push(L, wstr, std::char_traits<wchar_t>::length(wstr)); } static int push(lua_State* L, const wchar_t* wstr, std::size_t sz) { return push(L, wstr, wstr + sz); } static int push(lua_State* L, const wchar_t* strb, const wchar_t* stre) { if (sizeof(wchar_t) == 2) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert; std::string u8str = convert.to_bytes(strb, stre); return stack::push(L, u8str); } std::wstring_convert<std::codecvt_utf8<wchar_t>> convert; std::string u8str = convert.to_bytes(strb, stre); return stack::push(L, u8str); } }; template<> struct pusher<const char16_t*> { static int push(lua_State* L, const char16_t* u16str) { return push(L, u16str, std::char_traits<char16_t>::length(u16str)); } static int push(lua_State* L, const char16_t* u16str, std::size_t sz) { return push(L, u16str, u16str + sz); } static int push(lua_State* L, const char16_t* strb, const char16_t* stre) { #ifdef _MSC_VER std::wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t> convert; std::string u8str = convert.to_bytes(reinterpret_cast<const int16_t*>(strb), reinterpret_cast<const int16_t*>(stre)); #else std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert; std::string u8str = convert.to_bytes(strb, stre); #endif // VC++ is a shit return stack::push(L, u8str); } }; template<> struct pusher<const char32_t*> { static int push(lua_State* L, const char32_t* u32str) { return push(L, u32str, u32str + std::char_traits<char32_t>::length(u32str)); } static int push(lua_State* L, const char32_t* u32str, std::size_t sz) { return push(L, u32str, u32str + sz); } static int push(lua_State* L, const char32_t* strb, const char32_t* stre) { #ifdef _MSC_VER std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> convert; std::string u8str = convert.to_bytes(reinterpret_cast<const int32_t*>(strb), reinterpret_cast<const int32_t*>(stre)); #else std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; std::string u8str = convert.to_bytes(strb, stre); #endif // VC++ is a shit return stack::push(L, u8str); } }; template<size_t N> struct pusher<wchar_t[N]> { static int push(lua_State* L, const wchar_t(&str)[N]) { return push(L, str, N - 1); } static int push(lua_State* L, const wchar_t(&str)[N], std::size_t sz) { return stack::push<const wchar_t*>(L, str, str + sz); } }; template<size_t N> struct pusher<char16_t[N]> { static int push(lua_State* L, const char16_t(&str)[N]) { return push(L, str, N - 1); } static int push(lua_State* L, const char16_t(&str)[N], std::size_t sz) { return stack::push<const char16_t*>(L, str, str + sz); } }; template<size_t N> struct pusher<char32_t[N]> { static int push(lua_State* L, const char32_t(&str)[N]) { return push(L, str, N - 1); } static int push(lua_State* L, const char32_t(&str)[N], std::size_t sz) { return stack::push<const char32_t*>(L, str, str + sz); } }; template <> struct pusher<wchar_t> { static int push(lua_State* L, wchar_t c) { const wchar_t str[2] = { c, '\0' }; return stack::push(L, str, 1); } }; template <> struct pusher<char16_t> { static int push(lua_State* L, char16_t c) { const char16_t str[2] = { c, '\0' }; return stack::push(L, str, 1); } }; template <> struct pusher<char32_t> { static int push(lua_State* L, char32_t c) { const char32_t str[2] = { c, '\0' }; return stack::push(L, str, 1); } }; template<> struct pusher<std::wstring> { static int push(lua_State* L, const std::wstring& wstr) { return push(L, wstr.data(), wstr.size()); } static int push(lua_State* L, const std::wstring& wstr, std::size_t sz) { return stack::push(L, wstr.data(), wstr.data() + sz); } }; template<> struct pusher<std::u16string> { static int push(lua_State* L, const std::u16string& u16str) { return push(L, u16str, u16str.size()); } static int push(lua_State* L, const std::u16string& u16str, std::size_t sz) { return stack::push(L, u16str.data(), u16str.data() + sz); } }; template<> struct pusher<std::u32string> { static int push(lua_State* L, const std::u32string& u32str) { return push(L, u32str, u32str.size()); } static int push(lua_State* L, const std::u32string& u32str, std::size_t sz) { return stack::push(L, u32str.data(), u32str.data() + sz); } }; #endif // codecvt Header Support template<typename... Args> struct pusher<std::tuple<Args...>> { template <std::size_t... I, typename T> static int push(std::index_sequence<I...>, lua_State* L, T&& t) { int pushcount = 0; (void)detail::swallow{ 0, (pushcount += stack::push(L, detail::forward_get<I>(t) ), 0)... }; return pushcount; } template <typename T> static int push(lua_State* L, T&& t) { return push(std::index_sequence_for<Args...>(), L, std::forward<T>(t)); } }; template<typename A, typename B> struct pusher<std::pair<A, B>> { template <typename T> static int push(lua_State* L, T&& t) { int pushcount = stack::push(L, detail::forward_get<0>(t)); pushcount += stack::push(L, detail::forward_get<1>(t)); return pushcount; } }; template<typename O> struct pusher<optional<O>> { template <typename T> static int push(lua_State* L, T&& t) { if (t == nullopt) { return stack::push(L, nullopt); } return stack::push(L, t.value()); } }; template<> struct pusher<nullopt_t> { static int push(lua_State* L, nullopt_t) { return stack::push(L, nil); } }; template<> struct pusher<std::nullptr_t> { static int push(lua_State* L, std::nullptr_t) { return stack::push(L, nil); } }; template<> struct pusher<this_state> { static int push(lua_State*, const this_state&) { return 0; } }; } // stack } // sol // end of sol/stack_push.hpp // beginning of sol/stack_pop.hpp namespace sol { namespace stack { template <typename T, typename> struct popper { inline static decltype(auto) pop(lua_State* L) { record tracking{}; decltype(auto) r = get<T>(L, -lua_size<T>::value, tracking); lua_pop(L, tracking.used); return r; } }; template <typename T> struct popper<T, std::enable_if_t<std::is_base_of<stack_reference, meta::unqualified_t<T>>::value>> { static_assert(meta::neg<std::is_base_of<stack_reference, meta::unqualified_t<T>>>::value, "You cannot pop something that derives from stack_reference: it will not remain on the stack and thusly will go out of scope!"); }; } // stack } // sol // end of sol/stack_pop.hpp // beginning of sol/stack_field.hpp namespace sol { namespace stack { template <typename T, bool, bool, typename> struct field_getter { template <typename Key> void get(lua_State* L, Key&& key, int tableindex = -2) { push(L, std::forward<Key>(key)); lua_gettable(L, tableindex); } }; template <typename T, bool global, typename C> struct field_getter<T, global, true, C> { template <typename Key> void get(lua_State* L, Key&& key, int tableindex = -2) { push(L, std::forward<Key>(key)); lua_rawget(L, tableindex); } }; template <bool b, bool raw, typename C> struct field_getter<metatable_key_t, b, raw, C> { void get(lua_State* L, metatable_key_t, int tableindex = -1) { if (lua_getmetatable(L, tableindex) == 0) push(L, nil); } }; template <typename T, bool raw> struct field_getter<T, true, raw, std::enable_if_t<meta::is_c_str<T>::value>> { template <typename Key> void get(lua_State* L, Key&& key, int = -1) { lua_getglobal(L, &key[0]); } }; template <typename T> struct field_getter<T, false, false, std::enable_if_t<meta::is_c_str<T>::value>> { template <typename Key> void get(lua_State* L, Key&& key, int tableindex = -1) { lua_getfield(L, tableindex, &key[0]); } }; #if SOL_LUA_VERSION >= 503 template <typename T> struct field_getter<T, false, false, std::enable_if_t<std::is_integral<T>::value>> { template <typename Key> void get(lua_State* L, Key&& key, int tableindex = -1) { lua_geti(L, tableindex, static_cast<lua_Integer>(key)); } }; #endif // Lua 5.3.x #if SOL_LUA_VERSION >= 502 template <typename C> struct field_getter<void*, false, true, C> { void get(lua_State* L, void* key, int tableindex = -1) { lua_rawgetp(L, tableindex, key); } }; #endif // Lua 5.3.x template <typename T> struct field_getter<T, false, true, std::enable_if_t<std::is_integral<T>::value>> { template <typename Key> void get(lua_State* L, Key&& key, int tableindex = -1) { lua_rawgeti(L, tableindex, static_cast<lua_Integer>(key)); } }; template <typename... Args, bool b, bool raw, typename C> struct field_getter<std::tuple<Args...>, b, raw, C> { template <std::size_t... I, typename Keys> void apply(std::index_sequence<0, I...>, lua_State* L, Keys&& keys, int tableindex) { get_field<b, raw>(L, detail::forward_get<0>(keys), tableindex); void(detail::swallow{ (get_field<false, raw>(L, detail::forward_get<I>(keys)), 0)... }); reference saved(L, -1); lua_pop(L, static_cast<int>(sizeof...(I))); saved.push(); } template <typename Keys> void get(lua_State* L, Keys&& keys) { apply(std::make_index_sequence<sizeof...(Args)>(), L, std::forward<Keys>(keys), lua_absindex(L, -1)); } template <typename Keys> void get(lua_State* L, Keys&& keys, int tableindex) { apply(std::make_index_sequence<sizeof...(Args)>(), L, std::forward<Keys>(keys), tableindex); } }; template <typename A, typename B, bool b, bool raw, typename C> struct field_getter<std::pair<A, B>, b, raw, C> { template <typename Keys> void get(lua_State* L, Keys&& keys, int tableindex) { get_field<b, raw>(L, detail::forward_get<0>(keys), tableindex); get_field<false, raw>(L, detail::forward_get<1>(keys)); reference saved(L, -1); lua_pop(L, static_cast<int>(2)); saved.push(); } template <typename Keys> void get(lua_State* L, Keys&& keys) { get_field<b, raw>(L, detail::forward_get<0>(keys)); get_field<false, raw>(L, detail::forward_get<1>(keys)); reference saved(L, -1); lua_pop(L, static_cast<int>(2)); saved.push(); } }; template <typename T, bool, bool, typename> struct field_setter { template <typename Key, typename Value> void set(lua_State* L, Key&& key, Value&& value, int tableindex = -3) { push(L, std::forward<Key>(key)); push(L, std::forward<Value>(value)); lua_settable(L, tableindex); } }; template <typename T, bool b, typename C> struct field_setter<T, b, true, C> { template <typename Key, typename Value> void set(lua_State* L, Key&& key, Value&& value, int tableindex = -3) { push(L, std::forward<Key>(key)); push(L, std::forward<Value>(value)); lua_rawset(L, tableindex); } }; template <bool b, bool raw, typename C> struct field_setter<metatable_key_t, b, raw, C> { template <typename Value> void set(lua_State* L, metatable_key_t, Value&& value, int tableindex = -2) { push(L, std::forward<Value>(value)); lua_setmetatable(L, tableindex); } }; template <typename T, bool raw> struct field_setter<T, true, raw, std::enable_if_t<meta::is_c_str<T>::value>> { template <typename Key, typename Value> void set(lua_State* L, Key&& key, Value&& value, int = -2) { push(L, std::forward<Value>(value)); lua_setglobal(L, &key[0]); } }; template <typename T> struct field_setter<T, false, false, std::enable_if_t<meta::is_c_str<T>::value>> { template <typename Key, typename Value> void set(lua_State* L, Key&& key, Value&& value, int tableindex = -2) { push(L, std::forward<Value>(value)); lua_setfield(L, tableindex, &key[0]); } }; #if SOL_LUA_VERSION >= 503 template <typename T> struct field_setter<T, false, false, std::enable_if_t<std::is_integral<T>::value>> { template <typename Key, typename Value> void set(lua_State* L, Key&& key, Value&& value, int tableindex = -2) { push(L, std::forward<Value>(value)); lua_seti(L, tableindex, static_cast<lua_Integer>(key)); } }; #endif // Lua 5.3.x template <typename T> struct field_setter<T, false, true, std::enable_if_t<std::is_integral<T>::value>> { template <typename Key, typename Value> void set(lua_State* L, Key&& key, Value&& value, int tableindex = -2) { push(L, std::forward<Value>(value)); lua_rawseti(L, tableindex, static_cast<lua_Integer>(key)); } }; #if SOL_LUA_VERSION >= 502 template <typename C> struct field_setter<void*, false, true, C> { template <typename Key, typename Value> void set(lua_State* L, void* key, Value&& value, int tableindex = -2) { push(L, std::forward<Value>(value)); lua_rawsetp(L, tableindex, key); } }; #endif // Lua 5.2.x template <typename... Args, bool b, bool raw, typename C> struct field_setter<std::tuple<Args...>, b, raw, C> { template <bool g, std::size_t I, typename Key, typename Value> void apply(std::index_sequence<I>, lua_State* L, Key&& keys, Value&& value, int tableindex) { I < 1 ? set_field<g, raw>(L, detail::forward_get<I>(keys), std::forward<Value>(value), tableindex) : set_field<g, raw>(L, detail::forward_get<I>(keys), std::forward<Value>(value)); } template <bool g, std::size_t I0, std::size_t I1, std::size_t... I, typename Keys, typename Value> void apply(std::index_sequence<I0, I1, I...>, lua_State* L, Keys&& keys, Value&& value, int tableindex) { I0 < 1 ? get_field<g, raw>(L, detail::forward_get<I0>(keys), tableindex) : get_field<g, raw>(L, detail::forward_get<I0>(keys), -1); apply<false>(std::index_sequence<I1, I...>(), L, std::forward<Keys>(keys), std::forward<Value>(value), -1); } template <bool g, std::size_t I0, std::size_t... I, typename Keys, typename Value> void top_apply(std::index_sequence<I0, I...>, lua_State* L, Keys&& keys, Value&& value, int tableindex) { apply<g>(std::index_sequence<I0, I...>(), L, std::forward<Keys>(keys), std::forward<Value>(value), tableindex); lua_pop(L, static_cast<int>(sizeof...(I))); } template <typename Keys, typename Value> void set(lua_State* L, Keys&& keys, Value&& value, int tableindex = -3) { top_apply<b>(std::make_index_sequence<sizeof...(Args)>(), L, std::forward<Keys>(keys), std::forward<Value>(value), tableindex); } }; template <typename A, typename B, bool b, bool raw, typename C> struct field_setter<std::pair<A, B>, b, raw, C> { template <typename Keys, typename Value> void set(lua_State* L, Keys&& keys, Value&& value, int tableindex = -1) { get_field<b, raw>(L, detail::forward_get<0>(keys), tableindex); set_field<false, raw>(L, detail::forward_get<1>(keys), std::forward<Value>(value)); lua_pop(L, 1); } }; } // stack } // sol // end of sol/stack_field.hpp // beginning of sol/stack_probe.hpp namespace sol { namespace stack { template <typename T, bool b, bool raw, typename> struct probe_field_getter { template <typename Key> probe get(lua_State* L, Key&& key, int tableindex = -2) { if (!b && !maybe_indexable(L, tableindex)) { return probe(false, 0); } get_field<b, raw>(L, std::forward<Key>(key), tableindex); return probe(!check<nil_t>(L), 1); } }; template <typename A, typename B, bool b, bool raw, typename C> struct probe_field_getter<std::pair<A, B>, b, raw, C> { template <typename Keys> probe get(lua_State* L, Keys&& keys, int tableindex = -2) { if (!b && !maybe_indexable(L, tableindex)) { return probe(false, 0); } get_field<b, raw>(L, std::get<0>(keys), tableindex); if (!maybe_indexable(L)) { return probe(false, 1); } get_field<false, raw>(L, std::get<1>(keys), tableindex); return probe(!check<nil_t>(L), 2); } }; template <typename... Args, bool b, bool raw, typename C> struct probe_field_getter<std::tuple<Args...>, b, raw, C> { template <std::size_t I, typename Keys> probe apply(std::index_sequence<I>, int sofar, lua_State* L, Keys&& keys, int tableindex) { get_field < I < 1 && b, raw>(L, std::get<I>(keys), tableindex); return probe(!check<nil_t>(L), sofar); } template <std::size_t I, std::size_t I1, std::size_t... In, typename Keys> probe apply(std::index_sequence<I, I1, In...>, int sofar, lua_State* L, Keys&& keys, int tableindex) { get_field < I < 1 && b, raw>(L, std::get<I>(keys), tableindex); if (!maybe_indexable(L)) { return probe(false, sofar); } return apply(std::index_sequence<I1, In...>(), sofar + 1, L, std::forward<Keys>(keys), -1); } template <typename Keys> probe get(lua_State* L, Keys&& keys, int tableindex = -2) { if (!b && !maybe_indexable(L, tableindex)) { return probe(false, 0); } return apply(std::index_sequence_for<Args...>(), 1, L, std::forward<Keys>(keys), tableindex); } }; } // stack } // sol // end of sol/stack_probe.hpp #include <cstring> namespace sol { namespace stack { namespace stack_detail { template<typename T> inline int push_as_upvalues(lua_State* L, T& item) { typedef std::decay_t<T> TValue; const static std::size_t itemsize = sizeof(TValue); const static std::size_t voidsize = sizeof(void*); const static std::size_t voidsizem1 = voidsize - 1; const static std::size_t data_t_count = (sizeof(TValue) + voidsizem1) / voidsize; typedef std::array<void*, data_t_count> data_t; data_t data{ {} }; std::memcpy(&data[0], std::addressof(item), itemsize); int pushcount = 0; for (auto&& v : data) { pushcount += push(L, lightuserdata_value(v)); } return pushcount; } template<typename T> inline std::pair<T, int> get_as_upvalues(lua_State* L, int index = 1) { const static std::size_t data_t_count = (sizeof(T) + (sizeof(void*) - 1)) / sizeof(void*); typedef std::array<void*, data_t_count> data_t; data_t voiddata{ {} }; for (std::size_t i = 0, d = 0; d < sizeof(T); ++i, d += sizeof(void*)) { voiddata[i] = get<lightuserdata_value>(L, upvalue_index(index++)); } return std::pair<T, int>(*reinterpret_cast<T*>(static_cast<void*>(voiddata.data())), index); } struct evaluator { template <typename Fx, typename... Args> static decltype(auto) eval(types<>, std::index_sequence<>, lua_State*, int, record&, Fx&& fx, Args&&... args) { return std::forward<Fx>(fx)(std::forward<Args>(args)...); } template <typename Fx, typename Arg, typename... Args, std::size_t I, std::size_t... Is, typename... FxArgs> static decltype(auto) eval(types<Arg, Args...>, std::index_sequence<I, Is...>, lua_State* L, int start, record& tracking, Fx&& fx, FxArgs&&... fxargs) { return eval(types<Args...>(), std::index_sequence<Is...>(), L, start, tracking, std::forward<Fx>(fx), std::forward<FxArgs>(fxargs)..., stack_detail::unchecked_get<Arg>(L, start + tracking.used, tracking)); } }; template <bool checkargs = default_check_arguments, std::size_t... I, typename R, typename... Args, typename Fx, typename... FxArgs, typename = std::enable_if_t<!std::is_void<R>::value>> inline decltype(auto) call(types<R>, types<Args...> ta, std::index_sequence<I...> tai, lua_State* L, int start, Fx&& fx, FxArgs&&... args) { #ifndef _MSC_VER static_assert(meta::all<meta::is_not_move_only<Args>...>::value, "One of the arguments being bound is a move-only type, and it is not being taken by reference: this will break your code. Please take a reference and std::move it manually if this was your intention."); #endif // This compiler make me so fucking sad multi_check<checkargs, Args...>(L, start, type_panic); record tracking{}; return evaluator{}.eval(ta, tai, L, start, tracking, std::forward<Fx>(fx), std::forward<FxArgs>(args)...); } template <bool checkargs = default_check_arguments, std::size_t... I, typename... Args, typename Fx, typename... FxArgs> inline void call(types<void>, types<Args...> ta, std::index_sequence<I...> tai, lua_State* L, int start, Fx&& fx, FxArgs&&... args) { #ifndef _MSC_VER static_assert(meta::all<meta::is_not_move_only<Args>...>::value, "One of the arguments being bound is a move-only type, and it is not being taken by reference: this will break your code. Please take a reference and std::move it manually if this was your intention."); #endif // This compiler make me so fucking sad multi_check<checkargs, Args...>(L, start, type_panic); record tracking{}; evaluator{}.eval(ta, tai, L, start, tracking, std::forward<Fx>(fx), std::forward<FxArgs>(args)...); } } // stack_detail template <typename T> int set_ref(lua_State* L, T&& arg, int tableindex = -2) { push(L, std::forward<T>(arg)); return luaL_ref(L, tableindex); } inline void remove(lua_State* L, int index, int count) { if (count < 1) return; int top = lua_gettop(L); if (index == -1 || top == index) { // Slice them right off the top lua_pop(L, static_cast<int>(count)); return; } // Remove each item one at a time using stack operations // Probably slower, maybe, haven't benchmarked, // but necessary if (index < 0) { index = lua_gettop(L) + (index + 1); } int last = index + count; for (int i = index; i < last; ++i) { lua_remove(L, i); } } template <bool check_args = stack_detail::default_check_arguments, typename R, typename... Args, typename Fx, typename... FxArgs, typename = std::enable_if_t<!std::is_void<R>::value>> inline decltype(auto) call(types<R> tr, types<Args...> ta, lua_State* L, int start, Fx&& fx, FxArgs&&... args) { typedef std::make_index_sequence<sizeof...(Args)> args_indices; return stack_detail::call<check_args>(tr, ta, args_indices(), L, start, std::forward<Fx>(fx), std::forward<FxArgs>(args)...); } template <bool check_args = stack_detail::default_check_arguments, typename R, typename... Args, typename Fx, typename... FxArgs, typename = std::enable_if_t<!std::is_void<R>::value>> inline decltype(auto) call(types<R> tr, types<Args...> ta, lua_State* L, Fx&& fx, FxArgs&&... args) { return call<check_args>(tr, ta, L, 1, std::forward<Fx>(fx), std::forward<FxArgs>(args)...); } template <bool check_args = stack_detail::default_check_arguments, typename... Args, typename Fx, typename... FxArgs> inline void call(types<void> tr, types<Args...> ta, lua_State* L, int start, Fx&& fx, FxArgs&&... args) { typedef std::make_index_sequence<sizeof...(Args)> args_indices; stack_detail::call<check_args>(tr, ta, args_indices(), L, start, std::forward<Fx>(fx), std::forward<FxArgs>(args)...); } template <bool check_args = stack_detail::default_check_arguments, typename... Args, typename Fx, typename... FxArgs> inline void call(types<void> tr, types<Args...> ta, lua_State* L, Fx&& fx, FxArgs&&... args) { call<check_args>(tr, ta, L, 1, std::forward<Fx>(fx), std::forward<FxArgs>(args)...); } template <bool check_args = stack_detail::default_check_arguments, typename R, typename... Args, typename Fx, typename... FxArgs, typename = std::enable_if_t<!std::is_void<R>::value>> inline decltype(auto) call_from_top(types<R> tr, types<Args...> ta, lua_State* L, Fx&& fx, FxArgs&&... args) { return call<check_args>(tr, ta, L, static_cast<int>(lua_gettop(L) - sizeof...(Args)), std::forward<Fx>(fx), std::forward<FxArgs>(args)...); } template <bool check_args = stack_detail::default_check_arguments, typename... Args, typename Fx, typename... FxArgs> inline void call_from_top(types<void> tr, types<Args...> ta, lua_State* L, Fx&& fx, FxArgs&&... args) { call<check_args>(tr, ta, L, static_cast<int>(lua_gettop(L) - sizeof...(Args)), std::forward<Fx>(fx), std::forward<FxArgs>(args)...); } template<bool check_args = stack_detail::default_check_arguments, typename... Args, typename Fx, typename... FxArgs> inline int call_into_lua(types<void> tr, types<Args...> ta, lua_State* L, int start, Fx&& fx, FxArgs&&... fxargs) { call<check_args>(tr, ta, L, start, std::forward<Fx>(fx), std::forward<FxArgs>(fxargs)...); lua_settop(L, 0); return 0; } template<bool check_args = stack_detail::default_check_arguments, typename Ret0, typename... Ret, typename... Args, typename Fx, typename... FxArgs, typename = std::enable_if_t<meta::neg<std::is_void<Ret0>>::value>> inline int call_into_lua(types<Ret0, Ret...>, types<Args...> ta, lua_State* L, int start, Fx&& fx, FxArgs&&... fxargs) { decltype(auto) r = call<check_args>(types<meta::return_type_t<Ret0, Ret...>>(), ta, L, start, std::forward<Fx>(fx), std::forward<FxArgs>(fxargs)...); lua_settop(L, 0); return push_reference(L, std::forward<decltype(r)>(r)); } template<bool check_args = stack_detail::default_check_arguments, typename Fx, typename... FxArgs> inline int call_lua(lua_State* L, int start, Fx&& fx, FxArgs&&... fxargs) { typedef lua_bind_traits<meta::unqualified_t<Fx>> traits_type; typedef typename traits_type::args_list args_list; typedef typename traits_type::returns_list returns_list; return call_into_lua(returns_list(), args_list(), L, start, std::forward<Fx>(fx), std::forward<FxArgs>(fxargs)...); } inline call_syntax get_call_syntax(lua_State* L, const std::string& key, int index = -2) { luaL_getmetatable(L, key.c_str()); auto pn = pop_n(L, 1); if (lua_compare(L, -1, index, LUA_OPEQ) == 1) { return call_syntax::colon; } return call_syntax::dot; } inline void script(lua_State* L, const std::string& code) { if (luaL_dostring(L, code.c_str())) { lua_error(L); } } inline void script_file(lua_State* L, const std::string& filename) { if (luaL_dofile(L, filename.c_str())) { lua_error(L); } } inline void luajit_exception_handler(lua_State* L, int(*handler)(lua_State*, lua_CFunction) = detail::c_trampoline) { #ifdef SOL_LUAJIT lua_pushlightuserdata(L, (void*)handler); auto pn = pop_n(L, 1); luaJIT_setmode(L, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON); #else (void)L; (void)handler; #endif } inline void luajit_exception_off(lua_State* L) { #ifdef SOL_LUAJIT luaJIT_setmode(L, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_OFF); #else (void)L; #endif } } // stack } // sol // end of sol/stack.hpp // beginning of sol/variadic_args.hpp // beginning of sol/stack_proxy.hpp // beginning of sol/function.hpp // beginning of sol/function_result.hpp // beginning of sol/proxy_base.hpp namespace sol { template <typename Super> struct proxy_base { operator std::string() const { const Super& super = *static_cast<const Super*>(static_cast<const void*>(this)); return super.template get<std::string>(); } template<typename T, meta::enable<meta::neg<meta::is_string_constructible<T>>, is_proxy_primitive<meta::unqualified_t<T>>> = meta::enabler> operator T () const { const Super& super = *static_cast<const Super*>(static_cast<const void*>(this)); return super.template get<T>(); } template<typename T, meta::enable<meta::neg<meta::is_string_constructible<T>>, meta::neg<is_proxy_primitive<meta::unqualified_t<T>>>> = meta::enabler> operator T& () const { const Super& super = *static_cast<const Super*>(static_cast<const void*>(this)); return super.template get<T&>(); } }; } // sol // end of sol/proxy_base.hpp #include <cstdint> namespace sol { struct function_result : public proxy_base<function_result> { private: lua_State* L; int index; int returncount; public: function_result() = default; function_result(lua_State* L, int index = -1, int returncount = 0) : L(L), index(index), returncount(returncount) { } function_result(const function_result&) = default; function_result& operator=(const function_result&) = default; function_result(function_result&& o) : L(o.L), index(o.index), returncount(o.returncount) { // Must be manual, otherwise destructor will screw us // return count being 0 is enough to keep things clean // but will be thorough o.L = nullptr; o.index = 0; o.returncount = 0; } function_result& operator=(function_result&& o) { L = o.L; index = o.index; returncount = o.returncount; // Must be manual, otherwise destructor will screw us // return count being 0 is enough to keep things clean // but will be thorough o.L = nullptr; o.index = 0; o.returncount = 0; return *this; } template<typename T> decltype(auto) get() const { return stack::get<T>(L, index); } call_status status() const noexcept { return call_status::ok; } bool valid() const noexcept { return status() == call_status::ok || status() == call_status::yielded; } lua_State* lua_state() const { return L; }; int stack_index() const { return index; }; ~function_result() { lua_pop(L, returncount); } }; } // sol // end of sol/function_result.hpp // beginning of sol/function_types.hpp // beginning of sol/function_types_core.hpp // beginning of sol/wrapper.hpp namespace sol { template <typename F, typename = void> struct wrapper { typedef lua_bind_traits<F> traits_type; typedef typename traits_type::args_list args_list; typedef typename traits_type::args_list free_args_list; typedef typename traits_type::returns_list returns_list; template <typename... Args> static decltype(auto) call(F& f, Args&&... args) { return f(std::forward<Args>(args)...); } struct caller { template <typename... Args> decltype(auto) operator()(F& fx, Args&&... args) const { return call(fx, std::forward<Args>(args)...); } }; }; template <typename F> struct wrapper<F, std::enable_if_t<std::is_function<meta::unqualified_t<std::remove_pointer_t<F>>>::value>> { typedef lua_bind_traits<F> traits_type; typedef typename traits_type::args_list args_list; typedef typename traits_type::args_list free_args_list; typedef typename traits_type::returns_list returns_list; template <F fx, typename... Args> static decltype(auto) invoke(Args&&... args) { return fx(std::forward<Args>(args)...); } template <typename... Args> static decltype(auto) call(F& fx, Args&&... args) { return fx(std::forward<Args>(args)...); } struct caller { template <typename... Args> decltype(auto) operator()(F& fx, Args&&... args) const { return call(fx, std::forward<Args>(args)...); } }; template <F fx> struct invoker { template <typename... Args> decltype(auto) operator()(Args&&... args) const { return invoke<fx>(std::forward<Args>(args)...); } }; }; template <typename F> struct wrapper<F, std::enable_if_t<std::is_member_object_pointer<meta::unqualified_t<F>>::value>> { typedef lua_bind_traits<F> traits_type; typedef typename traits_type::object_type object_type; typedef typename traits_type::return_type return_type; typedef typename traits_type::args_list args_list; typedef types<object_type&, return_type> free_args_list; typedef typename traits_type::returns_list returns_list; template <F fx, typename... Args> static decltype(auto) invoke(object_type& mem, Args&&... args) { return (mem.*fx)(std::forward<Args>(args)...); } template <typename Fx> static decltype(auto) call(Fx&& fx, object_type& mem) { return (mem.*fx); } template <typename Fx, typename Arg, typename... Args> static void call(Fx&& fx, object_type& mem, Arg&& arg, Args&&...) { (mem.*fx) = std::forward<Arg>(arg); } struct caller { template <typename Fx, typename... Args> decltype(auto) operator()(Fx&& fx, object_type& mem, Args&&... args) const { return call(std::forward<Fx>(fx), mem, std::forward<Args>(args)...); } }; template <F fx> struct invoker { template <typename... Args> decltype(auto) operator()(Args&&... args) const { return invoke<fx>(std::forward<Args>(args)...); } }; }; template <typename F, typename R, typename O, typename... FArgs> struct member_function_wrapper { typedef O object_type; typedef lua_bind_traits<F> traits_type; typedef typename traits_type::args_list args_list; typedef types<object_type&, FArgs...> free_args_list; typedef meta::tuple_types<R> returns_list; template <F fx, typename... Args> static R invoke(O& mem, Args&&... args) { return (mem.*fx)(std::forward<Args>(args)...); } template <typename Fx, typename... Args> static R call(Fx&& fx, O& mem, Args&&... args) { return (mem.*fx)(std::forward<Args>(args)...); } struct caller { template <typename Fx, typename... Args> decltype(auto) operator()(Fx&& fx, O& mem, Args&&... args) const { return call(std::forward<Fx>(fx), mem, std::forward<Args>(args)...); } }; template <F fx> struct invoker { template <typename... Args> decltype(auto) operator()(O& mem, Args&&... args) const { return invoke<fx>(mem, std::forward<Args>(args)...); } }; }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args...)> : public member_function_wrapper<R(O:: *)(Args...), R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args...) const> : public member_function_wrapper<R(O:: *)(Args...) const, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args...) const volatile> : public member_function_wrapper<R(O:: *)(Args...) const volatile, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args...) &> : public member_function_wrapper<R(O:: *)(Args...) &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args...) const &> : public member_function_wrapper<R(O:: *)(Args...) const &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args...) const volatile &> : public member_function_wrapper<R(O:: *)(Args...) const volatile &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args..., ...) &> : public member_function_wrapper<R(O:: *)(Args..., ...) &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args..., ...) const &> : public member_function_wrapper<R(O:: *)(Args..., ...) const &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args..., ...) const volatile &> : public member_function_wrapper<R(O:: *)(Args..., ...) const volatile &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args...) && > : public member_function_wrapper<R(O:: *)(Args...) &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args...) const &&> : public member_function_wrapper<R(O:: *)(Args...) const &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args...) const volatile &&> : public member_function_wrapper<R(O:: *)(Args...) const volatile &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args..., ...) && > : public member_function_wrapper<R(O:: *)(Args..., ...) &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args..., ...) const &&> : public member_function_wrapper<R(O:: *)(Args..., ...) const &, R, O, Args...> { }; template <typename R, typename O, typename... Args> struct wrapper<R(O:: *)(Args..., ...) const volatile &&> : public member_function_wrapper<R(O:: *)(Args..., ...) const volatile &, R, O, Args...> { }; } // sol // end of sol/wrapper.hpp namespace sol { namespace function_detail { template <typename Fx> inline int call(lua_State* L) { Fx& fx = stack::get<user<Fx>>(L, upvalue_index(1)); return fx(L); } } // function_detail } // sol // end of sol/function_types_core.hpp // beginning of sol/function_types_templated.hpp // beginning of sol/call.hpp // beginning of sol/protect.hpp namespace sol { template <typename T> struct protect_t { T value; template <typename Arg, typename... Args, meta::disable<std::is_same<protect_t, meta::unqualified_t<Arg>>> = meta::enabler> protect_t(Arg&& arg, Args&&... args) : value(std::forward<Arg>(arg), std::forward<Args>(args)...) {} protect_t(const protect_t&) = default; protect_t(protect_t&&) = default; protect_t& operator=(const protect_t&) = default; protect_t& operator=(protect_t&&) = default; }; template <typename T> auto protect(T&& value) { return protect_t<std::decay_t<T>>(std::forward<T>(value)); } } // sol // end of sol/protect.hpp // beginning of sol/property.hpp namespace sol { struct no_prop { }; template <typename R, typename W> struct property_wrapper { typedef std::integral_constant<bool, !std::is_void<R>::value> can_read; typedef std::integral_constant<bool, !std::is_void<W>::value> can_write; typedef std::conditional_t<can_read::value, R, no_prop> Read; typedef std::conditional_t<can_write::value, W, no_prop> Write; Read read; Write write; template <typename Rx, typename Wx> property_wrapper(Rx&& r, Wx&& w) : read(std::forward<Rx>(r)), write(std::forward<Wx>(w)) {} }; namespace property_detail { template <typename R, typename W> inline decltype(auto) property(std::true_type, R&& read, W&& write) { return property_wrapper<std::decay_t<R>, std::decay_t<W>>(std::forward<R>(read), std::forward<W>(write)); } template <typename W, typename R> inline decltype(auto) property(std::false_type, W&& write, R&& read) { return property_wrapper<std::decay_t<R>, std::decay_t<W>>(std::forward<R>(read), std::forward<W>(write)); } template <typename R> inline decltype(auto) property(std::true_type, R&& read) { return property_wrapper<std::decay_t<R>, void>(std::forward<R>(read), no_prop()); } template <typename W> inline decltype(auto) property(std::false_type, W&& write) { return property_wrapper<void, std::decay_t<W>>(no_prop(), std::forward<W>(write)); } } // property_detail template <typename F, typename G> inline decltype(auto) property(F&& f, G&& g) { typedef lua_bind_traits<meta::unqualified_t<F>> left_traits; typedef lua_bind_traits<meta::unqualified_t<G>> right_traits; return property_detail::property(meta::boolean<(left_traits::free_arity < right_traits::free_arity)>(), std::forward<F>(f), std::forward<G>(g)); } template <typename F> inline decltype(auto) property(F&& f) { typedef lua_bind_traits<meta::unqualified_t<F>> left_traits; return property_detail::property(meta::boolean<(left_traits::free_arity < 2)>(), std::forward<F>(f)); } template <typename F> inline decltype(auto) readonly_property(F&& f) { return property_detail::property(std::true_type(), std::forward<F>(f)); } // Allow someone to make a member variable readonly (const) template <typename R, typename T> inline auto readonly(R T::* v) { typedef const R C; return static_cast<C T::*>(v); } template <typename T> struct var_wrapper { T value; template <typename... Args> var_wrapper(Args&&... args) : value(std::forward<Args>(args)...) {} var_wrapper(const var_wrapper&) = default; var_wrapper(var_wrapper&&) = default; var_wrapper& operator=(const var_wrapper&) = default; var_wrapper& operator=(var_wrapper&&) = default; }; template <typename V> inline auto var(V&& v) { typedef meta::unqualified_t<V> T; return var_wrapper<T>(std::forward<V>(v)); } } // sol // end of sol/property.hpp namespace sol { namespace call_detail { template <typename R, typename W> inline auto& pick(std::true_type, property_wrapper<R, W>& f) { return f.read; } template <typename R, typename W> inline auto& pick(std::false_type, property_wrapper<R, W>& f) { return f.write; } template <typename T, typename List> struct void_call; template <typename T, typename... Args> struct void_call<T, types<Args...>> { static void call(Args...) {} }; template <typename T> struct constructor_match { T* obj; constructor_match(T* obj) : obj(obj) {} template <typename Fx, std::size_t I, typename... R, typename... Args> int operator()(types<Fx>, index_value<I>, types<R...> r, types<Args...> a, lua_State* L, int, int start) const { detail::default_construct func{}; return stack::call_into_lua<false>(r, a, L, start, func, obj); } }; namespace overload_detail { template <std::size_t... M, typename Match, typename... Args> inline int overload_match_arity(types<>, std::index_sequence<>, std::index_sequence<M...>, Match&&, lua_State* L, int, int, Args&&...) { return luaL_error(L, "sol: no matching function call takes this number of arguments and the specified types"); } template <typename Fx, typename... Fxs, std::size_t I, std::size_t... In, std::size_t... M, typename Match, typename... Args> inline int overload_match_arity(types<Fx, Fxs...>, std::index_sequence<I, In...>, std::index_sequence<M...>, Match&& matchfx, lua_State* L, int fxarity, int start, Args&&... args) { typedef lua_bind_traits<meta::unqualified_t<Fx>> traits; typedef meta::tuple_types<typename traits::return_type> return_types; typedef typename traits::free_args_list args_list; // compile-time eliminate any functions that we know ahead of time are of improper arity if (meta::find_in_pack_v<index_value<traits::free_arity>, index_value<M>...>::value) { return overload_match_arity(types<Fxs...>(), std::index_sequence<In...>(), std::index_sequence<M...>(), std::forward<Match>(matchfx), L, fxarity, start, std::forward<Args>(args)...); } if (traits::free_arity != fxarity) { return overload_match_arity(types<Fxs...>(), std::index_sequence<In...>(), std::index_sequence<traits::free_arity, M...>(), std::forward<Match>(matchfx), L, fxarity, start, std::forward<Args>(args)...); } stack::record tracking{}; if (!stack::stack_detail::check_types<true>{}.check(args_list(), L, start, no_panic, tracking)) { return overload_match_arity(types<Fxs...>(), std::index_sequence<In...>(), std::index_sequence<M...>(), std::forward<Match>(matchfx), L, fxarity, start, std::forward<Args>(args)...); } return matchfx(types<Fx>(), index_value<I>(), return_types(), args_list(), L, fxarity, start, std::forward<Args>(args)...); } } // overload_detail template <typename... Functions, typename Match, typename... Args> inline int overload_match_arity(Match&& matchfx, lua_State* L, int fxarity, int start, Args&&... args) { return overload_detail::overload_match_arity(types<Functions...>(), std::make_index_sequence<sizeof...(Functions)>(), std::index_sequence<>(), std::forward<Match>(matchfx), L, fxarity, start, std::forward<Args>(args)...); } template <typename... Functions, typename Match, typename... Args> inline int overload_match(Match&& matchfx, lua_State* L, int start, Args&&... args) { int fxarity = lua_gettop(L) - (start - 1); return overload_match_arity<Functions...>(std::forward<Match>(matchfx), L, fxarity, start, std::forward<Args>(args)...); } template <typename T, typename... TypeLists, typename Match, typename... Args> inline int construct_match(Match&& matchfx, lua_State* L, int fxarity, int start, Args&&... args) { // use same overload resolution matching as all other parts of the framework return overload_match_arity<decltype(void_call<T, TypeLists>::call)...>(std::forward<Match>(matchfx), L, fxarity, start, std::forward<Args>(args)...); } template <typename T, typename... TypeLists> inline int construct(lua_State* L) { static const auto& meta = usertype_traits<T>::metatable; int argcount = lua_gettop(L); call_syntax syntax = argcount > 0 ? stack::get_call_syntax(L, &usertype_traits<T>::user_metatable[0], 1) : call_syntax::dot; argcount -= static_cast<int>(syntax); T** pointerpointer = reinterpret_cast<T**>(lua_newuserdata(L, sizeof(T*) + sizeof(T))); T*& referencepointer = *pointerpointer; T* obj = reinterpret_cast<T*>(pointerpointer + 1); referencepointer = obj; reference userdataref(L, -1); userdataref.pop(); construct_match<T, TypeLists...>(constructor_match<T>(obj), L, argcount, 1 + static_cast<int>(syntax)); userdataref.push(); luaL_getmetatable(L, &meta[0]); if (type_of(L, -1) == type::nil) { lua_pop(L, 1); return luaL_error(L, "sol: unable to get usertype metatable"); } lua_setmetatable(L, -2); return 1; } template <typename F, bool is_index, bool is_variable, bool checked, int boost, typename = void> struct agnostic_lua_call_wrapper { template <typename Fx, typename... Args> static int call(lua_State* L, Fx&& f, Args&&... args) { typedef wrapper<meta::unqualified_t<F>> wrap; typedef typename wrap::returns_list returns_list; typedef typename wrap::free_args_list args_list; typedef typename wrap::caller caller; return stack::call_into_lua<checked>(returns_list(), args_list(), L, boost + 1, caller(), std::forward<Fx>(f), std::forward<Args>(args)...); } }; template <typename T, bool is_variable, bool checked, int boost, typename C> struct agnostic_lua_call_wrapper<var_wrapper<T>, true, is_variable, checked, boost, C> { template <typename F> static int call(lua_State* L, F&& f) { return stack::push_reference(L, detail::unwrap(f.value)); } }; template <typename T, bool is_variable, bool checked, int boost, typename C> struct agnostic_lua_call_wrapper<var_wrapper<T>, false, is_variable, checked, boost, C> { template <typename V> static int call_assign(std::true_type, lua_State* L, V&& f) { detail::unwrap(f.value) = stack::get<meta::unwrapped_t<T>>(L, boost + (is_variable ? 3 : 1)); return 0; } template <typename... Args> static int call_assign(std::false_type, lua_State* L, Args&&...) { return luaL_error(L, "sol: cannot write to this variable: copy assignment/constructor not available"); } template <typename... Args> static int call_const(std::false_type, lua_State* L, Args&&... args) { typedef meta::unwrapped_t<T> R; return call_assign(std::is_assignable<std::add_lvalue_reference_t<meta::unqualified_t<R>>, R>(), L, std::forward<Args>(args)...); } template <typename... Args> static int call_const(std::true_type, lua_State* L, Args&&...) { return luaL_error(L, "sol: cannot write to a readonly (const) variable"); } template <typename V> static int call(lua_State* L, V&& f) { return call_const(std::is_const<meta::unwrapped_t<T>>(), L, f); } }; template <bool is_index, bool is_variable, bool checked, int boost, typename C> struct agnostic_lua_call_wrapper<lua_r_CFunction, is_index, is_variable, checked, boost, C> { static int call(lua_State* L, lua_r_CFunction f) { return f(L); } }; template <bool is_index, bool is_variable, bool checked, int boost, typename C> struct agnostic_lua_call_wrapper<lua_CFunction, is_index, is_variable, checked, boost, C> { static int call(lua_State* L, lua_CFunction f) { return f(L); } }; template <bool is_index, bool is_variable, bool checked, int boost, typename C> struct agnostic_lua_call_wrapper<no_prop, is_index, is_variable, checked, boost, C> { static int call(lua_State* L, const no_prop&) { return luaL_error(L, is_index ? "sol: cannot read from a writeonly property" : "sol: cannot write to a readonly property"); } }; template <bool is_index, bool is_variable, bool checked, int boost, typename C> struct agnostic_lua_call_wrapper<no_construction, is_index, is_variable, checked, boost, C> { static int call(lua_State* L, const no_construction&) { return luaL_error(L, "sol: cannot call this constructor (tagged as non-constructible)"); } }; template <typename... Args, bool is_index, bool is_variable, bool checked, int boost, typename C> struct agnostic_lua_call_wrapper<bases<Args...>, is_index, is_variable, checked, boost, C> { static int call(lua_State*, const bases<Args...>&) { // Uh. How did you even call this, lul return 0; } }; template <typename T, typename F, bool is_index, bool is_variable, bool checked = stack::stack_detail::default_check_arguments, int boost = 0, typename = void> struct lua_call_wrapper : agnostic_lua_call_wrapper<F, is_index, is_variable, checked, boost> {}; template <typename T, typename F, bool is_index, bool is_variable, bool checked, int boost> struct lua_call_wrapper<T, F, is_index, is_variable, checked, boost, std::enable_if_t<std::is_member_function_pointer<F>::value>> { typedef wrapper<meta::unqualified_t<F>> wrap; typedef typename wrap::object_type object_type; template <typename Fx> static int call(lua_State* L, Fx&& f, object_type& o) { typedef typename wrap::returns_list returns_list; typedef typename wrap::args_list args_list; typedef typename wrap::caller caller; return stack::call_into_lua<checked>(returns_list(), args_list(), L, boost + ( is_variable ? 3 : 2 ), caller(), std::forward<Fx>(f), o); } template <typename Fx> static int call(lua_State* L, Fx&& f) { typedef std::conditional_t<std::is_void<T>::value, object_type, T> Ta; #ifdef SOL_SAFE_USERTYPE object_type* o = static_cast<object_type*>(stack::get<Ta*>(L, 1)); if (o == nullptr) { return luaL_error(L, "sol: received null for 'self' argument (use ':' for accessing member functions, make sure member variables are preceeded by the actual object with '.' syntax)"); } return call(L, std::forward<Fx>(f), *o); #else object_type& o = static_cast<object_type&>(*stack::get<non_null<Ta*>>(L, 1)); return call(L, std::forward<Fx>(f), o); #endif // Safety } }; template <typename T, typename F, bool is_variable, bool checked, int boost> struct lua_call_wrapper<T, F, false, is_variable, checked, boost, std::enable_if_t<std::is_member_object_pointer<F>::value>> { typedef lua_bind_traits<F> traits_type; typedef wrapper<meta::unqualified_t<F>> wrap; typedef typename wrap::object_type object_type; template <typename V> static int call_assign(std::true_type, lua_State* L, V&& f, object_type& o) { typedef typename wrap::args_list args_list; typedef typename wrap::caller caller; return stack::call_into_lua<checked>(types<void>(), args_list(), L, boost + ( is_variable ? 3 : 2 ), caller(), f, o); } template <typename V> static int call_assign(std::true_type, lua_State* L, V&& f) { typedef std::conditional_t<std::is_void<T>::value, object_type, T> Ta; #ifdef SOL_SAFE_USERTYPE object_type* o = static_cast<object_type*>(stack::get<Ta*>(L, 1)); if (o == nullptr) { if (is_variable) { return luaL_error(L, "sol: received nil for 'self' argument (bad '.' access?)"); } return luaL_error(L, "sol: received nil for 'self' argument (pass 'self' as first argument)"); } return call_assign(std::true_type(), L, f, *o); #else object_type& o = static_cast<object_type&>(*stack::get<non_null<Ta*>>(L, 1)); return call_assign(std::true_type(), L, f, o); #endif // Safety } template <typename... Args> static int call_assign(std::false_type, lua_State* L, Args&&...) { return luaL_error(L, "sol: cannot write to this variable: copy assignment/constructor not available"); } template <typename... Args> static int call_const(std::false_type, lua_State* L, Args&&... args) { typedef typename traits_type::return_type R; return call_assign(std::is_assignable<std::add_lvalue_reference_t<meta::unqualified_t<R>>, R>(), L, std::forward<Args>(args)...); } template <typename... Args> static int call_const(std::true_type, lua_State* L, Args&&...) { return luaL_error(L, "sol: cannot write to a readonly (const) variable"); } template <typename V> static int call(lua_State* L, V&& f) { return call_const(std::is_const<typename traits_type::return_type>(), L, f); } template <typename V> static int call(lua_State* L, V&& f, object_type& o) { return call_const(std::is_const<typename traits_type::return_type>(), L, f, o); } }; template <typename T, typename F, bool is_variable, bool checked, int boost> struct lua_call_wrapper<T, F, true, is_variable, checked, boost, std::enable_if_t<std::is_member_object_pointer<F>::value>> { typedef lua_bind_traits<F> traits_type; typedef wrapper<meta::unqualified_t<F>> wrap; typedef typename wrap::object_type object_type; template <typename V> static int call(lua_State* L, V&& f, object_type& o) { typedef typename wrap::returns_list returns_list; typedef typename wrap::caller caller; return stack::call_into_lua<checked>(returns_list(), types<>(), L, boost + ( is_variable ? 3 : 2 ), caller(), f, o); } template <typename V> static int call(lua_State* L, V&& f) { typedef std::conditional_t<std::is_void<T>::value, object_type, T> Ta; #ifdef SOL_SAFE_USERTYPE object_type* o = static_cast<object_type*>(stack::get<Ta*>(L, 1)); if (o == nullptr) { if (is_variable) { return luaL_error(L, "sol: 'self' argument is nil (bad '.' access?)"); } return luaL_error(L, "sol: 'self' argument is nil (pass 'self' as first argument)"); } return call(L, f, *o); #else object_type& o = static_cast<object_type&>(*stack::get<non_null<Ta*>>(L, 1)); return call(L, f, o); #endif // Safety } }; template <typename T, typename... Args, bool is_index, bool is_variable, bool checked, int boost, typename C> struct lua_call_wrapper<T, constructor_list<Args...>, is_index, is_variable, checked, boost, C> { typedef constructor_list<Args...> F; static int call(lua_State* L, F&) { const auto& metakey = usertype_traits<T>::metatable; int argcount = lua_gettop(L); call_syntax syntax = argcount > 0 ? stack::get_call_syntax(L, &usertype_traits<T>::user_metatable[0], 1) : call_syntax::dot; argcount -= static_cast<int>(syntax); T** pointerpointer = reinterpret_cast<T**>(lua_newuserdata(L, sizeof(T*) + sizeof(T))); reference userdataref(L, -1); T*& referencepointer = *pointerpointer; T* obj = reinterpret_cast<T*>(pointerpointer + 1); referencepointer = obj; construct_match<T, Args...>(constructor_match<T>(obj), L, argcount, boost + 1 + static_cast<int>(syntax)); userdataref.push(); luaL_getmetatable(L, &metakey[0]); if (type_of(L, -1) == type::nil) { lua_pop(L, 1); return luaL_error(L, "sol: unable to get usertype metatable"); } lua_setmetatable(L, -2); return 1; } }; template <typename T, typename... Cxs, bool is_index, bool is_variable, bool checked, int boost, typename C> struct lua_call_wrapper<T, constructor_wrapper<Cxs...>, is_index, is_variable, checked, boost, C> { typedef constructor_wrapper<Cxs...> F; struct onmatch { template <typename Fx, std::size_t I, typename... R, typename... Args> int operator()(types<Fx>, index_value<I>, types<R...> r, types<Args...> a, lua_State* L, int, int start, F& f) { const auto& metakey = usertype_traits<T>::metatable; T** pointerpointer = reinterpret_cast<T**>(lua_newuserdata(L, sizeof(T*) + sizeof(T))); reference userdataref(L, -1); T*& referencepointer = *pointerpointer; T* obj = reinterpret_cast<T*>(pointerpointer + 1); referencepointer = obj; auto& func = std::get<I>(f.functions); stack::call_into_lua<checked>(r, a, L, boost + start, func, detail::implicit_wrapper<T>(obj)); userdataref.push(); luaL_getmetatable(L, &metakey[0]); if (type_of(L, -1) == type::nil) { lua_pop(L, 1); std::string err = "sol: unable to get usertype metatable for "; err += usertype_traits<T>::name; return luaL_error(L, err.c_str()); } lua_setmetatable(L, -2); return 1; } }; static int call(lua_State* L, F& f) { call_syntax syntax = stack::get_call_syntax(L, &usertype_traits<T>::user_metatable[0]); int syntaxval = static_cast<int>(syntax); int argcount = lua_gettop(L) - syntaxval; return construct_match<T, meta::pop_front_type_t<meta::function_args_t<Cxs>>...>(onmatch(), L, argcount, 1 + syntaxval, f); } }; template <typename T, typename Fx, bool is_index, bool is_variable, bool checked, int boost> struct lua_call_wrapper<T, destructor_wrapper<Fx>, is_index, is_variable, checked, boost, std::enable_if_t<std::is_void<Fx>::value>> { typedef destructor_wrapper<Fx> F; static int call(lua_State* L, const F&) { return detail::usertype_alloc_destroy<T>(L); } }; template <typename T, typename Fx, bool is_index, bool is_variable, bool checked, int boost> struct lua_call_wrapper<T, destructor_wrapper<Fx>, is_index, is_variable, checked, boost, std::enable_if_t<!std::is_void<Fx>::value>> { typedef destructor_wrapper<Fx> F; static int call(lua_State* L, const F& f) { T& obj = stack::get<T>(L); f.fx(detail::implicit_wrapper<T>(obj)); return 0; } }; template <typename T, typename... Fs, bool is_index, bool is_variable, bool checked, int boost, typename C> struct lua_call_wrapper<T, overload_set<Fs...>, is_index, is_variable, checked, boost, C> { typedef overload_set<Fs...> F; struct on_match { template <typename Fx, std::size_t I, typename... R, typename... Args> int operator()(types<Fx>, index_value<I>, types<R...>, types<Args...>, lua_State* L, int, int, F& fx) { auto& f = std::get<I>(fx.functions); return lua_call_wrapper<T, Fx, is_index, is_variable, checked, boost>{}.call(L, f); } }; static int call(lua_State* L, F& fx) { return overload_match_arity<Fs...>(on_match(), L, lua_gettop(L), 1, fx); } }; template <typename T, typename... Fs, bool is_index, bool is_variable, bool checked, int boost, typename C> struct lua_call_wrapper<T, factory_wrapper<Fs...>, is_index, is_variable, checked, boost, C> { typedef factory_wrapper<Fs...> F; struct on_match { template <typename Fx, std::size_t I, typename... R, typename... Args> int operator()(types<Fx>, index_value<I>, types<R...>, types<Args...>, lua_State* L, int, int, F& fx) { auto& f = std::get<I>(fx.functions); return lua_call_wrapper<T, Fx, is_index, is_variable, checked, boost>{}.call(L, f); } }; static int call(lua_State* L, F& fx) { return overload_match_arity<Fs...>(on_match(), L, lua_gettop(L), 1, fx); } }; template <typename T, typename R, typename W, bool is_index, bool is_variable, bool checked, int boost, typename C> struct lua_call_wrapper<T, property_wrapper<R, W>, is_index, is_variable, checked, boost, C> { typedef std::conditional_t<is_index, R, W> P; typedef meta::unqualified_t<P> U; typedef lua_bind_traits<U> traits_type; template <typename F> static int self_call(lua_State* L, F&& f) { typedef wrapper<U> wrap; typedef meta::unqualified_t<typename traits_type::template arg_at<0>> object_type; typedef meta::pop_front_type_t<typename traits_type::free_args_list> args_list; typedef T Ta; #ifdef SOL_SAFE_USERTYPE object_type* po = static_cast<object_type*>(stack::get<Ta*>(L, 1)); if (po == nullptr) { if (is_variable) { return luaL_error(L, "sol: 'self' argument is nil (bad '.' access?)"); } return luaL_error(L, "sol: 'self' argument is nil (pass 'self' as first argument)"); } object_type& o = *po; #else object_type& o = static_cast<object_type&>(*stack::get<non_null<Ta*>>(L, 1)); #endif // Safety typedef typename wrap::returns_list returns_list; typedef typename wrap::caller caller; return stack::call_into_lua<checked>(returns_list(), args_list(), L, boost + (is_variable ? 3 : 2), caller(), f, o); } template <typename F, typename... Args> static int defer_call(std::false_type, lua_State* L, F&& f, Args&&... args) { return self_call(L, pick(meta::boolean<is_index>(), f), std::forward<Args>(args)...); } template <typename F, typename... Args> static int defer_call(std::true_type, lua_State* L, F&& f, Args&&... args) { auto& p = pick(meta::boolean<is_index>(), std::forward<F>(f)); return lua_call_wrapper<T, meta::unqualified_t<decltype(p)>, is_index, is_variable, checked, boost>{}.call(L, p, std::forward<Args>(args)...); } template <typename F, typename... Args> static int call(lua_State* L, F&& f, Args&&... args) { typedef meta::any< std::is_void<U>, std::is_same<U, no_prop>, meta::is_specialization_of<var_wrapper, U>, meta::is_specialization_of<constructor_wrapper, U>, meta::is_specialization_of<constructor_list, U>, std::is_member_pointer<U> > is_specialized; return defer_call(is_specialized(), L, std::forward<F>(f), std::forward<Args>(args)...); } }; template <typename T, typename V, bool is_index, bool is_variable, bool checked, int boost, typename C> struct lua_call_wrapper<T, protect_t<V>, is_index, is_variable, checked, boost, C> { typedef protect_t<V> F; template <typename... Args> static int call(lua_State* L, F& fx, Args&&... args) { return lua_call_wrapper<T, V, is_index, is_variable, true, boost>{}.call(L, fx.value, std::forward<Args>(args)...); } }; template <typename T, typename Sig, typename P, bool is_index, bool is_variable, bool checked, int boost, typename C> struct lua_call_wrapper<T, function_arguments<Sig, P>, is_index, is_variable, checked, boost, C> { template <typename F> static int call(lua_State* L, F&& f) { return lua_call_wrapper<T, meta::unqualified_t<P>, is_index, is_variable, stack::stack_detail::default_check_arguments, boost>{}.call(L, std::get<0>(f.arguments)); } }; template <typename T, bool is_index, bool is_variable, int boost = 0, typename Fx, typename... Args> inline int call_wrapped(lua_State* L, Fx&& fx, Args&&... args) { return lua_call_wrapper<T, meta::unqualified_t<Fx>, is_index, is_variable, stack::stack_detail::default_check_arguments, boost>{}.call(L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename T, bool is_index, bool is_variable, typename F> inline int call_user(lua_State* L) { auto& fx = stack::get<user<F>>(L, upvalue_index(1)); return call_wrapped<T, is_index, is_variable>(L, fx); } template <typename T, typename = void> struct is_var_bind : std::false_type {}; template <typename T> struct is_var_bind<T, std::enable_if_t<std::is_member_object_pointer<T>::value>> : std::true_type {}; template <> struct is_var_bind<no_prop> : std::true_type {}; template <typename R, typename W> struct is_var_bind<property_wrapper<R, W>> : std::true_type {}; template <typename T> struct is_var_bind<var_wrapper<T>> : std::true_type {}; } // call_detail template <typename T> struct is_variable_binding : call_detail::is_var_bind<meta::unqualified_t<T>> {}; template <typename T> struct is_function_binding : meta::neg<is_variable_binding<T>> {}; } // sol // end of sol/call.hpp namespace sol { namespace function_detail { template <typename F, F fx> inline int call_wrapper_variable(std::false_type, lua_State* L) { typedef meta::bind_traits<meta::unqualified_t<F>> traits_type; typedef typename traits_type::args_list args_list; typedef meta::tuple_types<typename traits_type::return_type> return_type; return stack::call_into_lua(return_type(), args_list(), L, 1, fx); } template <typename R, typename V, V, typename T> inline int call_set_assignable(std::false_type, T&&, lua_State* L) { return luaL_error(L, "cannot write to this type: copy assignment/constructor not available"); } template <typename R, typename V, V variable, typename T> inline int call_set_assignable(std::true_type, lua_State* L, T&& mem) { (mem.*variable) = stack::get<R>(L, 2); return 0; } template <typename R, typename V, V, typename T> inline int call_set_variable(std::false_type, lua_State* L, T&&) { return luaL_error(L, "cannot write to a const variable"); } template <typename R, typename V, V variable, typename T> inline int call_set_variable(std::true_type, lua_State* L, T&& mem) { return call_set_assignable<R, V, variable>(std::is_assignable<std::add_lvalue_reference_t<R>, R>(), L, std::forward<T>(mem)); } template <typename V, V variable> inline int call_wrapper_variable(std::true_type, lua_State* L) { typedef meta::bind_traits<meta::unqualified_t<V>> traits_type; typedef typename traits_type::object_type T; typedef typename traits_type::return_type R; auto& mem = stack::get<T>(L, 1); switch (lua_gettop(L)) { case 1: { decltype(auto) r = (mem.*variable); stack::push_reference(L, std::forward<decltype(r)>(r)); return 1; } case 2: return call_set_variable<R, V, variable>(meta::neg<std::is_const<R>>(), L, mem); default: return luaL_error(L, "incorrect number of arguments to member variable function call"); } } template <typename F, F fx> inline int call_wrapper_function(std::false_type, lua_State* L) { return call_wrapper_variable<F, fx>(std::is_member_object_pointer<F>(), L); } template <typename F, F fx> inline int call_wrapper_function(std::true_type, lua_State* L) { return call_detail::call_wrapped<void, false, false>(L, fx); } template <typename F, F fx> int call_wrapper_entry(lua_State* L) { return call_wrapper_function<F, fx>(std::is_member_function_pointer<meta::unqualified_t<F>>(), L); } template <typename... Fxs> struct c_call_matcher { template <typename Fx, std::size_t I, typename R, typename... Args> int operator()(types<Fx>, index_value<I>, types<R>, types<Args...>, lua_State* L, int, int) const { typedef meta::at_in_pack_t<I, Fxs...> target; return target::call(L); } }; } // function_detail template <typename F, F fx> inline int c_call(lua_State* L) { #ifdef __clang__ return detail::trampoline(L, function_detail::call_wrapper_entry<F, fx>); #else return detail::static_trampoline<(&function_detail::call_wrapper_entry<F, fx>)>(L); #endif // fuck you clang :c } template <typename F, F f> struct wrap { typedef F type; static int call(lua_State* L) { return c_call<type, f>(L); } }; template <typename... Fxs> inline int c_call(lua_State* L) { if (sizeof...(Fxs) < 2) { return meta::at_in_pack_t<0, Fxs...>::call(L); } else { return call_detail::overload_match_arity<typename Fxs::type...>(function_detail::c_call_matcher<Fxs...>(), L, lua_gettop(L), 1); } } } // sol // end of sol/function_types_templated.hpp // beginning of sol/function_types_stateless.hpp namespace sol { namespace function_detail { template<typename Function> struct upvalue_free_function { typedef std::remove_pointer_t<std::decay_t<Function>> function_type; typedef lua_bind_traits<function_type> traits_type; static int real_call(lua_State* L) { auto udata = stack::stack_detail::get_as_upvalues<function_type*>(L); function_type* fx = udata.first; return call_detail::call_wrapped<void, true, false>(L, fx); } static int call(lua_State* L) { return detail::static_trampoline<(&real_call)>(L); } int operator()(lua_State* L) { return call(L); } }; template<typename T, typename Function> struct upvalue_member_function { typedef std::remove_pointer_t<std::decay_t<Function>> function_type; typedef lua_bind_traits<function_type> traits_type; static int real_call(lua_State* L) { // Layout: // idx 1...n: verbatim data of member function pointer // idx n + 1: is the object's void pointer // We don't need to store the size, because the other side is templated // with the same member function pointer type auto memberdata = stack::stack_detail::get_as_upvalues<function_type>(L, 1); auto objdata = stack::stack_detail::get_as_upvalues<T*>(L, memberdata.second); function_type& memfx = memberdata.first; auto& item = *objdata.first; return call_detail::call_wrapped<T, true, false, -1>(L, memfx, item); } static int call(lua_State* L) { return detail::static_trampoline<(&real_call)>(L); } int operator()(lua_State* L) { return call(L); } }; template<typename T, typename Function> struct upvalue_member_variable { typedef std::remove_pointer_t<std::decay_t<Function>> function_type; typedef lua_bind_traits<function_type> traits_type; static int real_call(lua_State* L) { // Layout: // idx 1...n: verbatim data of member variable pointer // idx n + 1: is the object's void pointer // We don't need to store the size, because the other side is templated // with the same member function pointer type auto memberdata = stack::stack_detail::get_as_upvalues<function_type>(L, 1); auto objdata = stack::stack_detail::get_as_upvalues<T*>(L, memberdata.second); auto& mem = *objdata.first; function_type& var = memberdata.first; switch (lua_gettop(L)) { case 0: return call_detail::call_wrapped<T, true, false, -1>(L, var, mem); case 1: return call_detail::call_wrapped<T, false, false, -1>(L, var, mem); default: return luaL_error(L, "sol: incorrect number of arguments to member variable function"); } } static int call(lua_State* L) { return detail::static_trampoline<(&real_call)>(L); } int operator()(lua_State* L) { return call(L); } }; template<typename T, typename Function> struct upvalue_this_member_function { typedef std::remove_pointer_t<std::decay_t<Function>> function_type; typedef lua_bind_traits<function_type> traits_type; static int real_call(lua_State* L) { // Layout: // idx 1...n: verbatim data of member variable pointer auto memberdata = stack::stack_detail::get_as_upvalues<function_type>(L, 1); function_type& memfx = memberdata.first; return call_detail::call_wrapped<T, false, false>(L, memfx); } static int call(lua_State* L) { return detail::static_trampoline<(&real_call)>(L); } int operator()(lua_State* L) { return call(L); } }; template<typename T, typename Function> struct upvalue_this_member_variable { typedef std::remove_pointer_t<std::decay_t<Function>> function_type; typedef lua_bind_traits<function_type> traits_type; static int real_call(lua_State* L) { // Layout: // idx 1...n: verbatim data of member variable pointer auto memberdata = stack::stack_detail::get_as_upvalues<function_type>(L, 1); function_type& var = memberdata.first; switch (lua_gettop(L)) { case 1: return call_detail::call_wrapped<T, true, false>(L, var); case 2: return call_detail::call_wrapped<T, false, false>(L, var); default: return luaL_error(L, "sol: incorrect number of arguments to member variable function"); } } static int call(lua_State* L) { return detail::static_trampoline<(&real_call)>(L); } int operator()(lua_State* L) { return call(L); } }; } // function_detail } // sol // end of sol/function_types_stateless.hpp // beginning of sol/function_types_stateful.hpp namespace sol { namespace function_detail { template<typename Func> struct functor_function { typedef meta::unwrapped_t<meta::unqualified_t<Func>> Function; typedef decltype(&Function::operator()) function_type; typedef meta::function_return_t<function_type> return_type; typedef meta::function_args_t<function_type> args_lists; Function fx; template<typename... Args> functor_function(Function f, Args&&... args) : fx(std::move(f), std::forward<Args>(args)...) {} int call(lua_State* L) { return call_detail::call_wrapped<void, true, false>(L, fx); } int operator()(lua_State* L) { auto f = [&](lua_State* L) -> int { return this->call(L); }; return detail::trampoline(L, f); } }; template<typename T, typename Function> struct member_function { typedef std::remove_pointer_t<std::decay_t<Function>> function_type; typedef meta::function_return_t<function_type> return_type; typedef meta::function_args_t<function_type> args_lists; function_type invocation; T member; template<typename... Args> member_function(function_type f, Args&&... args) : invocation(std::move(f)), member(std::forward<Args>(args)...) {} int call(lua_State* L) { return call_detail::call_wrapped<T, true, false, -1>(L, invocation, detail::unwrap(detail::deref(member))); } int operator()(lua_State* L) { auto f = [&](lua_State* L) -> int { return this->call(L); }; return detail::trampoline(L, f); } }; template<typename T, typename Function> struct member_variable { typedef std::remove_pointer_t<std::decay_t<Function>> function_type; typedef typename meta::bind_traits<function_type>::return_type return_type; typedef typename meta::bind_traits<function_type>::args_list args_lists; function_type var; T member; typedef std::add_lvalue_reference_t<meta::unwrapped_t<std::remove_reference_t<decltype(detail::deref(member))>>> M; template<typename... Args> member_variable(function_type v, Args&&... args) : var(std::move(v)), member(std::forward<Args>(args)...) {} int call(lua_State* L) { M mem = detail::unwrap(detail::deref(member)); switch (lua_gettop(L)) { case 0: return call_detail::call_wrapped<T, true, false, -1>(L, var, mem); case 1: return call_detail::call_wrapped<T, false, false, -1>(L, var, mem); default: return luaL_error(L, "sol: incorrect number of arguments to member variable function"); } } int operator()(lua_State* L) { auto f = [&](lua_State* L) -> int { return this->call(L); }; return detail::trampoline(L, f); } }; } // function_detail } // sol // end of sol/function_types_stateful.hpp // beginning of sol/function_types_overloaded.hpp namespace sol { namespace function_detail { template <typename... Functions> struct overloaded_function { typedef std::tuple<Functions...> overload_list; typedef std::make_index_sequence<sizeof...(Functions)> indices; overload_list overloads; overloaded_function(overload_list set) : overloads(std::move(set)) {} overloaded_function(Functions... fxs) : overloads(fxs...) { } template <typename Fx, std::size_t I, typename... R, typename... Args> int call(types<Fx>, index_value<I>, types<R...>, types<Args...>, lua_State* L, int, int) { auto& func = std::get<I>(overloads); return call_detail::call_wrapped<void, true, false>(L, func); } int operator()(lua_State* L) { auto mfx = [&](auto&&... args) { return this->call(std::forward<decltype(args)>(args)...); }; return call_detail::overload_match<Functions...>(mfx, L, 1); } }; } // function_detail } // sol // end of sol/function_types_overloaded.hpp // beginning of sol/resolve.hpp namespace sol { namespace detail { template<typename R, typename... Args, typename F, typename = std::result_of_t<meta::unqualified_t<F>(Args...)>> inline auto resolve_i(types<R(Args...)>, F&&)->R(meta::unqualified_t<F>::*)(Args...) { using Sig = R(Args...); typedef meta::unqualified_t<F> Fu; return static_cast<Sig Fu::*>(&Fu::operator()); } template<typename F, typename U = meta::unqualified_t<F>> inline auto resolve_f(std::true_type, F&& f) -> decltype(resolve_i(types<meta::function_signature_t<decltype(&U::operator())>>(), std::forward<F>(f))) { return resolve_i(types<meta::function_signature_t<decltype(&U::operator())>>(), std::forward<F>(f)); } template<typename F> inline void resolve_f(std::false_type, F&&) { static_assert(meta::has_deducible_signature<F>::value, "Cannot use no-template-parameter call with an overloaded functor: specify the signature"); } template<typename F, typename U = meta::unqualified_t<F>> inline auto resolve_i(types<>, F&& f) -> decltype(resolve_f(meta::has_deducible_signature<U>(), std::forward<F>(f))) { return resolve_f(meta::has_deducible_signature<U> {}, std::forward<F>(f)); } template<typename... Args, typename F, typename R = std::result_of_t<F&(Args...)>> inline auto resolve_i(types<Args...>, F&& f) -> decltype(resolve_i(types<R(Args...)>(), std::forward<F>(f))) { return resolve_i(types<R(Args...)>(), std::forward<F>(f)); } template<typename Sig, typename C> inline Sig C::* resolve_v(std::false_type, Sig C::* mem_func_ptr) { return mem_func_ptr; } template<typename Sig, typename C> inline Sig C::* resolve_v(std::true_type, Sig C::* mem_variable_ptr) { return mem_variable_ptr; } } // detail template<typename... Args, typename R> inline auto resolve(R fun_ptr(Args...))->R(*)(Args...) { return fun_ptr; } template<typename Sig> inline Sig* resolve(Sig* fun_ptr) { return fun_ptr; } template<typename... Args, typename R, typename C> inline auto resolve(R(C::*mem_ptr)(Args...))->R(C::*)(Args...) { return mem_ptr; } template<typename Sig, typename C> inline Sig C::* resolve(Sig C::* mem_ptr) { return detail::resolve_v(std::is_member_object_pointer<Sig C::*>(), mem_ptr); } template<typename... Sig, typename F> inline auto resolve(F&& f) -> decltype(detail::resolve_i(types<Sig...>(), std::forward<F>(f))) { return detail::resolve_i(types<Sig...>(), std::forward<F>(f)); } } // sol // end of sol/resolve.hpp namespace sol { namespace stack { template<typename... Sigs> struct pusher<function_sig<Sigs...>> { template <typename... Sig, typename Fx, typename... Args> static void select_convertible(std::false_type, types<Sig...>, lua_State* L, Fx&& fx, Args&&... args) { typedef std::remove_pointer_t<std::decay_t<Fx>> clean_fx; typedef function_detail::functor_function<clean_fx> F; set_fx<F>(L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename R, typename... A, typename Fx, typename... Args> static void select_convertible(std::true_type, types<R(A...)>, lua_State* L, Fx&& fx, Args&&... args) { using fx_ptr_t = R(*)(A...); fx_ptr_t fxptr = detail::unwrap(std::forward<Fx>(fx)); select_function(std::true_type(), L, fxptr, std::forward<Args>(args)...); } template <typename R, typename... A, typename Fx, typename... Args> static void select_convertible(types<R(A...)> t, lua_State* L, Fx&& fx, Args&&... args) { typedef std::decay_t<meta::unwrap_unqualified_t<Fx>> raw_fx_t; typedef R(*fx_ptr_t)(A...); typedef std::is_convertible<raw_fx_t, fx_ptr_t> is_convertible; select_convertible(is_convertible(), t, L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename... Args> static void select_convertible(types<>, lua_State* L, Fx&& fx, Args&&... args) { typedef meta::function_signature_t<meta::unwrap_unqualified_t<Fx>> Sig; select_convertible(types<Sig>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename T, typename... Args> static void select_reference_member_variable(std::false_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef std::remove_pointer_t<std::decay_t<Fx>> clean_fx; typedef function_detail::member_variable<meta::unwrap_unqualified_t<T>, clean_fx> F; set_fx<F>(L, std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...); } template <typename Fx, typename T, typename... Args> static void select_reference_member_variable(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef std::decay_t<Fx> dFx; dFx memfxptr(std::forward<Fx>(fx)); auto userptr = detail::ptr(std::forward<T>(obj), std::forward<Args>(args)...); lua_CFunction freefunc = &function_detail::upvalue_member_variable<std::decay_t<decltype(*userptr)>, meta::unqualified_t<Fx>>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, memfxptr); upvalues += stack::push(L, lightuserdata_value(static_cast<void*>(userptr))); stack::push(L, c_closure(freefunc, upvalues)); } template <typename Fx, typename... Args> static void select_member_variable(std::false_type, lua_State* L, Fx&& fx, Args&&... args) { select_convertible(types<Sigs...>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename T, typename... Args> static void select_member_variable(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef meta::boolean<meta::is_specialization_of<std::reference_wrapper, meta::unqualified_t<T>>::value || std::is_pointer<T>::value> is_reference; select_reference_member_variable(is_reference(), L, std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...); } template <typename Fx> static void select_member_variable(std::true_type, lua_State* L, Fx&& fx) { typedef typename meta::bind_traits<meta::unqualified_t<Fx>>::object_type C; lua_CFunction freefunc = &function_detail::upvalue_this_member_variable<C, Fx>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, fx); stack::push(L, c_closure(freefunc, upvalues)); } template <typename Fx, typename T, typename... Args> static void select_reference_member_function(std::false_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef std::decay_t<Fx> clean_fx; typedef function_detail::member_function<meta::unwrap_unqualified_t<T>, clean_fx> F; set_fx<F>(L, std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...); } template <typename Fx, typename T, typename... Args> static void select_reference_member_function(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef std::decay_t<Fx> dFx; dFx memfxptr(std::forward<Fx>(fx)); auto userptr = detail::ptr(std::forward<T>(obj), std::forward<Args>(args)...); lua_CFunction freefunc = &function_detail::upvalue_member_function<std::decay_t<decltype(*userptr)>, meta::unqualified_t<Fx>>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, memfxptr); upvalues += stack::push(L, lightuserdata_value(static_cast<void*>(userptr))); stack::push(L, c_closure(freefunc, upvalues)); } template <typename Fx, typename... Args> static void select_member_function(std::false_type, lua_State* L, Fx&& fx, Args&&... args) { select_member_variable(std::is_member_object_pointer<meta::unqualified_t<Fx>>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename T, typename... Args> static void select_member_function(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) { typedef meta::boolean<meta::is_specialization_of<std::reference_wrapper, meta::unqualified_t<T>>::value || std::is_pointer<T>::value> is_reference; select_reference_member_function(is_reference(), L, std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...); } template <typename Fx> static void select_member_function(std::true_type, lua_State* L, Fx&& fx) { typedef typename meta::bind_traits<meta::unqualified_t<Fx>>::object_type C; lua_CFunction freefunc = &function_detail::upvalue_this_member_function<C, Fx>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, fx); stack::push(L, c_closure(freefunc, upvalues)); } template <typename Fx, typename... Args> static void select_function(std::false_type, lua_State* L, Fx&& fx, Args&&... args) { select_member_function(std::is_member_function_pointer<meta::unqualified_t<Fx>>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename... Args> static void select_function(std::true_type, lua_State* L, Fx&& fx, Args&&... args) { std::decay_t<Fx> target(std::forward<Fx>(fx), std::forward<Args>(args)...); lua_CFunction freefunc = &function_detail::upvalue_free_function<Fx>::call; int upvalues = stack::stack_detail::push_as_upvalues(L, target); stack::push(L, c_closure(freefunc, upvalues)); } static void select_function(std::true_type, lua_State* L, lua_CFunction f) { stack::push(L, f); } template <typename Fx, typename... Args> static void select(lua_State* L, Fx&& fx, Args&&... args) { select_function(std::is_function<meta::unqualified_t<Fx>>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...); } template <typename Fx, typename... Args> static void set_fx(lua_State* L, Args&&... args) { lua_CFunction freefunc = function_detail::call<meta::unqualified_t<Fx>>; stack::push<user<Fx>>(L, std::forward<Args>(args)...); stack::push(L, c_closure(freefunc, 1)); } template<typename... Args> static int push(lua_State* L, Args&&... args) { // Set will always place one thing (function) on the stack select(L, std::forward<Args>(args)...); return 1; } }; template<typename T, typename... Args> struct pusher<function_arguments<T, Args...>> { template <std::size_t... I, typename FP> static int push_func(std::index_sequence<I...>, lua_State* L, FP&& fp) { return stack::push<T>(L, detail::forward_get<I>(fp.arguments)...); } static int push(lua_State* L, const function_arguments<T, Args...>& fp) { return push_func(std::make_index_sequence<sizeof...(Args)>(), L, fp); } static int push(lua_State* L, function_arguments<T, Args...>&& fp) { return push_func(std::make_index_sequence<sizeof...(Args)>(), L, std::move(fp)); } }; template<typename Signature> struct pusher<std::function<Signature>> { static int push(lua_State* L, std::function<Signature> fx) { return pusher<function_sig<Signature>>{}.push(L, std::move(fx)); } }; template<typename Signature> struct pusher<Signature, std::enable_if_t<std::is_member_pointer<Signature>::value>> { template <typename F> static int push(lua_State* L, F&& f) { return pusher<function_sig<>>{}.push(L, std::forward<F>(f)); } }; template<typename Signature> struct pusher<Signature, std::enable_if_t<meta::all<std::is_function<Signature>, meta::neg<std::is_same<Signature, lua_CFunction>>, meta::neg<std::is_same<Signature, std::remove_pointer_t<lua_CFunction>>>>::value>> { template <typename F> static int push(lua_State* L, F&& f) { return pusher<function_sig<>>{}.push(L, std::forward<F>(f)); } }; template<typename... Functions> struct pusher<overload_set<Functions...>> { static int push(lua_State* L, overload_set<Functions...>&& set) { typedef function_detail::overloaded_function<Functions...> F; pusher<function_sig<>>{}.set_fx<F>(L, std::move(set.functions)); return 1; } static int push(lua_State* L, const overload_set<Functions...>& set) { typedef function_detail::overloaded_function<Functions...> F; pusher<function_sig<>>{}.set_fx<F>(L, set.functions); return 1; } }; template <typename T> struct pusher<protect_t<T>> { static int push(lua_State* L, protect_t<T>&& pw) { lua_CFunction cf = call_detail::call_user<void, false, false, protect_t<T>>; int closures = stack::push<user<protect_t<T>>>(L, std::move(pw.value)); return stack::push(L, c_closure(cf, closures)); } static int push(lua_State* L, const protect_t<T>& pw) { lua_CFunction cf = call_detail::call_user<void, false, false, protect_t<T>>; int closures = stack::push<user<protect_t<T>>>(L, pw.value); return stack::push(L, c_closure(cf, closures)); } }; template <typename F, typename G> struct pusher<property_wrapper<F, G>, std::enable_if_t<!std::is_void<F>::value && !std::is_void<G>::value>> { static int push(lua_State* L, property_wrapper<F, G>&& pw) { return stack::push(L, sol::overload(std::move(pw.read), std::move(pw.write))); } static int push(lua_State* L, const property_wrapper<F, G>& pw) { return stack::push(L, sol::overload(pw.read, pw.write)); } }; template <typename F> struct pusher<property_wrapper<F, void>> { static int push(lua_State* L, property_wrapper<F, void>&& pw) { return stack::push(L, std::move(pw.read)); } static int push(lua_State* L, const property_wrapper<F, void>& pw) { return stack::push(L, pw.read); } }; template <typename F> struct pusher<property_wrapper<void, F>> { static int push(lua_State* L, property_wrapper<void, F>&& pw) { return stack::push(L, std::move(pw.write)); } static int push(lua_State* L, const property_wrapper<void, F>& pw) { return stack::push(L, pw.write); } }; template <typename T> struct pusher<var_wrapper<T>> { static int push(lua_State* L, var_wrapper<T>&& vw) { return stack::push(L, std::move(vw.value)); } static int push(lua_State* L, const var_wrapper<T>& vw) { return stack::push(L, vw.value); } }; template <typename... Functions> struct pusher<factory_wrapper<Functions...>> { static int push(lua_State* L, const factory_wrapper<Functions...>& fw) { typedef function_detail::overloaded_function<Functions...> F; pusher<function_sig<>>{}.set_fx<F>(L, fw.functions); return 1; } static int push(lua_State* L, factory_wrapper<Functions...>&& fw) { typedef function_detail::overloaded_function<Functions...> F; pusher<function_sig<>>{}.set_fx<F>(L, std::move(fw.functions)); return 1; } }; template <typename T, typename... Lists> struct pusher<detail::tagged<T, constructor_list<Lists...>>> { static int push(lua_State* L, detail::tagged<T, constructor_list<Lists...>>) { lua_CFunction cf = call_detail::construct<T, Lists...>; return stack::push(L, cf); } }; template <typename T, typename... Fxs> struct pusher<detail::tagged<T, constructor_wrapper<Fxs...>>> { template <typename C> static int push(lua_State* L, C&& c) { lua_CFunction cf = call_detail::call_user<T, false, false, constructor_wrapper<Fxs...>>; int closures = stack::push<user<constructor_wrapper<Fxs...>>>(L, std::forward<C>(c)); return stack::push(L, c_closure(cf, closures)); } }; template <typename T> struct pusher<detail::tagged<T, destructor_wrapper<void>>> { static int push(lua_State* L, destructor_wrapper<void>) { lua_CFunction cf = detail::usertype_alloc_destroy<T>; return stack::push(L, cf); } }; template <typename T, typename Fx> struct pusher<detail::tagged<T, destructor_wrapper<Fx>>> { static int push(lua_State* L, destructor_wrapper<Fx> c) { lua_CFunction cf = call_detail::call_user<T, false, false, destructor_wrapper<Fx>>; int closures = stack::push<user<T>>(L, std::move(c)); return stack::push(L, c_closure(cf, closures)); } }; } // stack } // sol // end of sol/function_types.hpp namespace sol { template <typename base_t> class basic_function : public base_t { private: void luacall(std::ptrdiff_t argcount, std::ptrdiff_t resultcount) const { lua_callk(base_t::lua_state(), static_cast<int>(argcount), static_cast<int>(resultcount), 0, nullptr); } template<std::size_t... I, typename... Ret> auto invoke(types<Ret...>, std::index_sequence<I...>, std::ptrdiff_t n) const { luacall(n, lua_size<std::tuple<Ret...>>::value); return stack::pop<std::tuple<Ret...>>(base_t::lua_state()); } template<std::size_t I, typename Ret> Ret invoke(types<Ret>, std::index_sequence<I>, std::ptrdiff_t n) const { luacall(n, lua_size<Ret>::value); return stack::pop<Ret>(base_t::lua_state()); } template <std::size_t I> void invoke(types<void>, std::index_sequence<I>, std::ptrdiff_t n) const { luacall(n, 0); } function_result invoke(types<>, std::index_sequence<>, std::ptrdiff_t n) const { int stacksize = lua_gettop(base_t::lua_state()); int firstreturn = (std::max)(1, stacksize - static_cast<int>(n)); luacall(n, LUA_MULTRET); int poststacksize = lua_gettop(base_t::lua_state()); int returncount = poststacksize - (firstreturn - 1); return function_result(base_t::lua_state(), firstreturn, returncount); } public: basic_function() = default; template <typename T, meta::enable<meta::neg<std::is_same<meta::unqualified_t<T>, basic_function>>, meta::neg<std::is_same<base_t, stack_reference>>, std::is_base_of<base_t, meta::unqualified_t<T>>> = meta::enabler> basic_function(T&& r) noexcept : base_t(std::forward<T>(r)) { #ifdef SOL_CHECK_ARGUMENTS if (!is_function<meta::unqualified_t<T>>::value) { auto pp = stack::push_pop(*this); stack::check<basic_function>(base_t::lua_state(), -1, type_panic); } #endif // Safety } basic_function(const basic_function&) = default; basic_function& operator=(const basic_function&) = default; basic_function(basic_function&&) = default; basic_function& operator=(basic_function&&) = default; basic_function(const stack_reference& r) : basic_function(r.lua_state(), r.stack_index()) {} basic_function(stack_reference&& r) : basic_function(r.lua_state(), r.stack_index()) {} basic_function(lua_State* L, int index = -1) : base_t(L, index) { #ifdef SOL_CHECK_ARGUMENTS stack::check<basic_function>(L, index, type_panic); #endif // Safety } template<typename... Args> function_result operator()(Args&&... args) const { return call<>(std::forward<Args>(args)...); } template<typename... Ret, typename... Args> decltype(auto) operator()(types<Ret...>, Args&&... args) const { return call<Ret...>(std::forward<Args>(args)...); } template<typename... Ret, typename... Args> decltype(auto) call(Args&&... args) const { base_t::push(); int pushcount = stack::multi_push_reference(base_t::lua_state(), std::forward<Args>(args)...); return invoke(types<Ret...>(), std::make_index_sequence<sizeof...(Ret)>(), pushcount); } }; namespace stack { template<typename Signature> struct getter<std::function<Signature>> { typedef meta::bind_traits<Signature> fx_t; typedef typename fx_t::args_list args_lists; typedef meta::tuple_types<typename fx_t::return_type> return_types; template<typename... Args, typename... Ret> static std::function<Signature> get_std_func(types<Ret...>, types<Args...>, lua_State* L, int index) { sol::function f(L, index); auto fx = [f, L, index](Args&&... args) -> meta::return_type_t<Ret...> { return f.call<Ret...>(std::forward<Args>(args)...); }; return std::move(fx); } template<typename... FxArgs> static std::function<Signature> get_std_func(types<void>, types<FxArgs...>, lua_State* L, int index) { sol::function f(L, index); auto fx = [f, L, index](FxArgs&&... args) -> void { f(std::forward<FxArgs>(args)...); }; return std::move(fx); } template<typename... FxArgs> static std::function<Signature> get_std_func(types<>, types<FxArgs...> t, lua_State* L, int index) { return get_std_func(types<void>(), t, L, index); } static std::function<Signature> get(lua_State* L, int index, record& tracking) { tracking.last = 1; tracking.used += 1; type t = type_of(L, index); if (t == type::none || t == type::nil) { return nullptr; } return get_std_func(return_types(), args_lists(), L, index); } }; } // stack } // sol // end of sol/function.hpp // beginning of sol/protected_function.hpp // beginning of sol/protected_function_result.hpp namespace sol { struct protected_function_result : public proxy_base<protected_function_result> { private: lua_State* L; int index; int returncount; int popcount; call_status err; template <typename T> decltype(auto) tagged_get(types<sol::optional<T>>) const { if (!valid()) { return sol::optional<T>(nullopt); } return stack::get<sol::optional<T>>(L, index); } template <typename T> decltype(auto) tagged_get(types<T>) const { #ifdef SOL_CHECK_ARGUMENTS if (!valid()) { type_panic(L, index, type_of(L, index), type::none); } #endif // Check Argument Safety return stack::get<T>(L, index); } optional<error> tagged_get(types<optional<error>>) const { if (valid()) { return nullopt; } return error(detail::direct_error, stack::get<std::string>(L, index)); } error tagged_get(types<error>) const { #ifdef SOL_CHECK_ARGUMENTS if (valid()) { type_panic(L, index, type_of(L, index), type::none); } #endif // Check Argument Safety return error(detail::direct_error, stack::get<std::string>(L, index)); } public: protected_function_result() = default; protected_function_result(lua_State* L, int index = -1, int returncount = 0, int popcount = 0, call_status err = call_status::ok) noexcept : L(L), index(index), returncount(returncount), popcount(popcount), err(err) { } protected_function_result(const protected_function_result&) = default; protected_function_result& operator=(const protected_function_result&) = default; protected_function_result(protected_function_result&& o) noexcept : L(o.L), index(o.index), returncount(o.returncount), popcount(o.popcount), err(o.err) { // Must be manual, otherwise destructor will screw us // return count being 0 is enough to keep things clean // but we will be thorough o.L = nullptr; o.index = 0; o.returncount = 0; o.popcount = 0; o.err = call_status::runtime; } protected_function_result& operator=(protected_function_result&& o) noexcept { L = o.L; index = o.index; returncount = o.returncount; popcount = o.popcount; err = o.err; // Must be manual, otherwise destructor will screw us // return count being 0 is enough to keep things clean // but we will be thorough o.L = nullptr; o.index = 0; o.returncount = 0; o.popcount = 0; o.err = call_status::runtime; return *this; } call_status status() const noexcept { return err; } bool valid() const noexcept { return status() == call_status::ok || status() == call_status::yielded; } template<typename T> decltype(auto) get() const { return tagged_get(types<meta::unqualified_t<T>>()); } lua_State* lua_state() const noexcept { return L; }; int stack_index() const noexcept { return index; }; ~protected_function_result() { stack::remove(L, index, popcount); } }; } // sol // end of sol/protected_function_result.hpp #include <algorithm> namespace sol { namespace detail { inline reference& handler_storage() { static sol::reference h; return h; } struct handler { const reference& target; int stackindex; handler(const reference& target) : target(target), stackindex(0) { if (target.valid()) { stackindex = lua_gettop(target.lua_state()) + 1; target.push(); } } bool valid() const { return stackindex != 0; } ~handler() { if (valid()) { lua_remove(target.lua_state(), stackindex); } } }; } template <typename base_t> class basic_protected_function : public base_t { public: static reference& get_default_handler() { return detail::handler_storage(); } static void set_default_handler(const reference& ref) { detail::handler_storage() = ref; } static void set_default_handler(reference&& ref) { detail::handler_storage() = std::move(ref); } private: call_status luacall(std::ptrdiff_t argcount, std::ptrdiff_t resultcount, detail::handler& h) const { return static_cast<call_status>(lua_pcallk(base_t::lua_state(), static_cast<int>(argcount), static_cast<int>(resultcount), h.stackindex, 0, nullptr)); } template<std::size_t... I, typename... Ret> auto invoke(types<Ret...>, std::index_sequence<I...>, std::ptrdiff_t n, detail::handler& h) const { luacall(n, sizeof...(Ret), h); return stack::pop<std::tuple<Ret...>>(base_t::lua_state()); } template<std::size_t I, typename Ret> Ret invoke(types<Ret>, std::index_sequence<I>, std::ptrdiff_t n, detail::handler& h) const { luacall(n, 1, h); return stack::pop<Ret>(base_t::lua_state()); } template <std::size_t I> void invoke(types<void>, std::index_sequence<I>, std::ptrdiff_t n, detail::handler& h) const { luacall(n, 0, h); } protected_function_result invoke(types<>, std::index_sequence<>, std::ptrdiff_t n, detail::handler& h) const { int stacksize = lua_gettop(base_t::lua_state()); int poststacksize = stacksize; int firstreturn = 1; int returncount = 0; call_status code = call_status::ok; #ifndef SOL_NO_EXCEPTIONS auto onexcept = [&](const char* error) { h.stackindex = 0; if (h.target.valid()) { h.target.push(); stack::push(base_t::lua_state(), error); lua_call(base_t::lua_state(), 1, 1); } else { stack::push(base_t::lua_state(), error); } }; try { #endif // No Exceptions firstreturn = (std::max)(1, static_cast<int>(stacksize - n - static_cast<int>(h.valid()))); code = luacall(n, LUA_MULTRET, h); poststacksize = lua_gettop(base_t::lua_state()) - static_cast<int>(h.valid()); returncount = poststacksize - (firstreturn - 1); #ifndef SOL_NO_EXCEPTIONS } // Handle C++ errors thrown from C++ functions bound inside of lua catch (const char* error) { onexcept(error); firstreturn = lua_gettop(base_t::lua_state()); return protected_function_result(base_t::lua_state(), firstreturn, 0, 1, call_status::runtime); } catch (const std::exception& error) { onexcept(error.what()); firstreturn = lua_gettop(base_t::lua_state()); return protected_function_result(base_t::lua_state(), firstreturn, 0, 1, call_status::runtime); } catch (...) { onexcept("caught (...) unknown error during protected_function call"); firstreturn = lua_gettop(base_t::lua_state()); return protected_function_result(base_t::lua_state(), firstreturn, 0, 1, call_status::runtime); } #endif // No Exceptions return protected_function_result(base_t::lua_state(), firstreturn, returncount, returncount, code); } public: reference error_handler; basic_protected_function() = default; template <typename T, meta::enable<meta::neg<std::is_same<meta::unqualified_t<T>, basic_protected_function>>, meta::neg<std::is_same<base_t, stack_reference>>, std::is_base_of<base_t, meta::unqualified_t<T>>> = meta::enabler> basic_protected_function(T&& r) noexcept : base_t(std::forward<T>(r)) { #ifdef SOL_CHECK_ARGUMENTS if (!is_function<meta::unqualified_t<T>>::value) { auto pp = stack::push_pop(*this); stack::check<basic_protected_function>(base_t::lua_state(), -1, type_panic); } #endif // Safety } basic_protected_function(const basic_protected_function&) = default; basic_protected_function& operator=(const basic_protected_function&) = default; basic_protected_function(basic_protected_function&&) = default; basic_protected_function& operator=(basic_protected_function&&) = default; basic_protected_function(const basic_function<base_t>& b, reference eh = get_default_handler()) : base_t(b), error_handler(std::move(eh)) {} basic_protected_function(basic_function<base_t>&& b, reference eh = get_default_handler()) : base_t(std::move(b)), error_handler(std::move(eh)) {} basic_protected_function(const stack_reference& r, reference eh = get_default_handler()) : basic_protected_function(r.lua_state(), r.stack_index(), std::move(eh)) {} basic_protected_function(stack_reference&& r, reference eh = get_default_handler()) : basic_protected_function(r.lua_state(), r.stack_index(), std::move(eh)) {} template <typename Super> basic_protected_function(proxy_base<Super>&& p, reference eh = get_default_handler()) : basic_protected_function(p.operator basic_function<base_t>(), std::move(eh)) {} template <typename Super> basic_protected_function(const proxy_base<Super>& p, reference eh = get_default_handler()) : basic_protected_function(static_cast<basic_function<base_t>>(p), std::move(eh)) {} basic_protected_function(lua_State* L, int index = -1, reference eh = get_default_handler()) : base_t(L, index), error_handler(std::move(eh)) { #ifdef SOL_CHECK_ARGUMENTS stack::check<basic_protected_function>(L, index, type_panic); #endif // Safety } template<typename... Args> protected_function_result operator()(Args&&... args) const { return call<>(std::forward<Args>(args)...); } template<typename... Ret, typename... Args> decltype(auto) operator()(types<Ret...>, Args&&... args) const { return call<Ret...>(std::forward<Args>(args)...); } template<typename... Ret, typename... Args> decltype(auto) call(Args&&... args) const { detail::handler h(error_handler); base_t::push(); int pushcount = stack::multi_push_reference(base_t::lua_state(), std::forward<Args>(args)...); return invoke(types<Ret...>(), std::make_index_sequence<sizeof...(Ret)>(), pushcount, h); } }; } // sol // end of sol/protected_function.hpp namespace sol { struct stack_proxy : public proxy_base<stack_proxy> { private: lua_State* L; int index; public: stack_proxy() : L(nullptr), index(0) {} stack_proxy(lua_State* L, int index) : L(L), index(index) {} template<typename T> decltype(auto) get() const { return stack::get<T>(L, stack_index()); } int push() const { lua_pushvalue(L, index); return 1; } lua_State* lua_state() const { return L; } int stack_index() const { return index; } template<typename... Ret, typename... Args> decltype(auto) call(Args&&... args) { return get<function>().template call<Ret...>(std::forward<Args>(args)...); } template<typename... Args> decltype(auto) operator()(Args&&... args) { return call<>(std::forward<Args>(args)...); } }; namespace stack { template <> struct getter<stack_proxy> { static stack_proxy get(lua_State* L, int index = -1) { return stack_proxy(L, index); } }; template <> struct pusher<stack_proxy> { static int push(lua_State*, const stack_proxy& ref) { return ref.push(); } }; } // stack namespace detail { template <> struct is_speshul<function_result> : std::true_type {}; template <> struct is_speshul<protected_function_result> : std::true_type {}; template <std::size_t I, typename... Args, typename T> stack_proxy get(types<Args...>, index_value<0>, index_value<I>, const T& fr) { return stack_proxy(fr.lua_state(), static_cast<int>(fr.stack_index() + I)); } template <std::size_t I, std::size_t N, typename Arg, typename... Args, typename T, meta::enable<meta::boolean<(N > 0)>> = meta::enabler> stack_proxy get(types<Arg, Args...>, index_value<N>, index_value<I>, const T& fr) { return get(types<Args...>(), index_value<N - 1>(), index_value<I + lua_size<Arg>::value>(), fr); } } template <> struct tie_size<function_result> : std::integral_constant<std::size_t, SIZE_MAX> {}; template <std::size_t I> stack_proxy get(const function_result& fr) { return stack_proxy(fr.lua_state(), static_cast<int>(fr.stack_index() + I)); } template <std::size_t I, typename... Args> stack_proxy get(types<Args...> t, const function_result& fr) { return detail::get(t, index_value<I>(), index_value<0>(), fr); } template <> struct tie_size<protected_function_result> : std::integral_constant<std::size_t, SIZE_MAX> {}; template <std::size_t I> stack_proxy get(const protected_function_result& fr) { return stack_proxy(fr.lua_state(), static_cast<int>(fr.stack_index() + I)); } template <std::size_t I, typename... Args> stack_proxy get(types<Args...> t, const protected_function_result& fr) { return detail::get(t, index_value<I>(), index_value<0>(), fr); } } // sol // end of sol/stack_proxy.hpp #include <limits> #include <iterator> namespace sol { template <bool is_const> struct va_iterator : std::iterator<std::random_access_iterator_tag, std::conditional_t<is_const, const stack_proxy, stack_proxy>, std::ptrdiff_t, std::conditional_t<is_const, const stack_proxy*, stack_proxy*>, std::conditional_t<is_const, const stack_proxy, stack_proxy>> { typedef std::iterator<std::random_access_iterator_tag, std::conditional_t<is_const, const stack_proxy, stack_proxy>, std::ptrdiff_t, std::conditional_t<is_const, const stack_proxy*, stack_proxy*>, std::conditional_t<is_const, const stack_proxy, stack_proxy>> base_t; typedef typename base_t::reference reference; typedef typename base_t::pointer pointer; typedef typename base_t::value_type value_type; typedef typename base_t::difference_type difference_type; typedef typename base_t::iterator_category iterator_category; lua_State* L; int index; int stacktop; stack_proxy sp; va_iterator() : L(nullptr), index((std::numeric_limits<int>::max)()), stacktop((std::numeric_limits<int>::max)()) {} va_iterator(lua_State* L, int index, int stacktop) : L(L), index(index), stacktop(stacktop), sp(L, index) {} reference operator*() { return stack_proxy(L, index); } pointer operator->() { sp = stack_proxy(L, index); return &sp; } va_iterator& operator++ () { ++index; return *this; } va_iterator operator++ (int) { auto r = *this; this->operator ++(); return r; } va_iterator& operator-- () { --index; return *this; } va_iterator operator-- (int) { auto r = *this; this->operator --(); return r; } va_iterator& operator+= (difference_type idx) { index += static_cast<int>(idx); return *this; } va_iterator& operator-= (difference_type idx) { index -= static_cast<int>(idx); return *this; } difference_type operator- (const va_iterator& r) const { return index - r.index; } va_iterator operator+ (difference_type idx) const { va_iterator r = *this; r += idx; return r; } reference operator[](difference_type idx) { return stack_proxy(L, index + static_cast<int>(idx)); } bool operator==(const va_iterator& r) const { if (stacktop == (std::numeric_limits<int>::max)()) { return r.index == r.stacktop; } else if (r.stacktop == (std::numeric_limits<int>::max)()) { return index == stacktop; } return index == r.index; } bool operator != (const va_iterator& r) const { return !(this->operator==(r)); } bool operator < (const va_iterator& r) const { return index < r.index; } bool operator > (const va_iterator& r) const { return index > r.index; } bool operator <= (const va_iterator& r) const { return index <= r.index; } bool operator >= (const va_iterator& r) const { return index >= r.index; } }; template <bool is_const> inline va_iterator<is_const> operator+(typename va_iterator<is_const>::difference_type n, const va_iterator<is_const>& r) { return r + n; } struct variadic_args { private: lua_State* L; int index; int stacktop; public: typedef stack_proxy reference_type; typedef stack_proxy value_type; typedef stack_proxy* pointer; typedef std::ptrdiff_t difference_type; typedef std::size_t size_type; typedef va_iterator<false> iterator; typedef va_iterator<true> const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; variadic_args() = default; variadic_args(lua_State* L, int index = -1) : L(L), index(lua_absindex(L, index)), stacktop(lua_gettop(L)) {} variadic_args(const variadic_args&) = default; variadic_args& operator=(const variadic_args&) = default; variadic_args(variadic_args&& o) : L(o.L), index(o.index), stacktop(o.stacktop) { // Must be manual, otherwise destructor will screw us // return count being 0 is enough to keep things clean // but will be thorough o.L = nullptr; o.index = 0; o.stacktop = 0; } variadic_args& operator=(variadic_args&& o) { L = o.L; index = o.index; stacktop = o.stacktop; // Must be manual, otherwise destructor will screw us // return count being 0 is enough to keep things clean // but will be thorough o.L = nullptr; o.index = 0; o.stacktop = 0; return *this; } iterator begin() { return iterator(L, index, stacktop + 1); } iterator end() { return iterator(L, stacktop + 1, stacktop + 1); } const_iterator begin() const { return const_iterator(L, index, stacktop + 1); } const_iterator end() const { return const_iterator(L, stacktop + 1, stacktop + 1); } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } reverse_iterator rbegin() { return std::reverse_iterator<iterator>(begin()); } reverse_iterator rend() { return std::reverse_iterator<iterator>(end()); } const_reverse_iterator rbegin() const { return std::reverse_iterator<const_iterator>(begin()); } const_reverse_iterator rend() const { return std::reverse_iterator<const_iterator>(end()); } const_reverse_iterator crbegin() const { return std::reverse_iterator<const_iterator>(cbegin()); } const_reverse_iterator crend() const { return std::reverse_iterator<const_iterator>(cend()); } int push() const { int pushcount = 0; for (int i = index; i <= stacktop; ++i) { lua_pushvalue(L, i); pushcount += 1; } return pushcount; } template<typename T> decltype(auto) get(difference_type start = 0) const { return stack::get<T>(L, index + static_cast<int>(start)); } stack_proxy operator[](difference_type start) const { return stack_proxy(L, index + static_cast<int>(start)); } lua_State* lua_state() const { return L; }; int stack_index() const { return index; }; int leftover_count() const { return stacktop - (index - 1); } int top() const { return stacktop; } }; namespace stack { template <> struct getter<variadic_args> { static variadic_args get(lua_State* L, int index, record& tracking) { tracking.last = 0; return variadic_args(L, index); } }; template <> struct pusher<variadic_args> { static int push(lua_State*, const variadic_args& ref) { return ref.push(); } }; } // stack } // sol // end of sol/variadic_args.hpp namespace sol { template <typename R = reference, bool should_pop = !std::is_base_of<stack_reference, R>::value, typename T> R make_reference(lua_State* L, T&& value) { int backpedal = stack::push(L, std::forward<T>(value)); R r = stack::get<R>(L, -backpedal); if (should_pop) { lua_pop(L, backpedal); } return r; } template <typename T, typename R = reference, bool should_pop = !std::is_base_of<stack_reference, R>::value, typename... Args> R make_reference(lua_State* L, Args&&... args) { int backpedal = stack::push<T>(L, std::forward<Args>(args)...); R r = stack::get<R>(L, -backpedal); if (should_pop) { lua_pop(L, backpedal); } return r; } template <typename base_t> class basic_object : public base_t { private: template<typename T> decltype(auto) as_stack(std::true_type) const { return stack::get<T>(base_t::lua_state(), base_t::stack_index()); } template<typename T> decltype(auto) as_stack(std::false_type) const { base_t::push(); return stack::pop<T>(base_t::lua_state()); } template<typename T> bool is_stack(std::true_type) const { return stack::check<T>(base_t::lua_state(), base_t::stack_index(), no_panic); } template<typename T> bool is_stack(std::false_type) const { auto pp = stack::push_pop(*this); return stack::check<T>(base_t::lua_state(), -1, no_panic); } template <bool invert_and_pop = false> basic_object(std::integral_constant<bool, invert_and_pop>, lua_State* L, int index = -1) noexcept : base_t(L, index) { if (invert_and_pop) { lua_pop(L, -index); } } public: basic_object() noexcept = default; template <typename T, meta::enable<meta::neg<std::is_same<meta::unqualified_t<T>, basic_object>>, meta::neg<std::is_same<base_t, stack_reference>>, std::is_base_of<base_t, meta::unqualified_t<T>>> = meta::enabler> basic_object(T&& r) : base_t(std::forward<T>(r)) {} basic_object(nil_t r) : base_t(r) {} basic_object(const basic_object&) = default; basic_object(basic_object&&) = default; basic_object& operator=(const basic_object&) = default; basic_object& operator=(basic_object&&) = default; basic_object& operator=(const base_t& b) { base_t::operator=(b); return *this; } basic_object& operator=(base_t&& b) { base_t::operator=(std::move(b)); return *this; } basic_object(const stack_reference& r) noexcept : basic_object(r.lua_state(), r.stack_index()) {} basic_object(stack_reference&& r) noexcept : basic_object(r.lua_state(), r.stack_index()) {} template <typename Super> basic_object(const proxy_base<Super>& r) noexcept : basic_object(r.operator basic_object()) {} template <typename Super> basic_object(proxy_base<Super>&& r) noexcept : basic_object(r.operator basic_object()) {} template <typename Super> basic_object& operator=(const proxy_base<Super>& r) { this->operator=(r.operator basic_object()); return *this; } template <typename Super> basic_object& operator=(proxy_base<Super>&& r) { this->operator=(r.operator basic_object()); return *this; } basic_object(lua_State* L, int index = -1) noexcept : base_t(L, index) {} template <typename T, typename... Args> basic_object(lua_State* L, in_place_type_t<T>, Args&&... args) noexcept : basic_object(std::integral_constant<bool, !std::is_base_of<stack_reference, base_t>::value>(), L, -stack::push<T>(L, std::forward<Args>(args)...)) {} template <typename T, typename... Args> basic_object(lua_State* L, in_place_t, T&& arg, Args&&... args) noexcept : basic_object(L, in_place<T>, std::forward<T>(arg), std::forward<Args>(args)...) {} template<typename T> decltype(auto) as() const { return as_stack<T>(std::is_same<base_t, stack_reference>()); } template<typename T> bool is() const { if (!base_t::valid()) return false; return is_stack<T>(std::is_same<base_t, stack_reference>()); } }; template <typename T> object make_object(lua_State* L, T&& value) { return make_reference<object, true>(L, std::forward<T>(value)); } template <typename T, typename... Args> object make_object(lua_State* L, Args&&... args) { return make_reference<T, object, true>(L, std::forward<Args>(args)...); } inline bool operator==(const object& lhs, const nil_t&) { return !lhs.valid(); } inline bool operator==(const nil_t&, const object& rhs) { return !rhs.valid(); } inline bool operator!=(const object& lhs, const nil_t&) { return lhs.valid(); } inline bool operator!=(const nil_t&, const object& rhs) { return rhs.valid(); } } // sol // end of sol/object.hpp namespace sol { template<typename Table, typename Key> struct proxy : public proxy_base<proxy<Table, Key>> { private: typedef meta::condition<meta::is_specialization_of<std::tuple, Key>, Key, std::tuple<meta::condition<std::is_array<meta::unqualified_t<Key>>, Key&, meta::unqualified_t<Key>>>> key_type; template<typename T, std::size_t... I> decltype(auto) tuple_get(std::index_sequence<I...>) const { return tbl.template traverse_get<T>(std::get<I>(key)...); } template<std::size_t... I, typename T> void tuple_set(std::index_sequence<I...>, T&& value) { tbl.traverse_set(std::get<I>(key)..., std::forward<T>(value)); } public: Table tbl; key_type key; template<typename T> proxy(Table table, T&& key) : tbl(table), key(std::forward<T>(key)) {} template<typename T> proxy& set(T&& item) { tuple_set(std::make_index_sequence<std::tuple_size<meta::unqualified_t<key_type>>::value>(), std::forward<T>(item)); return *this; } template<typename... Args> proxy& set_function(Args&&... args) { tbl.set_function(key, std::forward<Args>(args)...); return *this; } template<typename U, meta::enable<meta::neg<is_lua_reference<meta::unwrap_unqualified_t<U>>>, meta::is_callable<meta::unwrap_unqualified_t<U>>> = meta::enabler> proxy& operator=(U&& other) { return set_function(std::forward<U>(other)); } template<typename U, meta::disable<meta::neg<is_lua_reference<meta::unwrap_unqualified_t<U>>>, meta::is_callable<meta::unwrap_unqualified_t<U>>> = meta::enabler> proxy& operator=(U&& other) { return set(std::forward<U>(other)); } template<typename T> decltype(auto) get() const { return tuple_get<T>(std::make_index_sequence<std::tuple_size<meta::unqualified_t<key_type>>::value>()); } template<typename T> decltype(auto) get_or(T&& otherwise) const { typedef decltype(get<T>()) U; sol::optional<U> option = get<sol::optional<U>>(); if (option) { return static_cast<U>(option.value()); } return static_cast<U>(std::forward<T>(otherwise)); } template<typename T, typename D> decltype(auto) get_or(D&& otherwise) const { sol::optional<T> option = get<sol::optional<T>>(); if (option) { return static_cast<T>(option.value()); } return static_cast<T>(std::forward<D>(otherwise)); } template <typename K> decltype(auto) operator[](K&& k) const { auto keys = meta::tuplefy(key, std::forward<K>(k)); return proxy<Table, decltype(keys)>(tbl, std::move(keys)); } template<typename... Ret, typename... Args> decltype(auto) call(Args&&... args) { return get<function>().template call<Ret...>(std::forward<Args>(args)...); } template<typename... Args> decltype(auto) operator()(Args&&... args) { return call<>(std::forward<Args>(args)...); } bool valid() const { stack::push_pop(tbl); auto p = stack::probe_get_field<std::is_same<meta::unqualified_t<Table>, global_table>::value>(tbl.lua_state(), key, lua_gettop(tbl.lua_state())); lua_pop(tbl.lua_state(), p.levels); return p; } }; template<typename Table, typename Key, typename T> inline bool operator==(T&& left, const proxy<Table, Key>& right) { return left == right.template get<std::decay_t<T>>(); } template<typename Table, typename Key, typename T> inline bool operator==(const proxy<Table, Key>& right, T&& left) { return right.template get<std::decay_t<T>>() == left; } template<typename Table, typename Key, typename T> inline bool operator!=(T&& left, const proxy<Table, Key>& right) { return right.template get<std::decay_t<T>>() != left; } template<typename Table, typename Key, typename T> inline bool operator!=(const proxy<Table, Key>& right, T&& left) { return right.template get<std::decay_t<T>>() != left; } template<typename Table, typename Key> inline bool operator==(nil_t, const proxy<Table, Key>& right) { return !right.valid(); } template<typename Table, typename Key> inline bool operator==(const proxy<Table, Key>& right, nil_t) { return !right.valid(); } template<typename Table, typename Key> inline bool operator!=(nil_t, const proxy<Table, Key>& right) { return right.valid(); } template<typename Table, typename Key> inline bool operator!=(const proxy<Table, Key>& right, nil_t) { return right.valid(); } namespace stack { template <typename Table, typename Key> struct pusher<proxy<Table, Key>> { static int push(lua_State*, const proxy<Table, Key>& p) { sol::reference r = p; return r.push(); } }; } // stack } // sol // end of sol/proxy.hpp // beginning of sol/usertype.hpp // beginning of sol/usertype_metatable.hpp // beginning of sol/deprecate.hpp #ifndef SOL_DEPRECATED #ifdef _MSC_VER #define SOL_DEPRECATED __declspec(deprecated) #elif __GNUC__ #define SOL_DEPRECATED __attribute__((deprecated)) #else #define SOL_DEPRECATED [[deprecated]] #endif // compilers #endif // SOL_DEPRECATED namespace sol { namespace detail { template <typename T> struct SOL_DEPRECATED deprecate_type { using type = T; }; } // detail } // sol // end of sol/deprecate.hpp #include <unordered_map> #include <cstdio> namespace sol { namespace usertype_detail { struct no_comp { template <typename A, typename B> bool operator()(A&&, B&&) const { return false; } }; typedef void(*base_walk)(lua_State*, bool&, int&, string_detail::string_shim&); typedef int(*member_search)(lua_State*, void*); struct find_call_pair { member_search first; member_search second; find_call_pair(member_search first, member_search second) : first(first), second(second) {} }; inline bool is_indexer(string_detail::string_shim s) { return s == name_of(meta_function::index) || s == name_of(meta_function::new_index); } inline bool is_indexer(meta_function mf) { return mf == meta_function::index || mf == meta_function::new_index; } inline bool is_indexer(call_construction) { return false; } inline bool is_indexer(base_classes_tag) { return false; } inline auto make_shim(string_detail::string_shim s) { return s; } inline auto make_shim(call_construction) { return string_detail::string_shim(name_of(meta_function::call_function)); } inline auto make_shim(meta_function mf) { return string_detail::string_shim(name_of(mf)); } inline auto make_shim(base_classes_tag) { return string_detail::string_shim(detail::base_class_cast_key()); } template <typename Arg> inline std::string make_string(Arg&& arg) { string_detail::string_shim s = make_shim(arg); return std::string(s.c_str(), s.size()); } template <typename N> inline luaL_Reg make_reg(N&& n, lua_CFunction f) { luaL_Reg l{ make_shim(std::forward<N>(n)).c_str(), f }; return l; } struct registrar { virtual int push_um(lua_State* L) = 0; virtual ~registrar() {} }; template <bool is_index> inline int indexing_fail(lua_State* L) { auto maybeaccessor = stack::get<optional<string_detail::string_shim>>(L, is_index ? -1 : -2); string_detail::string_shim accessor = maybeaccessor.value_or(string_detail::string_shim("(unknown)")); if (is_index) return luaL_error(L, "sol: attempt to index (get) nil value \"%s\" on userdata (bad (misspelled?) key name or does not exist)", accessor.c_str()); else return luaL_error(L, "sol: attempt to index (set) nil value \"%s\" on userdata (bad (misspelled?) key name or does not exist)", accessor.c_str()); } template <bool is_index, typename Base> static void walk_single_base(lua_State* L, bool& found, int& ret, string_detail::string_shim&) { if (found) return; const char* metakey = &usertype_traits<Base>::metatable[0]; const char* gcmetakey = &usertype_traits<Base>::gc_table[0]; const char* basewalkkey = is_index ? detail::base_class_index_propogation_key() : detail::base_class_new_index_propogation_key(); luaL_getmetatable(L, metakey); if (type_of(L, -1) == type::nil) { lua_pop(L, 1); return; } stack::get_field(L, basewalkkey); if (type_of(L, -1) == type::nil) { lua_pop(L, 2); return; } lua_CFunction basewalkfunc = stack::pop<lua_CFunction>(L); lua_pop(L, 1); stack::get_field<true>(L, gcmetakey); int value = basewalkfunc(L); if (value > -1) { found = true; ret = value; } } template <bool is_index, typename... Bases> static void walk_all_bases(lua_State* L, bool& found, int& ret, string_detail::string_shim& accessor) { (void)L; (void)found; (void)ret; (void)accessor; (void)detail::swallow{ 0, (walk_single_base<is_index, Bases>(L, found, ret, accessor), 0)... }; } template <typename T, typename Op> inline int operator_wrap(lua_State* L) { auto maybel = stack::check_get<T>(L, 1); if (maybel) { auto mayber = stack::check_get<T>(L, 2); if (mayber) { auto& l = *maybel; auto& r = *mayber; if (std::is_same<no_comp, Op>::value) { return stack::push(L, detail::ptr(l) == detail::ptr(r)); } else { Op op; return stack::push(L, (detail::ptr(l) == detail::ptr(r)) || op(detail::deref(l), detail::deref(r))); } } } return stack::push(L, false); } template <typename T, typename Op, typename Supports, typename Regs, meta::enable<Supports> = meta::enabler> inline void make_reg_op(Regs& l, int& index, const char* name) { l[index] = { name, &operator_wrap<T, Op> }; ++index; } template <typename T, typename Op, typename Supports, typename Regs, meta::disable<Supports> = meta::enabler> inline void make_reg_op(Regs&, int&, const char*) { // Do nothing if there's no support } struct add_destructor_tag {}; struct check_destructor_tag {}; struct verified_tag {} const verified{}; template <typename T> struct is_constructor : std::false_type {}; template <typename... Args> struct is_constructor<constructors<Args...>> : std::true_type {}; template <typename... Args> struct is_constructor<constructor_wrapper<Args...>> : std::true_type {}; template <typename... Args> struct is_constructor<factory_wrapper<Args...>> : std::true_type {}; template <> struct is_constructor<no_construction> : std::true_type {}; template <typename... Args> using has_constructor = meta::any<is_constructor<meta::unqualified_t<Args>>...>; template <typename T> struct is_destructor : std::false_type {}; template <typename Fx> struct is_destructor<destructor_wrapper<Fx>> : std::true_type {}; template <typename... Args> using has_destructor = meta::any<is_destructor<meta::unqualified_t<Args>>...>; } // usertype_detail template <typename T> struct clean_type { typedef std::conditional_t<std::is_array<meta::unqualified_t<T>>::value, T&, std::decay_t<T>> type; }; template <typename T> using clean_type_t = typename clean_type<T>::type; template <typename T, typename IndexSequence, typename... Tn> struct usertype_metatable : usertype_detail::registrar {}; template <typename T, std::size_t... I, typename... Tn> struct usertype_metatable<T, std::index_sequence<I...>, Tn...> : usertype_detail::registrar { typedef std::make_index_sequence<sizeof...(I) * 2> indices; typedef std::index_sequence<I...> half_indices; typedef std::array<luaL_Reg, sizeof...(Tn) / 2 + 1 + 3> regs_t; typedef std::tuple<Tn...> RawTuple; typedef std::tuple<clean_type_t<Tn> ...> Tuple; template <std::size_t Idx> struct check_binding : is_variable_binding<meta::unqualified_tuple_element_t<Idx, Tuple>> {}; typedef std::unordered_map<std::string, usertype_detail::find_call_pair> mapping_t; Tuple functions; mapping_t mapping; lua_CFunction indexfunc; lua_CFunction newindexfunc; lua_CFunction destructfunc; lua_CFunction callconstructfunc; lua_CFunction indexbase; lua_CFunction newindexbase; usertype_detail::base_walk indexbaseclasspropogation; usertype_detail::base_walk newindexbaseclasspropogation; void* baseclasscheck; void* baseclasscast; bool mustindex; bool secondarymeta; bool hasequals; bool hasless; bool haslessequals; template <std::size_t Idx, meta::enable<std::is_same<lua_CFunction, meta::unqualified_tuple_element<Idx + 1, RawTuple>>> = meta::enabler> inline lua_CFunction make_func() { return std::get<Idx + 1>(functions); } template <std::size_t Idx, meta::disable<std::is_same<lua_CFunction, meta::unqualified_tuple_element<Idx + 1, RawTuple>>> = meta::enabler> inline lua_CFunction make_func() { return call<Idx + 1>; } static bool contains_variable() { typedef meta::any<check_binding<(I * 2 + 1)>...> has_variables; return has_variables::value; } bool contains_index() const { bool idx = false; (void)detail::swallow{ 0, ((idx |= usertype_detail::is_indexer(std::get<I * 2>(functions))), 0) ... }; return idx; } int finish_regs(regs_t& l, int& index) { if (!hasless) { const char* name = name_of(meta_function::less_than).c_str(); usertype_detail::make_reg_op<T, std::less<>, meta::supports_op_less<T>>(l, index, name); } if (!haslessequals) { const char* name = name_of(meta_function::less_than_or_equal_to).c_str(); usertype_detail::make_reg_op<T, std::less_equal<>, meta::supports_op_less_equal<T>>(l, index, name); } if (!hasequals) { const char* name = name_of(meta_function::equal_to).c_str(); usertype_detail::make_reg_op<T, std::conditional_t<meta::supports_op_equal<T>::value, std::equal_to<>, usertype_detail::no_comp>, std::true_type>(l, index, name); } if (destructfunc != nullptr) { l[index] = { name_of(meta_function::garbage_collect).c_str(), destructfunc }; ++index; } return index; } template <std::size_t Idx, typename F> void make_regs(regs_t&, int&, call_construction, F&&) { callconstructfunc = call<Idx + 1>; secondarymeta = true; } template <std::size_t, typename... Bases> void make_regs(regs_t&, int&, base_classes_tag, bases<Bases...>) { if (sizeof...(Bases) < 1) { return; } mustindex = true; (void)detail::swallow{ 0, ((detail::has_derived<Bases>::value = true), 0)... }; static_assert(sizeof(void*) <= sizeof(detail::inheritance_check_function), "The size of this data pointer is too small to fit the inheritance checking function: file a bug report."); static_assert(sizeof(void*) <= sizeof(detail::inheritance_cast_function), "The size of this data pointer is too small to fit the inheritance checking function: file a bug report."); baseclasscheck = (void*)&detail::inheritance<T, Bases...>::type_check; baseclasscast = (void*)&detail::inheritance<T, Bases...>::type_cast; indexbaseclasspropogation = usertype_detail::walk_all_bases<true, Bases...>; newindexbaseclasspropogation = usertype_detail::walk_all_bases<false, Bases...>; } template <std::size_t Idx, typename N, typename F, typename = std::enable_if_t<!meta::any_same<meta::unqualified_t<N>, base_classes_tag, call_construction>::value>> void make_regs(regs_t& l, int& index, N&& n, F&&) { if (is_variable_binding<meta::unqualified_t<F>>::value) { return; } luaL_Reg reg = usertype_detail::make_reg(std::forward<N>(n), make_func<Idx>()); // Returnable scope // That would be a neat keyword for C++ // returnable { ... }; if (reg.name == name_of(meta_function::equal_to)) { hasequals = true; } if (reg.name == name_of(meta_function::less_than)) { hasless = true; } if (reg.name == name_of(meta_function::less_than_or_equal_to)) { haslessequals = true; } if (reg.name == name_of(meta_function::garbage_collect)) { destructfunc = reg.func; return; } else if (reg.name == name_of(meta_function::index)) { indexfunc = reg.func; mustindex = true; return; } else if (reg.name == name_of(meta_function::new_index)) { newindexfunc = reg.func; mustindex = true; return; } l[index] = reg; ++index; } template <typename... Args, typename = std::enable_if_t<sizeof...(Args) == sizeof...(Tn)>> usertype_metatable(Args&&... args) : functions(std::forward<Args>(args)...), mapping(), indexfunc(usertype_detail::indexing_fail<true>), newindexfunc(usertype_detail::indexing_fail<false>), destructfunc(nullptr), callconstructfunc(nullptr), indexbase(&core_indexing_call<true>), newindexbase(&core_indexing_call<false>), indexbaseclasspropogation(usertype_detail::walk_all_bases<true>), newindexbaseclasspropogation(usertype_detail::walk_all_bases<false>), baseclasscheck(nullptr), baseclasscast(nullptr), mustindex(contains_variable() || contains_index()), secondarymeta(contains_variable()), hasequals(false), hasless(false), haslessequals(false) { std::initializer_list<typename mapping_t::value_type> ilist{ { std::pair<std::string, usertype_detail::find_call_pair>( usertype_detail::make_string(std::get<I * 2>(functions)), usertype_detail::find_call_pair(&usertype_metatable::real_find_call<I * 2, I * 2 + 1, false>, &usertype_metatable::real_find_call<I * 2, I * 2 + 1, true>) ) }... }; mapping.insert(ilist); } template <std::size_t I0, std::size_t I1, bool is_index> static int real_find_call(lua_State* L, void* um) { auto& f = *static_cast<usertype_metatable*>(um); if (is_variable_binding<decltype(std::get<I1>(f.functions))>::value) { return real_call_with<I1, is_index, true>(L, f); } return stack::push(L, c_closure(call<I1, is_index>, stack::push(L, light<usertype_metatable>(f)))); } template <bool is_index, bool toplevel = false> static int core_indexing_call(lua_State* L) { usertype_metatable& f = toplevel ? stack::get<light<usertype_metatable>>(L, upvalue_index(1)) : stack::pop<light<usertype_metatable>>(L); static const int keyidx = -2 + static_cast<int>(is_index); if (toplevel && stack::get<type>(L, keyidx) != type::string) { return is_index ? f.indexfunc(L) : f.newindexfunc(L); } std::string name = stack::get<std::string>(L, keyidx); auto memberit = f.mapping.find(name); if (memberit != f.mapping.cend()) { auto& member = is_index ? memberit->second.second : memberit->second.first; return (member)(L, static_cast<void*>(&f)); } string_detail::string_shim accessor = name; int ret = 0; bool found = false; // Otherwise, we need to do propagating calls through the bases if (is_index) f.indexbaseclasspropogation(L, found, ret, accessor); else f.newindexbaseclasspropogation(L, found, ret, accessor); if (found) { return ret; } return toplevel ? (is_index ? f.indexfunc(L) : f.newindexfunc(L)) : -1; } static int real_index_call(lua_State* L) { return core_indexing_call<true, true>(L); } static int real_new_index_call(lua_State* L) { return core_indexing_call<false, true>(L); } template <std::size_t Idx, bool is_index = true, bool is_variable = false> static int real_call(lua_State* L) { usertype_metatable& f = stack::get<light<usertype_metatable>>(L, upvalue_index(1)); return real_call_with<Idx, is_index, is_variable>(L, f); } template <std::size_t Idx, bool is_index = true, bool is_variable = false> static int real_call_with(lua_State* L, usertype_metatable& um) { auto& f = std::get<Idx>(um.functions); return call_detail::call_wrapped<T, is_index, is_variable>(L, f); } template <std::size_t Idx, bool is_index = true, bool is_variable = false> static int call(lua_State* L) { return detail::static_trampoline<(&real_call<Idx, is_index, is_variable>)>(L); } template <std::size_t Idx, bool is_index = true, bool is_variable = false> static int call_with(lua_State* L) { return detail::static_trampoline<(&real_call_with<Idx, is_index, is_variable>)>(L); } static int index_call(lua_State* L) { return detail::static_trampoline<(&real_index_call)>(L); } static int new_index_call(lua_State* L) { return detail::static_trampoline<(&real_new_index_call)>(L); } virtual int push_um(lua_State* L) override { return stack::push(L, std::move(*this)); } ~usertype_metatable() override { } }; namespace stack { template <typename T, std::size_t... I, typename... Args> struct pusher<usertype_metatable<T, std::index_sequence<I...>, Args...>> { typedef usertype_metatable<T, std::index_sequence<I...>, Args...> umt_t; typedef typename umt_t::regs_t regs_t; static umt_t& make_cleanup(lua_State* L, umt_t&& umx) { // ensure some sort of uniqueness static int uniqueness = 0; std::string uniquegcmetakey = usertype_traits<T>::user_gc_metatable; // std::to_string doesn't exist in android still, with NDK, so this bullshit // is necessary // thanks, Android :v int appended = snprintf(nullptr, 0, "%d", uniqueness); std::size_t insertionpoint = uniquegcmetakey.length() - 1; uniquegcmetakey.append(appended, '\0'); char* uniquetarget = &uniquegcmetakey[insertionpoint]; snprintf(uniquetarget, uniquegcmetakey.length(), "%d", uniqueness); ++uniqueness; const char* gcmetakey = &usertype_traits<T>::gc_table[0]; // Make sure userdata's memory is properly in lua first, // otherwise all the light userdata we make later will become invalid stack::push<user<umt_t>>(L, metatable_key, uniquegcmetakey, std::move(umx)); // Create the top level thing that will act as our deleter later on stack_reference umt(L, -1); stack::set_field<true>(L, gcmetakey, umt); umt.pop(); stack::get_field<true>(L, gcmetakey); return stack::pop<light<umt_t>>(L); } static int push(lua_State* L, umt_t&& umx) { umt_t& um = make_cleanup(L, std::move(umx)); regs_t value_table{ {} }; int lastreg = 0; (void)detail::swallow{ 0, (um.template make_regs<(I * 2)>(value_table, lastreg, std::get<(I * 2)>(um.functions), std::get<(I * 2 + 1)>(um.functions)), 0)... }; um.finish_regs(value_table, lastreg); value_table[lastreg] = { nullptr, nullptr }; regs_t ref_table = value_table; regs_t unique_table = value_table; bool hasdestructor = !value_table.empty() && name_of(meta_function::garbage_collect) == value_table[lastreg - 1].name; if (hasdestructor) { ref_table[lastreg - 1] = { nullptr, nullptr }; unique_table[lastreg - 1] = { value_table[lastreg - 1].name, detail::unique_destruct<T> }; } // Now use um const bool& mustindex = um.mustindex; for (std::size_t i = 0; i < 3; ++i) { // Pointer types, AKA "references" from C++ const char* metakey = nullptr; luaL_Reg* metaregs = nullptr; switch (i) { case 0: metakey = &usertype_traits<T*>::metatable[0]; metaregs = ref_table.data(); break; case 1: metakey = &usertype_traits<detail::unique_usertype<T>>::metatable[0]; metaregs = unique_table.data(); break; case 2: default: metakey = &usertype_traits<T>::metatable[0]; metaregs = value_table.data(); break; } luaL_newmetatable(L, metakey); stack_reference t(L, -1); stack::push(L, make_light(um)); luaL_setfuncs(L, metaregs, 1); if (um.baseclasscheck != nullptr) { stack::set_field(L, detail::base_class_check_key(), um.baseclasscheck, t.stack_index()); } if (um.baseclasscast != nullptr) { stack::set_field(L, detail::base_class_cast_key(), um.baseclasscast, t.stack_index()); } stack::set_field(L, detail::base_class_index_propogation_key(), make_closure(um.indexbase, make_light(um)), t.stack_index()); stack::set_field(L, detail::base_class_new_index_propogation_key(), make_closure(um.newindexbase, make_light(um)), t.stack_index()); if (mustindex) { // Basic index pushing: specialize // index and newindex to give variables and stuff stack::set_field(L, meta_function::index, make_closure(umt_t::index_call, make_light(um)), t.stack_index()); stack::set_field(L, meta_function::new_index, make_closure(umt_t::new_index_call, make_light(um)), t.stack_index()); } else { // If there's only functions, we can use the fast index version stack::set_field(L, meta_function::index, t, t.stack_index()); } // metatable on the metatable // for call constructor purposes and such lua_createtable(L, 0, 3); stack_reference metabehind(L, -1); if (um.callconstructfunc != nullptr) { stack::set_field(L, meta_function::call_function, make_closure(um.callconstructfunc, make_light(um)), metabehind.stack_index()); } if (um.secondarymeta) { stack::set_field(L, meta_function::index, make_closure(umt_t::index_call, make_light(um)), metabehind.stack_index()); stack::set_field(L, meta_function::new_index, make_closure(umt_t::new_index_call, make_light(um)), metabehind.stack_index()); } stack::set_field(L, metatable_key, metabehind, t.stack_index()); metabehind.pop(); // We want to just leave the table // in the registry only, otherwise we return it t.pop(); } // Now for the shim-table that actually gets assigned to the name luaL_newmetatable(L, &usertype_traits<T>::user_metatable[0]); stack_reference t(L, -1); stack::push(L, make_light(um)); luaL_setfuncs(L, value_table.data(), 1); { lua_createtable(L, 0, 3); stack_reference metabehind(L, -1); if (um.callconstructfunc != nullptr) { stack::set_field(L, meta_function::call_function, make_closure(um.callconstructfunc, make_light(um)), metabehind.stack_index()); } if (um.secondarymeta) { stack::set_field(L, meta_function::index, make_closure(umt_t::index_call, make_light(um)), metabehind.stack_index()); stack::set_field(L, meta_function::new_index, make_closure(umt_t::new_index_call, make_light(um)), metabehind.stack_index()); } stack::set_field(L, metatable_key, metabehind, t.stack_index()); metabehind.pop(); } return 1; } }; } // stack } // sol // end of sol/usertype_metatable.hpp // beginning of sol/simple_usertype_metatable.hpp namespace sol { namespace usertype_detail { const lua_Integer toplevel_magic = static_cast<lua_Integer>(0x00000001); struct variable_wrapper { virtual int index(lua_State* L) = 0; virtual int new_index(lua_State* L) = 0; virtual ~variable_wrapper() {}; }; template <typename T, typename F> struct callable_binding : variable_wrapper { F fx; template <typename Arg> callable_binding(Arg&& arg) : fx(std::forward<Arg>(arg)) {} virtual int index(lua_State* L) override { return call_detail::call_wrapped<T, true, true>(L, fx); } virtual int new_index(lua_State* L) override { return call_detail::call_wrapped<T, false, true>(L, fx); } }; typedef std::unordered_map<std::string, std::unique_ptr<variable_wrapper>> variable_map; typedef std::unordered_map<std::string, object> function_map; struct simple_map { const char* metakey; variable_map variables; function_map functions; base_walk indexbaseclasspropogation; base_walk newindexbaseclasspropogation; simple_map(const char* mkey, base_walk index, base_walk newindex, variable_map&& vars, function_map&& funcs) : metakey(mkey), variables(std::move(vars)), functions(std::move(funcs)), indexbaseclasspropogation(index), newindexbaseclasspropogation(newindex) {} }; template <typename T> inline int simple_metatable_newindex(lua_State* L) { int isnum = 0; lua_Integer magic = lua_tointegerx(L, lua_upvalueindex(4), &isnum); if (isnum != 0 && magic == toplevel_magic) { for (std::size_t i = 0; i < 3; lua_pop(L, 1), ++i) { // Pointer types, AKA "references" from C++ const char* metakey = nullptr; switch (i) { case 0: metakey = &usertype_traits<T*>::metatable[0]; break; case 1: metakey = &usertype_traits<detail::unique_usertype<T>>::metatable[0]; break; case 2: default: metakey = &usertype_traits<T>::metatable[0]; break; } luaL_getmetatable(L, metakey); int tableindex = lua_gettop(L); if (type_of(L, tableindex) == type::nil) { continue; } stack::set_field<false, true>(L, stack_reference(L, 2), stack_reference(L, 3), tableindex); } lua_settop(L, 0); return 0; } lua_pop(L, 1); return indexing_fail<false>(L); } template <bool is_index, bool toplevel = false> inline int simple_core_indexing_call(lua_State* L) { simple_map& sm = toplevel ? stack::get<user<simple_map>>(L, upvalue_index(1)) : stack::pop<user<simple_map>>(L); variable_map& variables = sm.variables; function_map& functions = sm.functions; static const int keyidx = -2 + static_cast<int>(is_index); if (toplevel) { if (stack::get<type>(L, keyidx) != type::string) { lua_CFunction indexingfunc = is_index ? stack::get<lua_CFunction>(L, upvalue_index(2)) : stack::get<lua_CFunction>(L, upvalue_index(3)); return indexingfunc(L); } } string_detail::string_shim accessor = stack::get<string_detail::string_shim>(L, keyidx); std::string accessorkey = accessor.c_str(); auto vit = variables.find(accessorkey); if (vit != variables.cend()) { auto& varwrap = *(vit->second); if (is_index) { return varwrap.index(L); } return varwrap.new_index(L); } auto fit = functions.find(accessorkey); if (fit != functions.cend()) { auto& func = (fit->second); return stack::push(L, func); } // Check table storage first for a method that works luaL_getmetatable(L, sm.metakey); if (type_of(L, -1) != type::nil) { stack::get_field<false, true>(L, accessor.c_str(), lua_gettop(L)); if (type_of(L, -1) != type::nil) { // Woo, we found it? lua_remove(L, -2); return 1; } lua_pop(L, 1); } lua_pop(L, 1); int ret = 0; bool found = false; // Otherwise, we need to do propagating calls through the bases if (is_index) { sm.indexbaseclasspropogation(L, found, ret, accessor); } else { sm.newindexbaseclasspropogation(L, found, ret, accessor); } if (found) { return ret; } if (toplevel) { lua_CFunction indexingfunc = is_index ? stack::get<lua_CFunction>(L, upvalue_index(2)) : stack::get<lua_CFunction>(L, upvalue_index(3)); return indexingfunc(L); } return -1; } inline int simple_real_index_call(lua_State* L) { return simple_core_indexing_call<true, true>(L); } inline int simple_real_new_index_call(lua_State* L) { return simple_core_indexing_call<false, true>(L); } inline int simple_index_call(lua_State* L) { return detail::static_trampoline<(&simple_real_index_call)>(L); } inline int simple_new_index_call(lua_State* L) { return detail::static_trampoline<(&simple_real_new_index_call)>(L); } } struct simple_tag {} const simple{}; template <typename T> struct simple_usertype_metatable : usertype_detail::registrar { public: usertype_detail::function_map registrations; usertype_detail::variable_map varmap; object callconstructfunc; lua_CFunction indexfunc; lua_CFunction newindexfunc; lua_CFunction indexbase; lua_CFunction newindexbase; usertype_detail::base_walk indexbaseclasspropogation; usertype_detail::base_walk newindexbaseclasspropogation; void* baseclasscheck; void* baseclasscast; bool mustindex; bool secondarymeta; template <typename N> void insert(N&& n, object&& o) { std::string key = usertype_detail::make_string(std::forward<N>(n)); auto hint = registrations.find(key); if (hint == registrations.cend()) { registrations.emplace_hint(hint, std::move(key), std::move(o)); return; } hint->second = std::move(o); } template <typename N, typename F, meta::enable<meta::is_callable<meta::unwrap_unqualified_t<F>>> = meta::enabler> void add_function(lua_State* L, N&& n, F&& f) { insert(std::forward<N>(n), make_object(L, as_function_reference(std::forward<F>(f)))); } template <typename N, typename F, meta::disable<meta::is_callable<meta::unwrap_unqualified_t<F>>> = meta::enabler> void add_function(lua_State* L, N&& n, F&& f) { object o = make_object(L, std::forward<F>(f)); if (std::is_same<meta::unqualified_t<N>, call_construction>::value) { callconstructfunc = std::move(o); return; } insert(std::forward<N>(n), std::move(o)); } template <typename N, typename F, meta::disable<is_variable_binding<meta::unqualified_t<F>>> = meta::enabler> void add(lua_State* L, N&& n, F&& f) { add_function(L, std::forward<N>(n), std::forward<F>(f)); } template <typename N, typename F, meta::enable<is_variable_binding<meta::unqualified_t<F>>> = meta::enabler> void add(lua_State*, N&& n, F&& f) { mustindex = true; secondarymeta = true; std::string key = usertype_detail::make_string(std::forward<N>(n)); auto o = std::make_unique<usertype_detail::callable_binding<T, std::decay_t<F>>>(std::forward<F>(f)); auto hint = varmap.find(key); if (hint == varmap.cend()) { varmap.emplace_hint(hint, std::move(key), std::move(o)); return; } hint->second = std::move(o); } template <typename N, typename... Fxs> void add(lua_State* L, N&& n, constructor_wrapper<Fxs...> c) { object o(L, in_place<detail::tagged<T, constructor_wrapper<Fxs...>>>, std::move(c)); if (std::is_same<meta::unqualified_t<N>, call_construction>::value) { callconstructfunc = std::move(o); return; } insert(std::forward<N>(n), std::move(o)); } template <typename N, typename... Lists> void add(lua_State* L, N&& n, constructor_list<Lists...> c) { object o(L, in_place<detail::tagged<T, constructor_list<Lists...>>>, std::move(c)); if (std::is_same<meta::unqualified_t<N>, call_construction>::value) { callconstructfunc = std::move(o); return; } insert(std::forward<N>(n), std::move(o)); } template <typename N> void add(lua_State* L, N&& n, destructor_wrapper<void> c) { object o(L, in_place<detail::tagged<T, destructor_wrapper<void>>>, std::move(c)); if (std::is_same<meta::unqualified_t<N>, call_construction>::value) { callconstructfunc = std::move(o); return; } insert(std::forward<N>(n), std::move(o)); } template <typename N, typename Fx> void add(lua_State* L, N&& n, destructor_wrapper<Fx> c) { object o(L, in_place<detail::tagged<T, destructor_wrapper<Fx>>>, std::move(c)); if (std::is_same<meta::unqualified_t<N>, call_construction>::value) { callconstructfunc = std::move(o); return; } insert(std::forward<N>(n), std::move(o)); } template <typename... Bases> void add(lua_State*, base_classes_tag, bases<Bases...>) { static_assert(sizeof(usertype_detail::base_walk) <= sizeof(void*), "size of function pointer is greater than sizeof(void*); cannot work on this platform. Please file a bug report."); if (sizeof...(Bases) < 1) { return; } mustindex = true; (void)detail::swallow{ 0, ((detail::has_derived<Bases>::value = true), 0)... }; static_assert(sizeof(void*) <= sizeof(detail::inheritance_check_function), "The size of this data pointer is too small to fit the inheritance checking function: Please file a bug report."); static_assert(sizeof(void*) <= sizeof(detail::inheritance_cast_function), "The size of this data pointer is too small to fit the inheritance checking function: Please file a bug report."); baseclasscheck = (void*)&detail::inheritance<T, Bases...>::type_check; baseclasscast = (void*)&detail::inheritance<T, Bases...>::type_cast; indexbaseclasspropogation = usertype_detail::walk_all_bases<true, Bases...>; newindexbaseclasspropogation = usertype_detail::walk_all_bases<false, Bases...>; } private: template<std::size_t... I, typename Tuple> simple_usertype_metatable(usertype_detail::verified_tag, std::index_sequence<I...>, lua_State* L, Tuple&& args) : callconstructfunc(nil), indexfunc(&usertype_detail::indexing_fail<true>), newindexfunc(&usertype_detail::indexing_fail<false>), indexbase(&usertype_detail::simple_core_indexing_call<true>), newindexbase(&usertype_detail::simple_core_indexing_call<false>), indexbaseclasspropogation(usertype_detail::walk_all_bases<true>), newindexbaseclasspropogation(&usertype_detail::walk_all_bases<false>), baseclasscheck(nullptr), baseclasscast(nullptr), mustindex(false), secondarymeta(false) { (void)detail::swallow{ 0, (add(L, detail::forward_get<I * 2>(args), detail::forward_get<I * 2 + 1>(args)),0)... }; } template<typename... Args> simple_usertype_metatable(lua_State* L, usertype_detail::verified_tag v, Args&&... args) : simple_usertype_metatable(v, std::make_index_sequence<sizeof...(Args) / 2>(), L, std::forward_as_tuple(std::forward<Args>(args)...)) {} template<typename... Args> simple_usertype_metatable(lua_State* L, usertype_detail::add_destructor_tag, Args&&... args) : simple_usertype_metatable(L, usertype_detail::verified, std::forward<Args>(args)..., "__gc", default_destructor) {} template<typename... Args> simple_usertype_metatable(lua_State* L, usertype_detail::check_destructor_tag, Args&&... args) : simple_usertype_metatable(L, meta::condition<meta::all<std::is_destructible<T>, meta::neg<usertype_detail::has_destructor<Args...>>>, usertype_detail::add_destructor_tag, usertype_detail::verified_tag>(), std::forward<Args>(args)...) {} public: simple_usertype_metatable(lua_State* L) : simple_usertype_metatable(L, meta::condition<meta::all<std::is_default_constructible<T>>, decltype(default_constructor), usertype_detail::check_destructor_tag>()) {} template<typename Arg, typename... Args, meta::disable_any< meta::any_same<meta::unqualified_t<Arg>, usertype_detail::verified_tag, usertype_detail::add_destructor_tag, usertype_detail::check_destructor_tag >, meta::is_specialization_of<constructors, meta::unqualified_t<Arg>>, meta::is_specialization_of<constructor_wrapper, meta::unqualified_t<Arg>> > = meta::enabler> simple_usertype_metatable(lua_State* L, Arg&& arg, Args&&... args) : simple_usertype_metatable(L, meta::condition<meta::all<std::is_default_constructible<T>, meta::neg<usertype_detail::has_constructor<Args...>>>, decltype(default_constructor), usertype_detail::check_destructor_tag>(), std::forward<Arg>(arg), std::forward<Args>(args)...) {} template<typename... Args, typename... CArgs> simple_usertype_metatable(lua_State* L, constructors<CArgs...> constructorlist, Args&&... args) : simple_usertype_metatable(L, usertype_detail::check_destructor_tag(), std::forward<Args>(args)..., "new", constructorlist) {} template<typename... Args, typename... Fxs> simple_usertype_metatable(lua_State* L, constructor_wrapper<Fxs...> constructorlist, Args&&... args) : simple_usertype_metatable(L, usertype_detail::check_destructor_tag(), std::forward<Args>(args)..., "new", constructorlist) {} virtual int push_um(lua_State* L) override { return stack::push(L, std::move(*this)); } }; namespace stack { template <typename T> struct pusher<simple_usertype_metatable<T>> { typedef simple_usertype_metatable<T> umt_t; static usertype_detail::simple_map& make_cleanup(lua_State* L, umt_t& umx) { static int uniqueness = 0; std::string uniquegcmetakey = usertype_traits<T>::user_gc_metatable; // std::to_string doesn't exist in android still, with NDK, so this bullshit // is necessary // thanks, Android :v int appended = snprintf(nullptr, 0, "%d", uniqueness); std::size_t insertionpoint = uniquegcmetakey.length() - 1; uniquegcmetakey.append(appended, '\0'); char* uniquetarget = &uniquegcmetakey[insertionpoint]; snprintf(uniquetarget, uniquegcmetakey.length(), "%d", uniqueness); ++uniqueness; const char* gcmetakey = &usertype_traits<T>::gc_table[0]; stack::push<user<usertype_detail::simple_map>>(L, metatable_key, uniquegcmetakey, &usertype_traits<T>::metatable[0], umx.indexbaseclasspropogation, umx.newindexbaseclasspropogation, std::move(umx.varmap), std::move(umx.registrations)); stack_reference stackvarmap(L, -1); stack::set_field<true>(L, gcmetakey, stackvarmap); stackvarmap.pop(); stack::get_field<true>(L, gcmetakey); usertype_detail::simple_map& varmap = stack::pop<light<usertype_detail::simple_map>>(L); return varmap; } static int push(lua_State* L, umt_t&& umx) { auto& varmap = make_cleanup(L, umx); bool hasequals = false; bool hasless = false; bool haslessequals = false; auto register_kvp = [&](std::size_t i, stack_reference& t, const std::string& first, object& second) { if (first == name_of(meta_function::equal_to)) { hasequals = true; } else if (first == name_of(meta_function::less_than)) { hasless = true; } else if (first == name_of(meta_function::less_than_or_equal_to)) { haslessequals = true; } else if (first == name_of(meta_function::index)) { umx.indexfunc = second.template as<lua_CFunction>(); } else if (first == name_of(meta_function::new_index)) { umx.newindexfunc = second.template as<lua_CFunction>(); } switch (i) { case 0: if (first == name_of(meta_function::garbage_collect)) { return; } break; case 1: if (first == name_of(meta_function::garbage_collect)) { stack::set_field(L, first, detail::unique_destruct<T>, t.stack_index()); return; } break; case 2: default: break; } stack::set_field(L, first, second, t.stack_index()); }; for (std::size_t i = 0; i < 3; ++i) { // Pointer types, AKA "references" from C++ const char* metakey = nullptr; switch (i) { case 0: metakey = &usertype_traits<T*>::metatable[0]; break; case 1: metakey = &usertype_traits<detail::unique_usertype<T>>::metatable[0]; break; case 2: default: metakey = &usertype_traits<T>::metatable[0]; break; } luaL_newmetatable(L, metakey); stack_reference t(L, -1); for (auto& kvp : varmap.functions) { auto& first = std::get<0>(kvp); auto& second = std::get<1>(kvp); register_kvp(i, t, first, second); } luaL_Reg opregs[4]{}; int opregsindex = 0; if (!hasless) { const char* name = name_of(meta_function::less_than).c_str(); usertype_detail::make_reg_op<T, std::less<>, meta::supports_op_less<T>>(opregs, opregsindex, name); } if (!haslessequals) { const char* name = name_of(meta_function::less_than_or_equal_to).c_str(); usertype_detail::make_reg_op<T, std::less_equal<>, meta::supports_op_less_equal<T>>(opregs, opregsindex, name); } if (!hasequals) { const char* name = name_of(meta_function::equal_to).c_str(); usertype_detail::make_reg_op<T, std::conditional_t<meta::supports_op_equal<T>::value, std::equal_to<>, usertype_detail::no_comp>, std::true_type>(opregs, opregsindex, name); } t.push(); luaL_setfuncs(L, opregs, 0); t.pop(); if (umx.baseclasscheck != nullptr) { stack::set_field(L, detail::base_class_check_key(), umx.baseclasscheck, t.stack_index()); } if (umx.baseclasscast != nullptr) { stack::set_field(L, detail::base_class_cast_key(), umx.baseclasscast, t.stack_index()); } // Base class propagation features stack::set_field(L, detail::base_class_index_propogation_key(), umx.indexbase, t.stack_index()); stack::set_field(L, detail::base_class_new_index_propogation_key(), umx.newindexbase, t.stack_index()); if (umx.mustindex) { // use indexing function stack::set_field(L, meta_function::index, make_closure(&usertype_detail::simple_index_call, make_light(varmap), umx.indexfunc, umx.newindexfunc ), t.stack_index()); stack::set_field(L, meta_function::new_index, make_closure(&usertype_detail::simple_new_index_call, make_light(varmap), umx.indexfunc, umx.newindexfunc ), t.stack_index()); } else { // Metatable indexes itself stack::set_field(L, meta_function::index, t, t.stack_index()); } // metatable on the metatable // for call constructor purposes and such lua_createtable(L, 0, 2 * static_cast<int>(umx.secondarymeta) + static_cast<int>(umx.callconstructfunc.valid())); stack_reference metabehind(L, -1); if (umx.callconstructfunc.valid()) { stack::set_field(L, sol::meta_function::call_function, umx.callconstructfunc, metabehind.stack_index()); } if (umx.secondarymeta) { stack::set_field(L, meta_function::index, make_closure(&usertype_detail::simple_index_call, make_light(varmap), umx.indexfunc, umx.newindexfunc ), metabehind.stack_index()); stack::set_field(L, meta_function::new_index, make_closure(&usertype_detail::simple_new_index_call, make_light(varmap), umx.indexfunc, umx.newindexfunc ), metabehind.stack_index()); } stack::set_field(L, metatable_key, metabehind, t.stack_index()); metabehind.pop(); t.pop(); } // Now for the shim-table that actually gets pushed luaL_newmetatable(L, &usertype_traits<T>::user_metatable[0]); stack_reference t(L, -1); for (auto& kvp : varmap.functions) { auto& first = std::get<0>(kvp); auto& second = std::get<1>(kvp); register_kvp(2, t, first, second); } { lua_createtable(L, 0, 2 + static_cast<int>(umx.callconstructfunc.valid())); stack_reference metabehind(L, -1); if (umx.callconstructfunc.valid()) { stack::set_field(L, sol::meta_function::call_function, umx.callconstructfunc, metabehind.stack_index()); } // use indexing function stack::set_field(L, meta_function::index, make_closure(&usertype_detail::simple_index_call, make_light(varmap), &usertype_detail::simple_index_call, &usertype_detail::simple_metatable_newindex<T>, usertype_detail::toplevel_magic ), metabehind.stack_index()); stack::set_field(L, meta_function::new_index, make_closure(&usertype_detail::simple_new_index_call, make_light(varmap), &usertype_detail::simple_index_call, &usertype_detail::simple_metatable_newindex<T>, usertype_detail::toplevel_magic ), metabehind.stack_index()); stack::set_field(L, metatable_key, metabehind, t.stack_index()); metabehind.pop(); } // Don't pop the table when we're done; // return it return 1; } }; } // stack } // sol // end of sol/simple_usertype_metatable.hpp // beginning of sol/container_usertype_metatable.hpp namespace sol { namespace detail { template <typename T> struct has_find { private: typedef std::array<char, 1> one; typedef std::array<char, 2> two; template <typename C> static one test(decltype(&C::find)); template <typename C> static two test(...); public: static const bool value = sizeof(test<T>(0)) == sizeof(char); }; template <typename T> T& get_first(const T& t) { return std::forward<T>(t); } template <typename A, typename B> decltype(auto) get_first(const std::pair<A, B>& t) { return t.first; } template <typename C, typename I, meta::enable<has_find<meta::unqualified_t<C>>> = meta::enabler> auto find(C& c, I&& i) { return c.find(std::forward<I>(i)); } template <typename C, typename I, meta::disable<has_find<meta::unqualified_t<C>>> = meta::enabler> auto find(C& c, I&& i) { using std::begin; using std::end; return std::find_if(begin(c), end(c), [&i](auto&& x) { return i == get_first(x); }); } } template <typename Raw, typename C = void> struct container_usertype_metatable { typedef meta::unqualified_t<Raw> T; typedef std::size_t K; typedef typename T::value_type V; typedef typename T::iterator I; typedef std::remove_reference_t<decltype(*std::declval<I&>())> IR; struct iter { T& source; I it; iter(T& source, I it) : source(source), it(std::move(it)) {} }; static auto& get_src(lua_State* L) { #ifdef SOL_SAFE_USERTYPE auto p = stack::get<T*>(L, 1); if (p == nullptr) { luaL_error(L, "sol: 'self' argument is nil (pass 'self' as first argument or call on proper type)"); } return *p; #else return stack::get<T>(L, 1); #endif } static int real_index_call(lua_State* L) { auto& src = get_src(L); #ifdef SOL_SAFE_USERTYPE auto maybek = stack::check_get<K>(L, 2); if (maybek) { using std::begin; auto it = begin(src); K k = *maybek; if (k <= src.size() && k > 0) { --k; std::advance(it, k); return stack::push_reference(L, *it); } } return stack::push(L, nil); #else using std::begin; auto it = begin(src); K k = stack::get<K>(L, 2); --k; std::advance(it, k); return stack::push_reference(L, *it); #endif // Safety } template <bool b, meta::disable<meta::boolean<b>> = meta::enabler> static int real_new_index_call_const(std::integral_constant<bool, b>, lua_State* L) { luaL_error(L, "sol: cannot write to a const value type or an immutable iterator (e.g., std::set)"); return 0; } template <bool b, meta::enable<meta::boolean<b>> = meta::enabler> static int real_new_index_call_const(std::integral_constant<bool, b>, lua_State* L) { auto& src = get_src(L); #ifdef SOL_SAFE_USERTYPE auto maybek = stack::check_get<K>(L, 2); if (maybek) { K k = *maybek; if (k <= src.size() && k > 0) { --k; using std::begin; auto it = begin(src); std::advance(it, k); *it = stack::get<V>(L, 3); } } #else using std::begin; auto it = begin(src); K k = stack::get<K>(L, 2); --k; std::advance(it, k); *it = stack::get<V>(L, 3); #endif return 0; } static int real_new_index_call(lua_State* L) { return real_new_index_call_const(meta::neg<meta::any<std::is_const<V>, std::is_const<IR>>>(), L); } static int real_pairs_next_call(lua_State* L) { using std::end; iter& i = stack::get<user<iter>>(L, 1); auto& source = i.source; auto& it = i.it; K k = stack::get<K>(L, 2); if (it == end(source)) { return 0; } int p = stack::multi_push_reference(L, k + 1, *it); std::advance(it, 1); return p; } static int real_pairs_call(lua_State* L) { auto& src = get_src(L); using std::begin; stack::push(L, pairs_next_call); stack::push<user<iter>>(L, src, begin(src)); stack::push(L, 0); return 3; } static int real_length_call(lua_State*L) { auto& src = get_src(L); return stack::push(L, src.size()); } #if 0 static int real_push_back_call(lua_State*L) { auto& src = get_src(L); src.push_back(stack::get<V>(L, 2)); return 0; } static int real_insert_call(lua_State*L) { using std::begin; auto& src = get_src(L); src.insert(std::next(begin(src), stack::get<K>(L, 2)), stack::get<V>(L, 3)); return 0; } static int push_back_call(lua_State*L) { return detail::static_trampoline<(&real_length_call)>(L); } static int insert_call(lua_State*L) { return detail::static_trampoline<(&real_insert_call)>(L); } #endif // Sometime later, in a distant universe... static int length_call(lua_State*L) { return detail::static_trampoline<(&real_length_call)>(L); } static int pairs_next_call(lua_State*L) { return detail::static_trampoline<(&real_pairs_next_call)>(L); } static int pairs_call(lua_State*L) { return detail::static_trampoline<(&real_pairs_call)>(L); } static int index_call(lua_State*L) { return detail::static_trampoline<(&real_index_call)>(L); } static int new_index_call(lua_State*L) { return detail::static_trampoline<(&real_new_index_call)>(L); } }; template <typename Raw> struct container_usertype_metatable<Raw, std::enable_if_t<meta::has_key_value_pair<meta::unqualified_t<Raw>>::value>> { typedef meta::unqualified_t<Raw> T; typedef typename T::value_type KV; typedef typename KV::first_type K; typedef typename KV::second_type V; typedef typename T::iterator I; struct iter { T& source; I it; iter(T& source, I it) : source(source), it(std::move(it)) {} }; static auto& get_src(lua_State* L) { #ifdef SOL_SAFE_USERTYPE auto p = stack::get<T*>(L, 1); if (p == nullptr) { luaL_error(L, "sol: 'self' argument is nil (pass 'self' as first argument or call on proper type)"); } return *p; #else return stack::get<T>(L, 1); #endif } static int real_index_call(lua_State* L) { auto& src = get_src(L); auto k = stack::check_get<K>(L, 2); if (k) { using std::end; auto it = detail::find(src, *k); if (it != end(src)) { auto& v = *it; return stack::push_reference(L, v.second); } } return stack::push(L, nil); } static int real_new_index_call_const(std::false_type, lua_State* L) { luaL_error(L, "sol: cannot write to a const value type"); return 0; } static int real_new_index_call_const(std::true_type, lua_State* L) { auto& src = get_src(L); auto k = stack::check_get<K>(L, 2); if (k) { using std::end; auto it = detail::find(src, *k); if (it != end(src)) { auto& v = *it; v.second = stack::get<V>(L, 3); } else { src.insert(it, { std::move(*k), stack::get<V>(L, 3) }); } } return 0; } static int real_new_index_call(lua_State* L) { return real_new_index_call_const(meta::neg<std::is_const<V>>(), L); } static int real_pairs_next_call(lua_State* L) { using std::end; iter& i = stack::get<user<iter>>(L, 1); auto& source = i.source; auto& it = i.it; std::advance(it, 1); if (it == end(source)) { return 0; } return stack::multi_push_reference(L, it->first, it->second); } static int real_pairs_call(lua_State* L) { auto& src = get_src(L); using std::begin; stack::push(L, pairs_next_call); stack::push<user<iter>>(L, src, begin(src)); stack::push(L, 1); return 3; } static int real_length_call(lua_State*L) { auto& src = get_src(L); return stack::push(L, src.size()); } static int length_call(lua_State*L) { return detail::static_trampoline<(&real_length_call)>(L); } static int pairs_next_call(lua_State*L) { return detail::static_trampoline<(&real_pairs_next_call)>(L); } static int pairs_call(lua_State*L) { return detail::static_trampoline<(&real_pairs_call)>(L); } static int index_call(lua_State*L) { return detail::static_trampoline<(&real_index_call)>(L); } static int new_index_call(lua_State*L) { return detail::static_trampoline<(&real_new_index_call)>(L); } }; namespace stack { template<typename T> struct pusher<T, std::enable_if_t<meta::all<meta::has_begin_end<T>, meta::neg<meta::any<std::is_base_of<reference, T>, std::is_base_of<stack_reference, T>>>>::value>> { typedef container_usertype_metatable<T> cumt; static int push(lua_State* L, const T& cont) { auto fx = [&L]() { const char* metakey = &usertype_traits<T>::metatable[0]; if (luaL_newmetatable(L, metakey) == 1) { luaL_Reg reg[] = { { "__index", &cumt::index_call }, { "__newindex", &cumt::new_index_call }, { "__pairs", &cumt::pairs_call }, { "__len", &cumt::length_call }, { "__gc", &detail::usertype_alloc_destroy<T> }, { nullptr, nullptr } }; luaL_setfuncs(L, reg, 0); } lua_setmetatable(L, -2); }; return pusher<detail::as_value_tag<T>>{}.push_fx(L, fx, cont); } static int push(lua_State* L, T&& cont) { auto fx = [&L]() { const char* metakey = &usertype_traits<T>::metatable[0]; if (luaL_newmetatable(L, metakey) == 1) { luaL_Reg reg[] = { { "__index", &cumt::index_call }, { "__newindex", &cumt::new_index_call }, { "__pairs", &cumt::pairs_call }, { "__len", &cumt::length_call }, { "__gc", &detail::usertype_alloc_destroy<T> }, { nullptr, nullptr } }; luaL_setfuncs(L, reg, 0); } lua_setmetatable(L, -2); }; return pusher<detail::as_value_tag<T>>{}.push_fx(L, fx, std::move(cont)); } }; template<typename T> struct pusher<T*, std::enable_if_t<meta::all<meta::has_begin_end<meta::unqualified_t<T>>, meta::neg<meta::any<std::is_base_of<reference, meta::unqualified_t<T>>, std::is_base_of<stack_reference, meta::unqualified_t<T>>>>>::value>> { typedef container_usertype_metatable<T> cumt; static int push(lua_State* L, T* cont) { auto fx = [&L]() { const char* metakey = &usertype_traits<meta::unqualified_t<T>*>::metatable[0]; if (luaL_newmetatable(L, metakey) == 1) { luaL_Reg reg[] = { { "__index", &cumt::index_call }, { "__newindex", &cumt::new_index_call }, { "__pairs", &cumt::pairs_call }, { "__len", &cumt::length_call }, { nullptr, nullptr } }; luaL_setfuncs(L, reg, 0); } lua_setmetatable(L, -2); }; return pusher<detail::as_pointer_tag<T>>{}.push_fx(L, fx, cont); } }; } // stack } // sol // end of sol/container_usertype_metatable.hpp namespace sol { template<typename T> class usertype { private: std::unique_ptr<usertype_detail::registrar, detail::deleter> metatableregister; template<typename... Args> usertype(usertype_detail::verified_tag, Args&&... args) : metatableregister(detail::make_unique_deleter<usertype_metatable<T, std::make_index_sequence<sizeof...(Args) / 2>, Args...>, detail::deleter>(std::forward<Args>(args)...)) {} template<typename... Args> usertype(usertype_detail::add_destructor_tag, Args&&... args) : usertype(usertype_detail::verified, std::forward<Args>(args)..., "__gc", default_destructor) {} template<typename... Args> usertype(usertype_detail::check_destructor_tag, Args&&... args) : usertype(meta::condition<meta::all<std::is_destructible<T>, meta::neg<usertype_detail::has_destructor<Args...>>>, usertype_detail::add_destructor_tag, usertype_detail::verified_tag>(), std::forward<Args>(args)...) {} public: template<typename... Args> usertype(Args&&... args) : usertype(meta::condition<meta::all<std::is_default_constructible<T>, meta::neg<usertype_detail::has_constructor<Args...>>>, decltype(default_constructor), usertype_detail::check_destructor_tag>(), std::forward<Args>(args)...) {} template<typename... Args, typename... CArgs> usertype(constructors<CArgs...> constructorlist, Args&&... args) : usertype(usertype_detail::check_destructor_tag(), std::forward<Args>(args)..., "new", constructorlist) {} template<typename... Args, typename... Fxs> usertype(constructor_wrapper<Fxs...> constructorlist, Args&&... args) : usertype(usertype_detail::check_destructor_tag(), std::forward<Args>(args)..., "new", constructorlist) {} template<typename... Args> usertype(simple_tag, lua_State* L, Args&&... args) : metatableregister(detail::make_unique_deleter<simple_usertype_metatable<T>, detail::deleter>(L, std::forward<Args>(args)...)) {} usertype_detail::registrar* registrar_data() { return metatableregister.get(); } int push(lua_State* L) { return metatableregister->push_um(L); } }; template<typename T> class simple_usertype : public usertype<T> { private: typedef usertype<T> base_t; lua_State* state; public: template<typename... Args> simple_usertype(lua_State* L, Args&&... args) : base_t(simple, L, std::forward<Args>(args)...), state(L) {} template <typename N, typename F> void set(N&& n, F&& f) { auto meta = static_cast<simple_usertype_metatable<T>*>(base_t::registrar_data()); meta->add(state, n, f); } }; namespace stack { template<typename T> struct pusher<usertype<T>> { static int push(lua_State* L, usertype<T>& user) { return user.push(L); } }; } // stack } // sol // end of sol/usertype.hpp // beginning of sol/table_iterator.hpp namespace sol { template <typename reference_type> class basic_table_iterator : public std::iterator<std::input_iterator_tag, std::pair<object, object>> { private: typedef std::iterator<std::input_iterator_tag, std::pair<object, object>> base_t; public: typedef object key_type; typedef object mapped_type; typedef base_t::value_type value_type; typedef base_t::iterator_category iterator_category; typedef base_t::difference_type difference_type; typedef base_t::pointer pointer; typedef base_t::reference reference; typedef const value_type& const_reference; private: std::pair<object, object> kvp; reference_type ref; int tableidx = 0; int keyidx = 0; std::ptrdiff_t idx = 0; public: basic_table_iterator() : keyidx(-1), idx(-1) { } basic_table_iterator(reference_type x) : ref(std::move(x)) { ref.push(); tableidx = lua_gettop(ref.lua_state()); stack::push(ref.lua_state(), nil); this->operator++(); if (idx == -1) { return; } --idx; } basic_table_iterator& operator++() { if (idx == -1) return *this; if (lua_next(ref.lua_state(), tableidx) == 0) { idx = -1; keyidx = -1; return *this; } ++idx; kvp.first = object(ref.lua_state(), -2); kvp.second = object(ref.lua_state(), -1); lua_pop(ref.lua_state(), 1); // leave key on the stack keyidx = lua_gettop(ref.lua_state()); return *this; } basic_table_iterator operator++(int) { auto saved = *this; this->operator++(); return saved; } reference operator*() { return kvp; } const_reference operator*() const { return kvp; } bool operator== (const basic_table_iterator& right) const { return idx == right.idx; } bool operator!= (const basic_table_iterator& right) const { return idx != right.idx; } ~basic_table_iterator() { if (keyidx != -1) { stack::remove(ref.lua_state(), keyidx, 1); } if (ref.valid()) { stack::remove(ref.lua_state(), tableidx, 1); } } }; } // sol // end of sol/table_iterator.hpp namespace sol { namespace detail { template <std::size_t n> struct clean { lua_State* L; clean(lua_State* L) : L(L) {} ~clean() { lua_pop(L, static_cast<int>(n)); } }; struct ref_clean { lua_State* L; int& n; ref_clean(lua_State* L, int& n) : L(L), n(n) {} ~ref_clean() { lua_pop(L, static_cast<int>(n)); } }; inline int fail_on_newindex(lua_State* L) { return luaL_error(L, "sol: cannot modify the elements of an enumeration table"); } } template <bool top_level, typename base_t> class basic_table_core : public base_t { friend class state; friend class state_view; template <typename... Args> using is_global = meta::all<meta::boolean<top_level>, meta::is_c_str<Args>...>; template<typename Fx> void for_each(std::true_type, Fx&& fx) const { auto pp = stack::push_pop(*this); stack::push(base_t::lua_state(), nil); while (lua_next(base_t::lua_state(), -2)) { sol::object key(base_t::lua_state(), -2); sol::object value(base_t::lua_state(), -1); std::pair<sol::object&, sol::object&> keyvalue(key, value); auto pn = stack::pop_n(base_t::lua_state(), 1); fx(keyvalue); } } template<typename Fx> void for_each(std::false_type, Fx&& fx) const { auto pp = stack::push_pop(*this); stack::push(base_t::lua_state(), nil); while (lua_next(base_t::lua_state(), -2)) { sol::object key(base_t::lua_state(), -2); sol::object value(base_t::lua_state(), -1); auto pn = stack::pop_n(base_t::lua_state(), 1); fx(key, value); } } template<typename Ret0, typename Ret1, typename... Ret, std::size_t... I, typename Keys> auto tuple_get(types<Ret0, Ret1, Ret...>, std::index_sequence<0, 1, I...>, Keys&& keys) const -> decltype(stack::pop<std::tuple<Ret0, Ret1, Ret...>>(nullptr)) { typedef decltype(stack::pop<std::tuple<Ret0, Ret1, Ret...>>(nullptr)) Tup; return Tup( traverse_get_optional<top_level, Ret0>(meta::is_specialization_of<sol::optional, meta::unqualified_t<Ret0>>(), detail::forward_get<0>(keys)), traverse_get_optional<top_level, Ret1>(meta::is_specialization_of<sol::optional, meta::unqualified_t<Ret1>>(), detail::forward_get<1>(keys)), traverse_get_optional<top_level, Ret>(meta::is_specialization_of<sol::optional, meta::unqualified_t<Ret>>(), detail::forward_get<I>(keys))... ); } template<typename Ret, std::size_t I, typename Keys> decltype(auto) tuple_get(types<Ret>, std::index_sequence<I>, Keys&& keys) const { return traverse_get_optional<top_level, Ret>(meta::is_specialization_of<sol::optional, meta::unqualified_t<Ret>>(), detail::forward_get<I>(keys)); } template<typename Pairs, std::size_t... I> void tuple_set(std::index_sequence<I...>, Pairs&& pairs) { auto pp = stack::push_pop<top_level && (is_global<decltype(detail::forward_get<I * 2>(pairs))...>::value)>(*this); void(detail::swallow{ (stack::set_field<top_level>(base_t::lua_state(), detail::forward_get<I * 2>(pairs), detail::forward_get<I * 2 + 1>(pairs), lua_gettop(base_t::lua_state()) ), 0)... }); } template <bool global, typename T, typename Key> decltype(auto) traverse_get_deep(Key&& key) const { stack::get_field<global>(base_t::lua_state(), std::forward<Key>(key)); return stack::get<T>(base_t::lua_state()); } template <bool global, typename T, typename Key, typename... Keys> decltype(auto) traverse_get_deep(Key&& key, Keys&&... keys) const { stack::get_field<global>(base_t::lua_state(), std::forward<Key>(key)); return traverse_get_deep<false, T>(std::forward<Keys>(keys)...); } template <bool global, typename T, std::size_t I, typename Key> decltype(auto) traverse_get_deep_optional(int& popcount, Key&& key) const { typedef decltype(stack::get<T>(base_t::lua_state())) R; auto p = stack::probe_get_field<global>(base_t::lua_state(), std::forward<Key>(key), lua_gettop(base_t::lua_state())); popcount += p.levels; if (!p.success) return R(nullopt); return stack::get<T>(base_t::lua_state()); } template <bool global, typename T, std::size_t I, typename Key, typename... Keys> decltype(auto) traverse_get_deep_optional(int& popcount, Key&& key, Keys&&... keys) const { auto p = I > 0 ? stack::probe_get_field<global>(base_t::lua_state(), std::forward<Key>(key), -1) : stack::probe_get_field<global>(base_t::lua_state(), std::forward<Key>(key), lua_gettop(base_t::lua_state())); popcount += p.levels; if (!p.success) return T(nullopt); return traverse_get_deep_optional<false, T, I + 1>(popcount, std::forward<Keys>(keys)...); } template <bool global, typename T, typename... Keys> decltype(auto) traverse_get_optional(std::false_type, Keys&&... keys) const { detail::clean<sizeof...(Keys)> c(base_t::lua_state()); return traverse_get_deep<top_level, T>(std::forward<Keys>(keys)...); } template <bool global, typename T, typename... Keys> decltype(auto) traverse_get_optional(std::true_type, Keys&&... keys) const { int popcount = 0; detail::ref_clean c(base_t::lua_state(), popcount); return traverse_get_deep_optional<top_level, T, 0>(popcount, std::forward<Keys>(keys)...); } template <bool global, typename Key, typename Value> void traverse_set_deep(Key&& key, Value&& value) const { stack::set_field<global>(base_t::lua_state(), std::forward<Key>(key), std::forward<Value>(value)); } template <bool global, typename Key, typename... Keys> void traverse_set_deep(Key&& key, Keys&&... keys) const { stack::get_field<global>(base_t::lua_state(), std::forward<Key>(key)); traverse_set_deep<false>(std::forward<Keys>(keys)...); } basic_table_core(lua_State* L, detail::global_tag t) noexcept : reference(L, t) { } public: typedef basic_table_iterator<base_t> iterator; typedef iterator const_iterator; basic_table_core() noexcept : base_t() { } template <typename T, meta::enable<meta::neg<std::is_same<meta::unqualified_t<T>, basic_table_core>>, meta::neg<std::is_same<base_t, stack_reference>>, std::is_base_of<base_t, meta::unqualified_t<T>>> = meta::enabler> basic_table_core(T&& r) noexcept : base_t(std::forward<T>(r)) { #ifdef SOL_CHECK_ARGUMENTS if (!is_table<meta::unqualified_t<T>>::value) { auto pp = stack::push_pop(*this); stack::check<basic_table_core>(base_t::lua_state(), -1, type_panic); } #endif // Safety } basic_table_core(const basic_table_core&) = default; basic_table_core(basic_table_core&&) = default; basic_table_core& operator=(const basic_table_core&) = default; basic_table_core& operator=(basic_table_core&&) = default; basic_table_core(const stack_reference& r) : basic_table_core(r.lua_state(), r.stack_index()) {} basic_table_core(stack_reference&& r) : basic_table_core(r.lua_state(), r.stack_index()) {} basic_table_core(lua_State* L, int index = -1) : base_t(L, index) { #ifdef SOL_CHECK_ARGUMENTS stack::check<basic_table_core>(L, index, type_panic); #endif // Safety } iterator begin() const { return iterator(*this); } iterator end() const { return iterator(); } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } template<typename... Ret, typename... Keys> decltype(auto) get(Keys&&... keys) const { static_assert(sizeof...(Keys) == sizeof...(Ret), "number of keys and number of return types do not match"); auto pp = stack::push_pop<is_global<Keys...>::value>(*this); return tuple_get(types<Ret...>(), std::make_index_sequence<sizeof...(Ret)>(), std::forward_as_tuple(std::forward<Keys>(keys)...)); } template<typename T, typename Key> decltype(auto) get_or(Key&& key, T&& otherwise) const { typedef decltype(get<T>("")) U; sol::optional<U> option = get<sol::optional<U>>(std::forward<Key>(key)); if (option) { return static_cast<U>(option.value()); } return static_cast<U>(std::forward<T>(otherwise)); } template<typename T, typename Key, typename D> decltype(auto) get_or(Key&& key, D&& otherwise) const { sol::optional<T> option = get<sol::optional<T>>(std::forward<Key>(key)); if (option) { return static_cast<T>(option.value()); } return static_cast<T>(std::forward<D>(otherwise)); } template <typename T, typename... Keys> decltype(auto) traverse_get(Keys&&... keys) const { auto pp = stack::push_pop<is_global<Keys...>::value>(*this); return traverse_get_optional<top_level, T>(meta::is_specialization_of<sol::optional, meta::unqualified_t<T>>(), std::forward<Keys>(keys)...); } template <typename... Keys> basic_table_core& traverse_set(Keys&&... keys) { auto pp = stack::push_pop<is_global<Keys...>::value>(*this); auto pn = stack::pop_n(base_t::lua_state(), static_cast<int>(sizeof...(Keys)-2)); traverse_set_deep<top_level>(std::forward<Keys>(keys)...); return *this; } template<typename... Args> basic_table_core& set(Args&&... args) { tuple_set(std::make_index_sequence<sizeof...(Args) / 2>(), std::forward_as_tuple(std::forward<Args>(args)...)); return *this; } template<typename T> basic_table_core& set_usertype(usertype<T>& user) { return set_usertype(usertype_traits<T>::name, user); } template<typename Key, typename T> basic_table_core& set_usertype(Key&& key, usertype<T>& user) { return set(std::forward<Key>(key), user); } template<typename Class, typename... Args> basic_table_core& new_usertype(const std::string& name, Args&&... args) { usertype<Class> utype(std::forward<Args>(args)...); set_usertype(name, utype); return *this; } template<typename Class, typename CTor0, typename... CTor, typename... Args> basic_table_core& new_usertype(const std::string& name, Args&&... args) { constructors<types<CTor0, CTor...>> ctor{}; return new_usertype<Class>(name, ctor, std::forward<Args>(args)...); } template<typename Class, typename... CArgs, typename... Args> basic_table_core& new_usertype(const std::string& name, constructors<CArgs...> ctor, Args&&... args) { usertype<Class> utype(ctor, std::forward<Args>(args)...); set_usertype(name, utype); return *this; } template<typename Class, typename... Args> basic_table_core& new_simple_usertype(const std::string& name, Args&&... args) { simple_usertype<Class> utype(base_t::lua_state(), std::forward<Args>(args)...); set_usertype(name, utype); return *this; } template<typename Class, typename CTor0, typename... CTor, typename... Args> basic_table_core& new_simple_usertype(const std::string& name, Args&&... args) { constructors<types<CTor0, CTor...>> ctor{}; return new_simple_usertype<Class>(name, ctor, std::forward<Args>(args)...); } template<typename Class, typename... CArgs, typename... Args> basic_table_core& new_simple_usertype(const std::string& name, constructors<CArgs...> ctor, Args&&... args) { simple_usertype<Class> utype(base_t::lua_state(), ctor, std::forward<Args>(args)...); set_usertype(name, utype); return *this; } template<typename Class, typename... Args> simple_usertype<Class> create_simple_usertype(Args&&... args) { simple_usertype<Class> utype(base_t::lua_state(), std::forward<Args>(args)...); return utype; } template<typename Class, typename CTor0, typename... CTor, typename... Args> simple_usertype<Class> create_simple_usertype(Args&&... args) { constructors<types<CTor0, CTor...>> ctor{}; return create_simple_usertype<Class>(ctor, std::forward<Args>(args)...); } template<typename Class, typename... CArgs, typename... Args> simple_usertype<Class> create_simple_usertype(constructors<CArgs...> ctor, Args&&... args) { simple_usertype<Class> utype(base_t::lua_state(), ctor, std::forward<Args>(args)...); return utype; } template<bool read_only = true, typename... Args> basic_table_core& new_enum(const std::string& name, Args&&... args) { if (read_only) { table idx = create_with(std::forward<Args>(args)...); table x = create_with( meta_function::new_index, detail::fail_on_newindex, meta_function::index, idx ); table target = create_named(name); target[metatable_key] = x; } else { create_named(name, std::forward<Args>(args)...); } return *this; } template<typename Fx> void for_each(Fx&& fx) const { typedef meta::is_invokable<Fx(std::pair<sol::object, sol::object>)> is_paired; for_each(is_paired(), std::forward<Fx>(fx)); } size_t size() const { auto pp = stack::push_pop(*this); lua_len(base_t::lua_state(), -1); return stack::pop<size_t>(base_t::lua_state()); } bool empty() const { return cbegin() == cend(); } template<typename T> proxy<basic_table_core&, T> operator[](T&& key) & { return proxy<basic_table_core&, T>(*this, std::forward<T>(key)); } template<typename T> proxy<const basic_table_core&, T> operator[](T&& key) const & { return proxy<const basic_table_core&, T>(*this, std::forward<T>(key)); } template<typename T> proxy<basic_table_core, T> operator[](T&& key) && { return proxy<basic_table_core, T>(*this, std::forward<T>(key)); } template<typename Sig, typename Key, typename... Args> basic_table_core& set_function(Key&& key, Args&&... args) { set_fx(types<Sig>(), std::forward<Key>(key), std::forward<Args>(args)...); return *this; } template<typename Key, typename... Args> basic_table_core& set_function(Key&& key, Args&&... args) { set_fx(types<>(), std::forward<Key>(key), std::forward<Args>(args)...); return *this; } template <typename... Args> basic_table_core& add(Args&&... args) { auto pp = stack::push_pop(*this); (void)detail::swallow{0, (stack::set_ref(base_t::lua_state(), std::forward<Args>(args)), 0)... }; return *this; } private: template<typename R, typename... Args, typename Fx, typename Key, typename = std::result_of_t<Fx(Args...)>> void set_fx(types<R(Args...)>, Key&& key, Fx&& fx) { set_resolved_function<R(Args...)>(std::forward<Key>(key), std::forward<Fx>(fx)); } template<typename Fx, typename Key, meta::enable<meta::is_specialization_of<overload_set, meta::unqualified_t<Fx>>> = meta::enabler> void set_fx(types<>, Key&& key, Fx&& fx) { set(std::forward<Key>(key), std::forward<Fx>(fx)); } template<typename Fx, typename Key, typename... Args, meta::disable<meta::is_specialization_of<overload_set, meta::unqualified_t<Fx>>> = meta::enabler> void set_fx(types<>, Key&& key, Fx&& fx, Args&&... args) { set(std::forward<Key>(key), as_function_reference(std::forward<Fx>(fx), std::forward<Args>(args)...)); } template<typename... Sig, typename... Args, typename Key> void set_resolved_function(Key&& key, Args&&... args) { set(std::forward<Key>(key), as_function_reference<function_sig<Sig...>>(std::forward<Args>(args)...)); } public: static inline table create(lua_State* L, int narr = 0, int nrec = 0) { lua_createtable(L, narr, nrec); table result(L); lua_pop(L, 1); return result; } template <typename Key, typename Value, typename... Args> static inline table create(lua_State* L, int narr, int nrec, Key&& key, Value&& value, Args&&... args) { lua_createtable(L, narr, nrec); table result(L); result.set(std::forward<Key>(key), std::forward<Value>(value), std::forward<Args>(args)...); lua_pop(L, 1); return result; } template <typename... Args> static inline table create_with(lua_State* L, Args&&... args) { static const int narr = static_cast<int>(meta::count_2_for_pack<std::is_integral, Args...>::value); return create(L, narr, static_cast<int>((sizeof...(Args) / 2) - narr), std::forward<Args>(args)...); } table create(int narr = 0, int nrec = 0) { return create(base_t::lua_state(), narr, nrec); } template <typename Key, typename Value, typename... Args> table create(int narr, int nrec, Key&& key, Value&& value, Args&&... args) { return create(base_t::lua_state(), narr, nrec, std::forward<Key>(key), std::forward<Value>(value), std::forward<Args>(args)...); } template <typename Name> table create(Name&& name, int narr = 0, int nrec = 0) { table x = create(base_t::lua_state(), narr, nrec); this->set(std::forward<Name>(name), x); return x; } template <typename Name, typename Key, typename Value, typename... Args> table create(Name&& name, int narr, int nrec, Key&& key, Value&& value, Args&&... args) { table x = create(base_t::lua_state(), narr, nrec, std::forward<Key>(key), std::forward<Value>(value), std::forward<Args>(args)...); this->set(std::forward<Name>(name), x); return x; } template <typename... Args> table create_with(Args&&... args) { return create_with(base_t::lua_state(), std::forward<Args>(args)...); } template <typename Name, typename... Args> table create_named(Name&& name, Args&&... args) { static const int narr = static_cast<int>(meta::count_2_for_pack<std::is_integral, Args...>::value); return create(std::forward<Name>(name), narr, sizeof...(Args) / 2 - narr, std::forward<Args>(args)...); } }; } // sol // end of sol/table_core.hpp namespace sol { typedef table_core<false> table; } // sol // end of sol/table.hpp // beginning of sol/load_result.hpp namespace sol { struct load_result : public proxy_base<load_result> { private: lua_State* L; int index; int returncount; int popcount; load_status err; template <typename T> decltype(auto) tagged_get(types<sol::optional<T>>) const { if (!valid()) { return sol::optional<T>(nullopt); } return stack::get<sol::optional<T>>(L, index); } template <typename T> decltype(auto) tagged_get(types<T>) const { #ifdef SOL_CHECK_ARGUMENTS if (!valid()) { type_panic(L, index, type_of(L, index), type::none); } #endif // Check Argument Safety return stack::get<T>(L, index); } sol::optional<sol::error> tagged_get(types<sol::optional<sol::error>>) const { if (valid()) { return nullopt; } return sol::error(detail::direct_error, stack::get<std::string>(L, index)); } sol::error tagged_get(types<sol::error>) const { #ifdef SOL_CHECK_ARGUMENTS if (valid()) { type_panic(L, index, type_of(L, index), type::none); } #endif // Check Argument Safety return sol::error(detail::direct_error, stack::get<std::string>(L, index)); } public: load_result() = default; load_result(lua_State* L, int index = -1, int returncount = 0, int popcount = 0, load_status err = load_status::ok) noexcept : L(L), index(index), returncount(returncount), popcount(popcount), err(err) { } load_result(const load_result&) = default; load_result& operator=(const load_result&) = default; load_result(load_result&& o) noexcept : L(o.L), index(o.index), returncount(o.returncount), popcount(o.popcount), err(o.err) { // Must be manual, otherwise destructor will screw us // return count being 0 is enough to keep things clean // but we will be thorough o.L = nullptr; o.index = 0; o.returncount = 0; o.popcount = 0; o.err = load_status::syntax; } load_result& operator=(load_result&& o) noexcept { L = o.L; index = o.index; returncount = o.returncount; popcount = o.popcount; err = o.err; // Must be manual, otherwise destructor will screw us // return count being 0 is enough to keep things clean // but we will be thorough o.L = nullptr; o.index = 0; o.returncount = 0; o.popcount = 0; o.err = load_status::syntax; return *this; } load_status status() const noexcept { return err; } bool valid() const noexcept { return status() == load_status::ok; } template<typename T> T get() const { return tagged_get(types<meta::unqualified_t<T>>()); } template<typename... Ret, typename... Args> decltype(auto) call(Args&&... args) { return get<function>().template call<Ret...>(std::forward<Args>(args)...); } template<typename... Args> decltype(auto) operator()(Args&&... args) { return call<>(std::forward<Args>(args)...); } lua_State* lua_state() const noexcept { return L; }; int stack_index() const noexcept { return index; }; ~load_result() { stack::remove(L, index, popcount); } }; } // sol // end of sol/load_result.hpp namespace sol { enum class lib : char { base, package, coroutine, string, os, math, table, debug, bit32, io, ffi, jit, utf8, count }; class state_view { private: lua_State* L; table reg; global_table global; optional<object> is_loaded_package(const std::string& key) { auto loaded = reg.traverse_get<optional<object>>("_LOADED", key); bool is53mod = loaded && !(loaded->is<bool>() && !loaded->as<bool>()); if (is53mod) return loaded; #if SOL_LUA_VERSION <= 501 auto loaded51 = global.traverse_get<optional<object>>("package", "loaded", key); bool is51mod = loaded51 && !(loaded51->is<bool>() && !loaded51->as<bool>()); if (is51mod) return loaded51; #endif return nullopt; } template <typename T> void ensure_package(const std::string& key, T&& sr) { #if SOL_LUA_VERSION <= 501 auto pkg = global["package"]; if (!pkg.valid()) { pkg = create_table_with("loaded", create_table_with(key, sr)); } else { auto ld = pkg["loaded"]; if (!ld.valid()) { ld = create_table_with(key, sr); } else { ld[key] = sr; } } #endif auto loaded = reg["_LOADED"]; if (!loaded.valid()) { loaded = create_table_with(key, sr); } else { loaded[key] = sr; } } template <typename Fx> object require_core(const std::string& key, Fx&& action, bool create_global = true) { optional<object> loaded = is_loaded_package(key); if (loaded && loaded->valid()) return std::move(*loaded); action(); auto sr = stack::get<stack_reference>(L); if (create_global) set(key, sr); ensure_package(key, sr); return stack::pop<object>(L); } public: typedef global_table::iterator iterator; typedef global_table::const_iterator const_iterator; state_view(lua_State* L) : L(L), reg(L, LUA_REGISTRYINDEX), global(L, detail::global_) { } lua_State* lua_state() const { return L; } template<typename... Args> void open_libraries(Args&&... args) { static_assert(meta::all_same<lib, Args...>::value, "all types must be libraries"); if (sizeof...(args) == 0) { luaL_openlibs(L); return; } lib libraries[1 + sizeof...(args)] = { lib::count, std::forward<Args>(args)... }; for (auto&& library : libraries) { switch (library) { #if SOL_LUA_VERSION <= 501 && defined(SOL_LUAJIT) case lib::coroutine: #endif // luajit opens coroutine base stuff case lib::base: luaL_requiref(L, "base", luaopen_base, 1); lua_pop(L, 1); break; case lib::package: luaL_requiref(L, "package", luaopen_package, 1); lua_pop(L, 1); break; #if !defined(SOL_LUAJIT) case lib::coroutine: #if SOL_LUA_VERSION > 501 luaL_requiref(L, "coroutine", luaopen_coroutine, 1); lua_pop(L, 1); #endif // Lua 5.2+ only break; #endif // Not LuaJIT case lib::string: luaL_requiref(L, "string", luaopen_string, 1); lua_pop(L, 1); break; case lib::table: luaL_requiref(L, "table", luaopen_table, 1); lua_pop(L, 1); break; case lib::math: luaL_requiref(L, "math", luaopen_math, 1); lua_pop(L, 1); break; case lib::bit32: #ifdef SOL_LUAJIT luaL_requiref(L, "bit32", luaopen_bit, 1); lua_pop(L, 1); #elif SOL_LUA_VERSION == 502 luaL_requiref(L, "bit32", luaopen_bit32, 1); lua_pop(L, 1); #else #endif // Lua 5.2 only (deprecated in 5.3 (503)) break; case lib::io: luaL_requiref(L, "io", luaopen_io, 1); lua_pop(L, 1); break; case lib::os: luaL_requiref(L, "os", luaopen_os, 1); lua_pop(L, 1); break; case lib::debug: luaL_requiref(L, "debug", luaopen_debug, 1); lua_pop(L, 1); break; case lib::utf8: #if SOL_LUA_VERSION > 502 && !defined(SOL_LUAJIT) luaL_requiref(L, "utf8", luaopen_utf8, 1); lua_pop(L, 1); #endif // Lua 5.3+ only break; case lib::ffi: #ifdef SOL_LUAJIT luaL_requiref(L, "ffi", luaopen_ffi, 1); lua_pop(L, 1); #endif break; case lib::jit: #ifdef SOL_LUAJIT luaL_requiref(L, "jit", luaopen_jit, 1); lua_pop(L, 1); #endif break; case lib::count: default: break; } } } object require(const std::string& key, lua_CFunction open_function, bool create_global = true) { luaL_requiref(L, key.c_str(), open_function, create_global ? 1 : 0); return stack::pop<object>(L); } object require_script(const std::string& key, const std::string& code, bool create_global = true) { return require_core(key, [this, &code]() {stack::script(L, code); }, create_global); } object require_file(const std::string& key, const std::string& filename, bool create_global = true) { return require_core(key, [this, &filename]() {stack::script_file(L, filename); }, create_global); } function_result script(const std::string& code) { int index = (::std::max)(lua_gettop(L), 1); stack::script(L, code); int returns = lua_gettop(L) - (index - 1); return function_result(L, index, returns); } function_result script_file(const std::string& filename) { int index = (::std::max)(lua_gettop(L), 1); stack::script_file(L, filename); int returns = lua_gettop(L) - (index - 1); return function_result(L, index, returns); } load_result load(const std::string& code) { load_status x = static_cast<load_status>(luaL_loadstring(L, code.c_str())); return load_result(L, lua_absindex(L, -1), 1, 1, x); } load_result load_file(const std::string& filename) { load_status x = static_cast<load_status>(luaL_loadfile(L, filename.c_str())); return load_result(L, lua_absindex(L, -1), 1, 1, x); } load_result load_buffer(const char *buff, size_t size, const char *name, const char* mode = nullptr) { load_status x = static_cast<load_status>(luaL_loadbufferx(L, buff, size, name, mode)); return load_result(L, lua_absindex(L, -1), 1, 1, x); } iterator begin() const { return global.begin(); } iterator end() const { return global.end(); } const_iterator cbegin() const { return global.cbegin(); } const_iterator cend() const { return global.cend(); } global_table globals() const { return global; } table registry() const { return reg; } operator lua_State* () const { return lua_state(); } void set_panic(lua_CFunction panic) { lua_atpanic(L, panic); } template<typename... Args, typename... Keys> decltype(auto) get(Keys&&... keys) const { return global.get<Args...>(std::forward<Keys>(keys)...); } template<typename T, typename Key> decltype(auto) get_or(Key&& key, T&& otherwise) const { return global.get_or(std::forward<Key>(key), std::forward<T>(otherwise)); } template<typename T, typename Key, typename D> decltype(auto) get_or(Key&& key, D&& otherwise) const { return global.get_or<T>(std::forward<Key>(key), std::forward<D>(otherwise)); } template<typename... Args> state_view& set(Args&&... args) { global.set(std::forward<Args>(args)...); return *this; } template<typename T, typename... Keys> decltype(auto) traverse_get(Keys&&... keys) const { return global.traverse_get<T>(std::forward<Keys>(keys)...); } template<typename... Args> state_view& traverse_set(Args&&... args) { global.traverse_set(std::forward<Args>(args)...); return *this; } template<typename T> state_view& set_usertype(usertype<T>& user) { return set_usertype(usertype_traits<T>::name, user); } template<typename Key, typename T> state_view& set_usertype(Key&& key, usertype<T>& user) { global.set_usertype(std::forward<Key>(key), user); return *this; } template<typename Class, typename... Args> state_view& new_usertype(const std::string& name, Args&&... args) { global.new_usertype<Class>(name, std::forward<Args>(args)...); return *this; } template<typename Class, typename CTor0, typename... CTor, typename... Args> state_view& new_usertype(const std::string& name, Args&&... args) { global.new_usertype<Class, CTor0, CTor...>(name, std::forward<Args>(args)...); return *this; } template<typename Class, typename... CArgs, typename... Args> state_view& new_usertype(const std::string& name, constructors<CArgs...> ctor, Args&&... args) { global.new_usertype<Class>(name, ctor, std::forward<Args>(args)...); return *this; } template<typename Class, typename... Args> state_view& new_simple_usertype(const std::string& name, Args&&... args) { global.new_simple_usertype<Class>(name, std::forward<Args>(args)...); return *this; } template<typename Class, typename CTor0, typename... CTor, typename... Args> state_view& new_simple_usertype(const std::string& name, Args&&... args) { global.new_simple_usertype<Class, CTor0, CTor...>(name, std::forward<Args>(args)...); return *this; } template<typename Class, typename... CArgs, typename... Args> state_view& new_simple_usertype(const std::string& name, constructors<CArgs...> ctor, Args&&... args) { global.new_simple_usertype<Class>(name, ctor, std::forward<Args>(args)...); return *this; } template<typename Class, typename... Args> simple_usertype<Class> create_simple_usertype(Args&&... args) { return global.create_simple_usertype<Class>(std::forward<Args>(args)...); } template<typename Class, typename CTor0, typename... CTor, typename... Args> simple_usertype<Class> create_simple_usertype(Args&&... args) { return global.create_simple_usertype<Class, CTor0, CTor...>(std::forward<Args>(args)...); } template<typename Class, typename... CArgs, typename... Args> simple_usertype<Class> create_simple_usertype(constructors<CArgs...> ctor, Args&&... args) { return global.create_simple_usertype<Class>(ctor, std::forward<Args>(args)...); } template<bool read_only = true, typename... Args> state_view& new_enum(const std::string& name, Args&&... args) { global.new_enum<read_only>(name, std::forward<Args>(args)...); return *this; } template <typename Fx> void for_each(Fx&& fx) { global.for_each(std::forward<Fx>(fx)); } template<typename T> proxy<global_table&, T> operator[](T&& key) { return global[std::forward<T>(key)]; } template<typename T> proxy<const global_table&, T> operator[](T&& key) const { return global[std::forward<T>(key)]; } template<typename Sig, typename... Args, typename Key> state_view& set_function(Key&& key, Args&&... args) { global.set_function<Sig>(std::forward<Key>(key), std::forward<Args>(args)...); return *this; } template<typename... Args, typename Key> state_view& set_function(Key&& key, Args&&... args) { global.set_function(std::forward<Key>(key), std::forward<Args>(args)...); return *this; } template <typename Name> table create_table(Name&& name, int narr = 0, int nrec = 0) { return global.create(std::forward<Name>(name), narr, nrec); } template <typename Name, typename Key, typename Value, typename... Args> table create_table(Name&& name, int narr, int nrec, Key&& key, Value&& value, Args&&... args) { return global.create(std::forward<Name>(name), narr, nrec, std::forward<Key>(key), std::forward<Value>(value), std::forward<Args>(args)...); } template <typename Name, typename... Args> table create_named_table(Name&& name, Args&&... args) { table x = global.create_with(std::forward<Args>(args)...); global.set(std::forward<Name>(name), x); return x; } table create_table(int narr = 0, int nrec = 0) { return create_table(lua_state(), narr, nrec); } template <typename Key, typename Value, typename... Args> table create_table(int narr, int nrec, Key&& key, Value&& value, Args&&... args) { return create_table(lua_state(), narr, nrec, std::forward<Key>(key), std::forward<Value>(value), std::forward<Args>(args)...); } template <typename... Args> table create_table_with(Args&&... args) { return create_table_with(lua_state(), std::forward<Args>(args)...); } static inline table create_table(lua_State* L, int narr = 0, int nrec = 0) { return global_table::create(L, narr, nrec); } template <typename Key, typename Value, typename... Args> static inline table create_table(lua_State* L, int narr, int nrec, Key&& key, Value&& value, Args&&... args) { return global_table::create(L, narr, nrec, std::forward<Key>(key), std::forward<Value>(value), std::forward<Args>(args)...); } template <typename... Args> static inline table create_table_with(lua_State* L, Args&&... args) { return global_table::create_with(L, std::forward<Args>(args)...); } }; } // sol // end of sol/state_view.hpp namespace sol { inline int default_at_panic(lua_State* L) { #ifdef SOL_NO_EXCEPTIONS (void)L; return -1; #else const char* message = lua_tostring(L, -1); std::string err = message ? message : "An unexpected error occurred and forced the lua state to call atpanic"; throw error(err); #endif } class state : private std::unique_ptr<lua_State, void(*)(lua_State*)>, public state_view { private: typedef std::unique_ptr<lua_State, void(*)(lua_State*)> unique_base; public: state(lua_CFunction panic = default_at_panic) : unique_base(luaL_newstate(), lua_close), state_view(unique_base::get()) { set_panic(panic); stack::luajit_exception_handler(unique_base::get()); } state(lua_CFunction panic, lua_Alloc alfunc, void* alpointer = nullptr) : unique_base(lua_newstate(alfunc, alpointer), lua_close), state_view(unique_base::get()) { set_panic(panic); stack::luajit_exception_handler(unique_base::get()); } using state_view::get; }; } // sol // end of sol/state.hpp // beginning of sol/coroutine.hpp // beginning of sol/thread.hpp namespace sol { class thread : public reference { public: thread() noexcept = default; thread(const thread&) = default; thread(thread&&) = default; thread(const stack_reference& r) : thread(r.lua_state(), r.stack_index()) {}; thread(stack_reference&& r) : thread(r.lua_state(), r.stack_index()) {}; thread& operator=(const thread&) = default; thread& operator=(thread&&) = default; thread(lua_State* L, int index = -1) : reference(L, index) { #ifdef SOL_CHECK_ARGUMENTS type_assert(L, index, type::thread); #endif // Safety } state_view state() const { return state_view(this->thread_state()); } lua_State* thread_state() const { auto pp = stack::push_pop(*this); lua_State* lthread = lua_tothread(lua_state(), -1); return lthread; } thread_status status() const { lua_State* lthread = thread_state(); thread_status lstat = static_cast<thread_status>(lua_status(lthread)); if (lstat != thread_status::ok && lua_gettop(lthread) == 0) { // No thing on the thread's stack means its dead return thread_status::dead; } return lstat; } thread create() { return create(lua_state()); } static thread create(lua_State* L) { lua_newthread(L); thread result(L); lua_pop(L, 1); return result; } }; } // sol // end of sol/thread.hpp namespace sol { class coroutine : public reference { private: call_status stats = call_status::yielded; void luacall(std::ptrdiff_t argcount, std::ptrdiff_t) { #if SOL_LUA_VERSION < 502 stats = static_cast<call_status>(lua_resume(lua_state(), static_cast<int>(argcount))); #else stats = static_cast<call_status>(lua_resume(lua_state(), nullptr, static_cast<int>(argcount))); #endif // Lua 5.1 compat } template<std::size_t... I, typename... Ret> auto invoke(types<Ret...>, std::index_sequence<I...>, std::ptrdiff_t n) { luacall(n, sizeof...(Ret)); return stack::pop<std::tuple<Ret...>>(lua_state()); } template<std::size_t I, typename Ret> Ret invoke(types<Ret>, std::index_sequence<I>, std::ptrdiff_t n) { luacall(n, 1); return stack::pop<Ret>(lua_state()); } template <std::size_t I> void invoke(types<void>, std::index_sequence<I>, std::ptrdiff_t n) { luacall(n, 0); } protected_function_result invoke(types<>, std::index_sequence<>, std::ptrdiff_t n) { int stacksize = lua_gettop(lua_state()); int firstreturn = (std::max)(1, stacksize - static_cast<int>(n)); luacall(n, LUA_MULTRET); int poststacksize = lua_gettop(lua_state()); int returncount = poststacksize - (firstreturn - 1); if (error()) { return protected_function_result(lua_state(), lua_absindex(lua_state(), -1), 1, returncount, status()); } return protected_function_result(lua_state(), firstreturn, returncount, returncount, status()); } public: coroutine() noexcept = default; coroutine(const coroutine&) noexcept = default; coroutine& operator=(const coroutine&) noexcept = default; coroutine(lua_State* L, int index = -1) : reference(L, index) { #ifdef SOL_CHECK_ARGUMENTS stack::check<coroutine>(L, index, type_panic); #endif // Safety } call_status status() const noexcept { return stats; } bool error() const noexcept { call_status cs = status(); return cs != call_status::ok && cs != call_status::yielded; } bool runnable() const noexcept { return valid() && (status() == call_status::yielded); } explicit operator bool() const noexcept { return runnable(); } template<typename... Args> protected_function_result operator()(Args&&... args) { return call<>(std::forward<Args>(args)...); } template<typename... Ret, typename... Args> decltype(auto) operator()(types<Ret...>, Args&&... args) { return call<Ret...>(std::forward<Args>(args)...); } template<typename... Ret, typename... Args> decltype(auto) call(Args&&... args) { push(); int pushcount = stack::multi_push(lua_state(), std::forward<Args>(args)...); return invoke(types<Ret...>(), std::make_index_sequence<sizeof...(Ret)>(), pushcount); } }; } // sol // end of sol/coroutine.hpp #endif // SOL_SINGLE_INCLUDE_HPP
mit
gossi/trixionary
src/action/relationship/VideoFeaturedTutorialSkillRemoveAction.php
1267
<?php namespace gossi\trixionary\action\relationship; use gossi\trixionary\domain\VideoDomain; use keeko\framework\foundation\AbstractAction; use phootwork\json\Json; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\OptionsResolver\OptionsResolver; use Tobscure\JsonApi\Exception\InvalidParameterException; /** * Removes featured_tutorial_skill as relationship to video * * This code is automatically created. Modifications will probably be overwritten. * * @author Thomas Gossmann */ class VideoFeaturedTutorialSkillRemoveAction extends AbstractAction { /** * @param OptionsResolver $resolver */ public function configureParams(OptionsResolver $resolver) { $resolver->setRequired(['id']); } /** * Automatically generated run method * * @param Request $request * @return Response */ public function run(Request $request) { $body = Json::decode($request->getContent()); if (!isset($body['data'])) { throw new InvalidParameterException(); } $data = $body['data']; $id = $this->getParam('id'); $domain = new VideoDomain($this->getServiceContainer()); $payload = $domain->removeSkill($id, $data); return $this->responder->run($request, $payload); } }
mit
ATMakersOrg/OpenIKeys
original/IntelliKeys/MacOSX/common/IKMsg.cpp
7129
// IKMsg.cpp: implementation of the IKMsg class. // ////////////////////////////////////////////////////////////////////// #include "IKCommon.h" #include "IKFile.h" #include "IKUtil.h" #include "IKMsg.h" static int defaultTimeout = 1000; static const TCHAR *strTransactLockFile = TEXT("transaction lock.dat"); static const TCHAR *strCommandFile = TEXT("command.dat"); static const TCHAR *strResponseFile = TEXT("response.dat"); static void MakeChannelFileName(IKString channel, IKString name, IKString& filename) { filename = IKUtil::GetChannelsFolder(); filename += channel; filename += IKUtil::GetPathDelimiter(); filename += name; } static void CleanupChannel(IKString channel) { IKString filename; // command file MakeChannelFileName(channel,IKString(strCommandFile),filename); IKFile::Remove(filename); // response file MakeChannelFileName(channel,IKString(strResponseFile),filename); IKFile::Remove(filename); } static int GetLock ( IKString channel, IKString lockName, int timeoutMS ) { IKString filename; MakeChannelFileName ( channel, lockName, filename ); unsigned int start = IKUtil::GetCurrentTimeMS(); while (1==1) { #ifdef PLAT_WINDOWS HANDLE hFile = CreateFile ( filename, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); return kResponseNoError; } #else FSSpec spec; TCHAR macFileName[255]; IKString::strcpy(&(macFileName[1]),filename); macFileName[0] = IKString::strlen(&(macFileName[1])); OSErr error = FSMakeFSSpec( 0, 0, (unsigned TCHAR *)macFileName, &spec ); if ((error == fnfErr) || (error == afpItemNotFound)) { error = FSpCreate(&spec,'TEXT','????',smSystemScript); if (error==noErr) return kResponseNoError; } #endif // if no timeout, just return error. if (timeoutMS<=0) return kResponseError; // are we timed out? unsigned int now = IKUtil::GetCurrentTimeMS(); if ((int)(now-start) > timeoutMS) return kResponseTimeout; IKUtil::Sleep(100); } return kResponseError; // we never get here } static int ReleaseLock ( IKString channel, IKString lockName ) { IKString filename; MakeChannelFileName ( channel, lockName, filename ); IKFile::Remove(filename); return kResponseNoError; } static int ReadDataFile (IKString filename, int *response, int *datalength, void *data ) { IKFile f; if (f.Open(filename,IKFile::modeRead)) { f.Read(response,4); f.Read(datalength,4); if(*datalength>0) f.Read(data,*datalength); f.Close(); return kResponseNoError; } return kResponseError; } static int WriteDataFile (IKString filename, int command, int datalength, void *data ) { IKString tempfile = filename; tempfile += TEXT(".temp"); IKFile f; if (f.Open(tempfile,IKFile::modeWrite|IKFile::modeCreate)) { f.Write((void *)&command, sizeof(command) ); f.Write((void *)&datalength,sizeof(datalength)); if (data!=NULL && datalength>0) f.Write(data,datalength); f.Close(); IKFile::Remove(filename); #ifdef PLAT_WINDOWS IKFile::Rename(tempfile,filename); #else // spec the old name. Must exist. FSSpec spec; TCHAR macFileName[255]; IKString::strcpy(&(macFileName[1]),tempfile); macFileName[0] = IKString::strlen(&(macFileName[1])); OSErr err = FSMakeFSSpec( 0, 0, (unsigned TCHAR *)macFileName, &spec ); if (err==noErr) { int i = filename.ReverseFind(TCHAR(':')); IKString shortname = filename.Mid(i+1); IKString::strcpy(&(macFileName[1]),shortname); macFileName[0] = IKString::strlen(&(macFileName[1])); err = FSpRename ( &spec, (unsigned TCHAR *) macFileName ); } #endif return kResponseNoError; } return kResponseError; } int IKMsg::Send ( IKString channel, int command, void *dataOut, int dataOutLen, void *dataIn,int *dataInLen ) { return IKMsg::SendTO ( channel, command, dataOut, dataOutLen, dataIn, dataInLen, defaultTimeout ); } int IKMsg::SendTO ( IKString channel, int command, void *dataOut, int dataOutLen, void *dataIn,int *dataInLen, int timeoutMS ) { //::MessageBox(NULL,"IKMsg::SendTO start","",MB_OK); // take out a transaction lock. int err = GetLock ( channel, IKString(strTransactLockFile), timeoutMS ); if (err != kResponseNoError) { return err; } // clean out the channel. CleanupChannel(channel); // send the command IKString filename; MakeChannelFileName(channel,IKString(strCommandFile),filename); err = WriteDataFile ( filename, command, dataOutLen, dataOut ); // get the response with timeout if (err == kResponseNoError) { unsigned int start = IKUtil::GetCurrentTimeMS(); while (1==1) { // read the file IKString responsefile; int l = 0; MakeChannelFileName(channel,IKString(strResponseFile),responsefile); int response; BYTE mydata[4096]; err = ReadDataFile ( responsefile, &response, &l, mydata); // if success, give data to caller and break if (err == kResponseNoError) { if (dataInLen) *dataInLen = l; if (dataIn) { for (int i=0;i<l;i++) ((BYTE *)dataIn)[i] = mydata[i]; ((BYTE *)dataIn)[l] = 0; ((BYTE *)dataIn)[l+1] = 0; } err = response; break; } // no time out. if (timeoutMS<=0) { err = kResponseError; break; } // time out unsigned int now = IKUtil::GetCurrentTimeMS(); if (now>start+timeoutMS) { err = kResponseTimeout; break; } // wait and try again IKUtil::Sleep(100); } } // clean out the channel. CleanupChannel(channel); // release the transaction lock. ReleaseLock ( channel, IKString(strTransactLockFile) ); return err; } int IKMsg::Receive ( IKString channel, int *command, void *data, int maxdata, int *dataread ) { int x = maxdata; IKString filename; MakeChannelFileName(channel,IKString(strCommandFile),filename); int err = ReadDataFile ( filename, command, dataread, data ); if(err==kResponseError) err = kResponseNoCommand; IKFile::Remove(filename); return err; } int IKMsg::Respond ( IKString channel, int response, void *data, int datalength ) { IKString filename; MakeChannelFileName(channel,IKString(strResponseFile),filename); int err = WriteDataFile ( filename, response, datalength, data ); return err; } void IKMsg::CleanSendingChannel() { IKString filename; MakeChannelFileName(TEXT("sending"),strTransactLockFile,filename); IKFile::Remove(filename); MakeChannelFileName(TEXT("sending"),strCommandFile,filename); IKFile::Remove(filename); filename += TEXT(".temp"); IKFile::Remove(filename); MakeChannelFileName(TEXT("sending"),strResponseFile,filename); IKFile::Remove(filename); filename += TEXT(".temp"); IKFile::Remove(filename); } void IKMsg::Initialize() { IKString filename; MakeChannelFileName(TEXT("sending"),"a.a",filename); IKFile::MakeWritable(filename); }
mit
hamid-omid/search_relevance
xgbFunctions.py
6347
''' Required functions for xgb.py __Author__: Ali Narimani __Version__: 2.1 ''' from sklearn.base import BaseEstimator, TransformerMixin from sklearn.metrics import mean_squared_error, make_scorer import re from nltk.stem.porter import * ### Keys: Snow = True # stemmer choice #### if Snow: from nltk.stem.snowball import SnowballStemmer #0.003 improvement but takes twice as long as PorterStemmer stemmer = SnowballStemmer('english') else: stemmer = PorterStemmer() def DeepClean(word): word = word.replace('kholerhighland', 'kohler highline') word = word.replace('smart', ' smart ') word = word.replace('residential', ' residential ') word = word.replace('whirlpool', ' whirlpool ') word = word.replace('alexandrea',' alexandria ') word = word.replace('bicycle',' bicycle ') word = word.replace('non',' non ') word = word.replace('replacement',' replacement') word = word.replace('mowerectrical', 'mow electrical') word = word.replace('dishwaaher', 'dishwasher') word = word.replace('fairfield',' fairfield ') word = word.replace('hooverwindtunnel','hoover windtunnel') word = word.replace('airconditionerwith','airconditioner with ') word = word.replace('pfistersaxton', 'pfister saxton') word = word.replace('eglimgton','ellington') word = word.replace('chrome', ' chrome ') word = word.replace('foot', ' foot ') word = word.replace('samsung', ' samsung ') word = word.replace('galvanised', ' galvanised ') word = word.replace('exhaust', ' exhaust ') word = word.replace('reprobramable', 'reprogramable') word = word.replace('rackcloset', 'rack closet ') word = word.replace('hamptonbay', ' hampton bay ') word = word.replace('cadet', ' cadet ') word = word.replace('weatherstripping', 'weather stripping') word = word.replace('poyurethane', 'polyurethane') word = word.replace('refrigeratorators','refrigerator') word = word.replace('baxksplash','backsplash') word = word.replace('inches',' inch ') word = word.replace('conditioner',' conditioner ') word = word.replace('landscasping',' landscaping ') word = word.replace('discontinuedbrown',' discontinued brown ') word = word.replace('drywall',' drywall ') word = word.replace('carpet', ' carpet ') word = word.replace('less', ' less ') word = word.replace('tub', ' tub') word = word.replace('tubs', ' tub ') word = word.replace('marble',' marble ') word = word.replace('replaclacemt',' replacement ') word = word.replace('non',' non ') word = word.replace('soundfroofing', 'sound proofing') return word def str_stem(s): if isinstance(s, str): s = s.lower() s = DeepClean(s) s = re.sub(r"(\w)\.([A-Z])", r"\1 \2", s) s = re.sub(r"([0-9]+)( *)(inches|inch|in|')\.?", r"\1in. ", s) s = re.sub(r"([0-9]+)( *)(foot|feet|ft|'')\.?", r"\1ft. ", s) s = re.sub(r"([0-9]+)( *)(pounds|pound|lbs|lb)\.?", r"\1lb. ", s) s = s.replace(" x "," xby ") s = s.replace("*"," xby ") s = s.replace(" by "," xby") s = s.replace("x0"," xby 0") s = s.replace("x1"," xby 1") s = s.replace("x2"," xby 2") s = s.replace("x3"," xby 3") s = s.replace("x4"," xby 4") s = s.replace("x5"," xby 5") s = s.replace("x6"," xby 6") s = s.replace("x7"," xby 7") s = s.replace("x8"," xby 8") s = s.replace("x9"," xby 9") s = s.replace("0x","0 xby ") s = s.replace("1x","1 xby ") s = s.replace("2x","2 xby ") s = s.replace("3x","3 xby ") s = s.replace("4x","4 xby ") s = s.replace("5x","5 xby ") s = s.replace("6x","6 xby ") s = s.replace("7x","7 xby ") s = s.replace("8x","8 xby ") s = s.replace("9x","9 xby ") s = re.sub(r"([0-9]+)( *)(square|sq) ?\.?(feet|foot|ft)\.?", r"\1sq.ft. ", s) s = re.sub(r"([0-9]+)( *)(gallons|gallon|gal)\.?", r"\1gal. ", s) s = re.sub(r"([0-9]+)( *)(ounces|ounce|oz)\.?", r"\1oz. ", s) s = re.sub(r"([0-9]+)( *)(centimeters|cm)\.?", r"\1cm. ", s) s = re.sub(r"([0-9]+)( *)(milimeters|mm)\.?", r"\1mm. ", s) s = re.sub(r"([0-9]+)( *)(degrees|degree)\.?", r"\1deg. ", s) s = re.sub(r"([0-9]+)( *)(volts|volt)\.?", r"\1volt. ", s) s = re.sub(r"([0-9]+)( *)(watts|watt)\.?", r"\1watt. ", s) s = re.sub(r"([0-9]+)( *)(amperes|ampere|amps|amp)\.?", r"\1amp. ", s) s = s.replace("whirpool","whirlpool") s = s.replace("whirlpoolga", "whirlpool") s = s.replace("whirlpoolstainless","whirlpool stainless") s = s.replace(" "," ") s = (" ").join([stemmer.stem(z) for z in s.split(" ")]) if s == '': s = 'null' return s.lower() else: return "null" def str_common_word(str1, str2): words, cnt = str1.split(), 0 for word in words: if str2.find(word)>=0: cnt+=1 return cnt def str_whole_word(str1, str2, i_): cnt = 0 while i_ < len(str2): i_ = str2.find(str1, i_) if i_ == -1: return cnt else: cnt += 1 i_ += len(str1) return cnt def jaccard(a, b): a = set(a.split()) b = set(b.split()) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)) class cust_regression_vals(BaseEstimator, TransformerMixin): def fit(self, x, y=None): return self def transform(self, hd_searches): d_col_drops=['id','relevance','search_term','product_title','product_description','attr','brand','Synonym',\ 'material','color'] hd_searches = hd_searches.drop(d_col_drops,axis=1).values return hd_searches class cust_txt_col(BaseEstimator, TransformerMixin): def __init__(self, key): self.key = key def fit(self, x, y=None): return self def transform(self, data_dict): return data_dict[self.key].apply(str) def fmean_squared_error(ground_truth, predictions): fmean_squared_error_ = mean_squared_error(ground_truth, predictions)**0.5 return fmean_squared_error_ RMSE = make_scorer(fmean_squared_error, greater_is_better=False)
mit
onfido/dependencies-resolver
dependencies_resolver/config/configuration.py
156
import os SCHEMA_FILE_LOCATION = os.path.join(os.path.dirname(__file__), 'schema.json') REGEX_MULTIPART_UPLOAD_PATTERN = r'-\d+' DEFAULT_CHUNK_SIZE = 4096
mit
harinathebc/sample_codeigniter
assets/vendor/moment-develop/locale/ka.js
4192
//! moment.js locale configuration //! locale : Georgian (ka) //! author : Irakli Janiashvili : https://github.com/irakli-janiashvili ;(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 ka = moment.defineLocale('ka', { months : { standalone: 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), format: 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') }, monthsShort : 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'), weekdays : { standalone: 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_'), isFormat: /(წინა|შემდეგ)/ }, weekdaysShort : 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'), weekdaysMin : 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'), longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY h:mm A', LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { sameDay : '[დღეს] LT[-ზე]', nextDay : '[ხვალ] LT[-ზე]', lastDay : '[გუშინ] LT[-ზე]', nextWeek : '[შემდეგ] dddd LT[-ზე]', lastWeek : '[წინა] dddd LT-ზე', sameElse : 'L' }, relativeTime : { future : function (s) { return (/(წამი|წუთი|საათი|წელი)/).test(s) ? s.replace(/ი$/, 'ში') : s + 'ში'; }, past : function (s) { if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { return s.replace(/(ი|ე)$/, 'ის წინ'); } if ((/წელი/).test(s)) { return s.replace(/წელი$/, 'წლის წინ'); } }, s : 'რამდენიმე წამი', m : 'წუთი', mm : '%d წუთი', h : 'საათი', hh : '%d საათი', d : 'დღე', dd : '%d დღე', M : 'თვე', MM : '%d თვე', y : 'წელი', yy : '%d წელი' }, ordinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/, ordinal : function (number) { if (number === 0) { return number; } if (number === 1) { return number + '-ლი'; } if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { return 'მე-' + number; } return number + '-ე'; }, week : { dow : 1, doy : 7 } }); return ka; }));
mit
piedoom/TumblrSharp
Examples/.Net Framework/Console/CreateTextPost/Program.cs
963
using DontPanic.TumblrSharp; using DontPanic.TumblrSharp.OAuth; using DontPanic.TumblrSharp.Client; using System; using System.Threading.Tasks; using ConsoleBasics; namespace CreateTextPost { public class Tumblr : TumblrBase { public async Task<PostCreationInfo> Post(string text) { //replace blogName with your blogname string blogName = "Your blogName"; var test = await client.CreatePostAsync(blogName, PostData.CreateText(text)); return test; } } class Program { static void Main(string[] args) { Tumblr tb = new Tumblr(); Console.WriteLine("Text posted:"); Console.WriteLine(); var text = Console.ReadLine(); var test = tb.Post(text).GetAwaiter().GetResult(); Console.WriteLine("Post ID: " + test.PostId.ToString()); Console.ReadKey(); } } }
mit
jmptable/semanter
Semanter/app/src/main/java/us/semanter/app/ui/review/NoteView.java
4694
package us.semanter.app.ui.review; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.util.AttributeSet; import android.view.MotionEvent; import us.semanter.app.model.Note; import us.semanter.app.ui.VisionView; public class NoteView extends VisionView { private final static float ZOOM_FACTOR = 4.0f; private Note note; private Bitmap noteImage; private float startZoom, currentZoom, imageZoom; private PointF startPosition, currentPosition, imagePosition; private boolean panning, zooming; public NoteView(Context ctx, AttributeSet attrSet) { super(ctx, attrSet); } public NoteView(Context ctx) { super(ctx); } public void setNote(Note note) { startZoom = 1.0f; currentZoom = 1.0f; imageZoom = 1.0f; currentPosition = new PointF(0, 0); startPosition = new PointF(0, 0); imagePosition = new PointF(0, 0); panning = false; zooming = false; this.note = note; noteImage = BitmapFactory.decodeFile(note.getLast().getPath()); } @Override protected void render(Canvas canvas) { Paint p = new Paint(); canvas.drawColor(Color.BLACK); if(noteImage != null) { float z; if(zooming) { z = imageZoom + (currentZoom - startZoom); } else { z = imageZoom; } canvas.scale(z, z, getWidth()/2.0f, getHeight()/2.0f); if(panning) { float dx = currentPosition.x - startPosition.x; float dy = currentPosition.y - startPosition.y; canvas.translate((imagePosition.x + dx)/z, (imagePosition.y + dy)/z); } else { canvas.translate(imagePosition.x/z, imagePosition.y/z); } canvas.drawBitmap(noteImage, 0, 0, p); } } @Override public boolean onTouchEvent(MotionEvent event) { switch(event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { // panning currentPosition.set(event.getX(), event.getY()); startPosition.set(event.getX(), event.getY()); panning = true; break; } case MotionEvent.ACTION_POINTER_DOWN: { panning = false; // zooming float x1 = event.getX(0); float y1 = event.getY(0); float x2 = event.getX(1); float y2 = event.getY(1); float distance = (float) Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); currentZoom = distance / (Math.max(getWidth(), getHeight()) / ZOOM_FACTOR); startZoom = currentZoom; zooming = true; break; } case MotionEvent.ACTION_MOVE: { if (event.getPointerCount() == 1) { if(panning) currentPosition.set(event.getX(), event.getY()); } else if (event.getPointerCount() == 2) { if(zooming) { float x1 = event.getX(0); float y1 = event.getY(0); float x2 = event.getX(1); float y2 = event.getY(1); float distance = (float) Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); currentZoom = distance / (Math.max(getWidth(), getHeight()) / ZOOM_FACTOR); } } break; } case MotionEvent.ACTION_UP: { if(panning) { currentPosition.set(event.getX(), event.getY()); // panning float dx = currentPosition.x - startPosition.x; float dy = currentPosition.y - startPosition.y; imagePosition.set(imagePosition.x + dx, imagePosition.y + dy); panning = false; } break; } case MotionEvent.ACTION_POINTER_UP: { if(zooming) { // zooming float deltaZoom = currentZoom - startZoom; imageZoom += deltaZoom; zooming = false; } break; } } return true; } }
mit
repne/happyface
HappyFace.Store/Storage/FileStorage.cs
1561
using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using HappyFace.Store.Serialization; namespace HappyFace.Store.Storage { public class FileStorage : IStorage { private readonly string _path; private readonly ISerializerFactory _serializerFactory; public FileStorage(string path, ISerializerFactory serializerFactory) { _path = path; _serializerFactory = serializerFactory; } public async Task Write<T>(IEnumerable<T> items, CancellationToken token) { var serializer = _serializerFactory.Create<T>(); using (var fs = new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) { foreach (var item in items) { serializer.Serialize(fs, item); } await fs.FlushAsync(token); } } public IEnumerable<T> Read<T>() { var serializer = _serializerFactory.Create<T>(); if (!File.Exists(_path)) { yield break; } using (var stream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.None, bufferSize: 4096, useAsync: true)) { while (stream.Position != stream.Length) { yield return serializer.Deserialize(stream); } } } } }
mit
Trikisatan/Newnorth-Alerts
WWW/Framework/Controls/TextBoxControl.php
1419
<? namespace Framework\Controls; use \Framework\Newnorth\Control; use \Framework\Newnorth\ConfigException; class TextBoxControl extends Control { /* Life cycle methods */ public function Initialize() { } public function Load() { } public function Execute() { } /* Methods */ public function ParseParameters() { $this->_Parameters['IsDisabled'] = isset($this->_Parameters['IsDisabled']) ? $this->_Parameters['IsDisabled'] === true : false; $this->_Parameters['IsReadOnly'] = isset($this->_Parameters['IsReadOnly']) ? $this->_Parameters['IsReadOnly'] === true : false; if(isset($this->_Parameters['Validators'])) { $this->ParseParameters_Validators($this->_Parameters['Validators']); } } private function ParseParameters_Validators($Validators) { $this->_Parameters['Validators'] = []; foreach($Validators as $Method => $Parameters) { $Method = 'Render'.$Method.'Validator'; if(!$this->GetValidatorRenderMethod($Method, $Owner)) { throw new ConfigException( 'Unable to find validator render method.', [ 'Object' => $this->__toString(), 'Method' => $Method, ] ); } $this->_Parameters['Validators'][] = [ 'Owner' => $Owner, 'Method' => $Method, 'Parameters' => $Parameters, 'ErrorMessage' => $Parameters['ErrorMessage'], ]; } } public function AutoFill($Value) { $this->_Parameters['Value'] = $Value; } } ?>
mit
TinyTronics/TM1637_6D
TM1637_6D.cpp
9951
/* * TM1637_6D.cpp * A library for the 6 digit TM1637 based segment display * * Modified for 6 digits and points by: TinyTronics.nl * * Copyright (c) 2012 seeed technology inc. * Website : www.seeed.cc * Author : Frankie.Chu * Create Time: 9 April,2012 * Change Log : * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "TM1637_6D.h" #include <Arduino.h> static int8_t TubeTab[] = {0x3f,0x06,0x5b,0x4f, 0x66,0x6d,0x7d,0x07, 0x7f,0x6f,0x00,0x40};//0~9, 10=blank digit, 11=dash/minus character TM1637_6D::TM1637_6D(uint8_t Clk, uint8_t Data) { Clkpin = Clk; Datapin = Data; pinMode(Clkpin,OUTPUT); pinMode(Datapin,OUTPUT); } void TM1637_6D::init(void) { clearDisplay(); } int TM1637_6D::writeByte(int8_t wr_data) { uint8_t i,count1; for(i=0;i<8;i++) //sent 8bit data { digitalWrite(Clkpin,LOW); if(wr_data & 0x01)digitalWrite(Datapin,HIGH);//LSB first else digitalWrite(Datapin,LOW); wr_data >>= 1; digitalWrite(Clkpin,HIGH); } digitalWrite(Clkpin,LOW); //wait for the ACK digitalWrite(Datapin,HIGH); digitalWrite(Clkpin,HIGH); pinMode(Datapin,INPUT); bitDelay(); uint8_t ack = digitalRead(Datapin); if (ack == 0) { pinMode(Datapin,OUTPUT); digitalWrite(Datapin,LOW); } bitDelay(); pinMode(Datapin,OUTPUT); bitDelay(); return ack; } //send start signal to TM1637 void TM1637_6D::start(void) { digitalWrite(Clkpin,HIGH);//send start signal to TM1637 digitalWrite(Datapin,HIGH); digitalWrite(Datapin,LOW); digitalWrite(Clkpin,LOW); } //End of transmission void TM1637_6D::stop(void) { digitalWrite(Clkpin,LOW); digitalWrite(Datapin,LOW); digitalWrite(Clkpin,HIGH); digitalWrite(Datapin,HIGH); } //display function.Write to full-screen. void TM1637_6D::display(int8_t DispData[], int8_t DispPointData[]) { int8_t SegData[6]; int8_t SegPointData[6]; int8_t i; for(i = 0;i < 6;i++) { if(DispData[i] > 11 || DispData[i] < 0) DispData[i] = 11; } SegData[0] = DispData[3]; SegData[1] = DispData[4]; SegData[2] = DispData[5]; SegData[3] = DispData[0]; SegData[4] = DispData[1]; SegData[5] = DispData[2]; SegPointData[0] = DispPointData[3]; SegPointData[1] = DispPointData[4]; SegPointData[2] = DispPointData[5]; SegPointData[3] = DispPointData[0]; SegPointData[4] = DispPointData[1]; SegPointData[5] = DispPointData[2]; coding(SegData, SegPointData); start(); //start signal sent to TM1637 from MCU writeByte(ADDR_AUTO);// stop(); // start(); // writeByte(Cmd_SetAddr);// for(i=0;i < 6;i ++) { writeByte(SegData[i]); // } stop(); // start(); // writeByte(Cmd_DispCtrl);// stop(); // } //****************************************** void TM1637_6D::display(uint8_t BitAddr,int8_t DispData,int8_t DispPointData) { int8_t SegData; SegData = coding(DispData, DispPointData); start(); //start signal sent to TM1637 from MCU writeByte(ADDR_FIXED);// stop(); // start(); // writeByte(BitAddr|0xc0);// writeByte(SegData);// stop(); // start(); // writeByte(Cmd_DispCtrl);// stop(); // } // Displays 6 dashes are error marker void TM1637_6D::displayError() { int8_t tempListDisp[6] = {11,11,11,11,11,11}; // fill array with dashes character(11th) int8_t tempListDispPoint[6] = {0x00,0x00,0x00,0x00,0x00,0x00}; // don't show any points display(tempListDisp, tempListDispPoint); } void TM1637_6D::displayInteger(int32_t intdisplay, bool leading_zeros) { int8_t tempListDisp[6] = {10,10,10,10,10,10}; // fill array with value for blank digit int8_t tempListDispPoint[6] = {0x00,0x00,0x00,0x00,0x00,0x00}; // don't show any points int8_t i = 0; // String for converting millis value to seperate characters in the string String intstring; // if the integer is bigger than 6 characters, display an error(dashes) if(intdisplay > 999999 || intdisplay < -99999) { displayError(); } else { if(intdisplay < 0) { intstring = String((intdisplay*-1), DEC); // convertering the inverted integer to a string if(leading_zeros) { intstring = "000000" + intstring; } // Adding some extra leading zeros for(i = 0; i < intstring.length(); i++) { // number "0" in ASCII is 48 in decimal. If we substract the character value // with 48, we will get the actual number it is representing as a character tempListDisp[i] = intstring[intstring.length()-i-1] - 48; } tempListDisp[5] = 11;// adding the dash/minus later for this negative integer } else { intstring = String(intdisplay, DEC); // convertering integer to a string if(leading_zeros){ intstring = "000000" + intstring;} // Adding some extra leading zeros for(i = 0; i < intstring.length(); i++) { // number "0" in ASCII is 48 in decimal. If we substract the character value // with 48, we will get the actual number it is representing as a character tempListDisp[i] = intstring[intstring.length()-i-1] - 48; } } display(tempListDisp, tempListDispPoint); } } void TM1637_6D::displayFloat(float floatdisplay) { int8_t tempListDisp[6] = {10,10,10,10,10,10}; // fill array with value for blank digit int8_t tempListDispPoint[6] = {0x00,0x00,0x00,0x00,0x00,0x00}; // don't show any points int8_t i = 0; // String for converting millis value to seperate characters in the string String floatstring; // if the integer is bigger than 6 characters, display an error(dashes) if(floatdisplay >= 999999.5 || floatdisplay <= -99999.5) { displayError(); } else { // Calculate how many digits we have before the decimal point if(floatdisplay < 0) { floatstring = String(floatdisplay*-1.0, 1);} // with one "dummy" decimal else { floatstring = String(floatdisplay, 1);} // with one "dummy" decimal for(i = 0; i < floatstring.length(); i++) { // check how many digits we have before the decimal point if(floatstring[i] == '.') break; } uint8_t numberofdigits = i; uint8_t decimal_point_add = 0; // used to skip the decimal point in the string if(floatdisplay < 0) { floatstring = String((floatdisplay*-1.0), 5-numberofdigits); // convertering the inverted integer to a string decimal_point_add = 0; for(i = 0; i < floatstring.length(); i++) { // number "0" in ASCII is 48 in decimal. If we substract the character value // with 48, we will get the actual number it is representing as a character tempListDisp[i] = floatstring[floatstring.length()-i-1-decimal_point_add] - 48; if(floatstring[floatstring.length()-i-2] == '.') { tempListDispPoint[i+1] = 0x80; // set decimal point decimal_point_add = 1; } } tempListDisp[5] = 11;// adding the dash/minus later for this negative integer } else { floatstring = String(floatdisplay, 6-numberofdigits); // convertering integer to a string decimal_point_add = 0; Serial.println(floatstring.length()); for(i = 0; i < (floatstring.length() - decimal_point_add); i++) { // number "0" in ASCII is 48 in decimal. If we substract the character value // with 48, we will get the actual number it is representing as a character tempListDisp[i] = floatstring[floatstring.length()-i-1-decimal_point_add] - 48; if(floatstring[floatstring.length()-i-2] == '.') { tempListDispPoint[i+1] = 0x80; // set decimal point decimal_point_add = 1; } } } if(decimal_point_add == 0) tempListDispPoint[0] = 0x80; display(tempListDisp, tempListDispPoint); } } void TM1637_6D::clearDisplay(void) { int8_t tempListDisp[6] = {10,10,10,10,10,10}; // fill array with dashes character(11th) int8_t tempListDispPoint[6] = {0x00,0x00,0x00,0x00,0x00,0x00}; // don't show any poinst display(tempListDisp, tempListDispPoint); } //To take effect the next time it displays. void TM1637_6D::set(uint8_t brightness,uint8_t SetData,uint8_t SetAddr) { Cmd_SetData = SetData; Cmd_SetAddr = SetAddr; Cmd_DispCtrl = 0x88 + brightness;//Set the brightness and it takes effect the next time it displays. } void TM1637_6D::coding(int8_t DispData[], int8_t DispPointData[]) { for(uint8_t i = 0;i < 6;i ++) { if(DispData[i] == 0x7f)DispData[i] = 0x00 + DispPointData[i]; else DispData[i] = TubeTab[DispData[i]] + DispPointData[i]; } } int8_t TM1637_6D::coding(int8_t DispData, int8_t DispPointData) { if(DispData == 0x7f) DispData = 0x00 + DispPointData;//The bit digital tube off else DispData = TubeTab[DispData] + DispPointData; return DispData; } void TM1637_6D::bitDelay(void) { delayMicroseconds(50); }
mit
nvtNgan/rpg-game-k16
rpg-game/js/plugins/YEP_X_TickBasedRegen.js
9978
//============================================================================= // Yanfly Engine Plugins - Extension Plugin - Tick Based Regeneration // YEP_X_TickBasedRegen.js //============================================================================= var Imported = Imported || {}; Imported.YEP_X_TickBasedRegen = true; var Yanfly = Yanfly || {}; Yanfly.TBR = Yanfly.TBR || {}; //============================================================================= /*: * @plugindesc v1.03 (Req YEP_BattleEngineCore & YEP_BuffsStatesCore) * Tick-Based Battle system regeneration. * @author Yanfly Engine Plugins * * @help * ============================================================================ * Introduction * ============================================================================ * * This plugin requires YEP_BattleEngineCore.js and YEP_BuffsStatesCore.js. * Make sure this plugin is located under both of the listed plugins in the * plugin list. * * For those running a Tick-Based Battle System with the Battle Engine Core * (ie. Active Turn Battle or Charge Turn Battle), this will automatically set * your states for Turn End timings to use a Time Based system, but in turn, * causes regeneration effects to occur individually. * * This means that if Harold receives Low Healing Regen, then 50 ticks later, * receives High Healing Regen, Harold does not regenerate HP at the same time. * Instead, he will regenerate individually for both Low Healing Regen and High * Healing Regen. * * For states that do not function off a Turn End system but still utilize * regeneration effects, those effects will also work off a tick-based manner. * * Lunatic Mode Regenerate effects from the Buffs & States Core plugin will * also function off of a periodic timed system as opposed to a regular per * actor turn system. * * If a state has been reapplied, the regeneration counter will also be reset * as to synchronize with the state's turn counter. * * If a battler has passive states, that battler's regeneration effects will * reset at the start of each battle and clear itself at the end of battle. For * example, if the amount of time you've set in the Battle Engine Core for the * states to tick down is 100, at the start of battle, all passive states will * be reset to 100 and must reach 0 before the regeneration effects trigger. * * *NOTE: Only states will function off of tick-based regeneration. HP/MP/TP * regeneration gained from traits in the actor, class, enemy, weapon, or armor * database object entries will occur upon the battler's turn end. * * ============================================================================ * Changelog * ============================================================================ * * Version 1.03: * - Added anti-crash method for actors that are joining mid-party. * * Version 1.02: * - Fixed a bug that caused HP/MP/TP regeneration from non-states to not * function properly. They will now occur at turn end. * * Version 1.01: * - Fixed a bug that caused tick-based states to not trigger Leave effects. * * Version 1.00: * - Finished Plugin! */ //============================================================================= if (Imported.YEP_BattleEngineCore && Imported.YEP_BuffsStatesCore) { //============================================================================= // Parameter Variables //============================================================================= Yanfly.Param.BECTimeStates = 'true'; //============================================================================= // Game_BattlerBase //============================================================================= Yanfly.TBR.Game_BattlerBase_refresh = Game_BattlerBase.prototype.refresh; Game_BattlerBase.prototype.refresh = function() { this._cacheStatesLength = undefined; this._cacheStatesIndex = []; Yanfly.TBR.Game_BattlerBase_refresh.call(this); }; Yanfly.TBR.Game_BattlerBase_traitObjects = Game_BattlerBase.prototype.traitObjects; Game_BattlerBase.prototype.traitObjects = function() { if ($gameTemp._tickBasedTraits) return []; return Yanfly.TBR.Game_BattlerBase_traitObjects.call(this); }; Yanfly.TBR.Game_Battler_regenerateHp = Game_Battler.prototype.regenerateHp; Game_Battler.prototype.regenerateHp = function() { if (BattleManager.timeBasedStates()) $gameTemp._tickBasedTraits = true; Yanfly.TBR.Game_Battler_regenerateHp.call(this); $gameTemp._tickBasedTraits = undefined; }; Yanfly.TBR.Game_Battler_regenerateMp = Game_Battler.prototype.regenerateMp; Game_Battler.prototype.regenerateMp = function() { if (BattleManager.timeBasedStates()) $gameTemp._tickBasedTraits = true; Yanfly.TBR.Game_Battler_regenerateMp.call(this); $gameTemp._tickBasedTraits = undefined; }; Yanfly.TBR.Game_Battler_regenerateTp = Game_Battler.prototype.regenerateTp; Game_Battler.prototype.regenerateTp = function() { if (BattleManager.timeBasedStates()) $gameTemp._tickBasedTraits = true; Yanfly.TBR.Game_Battler_regenerateTp.call(this); $gameTemp._tickBasedTraits = undefined; }; Game_BattlerBase.prototype.updateStateTicks = function() { if (this.isDead()) return; var needRefresh = false; var length = this._cacheStatesLength || this.states().length; this._cachePassiveTicks = this._cachePassiveTicks || {}; this._cacheStatesIndex = this._cacheStatesIndex || []; for (var i = 0; i < length; ++i) { if (!this._cacheStatesIndex[i]) { var state = this.states()[i]; if (state) this._cacheStatesIndex[i] = this.states()[i].id; } var stateId = this._cacheStatesIndex[i]; var state = $dataStates[stateId]; if (!state) continue; if (state.autoRemovalTiming === 2 && this._stateTurns[stateId]) { var value = BattleManager.tickRate() / Yanfly.Param.BECTurnTime; var shown1 = Math.ceil(this._stateTurns[stateId]); this._stateTurns[stateId] -= value; var shown2 = Math.ceil(this._stateTurns[stateId]); } else { if (!this._cachePassiveTicks[stateId]) { this._cachePassiveTicks[stateId] = Yanfly.Param.BECTurnTime; } var value = BattleManager.tickRate() / Yanfly.Param.BECTurnTime; var shown1 = Math.ceil(this._cachePassiveTicks[stateId]); this._cachePassiveTicks[stateId] -= value; var shown2 = Math.ceil(this._cachePassiveTicks[stateId]); } if (shown1 !== shown2) { this.updateStateTickRegen(state); needRefresh = true; } if (state.autoRemovalTiming === 2) { if (this._stateTurns[stateId] && this._stateTurns[stateId] <= 0) { $gameTemp._customLeaveEffectEval = true; this.removeState(stateId); $gameTemp._customLeaveEffectEval = undefined; } } } if (needRefresh) this.refresh(); }; Game_BattlerBase.prototype.updateStateTickRegen = function(state) { this.clearResult(); this.regenerateHpTick(state); this.regenerateMpTick(state); this.regenerateTpTick(state); this.startDamagePopup(); this.clearResult(); this.regenerateStateEffects(state.id); this.clearResult(); }; Game_BattlerBase.prototype.getStateTickTraits = function(state, code, dataId) { var length = state.traits.length; var value = 0; for (var i = 0; i < length; ++i) { var trait = state.traits[i]; if (trait.code === code && trait.dataId === dataId) { value += trait.value; } } return value; }; Game_BattlerBase.prototype.regenerateHpTick = function(state) { var rate = this.getStateTickTraits(state, 22, 7); var value = Math.floor(this.mhp * rate); value = Math.max(value, -this.maxSlipDamage()); if (value !== 0) { this.clearResult(); this.gainHp(value); this.startDamagePopup(); this.clearResult(); } }; Game_BattlerBase.prototype.regenerateMpTick = function(state) { var rate = this.getStateTickTraits(state, 22, 8); var value = Math.floor(this.mmp * rate); if (value !== 0) { this.clearResult(); this.gainMp(value); this.startDamagePopup(); this.clearResult(); } }; Game_BattlerBase.prototype.regenerateTpTick = function(state) { var rate = this.getStateTickTraits(state, 22, 9); var value = Math.floor(this.maxTp() * rate); if (value !== 0) this.gainSilentTp(value); }; Yanfly.TBR.Game_BattlerBase_resetStateCounts = Game_BattlerBase.prototype.resetStateCounts; Game_BattlerBase.prototype.resetStateCounts = function(stateId) { Yanfly.TBR.Game_BattlerBase_resetStateCounts.call(this, stateId); var state = $dataStates[stateId]; if (state && state.reapplyRules !== 0) { this._cachePassiveTicks = this._cachePassiveTicks || {}; this._cachePassiveTicks[stateId] = Yanfly.Param.BECTurnTime; } }; //============================================================================= // Game_Battler //============================================================================= Yanfly.TBR.Game_Battler_onBattleStart = Game_Battler.prototype.onBattleStart; Game_Battler.prototype.onBattleStart = function() { this._cachePassiveTicks = {}; Yanfly.TBR.Game_Battler_onBattleStart.call(this); }; Yanfly.TBR.Game_Battler_onBattleEnd = Game_Battler.prototype.onBattleEnd; Game_Battler.prototype.onBattleEnd = function() { this._cachePassiveTicks = {}; Yanfly.TBR.Game_Battler_onBattleEnd.call(this); }; Yanfly.TBR.Game_Battler_onRegenerateStateEffects = Game_Battler.prototype.onRegenerateStateEffects; Game_Battler.prototype.onRegenerateStateEffects = function() { if (BattleManager.timeBasedStates()) return; Yanfly.TBR.Game_Battler_onRegenerateStateEffects.call(this); }; //============================================================================= // End of File //============================================================================= };
mit
rainlike/justshop
vendor/knplabs/gaufrette/src/Gaufrette/Adapter/AwsS3.php
9911
<?php namespace Gaufrette\Adapter; use Gaufrette\Adapter; use Aws\S3\S3Client; use Gaufrette\Util; /** * Amazon S3 adapter using the AWS SDK for PHP v2.x. * * @author Michael Dowling <[email protected]> */ class AwsS3 implements Adapter, MetadataSupporter, ListKeysAware, SizeCalculator, MimeTypeProvider { /** @var S3Client */ protected $service; /** @var string */ protected $bucket; /** @var array */ protected $options; /** @var bool */ protected $bucketExists; /** @var array */ protected $metadata = []; /** @var bool */ protected $detectContentType; /** * @param S3Client $service * @param string $bucket * @param array $options * @param bool $detectContentType */ public function __construct(S3Client $service, $bucket, array $options = [], $detectContentType = false) { $this->service = $service; $this->bucket = $bucket; $this->options = array_replace( [ 'create' => false, 'directory' => '', 'acl' => 'private', ], $options ); $this->detectContentType = $detectContentType; } /** * Gets the publicly accessible URL of an Amazon S3 object. * * @param string $key Object key * @param array $options Associative array of options used to buld the URL * - expires: The time at which the URL should expire * represented as a UNIX timestamp * - Any options available in the Amazon S3 GetObject * operation may be specified. * * @return string * * @deprecated 1.0 Resolving object path into URLs is out of the scope of this repository since v0.4. gaufrette/extras * provides a Filesystem decorator with a regular resolve() method. You should use it instead. * * @see https://github.com/Gaufrette/extras */ public function getUrl($key, array $options = []) { @trigger_error( E_USER_DEPRECATED, 'Using AwsS3::getUrl() method was deprecated since v0.4. Please chek gaufrette/extras package if you want this feature' ); return $this->service->getObjectUrl( $this->bucket, $this->computePath($key), isset($options['expires']) ? $options['expires'] : null, $options ); } /** * {@inheritdoc} */ public function setMetadata($key, $metadata) { // BC with AmazonS3 adapter if (isset($metadata['contentType'])) { $metadata['ContentType'] = $metadata['contentType']; unset($metadata['contentType']); } $this->metadata[$key] = $metadata; } /** * {@inheritdoc} */ public function getMetadata($key) { return isset($this->metadata[$key]) ? $this->metadata[$key] : []; } /** * {@inheritdoc} */ public function read($key) { $this->ensureBucketExists(); $options = $this->getOptions($key); try { // Get remote object $object = $this->service->getObject($options); // If there's no metadata array set up for this object, set it up if (!array_key_exists($key, $this->metadata) || !is_array($this->metadata[$key])) { $this->metadata[$key] = []; } // Make remote ContentType metadata available locally $this->metadata[$key]['ContentType'] = $object->get('ContentType'); return (string) $object->get('Body'); } catch (\Exception $e) { return false; } } /** * {@inheritdoc} */ public function rename($sourceKey, $targetKey) { $this->ensureBucketExists(); $options = $this->getOptions( $targetKey, ['CopySource' => $this->bucket.'/'.$this->computePath($sourceKey)] ); try { $this->service->copyObject(array_merge($options, $this->getMetadata($targetKey))); return $this->delete($sourceKey); } catch (\Exception $e) { return false; } } /** * {@inheritdoc} */ public function write($key, $content) { $this->ensureBucketExists(); $options = $this->getOptions($key, ['Body' => $content]); /* * If the ContentType was not already set in the metadata, then we autodetect * it to prevent everything being served up as binary/octet-stream. */ if (!isset($options['ContentType']) && $this->detectContentType) { $options['ContentType'] = $this->guessContentType($content); } try { $this->service->putObject($options); if (is_resource($content)) { return Util\Size::fromResource($content); } return Util\Size::fromContent($content); } catch (\Exception $e) { return false; } } /** * {@inheritdoc} */ public function exists($key) { return $this->service->doesObjectExist($this->bucket, $this->computePath($key)); } /** * {@inheritdoc} */ public function mtime($key) { try { $result = $this->service->headObject($this->getOptions($key)); return strtotime($result['LastModified']); } catch (\Exception $e) { return false; } } /** * {@inheritdoc} */ public function size($key) { try { $result = $this->service->headObject($this->getOptions($key)); return $result['ContentLength']; } catch (\Exception $e) { return false; } } /** * {@inheritdoc} */ public function keys() { return $this->listKeys(); } /** * {@inheritdoc} */ public function listKeys($prefix = '') { $options = ['Bucket' => $this->bucket]; if ((string) $prefix != '') { $options['Prefix'] = $this->computePath($prefix); } elseif (!empty($this->options['directory'])) { $options['Prefix'] = $this->options['directory']; } $keys = []; $iter = $this->service->getIterator('ListObjects', $options); foreach ($iter as $file) { $keys[] = $this->computeKey($file['Key']); } return $keys; } /** * {@inheritdoc} */ public function delete($key) { try { $this->service->deleteObject($this->getOptions($key)); return true; } catch (\Exception $e) { return false; } } /** * {@inheritdoc} */ public function isDirectory($key) { $result = $this->service->listObjects([ 'Bucket' => $this->bucket, 'Prefix' => rtrim($this->computePath($key), '/').'/', 'MaxKeys' => 1, ]); return count($result['Contents']) > 0; } /** * Ensures the specified bucket exists. If the bucket does not exists * and the create option is set to true, it will try to create the * bucket. The bucket is created using the same region as the supplied * client object. * * @throws \RuntimeException if the bucket does not exists or could not be * created */ protected function ensureBucketExists() { if ($this->bucketExists) { return true; } if ($this->bucketExists = $this->service->doesBucketExist($this->bucket)) { return true; } if (!$this->options['create']) { throw new \RuntimeException(sprintf( 'The configured bucket "%s" does not exist.', $this->bucket )); } $this->service->createBucket([ 'Bucket' => $this->bucket, 'LocationConstraint' => $this->service->getRegion() ]); $this->bucketExists = true; return true; } protected function getOptions($key, array $options = []) { $options['ACL'] = $this->options['acl']; $options['Bucket'] = $this->bucket; $options['Key'] = $this->computePath($key); /* * Merge global options for adapter, which are set in the constructor, with metadata. * Metadata will override global options. */ $options = array_merge($this->options, $options, $this->getMetadata($key)); return $options; } protected function computePath($key) { if (empty($this->options['directory'])) { return $key; } return sprintf('%s/%s', $this->options['directory'], $key); } /** * Computes the key from the specified path. * * @param string $path * * return string */ protected function computeKey($path) { return ltrim(substr($path, strlen($this->options['directory'])), '/'); } /** * @param string $content * * @return string */ private function guessContentType($content) { $fileInfo = new \finfo(FILEINFO_MIME_TYPE); if (is_resource($content)) { return $fileInfo->file(stream_get_meta_data($content)['uri']); } return $fileInfo->buffer($content); } public function mimeType($key) { try { $result = $this->service->headObject($this->getOptions($key)); return ($result['ContentType']); } catch (\Exception $e) { return false; } } }
mit
CassioAmador/profile_tcabr
visualization_tools/test_custom_spectrogram_sim2.py
2623
"""Compare custom spectrogram with scipy's implementation""" import numpy as np import matplotlib.pyplot as plt from matplotlib.mlab import specgram from scipy import signal import time import sys sys.path.insert(0, './../src/') import custom_spectrogram as cs fs = 100 # 100 MHz tem = np.arange(int(8 * fs)) / fs f = 12 - 4 * np.sqrt(np.arange(tem.size) / tem.size) sinal = np.sin(2 * np.pi * f * tem) + 0.8 * np.sin(2 * np.pi * (f + 6) * tem) + 0.8 * np.sin(2 * np.pi * (f + 12) * tem) nfft = 1* fs window = 80 step_scale = 16 zer_pad = 8 print('\n time cost:') # measure custom spectrogram time # for some unkown reason, the step must be scaled down to compare to scipy. freq_min, freq_max = 0, 15 time0 = time.time() for i in range(10): time_spec, beat_freq = cs.eval_beat_freq(tem, window_size=window, step_scale=step_scale, zer_pad=zer_pad) fmin, fmax, mask = cs.eval_mask(beat_freq, window, freq_min, freq_max, zer_pad=zer_pad) Sxx_custom = cs.spectrogram(sinal, window_size=window, zer_pad=zer_pad, step_scale=step_scale, freq_mask=mask) time1 = time.time() print('\nCUSTOM: {0} ms'.format(100 * (time1 - time0))) plt.subplots(4, 1) ax1 = plt.subplot(411) plt.plot(tem, sinal) plt.xlim(tem[0], tem[-1]) plt.ylabel('signal') plt.setp(ax1.get_xticklabels(), visible=False) ax2 = plt.subplot(412, sharex=ax1) plt.pcolormesh(time_spec, beat_freq[mask], Sxx_custom) plt.plot(tem, f, 'k', lw=2) plt.ylim(freq_min, freq_max) plt.ylabel('custom') plt.setp(ax2.get_xticklabels(), visible=False) # measure scipy spectrogram time time0 = time.time() for i in range(10): freqs, tempo, Sxx_scipy = signal.spectrogram(sinal, fs, nperseg=nfft, noverlap=99, window=signal.get_window('hann', nfft), nfft=512) time1 = time.time() print('\nSCIPY: {0} ms'.format(100 * (time1 - time0))) ax3 = plt.subplot(413) plt.pcolormesh(tempo, freqs, Sxx_scipy) plt.ylim(freq_min, freq_max) plt.plot(tem, f, 'k', lw=2) plt.ylim(freq_min, freq_max) plt.ylabel('scipy') plt.setp(ax3.get_xticklabels(), visible=False) # measure matplotlib spectrogram time plt.subplot(414, sharex=ax1) time0 = time.time() for i in range(10): Sxx_malab, freqs, bins = specgram(sinal, Fs=fs, NFFT=nfft, noverlap=99, pad_to=512) time1 = time.time() print('\nMATPLOTLIB: {0} ms'.format(100 * (time1 - time0))) print('\ntime resolution:\n CUSTOM: {} \t SCIPY: {} \t MATPLOTLIB: {}'.format(Sxx_custom.shape, Sxx_scipy.shape, Sxx_malab.shape)) print('\ndark line is simulated frequency\n') plt.plot(tem, f, 'k', lw=2) plt.pcolormesh(bins, freqs, Sxx_malab) plt.ylim(freq_min, freq_max) plt.ylabel('mlab') plt.tight_layout(h_pad=0) plt.show()
mit
quailjs/quail
test/assessmentSpecs/specs/imgNotReferredToByColorAlone/imgNotReferredToByColorAloneSpec.js
5018
xdescribe('assessment: imgNotReferredToByColorAlone', function () { var client, assessments, quailResults, cases; // Evaluate the test page with Quail. describe('the non-match case', function () { before('load webdrivers and run evaluations with Quail', function () { return quailTestRunner.setup({ url: 'http://localhost:9999/imgNotReferredToByColorAlone/imgNotReferredToByColorAlone-nomatch.html', assessments: [ 'imgNotReferredToByColorAlone' ] }) .spread(function (_client_, _assessments_, _quailResults_) { client = _client_; assessments = _assessments_; quailResults = _quailResults_; cases = quailResults.tests.imgNotReferredToByColorAlone.cases; }); }); after('end the webdriver session', function () { return quailTestRunner.teardown(client); }); it('should return the correct number of tests', function () { expect(quailResults.stats.tests).to.equal(1); }); it('should return the correct number of cases', function () { expect(quailResults.stats.cases).to.equal(1); }); it('should have correct key under the test results', function () { expect(quailResults.tests).to.include.keys('imgNotReferredToByColorAlone'); }); it('should return the proper assessment for the test', function () { expect(cases[0]).to.have.quailStatus('passed'); }); }); // Evaluate the test page with Quail. describe('the match case', function () { before('load webdrivers and run evaluations with Quail', function () { return quailTestRunner.setup({ url: 'http://localhost:9999/imgNotReferredToByColorAlone/imgNotReferredToByColorAlone.html', assessments: [ 'imgNotReferredToByColorAlone' ] }) .spread(function (_client_, _assessments_, _quailResults_) { client = _client_; assessments = _assessments_; quailResults = _quailResults_; cases = quailResults.tests.imgNotReferredToByColorAlone.cases; }); }); after('end the webdriver session', function () { return quailTestRunner.teardown(client); }); it('should return the correct number of tests', function () { expect(quailResults.stats.tests).to.equal(1); }); it('should return the correct number of cases', function () { expect(quailResults.stats.cases).to.equal(0); }); it('should have correct key under the test results', function () { expect(quailResults.tests).to.include.keys('imgNotReferredToByColorAlone'); }); it('should return the proper assessment for assert-1', function () { expect(cases).quailGetById('assert-1').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-2', function () { expect(cases).quailGetById('assert-2').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-3', function () { expect(cases).quailGetById('assert-3').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-4', function () { expect(cases).quailGetById('assert-4').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-5', function () { expect(cases).quailGetById('assert-5').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-6', function () { expect(cases).quailGetById('assert-6').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-7', function () { expect(cases).quailGetById('assert-7').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-8', function () { expect(cases).quailGetById('assert-8').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-9', function () { expect(cases).quailGetById('assert-9').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-10', function () { expect(cases).quailGetById('assert-10').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-11', function () { expect(cases).quailGetById('assert-11').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-12', function () { expect(cases).quailGetById('assert-12').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-13', function () { expect(cases).quailGetById('assert-13').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-14', function () { expect(cases).quailGetById('assert-14').to.have.quailStatus('failed'); }); it('should return the proper assessment for assert-15', function () { expect(cases).quailGetById('assert-15').to.have.quailStatus('failed'); }); }); });
mit
shredder-rull/rhinoart_cms
spec/dummy/config/routes.rb
174
Rails.application.routes.draw do devise_for :users mount Rhinoart::Engine, at: "/" root 'pages#index' match '*url' => 'pages#internal', :as => :page, via: [:get] end
mit
dvsa/mot
mot-web-frontend/module/PersonModule/src/InputFilter/QualificationDetailsInputFilter.php
1239
<?php namespace Dvsa\Mot\Frontend\PersonModule\InputFilter; use DvsaClient\Mapper\QualificationDetailsMapper; use DvsaCommon\Factory\AutoWire\AutoWireableInterface; use DvsaCommon\HttpRestJson\Exception\ValidationException; use Zend\InputFilter\InputFilter; class QualificationDetailsInputFilter extends InputFilter implements AutoWireableInterface { private $qualificationDetailsMapper; private $personId; private $group; private $validationMessages = []; public function __construct(QualificationDetailsMapper $qualificationDetailsMapper, $personId, $group) { $this->qualificationDetailsMapper = $qualificationDetailsMapper; $this->personId = $personId; $this->group = $group; } public function isValid() { try { $data = QualificationDetailsMapper::mapFormDataToDto($this->data, $this->group); $this->qualificationDetailsMapper->validateQualificationDetails($this->personId, $data); } catch (ValidationException $e) { $this->validationMessages = $e->getErrors(); return false; } return true; } public function getMessages() { return $this->validationMessages; } }
mit
majiajia/blog_thinkphp
Tour/Modules/Index/Action/AboutAction.class.php
2550
<?php /** * Created by PhpStorm. * User: jiajiama * Date: 15-5-17 * Time: 下午9:03 */ class AboutAction extends Action { public function index() { $team_member_list = array(); $db_team_members = M("team_members"); $member_select = $db_team_members->limit(6)->select(); $index_member = 0; foreach($member_select as $member_select_item) { $team_member_list[$index_member]["member_pic"] = $member_select_item["avatar"]; $team_member_list[$index_member]["name"] = $member_select_item["name"]; $team_member_list[$index_member]["job_title"] = $member_select_item["title"]; $team_member_list[$index_member]["brief"] = $member_select_item["brief"]; $team_member_list[$index_member]["weibo"] = $member_select_item["weibo"]; $index_member ++; } // $team_member_list = array( // array("member_pic"=>"home-banner-phone.jpg","name"=>"John Smith","job_title"=>"CEO","brief"=>"没有简介"), // array("member_pic"=>"home-banner-phone.jpg","name"=>"John Smith","job_title"=>"CEO","brief"=>"没有简介"), // array("member_pic"=>"home-banner-phone.jpg","name"=>"John Smith","job_title"=>"CEO","brief"=>"没有简介"), // array("member_pic"=>"home-banner-phone.jpg","name"=>"John Smith","job_title"=>"CEO","brief"=>"没有简介"), // array("member_pic"=>"home-banner-phone.jpg","name"=>"John Smith","job_title"=>"CEO","brief"=>"没有简介"), // array("member_pic"=>"home-banner-phone.jpg","name"=>"John Smith","job_title"=>"CEO","brief"=>"没有简介") // ); $customers_list = array(); $db_customers = M("customers"); $customers_select = $db_customers->limit(6)->select(); $index = 0; foreach($customers_select as $customers_select_item) { $customers_list[$index]["curtomer_href"] = $customers_select_item["link"]; $customers_list[$index]["curtomer_img"] = $customers_select_item["path"]; $customers_list[$index]["title"] = $customers_select_item["name"]; $index ++; } $this->assign('title',"关于我们")-> assign("team_member_list",$team_member_list)-> assign("customers_list",$customers_list)-> assign('item_index_strategy',"1")-> assign("item_index_rent_car","2")-> assign("item_index_take_pic","3")-> assign("item_index_blog","4")-> display(); } }
mit
jiach1992/videoDemo
Model/RoleInfo.cs
689
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public class RoleInfo { public RoleInfo() { } #region Model private int _roleid; private string _rolename; /// <summary> /// /// </summary> public int RoleId { set { _roleid = value; } get { return _roleid; } } /// <summary> /// /// </summary> public string RoleName { set { _rolename = value; } get { return _rolename; } } #endregion Model } }
mit
akaraatanasov/JS-Core
JS Fundamentals/Control-Flow Logic - Lab/FruitVegetable.js
518
function fruitVegetable(word) { switch (word) { case 'banana': case 'apple': case 'kiwi': case 'cherry': case 'lemon': case 'grapes': case 'peach': console.log('fruit'); break; case 'tomato': case 'cucumber': case 'pepper': case 'onion': case 'garlic': case 'parsley': console.log('vegetable'); break; default: console.log('unknown'); } }
mit
karim/adila
database/src/main/java/adila/db/wifionly2dgms_vp742dfinlux.java
229
// This file is automatically generated. package adila.db; /* * Vestel VP74 * * DEVICE: wifionly-gms * MODEL: VP74-Finlux */ final class wifionly2dgms_vp742dfinlux { public static final String DATA = "Vestel|VP74|"; }
mit
team1389/Simulation-Ohm
Simulation-Ohm/src/simulation/drive_sim/xml/XMLShapeReader.java
4390
package simulation.drive_sim.xml; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.newdawn.slick.geom.Point; import org.newdawn.slick.geom.Polygon; import org.newdawn.slick.geom.Shape; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.team1389.util.list.AddList; import simulation.drive_sim.Alliance; import simulation.drive_sim.DriveSimulator; import simulation.drive_sim.field.AlliedBoundary; public class XMLShapeReader { Document document; File readFile; boolean filePresent; public XMLShapeReader(String fileName) { readFile = new File(fileName); try { initDocument(); } catch (Exception e) { e.printStackTrace(); } } public List<Shape> getBoundaries() { return filePresent ? getShapes("boundaries") : new ArrayList<>(); } public List<AlliedBoundary> getDropoffs() { return filePresent ? getAlliedBoundaries("dropoffs") : new ArrayList<>(); } public List<AlliedBoundary> getPickups() { return filePresent ? getAlliedBoundaries("pickups") : new ArrayList<>(); } private List<AlliedBoundary> getAlliedBoundaries(String listTag) { Node shapeListElement = document.getElementsByTagName(listTag).item(0); List<Node> shapeNodes = getShapeNodes(shapeListElement); return shapeNodes.stream().map(this::getAlliedBoundaryFromNode).collect(Collectors.toList()); } private AlliedBoundary getAlliedBoundaryFromNode(Node shapeNode) { List<Node> pointNodes = convertToList(shapeNode.getChildNodes()); List<Point> pointList = pointNodes.stream().map(this::pointFromNode).collect(Collectors.toList()); AddList<Float> pointsRaw = new AddList<>(); pointList.forEach(p -> pointsRaw.put(p.getX(), p.getY())); return new AlliedBoundary(new Polygon(convertList(pointsRaw)), getBoundaryAlliance(shapeNode)); } private Alliance getBoundaryAlliance(Node shapeNode) { return shapeNode.getAttributes().getNamedItem("alliance").getNodeValue().equals(Alliance.BLUE.name()) ? Alliance.BLUE : Alliance.RED; } private List<Shape> getShapes(String shapeListTag) { Node shapeListElement = document.getElementsByTagName(shapeListTag).item(0); List<Node> shapeNodes = getShapeNodes(shapeListElement); return shapeNodes.stream().map(this::getShapeFromNode).collect(Collectors.toList()); } private Shape getShapeFromNode(Node shapeNode) { List<Node> pointNodes = convertToList(shapeNode.getChildNodes()); List<Point> pointList = pointNodes.stream().map(this::pointFromNode).collect(Collectors.toList()); AddList<Float> pointsRaw = new AddList<>(); pointList.forEach(p -> pointsRaw.put(p.getX(), p.getY())); return new Polygon(convertList(pointsRaw)); } private float[] convertList(List<Float> floatList) { float[] floatArray = new float[floatList.size()]; int i = 0; for (Float f : floatList) { floatArray[i++] = (f != null ? f : Float.NaN); // Or whatever default you want. } return floatArray; } private Point pointFromNode(Node pointNode) { float x = Float.parseFloat(pointNode.getAttributes().getNamedItem("x").getNodeValue()) * DriveSimulator.scale; float y = Float.parseFloat(pointNode.getAttributes().getNamedItem("y").getNodeValue()) * DriveSimulator.scale; return new Point(x, y); } private List<Node> getShapeNodes(Node shapeListElement) { return convertToList(shapeListElement.getChildNodes()).stream().filter(n -> n.getNodeName().equals("shape")) .collect(Collectors.toList()); } private List<Node> convertToList(NodeList nodes) { return IntStream.range(0, nodes.getLength()).mapToObj(i -> nodes.item(i)).collect(Collectors.toList()); } private void initDocument() throws ParserConfigurationException, SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; db = dbf.newDocumentBuilder(); try { document = db.parse(readFile); filePresent = true; } catch (IOException e) { filePresent = false; // e.printStackTrace(); } } }
mit
akrherz/iem
htdocs/GIS/apps/rview/loop.php
769
<?php function printHTML($urls, $width, $height){ $urls = implode("::", $urls); return <<<EOF <form name="jsani" id="jsani" action="#" style="width: {$width}px; height: {$height}px;"> <input type="hidden" name="filenames" value="{$urls}"> <input type="hidden" name="controls" value="previous, stopplay, next, looprock, slowfast"> <input type="hidden" name="maxdwell" value="1400"> <input type="hidden" name="mindwell" value="100"> <input type="hidden" name="initdwell" value="300"> <input type="hidden" name="nsteps" value="8"> <input type="hidden" name="last_frame_pause" value="3"> <input type="hidden" name="first_frame_pause" value="2"> <input type="hidden" name="frame_pause" value="2:4,3:5"> </form> EOF; } ?>
mit
FrancoisVenter/TangentSolutionAssignment
application/resources/views/home.php
1585
<!DOCTYPE html> <html> <head> <title>ID REST</title> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="fragment" content="!"> <base href="/"> <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="css/app.css"> </head> <body data-ng-app="app"> <nav class="navbar navbar-default navbar-static-top"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu-items" aria-expanded="false"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" data-ui-sref="generate">ID REST</a> </div> <div class="collapse navbar-collapse" id="menu-items"> <ul class="nav navbar-nav"> <li data-ng-class="{active: $state.includes('generate')}"><a data-ui-sref="generate">Generate</a></li> <li data-ng-class="{active: $state.includes('validate')}"><a data-ui-sref="validate">Validate</a></li> </ul> </div> </nav> <div class="container"> <data-ui-view></data-ui-view> </div> <script src="js/index.js"></script> </body> </html>
mit
lunar-logan/trollback
src/main/java/org/inverse/Main.java
708
package org.inverse; import org.inverse.exception.QueryNotSupportedException; import org.inverse.exception.QueryParsingException; import org.inverse.service.RollbackService; /** * Created by Dell on 11-01-2017. */ public class Main { public static void main(String[] args) throws QueryParsingException, QueryNotSupportedException { String sql = "insert into t (a,b,c) values('ds','ds',5);"; RollbackService rollbackService = new RollbackService() { public String getRollbackQuery(String query) { return null; } }; String rollbackQuery = rollbackService.getRollbackQuery(sql); System.out.println(rollbackQuery); } }
mit
openxml/openxml-drawingml
spec/drawingml/elements/theme_elements_spec.rb
172
require "spec_helper" describe OpenXml::DrawingML::Elements::ThemeElements do include ElementTestMacros it_should_use tag: :themeElements, name: "theme_elements" end
mit
lukeberglund/Robots-CRUD-App
routes/robots.js
1656
var express = require('express'); var router = express.Router(); var fetch = require('node-fetch'); var baseUrl if (true == false) { baseUrl = "http://localhost:3000" } else { baseUrl = "https://southernct-443-robots-api.herokuapp.com" } /* List Robots */ router.get('/robots', function(req, res, next) { const endpointUrl = `${baseUrl}/api/robots` fetch(endpointUrl).then(function(response) { response.json().then(function(json){ console.log("LISTING ROBOTS", json.length) res.render('robots/index', {robots: json, title: "Robots List"}); }) }) }); /* NEW */ router.get('/robots/new', function(req, res, next) { res.render('robots/new', { title: "New Robot" }) }) /* Show Robot */ router.get('/robots/:id', function(req, res, next) { const robotId = req.params.id const endpointUrl = `${baseUrl}/api/robots/${robotId}` fetch(endpointUrl).then(function(response) { response.json().then(function(json){ console.log("SHOWING ROBOT", json) res.render('robots/show', { robot: json, title: `Robot ${robotId}`, requestUrl: endpointUrl }) }) }) }) /* EDIT */ router.get('/robots/:id/edit', function(req, res, next) { const robotId = req.params.id const endpointUrl = `${baseUrl}/api/robots/${robotId}` fetch(endpointUrl).then(function(response) { response.json().then(function(json){ console.log("POPULATING FORM WITH ROBOT", json) res.render('robots/edit', { robot: json, title: `Edit Robot ${robotId}`, requestUrl: endpointUrl, requestMethod: "PUT" }) }) }) }) module.exports = router;
mit
mateusmaso/underscore.prefilter
dist/underscore.prefilter.min.js
500
// underscore.prefilter // -------------------- // v0.1.2 // // Copyright (c) 2013-2015 Mateus Maso // Distributed under MIT license // // http://github.com/mateusmaso/underscore.prefilter !function(a,b){if("undefined"!=typeof exports){var c=require("underscore");"undefined"!=typeof module&&module.exports&&(module.exports=b(c)),exports=b(c)}else a._.mixin(b(a._))}(this,function(){return{prefilter:function(a,b){return function(){return b.apply(this,arguments)?a.apply(this,arguments):void 0}}}});
mit
smirfolio/rebal
install545d4d4d/class/Installer.php
44732
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Ionize * * @package Ionize * @author Ionize Dev Team * @license http://ionizecms.com/doc-license * @link http://ionizecms.com * @since Version 0.90 */ // ------------------------------------------------------------------------ /** * Ionize Installer * * @package Ionize * @subpackage Installer * @category Installer * @author Ionize Dev Team * */ class Installer { private static $instance; private $template; public $lang = array(); public $db; // -------------------------------------------------------------------- /** * Constructor * */ public function __construct() { self::$instance =& $this; // Default language $lang = 'en'; // Check GET language if (is_array($_GET) && isset($_GET['lang']) ) { if (is_file(ROOTPATH.'application/language/'.$_GET['lang'].'/install_lang.php')) $lang = $_GET['lang']; } $this->template['lang'] = $lang; // Include language file and merge it to language var include(ROOTPATH.'application/language/'. $lang .'/install_lang.php'); $this->lang = array_merge($this->lang, $lang); // Get all available translations $dirs = scandir(ROOTPATH.'application/language'); $languages = array(); foreach($dirs as $dir) { if (is_dir(ROOTPATH.'application/language/'.$dir)) { if (is_file(ROOTPATH.'application/language/'.$dir.'/install_lang.php') and strpos($dir, '.') === false) { $languages[] = $dir; } } } $this->template['languages'] = $languages; // Put the current URL to template (for language selection) $this->template['current_url'] = (isset($_GET['step'])) ? '?step='.$_GET['step'] : '?step=checkconfig'; } // -------------------------------------------------------------------- /** * Returns current instance of Installer * */ public static function &get_instance() { return self::$instance; } // -------------------------------------------------------------------- /** * Checks the config settings * */ function check_config() { // PHP version >= 5 $this->template['php_version'] = version_compare(substr(phpversion(), 0, 3), '5.0', '>='); // MySQL support $this->template['mysql_support'] = function_exists('mysql_connect'); // Safe Mode $this->template['safe_mode'] = (ini_get('safe_mode')) ? FALSE : TRUE; // Files upload $this->template['file_uploads'] = (ini_get('file_uploads')) ? TRUE : FALSE; // GD lib $this->template['gd_lib'] = function_exists('imagecreatetruecolor'); // Check files rights $files = array( 'application/config/config.php', 'application/config/database.php', 'application/config/email.php', 'application/config/language.php', 'application/config/modules.php' ); $check_files = array(); foreach($files as $file) $check_files[$file] = is_really_writable(ROOTPATH . $file); // Check folders rights $folders = array( 'application/config', 'files', 'themes' ); $check_folders = array(); foreach($folders as $folder) $check_folders[$folder] = $this->_test_dir(ROOTPATH . $folder, true); $this->template['check_files'] = $check_files; $this->template['check_folders'] = $check_folders; // Message to user if one setting is false foreach($this->template as $config) { if ( ! $config) { $this->template['next'] = false; $this->_send_error('check_config', lang('config_check_errors')); } } // Outputs the view $this->output('check_config'); } // -------------------------------------------------------------------- /** * Prints out the database form * */ function configure_database() { if ( ! isset($_POST['action'])) { $data = array('db_driver', 'db_hostname', 'db_name', 'db_username'); $this->_feed_blank_template($data); $this->output('database'); } else { $this->_save_database_settings(); } } // -------------------------------------------------------------------- /** * Prints out the user form * */ function configure_user() { // Check if an Admin user already exists in the DB $this->template['skip'] = FALSE; $this->db_connect(); $this->db->where('id_group', '1'); $query = $this->db->get('users'); if ($query->num_rows() > 0) { $this->template['skip'] = TRUE; } if ( ! isset($_POST['action'])) { // Skip TRUE and no POST = Admin user already exists if ($this->template['skip'] == TRUE) { $this->template['message_type'] = 'error'; $this->template['message'] = lang('user_info_admin_exists'); } // Prepare data $data = array('username', 'screen_name', 'email', 'encryption_key'); $this->_feed_blank_template($data); // Encryption key : check if one exists require(ROOTPATH . 'application/config/config.php'); if ($config['encryption_key'] == '') { $this->template['encryption_key'] = $this->generateEncryptKey(); } $this->output('user'); } else { $this->_save_user(); $this->db_connect(); header("Location: ".BASEURL.'install/?step=data&lang='.$this->template['lang'], TRUE, 302); } } // -------------------------------------------------------------------- /** * Installs the example datas * */ function install_data() { if ( ! isset($_POST['action'])) { $this->db_connect(); // Check if the DB was migrated : If yes, no sample data install $query = $this->db->get('page'); if ($query->num_rows() > 2) { header("Location: ".BASEURL.'install/?step=finish&lang='.$this->template['lang'], TRUE, 302); } $this->template['base_url'] = BASEURL; $this->output('data'); } else { // Install DATABASE example data require(ROOTPATH . 'application/config/database.php'); // Connect to DB $config = $db['default']; $dsn = $config['dbdriver'].'://'.$config['username'].':'.$config['password'].'@'.$config['hostname'].'/'.$config['database']; $this->db = DB($dsn, true, true); // Try connect or exit if ( ! $this->db->db_connect()) { $this->_send_error('data', lang('database_error_coud_not_connect'), $_POST); } // The database should exists, so try to connect if ( ! $this->db->db_select()) { $this->_send_error('database', lang('database_error_database_dont_exists'), $_POST); } else { $file = read_file('./database/demo_data.sql'); $requests = explode('--#--', $file); foreach($requests as $request) { $this->db->simple_query($request); } // Get languages and update the language config file $query = $this->db->get('lang'); $data = $query->result_array(); $this->_save_language_config_file($data); } /* * Install Themes example * Not yet implemented * $zip = new ZipArchive(); $res = $zip->open(ROOTPATH . 'install/example_data/themes.zip'); if ($res === true) { $zip->extractTo(ROOTPATH . 'themes/'); $zip->close(); } // http://se2.php.net/manual/en/function.exec.php // exec(command, $printed_data, $return_value); */ header("Location: ".BASEURL.'install/?step=finish&lang='.$this->template['lang'], TRUE, 302); } } // -------------------------------------------------------------------- /** * Migrate the DB if needed * No migration will be done if it is not needed, even this script is called. * */ function migrate() { $migration_files = $this->_get_migration_files(); // Migration not validated if ( ! isset($_POST['action'])) { $this->template['database_migration_text'] = ''; $this->template['button_label'] = lang('button_start_migrate'); if ( ! empty($migration_files)) { if (in_array('migration_0.9.7_0.9.9.xml', $migration_files)) $this->template['database_migration_from'] = lang('database_migration_from') . '<b class="highlight2">0.9.7</b>'; if (in_array('migration_0.9.6_0.9.7.xml', $migration_files)) $this->template['database_migration_from'] = lang('database_migration_from') . '<b class="highlight2">0.9.6</b>'; if (in_array('migration_0.9.5_0.9.6.xml', $migration_files)) $this->template['database_migration_from'] = lang('database_migration_from') . '<b class="highlight2">0.9.5</b>'; if (in_array('migration_0.9.4_0.9.5.xml', $migration_files)) $this->template['database_migration_from'] = lang('database_migration_from') . '<b class="highlight2">0.9.4</b>'; if (in_array('migration_0.93_0.9.4.xml', $migration_files)) $this->template['database_migration_from'] = lang('database_migration_from') . '<b class="highlight2">0.9.3</b>'; if (in_array('migration_0.92_0.93.xml', $migration_files)) $this->template['database_migration_from'] = lang('database_migration_from') . '<b class="highlight2">0.9.2</b>'; if (in_array('migration_0.90_0.92.xml', $migration_files)) $this->template['database_migration_from'] = lang('database_migration_from') . '<b class="highlight2">0.9.0</b>'; $this->template['database_migration_text'] = lang('database_migration_text'); } else { $this->template['button_label'] = lang('button_next_step'); $this->template['database_migration_from'] = lang('database_no_migration_needed'); } $this->output('migrate'); } else { $this->db_connect(); // Migration foreach ($migration_files as $file) { $xml = simplexml_load_file('./database/'.$file); $queries = $xml->xpath('/sql/query'); foreach ($queries as $query) { $this->db->query($query); } } // Rebuild the config/language.php file for consistency $query = $this->db->get('lang'); if ($query->num_rows() > 0) { $langs = $query->result_array(); $this->_save_language_config_file($langs); } /* * Migration to 0.9.4 * Users account migration * */ if (in_array('migration_0.93_0.9.4.xml', $migration_files)) { log_message('debug', 'Migration from 0.9.3'); $query = $this->db->get('users'); if ($query->num_rows() > 0) { foreach ($query->result_array() as $user) { if ($user['salt'] == '') { $user['salt'] = $this->get_salt(); $user['password'] = $this->_encrypt094($this->_decrypt093($user['password'], $user), $user); $this->db->where('username', $user['username']); $this->db->update('users', $user); } } } } /* * Migration to 0.9.5 * Migration to Connect Lib * */ if (in_array('migration_0.9.4_0.9.5.xml', $migration_files)) { log_message('debug', 'Migration from 0.9.5'); // Get the encryption key and move it to config/config.php $enc = false; $config = array(); if (is_file(ROOTPATH . 'application/config/access.php')) { include(ROOTPATH . 'application/config/access.php'); } if ( ! empty($config['encrypt_key']) && $config['encrypt_key'] != '') { $enc = $config['encrypt_key']; } // Write the config file and migrates users accounts if ($enc !== false) { $ret = false; $config_file = file(APPPATH . 'config/config' . EXT); $buff = ''; foreach ($config_file as $line) { if (strpos($line, "encryption_key") !== FALSE) { $line = "\$config['encryption_key'] = '".$enc."';\n"; } $buff .= $line; } if ($buff != '') $ret = @file_put_contents(APPPATH . 'config/config' . EXT, $buff); if ( ! $ret) { $this->_send_error('migrate', lang('settings_error_write_rights_config'), $_POST); } // Updates the users account $query = $this->db->get('users'); if ($query->num_rows() > 0) { foreach ($query->result_array() as $user) { $pass = $this->_decrypt094($user['password'], $user); $enc = $this->_encrypt($pass, $user); $user['password'] = $enc; $this->db->where('username', $user['username']); $this->db->update('users', $user); } } } else { $this->_send_error('user', lang('no_encryption_key_found'), $_POST); } } /* * Migration to 0.9.7 * Migration to CI2 * */ if (in_array('migration_0.9.6_0.9.7.xml', $migration_files)) { log_message('debug', 'Migration from 0.9.6'); // Updates the users account $query = $this->db->get('users'); if ($query->num_rows() > 0) { foreach ($query->result_array() as $user) { $old_decoded_pass = $this->_decrypt096($user['password'], $user); $encoded_pass = $this->_encrypt($old_decoded_pass, $user); $user['password'] = $encoded_pass; $this->db->where('username', $user['username']); $this->db->update('users', $user); } } } /* * Migration to 0.9.9 * Put url_mode to 'short' */ if (in_array('migration_0.9.7_0.9.9.xml', $migration_files)) { log_message('debug', 'Migration from 0.9.7'); require_once('./class/Config.php'); // Save version $conf = new ION_Config(APPPATH.'config/', 'ionize.php'); $conf->set_config('url_mode', 'short'); $conf->save(); } /* * Migration to 1.0 * Coming soon... * */ if (in_array('migration_0.9.9_1.0.xml', $migration_files)) { log_message('debug', 'Migration from 0.9.9'); } header("Location: ".BASEURL.'install/?step=user&lang='.$this->template['lang'], TRUE, 302); } } function migrate_users_to_ci2() { $this->db_connect(); // Updates the users account $query = $this->db->get('users'); if ($query->num_rows() > 0) { foreach ($query->result_array() as $user) { $old_decoded_pass = $this->_decrypt096($user['password'], $user); $encoded_pass = $this->_encrypt($old_decoded_pass, $user); $user['password'] = $encoded_pass; $this->db->where('username', $user['username']); $this->db->update('users', $user); echo($user['username'] . ' : ' . 'done<br/>'); } } } function show_password() { $this->db_connect(); // Updates the users account $query = $this->db->get('users'); if ($query->num_rows() > 0) { foreach ($query->result_array() as $user) { $decoded_pass = $this->_decrypt($user['password'], $user); var_dump($decoded_pass); } } } // -------------------------------------------------------------------- /** * Saves the website default settings * - Default lang * * */ function settings() { if ( ! isset($_POST['action'])) { $this->template['lang_code'] = 'en'; $this->template['lang_name'] = 'english'; $this->template['admin_url'] = 'admin'; $this->output('settings'); } else { $ret = $this->_save_settings(); if ($ret) { header("Location: ".BASEURL.'install/?step=user&lang='.$this->template['lang'], TRUE, 302); } else { $this->_send_error('settings', lang('settings_error_write_rights'), $_POST); } } } // -------------------------------------------------------------------- /** * Finish installation * */ function finish() { // Get the Language config file include(APPPATH.'config/language.php'); $this->db_connect(); /* * Create base content : 404 * if no 404 in the DB */ $this->db->where('name', '404'); $query = $this->db->get('page'); if ($query->num_rows() == 0) { // 404 page $data = array( 'id_menu' => '2', 'name' => '404', 'online' => '1', 'appears' => '0' ); $this->db->insert('page', $data); $id_page_404 = $this->db->insert_id(); // 404 article $data = array( 'name' => '404' ); $this->db->insert('article', $data); $id_article_404 = $this->db->insert_id(); // 404 article link to 404 page $data = array( 'id_page' => $id_page_404, 'id_article' => $id_article_404, 'online' => '1' ); $this->db->insert('page_article', $data); // 404 article lang data $langs = array_keys($config['available_languages']); foreach ($langs as $lang) { // 404 lang page $data = array( 'id_page' => $id_page_404, 'lang' => $lang, 'url' => '404', 'title' => '404' ); $this->db->insert('page_lang', $data); // 404 lang article $data = array( 'id_article' => $id_article_404, 'lang' => $lang, 'url' => '404', 'title' => '404', 'content' => '<p>The content you asked was not found !</p>' ); $this->db->insert('article_lang', $data); } } // Default minimal welcome page $this->db->where('id_menu', '1'); $query = $this->db->get('page'); if ($query->num_rows() == 0) { // Welcome page $data = array( 'id_menu' => '1', 'name' => 'welcome', 'online' => '1', 'appears' => '1', 'home' => '1', 'level' => '0' ); $this->db->insert('page', $data); $id_page = $this->db->insert_id(); // Welcome article $data = array( 'name' => 'welcome' ); $this->db->insert('article', $data); $id_article = $this->db->insert_id(); // Article link to page $data = array( 'id_page' => $id_page, 'id_article' => $id_article, 'online' => '1' ); $this->db->insert('page_article', $data); // Article lang data $langs = array_keys($config['available_languages']); foreach ($langs as $lang) { // Lang page $data = array( 'id_page' => $id_page, 'lang' => $lang, 'url' => 'welcome-url', 'title' => 'Welcome' ); $this->db->insert('page_lang', $data); // Lang article $data = array( 'id_article' => $id_article, 'lang' => $lang, 'url' => 'welcome-article-url', 'title' => 'Welcome to Ionize', 'url' => 'welcome-article-url', 'content' => '<p>For more information about building a website with Ionize, you can:</p> <ul><li>Download & read <a href="http://www.ionizecms.com">the Documentation</a></li><li>Visit <a href="http://www.ionizecms.com/forum">the Community Forum</a></li></ul><p>Have fun !</p>' ); $this->db->insert('article_lang', $data); } } // Default settings $langs = array_keys($config['available_languages']); foreach ($langs as $lang) { $this->db->where(array('lang' => $lang, 'name' => 'site_title')); $query = $this->db->get('setting'); if ($query->num_rows() == 0) { // Settings $data = array( 'name' => 'site_title', 'lang' => $lang, 'content' => 'My website' ); $this->db->insert('setting', $data); } } // VERSION /* require_once('./class/Config.php'); // Save version $conf = new ION_Config(APPPATH.'config/', 'ionize.php'); $conf->set_config('version', VERSION); if ($conf->save() == FALSE) { $this->_send_error('settings', lang('settings_error_write_rights_config'), $_POST); } */ $this->template['base_url'] = BASEURL; $this->output('finish'); } // -------------------------------------------------------------------- /** * Saves database settings * */ function _save_database_settings() { $fields = array('db_driver', 'db_hostname', 'db_name', 'db_username'); // Migration ? If yes, it will be set to true before the installer try to create the tables $this_is_a_migration = FALSE; // Post data $data = array(); // Check each mandatory POST data foreach ($fields as $key) { if (isset($_POST[$key])) { $val = $_POST[$key]; // Break if $val == '' if ($val == '') { $this->_send_error('database', lang('database_error_missing_settings'), $_POST); } if ( ! get_magic_quotes_gpc()) $val = addslashes($val); $data[$key] = trim($val); } } // Try connect or exit if ( ! $this->_db_connect($data)) { $this->_send_error('database', lang('database_error_coud_not_connect'), $_POST); } /* * If database don't exists, create it ! * */ if ( ! $this->db->db_select()) { // Loads CI DB Forge class require_once(BASEPATH.'database/DB_forge'.EXT); require_once(BASEPATH.'database/drivers/'.$this->db->dbdriver.'/'.$this->db->dbdriver.'_forge'.EXT); $class = 'CI_DB_'.$this->db->dbdriver.'_forge'; $this->dbforge = new $class(); if ( ! $this->dbforge->create_database($data['db_name'])) { $this->_send_error('database', lang('database_error_coud_not_create_database'), $_POST); } else { // Put information about database creation to view $this->template['database_created'] = lang('database_created'); $this->template['database_name'] = $data['db_name']; } } /* * Select database, save database config file and launch SQL table creation script * */ // The database should exists, so try to connect if ( ! $this->db->db_select()) { $this->_send_error('database', lang('database_error_database_dont_exists'), $_POST); } else { // Everything's OK, save config/database.php if ( ! $this->_save_database_settings_to_file($data)) { $this->_send_error('database', lang('database_error_writing_config_file'), $_POST); } // Check if one Ionize table already exists. If yes, this is a migration if ($this->db->table_exists('setting') == true) { $this_is_a_migration = TRUE; } // Load database XML script $xml = simplexml_load_file('./database/database.xml'); // Get tables & content $tables = $xml->xpath('/sql/tables/query'); $content = $xml->xpath('/sql/content/query'); // Create tables // In case of migration, this script will only create the missing tables foreach ($tables as $table) { $this->db->query($table); } // Checks the write rights of the MySQL user // by insertion of dummy data in the settings table if ($this->db->query("INSERT INTO setting ('name', 'content') values('test', 'test')")) { $this->_send_error('database', lang('database_error_coud_not_write_database'), $_POST); } else { $this->db->query("DELETE FROM setting WHERE name='test'"); } /* * Base content insert * In case of migration (content already exists), the existing content will not be overwritten * */ foreach ($content as $sql) { $this->db->query($sql); } // Users message $this->template['database_installation_message'] = lang('database_success_install'); } /** * Check for migration and redirect * */ $migration_files = $this->_get_migration_files(); if ( ! empty($migration_files)) { header("Location: ".BASEURL.'install/?step=migrate&lang='.$this->template['lang'], TRUE, 302); } else { // If the installer just created the tables go to the Settings panel if ($this_is_a_migration == FALSE) { header("Location: ".BASEURL.'install/?step=settings&lang='.$this->template['lang'], TRUE, 302); } // Else, go to the user creation step else { header("Location: ".BASEURL.'install/?step=user&lang='.$this->template['lang'], TRUE, 302); } } } // -------------------------------------------------------------------- /** * Saves the user informations * */ function _save_user() { // Config library require_once('./class/Config.php'); /* * Saves the new encryption key * */ if ( !empty($_POST['encryption_key']) && strlen($_POST['encryption_key']) > 31) { include(APPPATH.'config/config.php'); include(APPPATH.'config/connect.php'); if ($config['encryption_key'] == '') { $conf = new ION_Config(APPPATH.'config/', 'config.php'); $conf->set_config('encryption_key', $_POST['encryption_key']); if ($conf->save() == FALSE) { $this->_send_error('user', lang('settings_error_write_rights_config'), $_POST); } } } /* * Saves the users data * */ $fields = array('username', 'screen_name', 'email', 'password', 'password2'); // Post data $data = array(); // Check each mandatory POST data foreach ($fields as $key) { if (isset($_POST[$key])) { $val = $_POST[$key]; // Exit if $val == '' if ($val == '') { $this->_send_error('user', lang('user_error_missing_settings'), $_POST); } // Exit if username or password < 4 chars if (($key == 'username' OR $key == 'password') && strlen($val) < 4) { $this->_send_error('user', lang('user_error_not_enough_char'), $_POST); } if ( ! get_magic_quotes_gpc()) $val = addslashes($val); $data[$key] = trim($val); } } // Check email if ( ! valid_email($data['email']) ) { $this->_send_error('user', lang('user_error_email_not_valid'), $_POST); } // Check password if ( ! ($data['password'] == $data['password2']) ) { $this->_send_error('user', lang('user_error_passwords_not_equal'), $_POST); } // Here is everything OK, we can create the user $data['join_date'] = date('Y-m-d H:i:s'); $data['salt'] = $this->get_salt(); $data['password'] = $this->_encrypt($data['password'], $data); $data['id_group'] = '1'; // Clean data array unset($data['password2']); // DB save $this->db_connect(); // Check if the user exists $this->db->where('username', $data['username']); $query = $this->db->get('users'); if ($query->num_rows() > 0) { // updates the user $this->db->where('username', $data['username']); $this->db->update('users', $data); } else { // insert the user $this->db->insert('users', $data); } } // -------------------------------------------------------------------- /** * Saves the website settings * */ function _save_settings() { // Config library require_once('./class/Config.php'); // Check if data are empty if (empty($_POST['lang_code'])) { $this->_send_error('settings', lang('settings_error_missing_lang_code'), $_POST);} if (empty($_POST['lang_name'])) { $this->_send_error('settings', lang('settings_error_missing_lang_name'), $_POST);} // Lang code must be on 2 chars if (strlen($_POST['lang_code']) > 3) { $this->_send_error('settings', lang('settings_error_lang_code_2_chars'), $_POST);} // Check if admin URL is correct if ( ! preg_match("/^([a-z0-9])+$/i", $_POST['admin_url']) OR (empty($_POST['admin_url'])) ) { $this->_send_error('settings', lang('settings_error_admin_url'), $_POST);} // Save the Admin URL $conf = new ION_Config(APPPATH.'config/', 'config.php'); $conf->set_config('admin_url', $_POST['admin_url']); if ($conf->save() == FALSE) { $this->_send_error('settings', lang('settings_error_write_rights_config'), $_POST); } // DB save $this->db_connect(); $data = array( 'lang' => $_POST['lang_code'], 'name' => $_POST['lang_name'], 'online' => '1', 'def' => '1', 'ordering' => '1' ); // Check if the lang exists $this->db->where('lang', $_POST['lang_code']); $query = $this->db->get('lang'); if ($query->num_rows() > 0) { // updates the lang $this->db->where('lang', $_POST['lang_code']); $this->db->update('lang', $data); } else { // insert the lang $this->db->insert('lang', $data); } $data = array(0 => $data); return $this->_save_language_config_file($data); } // -------------------------------------------------------------------- /** * Outputs the view * */ function output($_view) { GLOBAL $config; if (!isset($this->template['next'])) {$this->template['next'] = true; } $this->template['version'] = $config['version']; extract($this->template); include('./views/header.php'); include('./views/' . $_view . '.php'); include('./views/footer.php'); } // -------------------------------------------------------------------- /** * Generates a random salt value. * * @return String Hash value * **/ function get_salt() { require('../application/config/connect.php'); return substr(md5(uniqid(rand(), true)), 0, $config['salt_length']); } // -------------------------------------------------------------------- /** * Get one translation * */ public function get_translation($line) { return (isset($this->lang[$line])) ? $this->lang[$line] : '#'.$line ; } // -------------------------------------------------------------------- /** * Connects to the DB with the database.php config file * */ function db_connect() { include(APPPATH.'config/database'.EXT); $this->db = DB('default', true); $this->db->db_connect(); $this->db->db_select(); } // -------------------------------------------------------------------- /** * Check needed migration and returns a migration array containing the XML files to execute. * */ function _get_migration_files() { // Array of XML migration files $migration_xml = array(); $this->db_connect(); // Try to get one table fields data : If not possible, the table doesn't exist : // The database doesn't contains correct tables -> error ! if (($test = $this->db->query('select count(1) from setting')) != false) { /* * From Ionize 0.90 or 0.91 * page_lang does not contains the 'online' field * */ $migrate_from = true; $fields = $this->db->field_data('page_lang'); foreach ($fields as $field) { if ($field->name == 'online') { $migrate_from = false; } } if ($migrate_from == true) { $migration_xml[] = 'migration_0.90_0.92.xml'; $migration_xml[] = 'migration_0.92_0.93.xml'; $migration_xml[] = 'migration_0.93_0.9.4.xml'; $migration_xml[] = 'migration_0.9.4_0.9.5.xml'; $migration_xml[] = 'migration_0.9.5_0.9.6.xml'; $migration_xml[] = 'migration_0.9.6_0.9.7.xml'; $migration_xml[] = 'migration_0.9.7_0.9.9.xml'; } /* * From Ionize 0.92 * The 'extend_field' table does not contains the 'value' field * If it contains this field, we are already in a 0.93 verion, so no migration * If the 'migration_xml' array isn't empty, we migrate from an earlier version, so no need to make this test * */ if (empty($migration_xml)) { $migrate_from = true; $fields = $this->db->field_data('extend_field'); foreach ($fields as $field) { if ($field->name == 'value') { $migrate_from = false; } } if ($migrate_from == true) { $migration_xml[] = 'migration_0.92_0.93.xml'; $migration_xml[] = 'migration_0.93_0.9.4.xml'; $migration_xml[] = 'migration_0.9.4_0.9.5.xml'; $migration_xml[] = 'migration_0.9.5_0.9.6.xml'; $migration_xml[] = 'migration_0.9.6_0.9.7.xml'; $migration_xml[] = 'migration_0.9.7_0.9.9.xml'; } } /* * From Ionize 0.93 * if the 'users' table field 'join_date' has the TIMESTAMP type, we will migrate the accounts. * If the 'migration_xml' array isn't empty, we migrate from an earlier version, so no need to make this test * */ if (empty($migration_xml)) { $migrate_from = true; $fields = $this->db->field_data('users'); foreach ($fields as $field) { if ($field->name == 'salt') $migrate_from = false; } if ($migrate_from == true) { $migration_xml[] = 'migration_0.93_0.9.4.xml'; $migration_xml[] = 'migration_0.9.4_0.9.5.xml'; $migration_xml[] = 'migration_0.9.5_0.9.6.xml'; $migration_xml[] = 'migration_0.9.6_0.9.7.xml'; $migration_xml[] = 'migration_0.9.7_0.9.9.xml'; } } /* * From Ionize 0.9.4 : the users.id_user field does not exists * */ if (empty($migration_xml)) { $migrate_from = false; $fields = $this->db->field_data('users'); foreach ($fields as $field) { if ($field->name == 'user_PK') $migrate_from = true; } if ($migrate_from == true) { $migration_xml[] = 'migration_0.9.4_0.9.5.xml'; $migration_xml[] = 'migration_0.9.5_0.9.6.xml'; $migration_xml[] = 'migration_0.9.6_0.9.7.xml'; $migration_xml[] = 'migration_0.9.7_0.9.9.xml'; } } /* * From Ionize 0.9.5 : the table article hasn't the 'flag' field * */ if (empty($migration_xml)) { $migrate_from = true; $fields = $this->db->field_data('article'); foreach ($fields as $field) { if ($field->name == 'flag') $migrate_from = false; } if ($migrate_from == true) { $migration_xml[] = 'migration_0.9.5_0.9.6.xml'; $migration_xml[] = 'migration_0.9.6_0.9.7.xml'; $migration_xml[] = 'migration_0.9.7_0.9.9.xml'; } } /* * From Ionize 0.9.6 : the table extend_field does not contains the field id_element_definition * */ if (empty($migration_xml)) { $migrate_from = true; $fields = $this->db->field_data('extend_field'); foreach ($fields as $field) { if ($field->name == 'id_element_definition') $migrate_from = false; } if ($migrate_from == true) { $migration_xml[] = 'migration_0.9.6_0.9.7.xml'; $migration_xml[] = 'migration_0.9.7_0.9.9.xml'; } } /* * From 0.9.7 * * */ if (empty($migration_xml)) { $version = $this->db->query("select content from setting where name='ionize_version'")->row_array(); $version = isset($version['content']) ? $version['content'] : ''; $version = str_replace('.', '', $version); if (intval($version) <= 97) { $migration_xml[] = 'migration_0.9.7_0.9.9.xml'; } } } return $migration_xml; } // -------------------------------------------------------------------- /** * Tests if a dir is writable * * @param string folder path to test * @param boolean if true, check all directories recursively * * @return boolean true if every tested dir is writable, false if one is not writable * */ function _test_dir($dir, $recursive = false) { if ( ! is_really_writable($dir) OR !$dh = opendir($dir)) return false; if ($recursive) { while (($file = readdir($dh)) !== false) if (@filetype($dir.$file) == 'dir' && $file != '.' && $file != '..') if (!$this->_test_dir($dir.$file, true)) return false; } closedir($dh); return true; } // -------------------------------------------------------------------- /** * Tests if a file is writable * * @param Mixed folder path to test * @param boolean if true, check all directories recursively * * @return boolean true if every tested dir is writable, false if one is not writable * */ function _test_file($files) { $return = array(); foreach ($files as $file) { if ( ! is_really_writable($file)) return false; } return true; } // -------------------------------------------------------------------- /** * Try to connect to the DB * */ function _db_connect($data) { // $dsn = 'dbdriver://username:password@hostname/database'; $dsn = $data['db_driver'].'://'.$data['db_username'].':'.$_POST['db_password'].'@'.$data['db_hostname'].'/'.$data['db_name']; $this->db = DB($dsn, true, true); return $this->db->db_connect(); } // -------------------------------------------------------------------- /** * Feed the templates data with blank values * @param array Array of key to fill */ function _feed_blank_template($data) { foreach($data as $key) { $this->template[$key] = ''; } } // -------------------------------------------------------------------- /** * Feed the templates data with provided values * @param array Array of key to fill */ function _feed_template($data) { foreach($data as $key => $value) { $this->template[$key] = $value; } } // -------------------------------------------------------------------- /** * Creates an error message and displays the submitted view * @param string View name * @param string Error message content * @param array Data to feed to form. Optional. */ function _send_error($view, $msg, $data = array()) { $this->template['message_type'] = 'error'; $this->template['message'] = $msg; if ( !empty($data)) { $this->_feed_template($data); } $this->output($view); exit(); } // -------------------------------------------------------------------- /** * Saves database settings to config/database.php file * */ function _save_database_settings_to_file($data) { // Files begin $conf = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n\n"; $conf .= "\$active_group = 'default';\n"; $conf .= "\$active_record = TRUE;\n\n"; $conf .= "\$db['default']['hostname'] = '".$data['db_hostname']."';\n"; $conf .= "\$db['default']['username'] = '".$data['db_username']."';\n"; $conf .= "\$db['default']['password'] = '".$_POST['db_password']."';\n"; $conf .= "\$db['default']['database'] = '".$data['db_name']."';\n"; $conf .= "\$db['default']['dbdriver'] = '".$data['db_driver']."';\n"; $conf .= "\$db['default']['dbprefix'] = '';\n"; $conf .= "\$db['default']['swap_pre'] = '';\n"; $conf .= "\$db['default']['pconnect'] = TRUE;\n"; $conf .= "\$db['default']['db_debug'] = FALSE;\n"; $conf .= "\$db['default']['cache_on'] = FALSE;\n"; $conf .= "\$db['default']['cachedir'] = '';\n"; $conf .= "\$db['default']['char_set'] = 'utf8';\n"; $conf .= "\$db['default']['dbcollat'] = 'utf8_unicode_ci';\n"; // files end $conf .= "\n"; $conf .= '/* End of file database.php */'."\n"; $conf .= '/* Auto generated by Installer on '. date('Y.m.d H:i:s') .' */'."\n"; $conf .= '/* Location: ./application/config/database.php */'."\n"; return @file_put_contents(APPPATH . '/config/database' . EXT, $conf); } function _save_language_config_file($data) { // Default language $def_lang = ''; // Available / Online languages array $available_languages = array(); $online_languages = array(); foreach($data as $l) { // Set defualt lang code if ($l['def'] == '1') $def_lang = $l['lang']; $available_languages[$l['lang']] = $l['name']; if($l['online'] == '1') $online_languages[$l['lang']] = $l['name']; } // Language file save $conf = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n\n"; $conf .='/*'."\n"; $conf .='| -------------------------------------------------------------------'."\n"; $conf .='| IONIZE LANGUAGES'."\n"; $conf .='| -------------------------------------------------------------------'."\n"; $conf .='| Contains the available languages definitions for the front-end.'."\n"; $conf .='| Auto-generated by Ionizes Language administration.'."\n"; $conf .='| Changes made in this file will be overwritten by languages save in Ionize.'."\n"; $conf .='|'."\n"; $conf .='|'."\n"; $conf .='*/'."\n\n"; $conf .= "// Default admin language code\n"; $conf .= "\$config['default_admin_lang'] = 'en';\n\n"; $conf .= "// Default language code\n"; $conf .= "// This code depends on the language defined through the Ionize admin panel\n"; $conf .= "// and will never change during the request process \n"; $conf .= "\$config['default_lang_code'] = '".$def_lang."';\n\n"; $conf .= "// Used language code\n"; $conf .= "// Dynamically changed by the Router depending on the browser, cookie or asked URL\n"; $conf .= "// By default, Ionize set it to the default lang code.\n"; $conf .= "\$config['detected_lang_code'] = '".$def_lang."';\n\n"; $conf .= "// Available languages\n"; $conf .= "// Languages set through Ionize. Includes offline languages\n"; $conf .= "\$config['available_languages'] = ".dump_variable($available_languages)."\n\n"; $conf .= "// Online languages\n"; $conf .= "// Languages set online through Ionize.\n"; $conf .= "\$config['online_languages'] = ".dump_variable($online_languages)."\n\n"; // files end $conf .= "\n\n"; $conf .= '/* End of file language.php */'."\n"; $conf .= '/* Auto generated by Ionize Installer on : '.date('Y.m.d H:i:s').' */'."\n"; $conf .= '/* Location: ./application/config/language.php */'."\n"; return @file_put_contents(APPPATH . 'config/language' . EXT, $conf); } // -------------------------------------------------------------------- /** * Encrypts one password, based on the encrypt key set in config/connect.php * * @param string Password to encrypt * @param array User data array * @return string Encrypted password * */ function _encrypt094($str, $data) { // Get the Access lib config file include(APPPATH.'config/access.php'); $hash = sha1($data['username'] . $data['salt']); $key = sha1($config['encrypt_key'] . $hash); return base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, substr($key, 0, 56), $str, MCRYPT_MODE_CFB, substr($config['encrypt_key'], 0, 8))); } // -------------------------------------------------------------------- function _decrypt($str, $data) { require_once('./class/Encrypt.php'); include(APPPATH.'config/config.php'); $encrypt = new ION_Encrypt($config); $hash = $encrypt->sha1($data['username'] . $data['salt']); $key = $encrypt->sha1($config['encryption_key'] . $hash); return $encrypt->decode($str, substr($key, 0, 56)); } function _decrypt096($str, $data) { require_once('./class/Encrypt.php'); include(APPPATH.'config/config.php'); $encrypt = new ION_Encrypt($config); $hash = $encrypt->sha1($data['username'] . $data['salt']); $key = $encrypt->sha1($config['encryption_key'] . $hash); return $encrypt->old_decode($str, substr($key, 0, 56)); } /** * Encrypts one password, based on the encrypt key set in config/connect.php * * @param string Password to encrypt * @param array User data array * @return string Encrypted password * */ function _encrypt($str, $data) { require_once('./class/Encrypt.php'); include(APPPATH.'config/config.php'); $encrypt = new ION_Encrypt($config); $hash = $encrypt->sha1($data['username'] . $data['salt']); $key = $encrypt->sha1($config['encryption_key'] . $hash); return $encrypt->encode($str, substr($key, 0, 56)); } // -------------------------------------------------------------------- function _decrypt094($str, $data) { // Get the Access lib config file include(APPPATH.'config/config.php'); $hash = sha1($data['username'] . $data['salt']); $key = sha1($config['encryption_key'] . $hash); return mcrypt_decrypt(MCRYPT_BLOWFISH, substr($key, 0, 56), base64_decode($str), MCRYPT_MODE_CFB, substr($config['encryption_key'], 0, 8)); } // -------------------------------------------------------------------- function _decrypt093($str, $data) { // Get the Access lib config file include(APPPATH.'config/access.php'); $hash = sha1($data['username'] . $data['join_date']); $key = sha1($config['encrypt_key'] . $hash); return mcrypt_decrypt(MCRYPT_BLOWFISH, substr($key, 0, 56), base64_decode($str), MCRYPT_MODE_CFB, substr($config['encrypt_key'], 0, 8)); } // -------------------------------------------------------------------- function generateEncryptKey($size=32) { $vowels = 'aeiouyAEIOUY'; $consonants = 'bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ1234567890@#$!()'; $key = ''; $alt = time() % 2; for ($i = 0; $i < $size; $i++) { if ($alt == 1) { $key .= $consonants[(rand() % strlen($consonants))]; $alt = 0; } else { $key .= $vowels[(rand() % strlen($vowels))]; $alt = 1; } } return $key; } } function &get_instance() { return Installer::get_instance(); } /** * Dumps the content of a variable into correct PHP. * * Attention! * Cannot handle objects! * * Usage: * <code> * $str = '$variable = ' . dump_variable($variable); * </code> * * @param mixed * @param int * @return string */ function dump_variable($data, $indent = 0) { $ind = str_repeat("\t", $indent); $str = ''; switch(gettype($data)) { case 'boolean': $str .= $data ? 'true' : 'false'; break; case 'integer': case 'double': $str .= $data; break; case 'string': $str .= "'". addcslashes($data, '\'\\') . "'"; break; case 'array': $str .= "array(\n"; $t = array(); foreach($data as $k => $v) { $s = ''; if( ! is_numeric($k)) { $s .= $ind . "\t'".addcslashes($k, '\'\\')."' => "; } $s .= dump_variable($v, $indent + 1); $t[] = $s; } $str .= implode(",\n", $t) . "\n" . $ind . "\t)"; break; default: $str .= 'NULL'; } return $str . ($indent ? '' : ';'); }
mit
Anovative/Nop39
Libraries/Nop.Core/Domain/Vendors/Vendor.cs
2829
using System.Collections.Generic; using Nop.Core.Domain.Localization; using Nop.Core.Domain.Seo; namespace Nop.Core.Domain.Vendors { /// <summary> /// Represents a vendor /// </summary> public partial class Vendor : BaseEntity, ILocalizedEntity, ISlugSupported { private ICollection<VendorNote> _vendorNotes; /// <summary> /// Gets or sets the name /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the email /// </summary> public string Email { get; set; } /// <summary> /// Gets or sets the description /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets the picture identifier /// </summary> public int PictureId { get; set; } /// <summary> /// Gets or sets the address identifier /// </summary> public int AddressId { get; set; } /// <summary> /// Gets or sets the admin comment /// </summary> public string AdminComment { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity is active /// </summary> public bool Active { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity has been deleted /// </summary> public bool Deleted { get; set; } /// <summary> /// Gets or sets the display order /// </summary> public int DisplayOrder { get; set; } /// <summary> /// Gets or sets the meta keywords /// </summary> public string MetaKeywords { get; set; } /// <summary> /// Gets or sets the meta description /// </summary> public string MetaDescription { get; set; } /// <summary> /// Gets or sets the meta title /// </summary> public string MetaTitle { get; set; } /// <summary> /// Gets or sets the page size /// </summary> public int PageSize { get; set; } /// <summary> /// Gets or sets a value indicating whether customers can select the page size /// </summary> public bool AllowCustomersToSelectPageSize { get; set; } /// <summary> /// Gets or sets the available customer selectable page size options /// </summary> public string PageSizeOptions { get; set; } /// <summary> /// Gets or sets vendor notes /// </summary> public virtual ICollection<VendorNote> VendorNotes { get { return _vendorNotes ?? (_vendorNotes = new List<VendorNote>()); } protected set { _vendorNotes = value; } } } }
mit
anephenix/yo-socketstream
app/generator.js
2224
module.exports = function (context) { // Generate directories and files for the app var directories = [ 'client', 'client/code', 'client/code/app', 'client/code/libs', 'client/css', 'client/css/libs', 'client/static', 'client/static/images', 'client/templates', 'client/views', 'server', 'server/middleware', 'server/rpc' ]; var filesToCopyAsIs = [ 'client/code/libs/jquery.min.js', 'client/static/favicon.ico', 'client/static/images/logo.png', 'client/templates/.gitkeep', 'server/middleware/.gitkeep', 'server/rpc/.gitkeep', 'README.md' ]; directories.forEach(function (directory) { context.mkdir(directory); }); filesToCopyAsIs.forEach(function (file) { context.copy(file, file); }); // Keep a record of what choices the developer made, // so that we can use those to generate the directories // and files based on their choices var scriptChoice = context.coffee ? 'coffee' : 'js'; var demoChoice = context.demo ? 'demo' : 'minimal'; var templateChoice = context.jade ? 'jade' : 'html'; // Generate the rest of the files and directories based on the // choices of the developer context.copy('client/code/app/app.'+demoChoice+'.'+scriptChoice , 'client/code/app/app.'+scriptChoice); context.copy('client/views/app.'+demoChoice+'.'+templateChoice , 'client/views/app.'+templateChoice); context.copy('client/css/app.'+demoChoice+'.styl' , 'client/css/app.styl'); context.copy('client/code/app/entry.'+scriptChoice , 'client/code/app/entry.'+scriptChoice); context.copy('server/middleware/example.'+scriptChoice , 'server/middleware/example.'+scriptChoice); if (context.demo) { // generate extra files for the app containing the demo example context.copy('server/rpc/demo.'+scriptChoice , 'server/rpc/demo.'+scriptChoice); context.mkdir('client/templates/chat'); context.copy('client/templates/chat/message.'+templateChoice , 'client/templates/chat/message.'+templateChoice); context.copy('client/css/libs/reset.css' , 'client/css/libs/reset.css'); } }
mit
concord-consortium/portal-report
js/selectors/report-tree.js
7891
import { createSelector } from "reselect"; import Immutable, { Map } from "immutable"; import { getViewType, FULL_REPORT, DASHBOARD, PORTAL_DASHBOARD } from "../util/misc"; // `getSequenceTree` generates tree that is consumed by React components from reportState (ImmutableJS Map). // Redux state has flat structure. This selector maps all the IDs and keys and creates a tree-like hierarchy. // It includes all the properties provided by API + calculates a few additional ones. // Inputs const getSequences = state => state.getIn(["report", "sequences"]); const getActivities = state => state.getIn(["report", "activities"]); const getPages = state => state.getIn(["report", "pages"]); const getSections = state => state.getIn(["report", "sections"]); const getQuestions = state => state.getIn(["report", "questions"]); const getAnswers = state => state.getIn(["report", "answers"]); const getStudents = state => state.getIn(["report", "students"]); const getHideSectionNames = state => state.getIn(["report", "hideSectionNames"]); const getShowFeaturedQuestionsOnly = state => state.getIn(["report", "showFeaturedQuestionsOnly"]); // Helpers // Why isn't this helper used by React components directly? So we don't have to care about view type here? // The problem is that if all the questions on given page are not visible, page should not be visible too. // If all the pages are not visible, then section is not visible too. And the same thing applies to activities. // It's convenient to calculate all that here while building a report tree. const isQuestionVisible = (question, featuredOnly) => { const viewType = getViewType(); // Custom question filtering is currently supported only by regular, non-dashboard report. // There are no checkboxes and controls in dashboard. if (viewType === FULL_REPORT && question.get("hiddenByUser")) { return false; } // Only dashboard is considered to be "featured question report". In the future, when there's a toggle // letting user switch `showFeaturedQuestionsOnly` on and off, this might not be the case anymore. // Note that === false check is explicit and it's like that by design. If API does not provide this property // (so the value is undefined or null), assume that the question is visible in the featured question report. // It's necessary so this report works before Portal (API) is updated to provide this flag. Later, it will be // less important. Additionally, for now we assume that the newer portal-dashboard follows the same logic. if (((viewType === DASHBOARD) || (viewType === PORTAL_DASHBOARD)) && featuredOnly && question.get("showInFeaturedQuestionReport") === false) { return false; } return true; }; // Selectors export const getAnswerTrees = createSelector( [ getAnswers, getStudents, getQuestions], (answers, students, questions) => { return answers // Filter out answers that are not matching any students in the class. Class could have been updated. // Also, filter out answers that are not matching any question. It might happen if the activity gets updated and // some questions are deleted. .filter(answer => students.has(answer.get("platformUserId")) && questions.has(answer.get("questionId"))) .map(answer => { if (answer.get("type") === "multiple_choice_answer") { const question = questions.get(answer.get("questionId")); // `|| []` => in case question doesn't have choices. const choices = Map((question.get("choices") || []).map(c => [c.get("id"), c])); const selectedChoices = answer.getIn(["answer", "choiceIds"]) .map(id => choices.get(id) || Map({content: "[the selected choice has been deleted by question author]", correct: false, id: -1})); const selectedCorrectChoices = selectedChoices.filter(c => c.get("correct")); answer = answer .set("scored", question.get("scored")) .set("selectedChoices", selectedChoices) .set("correct", selectedChoices.size > 0 && selectedChoices.size === selectedCorrectChoices.size); } return answer .set("student", students.get(answer.get("platformUserId"))); }); } ); export const getAnswersByQuestion = createSelector( [ getAnswerTrees, getStudents, getQuestions], (answers, students, questions) => { // Use withMutations so this isn't creating a lot of new objects const answerTreeResult = Map().withMutations(mutableTree => { // Create tree like: // { question1.id: {student1.id: answer1, student2.id: answer2, ...}, // question2.id: {student3.id: answer3, student4.id: answer4, ...} // ... } return answers.reduce((answerTree, answer) => { const questionId = answer.get("questionId"); let studentMap = answerTree.get(questionId) || Map(); studentMap = studentMap.set(answer.get("platformUserId"), answer); return answerTree.set(questionId, studentMap); }, mutableTree); }); return answerTreeResult; } ); export const getQuestionTrees = createSelector( [ getActivities, getSections, getPages, getQuestions, getShowFeaturedQuestionsOnly ], ( activities, sections, pages, questions, showFeaturedQuestionsOnly) => { return (questions || Immutable.fromJS({})).map(question => question // This is only a temporal solution. Answers should no longer be added to a report tree. // Components that need answer content should become containers and request answers from redux state. .set("answers", Immutable.fromJS([])) .set("visible", isQuestionVisible(question, showFeaturedQuestionsOnly)) ); }, ); export const getPageTrees = createSelector( [ getPages, getQuestionTrees ], (pages, questionTrees) => pages.map(page => { const mappedChildren = page.get("children").map(key => questionTrees.get(key)); return page .set("children", mappedChildren) // Page is visible only if at least one question is visible. .set("visible", !!mappedChildren.find(q => q.get("visible"))); }) ); export const getSectionTrees = createSelector( [ getSections, getPageTrees, getHideSectionNames ], (sections, pageTrees, hideSectionNames) => sections.map(section => { const mappedChildren = section.get("children").map(id => pageTrees.get(id.toString())); return section .set("children", mappedChildren) // Section is visible only if at least one page is visible. .set("visible", !!mappedChildren.find(p => p.get("visible"))) // Hide section titles for external activities. .set("nameHidden", hideSectionNames); }), ); export const getActivityTrees = createSelector( [ getActivities, getSectionTrees ], (activities, sectionTrees) => activities.map(activity => { const mappedChildren = activity.get("children").map(id => sectionTrees.get(id.toString())); // Calculate additional properties, flattened pages and questions. const pages = mappedChildren.map(section => section.get("children")).flatten(1); const questions = pages.map(page => page.get("children")).flatten(1); return activity .set("children", mappedChildren) .set("pages", pages) .set("questions", questions) // Activity is visible only if at least one section is visible. .set("visible", !!mappedChildren.find(s => s.get("visible"))); }), ); export const getSequenceTree = createSelector( [ getSequences, getActivityTrees ], (sequences, activityTrees) => { // There is always only one sequence. const sequence = sequences.values().next().value; const mappedChildren = sequence.get("children").map(id => activityTrees.get(id.toString())); return sequence .set("children", mappedChildren); }, ); export default getSequenceTree;
mit
devGomgbo/stockvalue
app/cache/dev/twig/b/8/b817507167aa45caac41e7a6ff7932152e6b33fa0d064934a028da1f65ae7aac.php
7007
<?php /* OroFilterBundle:Js:embedded_templates.js.twig */ class __TwigTemplate_b817507167aa45caac41e7a6ff7932152e6b33fa0d064934a028da1f65ae7aac extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $__internal_75a19091c62e614f6a6cb31beb19ac985450731fb1175be92a08026cfe50c649 = $this->env->getExtension("native_profiler"); $__internal_75a19091c62e614f6a6cb31beb19ac985450731fb1175be92a08026cfe50c649->enter($__internal_75a19091c62e614f6a6cb31beb19ac985450731fb1175be92a08026cfe50c649_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "OroFilterBundle:Js:embedded_templates.js.twig")); // line 1 echo "<script type=\"text/template\" id=\"none-filter-template-embedded\"> </script> <script type=\"text/template\" id=\"text-filter-template-embedded\"> <input type=\"text\" name=\"value\" value=\"\"/> </script> <script type=\"text/template\" id=\"choice-filter-template-embedded\"> <span> <%= _.__('oro.filter.embedded.choice.field_to_value') %> </span> <div class=\"dropdown\"> <a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\"><%- selectedChoiceLabel %></a>: <ul class=\"dropdown-menu\"> <% _.each(choices, function (option) { %> <li<% if (selectedChoice == option.value) { %> class=\"active\"<% } %>> <a class=\"choice-value\" href=\"#\" data-value=\"<%= option.value %>\"><%- option.label %></a> </li> <% }); %> </ul> <input type=\"text\" name=\"value\" value=\"<%- value %>\"> <input class=\"name_input\" type=\"hidden\" name=\"<%= name %>\" id=\"<%= name %>\" value=\"<%- selectedChoice %>\"/> </div> </script> <script type=\"text/template\" id=\"simple-choice-filter-template-embedded\"> <div class=\"dropdown\"> <a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\"><%- selectedChoiceLabel %></a> <ul class=\"dropdown-menu\"> <% _.each(choices, function (option) { %> <li<% if (selectedChoice == option.value) { %> class=\"active\"<% } %>> <a class=\"choice-value\" href=\"#\" data-value=\"<%= option.value %>\"><%- option.label %></a> </li> <% }); %> </ul> <input class=\"name_input\" type=\"hidden\" name=\"<%= name %>\" id=\"<%= name %>\" value=\"<%- selectedChoice %>\"/> </div> </script> <script type=\"text/template\" id=\"many-to-many-filter-template-embedded\"> <span> <%= _.__('oro.filter.embedded.choice.field_to_value') %> </span> <div class=\"dropdown\"> <a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\"><%- selectedChoiceLabel %></a>: <ul class=\"dropdown-menu\"> <% _.each(choices, function (option) { %> <li<% if (selectedChoice == option.value) { %> class=\"active\"<% } %>> <a class=\"choice-value\" href=\"#\" data-value=\"<%= option.value %>\"><%- option.label %></a> </li> <% }); %> </ul> <input class=\"name_input\" type=\"hidden\" name=\"<%= name %>\" id=\"<%= name %>\" value=\"<%- selectedChoice %>\"/> </div> </script> <script type=\"text/template\" id=\"select-field-template-embedded\"> <div class=\"dropdown\"> <% if (choices.length > 1) { %> <a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\"><%= selectedChoiceLabel %></a> <% } else { %> <span><%= selectedChoiceLabel %></span> <% } %> <ul class=\"dropdown-menu\"> <% _.each(choices, function (option) { %> <li<% if (selectedChoice == option.value) { %> class=\"active\"<% } %>> <a class=\"choice-value\" href=\"#\" data-value=\"<%= option.value %>\"><%= option.label %></a> </li> <% }); %> </ul> <select name=\"<%= name %>\" class=\"filter-select-oro name_input\" style=\"display:none\"> <% _.each(choices, function (option) { %> <option value=\"<%= option.value %>\"<% if (option.value == selectedChoice) { %> selected=\"selected\"<% } %>><%- option.label %></option> <% }); %> </select> </div> </script> <script type=\"text/template\" id=\"date-filter-template-embedded\"> <span> <%= _.__('oro.filter.embedded.date.field_to_value') %> </span> <%= parts.join('') %>: <div /> <div class=\"filter-start-date\"> <input type=\"text\" class=\"<%= inputClass %>\" value=\"<%- value.value.start %>\" name=\"start\" placeholder=\"<%- _.__('from') %>\"> </div> <span class=\"filter-separator\">-</span> <div class=\"filter-end-date\"> <input type=\"text\" class=\"<%= inputClass %>\" value=\"<%- value.value.end %>\" name=\"end\" placeholder=\"<%- _.__('to') %>\"> </div> </script> <script type=\"text/template\" id=\"select-filter-template-embedded\"> <div class=\"filter-item\"> <span> <%= _.__('oro.filter.embedded.select.field_to_value') %> </span> <div class=\"filter-select filter-criteria-selector\"> <select> <% _.each(options, function (option) { %> <option value=\"<%= option.value %>\" title=\"<%- option.label %>\" <% if (option.value == selected.value) { %> selected=\"selected\"<% } %>> <%- option.label %> </option> <% }); %> </select> </div> </div> </script> <script type=\"text/template\" id=\"multiselect-filter-template-embedded\"> <div class=\"filter-item\"> <span> <%= _.__('oro.filter.embedded.select.field_to_value') %> </span> <div class=\"filter-select filter-criteria-selector\"> <select multiple> <% _.each(options, function (option) { %> <option value=\"<%= option.value %>\" title=\"<%- option.label %>\" <% if (_.isArray(selected.value)) { %><% if (_.indexOf(selected.value, option.value) !== -1) { %> selected=\"selected\"<% } %> <% } else if (option.value == selected.value) { %> selected=\"selected\"<% } %>> <%- option.label %> </option> <% }); %> </select> </div> </div> </script> "; $__internal_75a19091c62e614f6a6cb31beb19ac985450731fb1175be92a08026cfe50c649->leave($__internal_75a19091c62e614f6a6cb31beb19ac985450731fb1175be92a08026cfe50c649_prof); } public function getTemplateName() { return "OroFilterBundle:Js:embedded_templates.js.twig"; } public function getDebugInfo() { return array ( 22 => 1,); } }
mit
metamarcdw/PyBitmessage-I2P
src/class_receiveDataThread.py
39916
doTimingAttackMitigation = True import time import threading import shared import hashlib from i2p import socket import random from struct import unpack, pack import sys import traceback #import string #from subprocess import call # used when the API must execute an outside program #from pyelliptic.openssl import OpenSSL #import highlevelcrypto from addresses import * from helper_generic import addDataPadding from helper_sql import sqlQuery from debug import logger # This thread is created either by the synSenderThread(for outgoing # connections) or the singleListenerThread(for incoming connections). class receiveDataThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.data = '' self.verackSent = False self.verackReceived = False def setup( self, sock, DEST, streamNumber, someObjectsOfWhichThisRemoteNodeIsAlreadyAware, selfInitiatedConnections, sendDataThreadQueue): self.sock = sock self.peer = shared.Peer(DEST) self.streamNumber = streamNumber self.objectsThatWeHaveYetToGetFromThisPeer = {} self.selfInitiatedConnections = selfInitiatedConnections self.sendDataThreadQueue = sendDataThreadQueue # used to send commands and data to the sendDataThread shared.connectedHostsList[ self.peer.dest] = 0 # The very fact that this receiveData thread exists shows that we are connected to the remote host. Let's add it to this list so that an outgoingSynSender thread doesn't try to connect to it. self.connectionIsOrWasFullyEstablished = False # set to true after the remote node and I accept each other's version messages. This is needed to allow the user interface to accurately reflect the current number of connections. if self.streamNumber == -1: # This was an incoming connection. Send out a version message if we accept the other node's version message. self.initiatedConnection = False else: self.initiatedConnection = True self.selfInitiatedConnections[streamNumber][self] = 0 self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware def run(self): with shared.printLock: print 'receiveDataThread starting. ID', str(id(self)) + '. The size of the shared.connectedHostsList is now', len(shared.connectedHostsList) while True: if shared.config.getint('bitmessagesettings', 'maxdownloadrate') == 0: downloadRateLimitBytes = float("inf") else: downloadRateLimitBytes = shared.config.getint('bitmessagesettings', 'maxdownloadrate') * 1000 with shared.receiveDataLock: while shared.numberOfBytesReceivedLastSecond >= downloadRateLimitBytes: if int(time.time()) == shared.lastTimeWeResetBytesReceived: # If it's still the same second that it was last time then sleep. time.sleep(0.3) else: # It's a new second. Let us clear the shared.numberOfBytesReceivedLastSecond. shared.lastTimeWeResetBytesReceived = int(time.time()) shared.numberOfBytesReceivedLastSecond = 0 dataLen = len(self.data) try: dataRecv = self.sock.recv(1024) self.data += dataRecv shared.numberOfBytesReceived += len(dataRecv) # for the 'network status' UI tab. The UI clears this value whenever it updates. shared.numberOfBytesReceivedLastSecond += len(dataRecv) # for the download rate limit except socket.Timeout: with shared.printLock: print 'Timeout occurred waiting for data from', self.peer, '. Closing receiveData thread. (ID:', str(id(self)) + ')' break except Exception as err: with shared.printLock: print 'sock.recv error. Closing receiveData thread (' + str(self.peer) + ', Thread ID:', str(id(self)) + ').', err break # print 'Received', repr(self.data) if len(self.data) == dataLen: # If self.sock.recv returned no data: with shared.printLock: print 'Connection to', self.peer, 'closed. Closing receiveData thread. (ID:', str(id(self)) + ')' break else: self.processData() try: del self.selfInitiatedConnections[self.streamNumber][self] with shared.printLock: print 'removed self (a receiveDataThread) from selfInitiatedConnections' except: pass self.sendDataThreadQueue.put((0, 'shutdown','no data')) # commands the corresponding sendDataThread to shut itself down. try: del shared.connectedHostsList[self.peer.dest] except Exception as err: with shared.printLock: print 'Could not delete', self.peer.dest, 'from shared.connectedHostsList.', err try: del shared.numberOfObjectsThatWeHaveYetToGetPerPeer[ self.peer] except: pass shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) with shared.printLock: print 'receiveDataThread ending. ID', str(id(self)) + '. The size of the shared.connectedHostsList is now', len(shared.connectedHostsList) def processData(self): if len(self.data) < shared.Header.size: # if so little of the data has arrived that we can't even read the checksum then wait for more data. return magic,command,payloadLength,checksum = shared.Header.unpack(self.data[:shared.Header.size]) if magic != 0xE9BEB4D9: self.data = "" return if payloadLength > 1600100: # ~1.6 MB which is the maximum possible size of an inv message. logger.info('The incoming message, which we have not yet download, is too large. Ignoring it. (unfortunately there is no way to tell the other node to stop sending it except to disconnect.) Message size: %s' % payloadLength) self.data = self.data[payloadLength + shared.Header.size:] del magic,command,payloadLength,checksum # we don't need these anymore and better to clean them now before the recursive call rather than after self.processData() return if len(self.data) < payloadLength + shared.Header.size: # check if the whole message has arrived yet. return payload = self.data[shared.Header.size:payloadLength + shared.Header.size] if checksum != hashlib.sha512(payload).digest()[0:4]: # test the checksum in the message. print 'Checksum incorrect. Clearing this message.' self.data = self.data[payloadLength + shared.Header.size:] del magic,command,payloadLength,checksum,payload # better to clean up before the recursive call self.processData() return # The time we've last seen this node is obviously right now since we # just received valid data from it. So update the knownNodes list so # that other peers can be made aware of its existance. if self.initiatedConnection and self.connectionIsOrWasFullyEstablished: # The remote port is only something we should share with others if it is the remote node's incoming port (rather than some random operating-system-assigned outgoing port). with shared.knownNodesLock: shared.knownNodes[self.streamNumber][self.peer] = int(time.time()) #Strip the nulls command = command.rstrip('\x00') with shared.printLock: print 'remoteCommand', repr(command), ' from', self.peer try: #TODO: Use a dispatcher here if command == 'error': self.recerror(payload) elif not self.connectionIsOrWasFullyEstablished: if command == 'version': self.recversion(payload) elif command == 'verack': self.recverack() else: if command == 'addr': self.recaddr(payload) elif command == 'inv': self.recinv(payload) elif command == 'getdata': self.recgetdata(payload) elif command == 'object': self.recobject(payload) elif command == 'ping': self.sendpong(payload) #elif command == 'pong': # pass except varintDecodeError as e: logger.debug("There was a problem with a varint while processing a message from the wire. Some details: %s" % e) except Exception as e: logger.critical("Critical error in a receiveDataThread: \n%s" % traceback.format_exc()) del payload self.data = self.data[payloadLength + shared.Header.size:] # take this message out and then process the next message if self.data == '': # if there are no more messages while len(self.objectsThatWeHaveYetToGetFromThisPeer) > 0: shared.numberOfInventoryLookupsPerformed += 1 objectHash, = random.sample( self.objectsThatWeHaveYetToGetFromThisPeer, 1) if objectHash in shared.inventory: with shared.printLock: print 'Inventory (in memory) already has object listed in inv message.' del self.objectsThatWeHaveYetToGetFromThisPeer[ objectHash] elif shared.isInSqlInventory(objectHash): if shared.verbose >= 3: with shared.printLock: print 'Inventory (SQL on disk) already has object listed in inv message.' del self.objectsThatWeHaveYetToGetFromThisPeer[ objectHash] else: # We don't have the object in our inventory. Let's request it. self.sendgetdata(objectHash) del self.objectsThatWeHaveYetToGetFromThisPeer[ objectHash] # It is possible that the remote node might not respond with the object. In that case, we'll very likely get it from someone else anyway. if len(self.objectsThatWeHaveYetToGetFromThisPeer) == 0: with shared.printLock: print '(concerning', str(self.peer) + ')', 'number of objectsThatWeHaveYetToGetFromThisPeer is now 0' try: del shared.numberOfObjectsThatWeHaveYetToGetPerPeer[ self.peer] # this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together. except: pass break if len(self.objectsThatWeHaveYetToGetFromThisPeer) == 0: # We had objectsThatWeHaveYetToGetFromThisPeer but the loop ran, they were all in our inventory, and now we don't have any to get anymore. with shared.printLock: print '(concerning', str(self.peer) + ')', 'number of objectsThatWeHaveYetToGetFromThisPeer is now 0' try: del shared.numberOfObjectsThatWeHaveYetToGetPerPeer[ self.peer] # this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together. except: pass if len(self.objectsThatWeHaveYetToGetFromThisPeer) > 0: with shared.printLock: print '(concerning', str(self.peer) + ')', 'number of objectsThatWeHaveYetToGetFromThisPeer is now', len(self.objectsThatWeHaveYetToGetFromThisPeer) shared.numberOfObjectsThatWeHaveYetToGetPerPeer[self.peer] = len( self.objectsThatWeHaveYetToGetFromThisPeer) # this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together. self.processData() def sendpong(self): with shared.printLock: print 'Sending pong' self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('pong'))) def recverack(self): with shared.printLock: print 'verack received' self.verackReceived = True if self.verackSent: # We have thus both sent and received a verack. self.connectionFullyEstablished() def connectionFullyEstablished(self): if self.connectionIsOrWasFullyEstablished: # there is no reason to run this function a second time return self.connectionIsOrWasFullyEstablished = True # Command the corresponding sendDataThread to set its own connectionIsOrWasFullyEstablished variable to True also self.sendDataThreadQueue.put((0, 'connectionIsOrWasFullyEstablished', 'no data')) if not self.initiatedConnection: shared.clientHasReceivedIncomingConnections = True shared.UISignalQueue.put(('setStatusIcon', 'green')) self.sock.settimeout( 600) # We'll send out a pong every 5 minutes to make sure the connection stays alive if there has been no other traffic to send lately. shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) with shared.printLock: print 'Connection fully established with', self.peer print 'The size of the connectedHostsList is now', len(shared.connectedHostsList) print 'The length of sendDataQueues is now:', len(shared.sendDataQueues) print 'broadcasting addr from within connectionFullyEstablished function.' # Let all of our peers know about this new node. dataToSend = (int(time.time()), self.streamNumber, 1, self.peer.dest) shared.broadcastToSendDataQueues(( self.streamNumber, 'advertisepeer', dataToSend)) self.sendaddr() # This is one large addr message to this one peer. if not self.initiatedConnection and len(shared.connectedHostsList) > 200: with shared.printLock: print 'We are connected to too many people. Closing connection.' self.sendDataThreadQueue.put((0, 'shutdown','no data')) return self.sendBigInv() def sendBigInv(self): # Select all hashes for objects in this stream. queryreturn = sqlQuery( '''SELECT hash FROM inventory WHERE expirestime>? and streamnumber=?''', int(time.time()), self.streamNumber) bigInvList = {} for row in queryreturn: hash, = row if hash not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: bigInvList[hash] = 0 # We also have messages in our inventory in memory (which is a python # dictionary). Let's fetch those too. with shared.inventoryLock: for hash, storedValue in shared.inventory.items(): if hash not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: objectType, streamNumber, payload, expiresTime, tag = storedValue if streamNumber == self.streamNumber and expiresTime > int(time.time()): bigInvList[hash] = 0 numberOfObjectsInInvMessage = 0 payload = '' # Now let us start appending all of these hashes together. They will be # sent out in a big inv message to our new peer. for hash, storedValue in bigInvList.items(): payload += hash numberOfObjectsInInvMessage += 1 if numberOfObjectsInInvMessage == 50000: # We can only send a max of 50000 items per inv message but we may have more objects to advertise. They must be split up into multiple inv messages. self.sendinvMessageToJustThisOnePeer( numberOfObjectsInInvMessage, payload) payload = '' numberOfObjectsInInvMessage = 0 if numberOfObjectsInInvMessage > 0: self.sendinvMessageToJustThisOnePeer( numberOfObjectsInInvMessage, payload) # Used to send a big inv message when the connection with a node is # first fully established. Notice that there is also a broadcastinv # function for broadcasting invs to everyone in our stream. def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload): payload = encodeVarint(numberOfObjects) + payload with shared.printLock: print 'Sending huge inv message with', numberOfObjects, 'objects to just this one peer' self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('inv', payload))) def _sleepForTimingAttackMitigation(self, sleepTime): # We don't need to do the timing attack mitigation if we are # only connected to the trusted peer because we can trust the # peer not to attack if sleepTime > 0 and doTimingAttackMitigation and shared.trustedPeer == None: with shared.printLock: print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' time.sleep(sleepTime) def recerror(self, data): """ The remote node has been polite enough to send you an error message. """ fatalStatus, readPosition = decodeVarint(data[:10]) banTime, banTimeLength = decodeVarint(data[readPosition:readPosition+10]) readPosition += banTimeLength inventoryVectorLength, inventoryVectorLengthLength = decodeVarint(data[readPosition:readPosition+10]) if inventoryVectorLength > 100: return readPosition += inventoryVectorLengthLength inventoryVector = data[readPosition:readPosition+inventoryVectorLength] readPosition += inventoryVectorLength errorTextLength, errorTextLengthLength = decodeVarint(data[readPosition:readPosition+10]) if errorTextLength > 1000: return readPosition += errorTextLengthLength errorText = data[readPosition:readPosition+errorTextLength] if fatalStatus == 0: fatalHumanFriendly = 'Warning' elif fatalStatus == 1: fatalHumanFriendly = 'Error' elif fatalStatus == 2: fatalHumanFriendly = 'Fatal' message = '%s message received from %s: %s.' % (fatalHumanFriendly, self.peer, errorText) if inventoryVector: message += " This concerns object %s" % inventoryVector.encode('hex') if banTime > 0: message += " Remote node says that the ban time is %s" % banTime logger.error(message) def recobject(self, data): self.messageProcessingStartTime = time.time() lengthOfTimeWeShouldUseToProcessThisMessage = shared.checkAndShareObjectWithPeers(data) """ Sleeping will help guarantee that we can process messages faster than a remote node can send them. If we fall behind, the attacker could observe that we are are slowing down the rate at which we request objects from the network which would indicate that we own a particular address (whichever one to which they are sending all of their attack messages). Note that if an attacker connects to a target with many connections, this mitigation mechanism might not be sufficient. """ sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - (time.time() - self.messageProcessingStartTime) self._sleepForTimingAttackMitigation(sleepTime) # We have received an inv message def recinv(self, data): totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers = 0 # this counts duplicates separately because they take up memory if len(shared.numberOfObjectsThatWeHaveYetToGetPerPeer) > 0: for key, value in shared.numberOfObjectsThatWeHaveYetToGetPerPeer.items(): totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers += value with shared.printLock: print 'number of keys(hosts) in shared.numberOfObjectsThatWeHaveYetToGetPerPeer:', len(shared.numberOfObjectsThatWeHaveYetToGetPerPeer) print 'totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers = ', totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers numberOfItemsInInv, lengthOfVarint = decodeVarint(data[:10]) if numberOfItemsInInv > 50000: sys.stderr.write('Too many items in inv message!') return if len(data) < lengthOfVarint + (numberOfItemsInInv * 32): print 'inv message doesn\'t contain enough data. Ignoring.' return if numberOfItemsInInv == 1: # we'll just request this data from the person who advertised the object. if totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers > 200000 and len(self.objectsThatWeHaveYetToGetFromThisPeer) > 1000: # inv flooding attack mitigation with shared.printLock: print 'We already have', totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers, 'items yet to retrieve from peers and over 1000 from this node in particular. Ignoring this inv message.' return self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware[ data[lengthOfVarint:32 + lengthOfVarint]] = 0 shared.numberOfInventoryLookupsPerformed += 1 if data[lengthOfVarint:32 + lengthOfVarint] in shared.inventory: with shared.printLock: print 'Inventory (in memory) has inventory item already.' elif shared.isInSqlInventory(data[lengthOfVarint:32 + lengthOfVarint]): print 'Inventory (SQL on disk) has inventory item already.' else: self.sendgetdata(data[lengthOfVarint:32 + lengthOfVarint]) else: # There are many items listed in this inv message. Let us create a # 'set' of objects we are aware of and a set of objects in this inv # message so that we can diff one from the other cheaply. startTime = time.time() advertisedSet = set() for i in range(numberOfItemsInInv): advertisedSet.add(data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]) objectsNewToMe = advertisedSet - shared.inventorySets[self.streamNumber] logger.info('inv message lists %s objects. Of those %s are new to me. It took %s seconds to figure that out.', numberOfItemsInInv, len(objectsNewToMe), time.time()-startTime) for item in objectsNewToMe: if totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers > 200000 and len(self.objectsThatWeHaveYetToGetFromThisPeer) > 1000: # inv flooding attack mitigation with shared.printLock: print 'We already have', totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers, 'items yet to retrieve from peers and over', len(self.objectsThatWeHaveYetToGetFromThisPeer), 'from this node in particular. Ignoring the rest of this inv message.' break self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware[item] = 0 # helps us keep from sending inv messages to peers that already know about the objects listed therein self.objectsThatWeHaveYetToGetFromThisPeer[item] = 0 # upon finishing dealing with an incoming message, the receiveDataThread will request a random object of from peer out of this data structure. This way if we get multiple inv messages from multiple peers which list mostly the same objects, we will make getdata requests for different random objects from the various peers. if len(self.objectsThatWeHaveYetToGetFromThisPeer) > 0: shared.numberOfObjectsThatWeHaveYetToGetPerPeer[ self.peer] = len(self.objectsThatWeHaveYetToGetFromThisPeer) # Send a getdata message to our peer to request the object with the given # hash def sendgetdata(self, hash): with shared.printLock: print 'sending getdata to retrieve object with hash:', hash.encode('hex') payload = '\x01' + hash self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('getdata', payload))) # We have received a getdata request from our peer def recgetdata(self, data): numberOfRequestedInventoryItems, lengthOfVarint = decodeVarint( data[:10]) if len(data) < lengthOfVarint + (32 * numberOfRequestedInventoryItems): print 'getdata message does not contain enough data. Ignoring.' return for i in xrange(numberOfRequestedInventoryItems): hash = data[lengthOfVarint + ( i * 32):32 + lengthOfVarint + (i * 32)] with shared.printLock: print 'received getdata request for item:', hash.encode('hex') shared.numberOfInventoryLookupsPerformed += 1 shared.inventoryLock.acquire() if hash in shared.inventory: objectType, streamNumber, payload, expiresTime, tag = shared.inventory[hash] shared.inventoryLock.release() self.sendObject(payload) else: shared.inventoryLock.release() queryreturn = sqlQuery( '''select payload from inventory where hash=? and expirestime>=?''', hash, int(time.time())) if queryreturn != []: for row in queryreturn: payload, = row self.sendObject(payload) else: logger.warning('%s asked for an object with a getdata which is not in either our memory inventory or our SQL inventory. We probably cleaned it out after advertising it but before they got around to asking for it.' % (self.peer,)) # Our peer has requested (in a getdata message) that we send an object. def sendObject(self, payload): with shared.printLock: print 'sending an object.' self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('object',payload))) # We have received an addr message. def recaddr(self, data): numberOfAddressesIncluded, lengthOfNumberOfAddresses = decodeVarint( data[:10]) if shared.verbose >= 1: with shared.printLock: print 'addr message contains', numberOfAddressesIncluded, 'IP addresses.' if numberOfAddressesIncluded > 1000 or numberOfAddressesIncluded == 0: return if len(data) != lengthOfNumberOfAddresses + (536 * numberOfAddressesIncluded): print 'addr message does not contain the correct amount of data. Ignoring.' return for i in range(0, numberOfAddressesIncluded): fullDest = data[20 + lengthOfNumberOfAddresses + (536 * i):536 + lengthOfNumberOfAddresses + (536 * i)] recaddrStream, = unpack('>I', data[8 + lengthOfNumberOfAddresses + ( 536 * i):12 + lengthOfNumberOfAddresses + (536 * i)]) if recaddrStream == 0: continue if recaddrStream != self.streamNumber and recaddrStream != (self.streamNumber * 2) and recaddrStream != ((self.streamNumber * 2) + 1): # if the embedded stream number is not in my stream or either of my child streams then ignore it. Someone might be trying funny business. continue recaddrServices, = unpack('>Q', data[12 + lengthOfNumberOfAddresses + ( 536 * i):20 + lengthOfNumberOfAddresses + (536 * i)]) timeSomeoneElseReceivedMessageFromThisNode, = unpack('>Q', data[lengthOfNumberOfAddresses + ( 536 * i):8 + lengthOfNumberOfAddresses + (536 * i)]) # This is the 'time' value in the received addr message. 64-bit. if recaddrStream not in shared.knownNodes: # knownNodes is a dictionary of dictionaries with one outer dictionary for each stream. If the outer stream dictionary doesn't exist yet then we must make it. with shared.knownNodesLock: shared.knownNodes[recaddrStream] = {} peerFromAddrMessage = shared.Peer(fullDest) if peerFromAddrMessage not in shared.knownNodes[recaddrStream]: if len(shared.knownNodes[recaddrStream]) < 20000 and timeSomeoneElseReceivedMessageFromThisNode > (int(time.time()) - 10800) and timeSomeoneElseReceivedMessageFromThisNode < (int(time.time()) + 10800): # If we have more than 20000 nodes in our list already then just forget about adding more. Also, make sure that the time that someone else received a message from this node is within three hours from now. with shared.knownNodesLock: shared.knownNodes[recaddrStream][peerFromAddrMessage] = timeSomeoneElseReceivedMessageFromThisNode with shared.printLock: print 'added new node', peerFromAddrMessage, 'to knownNodes in stream', recaddrStream shared.needToWriteKnownNodesToDisk = True hostDetails = ( timeSomeoneElseReceivedMessageFromThisNode, recaddrStream, recaddrServices, fullDest) shared.broadcastToSendDataQueues(( self.streamNumber, 'advertisepeer', hostDetails)) else: timeLastReceivedMessageFromThisNode = shared.knownNodes[recaddrStream][ peerFromAddrMessage] if (timeLastReceivedMessageFromThisNode < timeSomeoneElseReceivedMessageFromThisNode) and (timeSomeoneElseReceivedMessageFromThisNode < int(time.time())+900): # 900 seconds for wiggle-room in case other nodes' clocks aren't quite right. with shared.knownNodesLock: shared.knownNodes[recaddrStream][peerFromAddrMessage] = timeSomeoneElseReceivedMessageFromThisNode with shared.printLock: print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' # Send a huge addr message to our peer. This is only used # when we fully establish a connection with a # peer (with the full exchange of version and verack # messages). def sendaddr(self): addrsInMyStream = {} addrsInChildStreamLeft = {} addrsInChildStreamRight = {} # print 'knownNodes', shared.knownNodes # We are going to share a maximum number of 1000 addrs with our peer. # 500 from this stream, 250 from the left child stream, and 250 from # the right child stream. with shared.knownNodesLock: if len(shared.knownNodes[self.streamNumber]) > 0: for i in range(500): peer, = random.sample(shared.knownNodes[self.streamNumber], 1) addrsInMyStream[peer] = shared.knownNodes[ self.streamNumber][peer] if len(shared.knownNodes[self.streamNumber * 2]) > 0: for i in range(250): peer, = random.sample(shared.knownNodes[ self.streamNumber * 2], 1) addrsInChildStreamLeft[peer] = shared.knownNodes[ self.streamNumber * 2][peer] if len(shared.knownNodes[(self.streamNumber * 2) + 1]) > 0: for i in range(250): peer, = random.sample(shared.knownNodes[ (self.streamNumber * 2) + 1], 1) addrsInChildStreamRight[peer] = shared.knownNodes[ (self.streamNumber * 2) + 1][peer] numberOfAddressesInAddrMessage = 0 payload = '' # print 'addrsInMyStream.items()', addrsInMyStream.items() for PEER, value in addrsInMyStream.items(): timeLastReceivedMessageFromThisNode = value if timeLastReceivedMessageFromThisNode > (int(time.time()) - shared.maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. numberOfAddressesInAddrMessage += 1 payload += pack( '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time payload += pack('>I', self.streamNumber) payload += pack( '>q', 1) # service bit flags offered by this node payload += PEER.dest for PEER, value in addrsInChildStreamLeft.items(): timeLastReceivedMessageFromThisNode = value if timeLastReceivedMessageFromThisNode > (int(time.time()) - shared.maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. numberOfAddressesInAddrMessage += 1 payload += pack( '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time payload += pack('>I', self.streamNumber * 2) payload += pack( '>q', 1) # service bit flags offered by this node payload += PEER.dest for PEER, value in addrsInChildStreamRight.items(): timeLastReceivedMessageFromThisNode = value if timeLastReceivedMessageFromThisNode > (int(time.time()) - shared.maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. numberOfAddressesInAddrMessage += 1 payload += pack( '>Q', timeLastReceivedMessageFromThisNode) # 64-bit time payload += pack('>I', (self.streamNumber * 2) + 1) payload += pack( '>q', 1) # service bit flags offered by this node payload += PEER.dest payload = encodeVarint(numberOfAddressesInAddrMessage) + payload self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('addr', payload))) # We have received a version message def recversion(self, data): if len(data) < 83: # This version message is unreasonably short. Forget it. return if self.verackSent: """ We must have already processed the remote node's version message. There might be a time in the future when we Do want to process a new version message, like if the remote node wants to update the streams in which they are interested. But for now we'll ignore this version message """ return self.remoteProtocolVersion, = unpack('>L', data[:4]) if self.remoteProtocolVersion < 3: self.sendDataThreadQueue.put((0, 'shutdown','no data')) with shared.printLock: print 'Closing connection to old protocol version', self.remoteProtocolVersion, 'node: ', self.peer return timestamp, = unpack('>Q', data[12:20]) timeOffset = timestamp - int(time.time()) if timeOffset > 3600: self.sendDataThreadQueue.put((0, 'sendRawData', shared.assembleErrorMessage(fatal=2, errorText="Your time is too far in the future compared to mine. Closing connection."))) logger.info("%s's time is too far in the future (%s seconds). Closing connection to it." % (self.peer, timeOffset)) time.sleep(2) self.sendDataThreadQueue.put((0, 'shutdown','no data')) return if timeOffset < -3600: self.sendDataThreadQueue.put((0, 'sendRawData', shared.assembleErrorMessage(fatal=2, errorText="Your time is too far in the past compared to mine. Closing connection."))) logger.info("%s's time is too far in the past (timeOffset %s seconds). Closing connection to it." % (self.peer, timeOffset)) time.sleep(2) self.sendDataThreadQueue.put((0, 'shutdown','no data')) return self.myExternalDest = data[28:544] useragentLength, lengthOfUseragentVarint = decodeVarint( data[1076:1080]) readPosition = 1076 + lengthOfUseragentVarint useragent = data[readPosition:readPosition + useragentLength] readPosition += useragentLength numberOfStreamsInVersionMessage, lengthOfNumberOfStreamsInVersionMessage = decodeVarint( data[readPosition:]) readPosition += lengthOfNumberOfStreamsInVersionMessage self.streamNumber, lengthOfRemoteStreamNumber = decodeVarint( data[readPosition:]) with shared.printLock: print 'Remote node useragent:', useragent, ' stream number:', self.streamNumber, ' time offset:', timeOffset, 'seconds.' if self.streamNumber != 1: self.sendDataThreadQueue.put((0, 'shutdown','no data')) with shared.printLock: print 'Closed connection to', self.peer, 'because they are interested in stream', self.streamNumber, '.' return shared.connectedHostsList[ self.peer.dest] = 1 # We use this data structure to not only keep track of what hosts we are connected to so that we don't try to connect to them again, but also to list the connections count on the Network Status tab. # If this was an incoming connection, then the sendDataThread # doesn't know the stream. We have to set it. if not self.initiatedConnection: self.sendDataThreadQueue.put((0, 'setStreamNumber', self.streamNumber)) if data[1068:1076] == shared.eightBytesOfRandomDataUsedToDetectConnectionsToSelf: self.sendDataThreadQueue.put((0, 'shutdown','no data')) with shared.printLock: print 'Closing connection to myself: ', self.peer return # The other peer's protocol version is of interest to the sendDataThread but we learn of it # in this version message. Let us inform the sendDataThread. self.sendDataThreadQueue.put((0, 'setRemoteProtocolVersion', self.remoteProtocolVersion)) with shared.knownNodesLock: shared.knownNodes[self.streamNumber][shared.Peer(self.peer.dest)] = int(time.time()) shared.needToWriteKnownNodesToDisk = True self.sendverack() if self.initiatedConnection == False: self.sendversion() # Sends a version message def sendversion(self): with shared.printLock: print 'Sending version message' self.sendDataThreadQueue.put((0, 'sendRawData', shared.assembleVersionMessage( self.peer.dest, self.streamNumber))) # Sends a verack message def sendverack(self): with shared.printLock: print 'Sending verack' self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('verack'))) self.verackSent = True if self.verackReceived: self.connectionFullyEstablished()
mit
ShowingCloud/Cancri
app/controllers/competitions_controller.rb
28499
class CompetitionsController < ApplicationController before_action :authenticate_user!, except: [:index, :show, :invite, :events, :apply_process] before_action :set_competition, only: [:show] def index host_year = params[:host_year] competitions = Competition.where.not(status: 0); false if host_year.present? competitions = competitions.where(host_year: host_year) end if cookies[:area] == '1' competitions = competitions.where(district_id: 9) end @competitions = competitions.select(:id, :name, :cover).order('id desc').page(params[:page]).per(params[:per]) end def show end def apply_process end def events @competition = Competition.find(params[:id]) if current_user current_user_id = current_user.id events = Event.joins("left join team_user_ships t_u on t_u.event_id = events.id and t_u.user_id = #{current_user_id}").joins('left join teams t on t.id = t_u.team_id').where(competition_id: @competition.id, is_father: 0).select(:id, :name, :group, :team_max_num, 't.user_id as leader_id', 't.status as team_status', 't.identifier', 't_u.user_id as player_id', 't_u.team_id', 't_u.status as apply_status') already_events = events.select { |event| event.apply_status != nil } user_info = UserProfile.left_joins(:school, :district).where(user_id: current_user_id).select('user_profiles.*', 'schools.name as school_name', 'districts.name as district_name').take @user_info = user_info || current_user.build_user_profile else events = Event.where(competition_id: @competition.id, is_father: 0).select(:id, :name, :group, :team_max_num) already_events = [] end one_events = events.select { |event| event.team_max_num == 1 } - already_events multiple_events = events - one_events - already_events @events = {already: already_events, one: one_events, multiple: multiple_events} end def apply_event event_id = params[:ed] if require_mobile current_user_id = current_user.id @event = Event.joins(:competition).where(id: event_id).select('events.*', 'competitions.name as comp_name', 'competitions.apply_end_time as end_apply_time').take if @event.present? a_p = TeamUserShip.where(event_id: event_id, user_id: current_user_id).take if a_p.present? if a_p.status @has_apply = [true, true] else @has_apply = [true, false] end @team_players = Team.find_by_sql("select t.id as team_id, t.user_id as leader_user_id,t.players,a.team_id,u_p.username,u_p.bj,t.identifier,t.teacher,t.teacher_mobile,u.nickname,u_p.grade as grade,u_p.user_id as user_id,u_p.gender as gender, a.status as player_status,t.status as team_status,s.name as school_name from team_user_ships a INNER JOIN teams t on t.id = a.team_id left join user_profiles u_p on u_p.user_id = a.user_id left join users u on u.id = u_p.user_id left join schools s on s.id = a.school_id where a.team_id = #{a_p.team_id}") else @has_apply = [false, false] end end user_info = UserProfile.left_joins(:school, :district).where(user_id: current_user_id).select('user_profiles.*', 'schools.name as school_name', 'districts.name as district_name').take; false @user_info = user_info ||= current_user.build_user_profile else session[:redirect_to] = request.headers[:Referer] redirect_to user_mobile_path, notice: '继续操作前请添加手机信息' end end def apply_join_team user_id = current_user.id username = params[:username] gender = params[:gender] school_id = params[:school_id] grade = params[:grade] bj = params[:bj] birthday = params[:birthday] student_code = params[:student_code] identity_card = params[:identity_card] td = params[:td] if username.present? && school_id.to_i !=0 && grade.to_i !=0 && bj.present? && gender.present? && student_code.present? && birthday.present? && td.to_i !=0 if has_teacher_role result = [false, '您是教师,不能报名比赛!'] else user_profile = current_user.user_profile ||= current_user.build_user_profile if user_profile.update_attributes(username: username, gender: gender, school_id: school_id, grade: grade, student_code: student_code, birthday: birthday, identity_card: identity_card) event = Team.joins(:event).joins('left join competitions c on events.competition_id = c.id').where('teams.id=?', td).select('c.apply_end_time', 'events.team_max_num', :players, :identifier, 'events.id as event_id', 'teams.user_id', 'teams.status as team_status', 'events.name as event_name').take if event.present? && (event.apply_end_time > Time.zone.now) && (event.team_max_num > 1) && (event.team_max_num > event.players) && (event.team_status == 0) already_apply = TeamUserShip.where(user_id: user_id, event_id: event.event_id).exists? if already_apply.present? result = [false, '该比赛您已报名或等待队长审核'] else begin Notification.transaction do t_u = TeamUserShip.create!(team_id: td, user_id: user_id, event_id: event.event_id, school_id: school_id, grade: grade, status: 0) Notification.create!(user_id: event.user_id, content: username+' 申请加入您在比赛项目-'+ event.event_name.to_s + '中创建的队伍-'+ event.identifier, t_u_id: t_u.id, team_id: td, message_type: 2, reply_to: user_id) end result = [true, '申请成功,等待队长同意,结果将会通过消息推送告知您!'] rescue Exception => ex result = [false, ex.message] end end else result = [false, '不规范请求或已过报名时间!'] end else result = [false, user_profile.errors.full_messages.first] end end else result = [false, '信息输入不完整'] end render json: {status: result[0], message: result[1]} end def leader_batch_apply user_id = current_user.id username = params[:username] gender = params[:gender] school_id = params[:school_id] district_id = params[:district_id] sk_station = params[:sk_station] grade = params[:grade] bj = params[:bj] birthday = params[:birthday] student_code = params[:student_code] identity_card = params[:identity_card] group = params[:group] teacher = params[:teacher] eds = params[:eds] if eds.present? && eds.is_a?(Array) && eds.length < 6 && username.present? && school_id.to_i !=0 && district_id.present? && grade.to_i !=0 && gender.present? && student_code.present? && birthday.present? && teacher.present? && group.present? if has_teacher_role result = [false, '您是老师,不能报名比赛!'] else if current_user.mobile.present? events = Event.joins(:competition).where(id: eds).select(:id, :name, :group, 'competitions.apply_end_time') if events.present? && events.length == eds.length if events[0].apply_end_time > Time.zone.now already_apply = TeamUserShip.where(user_id: user_id, event_id: eds).exists? if already_apply result = [false, '您提交的项目中部分您已报名,无需再次报名'] else user_profile = current_user.user_profile ||= current_user.build_user_profile if user_profile.update_attributes(username: username, gender: gender, district_id: district_id, school_id: school_id, grade: grade, bj: bj, student_code: student_code, birthday: birthday, identity_card: identity_card) result_status = true result = [] success_teams = [] each_index = 0 events.each_with_index do |event, index| each_index = index if event.group.include?(group) if result_status begin TeamUserShip.transaction do team = Team.create!(group: group, user_id: user_id, teacher: teacher, event_id: event.id, district_id: district_id, school_id: school_id, sk_station: sk_station) team.team_user_ships.create!(team_id: team.id, user_id: user_id, event_id: event.id, district_id: district_id, school_id: school_id, grade: grade, status: true) result << "#{event.name}报名成功!" success_teams << {event_name: event.name, team_id: team.id, identifier: team.identifier, event_id: event.id} end rescue Exception => ex result_status = false result << ex.message end else break end else result = [false, "#{event.name}不包含您所报名的组别!"] result_status = false break end end if result_status result = [true, '提交成功', success_teams] else if each_index > 0 result = [true, (result[0..-2]+['剩余项目报名失败']).join(','), success_teams] else result = [false, result[1]] end end else result = [false, user_profile.errors.full_messages.first] end end else result = [false, '该比赛已过报名时间'] end else result = [false, '项目参数不规范'] end else result = [false, '请先添加手机号!'] end end else result = [false, '信息输入不完整或不规范'] end render json: {status: result[0], message: result[1], success_teams: result[2]} end ## old def leader_create_team user_id = current_user.id username = params[:username] gender = params[:gender] school_id = params[:school] district_id = params[:district_id] grade = params[:grade] birthday = params[:birthday] student_code = params[:student_code] identity_card = params[:identity_card] group = params[:team_group] teacher = params[:teacher_name] teacher_mobile = params[:teacher_mobile] ed = params[:team_event] if username.present? && school_id.to_i !=0 && district_id.present? && grade.to_i !=0 && gender.present? && student_code.present? && birthday.present? && teacher.present? && group.present? if has_teacher_role result = [false, '您是老师,不能报名比赛'] else user = current_user.user_profile ||= current_user.build_user_profile if user.update_attributes(username: username, gender: gender, school_id: school_id, district_id: district_id, grade: grade, student_code: student_code, birthday: birthday, identity_card: identity_card) event = Event.joins(:competition).where(id: ed).select(' competitions.apply_end_time ').take if event.present? && event.apply_end_time > Time.zone.now already_apply = TeamUserShip.where(user_id: user_id, event_id: ed, status: true).exists? if already_apply result = [false, ' 该比赛您已经报名 , 请不要再次报名! '] else begin TeamUserShip.transaction do team = Team.create!(group: group, user_id: user_id, teacher: teacher, teacher_mobile: teacher_mobile, event_id: ed, school_id: school_id, district_id: district_id) TeamUserShip.create!(team_id: team.id, user_id: team.user_id, event_id: ed, school_id: school_id, district_id: district_id, grade: grade, status: true) end result = [true, '队伍创建成功!'] rescue Exception => ex result = [false, ex.message] end end else result = [false, ' 不规范请求或已过报名时间! '] end else result = [false, user.errors.full_messages.first] end end else result = [false, ' 信息输入不完整 '] end render json: result end def search_team event_id = params[:ed] team_identify = params[:team] if event_id.present? && team_identify.present? team = Team.joins(:event).joins('left join schools on teams.school_id = schools.id').joins('left join user_profiles up on up.user_id = teams.user_id').where(event_id: event_id, identifier: team_identify).select(:id, :status, :identifier, :players, :teacher, :teacher_mobile, 'events.team_max_num', 'schools.name as school_name', 'up.username') result = [true, team] else result = [false, '参数不完整'] end render json: result end def search_user invited_name = params[:invited_name] if request.method == 'GET' && invited_name.present? && invited_name.length>1 users = UserProfile.left_joins(:user, :school).where(['user_profiles.username like ?', "#{invited_name}%"]).where('school_id is not NULL').select(:user_id, :nickname, 'user_profiles.username', 'schools.name as school_name', 'user_profiles.gender', 'user_profiles.grade', 'user_profiles.bj') result = [true, users] else result = [false, '请至少输入名字的前两个字'] end render json: result end def leader_invite_player ud = params[:ud] td = params[:td] if request.method == 'POST' && ud.present? && td.present? event_info = Event.joins(:competition, :teams).where('teams.id=?', td.to_i).select(:id, :name, :team_max_num, 'competitions.apply_end_time', 'teams.players', 'teams.user_id', 'teams.identifier').take user_info = User.left_joins(:user_profile).where(id: ud).select(:id, :nickname, 'user_profiles.username').take if event_info.present? && (event_info.apply_end_time > Time.now) && (event_info.team_max_num > event_info.players) && (current_user.id == event_info.user_id) && user_info.present? if check_teacher_role(ud) result = [false, '不能邀请老师'] else if TeamUserShip.where(user_id: ud, event_id: event_info.id).exists? result = [false, '该户已报名此项目或已被您或其他人邀请参加'] else t_u = TeamUserShip.create(team_id: td, user_id: ud, event_id: event_info.id, status: 2, school_id: 0) if t_u.save result= [true, '邀请成功,等待该队员同意', user_info.nickname, user_info.username] Notification.create(user_id: ud, message_type: 1, content: current_user.user_profile.try(:username)+'邀请你参加['+event_info.name+']比赛项目,队伍为:'+event_info.identifier, t_u_id: t_u.id, team_id: td, reply_to: current_user.id) else result= [false, '邀请失败'] end end end else result= [false, '不规范请求'] end else result = [false, '信息不完整'] end render json: result end def leader_delete_team td = params[:td] if td.present? team_info = Event.joins(:teams, :competition).where('teams.id=?', td).select(:name, :team_max_num, 'teams.user_id', 'teams.status', 'teams.players', 'competitions.apply_end_time').take if team_info.present? && (team_info.status != 1) && (team_info.user_id == current_user.id) && (team_info.apply_end_time > Time.now) if Team.find(td).destroy result = [true, '解散成功'] if (team_info.team_max_num > 1) && (team_info.players>1) players = TeamUserShip.where(team_id: td).pluck(:id); false players.drop(current_user.id).each do |u| Notification.create(user_id: u, message_type: 0, content: '在比赛项目--'+team_info.name+'中,您参加的队伍已被队长解散') end end else result = [false, '解散失败'] end else result = [false, '不规范请求或报名时间已截止'] end else result = [false, '参数不完整'] end render json: result end def leader_delete_player td = params[:td] ud = params[:ud] current_user_id = current_user.id if ud == current_user_id.to_s result = [false, '队长不能剔除自己'] else team_info = Event.joins(:teams, :competition).where('teams.id=?', td).select(:name, 'teams.user_id', 'teams.status', 'competitions.apply_end_time').take if team_info.present? && (team_info.status ==0) && (team_info.user_id == current_user_id) && (team_info.apply_end_time > Time.now) t_u = TeamUserShip.where(user_id: ud, team_id: td).take if t_u.present? && t_u.destroy result = [true, '清退成功!'] Notification.create(user_id: team_info.user_id, message_type: 0, content: '在比赛项目:'+team_info.name+'中,您被队长移出队伍') else result = [false, '清退失败!'] end else result = [false, '不规范请求或报名时间已截止'] end end render json: result end def player_agree_leader_invite username = params[:username] gender = params[:gender] district_id = params[:district_id] school_id = params[:school_id] grade = params[:grade] birthday = params[:birthday] student_code = params[:student_code] identity_card = params[:identity_card] td = params[:td] if username.present? && school_id.to_i !=0 && grade.to_i !=0 && gender.present? && district_id.to_i != 0 && student_code.present? && birthday.present? user_profile = current_user.user_profile ||= current_user.build_user_profile if user_profile.update_attributes(username: username, gender: gender, school_id: school_id, grade: grade, district_id: district_id, student_code: student_code, birthday: birthday, identity_card: identity_card) event = Event.joins(:teams, :competition).where('teams.id=?', td).select(:id, :name, 'competitions.apply_end_time', 'teams.user_id as leader_user_id', 'teams.status as team_status', 'teams.identifier').take if event.present? && event.apply_end_time > Time.now && event.team_status==0 t_u = TeamUserShip.where(user_id: current_user.id, event_id: event.id).take if t_u.present? if t_u.status == 1 result = [false, '该比赛您已经报名,请不要再次报名!'] else if t_u.update_attributes(status: 1, school_id: school_id, district_id: district_id, grade: grade) result = [true, '操作成功,您已成为该队队员'] Notification.create(user_id: event.leader_user_id, message_type: 0, content: username+'同意了您的邀请,加入了您在比赛项目:'+event.name+'中创建的队伍--'+event.identifier) else result= [false, '加入失败'] end end else result = [false, '不规范请求!'] end else result = [false, ' 不规范请求或已过报名时间! '] end else result = [false, user_profile.errors.full_messages.first] end else result = [false, '信息不完整'] end render json: result end def leader_deal_player_apply t_u_id = params[:tud] notification_id = params[:nd] reject = params[:reject] # option if t_u_id.present? && (request.format.json? || (request.format.html? && notification_id.present?)) t_u = TeamUserShip.where(id: t_u_id).first if t_u.present? team_info = Event.joins(:competition).left_joins(:teams).where('teams.id=?', t_u.team_id).select(:name, 'competitions.apply_end_time', 'teams.user_id as leader_user_id', 'teams.status as team_status', 'teams.identifier').take if team_info.present? && (team_info.apply_end_time > Time.now) && (team_info.team_status ==0) && (t_u.status == 0) && (team_info.leader_user_id == current_user.id) if reject.present? && reject=='1' Notification.create(user_id: t_u.user_id, content: team_info.name+'比赛项目中队伍'+team_info.identifier+'的队长拒绝了你的申请,您未能加入该队', message_type: 0) if t_u.destroy result = [true, '拒绝成功'] else result = [false, '拒绝失败'] end else t_u.status = 1 if t_u.save result = [true, '接受成功'] Notification.create(user_id: t_u.user_id, content: team_info.name+'比赛项目中'+team_info.identifier+'的队长同意了你的申请,您已成功加入了该队', message_type: 0) else result = [false, '接受失败'] end end else result = [false, '不规范请求'] end else result = [false, '不规范请求'] end else result = [false, '参数不规范'] end respond_to do |format| format.html { redirect_to "/user/notify?id=#{notification_id}", notice: result[1] } format.json { render json: result } end end def school_refuse_teams com_id = params[:comd] team_ids = params[:tds] if com_id.present? && team_ids.present? && team_ids.is_a?(Array) competition = Competition.where(id: com_id, status: 1).select(:school_audit_time).take if competition.present? && competition.school_audit_time > Time.now team_ids = team_ids.map { |t| t.to_i } teacher_info = UserRole.joins('left join user_profiles u_p on user_roles.user_id = u_p.user_id').where(role_id: 1, status: 1, user_id: current_user.id).select(:role_type, :school_id, :district_id).take if teacher_info.present? && teacher_info.role_type == 3 && teacher_info.school_id.present? all_team_ids = Team.joins(:event).where(school_id: teacher_info.school_id, status: [2, 3]).where('events.competition_id = ?', com_id).pluck(:id); false if (all_team_ids & team_ids).length == team_ids.length if Team.where(id: team_ids).update_all(status: -2) == team_ids.length result = [true, '拒绝成功'] else result = [false, '有部分队伍拒绝失败'] end else result = [false, '不规范操作'] end else result = [false, '没有权限'] end else result = [false, '不规范请求或已过学校审核时间'] end else result = [false, '参数不规范'] end render json: result end def district_refuse_teams com_id = params[:comd] team_ids = params[:tds] if team_ids.present? && team_ids.is_a?(Array) && com_id.present? competition = Competition.where(id: com_id, status: 1).select(:district_audit_time).take if competition.present? && competition.district_audit_time > Time.now team_ids = team_ids.map { |t| t.to_i } teacher_info = UserRole.joins('left join user_profiles u_p on user_roles.user_id = u_p.user_id').where(role_id: 1, status: 1, user_id: current_user.id).select(:role_type, :school_id, :district_id).take if teacher_info.present? && teacher_info.role_type == 2 && teacher_info.district_id.present? all_team_ids = Team.joins(:event).where(district_id: teacher_info.district_id, status: [2, 3]).where('events.competition_id = ?', com_id).pluck(:id); false if (all_team_ids & team_ids).length == team_ids.length if Team.where(id: team_ids).update_all(status: -3) == team_ids.length result = [true, '拒绝成功'] else result = [false, '有部分队伍拒绝失败'] end else result = [false, '不规范操作'] end else result = [false, '没有权限'] end else result = [false, '不规范请求或已过区县审核时间'] end else result = [false, '参数不规范'] end render json: result end def leader_submit_team team_id = params[:td] if team_id.present? team = Team.joins(:event).joins('left join competitions c on c.id = events.competition_id').where('teams.id=?', team_id).select('teams.*', 'c.apply_end_time', 'events.team_max_num').take if team.present? && (team.apply_end_time > Time.now) && (team.status ==0) && (team.user_id == current_user.id) if (team.team_max_num > 1) && (team.team_user_ships.pluck(:status) & [false]).count > 0 result = [false, '有队员还未确认参加,不能提交'] else if team.update_attributes(status: 2) result = [true, '提交成功,审核结果将会在消息中告知您'] else result = [false, '提交失败'] end end else result = [false, '不规范操作或已过报名时间'] end else result = [false, '参数不完整'] end render json: result end def school_submit_teams com_id = params[:comd] team_ids = params[:tds] if com_id.present? && team_ids.present? && team_ids.is_a?(Array) competition = Competition.where(id: com_id, status: 1).select(:school_audit_time).take if competition.present? && competition.school_audit_time > Time.now team_ids = team_ids.map { |t| t.to_i } teacher_info = UserRole.joins('left join user_profiles u_p on user_roles.user_id = u_p.user_id').where(role_id: 1, status: 1, user_id: current_user.id).select(:role_type, :school_id, :district_id).take if teacher_info.present? && teacher_info.role_type == 3 && teacher_info.school_id.present? all_team_ids = Team.joins(:event).where(school_id: teacher_info.school_id, status: [2, -2]).where('events.competition_id = ?', com_id).pluck(:id); false if (all_team_ids & team_ids).length == team_ids.length if Team.where(id: team_ids).update_all(status: 3) == team_ids.length result = [true, '提交成功'] else result = [false, '有部分未提交成功'] end else result = [false, '不规范操作'] end else result = [false, '没有权限'] end else result = [false, '不规范请求或已过学校审核提交时间'] end else result = [false, '参数不规范'] end render json: result end def district_submit_teams com_id = params[:comd] team_ids = params[:tds] if team_ids.present? && team_ids.is_a?(Array) && com_id.present? competition = Competition.where(id: com_id, status: 1).select(:district_audit_time).take if competition.present? && competition.district_audit_time > Time.now team_ids = team_ids.map { |t| t.to_i } teacher_info = UserRole.joins('left join user_profiles u_p on user_roles.user_id = u_p.user_id').where(role_id: 1, status: 1, user_id: current_user.id).select(:role_type, :school_id, :district_id).take if teacher_info.present? && teacher_info.role_type == 2 && teacher_info.district_id.present? all_team_ids = Team.joins(:event).where(district_id: teacher_info.district_id, status: [2, 3, -3]).where('events.competition_id = ?', com_id).pluck(:id); false if (all_team_ids & team_ids).length == team_ids.length if Team.where(id: team_ids).update_all(status: 1) == team_ids.length result = [true, '提交成功'] else result = [false, '有部分未提交成功'] end else result = [false, '不规范操作'] end else result = [false, '没有权限'] end else result = [false, '不规范请求或已过区县审核时间'] end else result = [false, '参数不规范'] end render json: result end protected def set_competition @competition = Competition.find(params[:id]) end end
mit
zhangbobell/mallshop
plugins/onekey/taobao/top/request/RefundMessagesGetRequest.php
1999
<?php /** * TOP API: taobao.refund.messages.get request * * @author auto create * @since 1.0, 2014-09-13 16:51:05 */ class RefundMessagesGetRequest { /** * 需返回的字段列表。可选值:RefundMessage结构体中的所有字段,以半角逗号(,)分隔。 **/ private $fields; /** * 页码。取值范围:大于零的整数; 默认值:1<br /> 支持最小值为:1 **/ private $pageNo; /** * 每页条数。取值范围:大于零的整数; 默认值:40;最大值:100<br /> 支持最大值为:100<br /> 支持最小值为:1 **/ private $pageSize; /** * 退款单号 **/ private $refundId; private $apiParas = array(); public function setFields($fields) { $this->fields = $fields; $this->apiParas["fields"] = $fields; } public function getFields() { return $this->fields; } public function setPageNo($pageNo) { $this->pageNo = $pageNo; $this->apiParas["page_no"] = $pageNo; } public function getPageNo() { return $this->pageNo; } public function setPageSize($pageSize) { $this->pageSize = $pageSize; $this->apiParas["page_size"] = $pageSize; } public function getPageSize() { return $this->pageSize; } public function setRefundId($refundId) { $this->refundId = $refundId; $this->apiParas["refund_id"] = $refundId; } public function getRefundId() { return $this->refundId; } public function getApiMethodName() { return "taobao.refund.messages.get"; } public function getApiParas() { return $this->apiParas; } public function check() { RequestCheckUtil::checkNotNull($this->fields,"fields"); RequestCheckUtil::checkMinValue($this->pageNo,1,"pageNo"); RequestCheckUtil::checkMaxValue($this->pageSize,100,"pageSize"); RequestCheckUtil::checkMinValue($this->pageSize,1,"pageSize"); RequestCheckUtil::checkNotNull($this->refundId,"refundId"); } public function putOtherTextParam($key, $value) { $this->apiParas[$key] = $value; $this->$key = $value; } }
mit
msaranu/TwitterApp
app/src/main/java/com/codepath/apps/twitterEnhanced/activities/DirectMessageActivity.java
1427
package com.codepath.apps.twitterEnhanced.activities; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.codepath.apps.twitterEnhanced.R; import com.codepath.apps.twitterEnhanced.fragments.DirectMessageFragment; import butterknife.BindView; import butterknife.ButterKnife; public class DirectMessageActivity extends AppCompatActivity { @BindView(R.id.etDMSend) public EditText etDMSend; @BindView(R.id.btnDMSend) public Button btnDMSend; String messageTest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_direct_message); ButterKnife.bind(this); constructFragment(null); } public void onDMSend(View v){ if(etDMSend != null && etDMSend.getText() !=null){ messageTest = etDMSend.getText().toString(); } constructFragment(messageTest); } public void constructFragment(String messageTest){ DirectMessageFragment directMessageFragment = DirectMessageFragment.newInstance(messageTest); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fragmentDM, directMessageFragment); ft.commit(); } }
mit
zcodes/symfony
src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php
8350
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\PropertyInfo\Extractor; use phpDocumentor\Reflection\DocBlock; use phpDocumentor\Reflection\DocBlockFactory; use phpDocumentor\Reflection\DocBlockFactoryInterface; use phpDocumentor\Reflection\Types\Context; use phpDocumentor\Reflection\Types\ContextFactory; use Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface; use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface; use Symfony\Component\PropertyInfo\Type; use Symfony\Component\PropertyInfo\Util\PhpDocTypeHelper; /** * Extracts data using a PHPDoc parser. * * @author Kévin Dunglas <[email protected]> * * @final */ class PhpDocExtractor implements PropertyDescriptionExtractorInterface, PropertyTypeExtractorInterface { const PROPERTY = 0; const ACCESSOR = 1; const MUTATOR = 2; /** * @var DocBlock[] */ private $docBlocks = []; /** * @var Context[] */ private $contexts = []; private $docBlockFactory; private $contextFactory; private $phpDocTypeHelper; private $mutatorPrefixes; private $accessorPrefixes; private $arrayMutatorPrefixes; /** * @param string[]|null $mutatorPrefixes * @param string[]|null $accessorPrefixes * @param string[]|null $arrayMutatorPrefixes */ public function __construct(DocBlockFactoryInterface $docBlockFactory = null, array $mutatorPrefixes = null, array $accessorPrefixes = null, array $arrayMutatorPrefixes = null) { if (!class_exists(DocBlockFactory::class)) { throw new \LogicException(sprintf('Unable to use the "%s" class as the "phpdocumentor/reflection-docblock" package is not installed.', __CLASS__)); } $this->docBlockFactory = $docBlockFactory ?: DocBlockFactory::createInstance(); $this->contextFactory = new ContextFactory(); $this->phpDocTypeHelper = new PhpDocTypeHelper(); $this->mutatorPrefixes = null !== $mutatorPrefixes ? $mutatorPrefixes : ReflectionExtractor::$defaultMutatorPrefixes; $this->accessorPrefixes = null !== $accessorPrefixes ? $accessorPrefixes : ReflectionExtractor::$defaultAccessorPrefixes; $this->arrayMutatorPrefixes = null !== $arrayMutatorPrefixes ? $arrayMutatorPrefixes : ReflectionExtractor::$defaultArrayMutatorPrefixes; } /** * {@inheritdoc} */ public function getShortDescription($class, $property, array $context = []): ?string { /** @var $docBlock DocBlock */ list($docBlock) = $this->getDocBlock($class, $property); if (!$docBlock) { return null; } $shortDescription = $docBlock->getSummary(); if (!empty($shortDescription)) { return $shortDescription; } foreach ($docBlock->getTagsByName('var') as $var) { $varDescription = $var->getDescription()->render(); if (!empty($varDescription)) { return $varDescription; } } return null; } /** * {@inheritdoc} */ public function getLongDescription($class, $property, array $context = []): ?string { /** @var $docBlock DocBlock */ list($docBlock) = $this->getDocBlock($class, $property); if (!$docBlock) { return null; } $contents = $docBlock->getDescription()->render(); return '' === $contents ? null : $contents; } /** * {@inheritdoc} */ public function getTypes($class, $property, array $context = []): ?array { /** @var $docBlock DocBlock */ list($docBlock, $source, $prefix) = $this->getDocBlock($class, $property); if (!$docBlock) { return null; } switch ($source) { case self::PROPERTY: $tag = 'var'; break; case self::ACCESSOR: $tag = 'return'; break; case self::MUTATOR: $tag = 'param'; break; } $types = []; /** @var DocBlock\Tags\Var_|DocBlock\Tags\Return_|DocBlock\Tags\Param $tag */ foreach ($docBlock->getTagsByName($tag) as $tag) { if ($tag && null !== $tag->getType()) { $types = array_merge($types, $this->phpDocTypeHelper->getTypes($tag->getType())); } } if (!isset($types[0])) { return null; } if (!\in_array($prefix, $this->arrayMutatorPrefixes)) { return $types; } return [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), $types[0])]; } private function getDocBlock(string $class, string $property): array { $propertyHash = sprintf('%s::%s', $class, $property); if (isset($this->docBlocks[$propertyHash])) { return $this->docBlocks[$propertyHash]; } $ucFirstProperty = ucfirst($property); switch (true) { case $docBlock = $this->getDocBlockFromProperty($class, $property): $data = [$docBlock, self::PROPERTY, null]; break; case list($docBlock) = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::ACCESSOR): $data = [$docBlock, self::ACCESSOR, null]; break; case list($docBlock, $prefix) = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::MUTATOR): $data = [$docBlock, self::MUTATOR, $prefix]; break; default: $data = [null, null, null]; } return $this->docBlocks[$propertyHash] = $data; } private function getDocBlockFromProperty(string $class, string $property): ?DocBlock { // Use a ReflectionProperty instead of $class to get the parent class if applicable try { $reflectionProperty = new \ReflectionProperty($class, $property); } catch (\ReflectionException $e) { return null; } try { return $this->docBlockFactory->create($reflectionProperty, $this->createFromReflector($reflectionProperty->getDeclaringClass())); } catch (\InvalidArgumentException $e) { return null; } } private function getDocBlockFromMethod(string $class, string $ucFirstProperty, int $type): ?array { $prefixes = self::ACCESSOR === $type ? $this->accessorPrefixes : $this->mutatorPrefixes; $prefix = null; foreach ($prefixes as $prefix) { $methodName = $prefix.$ucFirstProperty; try { $reflectionMethod = new \ReflectionMethod($class, $methodName); if ($reflectionMethod->isStatic()) { continue; } if ( (self::ACCESSOR === $type && 0 === $reflectionMethod->getNumberOfRequiredParameters()) || (self::MUTATOR === $type && $reflectionMethod->getNumberOfParameters() >= 1) ) { break; } } catch (\ReflectionException $e) { // Try the next prefix if the method doesn't exist } } if (!isset($reflectionMethod)) { return null; } try { return [$this->docBlockFactory->create($reflectionMethod, $this->createFromReflector($reflectionMethod->getDeclaringClass())), $prefix]; } catch (\InvalidArgumentException $e) { return null; } } /** * Prevents a lot of redundant calls to ContextFactory::createForNamespace(). */ private function createFromReflector(\ReflectionClass $reflector): Context { $cacheKey = $reflector->getNamespaceName().':'.$reflector->getFileName(); if (isset($this->contexts[$cacheKey])) { return $this->contexts[$cacheKey]; } $this->contexts[$cacheKey] = $this->contextFactory->createFromReflector($reflector); return $this->contexts[$cacheKey]; } }
mit
steflef/lmtl
www/collab_api/public/js/libs/gatlas/g_911.01.js
19114
var ga = {}; var map, layer, parser; var zoom = 12; var eventinfos = []; var templates = []; // Leaflet Default Icon var MyIcon = L.Icon.extend({ iconUrl: BASE_URL+'public/imgs/interface/leaflet/marker.png', shadowUrl:BASE_URL+'public/imgs/interface/leaflet/marker-shadow.png'/* , iconSize: new L.Point(25, 41), shadowSize: new L.Point(41, 41), iconAnchor:new L.Point(13,41), popupAnchor:new L.Point(0,-33) */ }); var icon = new MyIcon(); function showEvents(e) { $j("#last24hour div.filter-box-mod").addClass("noDisplay"); $j(e).each(function(){ $j('.'+this).removeClass("noDisplay"); }); // Header $j("#showAllEvents").removeClass("noDisplay"); } function showAllEvents() { $j("#last24hour div").removeClass("noDisplay"); $j("#showAllEvents").addClass("noDisplay"); } function zoomTo(lon,lat) { if( lon==0 || lat==0) { alert("La géoréférence de cet événement est partielle ou inconnue."); } else { var point = new OpenLayers.LonLat(lon, lat); map.setCenter( point.transform(serverProj, map.getProjectionObject()),5,false,true); } } function filter_24h( filterName, param ){ var evntsList, len, header=[], items2hide, items2show; $j('#w_panel').show(); items2hide = $j("div.eventInfos") .find("dt."+filterName+":not(:contains('"+param+"'))") .parents(".eventInfos"); items2show = $j("div.eventInfos") .find("dt."+filterName+":contains('"+param+"')") .parents(".eventInfos"); if( eventinfos.length === 0 ) eventinfos = $j.merge(items2hide,items2show); len = items2show.length; evntsList = $j('#last24hour'); evntsList.find("div.evnts-cluster").remove(); header.push( '<div class="evnts-header evnts-cluster">' ); header.push( '<div class="filter-box-mod left_area">' ); header.push( '<dl class="event font_style" >' ); header.push( '<dt style="right:10px;top:2px;"><a href="#" class="close" ></a></dt>' ); header.push( '<dd>Filtre ('+param+') '+len+' appel(s)</dd>' ); header.push( '</dl>' ); header.push( '</div>' ); header.push( '</div>' ); evntsList.find("div.evnts-header").hide(); evntsList.prepend( header.join('') ); $j("div.evnts-cluster") .unbind("click") .bind("click", function() { $j('#status').text("suppression du filtre ..."); $j('#w_panel').show(); runFilter(eventinfos, eventinfos.length, 'show_all', function(){ evntsList.find("div.evnts-cluster").remove(); oEv.clearFilter(); $j('#w_panel').hide(); }); $j(this).unbind("click"); }); runFilter(items2hide, items2hide.length, 'hide', function(){ $j('#w_panel').hide(); runFilter(items2show, len, 'show', function( ids ){ oEv.setFilter(ids); }); }); } runFilter = function (e, l, sh, onComplete){ var pos = 0; var step = 100; var call_ids = []; (function(){ //console.log("RUN FILTER ("+sh+"):: batch => " + pos); $j('#status').text("traitement du filtre "+pos+"/"+l+" ..."); var s = pos+step; if( sh === 'hide') { for(var i= pos;i<s;i++) { if (i >= l) break; $j(e[i]).hide(); } } if( sh === 'show') { for(var i= pos;i<s;i++) { if (i >= l) break; call_ids.push( $j(e[i]) .show() .attr('id') .substring(5) ); } } if( sh === 'show_all') { for(var i= pos;i<s;i++) { if ( i >= l ) break; $j(e[i]).show(); } } pos = s; if (pos < l) { setTimeout(arguments.callee,10); } else { $j('#status').text(""); onComplete(call_ids); } })(); } function list_cluster_24h( call_ids ){ var evntsList, len, header=[], items2hide, items2show; $j('#w_panel').show(); items2hide = $j("div.eventInfos"); items2show = call_ids; len = items2show.length; evntsList = $j('#last24hour'); evntsList.find("div.evnts-cluster").remove(); header.push( '<div class="evnts-header evnts-cluster">' ); header.push( '<div class="filter-box-mod left_area">' ); header.push( '<dl class="event font_style" >' ); header.push( '<dt style="right:10px;top:2px;"><a href="#" class="close" ></a></dt>' ); header.push( '<dd>Regroupement de '+len+' appel(s)</dd>' ); header.push( '</dl>' ); header.push( '</div>' ); header.push( '</div>' ); evntsList.find("div.evnts-header").hide(); evntsList.prepend( header.join('') ); $j("div.evnts-cluster") .unbind("click") .bind("click", function() { DEBUG("CLICK BINDING"); $j('#w_panel').show(); evntsList.find("div.eventInfos").show(); evntsList.find("div.evnts-header").show(); evntsList.find("div.evnts-cluster").remove(); $j('#w_panel').hide(); $j(this).unbind("click"); }); runFilter(items2hide, items2hide.length, 'hide', function(){ runCluster(items2show, len, function(){ $j('#w_panel').hide(); }); }); } runCluster = function (e, l, onComplete){ var pos = 0; var step = 100; //console.log(arguments); (function(){ //console.log("RUN CLUSTER :: batch => " + pos); $j('#status').text("traitement du regroupement ("+pos+") ..."); var s = pos+step; for(var i= pos;i<s;i++) { if (i >= l) break; $j("div.eventInfos#call_"+e[i]).show(); } pos = s; if (pos < l) { setTimeout(arguments.callee,10); } else { $j('#status').text(""); onComplete(); } })(); } /* !onReady */ $j(document).ready(function(){ /// CLEANING UP THE TEMPLATE FROM THE CODE // INJECT TMPL in DOM + insert in array + remove from DOM var tmpTmpl = $j('footer').append( $j('#tmpl').html() ).addClass('noDisplay'); DEBUG( '** Template(s) trouvée(s)-> '+ $j(tmpTmpl).find('.tmpl').length ); $j(tmpTmpl).find('.tmpl').each(function(){ templates[ $j(this).get(0).id ] = $j(this).html(); $j(this).remove(); }) $j(tmpTmpl).remove(); /// MAP EVENT LISTENER //function listnerMoveEnd(event){} /// CLEAR THE POPUP-INFO IF VISIBLE //function listnerMoveStart(event){} /// STATISTIQUE 24H SELECT BOX /* $j('#par_code').bind('change', function(e){ t = Number($j(this).val()); $j(this).parent().parent().find('ul').addClass('noDisplay'); $j('#par_code_'+t).removeClass('noDisplay'); }).change(); */ /// CREATE LEAFLET MAP map = new L.Map('mapPort', {'scrollWheelZoom':false}); var markersLayer = new L.LayerGroup(); var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmAttrib='Map data © openstreetmap contributors', osm = new L.TileLayer(osmUrl,{minZoom: 8, maxZoom:18, attribution: osmAttrib}); var osmLocalUrl= BASE_URL+'public/maps/sjsr_roads/{z}/{x}/{y}.png', osmLocalAttrib='© openstreetmap', osmLocal = new L.TileLayer(osmLocalUrl,{minZoom: 9, maxZoom:17, attribution: osmLocalAttrib, scheme:'tms', format: 'image/png',transparent: true}); var lim_admin_url = BASE_URL+'public/maps/sjsr_secteurs/{z}/{x}/{y}.png', lim_admin_attrib='GAtlas © 2011'; var lim_admin = new L.TileLayer(lim_admin_url, {minZoom: 9,maxZoom: 17, attribution: lim_admin_attrib, format: 'image/png',transparent: true}); var geojsonLayer = new L.GeoJSON(null); var canvasTiles = new L.TileLayer.Canvas(); /* geojsonLayer.setStyle( { "color": "#ff0000", "weight": 4, "opacity": 0.9 } ); */ /* geojsonLayer.on("featureparse", function (e){ if (e.properties && e.properlties.style && e.layer.setStyle){ // The setStyle method isn't available for Points. More on that below ... e.layer.setStyle(e.properties.style); } }); */ var defaultStyle = { color: '#666', weight: 0.2, opacity: 0.9, fillOpacity: 0.4, fillColor: '#fff' }; var highlightStyle = { color: '#333', weight: 1, opacity: 1, fillOpacity: 0, fillColor: '#fff' }; geojsonLayer.on("featureparse", function (e){ e.layer.setStyle(defaultStyle); // Create a self-invoking function that passes in the layer // and the properties associated with this particular record. (function(layer, properties) { // Create a mouseover event layer.on("mouseover", function (e) { // Change the style to the highlighted version layer.setStyle(highlightStyle); // Create a popup with a unique ID linked to this record var popup = $j("<div></div>", { id: "popup-" + properties.hex_id, css: { position: "absolute", bottom: "85px", left: "50px", zIndex: 100002, backgroundColor: "white", padding: "8px", border: "1px solid #ccc" } }); // Insert a headline into that popup var hed = $j("<div></div>", { text: "Hex ID : " + properties.hex_id, css: {fontSize: "16px", marginBottom: "3px"} }).appendTo(popup); // Add the popup to the map popup.appendTo("#mapPort"); }); // Create a mouseout event that undoes the mouseover changes layer.on("mouseout", function (e) { // Start by reverting the style back layer.setStyle(defaultStyle); // And then destroying the popup $j("#popup-" + properties.hex_id).remove(); }); // Close the "anonymous" wrapper function, and call it while passing // in the variables necessary to make the events work the way we want. })(e.layer, e.properties); }); geojsonLayer.addGeoJSON(geojsonFeature); var sjsr = new L.LatLng( 46.723301297642678,-71.507612794586862); //var sjsr = new L.LatLng(45.3,-73.26); map.setView(sjsr, 13).addLayer(osm).addLayer(geojsonLayer).addLayer(canvasTiles); //map.setView(sjsr, 13).addLayer(osm).addLayer(lim_admin).addLayer(geojsonLayer).addLayer(markersLayer); DEBUG( map.getBounds() ); //return false; map.on('click', function(e) { DEBUG('MAP CLICK'); //DEBUG(e); }); markerClick = function(e) { DEBUG('markerClip CLICK'); DEBUG(e); DEBUG(e.target.data.desc); } /// RAPHAEL VECTORS $j("#mapPort").find("div").eq(1).prepend('<div id="r_map" style="border:0;height:100%;position:absolute;left:0;top:0;">test</div>'); r_clusters = Raphael($j("#r_map")[0], 564, 600); st = r_clusters.set(); ev = r_clusters.set(); /// RAO 911 oEv = new eventManager(map,markersLayer,{}); /// MAP EVENTS //map.events.register('moveend', null, listnerMoveEnd); //map.events.register('movestart', null, listnerMoveStart); // CLICK HANDLER FOR LIST OF CALLS $j("div#last24hour").delegate('dl','click', function(e){ var id = e.currentTarget.id.substring(1); if( id !== '') getRef( id ); $j("div#last24hour").find(".evt-selected").removeClass("evt-selected"); $j(this).parent().addClass('evt-selected'); }); // TEXT COLORATION FOR THE 48Hours tendency if( $j(".diff-48h >h1").text().substring(0,1) == '+'){ $j(".diff-48h >h1").addClass("plus"); }else{ $j(".diff-48h >h1").addClass("minus"); } // ASSIGNATION POUR LE MESSAGE USAGER $j(".alert-message").alert() /* !END onReady */ }); /// AFFICHE UNE RÉFÉRENCE function getRef(e) { // BUILD TEMPORARY BOX var infos = $j("#_"+e); DEBUG(infos); var date_time = infos.find("dd:first").text(); var desc = infos.find("dd:eq(1)").text(); var data = {e:e, infos:infos, evnt_date: date_time.substring(0,11), evnt_time: date_time.substring(11), desc:desc }; var tmpl = templates['tmpl-details-noGeo']; var html_content = Mustache.to_html(tmpl, data); $j('.c-details').html( html_content ).find('#ui-tabs').tabs(); $j('.c-details').append('<div class="c-close"><a href="#" title="Fermer"></a></div>'); //$j('.c-close').before( html_content ).parent().find('#ui-tabs').tabs(); $j('.c-close').bind("click", function(){ $j('.content-details').hide(); $j("div#last24hour").find(".evt-selected").removeClass("evt-selected"); }); $j('.content-details').show(); var sidebarWidth = $j(".sidebar").outerWidth(); DEBUG(">>>" + sidebarWidth); //$j(".c-details").css('left', (sidebarWidth +20)+"px"); $j(".c-details") .css('left', (sidebarWidth -200)+"px") .stop() .animate({ left: '+=220' }, "fast", function() { // Animation complete. }); // LOADING DATA $j.post(BASE_URL + "raoevnts/ref/"+ e, null, function(data) { $j("#loading").hide(); if( data.status !== 1 ){ DEBUG("Erreur JSON getRef !!!"); } parseRefData(data); }, "json").error( function(request, error) { DEBUG("POST ERROR => " + error); DEBUG( request ); }); } /// PARSE SERVER JSON DATA function parseRefData(data) { /// RESUME $j('.c-details').find("#tabs-1").find(".i-content").append(data.results.resumeHtml); lonlat = { lon:data.results.overview_data.lon, lat:data.results.overview_data.lat }; show_map(lonlat); $j('.c-details').find("#tabs-1").find(".lieu-infos").html("<dl>"+data.results.localisationHtml+"</dl>"); /// SEQUENCES if( data.results.sequenceHtml.length < 10 ) { data.results.sequenceHtml = '<span class="round">Aucune séquence pour cet appel.</span>'; } $j('.c-details').find("#tabs-2").find(".i-content").html(data.results.sequenceHtml); // HISTORY dynamic templating with Mustache if (data.results.history.results_count > 1 ) { var actualCode = data.results.overview_data.call_id; var aHisto = []; $j.each(data.results.history.results, function(i, val) { if (val.call_id == actualCode) return true; var hTime = val.call_dt.substring(11); var aTime = hTime.split('.'); var oHdata = { card_id:val.call_id, card_date: val.call_dt.substring(0,11), card_time: aTime[0], card_desc:val.call_desc, distance: (Math.round( val.distance *100, 2 ))/100 }; aHisto.push(oHdata); }); var oD = {cards:aHisto}; var tmpl = templates['tmpl-card']; var html_content = Mustache.to_html(tmpl, oD); $j('.c-details').find("#tabs-3").find(".i-content").html(html_content); } else { $j('.c-details').find("#tabs-3").find(".i-content").html("Aucun historique pour cet appel."); } // RAW DATA TERMINAL STYLE var html = ''; $j.each(data.results.raw_data, function(i, val) { html += '<li><abbr title="' + val.desc + '">'+i+'</abbr> => '+ val.value + '</li>'; }); $j('.c-details').find("#tabs-4").find(".i-content").html("<ul>"+html+"</ul>"); } function show_map(lonlat) { var html ='<div style="margin-top:10px;border:0;padding:8px;-moz-border-radius:5px;background-color:#e6e6e6;float:left;width:96%;">'; html +=' <div id="g-map" style="border:2px solid #666;height:200px;width:220px;float:left;"></div>'; html +=' <div class="lieu-infos" style="float:right;width:350px;font-size:14px;"></div>'; html +='</div>'; //$j("#cboxContent").find("#tabs-1").find(".i-content").append(html); $j(".c-details").find("#tabs-1").find(".i-content").append(html); g_atlas.event = {lat:lonlat.lat, lon:lonlat.lon}; var e = g_atlas.event; e.map = new L.Map('g-map', {'scrollWheelZoom':false, 'dragging':false, 'touchZoom':false, 'zoomControl':false}); var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmAttrib='Map data © openstreetmap contributors', osm = new L.TileLayer(osmUrl,{minZoom: 10, maxZoom:18, attribution: osmAttrib}); var callPos = new L.LatLng(g_atlas.event.lat,g_atlas.event.lon); e.map.setView(callPos, 17).addLayer(osm); // MARKER var marker = new L.Marker(callPos, {'icon':icon}); e.map.addLayer(marker); } /// TOGGLE MAP FULLVIEW // CENTERVIEW function toggleView() { if( $j("#map-viewer").css('width') == '100%' ) { var p = map.getCenter(); $j("#map-viewer").css({width:'57%'}); $j("#stats").show(); map.setCenter( p); $j("#toggle-view").css({backgroundPosition:'top left'}); } else { var p = map.getCenter(); $j("#stats").hide(); $j("#map-viewer").css({width:'100%'}); $j("#toggle-view").css({backgroundPosition:'bottom left'}); map.setCenter( p); } oEv.update(true); } /// CENTRE LA CARTE SUR UN POINT, ZOOM FIXE(17) function toCenter(e) { var o = oEv.aEvents[oEv.aLookup[e]]; //console.log("TO CENTER >>>"); //console.log(o); map.setCenter( o.point,17); // OUVERTURE AUTOMATIQUE DU POPUP if( o.vector.marker != undefined) { $j(o.vector.marker.node).trigger('test', [t,e]); } /// TODO make it works with clusters usin aEvent.aPointers } /// ERROR HANDLER IN CASE NO FLASH IN BROWSER function handleNoFlash(errorCode) { if (errorCode == 603) { alert("Error: Flash doesn't appear to be supported by your browser"); return; } } /// XYZ FONCTION FOR HEATMAP function get_my_url (bounds) { var res = this.map.getResolution(); //console.info(this.map.getResolution()); // console.info("bounds"); // console.info(bounds); var x = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w)); var y = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h)); var z = this.map.getZoom(); var path = z + "/" + x + "/" + y + "." + this.type; var url = this.url; if (url instanceof Array) { url = this.selectUrl(path, url); } return url + path; } function scrollContent(n,pos) { if(!g_atlas.event.scroll) { g_atlas.event.scroll = 0; $j('.infoPop-scroller').css({left:'0'}); g_atlas.event.flag = 1; } if( g_atlas.event.flag == 0){ return; } if( n == null && pos > 0 ) { g_atlas.event.scroll = 0; //console.log('Scroll Content pos=> '+pos); if(g_atlas.event.scroll < (g_atlas.event.maxscroll -1 ) ) { $j('a.back').css({backgroundColor:'#ccc'}); var newPos = (pos -1); g_atlas.event.scroll = newPos; g_atlas.event.flag = 0; //console.log('Positionning'); var l = newPos * 333; $j('.infoPop-scroller').animate({left:'-='+l}, 'fast', function() { if(g_atlas.event.scroll == (g_atlas.event.maxscroll -1 ) ) { $j('a.next').css({backgroundColor:'#666'}); } g_atlas.event.flag = 1; //console.log('END Positionning'); }); } } else { if(n == 'next') { if(g_atlas.event.scroll < (g_atlas.event.maxscroll -1 ) ) { $j('a.back').css({backgroundColor:'#ccc'}); g_atlas.event.scroll ++; g_atlas.event.flag = 0; $j('.infoPop-scroller').animate({left:'-=333'}, 'fast', function() { if(g_atlas.event.scroll == (g_atlas.event.maxscroll -1 ) ) { $j('a.next').css({backgroundColor:'#666'}); } g_atlas.event.flag = 1; }); } } else { if(g_atlas.event.scroll > 0 ) { $j('a.next').css({backgroundColor:'#ccc'}); g_atlas.event.scroll --; g_atlas.event.flag = 0; $j('.infoPop-scroller').animate({left:'+=333'}, 'fast', function() { if(g_atlas.event.scroll == 0 ) { $j('a.back').css({backgroundColor:'#666'}); } g_atlas.event.flag = 1; }); } } } }
mit
moljac/Ph4ct3x
source/business-domain-logic/Utilities/Weather/HolisticWare.Ph4ct3x.Utilities.Weather.Providers.DHMZ_MeteoHR_PrognozaHR/DHMZ_MeteoHR_PrognozaHR/agro7.cs
8045
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // //This source code was auto-generated by MonoXSD // namespace HolisticWare.Ph4ct3x.Utilities.Weather.Providers.DHMZ_MeteoHR_PrognozaHR.WeatherData.Current.SoilTemperatures.Weekly { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "0.0.0.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public partial class AgroMeteoroloskiPodaci { private string naslovField; private AgroMeteoroloskiPodaciPodaciGrad[][] podaciField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Naslov { get { return this.naslovField; } set { this.naslovField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] [System.Xml.Serialization.XmlArrayItemAttribute("Grad", typeof(AgroMeteoroloskiPodaciPodaciGrad), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public AgroMeteoroloskiPodaciPodaciGrad[][] Podaci { get { return this.podaciField; } set { this.podaciField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "0.0.0.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] public partial class AgroMeteoroloskiPodaciPodaciGrad { private string gradImeField; private string tmaxField; private string tminField; private string tmin5Field; private string oborField; private string snijegField; private string vlagaMaxField; private string vlagaMinField; private string sunceField; private string tna5MaxField; private string tna5MinField; private string tna20MaxField; private string tna20MinField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string GradIme { get { return this.gradImeField; } set { this.gradImeField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Tmax { get { return this.tmaxField; } set { this.tmaxField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Tmin { get { return this.tminField; } set { this.tminField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Tmin5 { get { return this.tmin5Field; } set { this.tmin5Field = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Obor { get { return this.oborField; } set { this.oborField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Snijeg { get { return this.snijegField; } set { this.snijegField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string VlagaMax { get { return this.vlagaMaxField; } set { this.vlagaMaxField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string VlagaMin { get { return this.vlagaMinField; } set { this.vlagaMinField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Sunce { get { return this.sunceField; } set { this.sunceField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Tna5Max { get { return this.tna5MaxField; } set { this.tna5MaxField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Tna5Min { get { return this.tna5MinField; } set { this.tna5MinField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Tna20Max { get { return this.tna20MaxField; } set { this.tna20MaxField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Tna20Min { get { return this.tna20MinField; } set { this.tna20MinField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "0.0.0.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public partial class NewDataSet { private AgroMeteoroloskiPodaci[] itemsField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("AgroMeteoroloskiPodaci")] public AgroMeteoroloskiPodaci[] Items { get { return this.itemsField; } set { this.itemsField = value; } } } }
mit
Rhymond/product-compare-react
config/webpackDevServer.config.js
5154
'use strict'; const errorOverlayMiddleware = require('react-error-overlay/middleware'); const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware'); const config = require('./webpack.config.dev'); const paths = require('./paths'); const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; const host = process.env.HOST || '0.0.0.0'; module.exports = function(proxy, allowedHost) { return { // WebpackDevServer 2.4.3 introduced a security fix that prevents remote // websites from potentially accessing local content through DNS rebinding: // https://github.com/webpack/webpack-dev-server/issues/887 // https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a // However, it made several existing use cases such as development in cloud // environment or subdomains in development significantly more complicated: // https://github.com/facebookincubator/create-react-app/issues/2271 // https://github.com/facebookincubator/create-react-app/issues/2233 // While we're investigating better solutions, for now we will take a // compromise. Since our WDS configuration only serves files in the `public` // folder we won't consider accessing them a vulnerability. However, if you // use the `proxy` feature, it gets more dangerous because it can expose // remote code execution vulnerabilities in backends like Django and Rails. // So we will disable the host check normally, but enable it if you have // specified the `proxy` setting. Finally, we let you override it if you // really know what you're doing with a special environment variable. disableHostCheck: !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true', // Enable gzip compression of generated files. compress: true, // Silence WebpackDevServer's own logs since they're generally not useful. // It will still show compile warnings and errors with this setting. clientLogLevel: 'none', // By default WebpackDevServer serves physical files from current directory // in addition to all the virtual build products that it serves from memory. // This is confusing because those files won’t automatically be available in // production build folder unless we copy them. However, copying the whole // project directory is dangerous because we may expose sensitive files. // Instead, we establish a convention that only files in `public` directory // get served. Our build script will copy `public` into the `build` folder. // In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In JavaScript code, you can access it with `process.env.PUBLIC_URL`. // Note that we only recommend to use `public` folder as an escape hatch // for files like `favicon.ico`, `manifest.json`, and libraries that are // for some reason broken when imported through Webpack. If you just want to // use an image, put it in `src` and `import` it from JavaScript instead. contentBase: paths.appPublic, // By default files from `contentBase` will not trigger a page reload. watchContentBase: true, // Enable hot reloading server. It will provide /sockjs-node/ endpoint // for the WebpackDevServer client so it can learn when the files were // updated. The WebpackDevServer client is included as an entry point // in the Webpack development configuration. Note that only changes // to CSS are currently hot reloaded. JS changes will refresh the browser. hot: true, // It is important to tell WebpackDevServer to use the same "root" path // as we specified in the config. In development, we always serve from /. publicPath: config.output.publicPath, // WebpackDevServer is noisy by default so we emit custom message instead // by listening to the compiler events with `compiler.plugin` calls above. quiet: true, // Reportedly, this avoids CPU overload on some systems. // https://github.com/facebookincubator/create-react-app/issues/293 watchOptions: { ignored: /node_modules/, poll: true }, // Enable HTTPS if the HTTPS environment variable is set to 'true' https: protocol === 'https', host: host, overlay: false, historyApiFallback: { // Paths with dots should still use the history fallback. // See https://github.com/facebookincubator/create-react-app/issues/387. disableDotRule: true, }, public: allowedHost, proxy, setup(app) { // This lets us open files from the runtime error overlay. app.use(errorOverlayMiddleware()); // This service worker file is effectively a 'no-op' that will reset any // previous service worker registered for the same host:port combination. // We do this in development to avoid hitting the production cache if // it used the same host and port. // https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432 app.use(noopServiceWorkerMiddleware()); }, }; };
mit
glennjones/hapi-swagger
test/unit/utilities-test.js
9760
const Code = require('@hapi/code'); const Joi = require('joi'); const Lab = require('@hapi/lab'); const Helper = require('../helper.js'); const Utilities = require('../../lib/utilities.js'); const expect = Code.expect; const lab = (exports.lab = Lab.script()); lab.experiment('utilities', () => { lab.test('isObject', () => { expect(Utilities.isObject(function() {})).to.equal(false); expect(Utilities.isObject({})).to.equal(true); expect(Utilities.isObject(Joi.object())).to.equal(true); expect(Utilities.isObject(null)).to.equal(false); expect(Utilities.isObject(undefined)).to.equal(false); expect(Utilities.isObject([])).to.equal(false); expect(Utilities.isObject('string')).to.equal(false); expect(Utilities.isObject(5)).to.equal(false); }); lab.test('isFunction', () => { expect(Utilities.isFunction(function() {})).to.equal(true); expect(Utilities.isFunction({})).to.equal(false); expect(Utilities.isFunction(Joi.object())).to.equal(false); expect(Utilities.isFunction(null)).to.equal(false); expect(Utilities.isFunction(undefined)).to.equal(false); expect(Utilities.isFunction([])).to.equal(false); expect(Utilities.isFunction('string')).to.equal(false); expect(Utilities.isFunction(5)).to.equal(false); }); lab.test('isRegex', () => { expect(Utilities.isRegex(undefined)).to.equal(false); expect(Utilities.isRegex(null)).to.equal(false); expect(Utilities.isRegex(false)).to.equal(false); expect(Utilities.isRegex(true)).to.equal(false); expect(Utilities.isRegex(42)).to.equal(false); expect(Utilities.isRegex('string')).to.equal(false); expect(Utilities.isRegex(function() {})).to.equal(false); expect(Utilities.isRegex([])).to.equal(false); expect(Utilities.isRegex({})).to.equal(false); expect(Utilities.isRegex(/a/g)).to.equal(true); expect(Utilities.isRegex(new RegExp('a', 'g'))).to.equal(true); }); lab.test('hasProperties', () => { expect(Utilities.hasProperties({})).to.equal(false); expect(Utilities.hasProperties({ name: 'test' })).to.equal(true); expect(Utilities.hasProperties(Helper.objWithNoOwnProperty())).to.equal(false); }); lab.test('deleteEmptyProperties', () => { //console.log( JSON.stringify(Utilities.deleteEmptyProperties(objWithNoOwnProperty())) ); expect(Utilities.deleteEmptyProperties({})).to.equal({}); expect(Utilities.deleteEmptyProperties({ name: 'test' })).to.equal({ name: 'test' }); expect(Utilities.deleteEmptyProperties({ name: null })).to.equal({}); expect(Utilities.deleteEmptyProperties({ name: undefined })).to.equal({}); expect(Utilities.deleteEmptyProperties({ name: [] })).to.equal({}); expect(Utilities.deleteEmptyProperties({ name: {} })).to.equal({}); expect(Utilities.deleteEmptyProperties({ example: [], default: [] })).to.equal({ example: [], default: [] }); expect(Utilities.deleteEmptyProperties({ example: {}, default: {} })).to.equal({ example: {}, default: {} }); // this needs JSON.stringify to compare outputs expect(JSON.stringify(Utilities.deleteEmptyProperties(Helper.objWithNoOwnProperty()))).to.equal('{}'); }); lab.test('first', () => { expect(Utilities.first({})).to.equal(undefined); expect(Utilities.first('test')).to.equal(undefined); expect(Utilities.first([])).to.equal(undefined); expect(Utilities.first(['test'])).to.equal('test'); expect(Utilities.first(['one', 'two'])).to.equal('one'); }); lab.test('hasKey', () => { expect(Utilities.hasKey({}, 'x')).to.equal(false); expect(Utilities.hasKey([], 'x')).to.equal(false); expect(Utilities.hasKey(null, 'x')).to.equal(false); expect(Utilities.hasKey(undefined, 'x')).to.equal(false); expect(Utilities.hasKey({ x: 1 }, 'x')).to.equal(true); expect(Utilities.hasKey({ a: { x: 1 } }, 'x')).to.equal(true); expect(Utilities.hasKey({ a: { b: { x: 1 } } }, 'x')).to.equal(true); expect(Utilities.hasKey({ x: 1, z: 2 }, 'x')).to.equal(true); expect(Utilities.hasKey({ xx: 1 }, 'x')).to.equal(false); expect(Utilities.hasKey([{ x: 1 }], 'x')).to.equal(true); expect(Utilities.hasKey({ a: [{ x: 1 }] }, 'x')).to.equal(true); expect(Utilities.hasKey(Helper.objWithNoOwnProperty(), 'x')).to.equal(false); expect(Utilities.hasKey({ a: {} }, 'x')).to.equal(false); }); lab.test('findAndRenameKey', () => { expect(Utilities.findAndRenameKey({}, 'x', 'y')).to.equal({}); expect(Utilities.findAndRenameKey([], 'x', 'y')).to.equal([]); expect(Utilities.findAndRenameKey(null, 'x', 'y')).to.equal(null); expect(Utilities.findAndRenameKey(undefined, 'x', 'y')).to.equal(undefined); expect(Utilities.findAndRenameKey({ x: 1 }, 'x', 'y')).to.equal({ y: 1 }); expect(Utilities.findAndRenameKey({ a: { x: 1 } }, 'x', 'y')).to.equal({ a: { y: 1 } }); expect(Utilities.findAndRenameKey({ a: { b: { x: 1 } } }, 'x', 'y')).to.equal({ a: { b: { y: 1 } } }); expect(Utilities.findAndRenameKey({ x: 1, z: 2 }, 'x', 'y')).to.equal({ y: 1, z: 2 }); expect(Utilities.findAndRenameKey({ xx: 1 }, 'x', 'y')).to.equal({ xx: 1 }); expect(Utilities.findAndRenameKey([{ x: 1 }], 'x', 'y')).to.equal([{ y: 1 }]); expect(Utilities.findAndRenameKey({ a: [{ x: 1 }] }, 'x', 'y')).to.equal({ a: [{ y: 1 }] }); expect(Utilities.findAndRenameKey({ x: 1 }, 'x', null)).to.equal({}); expect(Utilities.findAndRenameKey({ x: 1, z: 2 }, 'x', null)).to.equal({ z: 2 }); expect(Utilities.findAndRenameKey(Helper.objWithNoOwnProperty(), 'x', 'y')).to.equal({}); }); lab.test('replaceValue', () => { expect(Utilities.replaceValue(['a', 'b'], 'a', 'c')).to.equal(['b', 'c']); expect(Utilities.replaceValue(['a', 'b'], null, null)).to.equal(['a', 'b']); expect(Utilities.replaceValue(['a', 'b'], 'a', null)).to.equal(['a', 'b']); expect(Utilities.replaceValue(null, null, null)).to.equal(null); expect(Utilities.replaceValue()).to.equal(undefined); }); lab.test('removeProps', () => { expect(Utilities.removeProps({ a: 1, b: 2 }, ['a'])).to.equal({ a: 1 }); expect(Utilities.removeProps({ a: 1, b: 2 }, ['a', 'b'])).to.equal({ a: 1, b: 2 }); expect(Utilities.removeProps({ a: 1, b: 2 }, ['c'])).to.equal({}); expect(Utilities.removeProps(Helper.objWithNoOwnProperty(), ['b'])).to.equal({}); }); lab.test('isJoi', () => { expect(Utilities.isJoi({})).to.equal(false); expect(Utilities.isJoi(Joi.object())).to.equal(true); expect( Utilities.isJoi( Joi.object({ id: Joi.string() }) ) ).to.equal(true); }); lab.test('hasJoiChildren', () => { expect(Utilities.hasJoiChildren({})).to.equal(false); expect(Utilities.hasJoiChildren(Joi.object())).to.equal(false); expect( Utilities.hasJoiChildren( Joi.object({ id: Joi.string() }) ) ).to.equal(true); }); lab.test('toJoiObject', () => { expect(Joi.isSchema(Utilities.toJoiObject({}))).to.equal(true) expect(Joi.isSchema(Utilities.toJoiObject(Joi.object()))).to.equal(true) }); lab.test('hasJoiMeta', () => { expect(Utilities.hasJoiMeta({})).to.equal(false); expect(Utilities.hasJoiMeta(Joi.object())).to.equal(false); expect(Utilities.hasJoiMeta(Joi.object().meta({ test: 'test' }))).to.equal(true); }); lab.test('getJoiMetaProperty', () => { expect(Utilities.getJoiMetaProperty({}, 'test')).to.equal(undefined); expect(Utilities.getJoiMetaProperty(Joi.object(), 'test')).to.equal(undefined); expect(Utilities.getJoiMetaProperty(Joi.object().meta({ test: 'test' }), 'test')).to.equal('test'); expect(Utilities.getJoiMetaProperty(Joi.object().meta({ test: 'test' }), 'nomatch')).to.equal(undefined); }); lab.test('toTitleCase', () => { expect(Utilities.toTitleCase('test')).to.equal('Test'); expect(Utilities.toTitleCase('tesT')).to.equal('Test'); }); lab.test('createId', () => { expect(Utilities.createId('PUT', 'v1/sum/add/{a}/{b}')).to.equal('putV1SumAddAB'); expect(Utilities.createId('PUT', 'sum')).to.equal('putSum'); }); lab.test('replaceInPath', () => { const pathReplacements = [ { replaceIn: 'all', pattern: /v([0-9]+)\//, replacement: '' }, { replaceIn: 'groups', pattern: /[.].*$/, replacement: '' } ]; expect(Utilities.replaceInPath('api/v1/users', ['endpoints'], pathReplacements)).to.equal('api/users'); expect(Utilities.replaceInPath('api/v2/users', ['groups'], pathReplacements)).to.equal('api/users'); expect(Utilities.replaceInPath('api/users.get', ['groups'], pathReplacements)).to.equal('api/users'); expect(Utilities.replaceInPath('api/users.search', ['groups'], pathReplacements)).to.equal('api/users'); }); lab.test('mergeVendorExtensions', () => { expect(Utilities.assignVendorExtensions({ a: 1, b: 2 }, { 'x-a': 1, 'x-b': 2, c: 3 })).to.equal({ a: 1, b: 2, 'x-a': 1, 'x-b': 2 }); expect(Utilities.assignVendorExtensions({ a: 1, b: 2 }, null)).to.equal({ a: 1, b: 2 }); expect(Utilities.assignVendorExtensions(null, null)).to.equal(null); expect(Utilities.assignVendorExtensions(null, { 'x-a': 1, 'x-b': 2, c: 3 })).to.equal(null); expect(Utilities.assignVendorExtensions({ a: 1, b: 2 }, { 'x-a': 1, 'x-b': null, c: 3 })).to.equal({ a: 1, b: 2, 'x-a': 1, 'x-b': null }); expect(Utilities.assignVendorExtensions({ a: 1, b: 2, 'x-a': 100 }, { 'x-a': 1, 'x-b': 2, c: 3 })).to.equal({ a: 1, b: 2, 'x-a': 1, 'x-b': 2 }); expect(Utilities.assignVendorExtensions({ a: 1, b: 2 }, { 'x-': 1 })).to.equal({ a: 1, b: 2 }); }); });
mit
RichardBangs/SimpleEngine
SimpleEngine/Game/GameManager.cpp
5442
#include "GameManager.h" #include "glew.h" #include "freeglut.h" #include "glm.hpp" #include "Path.h" #include "Renderer\RenderableManager.h" #include "Renderer\Textures\TextureLoader.h" #include "Renderer\Textures\SpriteLoader.h" #include "../Server.h" #include "Simulation\SimulationManager.h" #include "Simulation\GameState.h" #include "Simulation\PlayerState.h" #include "Events\PlayerCreatedEvent.h" #include "Events\ObjectCreatedEvent.h" #include "Events\ObjectDestroyedEvent.h" #include "RequestEvents\RequestEventBase.h" #include "RequestEvents\PlayerCreateRequestEvent.h" #include "Simulation\WorldState.h" #include "Simulation\WorldObjectState.h" #include "WorldObjectTree.h" #include "InputManager.h" #include "World.h" #include "Player.h" #include "glm.hpp" namespace Game { GameManager::GameManager() { InputManager::Create(); const char* cityAtlasPath = "textures\\CitySpriteAtlas.png"; Renderer::SpriteLoader::RegisterAtlas(cityAtlasPath, 16, 16, 1, 1); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 0, 25, "City::Grass-TopLeft"); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 1, 25, "City::Grass-Top"); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 2, 25, "City::Grass-TopRight"); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 0, 26, "City::Grass-MiddleLeft"); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 1, 26, "City::Grass-Middle"); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 2, 26, "City::Grass-MiddleRight"); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 0, 27, "City::Grass-BottomLeft"); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 1, 27, "City::Grass-Bottom"); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 2, 27, "City::Grass-BottomRight"); Renderer::SpriteLoader::RegisterSprite(cityAtlasPath, 34, 13, "City::Tree"); const char* charactersAtlasPath = "textures\\CharactersSpriteAtlas.png"; Renderer::SpriteLoader::RegisterAtlas(charactersAtlasPath, 16, 16, 1, 1); Renderer::SpriteLoader::RegisterSprite(charactersAtlasPath, 0, 17, "Characters::Hero0"); Simulation::ServerManager::Create(); Simulation::ServerManager::Instance().Start(); _world = new World(); _idOfLocalPlayer = 0; Simulation::SimulationManager::Create(); auto requestPlayerCreate = new Simulation::PlayerCreateRequestEvent(); Simulation::SimulationManager::Instance().RequestEvent(requestPlayerCreate); _uuidOfLocalPlayerCreation = requestPlayerCreate->UUID(); //Simulation::SimulationManager::Instance().AddEvent(new Simulation::PlayerCreatedEvent(0, _idOfLocalPlayer)); //Simulation::SimulationManager::Instance().AddEvent(new Simulation::PlayerCreatedEvent(100, 74)); //Simulation::SimulationManager::Instance().AddEvent(new Simulation::ObjectCreatedEvent(0, 0, 1, 1)); //Simulation::SimulationManager::Instance().AddEvent(new Simulation::ObjectCreatedEvent(50, 1, 6, 4)); //Simulation::SimulationManager::Instance().AddEvent(new Simulation::ObjectCreatedEvent(100, 2, 10, 7)); } GameManager::~GameManager() { } void GameManager::OnUpdate(float dt) { // Can be both server, AND client. if (Simulation::ServerManager::Instance().IsServer()) { ServerUpdate(); } if (Simulation::ServerManager::Instance().IsClient()) { ClientUpdate(dt); } } void GameManager::ServerUpdate() { auto messageList = Simulation::ServerManager::Instance().IncomingMessages(); for (auto it = messageList.begin(); it != messageList.end(); ++it) { auto requestEvent = *it; int numPlayers = _players.size(); switch (requestEvent->GetType()) { case Simulation::eRequestEventType::PlayerCreate: Simulation::ServerManager::Instance().AddMessage(new Simulation::PlayerCreatedEvent(Simulation::SimulationManager::Instance().Frame()+1, numPlayers)); _players[numPlayers] = new Player(numPlayers, requestEvent->UUID() == _uuidOfLocalPlayerCreation); break; default: assert("UNIMPLEMENTED RESPONSE FOR REQUEST EVENT"); break; } } Simulation::ServerManager::Instance().ClearIncomingMessages(); } void GameManager::ClientUpdate(float dt) { Simulation::GameState* gameState = Simulation::SimulationManager::Instance().Tick(); // REMOVE OBJECTS FROM VIEW THAT DON'T EXIST IN THE GAME STATE for (auto it = _world->_objects.begin(); it != _world->_objects.end();) { auto myWorldObject = it->second; if (gameState->_world->_objects.count(myWorldObject->_id) == 0) { _world->_objects.erase(it++); delete myWorldObject; } else ++it; } // ADD OBJECTS TO VIEW THAT EXIST IN THE GAME STATE for (auto it = gameState->_players.begin(); it != gameState->_players.end(); ++it) { Simulation::PlayerState* playerState = *it; if (_players.count(playerState->_id) == 0) _players[playerState->_id] = new Player(playerState->_id, playerState->_id == _idOfLocalPlayer); _players[playerState->_id]->UpdateView(playerState, gameState, dt); } for (auto it = gameState->_world->_objects.begin(); it != gameState->_world->_objects.end(); ++it) { Simulation::WorldObjectState* objectState = it->second; if (_world->_objects.count(objectState->_id) == 0) _world->_objects[objectState->_id] = (WorldObject*)new WorldObjectTree(objectState->_id, objectState->_x, objectState->_y); //_world->_objects[objectState->_id]->Update } } void GameManager::OnRender() { } }
mit
Night75/webmixin-2014
src/Night/DisplayBundle/DataFixtures/ORM/LoadWebTechnologiesData.php
2183
<?php namespace Night\DisplayBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Night\DisplayBundle\Entity\Image; use Night\DisplayBundle\Entity\WebTechnology; use Doctrine\Common\DataFixtures\AbstractFixture; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Symfony\Component\DependencyInjection\ContainerInterface; class LoadWebTechonologiesData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface { /** @var ObjectManager */ protected $em; /** @var ContainerInterface */ protected $container; /** * {@inheritDoc} */ public function load(ObjectManager $em) { $this->em = $em; $this->loadBasic('php', 'img-php'); $this->loadBasic('c-sharp', 'img-c-sharp'); $this->loadBasic('css', 'img-css'); $this->loadBasic('html', 'img-html'); $this->loadBasic('html5', 'img-html5'); $this->loadBasic('javascript', 'img-javascript'); $this->loadBasic('jquery', 'img-jquery'); $this->loadBasic('less', 'img-less'); $this->loadBasic('nodejs', 'img-nodejs'); $this->loadBasic('symfony', 'img-symfony'); } protected function loadBasic($name, $imgReference) { $language = new WebTechnology(); $language->setName($name); $this->addReference($name, $language); $imgItem = new Image\ImageWebTechnology(); $imgItem->setImage($this->getReference($imgReference)); $imgItem->setOrder(1); $language->setImageItem($imgItem); $this->em->persist($language); $this->em->flush(); } /** * Sets the Container. * * @param ContainerInterface|null $container A ContainerInterface instance or null * * @api */ public function setContainer(ContainerInterface $container = null) { $this->container = $container; } /** * Get the order of this fixture * * @return integer */ function getOrder() { return 5; } }
mit
itpastorn/webbserverprogrammering-1
html/admin.php
86
<?php /** * Page controler för adminsidan * * Denna ska skapas i kapitel 15 */
mit
Sebram/LANOTE
src/LN/FrontBundle/Controller/DefaultController.php
297
<?php namespace LN\FrontBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction($name) { return $this->render('LNFrontBundle:Default:index.html.twig', array('name' => $name)); } }
mit
pdkhuong/VideoFW
application/models/Editor_box_item_model.php
5593
<?php class Editor_Box_Item_model extends CI_Model { const TABLE_NAME = 'editor_box_item'; const TABLE_KEY = 'id'; static protected $_instance = NULL; static protected $_assoc_columns = array( 'box_id', 'item_text', 'item_link', 'item_thumbnail', 'order', ); function __construct() { parent::__construct(); } /** * * @return Editor_Box_Item_model */ static public function getInstance() { if (self::$_instance === NULL) { self::$_instance = new self(); } return self::$_instance; } function getRange($where = '', $offset = 0, $itemPerPage = 15, $order='') { $orderBy = $order ? ' ORDER BY '.$order : ''; $offset = intval($offset); $limit = intval($itemPerPage); $whereClause = ""; if (!empty($where)) { $whereClause = " WHERE " . $where; } $sql = "SELECT * FROM " . self::TABLE_NAME . $whereClause .$orderBy. " LIMIT $offset,$limit"; $query = $this->db->query($sql); $data = $query->result_array(); return $data; } function getRangeFull($where = '', $offset = 0, $itemPerPage = 15, $order='') { $orderBy = $order ? ' ORDER BY '.$order : ''; $offset = intval($offset); $limit = intval($itemPerPage); $whereClause = ""; if (!empty($where)) { $whereClause = " WHERE " . $where; } $sql = "SELECT editor_box_item.*, editor_box.name as box_name, editor_box.id as box_id FROM editor_box_item LEFT JOIN editor_box ON editor_box_item.box_id = editor_box.id ". $whereClause . $orderBy ." LIMIT $offset,$limit"; $query = $this->db->query($sql); $data = $query->result_array(); return $data; } function getTotal($where = '') { $whereClause = ""; if (!empty($where)) { $whereClause = " WHERE " . $where; } $tableKey = self::TABLE_KEY; $sql = "SELECT COUNT($tableKey) AS total FROM " . self::TABLE_NAME; $sql .= $whereClause; $query = $this->db->query($sql); $result = $query->result_array(); return $result[0]['total']; } function getById($id) { $data = array(); try { $sql = "SELECT * FROM " . self::TABLE_NAME . " WHERE " . self::TABLE_KEY . " = ?"; $query = $this->db->query($sql, array($id)); $data = $query->result_array(); if (isset($data[0])) { $data = $data[0]; } } catch (Exception $ex) { } return $data; } function getByIdFull($id) { $data = array(); try { $sql = "SELECT v.*, vu.id as vuid, vu.streaming_url, vu.type, vu.is_part ". " FROM " . self::TABLE_NAME . ' AS v '. " LEFT JOIN video_url AS vu ON v.id=vu.video_id". " WHERE v." . self::TABLE_KEY . " = ?"; $query = $this->db->query($sql, array($id)); $datas = $query->result_array(); if ($datas) { $videoUrl = array(); foreach($datas as $d){ if($d['streaming_url']){ $videoUrl[$d['vuid']] = array( 'id' => $d['vuid'], 'streaming_url' => $d['streaming_url'], 'type' => $d['type'], 'is_part' => $d['is_part'] ); } } $data = $datas[0]; $data['video_url'] = $videoUrl; } } catch (Exception $ex) { } return $data; } function getByTitle($title){ $title = strtolower($title); $data = array(); try { $sql = "SELECT * FROM " . self::TABLE_NAME . " WHERE LOWER(title) = ?"; $query = $this->db->query($sql, array($title)); $data = $query->result_array(); if (isset($data[0])) { $data = $data[0]; } } catch (Exception $ex) { } return $data; } function insert($params) { try { $params = $this->filterProps($params); $this->db->insert(self::TABLE_NAME, $params); return $this->db->insert_id(); } catch (Exception $ex) { return ERROR_SYSTEM; } } function updateImportStatus($importStatus=0){ $query = "UPDATE ".self::TABLE_NAME." SET import_status={$importStatus}"; $this->db->query($query); } function update($id, $params) { try { $params = $this->filterProps($params); $this->db->update(self::TABLE_NAME, $params, array(self::TABLE_KEY => $id)); return $id; } catch (Exception $ex) { return ERROR_SYSTEM; } } function delete($id) { return $this->db->delete(self::TABLE_NAME, array(self::TABLE_KEY => $id)); } function addVideoToSerie($arrVideoIds, $serieId){ if($arrVideoIds){ $params['series_id'] = $serieId; foreach($arrVideoIds as $videoId){ $this->db->update(self::TABLE_NAME, $params, array(self::TABLE_KEY => $videoId)); } } } function removeSeriesOfVideo($videoId){ $params['series_id'] = 0; $this->db->update(self::TABLE_NAME, $params, array(self::TABLE_KEY => $videoId)); return $result; } function getVideoByOriginalUrl($originalUrl=""){ $data = array(); if(!empty($originalUrl)){ $originalUrl = stripslashes($originalUrl); $whereClause = ' WHERE original_url="'.$originalUrl.'"'; $sql = "SELECT * FROM ".self::TABLE_NAME.$whereClause; $query = $this->db->query($sql); $data = $query->result_array(); if(isset($data[0])){ $data = $data[0]; } } return $data; } private function filterProps($param) { if (!is_array($param)) throw new Exception("Invalid input"); $result = array(); foreach (self::$_assoc_columns as $column) if (isset($param[$column])) $result[$column] = $param[$column]; return $result; } }
mit
Arasaac/dockerizePHPApp
php/inc/herramientas/gestor_pictogramas/listar_palabras_reducido.php
4218
<?php include ('../../../classes/querys/query.php'); $query=new query(); $id_tipo=""; $letra=""; $id_tipo=$_POST['id_tipo']; $letra=$_POST['letra']; /* ******************************************************************************************* */ /* LISTAR PALABRAS */ /* ******************************************************************************************* */ if(!isset($_POST['pg'])){ $pg = "0"; } else { $pg = $_POST['pg']; } $cantidad=10; // cantidad de resultados por p&aacute;gina $inicial = $pg * $cantidad; $contar=$query->listar_diccionario_palabras($id_tipo,$letra); $pegar=$query->listar_diccionario_palabras_limit($id_tipo,$letra,$inicial,$cantidad); $total_records = mysql_num_rows($contar); $pages = intval($total_records / $cantidad); ?> <table cellpadding="0" cellspacing="0" border="0"> <thead> <tr> <th field="Id" dataType="Number">&nbsp;</th> <th align="left" field="Id" dataType="Number">Id</th> <th align="left" field="Name" dataType="String">Palabra</th> <th align="left" dataType="html">Acepcion</th> </tr> </thead> <tbody> <?php $color = 'tablaAlterno1'; while ($entrada = mysql_fetch_array($pegar)) { $color = ($color == 'tablaAlterno1') ? 'tablaAlterno2' : 'tablaAlterno1'; ?> <tr class="<?php echo $color; ?>"> <td><span style="width:500px; height:300px;"> <input type="button" name="Submit2" value="S" onclick="add_palabra('palabra_seleccionada.php','<?php echo $entrada['id_palabra']; ?>','selected_word'); Dialog.closeInfo();" /> </span></td> <td align="left"><?php echo $entrada['id_palabra']; ?></td> <td align="left"><?php echo utf8_encode($entrada['palabra']); ?></td> <td align="left"><div id="palabra_<?php echo $entrada['id_palabra']?>"><?php echo utf8_encode($entrada['definicion']); ?></div></td> </tr> <?php } ?> </tbody> </table> </div> </br> <table width="60%" height="30" border="0" align="center" cellpadding="0" cellspacing="2"> <tr class="textos"> <td width="9%" style="color:#A12B6F; font-family:Georgia, Times New Roman, Times, serif; font-size:12px; text-align:center;"> <input type="button" name="Submit" value="&lt;&lt;" onclick='cargar_div2("listar_palabras_reducido.php","id_tipo="+document.vm_diccionario.tipo_palabra.value+"&letra="+document.vm_diccionario.letra.value+"&pg=0","tabla_palabras");'> </td> <td width="28%" style="color:#A12B6F; font-family:Georgia, Times New Roman, Times, serif; font-size:12px; text-align:center;"><div align="center"><?php if ($_POST['pg'] != 0) { $url = $_POST['pg'] - 1; } ?> <input type="button" name="Submit" value="< Anterior" onclick='cargar_div2("listar_palabras_reducido.php","id_tipo="+document.vm_diccionario.tipo_palabra.value+"&letra="+document.vm_diccionario.letra.value+"&pg=<?php echo $url ?>","tabla_palabras");'> </div></td> <td width="28%" style="color:#A12B6F; font-family:Georgia, Times New Roman, Times, serif; font-size:12px; text-align:center;">&nbsp;</td> <td width="26%" style="color:#A12B6F; font-family:Georgia, Times New Roman, Times, serif; font-size:12px; text-align:center;"><div align="center"><?php if ($_POST['pg'] < $pages) { $url = $_POST['pg'] + 1; } ?> <input type="button" name="Submit" value="Siguiente >" onclick='cargar_div2("listar_palabras_reducido.php","id_tipo="+document.vm_diccionario.tipo_palabra.value+"&letra="+document.vm_diccionario.letra.value+"&pg=<?php echo $url ?>","tabla_palabras");'> </div></td> <td width="9%" style="color:#A12B6F; font-family:Georgia, Times New Roman, Times, serif; font-size:12px; text-align:center;"><input type="button" name="button" value="&gt;&gt;" onclick='cargar_div2("listar_palabras_reducido.php","id_tipo="+document.vm_diccionario.tipo_palabra.value+"&letra="+document.vm_diccionario.letra.value+"&pg=<?php echo $pages; ?>","tabla_palabras");'></td> </tr> </table>
mit
vincentremond/OKTM
src/OverkillTaskManager.Web/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs
383
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; namespace OverkillTaskManager.Web.Models.ManageViewModels { public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<SelectListItem> Providers { get; set; } } }
mit
mitdbg/modeldb
webapp/client/src/features/highLevelSearch/view/SearchResults/Filters/Filters.tsx
2453
import cn from 'classnames'; import * as React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators, Dispatch } from 'redux'; import { Entities, ActiveFilter, IEntitiesResults, } from 'shared/models/HighLevelSearch'; import matchType from 'shared/utils/matchType'; import { actions } from '../../../store'; import styles from './Filters.module.css'; import { IApplicationState } from 'setup/store/store'; interface ILocalProps { entitiesResults: IEntitiesResults; activeFilter: ActiveFilter; } const mapStateToProps = (state: IApplicationState) => ({ isEnableRepositories: true, }); const mapDispatchToProps = (dispatch: Dispatch) => { return bindActionCreators( { setFilter: actions.setFilter, }, dispatch ); }; type AllProps = ILocalProps & ReturnType<typeof mapDispatchToProps> & ReturnType<typeof mapStateToProps>; const Filters = ({ entitiesResults, activeFilter, setFilter, isEnableRepositories, }: AllProps) => { const filteredEntities = Object.values(Entities).filter(type => matchType( { projects: () => true, experiments: () => true, experimentRuns: () => true, datasets: () => true, repositories: () => isEnableRepositories, }, type ) ); return ( <div className={styles.root}> {filteredEntities.map(type => ( <div className={cn(styles.filter, { [styles.active]: type === activeFilter, })} key={type} onClick={type !== activeFilter ? () => setFilter(type) : undefined} > <span className={styles.filter__name}> {matchType( { projects: () => 'Projects', experiments: () => 'Experiments', experimentRuns: () => 'Experiment runs', datasets: () => 'Datasets', repositories: () => 'Repositories', }, type )} </span> <span className={styles.filter__totalCount}> {(() => { if (entitiesResults[type].communication.isRequesting) { return '...'; } else { return entitiesResults[type].data.totalCount; } })()} </span> </div> ))} </div> ); }; export default connect( mapStateToProps, mapDispatchToProps )(Filters);
mit
freak3dot/we-jit
js/util.js
543
/** * Reserved for future use * @param text string Language to translate * @return string Translated string */ function gettext(text){ return text; } /** * http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript * @return string Random String */ function makeId(){ var text = '', possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for(var i=0; i < 10; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; }
mit
TelerikAcademy/ASP.NET-MVC
resources/05. ASP.NET-Web-Security/Demo/XSS-LiveDemo/DemoBadPerson/TelerikAcademy.ForumSystem.Data.Model/Hack.cs
330
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TelerikAcademy.ForumSystem.Data.Model.Abstracts; namespace TelerikAcademy.ForumSystem.Data.Model { public class Hack : DataModel { public string Cookie { get; set; } } }
mit
csecapstone485organization/ddf-mobile
App/components/MapResults.js
5703
import React, { PropTypes, Component } from 'react' import { Text, View, Platform, ListView, StyleSheet, Dimensions, TouchableHighlight } from 'react-native' import { Actions } from 'react-native-router-flux' import store from '../store/store' import MapView from 'react-native-maps'; import { cql_TEST_RESULTS } from '../constants/MockData.js' var {height, width} = Dimensions.get('window') export default class MapResults extends Component { constructor() { super() this.mapRef = null this.coordinateList = [] } componentDidMount() { let coordinates = [] for (coordinate of this.coordinateList) { coordinates.push(coordinate.latlng); } var tempMapRef = this.mapRef; setTimeout(function(){tempMapRef.fitToCoordinates( coordinates, { edgePadding: { top: 10, right: 10, bottom: 10, left: 10 }, animated: true } );}, 1000); } render() { for(result of cql_TEST_RESULTS.results) { if(result.metacard.geometry !== null && result.properties !== null) { this.coordinateList.push( { latlng: { latitude: result.metacard.geometry.coordinates[1], longitude: result.metacard.geometry.coordinates[0] }, title: result.metacard.properties.title, description: result.metacard.properties.created } ) } } const MapMarker = (props) => { const onPress = (resultId) => { this.props.onResultSelection(resultId); Actions.detailsPage(); // TODO: Replace when actual result object passed in from DDF // onResultSelection(result.id); } return ( <MapView.Marker key={props.id} coordinate={props.marker.latlng} title={props.marker.title} description={props.marker.description} > <MapView.Callout tooltip style={styles.callout}> <View style={[styles.calloutContainer, props.style]}> <TouchableHighlight onPress={() => onPress(props.marker.title)} underlayColor='transparent'> <View style={styles.bubble}> <View style={styles.amount}> <Text style={styles.calloutHeaderText} numberOfLines={1} ellipsizeMode={'tail'}>{props.marker.title}</Text> <Text style={styles.calloutDescriptionText}>{props.marker.description}</Text> </View> </View> </TouchableHighlight> <View style={styles.arrowBorder} /> <View style={styles.arrow} /> </View> </MapView.Callout> </MapView.Marker> ) } const styles = StyleSheet.create({ container: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'flex-end', alignItems: 'center', marginBottom:40 }, map: { width: width, height: height }, pushDown: { marginTop: (Platform.OS === 'ios') ? 20 : 0 }, callout: { width: 140, height: 100, }, calloutContainer: { flexDirection: 'column', alignSelf: 'flex-start', }, calloutHeaderText: { fontSize: 18, }, calloutDescriptionText: { }, bubble: { width: 300, flexDirection: 'row', alignSelf: 'center', backgroundColor: 'white', paddingHorizontal: 12, paddingVertical: 12, borderRadius: 6, borderColor: 'white', borderWidth: 0.5, marginTop: 32, }, amount: { flex: 1, }, arrow: { backgroundColor: 'transparent', borderWidth: 16, borderColor: 'transparent', borderTopColor: 'white', alignSelf: 'center', marginTop: -32, }, arrowBorder: { backgroundColor: 'transparent', borderWidth: 16, borderColor: 'transparent', borderTopColor: 'white', alignSelf: 'center', marginTop: -0.5, }, closeButton: { }, closeButtonText: { padding: 5, fontSize: 18, color: 'blue', textAlign: 'right', fontWeight: '300', }, modalHeader: { flexDirection: 'row', }, modalHeaderSection: { flexGrow: 2, }, }); const mapData = { //List of markers markers:this.coordinateList } return( <View style={styles.container}> <MapView style={styles.map} //===========Adding Component here============ /*Variable Description mapType change string "standard", "hybird", "satellite", and "terrain" */ mapType="standard" showsUserLocation={true} followUserLocation={false} showsCompass={false} showsPointOfInterest={false} //Required to render map region={mapData.region} ref={(ref) => {this.mapRef = ref}} > {mapData.markers.map((marker, i) => ( <MapMarker id={i} marker={marker} onResultSelection={this.props.onResultSelection} mapData={mapData} /> ))} </MapView> </View> ) } }
mit
minero/minero-go
config/doc.go
828
// Package config defines a parser and a handler for minero's simple configuration file format. // // Properties: // - Less verbose than JSON. // - Simpler than YAML. // - Easy parsing. // - Indentation based. // // Notes on Indentation: // - Spaces and tabs are equivalent here. Examples: // " \t" == "\t\t " // true // " " == "\t\t\t" // true // - You can mix both, although it's not recomended. // - Indentation level is computed using: level = num_tabs + num_spaces. // // Example input: // // a: // b: // c: 2 // d: 3 // e: // f: 5 // g: // h: 7 // // After parsing produces: // // var config = Map{ // "a.b.c": "2", // "a.b.d": "3", // "a.e.f": "5", // "g.h": "7" // } // // Online config tester: http://play.golang.org/p/FP9hHDBjnN package config
mit
mmig/mmir-starter-kit
www/mmirf/env/media/webMicLevels.js
20402
/** * MicLevelsAnalysis is a plugin/module for generating "microphone input levels changed events" for * ASR (speech recognition) modules based on Web Audio Input (i.e. analyze audio from getUserMedia) * * The plugin triggers events <code>miclevelchanged</code> on listeners registered to the MediaManager. * * In addition, if the mic-levels-audio plugin starts its own audio-stream, an <code>webaudioinputstarted</code> * event is trigger, when the plugin starts. * * @example * * //////////////////////////////// within media plugin: load analyzer ////////////////////////////////// * //within audio-input plugin that uses Web Audio: load mic-levels-analyzer plugin * * //first: check, if the analyzer plugin is already loaded (should be loaded only once) * if(!mediaManager.micLevelsAnalysis){ * * //set marker so that other plugins may know that the analyzer will be loaded: * mediaManager.micLevelsAnalysis = true; * * //load the analyzer * mediaManager.loadFile(micLevelsImplFile, function success(){ * * //... finish the audio-plugin initialization, e.g. invoke initializer-callback * * }, function error(err){ * * // ... in case the analyzer could not be loaded: * // do some error handling ... * * //... and supply a stub-implementation for the analyzer module: * mediaManager.micLevelsAnalysis = { * _active: false, * start: function(){ * console.info('STUB::micLevelsAnalysis.start()'); * }, * stop: function(){ * console.info('STUB::micLevelsAnalysis.stop()'); * }, * enable: function(enable){ * console.info('STUB::micLevelsAnalysis.enable('+(typeof enable === 'undefined'? '': enable)+') -> false'); * return false;//<- the stub can never be enabled * }, * active: function(active){ * this._active = typeof active === 'undefined'? this._active: active; * console.info('STUB::micLevelsAnalysis.active('+(typeof active === 'undefined'? '': active)+') -> ' + this._active); * return active;//<- must always return the input-argument's value * } * }; * * //... finish the audio-plugin initialization without the mic-levels-analyzer, e.g. invoke initializer-callback * * }); * } else { * * //if analyzer is already loaded/loading: just finish the audio-plugin initialization, * // e.g. invoke initializer-callback * * } * * * //////////////////////////////// use of mic-levels-analysis events ////////////////////////////////// * //in application code: listen for mic-level-changes * * mmir.MediaManager.on('miclevelchange', function(micValue){ * * }); * * @class * @public * @name MicLevelsAnalysis * @memberOf mmir.env.media * * @see {@link mmir.env.media.WebspeechAudioInput} for an example on integrating the mic-levels-analysis plugin into an audio-input plugin * * @requires HTML5 AudioContext * @requires HTML5 getUserMedia (audio) */ define(['mmirf/mediaManager'], function(mediaManager){ /** @class MicLevelsAnalysis */ return { /** @memberOf MicLevelsAnalysis.module# */ initialize: function(callBack, __mediaManager){//, ctxId, moduleConfig){//DISABLED this argument is currently un-used -> disabled /** * @type navigator * @memberOf MicLevelsAnalysis# */ var html5Navigator = navigator; /** * @type AudioContext * @memberOf MicLevelsAnalysis# */ var _audioContext; /** @memberOf MicLevelsAnalysis# */ var createAudioContext = function(){ if(typeof AudioContext !== 'undefined'){ _audioContext = new AudioContext; } else {//if(typeof webkitAudioContext !== 'undefined'){ _audioContext = new webkitAudioContext; } }; var nonFunctional = false; try { // unify the different kinds of HTML5 implementations //window.AudioContext = window.AudioContext || window.webkitAudioContext; /** @memberOf MicLevelsAnalysis.navigator# */ html5Navigator.__getUserMedia = html5Navigator.getUserMedia || html5Navigator.webkitGetUserMedia || html5Navigator.mozGetUserMedia; //window.URL = window.URL || window.webkitURL; // _audioContext = new webkitAudioContext; // createAudioContext(); } catch (e) { console.error('No web audio support in this browser! Error: '+(e.stack? e.stack : e)); nonFunctional = true; } /** * state-flag that indicates, if the process (e.g. ASR, recording) * is actually active right now, i.e. if analysis calculations should be done or not. * * @memberOf MicLevelsAnalysis# */ var recording = false; /** * Switch for generally disabling "microphone-level changed" calculations * (otherwise calculation becomes active/inactive depending on whether or * not a listener is registered to event {@link #MIC_CHANGED_EVT_NAME}) * * <p> * TODO make this configurable?... * * @memberOf MicLevelsAnalysis# */ var isMicLevelsEnabled = true; /** MIC-LEVELS: the maximal value to occurs in the input data * <p> * FIXME verify / check if this is really the maximal possible value... * @contant * @memberOf MicLevelsAnalysis# */ var MIC_MAX_VAL = 2;// /** MIC-LEVELS: the maximal value for level changes (used for normalizing change-values) * @constant * @memberOf MicLevelsAnalysis# */ var MIC_MAX_NORM_VAL = -90;// -90 dB ... ??? /** MIC-LEVELS: normalization factor for values: adjust value, so that is * more similar to the results from the other input-modules * @constant * @memberOf MicLevelsAnalysis# */ var MIC_NORMALIZATION_FACTOR = 3.5;//adjust value, so that is more similar to the results from the other input-modules /** MIC-LEVELS: time interval / pauses between calculating level changes * @constant * @memberOf MicLevelsAnalysis# */ var MIC_QUERY_INTERVALL = 48; /** MIC-LEVELS: threshold for calculating level changes * @constant * @memberOf MicLevelsAnalysis# */ var LEVEL_CHANGED_THRESHOLD = 1.05; /** * MIC-LEVELS: Name for the event that is emitted, when the input-mircophone's level change. * * @private * @constant * @default "miclevelchanged" * @memberOf MicLevelsAnalysis# */ var MIC_CHANGED_EVT_NAME = 'miclevelchanged'; /** * STREAM_STARTED: Name for the event that is emitted, when the audio input stream for analysis becomes available. * * @private * @constant * @default "webaudioinputstarted" * @memberOf MicLevelsAnalysis# */ var STREAM_STARTED_EVT_NAME = 'webaudioinputstarted'; /** * HELPER normalize the levels-changed value to MIC_MAX_NORM_VAL * @deprecated currently un-used * @memberOf MicLevelsAnalysis# */ var normalize = function (v){ return MIC_MAX_NORM_VAL * v / MIC_MAX_VAL; }; /** * HELPER calculate the RMS value for list of audio values * @deprecated currently un-used * @memberOf MicLevelsAnalysis# */ var getRms = function (buffer, size){ if(!buffer || size === 0){ return 0; } var sum = 0, i = 0; for(; i < size; ++i){ sum += buffer[i]; } var avg = sum / size; var meansq = 0; for(i=0; i < size; ++i){ meansq += Math.pow(buffer[i] - avg, 2); } var avgMeansq = meansq / size; return Math.sqrt(avgMeansq); }; /** * HELPER calculate the dezible value for PCM value * @deprecated currently un-used * @memberOf MicLevelsAnalysis# */ var getDb = function (pcmData, upperLimit){ return 20 * Math.log10(Math.abs(pcmData)/upperLimit); }; /** * HELPER determine if a value has change in comparison with a previous value * (taking the LEVEL_CHANGED_THRESHOLD into account) * @memberOf MicLevelsAnalysis# */ var hasChanged = function(value, previousValue){ var res = typeof previousValue === 'undefined' || Math.abs(value - previousValue) > LEVEL_CHANGED_THRESHOLD; return res; }; /** * @type LocalMediaStream * @memberOf MicLevelsAnalysis# * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_API#LocalMediaStream */ var _currentInputStream; /** * @type AnalyserNode * @memberOf MicLevelsAnalysis# * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode */ var _audioAnalyzer; var _ownsInputStream = true; //FIXME test // window.RAW_DATA = []; // window.DB_DATA = []; // window.RMS_DATA = []; /** * HELPER callback for getUserMedia: creates the microphone-levels-changed "analyzer" * and fires mic-levels-changed events for registered listeners * @param {LocalMediaStream} inputstream * @memberOf MicLevelsAnalysis# */ function _startUserMedia(inputstream, foreignAudioData){ mediaManager._log.info('MicLevelsAnalysis: start analysing audio input...'); var buffer = 0; // var prevDb; var prevRms; //we only need one analysis: if there is one active from a previous start // -> do stop it, before storing the new inputstream in _currentInputStream if(_currentInputStream){ _stopAudioAnalysis(); } _currentInputStream = inputstream; if(_isAnalysisCanceled === true){ //ASR was stopped, before the audio-stream for the analysis became available: // -> stop analysis now, since ASR is not active (and close the audio stream without doing anything) _stopAudioAnalysis(); return;//////////////// EARLY EXIT ////////////////////// } var inputNode; if(!foreignAudioData){ _ownsInputStream = true; if(!_audioContext){ createAudioContext(); } inputNode = _audioContext.createMediaStreamSource(_currentInputStream); //fire event STREAM_STARTED to inform listeners & allow them to use the audio stream mediaManager._fireEvent(STREAM_STARTED_EVT_NAME, [inputNode, _audioContext]); } else { _ownsInputStream = false; _currentInputStream = true; inputNode = foreignAudioData.inputSource; _audioContext = foreignAudioData.audioContext; } ///////////////////// VIZ /////////////////// // recorder = recorderInstance; _audioAnalyzer = _audioContext.createAnalyser(); _audioAnalyzer.fftSize = 2048; _audioAnalyzer.minDecibels = -90; _audioAnalyzer.maxDecibels = 0; _audioAnalyzer.smoothingTimeConstant = 0.8;//NOTE: value 1 will smooth everything *completely* -> do not use 1 inputNode.connect(_audioAnalyzer); // audioRecorder = new Recorder( _currentInputStream ); // recorder = new Recorder(_currentInputStream, {workerPath: recorderWorkerPath}); // updateAnalysers(); var updateAnalysis = function(){ if(!_currentInputStream){ return; } var size = _audioAnalyzer.fftSize;//.frequencyBinCount;// var data = new Uint8Array(size);//new Float32Array(size);// _audioAnalyzer.getByteTimeDomainData(data);//.getFloatFrequencyData(data);//.getByteFrequencyData(data);//.getFloatTimeDomainData(data);// // var view = new DataView(data.buffer); var MAX = 255;//32768; var MIN = 0;//-32768; var min = MAX;//32768; var max = MIN;//-32768; var total = 0; for(var i=0; i < size; ++i){ var datum = Math.abs(data[i]); //FIXM TEST // mediaManager._log.d('data '+(20 * Math.log10(data[i]/MAX)));//+view.getInt16(i)); // mediaManager._log.d('data '+view.getInt16(i)); // mediaManager._log.d('data '+data[i]); // window.RAW_DATA.push(data[i]); // window.DB_DATA.push(20 * Math.log10(data[i]/MAX)); // window.RMS_DATA.push(''); if (datum < min) min = datum; if (datum > max) max = datum; total += datum; } var avg = total / size; // mediaManager._log.debug('audio ['+min+', '+max+'], avg '+avg); // var rms = getRms(data, size); // var db = 20 * Math.log(rms);// / 0.0002); // mediaManager._log.debug('audio rms '+rms+', db '+db); /* RMS stands for Root Mean Square, basically the root square of the * average of the square of each value. */ var rms = 0, val; for (var i = 0; i < data.length; i++) { val = data[i] - avg; rms += val * val; } rms /= data.length; rms = Math.sqrt(rms); // window.RMS_DATA[window.RMS_DATA.length-1] = rms;//FIXME TEST // var db = 20 * Math.log10(Math.abs(max)/MAX); // var db = rms; // mediaManager._log.debug('audio rms '+rms); // mediaManager._log.debug('audio rms changed: '+prevDb+' -> '+db); //actually fire the change-event on all registered listeners: if(hasChanged(rms, prevRms)){ prevRms = rms; // //adjust value // db *= MIC_NORMALIZATION_FACTOR; db = 20 * Math.log10(Math.abs(max)/MAX); //mediaManager._log.debug('audio rms changed ('+db+'): '+prevRms+' -> '+rms); mediaManager._fireEvent(MIC_CHANGED_EVT_NAME, [db, rms]); } if(_isAnalysisActive && _currentInputStream){ setTimeout(updateAnalysis, MIC_QUERY_INTERVALL); } }; updateAnalysis(); ///////////////////// VIZ /////////////////// } /** internal flag: is/should mic-levels analysis be active? * @memberOf MicLevelsAnalysis# */ var _isAnalysisActive = false; /** internal flag: is/should mic-levels analysis be active? * @memberOf MicLevelsAnalysis# */ var _isAnalysisCanceled = false; /** HELPER start-up mic-levels analysis (and fire events for registered listeners) * @memberOf MicLevelsAnalysis# */ function _startAudioAnalysis(audioInputData){ if(_isAnalysisActive === true){ return; } _isAnalysisCanceled = false; _isAnalysisActive = true; if(audioInputData){ //use existing input stream for analysis: _startUserMedia(null, audioInputData); } else { //start analysis with own audio input stream: html5Navigator.__getUserMedia({audio: true}, _startUserMedia, function(e) { mediaManager._log.error("MicLevelsAnalysis: failed _startAudioAnalysis, error for getUserMedia ", e); _isAnalysisActive = false; }); } } /** HELPER stop mic-levels analysis * @memberOf MicLevelsAnalysis# */ function _stopAudioAnalysis(){ if(_ownsInputStream){ if(_currentInputStream){ var stream = _currentInputStream; _currentInputStream = void(0); //DISABLED: MediaStream.stop() is deprecated -> instead: stop all tracks individually // stream.stop(); try{ if(stream.active){ var list = stream.getTracks(), track; for(var i=list.length-1; i >= 0; --i){ track = list[i]; if(track.readyState !== 'ended'){ track.stop(); } } } } catch (err){ mediaManager._log.error('MicLevelsAnalysis: a problem occured while stopping audio input analysis: '+(e.stack? e.stack : e)); } _isAnalysisCanceled = false; _isAnalysisActive = false; mediaManager._log.info('MicLevelsAnalysis: stopped analysing audio input!'); } else if(_isAnalysisActive === true){ mediaManager._log.warn('MicLevelsAnalysis: stopped analysing audio input process, but no valid audio stream present!'); _isAnalysisCanceled = true; _isAnalysisActive = false; } } else {//input stream is owned by external creator: just set internal flag for stopping analysis _currentInputStream = void(0);//remove foreign inputStream _audioContext = void(0);//remove foreign audioContext _isAnalysisCanceled = false; _isAnalysisActive = false; } } /** HELPER determine whether to start/stop audio-analysis based on * listeners getting added/removed on the MediaManager * @memberOf MicLevelsAnalysis# */ function _updateMicLevelAnalysis(actionType, handler){ //start analysis now, if necessary if( actionType === 'added' && recording === true && _isAnalysisActive === false && isMicLevelsEnabled === true ){ _startAudioAnalysis(); } //stop analysis, if there is no listener anymore else if(actionType === 'removed' && _isAnalysisActive === true && mediaManager.hasListeners(MIC_CHANGED_EVT_NAME) === false ){ _stopAudioAnalysis(); } } //observe changes on listener-list for mic-levels-changed-event mediaManager._addListenerObserver(MIC_CHANGED_EVT_NAME, _updateMicLevelAnalysis); callBack({micLevelsAnalysis: { /** * Start the audio analysis for generating "microphone levels changed" events. * * This functions should be called, when ASR is starting / receiving the audio audio stream. * * * When the analysis has started, listeners of the <code>MediaManager</code> for * event <code>miclevelchanged</code> will get notified, when the mic-levels analysis detects * changes in the microphone audio input levels. * * @param {AudioInputData} [audioInputData] * If provided, the analysis will use these audio input objects instead * of creating its own audio-input via <code>getUserMedia</code>. * The AudioInputData object must have 2 properties: * { * inputSource: MediaStreamAudioSourceNode (HTML5 Web Audio API) * audioContext: AudioContext (HTML5 Web Audio API) * } * If this argument is omitted, then the analysis will create its own * audio input stream via <code>getUserMedia</code> * * @memberOf MicLevelsAnalysis.prototype */ start: function(audioInputData){ if(isMicLevelsEnabled){//same as: this.enabled() _startAudioAnalysis(audioInputData); } }, /** * Stops the audio analysis for "microphone levels changed" events. * * This functions should be called, when ASR has stopped / closed the audio input stream. * * @memberOf MicLevelsAnalysis.prototype */ stop: function(){ _stopAudioAnalysis(); }, /** * Get/set the mic-level-analysis' enabled-state: * If the analysis is disabled, then {@link #start} will not active the analysis (and currently running * analysis will be stopped). * * This function is getter and setter: if an argument <code>enable</code> is provided, then the * mic-level-analysis' enabled-state will be set, before returning the current value of the enabled-state * (if omitted, just the enabled-state will be returned) * * @param {Boolean} [enable] OPTIONAL * if <code>enable</code> is provided, then the mic-level-analysis' enabled-state * is set to this value. * @returns {Boolean} * the mic-level-analysis' enabled-state * * @memberOf MicLevelsAnalysis.prototype */ enabled: function(enable){ if(typeof enable !== 'undefined'){ if(!enable && (isMicLevelsEnabled != enable || _isAnalysisActive)){ this.stop(); } isMicLevelsEnabled = enable; } return isMicLevelsEnabled; }, /** * Getter/Setter for ASR-/recording-active state. * * This function should be called with <code>true</code> when ASR starts and * with <code>false</code> when ASR stops. * * * NOTE setting the <code>active</code> state allows the analyzer to start * processing when a listener for <code>miclevelchanged</code> is added while * ASR/recording is already active (otherwise the processing would not start * immediately, but when the ASR/recording is started the next time). * * * @param {Boolean} [active] * if <code>active</code> is provided, then the mic-level-analysis' (recording) active-state * is set to this value. * @returns {Boolean} * the mic-level-analysis' (recording) active-state. * If argument <code>active</code> was supplied, then the return value will be the same * as this input value. * * @memberOf MicLevelsAnalysis.prototype */ active: function(active){ if(typeof active !== 'undefined'){ recording = active; } return recording; } }}) } }; });//END define
mit
iwagaki/GPUMonitor
GPUMonitor/Form1.cs
14318
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing.Imaging; using System.Runtime.InteropServices; using OpenCvSharp; using OpenCvSharp.Extensions; using System.IO; using System.Diagnostics; using System.Threading; using System.Xml; using System.Xml.Schema; namespace GPUMonitor { public partial class Form1 : Form { System.Threading.Thread t = null; public Bitmap capturedScreen; private Bitmap bmp; private Graphics g; private Bitmap icon; private Bitmap obj0; private Bitmap obj1; string score = ""; string key = null; private Object thisLock = new Object(); private State threadState = new State(); private Bitmap lastBitmap = null; private string targetAppName = null; public class ImageObject { private string objectName = null; private Rectangle rect; private Bitmap bitmap; private double scoreThreshold; private static Graphics parentGraphics; private static Bitmap parentBitmap; private static string debugScore; private static Bitmap debugBitmap; static public void setParent(Graphics graphics, Bitmap bitmap, string score, Bitmap lastBitmap) { parentBitmap = bitmap; parentGraphics = graphics; debugScore = score; // TODO debugBitmap = lastBitmap; } static public ImageObject create(string objectName, Rectangle rectOnParent, double scoreThreshold, string path) { ImageObject obj = new ImageObject(); obj.objectName = objectName; obj.rect = rectOnParent; obj.scoreThreshold = scoreThreshold; obj.bitmap = new Bitmap(path); return obj; } public bool findImageInScreen(Object lockObject, bool update = true) { captureScreen(); return findImageIn(parentBitmap, lockObject, update); } public bool findImageIn(Bitmap targetBitmap, Object lockObject, bool update) { Bitmap croppedScreenBitmap = parentBitmap.Clone(rect, parentBitmap.PixelFormat); IplImage screenImage = BitmapConverter.ToIplImage(croppedScreenBitmap); IplImage targetImage = BitmapConverter.ToIplImage(targetBitmap); CvSize resSize = new CvSize(screenImage.Width - targetImage.Width + 1, screenImage.Height - targetImage.Height + 1); IplImage resImg = Cv.CreateImage(resSize, BitDepth.F32, 1); Cv.MatchTemplate(screenImage, targetImage, resImg, MatchTemplateMethod.SqDiffNormed); double minVal; double maxVal; CvPoint minLoc; CvPoint maxLoc; Cv.MinMaxLoc(resImg, out minVal, out maxVal, out minLoc, out maxLoc); string val = minVal.ToString("0.00000"); debugScore = val; lock (lockObject) { if (update) debugBitmap = croppedScreenBitmap; if ((minVal < scoreThreshold)) { if (update) { Graphics g = Graphics.FromImage(croppedScreenBitmap); g.DrawRectangle(new Pen(Color.Red, 2), new Rectangle(minLoc.X, minLoc.Y, targetImage.Width, targetImage.Height)); } return true; } return false; } } private void captureScreen() { parentGraphics.CopyFromScreen(new Point(rect.Left, rect.Top), new Point(rect.Left, rect.Top), rect.Size); } } public Form1() { InitializeComponent(); // this.TopMost = true; string xmlPath = "config.xml"; XmlDocument configXml = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; settings.ValidationType = ValidationType.DTD; XmlReader reader = XmlReader.Create(xmlPath, settings); try { configXml.Load(reader); } catch (XmlSchemaValidationException e) { MessageBox.Show(e.Message, "Illigal setting in config.xml", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception e) { MessageBox.Show(e.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } targetAppName = configXml.SelectSingleNode("/configuration/application/processname").InnerText; bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); g = Graphics.FromImage(bmp); icon = new Bitmap(@"icon.bmp"); XmlNodeList nodes = configXml.SelectNodes("/configuration/objects/object"); obj0 = new Bitmap(nodes[0].SelectSingleNode("file").InnerText); // casting_icon.bmp obj1 = new Bitmap(nodes[1].SelectSingleNode("file").InnerText); // hp_bar.bmp } private delegate void threadObject(); private void reset(threadObject func) { stop(); threadState.setState(State.threadState.ACTIVE); t = new System.Threading.Thread(new System.Threading.ThreadStart(func)); t.Start(); } private void stop() { if (t != null) { threadState.setState(0); t.Join(); } } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { g.Dispose(); } private void Form1_Load(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { #if false MODI.Document doc = new MODI.Document(); doc.Create(@"test.bmp"); doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false); StringBuilder str = new StringBuilder(); for (int i = 0; i < doc.Images.Count; i++) { MODI.Image img = (MODI.Image)doc.Images[i]; MODI.Layout layout = img.Layout; Console.WriteLine(layout.Text); Console.WriteLine(); for (int j = 0; j < layout.Words.Count; j++) { MODI.Word word = (MODI.Word)layout.Words[j]; str.Append("[" + word.Text + "]"); } } StreamWriter outfile = new StreamWriter(@"ocr.txt"); outfile.Write(str.ToString()); outfile.Close(); #endif } // timer1 object is placed in Form1.cs (Design) private void timer1_Tick(object sender, EventArgs e) { string appName = GetActiveApplicationName(); label1.Text = appName; label2.Text = score; //Rectangle rect = new Rectangle(1000, 850, 100, 100); //g.CopyFromScreen(new Point(rect.Left, rect.Top), new Point(rect.Left, rect.Top), rect.Size); //Bitmap croppedScreenBitmap = screenBitmap.Clone(searchRect, screenBitmap.PixelFormat); //lastBitmap = croppedScreenBitmap; //Rectangle rect = Screen.PrimaryScreen.Bounds; //bmp = new Bitmap(rect.Width, rect.Height); //Graphics g = Graphics.FromImage(bmp); //g.CopyFromScreen(rect.X, rect.Y, 0, 0, rect.Size); //lastBitmap = bmp; // pictureBox1.Image = lastBitmap; if (lastBitmap != null) { lock(thisLock) { pictureBox1.Image = lastBitmap; lastBitmap = null; } } if (appName == targetAppName) { threadState.setState(State.threadState.ACTIVE); lock(thisLock) { if (key != null) { SendKeys.Send(key); key = null; } } } else { threadState.setState(State.threadState.SUSPENDED); } } class State { public enum threadState {EXIT, SUSPENDED, ACTIVE }; private threadState state = threadState.EXIT; private Object stateLock = new Object(); public void setState(threadState state) { lock (stateLock) { this.state = state; } } public bool waitState() { while (true) { lock (stateLock) { if (state == threadState.EXIT) return true; if (state == threadState.ACTIVE) return false; } Thread.Sleep(500); } } } private void macro1() { mainLoop(false); } private void macro2() { mainLoop(true); } private void mainLoop(bool isNegative) { Console.WriteLine("INFO: Thread has been started"); while (true) { if (threadState.waitState()) return; while (true) { if (threadState.waitState()) return; if (findTemplate(obj0, new Rectangle(1000, 850, 100, 100), 0.05)) { lock (thisLock) { key = "8"; } break; } Thread.Sleep(500); } Thread.Sleep(1000); if (findTemplate(obj0, new Rectangle(1000, 850, 100, 100), 0.05)) continue; Thread.Sleep(5000); while (true) { if (threadState.waitState()) return; if (findTemplate(obj0, new Rectangle(1000, 850, 100, 100), 0.05, false)) break; if (isNegative ^ findTemplate(obj1, new Rectangle(908, 410, 100, 200), 0.0005)) { lock (thisLock) { key = "8"; } break; } Thread.Sleep(100); } Thread.Sleep(500); } } private bool findTemplate(Bitmap image, Rectangle rect, double th, bool update = true) { g.CopyFromScreen(new Point(rect.Left, rect.Top), new Point(rect.Left, rect.Top), rect.Size); return findImage(bmp, image, rect, th, update); } [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); private string GetActiveApplicationName() { IntPtr hWnd = GetForegroundWindow(); int processid; GetWindowThreadProcessId(hWnd, out processid); return Process.GetProcessById(processid).ProcessName; } private bool findImage(Bitmap screenBitmap, Bitmap targetBitmap, Rectangle searchRect, double th, bool update) { Bitmap croppedScreenBitmap = screenBitmap.Clone(searchRect, screenBitmap.PixelFormat); IplImage screenImage = BitmapConverter.ToIplImage(croppedScreenBitmap); IplImage targetImage = BitmapConverter.ToIplImage(targetBitmap); CvSize resSize = new CvSize(screenImage.Width - targetImage.Width + 1, screenImage.Height - targetImage.Height + 1); IplImage resImg = Cv.CreateImage(resSize, BitDepth.F32, 1); Cv.MatchTemplate(screenImage, targetImage, resImg, MatchTemplateMethod.SqDiffNormed); double minVal = 0.0; double maxVal = 0.0; CvPoint minLoc; CvPoint maxLoc; Cv.MinMaxLoc(resImg, out minVal, out maxVal, out minLoc, out maxLoc); string val = minVal.ToString("0.00000"); score = val; lock(thisLock) { if (update) { lastBitmap = croppedScreenBitmap; } if ((minVal < th)) { if (update) { Graphics g = Graphics.FromImage(croppedScreenBitmap); g.DrawRectangle(new Pen(Color.Red, 2), new Rectangle(minLoc.X, minLoc.Y, targetImage.Width, targetImage.Height)); } return true; } return false; } } private void button1_Click(object sender, EventArgs e) { Console.WriteLine("INFO: STOP"); stop(); } private void button2_Click(object sender, EventArgs e) { Console.WriteLine("INFO: MACRO1"); reset(macro1); } private void button3_Click(object sender, EventArgs e) { Console.WriteLine("INFO: MACRO2"); reset(macro2); } } }
mit
Sevenflanks/linebot-operator-next
src/test/java/next/operator/linebot/talker/UrlTalkerTest.java
444
package next.operator.linebot.talker; import next.operator.GenericTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; public class UrlTalkerTest extends GenericTest { @Autowired UrlTalker urlTalker; @Test public void talk() throws Exception { final String talk = urlTalker.talk("http://img.2cat.org/~tedc21thc/live/src/1500035493383.jpg"); System.out.println(talk); } }
mit
test101110/WcfExperiments
CalculatorService/Properties/AssemblyInfo.cs
2026
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Управление общими сведениями о сборке осуществляется с помощью // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("CalculatorService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("CalculatorService")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми // для COM-компонентов. Если требуется обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("d57402e7-6da6-4617-b84a-ff12b9f7bfa5")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер построения // Редакция // // Можно задать все значения или принять номер построения и номер редакции по умолчанию, // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
diego-nz/TiendaRopa
modelo/conexion.php
156
<?php $mysqli=new mysqli("localhost","root","","web"); if(mysqli_connect_errno()){ echo 'Conexión fallida ',mysqli_connect_error(); exit(); } ?>
mit
elvisun/VR-Motion-Sickness-Reducer
AlignView.cs
329
using UnityEngine; using System.Collections; public class AlignView : MonoBehaviour { // Use this for initialization void Start () { //Debug.LogWarning ("align view..."); //this.transform.rotation = this.transform.parent.gameObject.transform.rotation; } // Update is called once per frame void Update () { } }
mit
markledwich2/mutuosite
js/main.js
219
(function () { $("a[href*=\\#]").on("click", function (event) { if(!this.hash) return; event.preventDefault(); $("html, body").animate({ scrollTop: $(this.hash).offset().top }, 500); }); })();
mit